diff --git a/core/src/components/button/button.tsx b/core/src/components/button/button.tsx index f6d7de5aa00..dd64848055e 100644 --- a/core/src/components/button/button.tsx +++ b/core/src/components/button/button.tsx @@ -206,11 +206,9 @@ export class Button implements ComponentInterface, AnchorInterface, ButtonInterf * The ARIA state has to stay live, since `ion-input-password-toggle` rewrites * `aria-label` and `aria-pressed` on its `ion-button` on every toggle. We keep * `aria-disabled` out of the watch because the `` below renders it from the - * `disabled` prop and those writes would clobber a developer's value, and `role` out - * because a post-load write stays on the host too, which would put the same role on - * two elements in the accessibility tree. + * `disabled` prop and those writes would clobber a developer's value. */ - this.ariaController = createAriaAttributeController(this.el, () => forceUpdate(this), ['aria-disabled', 'role']); + this.ariaController = createAriaAttributeController(this.el, () => forceUpdate(this), ['aria-disabled']); this.tabindexController = createTabindexController(this.el, () => forceUpdate(this)); } diff --git a/core/src/components/button/test/a11y/button.e2e.ts b/core/src/components/button/test/a11y/button.e2e.ts index 6ebc2372d8f..55ffb37e291 100644 --- a/core/src/components/button/test/a11y/button.e2e.ts +++ b/core/src/components/button/test/a11y/button.e2e.ts @@ -216,23 +216,18 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => { await expect(nativeButton).toHaveAttribute('aria-disabled', 'true'); }); - test('should not sync role from the host', async ({ page }) => { + test('should sync role from the host', async ({ page }) => { await page.setContent(`Button`, config); const host = page.locator('ion-button'); const nativeButton = host.locator('button'); - // The initial copy moves role onto the native button, as it always has. await expect(nativeButton).toHaveAttribute('role', 'switch'); - // A later write is only read, so it stays on the host. Copying it as well would put - // the same role on both elements, and two of that role in the accessibility tree. - await host.evaluate((el) => { - el.setAttribute('role', 'checkbox'); - el.setAttribute('aria-label', 'barrier'); - }); - await expect(nativeButton).toHaveAttribute('aria-label', 'barrier'); - await expect(nativeButton).toHaveAttribute('role', 'switch'); + await host.evaluate((el) => el.setAttribute('role', 'checkbox')); + + await expect(nativeButton).toHaveAttribute('role', 'checkbox'); + await expect(host).toHaveAttribute('role', ''); }); test('should keep syncing after the button is detached and reattached', async ({ page }) => { @@ -275,6 +270,11 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => { }); test('should sync updates, empty values and removals after the initial copy', async ({ page }) => { + test.info().annotations.push({ + type: 'issue', + description: 'https://github.com/ionic-team/ionic-framework/issues/31659', + }); + await page.setContent(`Button`, config); const host = page.locator('ion-button'); @@ -284,21 +284,69 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => { await expect(host).not.toHaveAttribute('aria-description'); await expect(nativeButton).toHaveAttribute('aria-description', 'initial'); - // Post-load writes stay on the host and are copied to the native button. + // A later write is copied to the native button and left on the host as an empty string. await host.evaluate((el) => el.setAttribute('aria-description', 'second')); - await expect(host).toHaveAttribute('aria-description', 'second'); await expect(nativeButton).toHaveAttribute('aria-description', 'second'); + await expect(host).toHaveAttribute('aria-description', ''); // An empty string is a valid ARIA attribute value. await host.evaluate((el) => el.setAttribute('aria-description', '')); await expect(nativeButton).toHaveAttribute('aria-description', ''); // A removal of a post-load write does reach the native button. + await host.evaluate((el) => el.setAttribute('aria-description', 'third')); + await expect(nativeButton).toHaveAttribute('aria-description', 'third'); await host.evaluate((el) => el.removeAttribute('aria-description')); await expect(host).not.toHaveAttribute('aria-description'); await expect(nativeButton).not.toHaveAttribute('aria-description'); }); + test('should not leave an aria-label on the host when the same value is written again', async ({ page }) => { + test.info().annotations.push({ + type: 'issue', + description: 'https://github.com/ionic-team/ionic-framework/issues/31659', + }); + + await page.setContent(`Button`, config); + + const host = page.locator('ion-button'); + const nativeButton = host.locator('button'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'Scan')); + + await expect(host).toHaveAttribute('aria-label', ''); + await expect(nativeButton).toHaveAttribute('aria-label', 'Scan'); + }); + + test('should leave a state written after load on the host so it can be read back', async ({ page }) => { + await page.setContent(`Button`, config); + + const host = page.locator('ion-button'); + const nativeButton = host.locator('button'); + const toggle = () => + host.evaluate((el) => + el.setAttribute('aria-pressed', el.getAttribute('aria-pressed') === 'true' ? 'false' : 'true') + ); + + await toggle(); + await expect(nativeButton).toHaveAttribute('aria-pressed', 'true'); + + await toggle(); + await expect(nativeButton).toHaveAttribute('aria-pressed', 'false'); + await expect(host).toHaveAttribute('aria-pressed', 'false'); + }); + + test('should leave an aria-labelledby written after load on the host', async ({ page }) => { + await page.setContent(`ScanButton`, config); + + const host = page.locator('ion-button'); + + await host.evaluate((el) => el.setAttribute('aria-labelledby', 'label')); + + await expect(host.locator('button')).toHaveAttribute('aria-labelledby', 'label'); + await expect(host).toHaveAttribute('aria-labelledby', 'label'); + }); + test('should keep a value from the initial markup when the host attribute is removed', async ({ page }) => { await page.setContent(`Button`, config); diff --git a/core/src/components/card/card.tsx b/core/src/components/card/card.tsx index b0f3d64dd85..002acd21471 100644 --- a/core/src/components/card/card.tsx +++ b/core/src/components/card/card.tsx @@ -90,11 +90,17 @@ export class Card implements ComponentInterface, AnchorInterface, ButtonInterfac componentWillLoad() { /** - * Only the initial copy takes the attribute off the host, so an `aria-label` written - * after load stays on the host too. That's harmless here, because unlike `ion-item` - * the card host renders no role of its own, so nothing reads the leftover copy. + * A non-clickable card renders no native element to apply the copy to, so an + * `aria-label` written after load has to stay on the host. */ - this.ariaController = createAttributeController(this.el, ['aria-label'], () => forceUpdate(this)); + this.ariaController = createAttributeController( + this.el, + ['aria-label'], + () => forceUpdate(this), + [], + undefined, + () => !this.isClickable() + ); // A card that isn't clickable has no native button or link, so `tabindex` stays on the host. this.tabindexController = createTabindexController( @@ -105,12 +111,13 @@ export class Card implements ComponentInterface, AnchorInterface, ButtonInterfac } /** - * Changing `href` or `button` adds or removes the native element, so `tabindex` has to - * move with it. + * Changing `href` or `button` adds or removes the native element, so `tabindex` and a + * label written after load have to move with it. */ @Watch('href') @Watch('button') clickableChanged() { + this.ariaController?.refresh(); this.tabindexController?.refresh(); } diff --git a/core/src/components/card/test/a11y/card.e2e.ts b/core/src/components/card/test/a11y/card.e2e.ts index 7adb42ed5e7..4c2bdd6ab0b 100644 --- a/core/src/components/card/test/a11y/card.e2e.ts +++ b/core/src/components/card/test/a11y/card.e2e.ts @@ -105,21 +105,34 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => { await expect(host).not.toHaveAttribute('aria-label'); await expect(nativeCard).toHaveAttribute('aria-label', 'initial'); - // Post-load writes stay on the host and are copied to the native element. + // A later write is copied to the native element and left on the host as an empty string. await host.evaluate((el) => el.setAttribute('aria-label', 'second')); - await expect(host).toHaveAttribute('aria-label', 'second'); await expect(nativeCard).toHaveAttribute('aria-label', 'second'); + await expect(host).toHaveAttribute('aria-label', ''); // An empty string is a valid ARIA attribute value. await host.evaluate((el) => el.setAttribute('aria-label', '')); await expect(nativeCard).toHaveAttribute('aria-label', ''); // A removal of a post-load write does reach the native element. + await host.evaluate((el) => el.setAttribute('aria-label', 'third')); + await expect(nativeCard).toHaveAttribute('aria-label', 'third'); await host.evaluate((el) => el.removeAttribute('aria-label')); await expect(host).not.toHaveAttribute('aria-label'); await expect(nativeCard).not.toHaveAttribute('aria-label'); }); + test('should keep an aria-label written after load on the host of a non-clickable card', async ({ page }) => { + await page.setContent(`Card`, config); + + const host = page.locator('ion-card'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'updated')); + await page.waitForChanges(); + + await expect(host).toHaveAttribute('aria-label', 'updated'); + }); + test('should apply aria-label to the native element when the card becomes clickable', async ({ page }) => { await page.setContent(`Card`, config); @@ -136,6 +149,38 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => { await expect(host.locator('[part="native"]')).toHaveAttribute('aria-label', 'label'); }); + test('should put an aria-label written after load back on the host when the card stops being clickable', async ({ + page, + }) => { + await page.setContent(`Card`, config); + + const host = page.locator('ion-card'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'updated')); + await expect(host).toHaveAttribute('aria-label', ''); + + await host.evaluate((el: HTMLIonCardElement) => (el.button = false)); + await page.waitForChanges(); + + await expect(host).toHaveAttribute('aria-label', 'updated'); + }); + + test('should put an aria-label written after load back on the host when the card loses its href', async ({ + page, + }) => { + await page.setContent(`Card`, config); + + const host = page.locator('ion-card'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'updated')); + await expect(host).toHaveAttribute('aria-label', ''); + + await host.evaluate((el: HTMLIonCardElement) => (el.href = undefined)); + await page.waitForChanges(); + + await expect(host).toHaveAttribute('aria-label', 'updated'); + }); + test('should not sync ARIA attributes other than aria-label', async ({ page }) => { await page.setContent(`Card`, config); diff --git a/core/src/components/item/item.tsx b/core/src/components/item/item.tsx index 52ed6171345..c3c3a02fb32 100644 --- a/core/src/components/item/item.tsx +++ b/core/src/components/item/item.tsx @@ -130,15 +130,17 @@ export class Item implements ComponentInterface, AnchorInterface, ButtonInterfac buttonChanged() { // Update the focusable option when the button option is changed this.focusable = this.isFocusable(); + this.ariaController?.refresh(); this.tabindexController?.refresh(); } /** - * Adding or removing `href` adds or removes the native element, so `tabindex` has to move - * with it. The same goes for `button` in `buttonChanged`. + * Adding or removing `href` adds or removes the native element, so `tabindex` and a label + * written after load have to move with it. The same goes for `button` in `buttonChanged`. */ @Watch('href') hrefChanged() { + this.ariaController?.refresh(); this.tabindexController?.refresh(); } @@ -200,12 +202,18 @@ export class Item implements ComponentInterface, AnchorInterface, ButtonInterfac componentWillLoad() { /** - * Only the initial copy takes the attribute off the host, so an `aria-label` written - * after load names both the native element and the Host, which is a `listitem` when - * the item is in an `ion-list`. The two names always agree, so a screen reader just - * reads it twice. + * A non-clickable item renders a `div`, which ARIA doesn't allow a name on, so an + * `aria-label` written after load also stays on the Host, which is a `listitem` + * when the item is in an `ion-list`. */ - this.ariaController = createAttributeController(this.el, ['aria-label'], () => forceUpdate(this)); + this.ariaController = createAttributeController( + this.el, + ['aria-label'], + () => forceUpdate(this), + [], + undefined, + () => !this.isClickable() + ); // An item that isn't clickable has no native button or link, so `tabindex` stays on the host. this.tabindexController = createTabindexController( diff --git a/core/src/components/item/test/a11y/item.e2e.ts b/core/src/components/item/test/a11y/item.e2e.ts index 084e4d3b65e..6e011b72da8 100644 --- a/core/src/components/item/test/a11y/item.e2e.ts +++ b/core/src/components/item/test/a11y/item.e2e.ts @@ -226,21 +226,67 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => { await expect(host).not.toHaveAttribute('aria-label'); await expect(nativeItem).toHaveAttribute('aria-label', 'initial'); - // Post-load writes stay on the host and are copied to the native element. + // A later write is copied to the native element and left on the host as an empty string. await host.evaluate((el) => el.setAttribute('aria-label', 'second')); - await expect(host).toHaveAttribute('aria-label', 'second'); await expect(nativeItem).toHaveAttribute('aria-label', 'second'); + await expect(host).toHaveAttribute('aria-label', ''); // An empty string is a valid ARIA attribute value. await host.evaluate((el) => el.setAttribute('aria-label', '')); await expect(nativeItem).toHaveAttribute('aria-label', ''); // A removal of a post-load write does reach the native element. + await host.evaluate((el) => el.setAttribute('aria-label', 'third')); + await expect(nativeItem).toHaveAttribute('aria-label', 'third'); await host.evaluate((el) => el.removeAttribute('aria-label')); await expect(host).not.toHaveAttribute('aria-label'); await expect(nativeItem).not.toHaveAttribute('aria-label'); }); + test('should keep an aria-label written after load on the host of a non-clickable item', async ({ page }) => { + await page.setContent(`Item`, config); + + const host = page.locator('ion-item'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'updated')); + await page.waitForChanges(); + + await expect(host).toHaveAttribute('aria-label', 'updated'); + }); + + test('should move an aria-label written after load off the host when the item becomes clickable', async ({ + page, + }) => { + await page.setContent(`Item`, config); + + const host = page.locator('ion-item'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'updated')); + await page.waitForChanges(); + await expect(host).toHaveAttribute('aria-label', 'updated'); + + await host.evaluate((el: HTMLIonItemElement) => (el.button = true)); + await page.waitForChanges(); + + await expect(host).toHaveAttribute('aria-label', ''); + await expect(host.locator('button')).toHaveAttribute('aria-label', 'updated'); + }); + + test('should move an aria-label written after load off the host when the item gets an href', async ({ page }) => { + await page.setContent(`Item`, config); + + const host = page.locator('ion-item'); + + await host.evaluate((el) => el.setAttribute('aria-label', 'updated')); + await page.waitForChanges(); + + await host.evaluate((el: HTMLIonItemElement) => (el.href = '#')); + await page.waitForChanges(); + + await expect(host).toHaveAttribute('aria-label', ''); + await expect(host.locator('a')).toHaveAttribute('aria-label', 'updated'); + }); + test('should not sync ARIA attributes other than aria-label', async ({ page }) => { await page.setContent(`Item`, config); diff --git a/core/src/utils/attribute-controller.ts b/core/src/utils/attribute-controller.ts index 7ddf1546769..f55341de1b2 100644 --- a/core/src/utils/attribute-controller.ts +++ b/core/src/utils/attribute-controller.ts @@ -2,6 +2,8 @@ import { win } from '@utils/browser'; import type { Attributes } from '@utils/helpers'; import { ariaAttributes, inheritAttributes } from '@utils/helpers'; +const hostNamingAttributes = ['aria-label', 'aria-description', 'role']; + /** * Copies a set of attributes off the host element so they can be applied to an element * inside the shadow root, then keeps that copy in sync as the host attributes change. @@ -11,13 +13,15 @@ import { ariaAttributes, inheritAttributes } from '@utils/helpers'; * Create the controller in `componentWillLoad`. It takes the initial copy and starts * watching right away, so `init()` is only needed to resume after a move. * - * Two things to know before adopting it. Unless `moveFromHost` says otherwise, only the - * initial copy removes the attributes from the host, so a value written after load sits - * on the host as well as on the element it is applied to, which matters if the host has - * a role of its own. And an attribute moved off the host can never be removed, only - * overwritten, since removing it from the host doesn't fire a mutation. - * An empty string works for `aria-label` and friends, but a token-valued attribute - * has to be set to its default instead, so `aria-pressed="false"` rather than empty. + * An `aria-label`, `aria-description` or `role` written after load is copied and then + * replaced on the host with an empty string, so the host isn't a second node in the + * accessibility tree and a later `removeAttribute` still fires a mutation. Anything else + * stays on the host unless `moveFromHost` takes it off, since it leaves the host unnamed + * or, like `aria-labelledby`, only resolves from there. A value the initial copy or + * `moveFromHost` takes off the host can only be overwritten, since removing an attribute + * that isn't there fires no mutation. An empty string works for `aria-label` and friends, + * but a token-valued attribute has to be set to its default instead, so + * `aria-pressed="false"` rather than empty. * * @internal * @param el The host element to copy from and watch. @@ -25,19 +29,22 @@ import { ariaAttributes, inheritAttributes } from '@utils/helpers'; * @param onChange Called after `attributes` changes, so the component can re-render. * @param hostOwnedAttributes Attributes copied at load but not watched. Use it for * attributes the component renders on its own ``, since a later change to one of - * those is the component's own write, and for attributes that would put a second node in - * the accessibility tree if the host kept a copy alongside the one we apply. + * those is the component's own write. * @param moveFromHost Called on load, after every write and on `refresh()` to decide whether * a value moves off the host. A rejected value stays on the host and is left out of * `attributes`. It can read component state, as long as the component calls `refresh()` * when that state changes. + * @param keepOnHost While this returns `true`, a value written after load stays on the + * host. It's checked on every write and on `refresh()`. Use it when the component + * sometimes renders nothing that can carry the copy. */ export const createAttributeController = ( el: HTMLElement, attributes: string[], onChange: () => void, hostOwnedAttributes: string[] = [], - moveFromHost?: (name: string, value: string) => boolean + moveFromHost?: (name: string, value: string) => boolean, + keepOnHost: () => boolean = () => false ): AttributeController => { let inherited: Attributes = inheritAttributes(el, attributes); let observer: MutationObserver | undefined; @@ -48,12 +55,17 @@ export const createAttributeController = ( const watchedAttributes = attributes.filter((attr) => !hostOwnedAttributes.includes(attr)); /** - * The names still on the host, which is everything written after load. The initial - * copy removes what it captures, so a missing attribute only counts as a removal - * when its name is in here. + * The names written to the host after load, including the empty strings we leave in + * place of a copy. The initial copy removes what it captures, so a missing attribute + * only counts as a removal when its name is in here. */ const hostWritten = new Set(); + /** + * The names whose host value is our empty string, not one the developer wrote. + */ + const replaced = new Set(); + const setPresence = (name: string, value: string | null) => { if (value === null) { hostWritten.delete(name); @@ -76,6 +88,33 @@ export const createAttributeController = ( } }; + const replaceOnHost = (written: Attributes) => { + const keep = keepOnHost(); + + for (const [name, value] of Object.entries(written)) { + // An empty value already gives the host no name, so it can stay as written. + if (keep || value === null || value === '' || !hostNamingAttributes.includes(name)) { + replaced.delete(name); + continue; + } + + el.setAttribute(name, ''); + replaced.add(name); + } + + // Drain our own writes so the observer doesn't read them as the developer's. + observer?.takeRecords(); + }; + + const restoreOnHost = () => { + for (const name of replaced) { + el.setAttribute(name, inherited[name]!); + } + + replaced.clear(); + observer?.takeRecords(); + }; + // The initial copy took everything off the host, so put back what has to stay there. for (const [name, value] of Object.entries(inherited)) { if (staysOnHost(name, value)) { @@ -90,6 +129,7 @@ export const createAttributeController = ( * the host has to be re-read on the way back in. */ const readMissedChanges = () => { + const written: Attributes = {}; const changed: Attributes = {}; for (const name of watchedAttributes) { @@ -102,14 +142,20 @@ export const createAttributeController = ( * An attribute that was never written to the host is missing because the initial * copy took it, not because the developer cleared it. */ - if ((value === null && !wasOnHost) || value === inherited[name]) { + if (value === null && !wasOnHost) { continue; } - changed[name] = value; + // Even a rewrite of the same value has to be replaced on the host. + written[name] = value; + + if (value !== inherited[name]) { + changed[name] = value; + } } moveOffHost(changed); + replaceOnHost(written); if (Object.keys(changed).length > 0) { inherited = { ...inherited, ...changed }; @@ -131,11 +177,10 @@ export const createAttributeController = ( } moveOffHost(changed); - // Drop the removals `moveOffHost` just queued, or they'd read back as the developer - // clearing the attribute. - observer?.takeRecords(); - inherited = { ...inherited, ...changed }; + // This also drops the removals `moveOffHost` just queued, or they'd read back as the + // developer clearing the attribute. + replaceOnHost(changed); onChange(); }; @@ -153,26 +198,26 @@ export const createAttributeController = ( }; const destroy = () => { - observer?.disconnect(); - observer = undefined; - }; - - const refresh = () => { - if (moveFromHost === undefined) { + if (observer === undefined) { return; } - // A write made earlier in the same tick hasn't reached `inherited` yet, so take it in - // first, or the loop below would act on the old value and drop the new one. - if (observer !== undefined) { - const pending = observer.takeRecords(); - if (pending.length > 0) { - handleRecords(pending); - } - } else { - readMissedChanges(); + // Apply a write made just before the move, since it hasn't been delivered yet. + const pending = observer.takeRecords(); + + if (pending.length > 0) { + handleRecords(pending); } + observer.disconnect(); + observer = undefined; + + // Put the copied values back while detached, or `init()` would read our empty strings + // as the developer clearing them. + restoreOnHost(); + }; + + const applyMoveFromHost = () => { for (const [name, value] of Object.entries(inherited)) { if (value == null) { continue; @@ -188,9 +233,49 @@ export const createAttributeController = ( hostWritten.delete(name); } } + }; + + const refresh = () => { + /** + * A detached host already has its replaced values back, and `init()` checks + * `keepOnHost` again on reattach, so only `moveFromHost` has work to do here. + */ + if (observer === undefined) { + if (moveFromHost !== undefined) { + readMissedChanges(); + applyMoveFromHost(); + } + return; + } + + // A write made earlier in the same tick hasn't reached `inherited` yet, so take it in + // first, or the writes below would act on the old value and drop the new one. + const pending = observer.takeRecords(); + + if (pending.length > 0) { + handleRecords(pending); + } + + if (moveFromHost !== undefined) { + applyMoveFromHost(); + } + + if (keepOnHost()) { + restoreOnHost(); + } else { + const written: Attributes = {}; + + for (const name of hostWritten) { + if (!replaced.has(name)) { + written[name] = el.getAttribute(name); + } + } + + replaceOnHost(written); + } // Drop our own writes, or they'd read back as the developer's. - observer?.takeRecords(); + observer.takeRecords(); }; /** @@ -277,12 +362,13 @@ export type AttributeController = { */ init: () => void; /** - * Stops watching the host element. Call this from `disconnectedCallback`. + * Stops watching the host element and puts back the values it replaced, so a move keeps + * them. Call this from `disconnectedCallback`. */ destroy: () => void; /** - * Re-runs `moveFromHost` against the current values. Call this when state that - * `moveFromHost` reads changes, such as whether the component renders a native button. + * Re-runs `moveFromHost` and `keepOnHost` against the current values. Call this when + * state either one reads changes, such as whether the component renders a native button. */ refresh: () => void; }; diff --git a/core/src/utils/test/attribute-controller.spec.ts b/core/src/utils/test/attribute-controller.spec.ts index 92fde4d33d2..9074d0d1baf 100644 --- a/core/src/utils/test/attribute-controller.spec.ts +++ b/core/src/utils/test/attribute-controller.spec.ts @@ -125,15 +125,29 @@ describe('createAttributeController()', () => { expect(MockMutationObserver.latest.observedFilter).toEqual(['aria-label']); }); - it('should apply a later attribute change', () => { + it('should apply a later attribute change and leave an empty string on the host', () => { const el = createHost({ 'aria-label': 'Save' }); const onChange = jest.fn(); const controller = createAttributeController(el, ['aria-label'], onChange); el.setAttribute('aria-label', 'Submit'); - MockMutationObserver.latest.emit('aria-label'); + MockMutationObserver.latest.flush(); expect(controller.attributes).toEqual({ 'aria-label': 'Submit' }); + expect(el.getAttribute('aria-label')).toBe(''); + expect(onChange).toHaveBeenCalledTimes(1); + }); + + it('should not read its own empty string on the host as a change', () => { + const el = createHost(); + const onChange = jest.fn(); + const controller = createAttributeController(el, ['aria-label'], onChange); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + MockMutationObserver.latest.flush(); + + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); expect(onChange).toHaveBeenCalledTimes(1); }); @@ -142,9 +156,26 @@ describe('createAttributeController()', () => { const controller = createAttributeController(el, ['aria-label'], jest.fn()); el.setAttribute('aria-label', 'Save'); - MockMutationObserver.latest.emit('aria-label'); + MockMutationObserver.latest.flush(); + el.removeAttribute('aria-label'); + MockMutationObserver.latest.flush(); + + expect(controller.attributes['aria-label']).toBeNull(); + expect(el.hasAttribute('aria-label')).toBe(false); + }); + + it('should leave a later write on the host while keepOnHost returns true', () => { + const el = createHost(); + const controller = createAttributeController(el, ['aria-label'], jest.fn(), [], undefined, () => true); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + expect(el.getAttribute('aria-label')).toBe('Save'); + el.removeAttribute('aria-label'); - MockMutationObserver.latest.emit('aria-label'); + MockMutationObserver.latest.flush(); expect(controller.attributes['aria-label']).toBeNull(); }); @@ -183,19 +214,18 @@ describe('createAttributeController()', () => { it('should resume watching after destroy', () => { const el = createHost(); - const onChange = jest.fn(); - const controller = createAttributeController(el, ['aria-label'], onChange); + const controller = createAttributeController(el, ['aria-label'], jest.fn()); controller.destroy(); controller.init(); el.setAttribute('aria-label', 'Submit'); - MockMutationObserver.latest.emit('aria-label'); + MockMutationObserver.latest.flush(); expect(controller.attributes).toEqual({ 'aria-label': 'Submit' }); }); - it('should pick up a change made while not watching', () => { + it('should pick up a change made while not watching and leave an empty string on the host', () => { const el = createHost(); const onChange = jest.fn(); const controller = createAttributeController(el, ['aria-label'], onChange); @@ -205,6 +235,7 @@ describe('createAttributeController()', () => { controller.init(); expect(controller.attributes).toEqual({ 'aria-label': 'Submit' }); + expect(el.getAttribute('aria-label')).toBe(''); expect(onChange).toHaveBeenCalledTimes(1); }); @@ -213,7 +244,7 @@ describe('createAttributeController()', () => { const controller = createAttributeController(el, ['aria-label'], jest.fn()); el.setAttribute('aria-label', 'Submit'); - MockMutationObserver.latest.emit('aria-label'); + MockMutationObserver.latest.flush(); controller.destroy(); el.removeAttribute('aria-label'); @@ -222,16 +253,19 @@ describe('createAttributeController()', () => { expect(controller.attributes['aria-label']).toBeNull(); }); - it('should track a detached write of an unchanged value, so a later removal is seen', () => { + it('should replace a detached write of an unchanged value without re-rendering', () => { const el = createHost({ 'aria-label': 'Save' }); - const controller = createAttributeController(el, ['aria-label'], jest.fn()); + const onChange = jest.fn(); + const controller = createAttributeController(el, ['aria-label'], onChange); - // Re-setting the value the copy already captured puts the attribute back on the - // host, even though nothing about the rendered value changed. controller.destroy(); el.setAttribute('aria-label', 'Save'); controller.init(); + expect(el.getAttribute('aria-label')).toBe(''); + expect(onChange).not.toHaveBeenCalled(); + + // The empty string left in its place means a later removal is still seen. controller.destroy(); el.removeAttribute('aria-label'); controller.init(); @@ -239,21 +273,149 @@ describe('createAttributeController()', () => { expect(controller.attributes['aria-label']).toBeNull(); }); - it('should not re-render when a detached write matches the current value', () => { + it('should not re-render on resume when nothing changed while not watching', () => { const el = createHost(); const onChange = jest.fn(); const controller = createAttributeController(el, ['aria-label'], onChange); el.setAttribute('aria-label', 'Save'); - MockMutationObserver.latest.emit('aria-label'); + MockMutationObserver.latest.flush(); onChange.mockClear(); controller.destroy(); controller.init(); + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + expect(el.getAttribute('aria-label')).toBe(''); expect(onChange).not.toHaveBeenCalled(); }); + it('should put the copied value back on the host while not watching', () => { + const el = createHost(); + const controller = createAttributeController(el, ['aria-label'], jest.fn()); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + controller.destroy(); + + expect(el.getAttribute('aria-label')).toBe('Save'); + }); + + it('should apply a write that was not delivered before destroy', () => { + const el = createHost(); + const controller = createAttributeController(el, ['aria-label'], jest.fn()); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + + el.setAttribute('aria-label', 'Submit'); + controller.destroy(); + controller.init(); + + expect(controller.attributes).toEqual({ 'aria-label': 'Submit' }); + + el.removeAttribute('aria-label'); + controller.destroy(); + controller.init(); + + expect(controller.attributes['aria-label']).toBeNull(); + expect(el.hasAttribute('aria-label')).toBe(false); + }); + + it('should put a value back on the host when keepOnHost turns true', () => { + const el = createHost(); + const onChange = jest.fn(); + let keep = false; + const controller = createAttributeController(el, ['aria-label'], onChange, [], undefined, () => keep); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + expect(el.getAttribute('aria-label')).toBe(''); + onChange.mockClear(); + + keep = true; + controller.refresh(); + + expect(el.getAttribute('aria-label')).toBe('Save'); + MockMutationObserver.latest.flush(); + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + expect(onChange).not.toHaveBeenCalled(); + }); + + it('should keep the copied value through a move after refresh leaves it replaced', () => { + const el = createHost(); + const controller = createAttributeController(el, ['aria-label'], jest.fn(), [], undefined, () => false); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + controller.refresh(); + + controller.destroy(); + controller.init(); + + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + expect(el.getAttribute('aria-label')).toBe(''); + }); + + it('should leave an attribute that does not name the host on the host as written', () => { + const el = createHost(); + const controller = createAttributeController(el, ['aria-pressed', 'aria-labelledby'], jest.fn()); + + el.setAttribute('aria-pressed', 'true'); + el.setAttribute('aria-labelledby', 'label'); + MockMutationObserver.latest.flush(); + + expect(controller.attributes).toEqual({ 'aria-pressed': 'true', 'aria-labelledby': 'label' }); + expect(el.getAttribute('aria-pressed')).toBe('true'); + expect(el.getAttribute('aria-labelledby')).toBe('label'); + }); + + it('should not touch the host when refresh is called while not watching', () => { + const el = createHost(); + const controller = createAttributeController(el, ['aria-label'], jest.fn(), [], undefined, () => false); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + + controller.destroy(); + controller.refresh(); + controller.init(); + + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + expect(el.getAttribute('aria-label')).toBe(''); + }); + + it('should replace a value kept on the host when keepOnHost turns false', () => { + const el = createHost(); + let keep = true; + const controller = createAttributeController(el, ['aria-label'], jest.fn(), [], undefined, () => keep); + + el.setAttribute('aria-label', 'Save'); + MockMutationObserver.latest.flush(); + expect(el.getAttribute('aria-label')).toBe('Save'); + + keep = false; + controller.refresh(); + + expect(el.getAttribute('aria-label')).toBe(''); + MockMutationObserver.latest.flush(); + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + }); + + it('should apply a write made in the same task as refresh', () => { + const el = createHost(); + let keep = true; + const controller = createAttributeController(el, ['aria-label'], jest.fn(), [], undefined, () => keep); + + el.setAttribute('aria-label', 'Save'); + keep = false; + controller.refresh(); + MockMutationObserver.latest.flush(); + + expect(controller.attributes).toEqual({ 'aria-label': 'Save' }); + expect(el.getAttribute('aria-label')).toBe(''); + }); + it('should apply every attribute in one mutation batch with a single re-render', () => { const el = createHost(); const onChange = jest.fn(); @@ -261,7 +423,7 @@ describe('createAttributeController()', () => { el.setAttribute('aria-label', 'Save'); el.setAttribute('aria-description', 'Saves the draft'); - MockMutationObserver.latest.emit('aria-label', 'aria-description'); + MockMutationObserver.latest.flush(); expect(controller.attributes).toEqual({ 'aria-label': 'Save', 'aria-description': 'Saves the draft' }); expect(onChange).toHaveBeenCalledTimes(1); diff --git a/docs/component-guide.md b/docs/component-guide.md index f562fbd1c14..57f192f643d 100644 --- a/docs/component-guide.md +++ b/docs/component-guide.md @@ -470,10 +470,12 @@ In the following example the `aria-label` is copied from the Host using `createA > [!NOTE] > Use `createAttributeController` to specify which attributes should be copied or `createAriaAttributeController` to copy all of the possible `aria` attributes. -The controller keeps the copy in sync when the host attribute changes after load. Both `inheritAttributes` and `inheritAriaAttributes` do the same copy but only once, so a change made after load never reaches the native element. Those are still the right choice for an attribute that is only read at load. +The controller keeps the copy in sync when the host attribute changes after load. Both `inheritAttributes` and `inheritAriaAttributes` do the same copy but only once, so a change made after load never reaches the native element. Those are still the right choice for an attribute that is only read at load. An `aria-label`, `aria-description` or `role` written after load is replaced on the host with an empty string, so the host doesn't show up as a second node in the accessibility tree and a later removal still reaches the native element. Anything else written after load stays on the host as written. > [!IMPORTANT] -> Pass `hostOwnedAttributes`, the last argument of either function, for any attribute that should be copied at load but not watched afterwards. There are two cases. One is an attribute the component renders on its own ``, like the `aria-disabled` that `ion-button` renders from its `disabled` prop, where watching it would let the component's own renders overwrite a developer's value. The other is an attribute that would put a second node in the accessibility tree if the host kept a copy, like `role`, since only the initial copy removes attributes from the host and anything written after load stays there too. +> Pass `hostOwnedAttributes` for any attribute that should be copied at load but not watched afterwards, like the `aria-disabled` that `ion-button` renders on its `` from its `disabled` prop. Watching it would let the component's own renders overwrite a developer's value. +> +> Pass `keepOnHost` to `createAttributeController` when the component sometimes renders no element that can carry the copy, like `ion-card` without `href` or `button`, or the generic `div` of a non-clickable `ion-item`, which ARIA doesn't allow a name on. While it returns `true`, a value written after load stays on the host as written. Call the controller's `refresh()` when something it reads changes, so the value moves to match. > [!NOTE] > Attributes that reference an element by ID (`aria-labelledby`, `aria-describedby`, `aria-controls`, `aria-owns`, `aria-activedescendant`) cannot resolve a light DOM ID from inside the shadow root, so only copy those when the target is in the same tree. @@ -600,10 +602,12 @@ In the following example the `aria-label` is copied from the Host using `createA > [!NOTE] > Use `createAttributeController` to specify which attributes should be copied or `createAriaAttributeController` to copy all of the possible `aria` attributes. -The controller keeps the copy in sync when the host attribute changes after load. Both `inheritAttributes` and `inheritAriaAttributes` do the same copy but only once, so a change made after load never reaches the native element. Those are still the right choice for an attribute that is only read at load. +The controller keeps the copy in sync when the host attribute changes after load. Both `inheritAttributes` and `inheritAriaAttributes` do the same copy but only once, so a change made after load never reaches the native element. Those are still the right choice for an attribute that is only read at load. An `aria-label`, `aria-description` or `role` written after load is replaced on the host with an empty string, so the host doesn't show up as a second node in the accessibility tree and a later removal still reaches the native element. Anything else written after load stays on the host as written. > [!IMPORTANT] -> Pass `hostOwnedAttributes`, the last argument of either function, for any attribute that should be copied at load but not watched afterwards. There are two cases. One is an attribute the component renders on its own ``, like the `aria-disabled` that `ion-button` renders from its `disabled` prop, where watching it would let the component's own renders overwrite a developer's value. The other is an attribute that would put a second node in the accessibility tree if the host kept a copy, like `role`, since only the initial copy removes attributes from the host and anything written after load stays there too. +> Pass `hostOwnedAttributes` for any attribute that should be copied at load but not watched afterwards, like the `aria-disabled` that `ion-button` renders on its `` from its `disabled` prop. Watching it would let the component's own renders overwrite a developer's value. +> +> Pass `keepOnHost` to `createAttributeController` when the component sometimes renders no element that can carry the copy, like `ion-card` without `href` or `button`, or the generic `div` of a non-clickable `ion-item`, which ARIA doesn't allow a name on. While it returns `true`, a value written after load stays on the host as written. Call the controller's `refresh()` when something it reads changes, so the value moves to match. > [!NOTE] > Attributes that reference an element by ID (`aria-labelledby`, `aria-describedby`, `aria-controls`, `aria-owns`, `aria-activedescendant`) cannot resolve a light DOM ID from inside the shadow root, so only copy those when the target is in the same tree.