diff --git a/.changeset/soft-walls-swim.md b/.changeset/soft-walls-swim.md new file mode 100644 index 000000000..f73612a5a --- /dev/null +++ b/.changeset/soft-walls-swim.md @@ -0,0 +1,5 @@ +--- +'@lion/form-core': patch +--- + +Adding form elements at the top of a form now adds them to the beginning of the `.formElements` to keep it in sync with the dom order. diff --git a/packages/form-core/src/registration/FormRegistrarMixin.js b/packages/form-core/src/registration/FormRegistrarMixin.js index 74d7717fb..53ecc78d6 100644 --- a/packages/form-core/src/registration/FormRegistrarMixin.js +++ b/packages/form-core/src/registration/FormRegistrarMixin.js @@ -80,7 +80,7 @@ const FormRegistrarMixinImplementation = superclass => child.__parentFormGroup = this; // 1. Add children as array element - if (indexToInsertAt > 0) { + if (indexToInsertAt >= 0) { this.formElements.splice(indexToInsertAt, 0, child); } else { this.formElements.push(child); diff --git a/packages/form-core/test-suites/FormRegistrationMixins.suite.js b/packages/form-core/test-suites/FormRegistrationMixins.suite.js index 735971c2b..8cabf1966 100644 --- a/packages/form-core/test-suites/FormRegistrationMixins.suite.js +++ b/packages/form-core/test-suites/FormRegistrationMixins.suite.js @@ -133,25 +133,37 @@ export const runRegistrationSuite = customConfig => { it('adds elements to formElements in the right order (DOM)', async () => { const el = /** @type {RegistrarClass} */ (await fixture(html` <${parentTag}> - <${childTag}> - <${childTag}> - <${childTag}> + <${childTag} pos="0"> + <${childTag} pos="1"> + <${childTag} pos="2"> `)); + /** INSERT field before the pos=1 */ /** * @typedef {Object.} prop */ const newField = /** @type {RegisteringClass & prop} */ (await fixture(html` <${childTag}> `)); - newField.myProp = 'test'; - + newField.setAttribute('pos', 'inserted-before-1'); el.insertBefore(newField, el.children[1]); expect(el.formElements.length).to.equal(4); const secondChild = /** @type {RegisteringClass & prop} */ (el.children[1]); - expect(secondChild.myProp).to.equal('test'); - expect(el.formElements[1].myProp).to.equal('test'); + expect(secondChild.getAttribute('pos')).to.equal('inserted-before-1'); + expect(el.formElements[1].getAttribute('pos')).to.equal('inserted-before-1'); + + /** INSERT field before the pos=0 (e.g. at the top) */ + const topField = /** @type {RegisteringClass & prop} */ (await fixture(html` + <${childTag}> + `)); + topField.setAttribute('pos', 'inserted-before-0'); + el.insertBefore(topField, el.children[0]); + + // expect(el.formElements.length).to.equal(5); + const firstChild = /** @type {RegisteringClass & prop} */ (el.children[0]); + expect(firstChild.getAttribute('pos')).to.equal('inserted-before-0'); + expect(el.formElements[0].getAttribute('pos')).to.equal('inserted-before-0'); }); describe('FormRegistrarPortalMixin', () => {