Skip to content

Commit

Permalink
fix(clone-attributes): determining attributes from props is unnecessary
Browse files Browse the repository at this point in the history
Resolves #190
  • Loading branch information
borisdiakur committed Dec 14, 2021
1 parent b201d3f commit a0648ef
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ exports[`ld-button brand-color (secondary) 1`] = `
</ld-button>
`;

exports[`ld-button clones attributes to inner button 1`] = `
<ld-button aria-label="yolo" hidden="" size="sm">
<mock:shadow-root>
<button aria-label="yolo" aria-live="polite" class="ld-button ld-button--sm" hidden="" part="button focusable">
<slot></slot>
</button>
</mock:shadow-root>
</ld-button>
`;

exports[`ld-button danger 1`] = `
<ld-button mode="danger">
<mock:shadow-root>
Expand Down
8 changes: 8 additions & 0 deletions src/liquid/components/ld-button/test/ld-button.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -340,4 +340,12 @@ describe('ld-button', () => {
})
expect(page.root).toMatchSnapshot()
})

it('clones attributes to inner button', async () => {
const page = await newSpecPage({
components: [LdButton],
html: `<ld-button size="sm" aria-label="yolo" hidden></ld-button>`,
})
expect(page.root).toMatchSnapshot()
})
})
31 changes: 5 additions & 26 deletions src/liquid/utils/cloneAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,39 +8,18 @@ export function cloneAttributes(attributesToIgnore: string[] = []) {
...attributesToIgnore,
])

// Get attributes from props.
const attributesFromProps = {}
for (const key in this) {
// Component props are getters. Getters don't have a descriptor.
// So we can check for component props as follows:
if (
!Object.getOwnPropertyDescriptor(this, key) &&
this[key] !== undefined &&
this[key] !== null
) {
const attrName = key.replaceAll(/([A-Z])/g, '-$1').toLowerCase()

if (!attributesToIgnoreSet.has(attrName)) {
attributesFromProps[attrName] = this[key]
}
}
}

// Get attributes not in props.
const attributesNotInProps = {}
const attributesToClone = {}
for (const attr of this.el.attributes) {
if (
attr.name in attributesFromProps ||
attributesToIgnoreSet.has(attr.name)
) {
if (attributesToIgnoreSet.has(attr.name)) {
continue
}
attributesNotInProps[attr.name] = attr.value
const valueToClone = attr.value === '' ? true : attr.value
attributesToClone[attr.name] = valueToClone
}

// Update cloned attributes state.
const allAttributes = { ...attributesFromProps, ...attributesNotInProps }
this.clonedAttributes = allAttributes
this.clonedAttributes = attributesToClone

// Set up attributes observer.
const callback = (mutationsList) => {
Expand Down

0 comments on commit a0648ef

Please sign in to comment.