Skip to content

Commit

Permalink
Merge pull request #132 from gutentag2012/fix/dirty-dates
Browse files Browse the repository at this point in the history
Fix/dirty dates
  • Loading branch information
gutentag2012 authored Nov 10, 2024
2 parents 910fb6a + ca048fc commit 392a53a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
25 changes: 25 additions & 0 deletions packages/form-core/src/FieldGroupLogic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,31 @@ describe('FieldGroupLogic', () => {
field.handleChange('default')
expect(group.isDirty.value).toBe(false)
})
it('should be dirty if any of the fields are different from their default value in the form', () => {
const startDate = new Date(2024, 1, 1)
const otherDate = new Date(2024, 2, 1)
const form = new FormLogic({
defaultValues: {
name: 'default',
date: startDate,
},
})
form.mount()
const field = new FieldLogic(form, 'name')
const dateField = new FieldLogic(form, 'date')
field.mount()
dateField.mount()
const group = form.getOrCreateFieldGroup(['name', 'date'])
group.mount()

expect(form.isDirty.value).toBe(false)
expect(group.isDirty.value).toBe(false)
expect(field.isDirty.value).toBe(false)
dateField.data.value = otherDate
expect(form.isDirty.value).toBe(true)
expect(group.isDirty.value).toBe(true)
expect(dateField.isDirty.value).toBe(true)
})
it('should be dirty if elements have been added to an array field', () => {
const form = new FormLogic({
defaultValues: {
Expand Down
12 changes: 12 additions & 0 deletions packages/form-core/src/utils/access.utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ describe('access.utils', () => {
it('should return value for array path', () => {
expect(getValueAtPath({ a: [1, 2] }, 'a.0')).toBe(1)
})
it('should return dates', () => {
const date = new Date()
expect(getValueAtPath({ date }, 'date')).toBe(date)
})
})
describe('setValueAtPath', () => {
it('should do nothing for an undefined object', () => {
Expand Down Expand Up @@ -146,5 +150,13 @@ describe('access.utils', () => {
expect(copy.a).not.toBe(obj.a)
expect(copy.a[0]).not.toBe(obj.a[0])
})
it('should copy dates', () => {
const date = new Date()
const obj = { date }
const copy = deepCopy(obj)
expect(copy).toStrictEqual(obj)
expect(copy).not.toBe(obj)
expect(copy.date).toStrictEqual(obj.date)
})
})
})
3 changes: 3 additions & 0 deletions packages/form-core/src/utils/access.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ export function deepCopy<T>(value: T): T {
if (Array.isArray(value)) {
return value.map(deepCopy) as T
}
if (value instanceof Date) {
return new Date(value.getTime()) as T
}
if (typeof value === 'object' && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([key, value]) => [key, deepCopy(value)]),
Expand Down

0 comments on commit 392a53a

Please sign in to comment.