Skip to content

Commit

Permalink
fix(focus): control not working when for reflects as empty
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 527926302
  • Loading branch information
asyncLiz authored and Copybara-Service committed Apr 28, 2023
1 parent 016b851 commit f83db36
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions focus/lib/focus-ring.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export class FocusRing extends LitElement {
* </button>
* ```
*/
@property({attribute: 'for', reflect: true}) htmlFor = '';
@property({attribute: 'for', reflect: true}) htmlFor: string|null = null;

/**
* The element that controls the visibility of the focus ring. It is one of:
Expand Down Expand Up @@ -74,45 +74,37 @@ export class FocusRing extends LitElement {
return;
}

this.detach();
for (const event of ['focusin', 'focusout', 'pointerdown']) {
control.addEventListener(event, this);
}

this.currentControl = control;
this.setCurrentControl(control);
// When imperatively attaching the focus ring, remove the `for` attribute so
// that the attached control is used instead of a referenced one.
this.removeAttribute('for');
}

/**
* Detaches the focus ring from its current interactive element.
*/
detach() {
for (const event of ['focusin', 'focusout', 'pointerdown']) {
this.currentControl?.removeEventListener(event, this);
}

this.currentControl = null;
this.setCurrentControl(null);
// When imperatively detaching, add an empty `for=""` attribute. This will
// ensure the control is `null` rather than the `parentElement`.
this.setAttribute('for', '');
}

override connectedCallback() {
super.connectedCallback();
const {control} = this;
if (control) {
this.attach(control);
}
this.setCurrentControl(this.control);
}

override disconnectedCallback() {
super.disconnectedCallback();
this.detach();
this.setCurrentControl(null);
}

protected override updated(changedProperties: PropertyValues<FocusRing>) {
if (changedProperties.has('htmlFor')) {
const {control} = this;
if (control) {
this.attach(control);
this.setCurrentControl(control);
}
}
}
Expand Down Expand Up @@ -141,6 +133,15 @@ export class FocusRing extends LitElement {

event[HANDLED_BY_FOCUS_RING] = true;
}

private setCurrentControl(control: HTMLElement|null) {
for (const event of ['focusin', 'focusout', 'pointerdown']) {
this.currentControl?.removeEventListener(event, this);
control?.addEventListener(event, this);
}

this.currentControl = control;
}
}

const HANDLED_BY_FOCUS_RING = Symbol('handledByFocusRing');
Expand Down

0 comments on commit f83db36

Please sign in to comment.