Skip to content

Commit

Permalink
feat(fragment): set by component name (#477)
Browse files Browse the repository at this point in the history
  • Loading branch information
redgeoff authored Sep 22, 2021
1 parent 48ab301 commit 273e3ec
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/fragment.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import UIComponent from './ui-component';
import Mapa from './mapa';

export default class Fragment extends UIComponent {
className = 'Fragment';

setNamedItems(items) {
this._items.clear();
items.forEach((item, index) => {
item.set({ parent: this });
const key = item.get('name') ? item.get('name') : index;
this._items.set(key, item);
});
}

create(props) {
// Use a Mapa so that we can reference the items by name, e.g. `items.myComponentName`
this._items = new Mapa();

super.create(props);

this.set({
Expand All @@ -20,10 +33,12 @@ export default class Fragment extends UIComponent {
}

set(props) {
if (props.items !== undefined) {
props.items.forEach((item) => item.set({ parent: this }));
const { items } = props;

if (items !== undefined) {
this.setNamedItems(items);
}

super.set(props);
super.set({ ...props, items: undefined });
}
}
20 changes: 20 additions & 0 deletions src/fragment.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Fragment from './fragment';
import GridItem from './grid-item';
import TextField from './fields/text-field';

it('should set parent', () => {
const item = new GridItem();
Expand All @@ -8,3 +9,22 @@ it('should set parent', () => {
});
expect(item.get('parent')).toEqual(fragment);
});

it('should set with item index', () => {
const fragment = new Fragment({
items: [new TextField({ value: 'Bon' }), new TextField({ value: 'Jovi' })],
});
expect(fragment.get('items.0.value')).toEqual('Bon');
expect(fragment.get('items.1.value')).toEqual('Jovi');
});

it('should set with item name', () => {
const fragment = new Fragment({
items: [
new TextField({ name: 'first', value: 'Bon' }),
new TextField({ name: 'last', value: 'Jovi' }),
],
});
expect(fragment.get('items.first.value')).toEqual('Bon');
expect(fragment.get('items.last.value')).toEqual('Jovi');
});

0 comments on commit 273e3ec

Please sign in to comment.