@internetarchive/modal-manager 0.9.1-alpha.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
1
  import { LitElement, CSSResult, TemplateResult, PropertyValues } from 'lit';
2
- import Modal from './shoelace/modal';
3
2
  import './modal-template';
4
3
  import { ModalConfig } from './modal-config';
5
4
  import { ModalManagerInterface } from './modal-manager-interface';
@@ -23,7 +22,7 @@ export declare class ModalManager extends LitElement implements ModalManagerInte
23
22
  */
24
23
  customModalContent?: TemplateResult;
25
24
  /**
26
- * This hostBridge handles environmental-specific interactions such as adding classes
25
+ * Thie hostBridge handles environmental-specific interactions such as adding classes
27
26
  * to the body tag or event listeners needed to support the modal manager in the host environment.
28
27
  *
29
28
  * There is a default `ModalManagerHostBridge`, but consumers can override it with a custom
@@ -41,9 +40,6 @@ export declare class ModalManager extends LitElement implements ModalManagerInte
41
40
  * @memberof ModalManager
42
41
  */
43
42
  private modalTemplate;
44
- modal: Modal;
45
- firstUpdated(): Promise<void>;
46
- disconnectedCallback(): void;
47
43
  /** @inheritdoc */
48
44
  render(): TemplateResult;
49
45
  /** @inheritdoc */
@@ -1,7 +1,6 @@
1
1
  import { __awaiter, __decorate } from "tslib";
2
2
  import { LitElement, html, css, } from 'lit';
3
3
  import { property, customElement, query } from 'lit/decorators.js';
4
- import Modal from './shoelace/modal';
5
4
  import './modal-template';
6
5
  import { ModalConfig } from './modal-config';
7
6
  import { ModalManagerHostBridge } from './modal-manager-host-bridge';
@@ -19,7 +18,7 @@ let ModalManager = class ModalManager extends LitElement {
19
18
  */
20
19
  this.mode = ModalManagerMode.Closed;
21
20
  /**
22
- * This hostBridge handles environmental-specific interactions such as adding classes
21
+ * Thie hostBridge handles environmental-specific interactions such as adding classes
23
22
  * to the body tag or event listeners needed to support the modal manager in the host environment.
24
23
  *
25
24
  * There is a default `ModalManagerHostBridge`, but consumers can override it with a custom
@@ -29,8 +28,6 @@ let ModalManager = class ModalManager extends LitElement {
29
28
  * @memberof ModalManager
30
29
  */
31
30
  this.hostBridge = new ModalManagerHostBridge(this);
32
- // Imported tab handling from shoelace
33
- this.modal = new Modal(this);
34
31
  /**
35
32
  * Whether the modal should close if the user taps on the backdrop
36
33
  *
@@ -39,17 +36,6 @@ let ModalManager = class ModalManager extends LitElement {
39
36
  */
40
37
  this.closeOnBackdropClick = true;
41
38
  }
42
- firstUpdated() {
43
- return __awaiter(this, void 0, void 0, function* () {
44
- // Give the browser a chance to paint
45
- // eslint-disable-next-line no-promise-executor-return
46
- yield new Promise(r => setTimeout(r, 0));
47
- });
48
- }
49
- disconnectedCallback() {
50
- super.disconnectedCallback();
51
- this.modal.deactivate();
52
- }
53
39
  /** @inheritdoc */
