Skip to content

Commit

Permalink
Default values for child fields (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
smikhalevski authored Apr 23, 2024
1 parent 96ba047 commit df9d7ed
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
9 changes: 7 additions & 2 deletions packages/roqueform/src/main/createField.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ function getOrCreateField(
setValue(field, field.value, false);
},

at: key => getOrCreateField(field.valueAccessor, field, key, null, plugin),
at: (key, defaultValue) => getOrCreateField(field.valueAccessor, field, key, defaultValue, plugin),

on: (type, subscriber) => {
const subscribers = (field.subscribers[type] ||= []);
Expand All @@ -111,7 +111,12 @@ function getOrCreateField(
field.rootField = field;

if (parentField !== null) {
field.value = parentField.valueAccessor.get(parentField.value, key);
const derivedValue = parentField.valueAccessor.get(parentField.value, key);

if (derivedValue !== undefined) {
field.value = derivedValue;
}

field.initialValue = parentField.valueAccessor.get(parentField.initialValue, key);
field.rootField = parentField.rootField;
(parentField.children ||= []).push(field);
Expand Down
3 changes: 2 additions & 1 deletion packages/roqueform/src/main/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,11 @@ export interface BareField<Value = any, Plugin = any> {
* {@link value the current value}.
*
* @param key The key in the value of this field.
* @param defaultValue The default value used if the value at given key is `undefined`.
* @returns The child field instance.
* @template Key The key in the value of this field.
*/
at<Key extends KeyOf<Value>>(key: Key): Field<ValueAt<Value, Key>, Plugin>;
at<Key extends KeyOf<Value>>(key: Key, defaultValue?: ValueAt<Value, Key>): Field<ValueAt<Value, Key>, Plugin>;

/**
* Subscribes to all events.
Expand Down
14 changes: 14 additions & 0 deletions packages/roqueform/src/test/createField.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ describe('createField', () => {
expect(field.at('aaa')).toBe(field.at('aaa'));
});

test('returns a field at key with the default value', () => {
const field = createField<{ aaa?: number }>({}).at('aaa', 111);

expect(field.value).toBe(111);
expect(field.initialValue).toBe(undefined);
});

test('default value does not override a defined value', () => {
const field = createField({ aaa: 222 }).at('aaa', 111);

expect(field.value).toBe(222);
expect(field.initialValue).toBe(222);
});

test('sets a value to a root field', () => {
const field = createField(111);

Expand Down

0 comments on commit df9d7ed

Please sign in to comment.