54
40
  render() {
55
41
  return html `
@@ -57,7 +43,7 @@ let ModalManager = class ModalManager extends LitElement {
57
43
  <div class="backdrop" @click=${this.backdropClicked}></div>
58
44
  <modal-template
59
45
  @closeButtonPressed=${this.closeButtonPressed}
60
- tabindex="-1"
46
+ tabindex="0"
61
47
  >
62
48
  ${this.customModalContent}
63
49
  </modal-template>
@@ -73,7 +59,6 @@ let ModalManager = class ModalManager extends LitElement {
73
59
  this.mode = ModalManagerMode.Closed;
74
60
  this.customModalContent = undefined;
75
61
  this.modalTemplate.config = new ModalConfig();
76
- this.modal.deactivate();
77
62
  }
78
63
  /**
79
64
  * Call the userClosedModalCallback and reset it if it exists
@@ -99,13 +84,7 @@ let ModalManager = class ModalManager extends LitElement {
99
84
  this.customModalContent = options.customModalContent;
100
85
  this.mode = ModalManagerMode.Open;
101
86
  yield this.modalTemplate.updateComplete;
102
- this.modal.activate();
103
- // document.addEventListener('keydown', this.tabHandler);
104
- // this.firstFocusableElement.focus();
105
- // console.log('firstFocusableElement', this.firstFocusableElement);
106
- // console.log('lastFocusableElement', this.lastFocusableElement);
107
- // console.log('focusableContent', this.focusableContent);
108
- // this.modalTemplate.focus();
87
+ this.modalTemplate.focus();
109
88
  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M,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;0CAChB;AAQE;IAA3B,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;wDAAqC;AAahE;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;gDAGzB;AASuB;IAAxB,KAAK,CAAC,gBAAgB,CAAC;mDAAuC;AA1CpD,YAAY;IADxB,aAAa,CAAC,eAAe,CAAC;GAClB,YAAY,CA2OxB;SA3OY,YAAY","sourcesContent":["import {\n LitElement,\n html,\n css,\n CSSResult,\n TemplateResult,\n PropertyValues,\n} from 'lit';\nimport { property, customElement, query } from 'lit/decorators.js';\n\nimport Modal from './shoelace/modal';\n\nimport './modal-template';\nimport { ModalTemplate } from './modal-template';\nimport { ModalConfig } from './modal-config';\nimport { ModalManagerHostBridge } from './modal-manager-host-bridge';\nimport { ModalManagerInterface } from './modal-manager-interface';\nimport { ModalManagerHostBridgeInterface } from './modal-manager-host-bridge-interface';\nimport { ModalManagerMode } from './modal-manager-mode';\n\n@customElement('modal-manager')\nexport class ModalManager extends LitElement implements ModalManagerInterface {\n /**\n * The current mode of the ModalManager\n *\n * Current options are `modal` or `closed`\n *\n * @type {ModalManagerMode}\n * @memberof ModalManager\n */\n @property({ type: String, reflect: true }) mode: ModalManagerMode =\n ModalManagerMode.Closed;\n\n /**\n * Custom content to display in the modal's content slot\n *\n * @type {(TemplateResult | undefined)}\n * @memberof ModalManager\n */\n @property({ type: Object }) customModalContent?: TemplateResult;\n\n /**\n * This hostBridge handles environmental-specific interactions such as adding classes\n * to the body tag or event listeners needed to support the modal manager in the host environment.\n *\n * There is a default `ModalManagerHostBridge`, but consumers can override it with a custom\n * `ModalManagerHostBridgeInterface`\n *\n * @type {ModalManagerHostBridgeInterface}\n * @memberof ModalManager\n */\n @property({ type: Object })\n hostBridge: ModalManagerHostBridgeInterface = new ModalManagerHostBridge(\n this\n );\n\n /**\n * Reference to the ModalTemplate DOM element\n *\n * @private\n * @type {ModalTemplate}\n * @memberof ModalManager\n */\n @query('modal-template') private modalTemplate!: ModalTemplate;\n\n // Imported tab handling from shoelace\n public modal = new Modal(this);\n\n async firstUpdated(): Promise<void> {\n // Give the browser a chance to paint\n // eslint-disable-next-line no-promise-executor-return\n await new Promise(r => setTimeout(r, 0));\n }\n\n disconnectedCallback() {\n super.disconnectedCallback();\n this.modal.deactivate();\n }\n\n /** @inheritdoc */\n render(): TemplateResult {\n return html`\n <div class=\"container\">\n <div class=\"backdrop\" @click=${this.backdropClicked}></div>\n <modal-template\n @closeButtonPressed=${this.closeButtonPressed}\n tabindex=\"-1\"\n >\n ${this.customModalContent}\n </modal-template>\n </div>\n `;\n }\n\n /** @inheritdoc */\n getMode(): ModalManagerMode {\n return this.mode;\n }\n\n /** @inheritdoc */\n closeModal(): void {\n this.mode = ModalManagerMode.Closed;\n this.customModalContent = undefined;\n this.modalTemplate.config = new ModalConfig();\n this.modal.deactivate();\n }\n\n /**\n * Whether the modal should close if the user taps on the backdrop\n *\n * @private\n * @memberof ModalManager\n */\n private closeOnBackdropClick = true;\n\n /**\n * A callback if the user closes the modal\n *\n * @private\n * @memberof ModalManager\n */\n private userClosedModalCallback?: () => void;\n\n /**\n * Call the userClosedModalCallback and reset it if it exists\n *\n * @private\n * @memberof ModalManager\n */\n private callUserClosedModalCallback(): void {\n // we assign the callback to a temp var and undefine it before calling it\n // otherwise, we run into the potential for an infinite loop if the\n // callback triggers another `showModal()`, which would execute `userClosedModalCallback`\n const callback = this.userClosedModalCallback;\n this.userClosedModalCallback = undefined;\n if (callback) callback();\n }\n\n /** @inheritdoc */\n async showModal(options: {\n config: ModalConfig;\n customModalContent?: TemplateResult;\n userClosedModalCallback?: () => void;\n }): Promise<void> {\n this.closeOnBackdropClick = options.config.closeOnBackdropClick;\n this.userClosedModalCallback = options.userClosedModalCallback;\n this.modalTemplate.config = options.config;\n this.customModalContent = options.customModalContent;\n this.mode = ModalManagerMode.Open;\n await this.modalTemplate.updateComplete;\n\n this.modal.activate();\n\n // document.addEventListener('keydown', this.tabHandler);\n\n // this.firstFocusableElement.focus();\n // console.log('firstFocusableElement', this.firstFocusableElement);\n // console.log('lastFocusableElement', this.lastFocusableElement);\n // console.log('focusableContent', this.focusableContent);\n\n // this.modalTemplate.focus();\n }\n\n /** @inheritdoc */\n updated(changed: PropertyValues): void {\n /* istanbul ignore else */\n if (changed.has('mode')) {\n this.handleModeChange();\n }\n }\n\n /**\n * Called when the backdrop is clicked\n *\n * @private\n * @memberof ModalManager\n */\n private backdropClicked(): void {\n if (this.closeOnBackdropClick) {\n this.closeModal();\n this.callUserClosedModalCallback();\n }\n }\n\n /**\n * Handle the mode change\n *\n * @private\n * @memberof ModalManager\n */\n private handleModeChange(): void {\n this.hostBridge.handleModeChange(this.mode);\n this.emitModeChangeEvent();\n }\n\n /**\n * Emit a modeChange event\n *\n * @private\n * @memberof ModalManager\n */\n private emitModeChangeEvent(): void {\n const event = new CustomEvent('modeChanged', {\n detail: { mode: this.mode },\n });\n this.dispatchEvent(event);\n }\n\n /**\n * Called when the modal close button is pressed. Closes the modal.\n *\n * @private\n * @memberof ModalManager\n */\n private closeButtonPressed(): void {\n this.closeModal();\n this.callUserClosedModalCallback();\n }\n\n /** @inheritdoc */\n static get styles(): CSSResult {\n const modalBackdropColor = css`var(--modalBackdropColor, rgba(10, 10, 10, 0.9))`;\n const modalBackdropZindex = css`var(--modalBackdropZindex, 1000)`;\n\n const modalWidth = css`var(--modalWidth, 32rem)`;\n const modalMaxWidth = css`var(--modalMaxWidth, 95%)`;\n const modalZindex = css`var(--modalZindex, 2000)`;\n\n return css`\n .container {\n width: 100%;\n height: 100%;\n }\n\n .backdrop {\n position: fixed;\n top: 0;\n left: 0;\n background-color: ${modalBackdropColor};\n width: 100%;\n height: 100%;\n z-index: ${modalBackdropZindex};\n }\n\n modal-template {\n outline: 0;\n position: fixed;\n top: 0;\n left: 50%;\n transform: translate(-50%, 0);\n z-index: ${modalZindex};\n width: ${modalWidth};\n max-width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AAE;SAC5B,CAAC,CAAC;QACH,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;;;;OAKG;IACK,kBAAkB;QACxB,IAAI,CAAC,UAAU,EAAE,CAAC;QAClB,IAAI,CAAC,2BAA2B,EAAE,CAAC;IACrC,CAAC;IAED,kBAAkB;IAClB,MAAM,KAAK,MAAM;QACf,MAAM,kBAAkB,GAAG,GAAG,CAAA,kDAAkD,CAAC;QACjF,MAAM,mBAAmB,GAAG,GAAG,CAAA,kCAAkC,CAAC;QAElE,MAAM,UAAU,GAAG,GAAG,CAAA,0BAA0B,CAAC;QACjD,MAAM,aAAa,GAAG,GAAG,CAAA,2BAA2B,CAAC;QACrD,MAAM,WAAW,GAAG,GAAG,CAAA,0BAA0B,CAAC;QAElD,OAAO,GAAG,CAAA;;;;;;;;;;4BAUc,kBAAkB;;;mBAG3B,mBAAmB;;;;;;;;;mBASnB,WAAW;iBACb,UAAU;qBACN,aAAa;;KAE7B,CAAC;IACJ,CAAC;CACF,CAAA;AAzM4C;IAA1C,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;0CAChB;AAQE;IAA3B,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;wDAAqC;AAahE;IADC,QAAQ,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;gDAGzB;AASuB;IAAxB,KAAK,CAAC,gBAAgB,CAAC;mDAAuC;AA1CpD,YAAY;IADxB,aAAa,CAAC,eAAe,CAAC;GAClB,YAAY,CAkNxB;SAlNY,YAAY","sourcesContent":["import {\n LitElement,\n html,\n css,\n CSSResult,\n TemplateResult,\n PropertyValues,\n} from 'lit';\nimport { property, customElement, query } from 'lit/decorators.js';\n\nimport './modal-template';\nimport { ModalTemplate } from './modal-template';\nimport { ModalConfig } from './modal-config';\nimport { ModalManagerHostBridge } from './modal-manager-host-bridge';\nimport { ModalManagerInterface } from './modal-manager-interface';\nimport { ModalManagerHostBridgeInterface } from './modal-manager-host-bridge-interface';\nimport { ModalManagerMode } from './modal-manager-mode';\n\n@customElement('modal-manager')\nexport class ModalManager extends LitElement implements ModalManagerInterface {\n /**\n * The current mode of the ModalManager\n *\n * Current options are `modal` or `closed`\n *\n * @type {ModalManagerMode}\n * @memberof ModalManager\n */\n @property({ type: String, reflect: true }) mode: ModalManagerMode =\n ModalManagerMode.Closed;\n\n /**\n * Custom content to display in the modal's content slot\n *\n * @type {(TemplateResult | undefined)}\n * @memberof ModalManager\n */\n @property({ type: Object }) customModalContent?: TemplateResult;\n\n /**\n * Thie hostBridge handles environmental-specific interactions such as adding classes\n * to the body tag or event listeners needed to support the modal manager in the host environment.\n *\n * There is a default `ModalManagerHostBridge`, but consumers can override it with a custom\n * `ModalManagerHostBridgeInterface`\n *\n * @type {ModalManagerHostBridgeInterface}\n * @memberof ModalManager\n */\n @property({ type: Object })\n hostBridge: ModalManagerHostBridgeInterface = new ModalManagerHostBridge(\n this\n );\n\n /**\n * Reference to the ModalTemplate DOM element\n *\n * @private\n * @type {ModalTemplate}\n * @memberof ModalManager\n */\n @query('modal-template') private modalTemplate!: ModalTemplate;\n\n /** @inheritdoc */\n render(): TemplateResult {\n return html`\n <div class=\"container\">\n <div class=\"backdrop\" @click=${this.backdropClicked}></div>\n <modal-template\n @closeButtonPressed=${this.closeButtonPressed}\n tabindex=\"0\"\n >\n ${this.customModalContent}\n </modal-template>\n </div>\n `;\n }\n\n /** @inheritdoc */\n getMode(): ModalManagerMode {\n return this.mode;\n }\n\n /** @inheritdoc */\n closeModal(): void {\n this.mode = ModalManagerMode.Closed;\n this.customModalContent = undefined;\n this.modalTemplate.config = new ModalConfig();\n }\n\n /**\n * Whether the modal should close if the user taps on the backdrop\n *\n * @private\n * @memberof ModalManager\n */\n private closeOnBackdropClick = true;\n\n /**\n * A callback if the user closes the modal\n *\n * @private\n * @memberof ModalManager\n */\n private userClosedModalCallback?: () => void;\n\n /**\n * Call the userClosedModalCallback and reset it if it exists\n *\n * @private\n * @memberof ModalManager\n */\n private callUserClosedModalCallback(): void {\n // we assign the callback to a temp var and undefine it before calling it\n // otherwise, we run into the potential for an infinite loop if the\n // callback triggers another `showModal()`, which would execute `userClosedModalCallback`\n const callback = this.userClosedModalCallback;\n this.userClosedModalCallback = undefined;\n if (callback) callback();\n }\n\n /** @inheritdoc */\n async showModal(options: {\n config: ModalConfig;\n customModalContent?: TemplateResult;\n userClosedModalCallback?: () => void;\n }): Promise<void> {\n this.closeOnBackdropClick = options.config.closeOnBackdropClick;\n this.userClosedModalCallback = options.userClosedModalCallback;\n this.modalTemplate.config = options.config;\n this.customModalContent = options.customModalContent;\n this.mode = ModalManagerMode.Open;\n await this.modalTemplate.updateComplete;\n this.modalTemplate.focus();\n }\n\n /** @inheritdoc */\n updated(changed: PropertyValues): void {\n /* istanbul ignore else */\n if (changed.has('mode')) {\n this.handleModeChange();\n }\n }\n\n /**\n * Called when the backdrop is clicked\n *\n * @private\n * @memberof ModalManager\n */\n private backdropClicked(): void {\n if (this.closeOnBackdropClick) {\n this.closeModal();\n this.callUserClosedModalCallback();\n }\n }\n\n /**\n * Handle the mode change\n *\n * @private\n * @memberof ModalManager\n */\n private handleModeChange(): void {\n this.hostBridge.handleModeChange(this.mode);\n this.emitModeChangeEvent();\n }\n\n /**\n * Emit a modeChange event\n *\n * @private\n * @memberof ModalManager\n */\n private emitModeChangeEvent(): void {\n const event = new CustomEvent('modeChanged', {\n detail: { mode: this.mode },\n });\n this.dispatchEvent(event);\n }\n\n /**\n * Called when the modal close button is pressed. Closes the modal.\n *\n * @private\n * @memberof ModalManager\n */\n private closeButtonPressed(): void {\n this.closeModal();\n this.callUserClosedModalCallback();\n }\n\n /** @inheritdoc */\n static get styles(): CSSResult {\n const modalBackdropColor = css`var(--modalBackdropColor, rgba(10, 10, 10, 0.9))`;\n const modalBackdropZindex = css`var(--modalBackdropZindex, 1000)`;\n\n const modalWidth = css`var(--modalWidth, 32rem)`;\n const modalMaxWidth = css`var(--modalMaxWidth, 95%)`;\n const modalZindex = css`var(--modalZindex, 2000)`;\n\n return css`\n .container {\n width: 100%;\n height: 100%;\n }\n\n .backdrop {\n position: fixed;\n top: 0;\n left: 0;\n background-color: ${modalBackdropColor};\n width: 100%;\n height: 100%;\n z-index: ${modalBackdropZindex};\n }\n\n modal-template {\n outline: 0;\n position: fixed;\n top: 0;\n left: 50%;\n transform: translate(-50%, 0);\n z-index: ${modalZindex};\n width: ${modalWidth};\n max-width: ${modalMaxWidth};\n }\n `;\n }\n}\n"]}
@@ -10,9 +10,10 @@ function getCachedComputedStyle(el) {
10
10
  return computedStyle;
11
11
  }
12
12
  function isVisible(el) {
13
- // This is the fastest check, but isn't supported in Safari.
13
+ // This is the fastest check, but isn't supported in Safari.
14
14
  if ('checkVisibility' in el && typeof el['checkVisibility'] === 'function') {
15
15
  // Opacity is focusable, visibility is not.
16
+ /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
16
17
  return el['checkVisibility']({
17
18
  checkOpacity: false,
18
19
  checkVisibilityCSS: true,
@@ -1 +1 @@
1
- {"version":3,"file":"tabbable.js","sourceRoot":"","sources":["../../../src/shoelace/tabbable.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,wFAAwF;AACxF,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAgC,CAAC;AAErE,SAAS,sBAAsB,CAAC,EAAe;IAC7C,IAAI,aAAa,GAAoC,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAE9E,IAAI,CAAC,aAAa,EAAE;QAClB,aAAa,GAAG,MAAM,CAAC,gBAAgB,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;QAClD,gBAAgB,CAAC,GAAG,CAAC,EAAE,EAAE,aAAa,CAAC,CAAC;KACzC;IAED,OAAO,aAAa,CAAC;AACvB,CAAC;AAED,SAAS,SAAS,CAAC,EAAe;IAChC,8DAA8D;IAC9D,IAAI,iBAAiB,IAAI,EAAE,IA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AC;YAExB,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE;gBACpD,gBAAgB,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;aAC3B;YAED,IACE,EAAE,YAAY,eAAe;gBAC7B,oCAAoC,CAAC,EAAE,EAAE,IAAI,CAAC,EAC9C;gBACA,EAAE,CAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,OAAO,CAC5C,CAAC,UAAmB,EAAE,EAAE;oBACtB,IAAI,CAAC,UAAsC,CAAC,CAAC;gBAC/C,CAAC,CACF,CAAC;aACH;YAED,IAAI,EAAE,CAAC,UAAU,KAAK,IAAI,IAAI,EAAE,CAAC,UAAU,CAAC,IAAI,KAAK,MAAM,EAAE;gBAC3D,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC;aACrB;SACF;QAED,KAAK,MAAM,CAAC,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,QAAQ,CAAkB,EAAE;YACxD,IAAI,CAAC,CAAC,CAAC,CAAC;SACT;IACH,CAAC;IAED,0CAA0C;IAC1C,IAAI,CAAC,IAAI,CAAC,CAAC;IAEX,yHAAyH;IACzH,uCAAuC;IACvC,OAAO,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QACpC,iCAAiC;QACjC,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC;QAC1D,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC;QAC1D,OAAO,SAAS,GAAG,SAAS,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Cached compute style calls. This is specifically for browsers that dont support `checkVisibility()`.\n// computedStyle calls are \"live\" so they only need to be retrieved once for an element.\nconst computedStyleMap = new WeakMap<Element, CSSStyleDeclaration>();\n\nfunction getCachedComputedStyle(el: HTMLElement): CSSStyleDeclaration {\n let computedStyle: undefined | CSSStyleDeclaration = computedStyleMap.get(el);\n\n if (!computedStyle) {\n computedStyle = window.getComputedStyle(el, null);\n computedStyleMap.set(el, computedStyle);\n }\n\n return computedStyle;\n}\n\nfunction isVisible(el: HTMLElement): boolean {\n // This is the fastest check, but isn't supported in Safari. \n if ('checkVisibility' in el && typeof el['checkVisibility'] === 'function') {\n // Opacity is focusable, visibility is not.\n return (el as any)['checkVisibility']({\n checkOpacity: false,\n checkVisibilityCSS: true,\n });\n }\n\n // Fallback \"polyfill\" for \"checkVisibility\"\n const computedStyle = getCachedComputedStyle(el as HTMLElement);\n\n return (\n computedStyle.visibility !== 'hidden' && computedStyle.display !== 'none'\n );\n}\n\n// While this behavior isn't standard in Safari / Chrome yet, I think it's the most reasonable\n// way of handling tabbable overflow areas. Browser sniffing seems gross, and it's the most\n// accessible way of handling overflow areas. [Konnor]\nfunction isOverflowingAndTabbable(el: HTMLElement): boolean {\n const computedStyle = getCachedComputedStyle(el);\n\n const { overflowY, overflowX } = computedStyle;\n\n if (overflowY === 'scroll' || overflowX === 'scroll') {\n return true;\n }\n\n if (overflowY !== 'auto' || overflowX !== 'auto') {\n return false;\n }\n\n // Always overflow === \"auto\" by this point\n const isOverflowingY = el.scrollHeight > el.clientHeight;\n\n if (isOverflowingY && overflowY === 'auto') {\n return true;\n }\n\n const isOverflowingX = el.scrollWidth > el.clientWidth;\n\n if (isOverflowingX && overflowX === 'auto') {\n return true;\n }\n\n return false;\n}\n\n/** Determines if the specified element is tabbable using heuristics inspired by https://github.com/focus-trap/tabbable */\nfunction isTabbable(el: HTMLElement) {\n const tag = el.tagName.toLowerCase();\n\n const tabindex = Number(el.getAttribute('tabindex'));\n const hasTabindex = el.hasAttribute('tabindex');\n\n // elements with a tabindex attribute that is either NaN or <= -1 are not tabbable\n if (hasTabindex && (isNaN(tabindex) || tabindex <= -1)) {\n return false;\n }\n\n // Elements with a disabled attribute are not tabbable\n if (el.hasAttribute('disabled')) {\n return false;\n }\n\n // If any parents have \"inert\", we aren't \"tabbable\"\n if (el.closest('[inert]')) {\n return false;\n }\n\n // Radios without a checked attribute are not tabbable\n if (\n tag === 'input' &&\n el.getAttribute('type') === 'radio' &&\n !el.hasAttribute('checked')\n ) {\n return false;\n }\n\n if (!isVisible(el)) {\n return false;\n }\n\n // Audio and video elements with the controls attribute are tabbable\n if ((tag === 'audio' || tag === 'video') && el.hasAttribute('controls')) {\n return true;\n }\n\n // Elements with a tabindex other than -1 are tabbable\n if (el.hasAttribute('tabindex')) {\n return true;\n }\n\n // Elements with a contenteditable attribute are tabbable\n if (\n el.hasAttribute('contenteditable') &&\n el.getAttribute('contenteditable') !== 'false'\n ) {\n return true;\n }\n\n // At this point, the following elements are considered tabbable\n const isNativelyTabbable = [\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'a',\n 'audio',\n 'video',\n 'summary',\n 'iframe',\n ].includes(tag);\n\n if (isNativelyTabbable) {\n return true;\n }\n\n // We save the overflow checks for last, because they're the most expensive\n return isOverflowingAndTabbable(el);\n}\n\n/**\n * Returns the first and last bounding elements that are tabbable. This is more performant than checking every single\n * element because it short-circuits after finding the first and last ones.\n */\nexport function getTabbableBoundary(root: HTMLElement | ShadowRoot) {\n const tabbableElements = getTabbableElements(root);\n\n // Find the first and last tabbable elements\n const start = tabbableElements[0] ?? null;\n const end = tabbableElements[tabbableElements.length - 1] ?? null;\n\n return { start, end };\n}\n\n/**\n * This looks funky. Basically a slot's children will always be picked up *if* they're within the `root` element.\n * However, there is an edge case when, if the `root` is wrapped by another shadow DOM, it won't grab the children.\n * This fixes that fun edge case.\n */\nfunction getSlottedChildrenOutsideRootElement(\n slotElement: HTMLSlotElement,\n root: HTMLElement | ShadowRoot\n) {\n return (\n (slotElement.getRootNode({ composed: true }) as ShadowRoot | null)?.host !==\n root\n );\n}\n\nexport function getTabbableElements(root: HTMLElement | ShadowRoot) {\n const walkedEls = new WeakMap();\n const tabbableElements: HTMLElement[] = [];\n\n function walk(el: HTMLElement | ShadowRoot) {\n if (el instanceof Element) {\n // if the element has \"inert\" we can just no-op it.\n if (el.hasAttribute('inert') || el.closest('[inert]')) {\n return;\n }\n\n if (walkedEls.has(el)) {\n return;\n }\n walkedEls.set(el, true);\n\n if (!tabbableElements.includes(el) && isTabbable(el)) {\n tabbableElements.push(el);\n }\n\n if (\n el instanceof HTMLSlotElement &&\n getSlottedChildrenOutsideRootElement(el, root)\n ) {\n el.assignedElements({ flatten: true }).forEach(\n (assignedEl: Element) => {\n walk(assignedEl as HTMLElement | ShadowRoot);\n }\n );\n }\n\n if (el.shadowRoot !== null && el.shadowRoot.mode === 'open') {\n walk(el.shadowRoot);\n }\n }\n\n for (const e of Array.from(el.children) as HTMLElement[]) {\n walk(e);\n }\n }\n\n // Collect all elements including the root\n walk(root);\n\n // Is this worth having? Most sorts will always add increased overhead. And positive tabindexes shouldn't really be used.\n // So is it worth being right? Or fast?\n return tabbableElements.sort((a, b) => {\n // Make sure we sort by tabindex.\n const aTabindex = Number(a.getAttribute('tabindex')) || 0;\n const bTabindex = Number(b.getAttribute('tabindex')) || 0;\n return bTabindex - aTabindex;\n });\n}\n"]}
1
+ {"version":3,"file":"tabbable.js","sourceRoot":"","sources":["../../../src/shoelace/tabbable.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,wFAAwF;AACxF,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAgC,CAAC;AAErE,SAAS,sBAAsB,CAAC,EAAe;IAC7C,IAAI,aAAa,GAAoC,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAE9E,IAAI,CAAC,aAAa,EAAE;QAClB,aAAa,GAAG,MAAM,CAAC,gBAAgB,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;QAClD,gBAAgB,CAAC,GAAG,CAAC,EAAE,EAAE,aAAa,CAAC,CAAC;KACzC;I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S,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Cached compute style calls. This is specifically for browsers that dont support `checkVisibility()`.\n// computedStyle calls are \"live\" so they only need to be retrieved once for an element.\nconst computedStyleMap = new WeakMap<Element, CSSStyleDeclaration>();\n\nfunction getCachedComputedStyle(el: HTMLElement): CSSStyleDeclaration {\n let computedStyle: undefined | CSSStyleDeclaration = computedStyleMap.get(el);\n\n if (!computedStyle) {\n computedStyle = window.getComputedStyle(el, null);\n computedStyleMap.set(el, computedStyle);\n }\n\n return computedStyle;\n}\n\nfunction isVisible(el: HTMLElement): boolean {\n // This is the fastest check, but isn't supported in Safari.\n if ('checkVisibility' in el && typeof el['checkVisibility'] === 'function') {\n // Opacity is focusable, visibility is not.\n /* eslint-disable-next-line @typescript-eslint/no-explicit-any */\n return (el as any)['checkVisibility']({\n checkOpacity: false,\n checkVisibilityCSS: true,\n });\n }\n\n // Fallback \"polyfill\" for \"checkVisibility\"\n const computedStyle = getCachedComputedStyle(el as HTMLElement);\n\n return (\n computedStyle.visibility !== 'hidden' && computedStyle.display !== 'none'\n );\n}\n\n// While this behavior isn't standard in Safari / Chrome yet, I think it's the most reasonable\n// way of handling tabbable overflow areas. Browser sniffing seems gross, and it's the most\n// accessible way of handling overflow areas. [Konnor]\nfunction isOverflowingAndTabbable(el: HTMLElement): boolean {\n const computedStyle = getCachedComputedStyle(el);\n\n const { overflowY, overflowX } = computedStyle;\n\n if (overflowY === 'scroll' || overflowX === 'scroll') {\n return true;\n }\n\n if (overflowY !== 'auto' || overflowX !== 'auto') {\n return false;\n }\n\n // Always overflow === \"auto\" by this point\n const isOverflowingY = el.scrollHeight > el.clientHeight;\n\n if (isOverflowingY && overflowY === 'auto') {\n return true;\n }\n\n const isOverflowingX = el.scrollWidth > el.clientWidth;\n\n if (isOverflowingX && overflowX === 'auto') {\n return true;\n }\n\n return false;\n}\n\n/** Determines if the specified element is tabbable using heuristics inspired by https://github.com/focus-trap/tabbable */\nfunction isTabbable(el: HTMLElement) {\n const tag = el.tagName.toLowerCase();\n\n const tabindex = Number(el.getAttribute('tabindex'));\n const hasTabindex = el.hasAttribute('tabindex');\n\n // elements with a tabindex attribute that is either NaN or <= -1 are not tabbable\n if (hasTabindex && (isNaN(tabindex) || tabindex <= -1)) {\n return false;\n }\n\n // Elements with a disabled attribute are not tabbable\n if (el.hasAttribute('disabled')) {\n return false;\n }\n\n // If any parents have \"inert\", we aren't \"tabbable\"\n if (el.closest('[inert]')) {\n return false;\n }\n\n // Radios without a checked attribute are not tabbable\n if (\n tag === 'input' &&\n el.getAttribute('type') === 'radio' &&\n !el.hasAttribute('checked')\n ) {\n return false;\n }\n\n if (!isVisible(el)) {\n return false;\n }\n\n // Audio and video elements with the controls attribute are tabbable\n if ((tag === 'audio' || tag === 'video') && el.hasAttribute('controls')) {\n return true;\n }\n\n // Elements with a tabindex other than -1 are tabbable\n if (el.hasAttribute('tabindex')) {\n return true;\n }\n\n // Elements with a contenteditable attribute are tabbable\n if (\n el.hasAttribute('contenteditable') &&\n el.getAttribute('contenteditable') !== 'false'\n ) {\n return true;\n }\n\n // At this point, the following elements are considered tabbable\n const isNativelyTabbable = [\n 'button',\n 'input',\n 'select',\n 'textarea',\n 'a',\n 'audio',\n 'video',\n 'summary',\n 'iframe',\n ].includes(tag);\n\n if (isNativelyTabbable) {\n return true;\n }\n\n // We save the overflow checks for last, because they're the most expensive\n return isOverflowingAndTabbable(el);\n}\n\n/**\n * Returns the first and last bounding elements that are tabbable. This is more performant than checking every single\n * element because it short-circuits after finding the first and last ones.\n */\nexport function getTabbableBoundary(root: HTMLElement | ShadowRoot) {\n const tabbableElements = getTabbableElements(root);\n\n // Find the first and last tabbable elements\n const start = tabbableElements[0] ?? null;\n const end = tabbableElements[tabbableElements.length - 1] ?? null;\n\n return { start, end };\n}\n\n/**\n * This looks funky. Basically a slot's children will always be picked up *if* they're within the `root` element.\n * However, there is an edge case when, if the `root` is wrapped by another shadow DOM, it won't grab the children.\n * This fixes that fun edge case.\n */\nfunction getSlottedChildrenOutsideRootElement(\n slotElement: HTMLSlotElement,\n root: HTMLElement | ShadowRoot\n) {\n return (\n (slotElement.getRootNode({ composed: true }) as ShadowRoot | null)?.host !==\n root\n );\n}\n\nexport function getTabbableElements(root: HTMLElement | ShadowRoot) {\n const walkedEls = new WeakMap();\n const tabbableElements: HTMLElement[] = [];\n\n function walk(el: HTMLElement | ShadowRoot) {\n if (el instanceof Element) {\n // if the element has \"inert\" we can just no-op it.\n if (el.hasAttribute('inert') || el.closest('[inert]')) {\n return;\n }\n\n if (walkedEls.has(el)) {\n return;\n }\n walkedEls.set(el, true);\n\n if (!tabbableElements.includes(el) && isTabbable(el)) {\n tabbableElements.push(el);\n }\n\n if (\n el instanceof HTMLSlotElement &&\n getSlottedChildrenOutsideRootElement(el, root)\n ) {\n el.assignedElements({ flatten: true }).forEach(\n (assignedEl: Element) => {\n walk(assignedEl as HTMLElement | ShadowRoot);\n }\n );\n }\n\n if (el.shadowRoot !== null && el.shadowRoot.mode === 'open') {\n walk(el.shadowRoot);\n }\n }\n\n for (const e of Array.from(el.children) as HTMLElement[]) {\n walk(e);\n }\n }\n\n // Collect all elements including the root\n walk(root);\n\n // Is this worth having? Most sorts will always add increased overhead. And positive tabindexes shouldn't really be used.\n // So is it worth being right? Or fast?\n return tabbableElements.sort((a, b) => {\n // Make sure we sort by tabindex.\n const aTabindex = Number(a.getAttribute('tabindex')) || 0;\n const bTabindex = Number(b.getAttribute('tabindex')) || 0;\n return bTabindex - aTabindex;\n });\n}\n"]}
package/index.html CHANGED
@@ -56,7 +56,7 @@
56
56
 
57
57
  render(
58
58
  html`
59
- <modal-manager tabindex="-1">
59
+ <modal-manager>
60
60
  <div slot="slot-content-demo">
61
61
  <p>Slotted Content</p>
62
62
  </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@internetarchive/modal-manager",
3
- "version": "0.9.1-alpha.0",
3
+ "version": "1.0.0",
4
4
  "description": "A Modal Manager Web Component",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,7 +26,7 @@
26
26
  "circular": "madge --circular .",
27
27
  "test": "tsc && npm run lint && npm run circular && karma start --coverage",
28
28
  "test:watch": "concurrently --kill-others --names tsc,karma \"npm run tsc:watch\" \"karma start --auto-watch=true --single-run=false\"",
29
- "publish:alpha": "npm run test && npm run prepare && npm version prerelease --preid alpha && npm publish --tag alpha"
29
+ "publish:alpha": "npm run test && npm run prepare && npm version prerelease --preid alpha --no-git-tag-version && npm publish --tag alpha"
30
30
  },
31
31
  "dependencies": {
32
32
  "@internetarchive/ia-activity-indicator": "^0.0.4",
@@ -8,8 +8,6 @@ import {
8
8
  } from 'lit';
9
9
  import { property, customElement, query } from 'lit/decorators.js';
10
10
 
11
- import Modal from './shoelace/modal';
12
-
13
11
  import './modal-template';
14
12
  import { ModalTemplate } from './modal-template';
15
13
  import { ModalConfig } from './modal-config';
@@ -40,7 +38,7 @@ export class ModalManager extends LitElement implements ModalManagerInterface {
40
38
  @property({ type: Object }) customModalContent?: TemplateResult;
41
39
 
42
40
  /**
43
- * This hostBridge handles environmental-specific interactions such as adding classes
41
+ * Thie hostBridge handles environmental-specific interactions such as adding classes
44
42
  * to the body tag or event listeners needed to support the modal manager in the host environment.
45
43
  *
46
44
  * There is a default `ModalManagerHostBridge`, but consumers can override it with a custom
@@ -63,20 +61,6 @@ export class ModalManager extends LitElement implements ModalManagerInterface {
63
61
  */
64
62
  @query('modal-template') private modalTemplate!: ModalTemplate;
65
63
 
66
- // Imported tab handling from shoelace
67
- public modal = new Modal(this);
68
-
69
- async firstUpdated(): Promise<void> {
70
- // Give the browser a chance to paint
71
- // eslint-disable-next-line no-promise-executor-return
72
- await new Promise(r => setTimeout(r, 0));
73
- }
74
-
75
- disconnectedCallback() {
76
- super.disconnectedCallback();
77
- this.modal.deactivate();
78
- }
79
-
80
64
  /** @inheritdoc */
81
65
  render(): TemplateResult {
82
66
  return html`
@@ -84,7 +68,7 @@ export class ModalManager extends LitElement implements ModalManagerInterface {
84
68
  <div class="backdrop" @click=${this.backdropClicked}></div>
85
69
  <modal-template
86
70
  @closeButtonPressed=${this.closeButtonPressed}
87
- tabindex="-1"
71
+ tabindex="0"
88
72
  >
89
73
  ${this.customModalContent}
90
74
  </modal-template>
@@ -102,7 +86,6 @@ export class ModalManager extends LitElement implements ModalManagerInterface {
102
86
  this.mode = ModalManagerMode.Closed;
103
87
  this.customModalContent = undefined;
104
88
  this.modalTemplate.config = new ModalConfig();
105
- this.modal.deactivate();
106
89
  }
107
90
 
108
91
  /**
@@ -148,17 +131,7 @@ export class ModalManager extends LitElement implements ModalManagerInterface {
148
131
  this.customModalContent = options.customModalContent;
149
132
  this.mode = ModalManagerMode.Open;
150
133
  await this.modalTemplate.updateComplete;
151
-
152
- this.modal.activate();
153
-
154
- // document.addEventListener('keydown', this.tabHandler);
155
-
156
- // this.firstFocusableElement.focus();
157
- // console.log('firstFocusableElement', this.firstFocusableElement);
158
- // console.log('lastFocusableElement', this.lastFocusableElement);
159
- // console.log('focusableContent', this.focusableContent);
160
-
161
- // this.modalTemplate.focus();
134
+ this.modalTemplate.focus();
162
135
  }
163
136
 
164
137
  /** @inheritdoc */
@@ -1,32 +0,0 @@
1
- /**
2
- * Use a generator so we can iterate and possibly break early.
3
- * @example
4
- * // to operate like a regular array. This kinda nullifies generator benefits, but worth knowing if you need the whole array.
5
- * const allActiveElements = [...activeElements()]
6
- *
7
- * // Early return
8
- * for (const activeElement of activeElements()) {
9
- * if (<cond>) {
10
- * break; // Break the loop, dont need to iterate over the whole array or store an array in memory!
11
- * }
12
- * }
13
- */
14
- export function* activeElements(
15
- activeElement: Element | null = document.activeElement
16
- ): Generator<Element> {
17
- if (activeElement === null || activeElement === undefined) return;
18
-
19
- yield activeElement;
20
-
21
- if (
22
- 'shadowRoot' in activeElement &&
23
- activeElement.shadowRoot &&
24
- activeElement.shadowRoot.mode !== 'closed'
25
- ) {
26
- yield* activeElements(activeElement.shadowRoot.activeElement);
27
- }
28
- }
29
-
30
- export function getDeepestActiveElement() {
31
- return [...activeElements()].pop();
32
- }
@@ -1,165 +0,0 @@
1
- import { activeElements, getDeepestActiveElement } from './active-elements.js';
2
- import { getTabbableElements } from './tabbable.js';
3
-
4
- let activeModals: HTMLElement[] = [];
5
-
6
- export default class Modal {
7
- element: HTMLElement;
8
- isExternalActivated: boolean = false;
9
- tabDirection: 'forward' | 'backward' = 'forward';
10
- currentFocus: HTMLElement | null = null;
11
- previousFocus: HTMLElement | null = null;
12
- elementsWithTabbableControls: string[];
13
-
14
- constructor(element: HTMLElement) {
15
- this.element = element;
16
-
17
- this.elementsWithTabbableControls = ['iframe'];
18
- }
19
-
20
- /** Activates focus trapping. */
21
- activate() {
22
- activeModals.push(this.element);
23
- document.addEventListener('focusin', this.handleFocusIn);
24
- document.addEventListener('keydown', this.handleKeyDown);
25
- document.addEventListener('keyup', this.handleKeyUp);
26
- }
27
-
28
- /** Deactivates focus trapping. */
29
- deactivate() {
30
- activeModals = activeModals.filter(modal => modal !== this.element);
31
- this.currentFocus = null;
32
- document.removeEventListener('focusin', this.handleFocusIn);
33
- document.removeEventListener('keydown', this.handleKeyDown);
34
- document.removeEventListener('keyup', this.handleKeyUp);
35
- }
36
-
37
- /** Determines if this modal element is currently active or not. */
38
- isActive() {
39
- // The "active" modal is always the most recent one shown
40
- return activeModals[activeModals.length - 1] === this.element;
41
- }
42
-
43
- /** Activates external modal behavior and temporarily disables focus trapping. */
44
- activateExternal() {
45
- this.isExternalActivated = true;
46
- }
47
-
48
- /** Deactivates external modal behavior and re-enables focus trapping. */
49
- deactivateExternal() {
50
- this.isExternalActivated = false;
51
- }
52
-
53
- private checkFocus() {
54
- if (this.isActive() && !this.isExternalActivated) {
55
- const tabbableElements = getTabbableElements(this.element);
56
- if (!this.element.matches(':focus-within')) {
57
- const start = tabbableElements[0];
58
- const end = tabbableElements[tabbableElements.length - 1];
59
- const target = this.tabDirection === 'forward' ? start : end;
60
-
61
- if (typeof target?.focus === 'function') {
62
- this.currentFocus = target;
63
- target.focus({ preventScroll: false });
64
- }
65
- }
66
- }
67
- }
68
-
69
- private handleFocusIn = () => {
70
- if (!this.isActive()) return;
71
- this.checkFocus();
72
- };
73
-
74
- private possiblyHasTabbableChildren(element: HTMLElement) {
75
- return (
76
- this.elementsWithTabbableControls.includes(
77
- element.tagName.toLowerCase()
78
- ) || element.hasAttribute('controls')
79
- // Should we add a data-attribute for people to set just in case they have an element where we don't know if it has possibly tabbable elements?
80
- );
81
- }
82
-
83
- private handleKeyDown = (event: KeyboardEvent) => {
84
- if (event.key !== 'Tab' || this.isExternalActivated) return;
85
- if (!this.isActive()) return;
86
-
87
- // Because sometimes focus can actually be taken over from outside sources,
88
- // we don't want to rely on `this.currentFocus`. Instead we check the actual `activeElement` and
89
- // recurse through shadowRoots.
90
- const currentActiveElement = getDeepestActiveElement();
91
- this.previousFocus = currentActiveElement as HTMLElement | null;
92
-
93
- if (
94
- this.previousFocus &&
95
- this.possiblyHasTabbableChildren(this.previousFocus)
96
- ) {
97
- return;
98
- }
99
-
100
- if (event.shiftKey) {
101
- this.tabDirection = 'backward';
102
- } else {
103
- this.tabDirection = 'forward';
104
- }
105
-
106
- const tabbableElements = getTabbableElements(this.element);
107
-
108
- let currentFocusIndex = tabbableElements.findIndex(
109
- el => el === currentActiveElement
110
- );
111
-
112
- this.previousFocus = this.currentFocus;
113
-
114
- const addition = this.tabDirection === 'forward' ? 1 : -1;
115
-
116
- // eslint-disable-next-line
117
- while (true) {
118
- if (currentFocusIndex + addition >= tabbableElements.length) {
119
- currentFocusIndex = 0;
120
- } else if (currentFocusIndex + addition < 0) {
121
- currentFocusIndex = tabbableElements.length - 1;
122
- } else {
123
- currentFocusIndex += addition;
124
- }
125
-
126
- this.previousFocus = this.currentFocus;
127
- const nextFocus =
128
- /** @type {HTMLElement} */ tabbableElements[currentFocusIndex];
129
-
130
- // This is a special case. We need to make sure we're not calling .focus() if we're already focused on an element
131
- // that possibly has "controls"
132
- if (this.tabDirection === 'backward') {
133
- if (
134
- this.previousFocus &&
135
- this.possiblyHasTabbableChildren(this.previousFocus)
136
- ) {
137
- return;
138
- }
139
- }
140
-
141
- if (nextFocus && this.possiblyHasTabbableChildren(nextFocus)) {
142
- return;
143
- }
144
-
145
- event.preventDefault();
146
- this.currentFocus = nextFocus;
147
- this.currentFocus?.focus({ preventScroll: false });
148
-
149
- // Check to make sure focus actually changed. It may not always be the next focus, we just don't want it to be the previousFocus.
150
- const allActiveElements = [...activeElements()];
151
- if (
152
- allActiveElements.includes(this.currentFocus) ||
153
- !allActiveElements.includes(this.previousFocus!)
154
- ) {
155
- break;
156
- }
157
- }
158
-
159
- setTimeout(() => this.checkFocus());
160
- };
161
-
162
- private handleKeyUp = () => {
163
- this.tabDirection = 'forward';
164
- };
165
- }
@@ -1,221 +0,0 @@
1
- // Cached compute style calls. This is specifically for browsers that dont support `checkVisibility()`.
2
- // computedStyle calls are "live" so they only need to be retrieved once for an element.
3
- const computedStyleMap = new WeakMap<Element, CSSStyleDeclaration>();
4
-
5
- function getCachedComputedStyle(el: HTMLElement): CSSStyleDeclaration {
6
- let computedStyle: undefined | CSSStyleDeclaration = computedStyleMap.get(el);
7
-
8
- if (!computedStyle) {
9
- computedStyle = window.getComputedStyle(el, null);
10
- computedStyleMap.set(el, computedStyle);
11
- }
12
-
13
- return computedStyle;
14
- }
15
-
16
- function isVisible(el: HTMLElement): boolean {
17
- // This is the fastest check, but isn't supported in Safari.
18
- if ('checkVisibility' in el && typeof el['checkVisibility'] === 'function') {
19
- // Opacity is focusable, visibility is not.
20
- return (el as any)['checkVisibility']({
21
- checkOpacity: false,
22
- checkVisibilityCSS: true,
23
- });
24
- }
25
-
26
- // Fallback "polyfill" for "checkVisibility"
27
- const computedStyle = getCachedComputedStyle(el as HTMLElement);
28
-
29
- return (
30
- computedStyle.visibility !== 'hidden' && computedStyle.display !== 'none'
31
- );
32
- }
33
-
34
- // While this behavior isn't standard in Safari / Chrome yet, I think it's the most reasonable
35
- // way of handling tabbable overflow areas. Browser sniffing seems gross, and it's the most
36
- // accessible way of handling overflow areas. [Konnor]
37
- function isOverflowingAndTabbable(el: HTMLElement): boolean {
38
- const computedStyle = getCachedComputedStyle(el);
39
-
40
- const { overflowY, overflowX } = computedStyle;
41
-
42
- if (overflowY === 'scroll' || overflowX === 'scroll') {
43
- return true;
44
- }
45
-
46
- if (overflowY !== 'auto' || overflowX !== 'auto') {
47
- return false;
48
- }
49
-
50
- // Always overflow === "auto" by this point
51
- const isOverflowingY = el.scrollHeight > el.clientHeight;
52
-
53
- if (isOverflowingY && overflowY === 'auto') {
54
- return true;
55
- }
56
-
57
- const isOverflowingX = el.scrollWidth > el.clientWidth;
58
-
59
- if (isOverflowingX && overflowX === 'auto') {
60
- return true;
61
- }
62
-
63
- return false;
64
- }
65
-
66
- /** Determines if the specified element is tabbable using heuristics inspired by https://github.com/focus-trap/tabbable */
67
- function isTabbable(el: HTMLElement) {
68
- const tag = el.tagName.toLowerCase();
69
-
70
- const tabindex = Number(el.getAttribute('tabindex'));
71
- const hasTabindex = el.hasAttribute('tabindex');
72
-
73
- // elements with a tabindex attribute that is either NaN or <= -1 are not tabbable
74
- if (hasTabindex && (isNaN(tabindex) || tabindex <= -1)) {
75
- return false;
76
- }
77
-
78
- // Elements with a disabled attribute are not tabbable
79
- if (el.hasAttribute('disabled')) {
80
- return false;
81
- }
82
-
83
- // If any parents have "inert", we aren't "tabbable"
84
- if (el.closest('[inert]')) {
85
- return false;
86
- }
87
-
88
- // Radios without a checked attribute are not tabbable
89
- if (
90
- tag === 'input' &&
91
- el.getAttribute('type') === 'radio' &&
92
- !el.hasAttribute('checked')
93
- ) {
94
- return false;
95
- }
96
-
97
- if (!isVisible(el)) {
98
- return false;
99
- }
100
-
101
- // Audio and video elements with the controls attribute are tabbable
102
- if ((tag === 'audio' || tag === 'video') && el.hasAttribute('controls')) {
103
- return true;
104
- }
105
-
106
- // Elements with a tabindex other than -1 are tabbable
107
- if (el.hasAttribute('tabindex')) {
108
- return true;
109
- }
110
-
111
- // Elements with a contenteditable attribute are tabbable
112
- if (
113
- el.hasAttribute('contenteditable') &&
114
- el.getAttribute('contenteditable') !== 'false'
115
- ) {
116
- return true;
117
- }
118
-
119
- // At this point, the following elements are considered tabbable
120
- const isNativelyTabbable = [
121
- 'button',
122
- 'input',
123
- 'select',
124
- 'textarea',
125
- 'a',
126
- 'audio',
127
- 'video',
128
- 'summary',
129
- 'iframe',
130
- ].includes(tag);
131
-
132
- if (isNativelyTabbable) {
133
- return true;
134
- }
135
-
136
- // We save the overflow checks for last, because they're the most expensive
137
- return isOverflowingAndTabbable(el);
138
- }
139
-
140
- /**
141
- * Returns the first and last bounding elements that are tabbable. This is more performant than checking every single
142
- * element because it short-circuits after finding the first and last ones.
143
- */
144
- export function getTabbableBoundary(root: HTMLElement | ShadowRoot) {
145
- const tabbableElements = getTabbableElements(root);
146
-
147
- // Find the first and last tabbable elements
148
- const start = tabbableElements[0] ?? null;
149
- const end = tabbableElements[tabbableElements.length - 1] ?? null;
150
-
151
- return { start, end };
152
- }
153
-
154
- /**
155
- * This looks funky. Basically a slot's children will always be picked up *if* they're within the `root` element.
156
- * However, there is an edge case when, if the `root` is wrapped by another shadow DOM, it won't grab the children.
157
- * This fixes that fun edge case.
158
- */
159
- function getSlottedChildrenOutsideRootElement(
160
- slotElement: HTMLSlotElement,
161
- root: HTMLElement | ShadowRoot
162
- ) {
163
- return (
164
- (slotElement.getRootNode({ composed: true }) as ShadowRoot | null)?.host !==
165
- root
166
- );
167
- }
168
-
169
- export function getTabbableElements(root: HTMLElement | ShadowRoot) {
170
- const walkedEls = new WeakMap();
171
- const tabbableElements: HTMLElement[] = [];
172
-
173
- function walk(el: HTMLElement | ShadowRoot) {
174
- if (el instanceof Element) {
175
- // if the element has "inert" we can just no-op it.
176
- if (el.hasAttribute('inert') || el.closest('[inert]')) {
177
- return;
178
- }
179
-
180
- if (walkedEls.has(el)) {
181
- return;
182
- }
183
- walkedEls.set(el, true);
184
-
185
- if (!tabbableElements.includes(el) && isTabbable(el)) {
186
- tabbableElements.push(el);
187
- }
188
-
189
- if (
190
- el instanceof HTMLSlotElement &&
191
- getSlottedChildrenOutsideRootElement(el, root)
192
- ) {
193
- el.assignedElements({ flatten: true }).forEach(
194
- (assignedEl: Element) => {
195
- walk(assignedEl as HTMLElement | ShadowRoot);
196
- }
197
- );
198
- }
199
-
200
- if (el.shadowRoot !== null && el.shadowRoot.mode === 'open') {
201
- walk(el.shadowRoot);
202
- }
203
- }
204
-
205
- for (const e of Array.from(el.children) as HTMLElement[]) {
206
- walk(e);
207
- }
208
- }
209
-
210
- // Collect all elements including the root
211
- walk(root);
212
-
213
- // Is this worth having? Most sorts will always add increased overhead. And positive tabindexes shouldn't really be used.
214
- // So is it worth being right? Or fast?
215
- return tabbableElements.sort((a, b) => {
216
- // Make sure we sort by tabindex.
217
- const aTabindex = Number(a.getAttribute('tabindex')) || 0;
218
- const bTabindex = Number(b.getAttribute('tabindex')) || 0;
219
- return bTabindex - aTabindex;
220
- });
221
- }