@spectrum-web-components/reactive-controllers 1.2.0-beta.8 → 1.2.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.
- package/README.md +1 -1
- package/package.json +7 -6
- package/src/ColorController.d.ts +219 -0
- package/src/ColorController.dev.js +455 -0
- package/src/ColorController.dev.js.map +7 -0
- package/src/ColorController.js +2 -0
- package/src/ColorController.js.map +7 -0
- package/src/FocusGroup.d.ts +9 -2
- package/src/FocusGroup.dev.js +46 -8
- package/src/FocusGroup.dev.js.map +2 -2
- package/src/FocusGroup.js +1 -1
- package/src/FocusGroup.js.map +3 -3
- package/src/RovingTabindex.dev.js +1 -2
- package/src/RovingTabindex.dev.js.map +2 -2
- package/src/RovingTabindex.js +1 -1
- package/src/RovingTabindex.js.map +2 -2
- package/test/color-controller.test.js +208 -0
- package/test/color-controller.test.js.map +7 -0
- package/test/roving-tabindex-integration.test.js +13 -15
- package/test/roving-tabindex-integration.test.js.map +2 -2
- package/src/Color.d.ts +0 -46
- package/src/Color.dev.js +0 -198
- package/src/Color.dev.js.map +0 -7
- package/src/Color.js +0 -2
- package/src/Color.js.map +0 -7
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["ColorController.ts"],
|
|
4
|
+
"sourcesContent": ["/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { ReactiveElement } from 'lit';\nimport Color from 'colorjs.io';\nimport type {\n ColorObject,\n ColorTypes as DefaultColorTypes,\n} from 'colorjs.io/types/src/color';\nimport type ColorSpace from 'colorjs.io/types/src/space';\n\n/**\n * Represents various color types that can be used in the application.\n *\n * This type can be one of the following:\n * - `DefaultColorTypes`: A predefined set of color types.\n * - An object representing an RGBA color with properties:\n * - `r`: Red component, can be a number or string.\n * - `g`: Green component, can be a number or string.\n * - `b`: Blue component, can be a number or string.\n * - `a` (optional): Alpha component, can be a number or string.\n * - An object representing an HSLA color with properties:\n * - `h`: Hue component, can be a number or string.\n * - `s`: Saturation component, can be a number or string.\n * - `l`: Lightness component, can be a number or string.\n * - `a` (optional): Alpha component, can be a number or string.\n * - An object representing an HSVA color with properties:\n * - `h`: Hue component, can be a number or string.\n * - `s`: Saturation component, can be a number or string.\n * - `v`: Value component, can be a number or string.\n * - `a` (optional): Alpha component, can be a number or string.\n */\ntype ColorTypes =\n | DefaultColorTypes\n | {\n r: number | string;\n g: number | string;\n b: number | string;\n a?: number | string;\n }\n | {\n h: number | string;\n s: number | string;\n l: number | string;\n a?: number | string;\n }\n | {\n h: number | string;\n s: number | string;\n v: number | string;\n a?: number | string;\n };\n\nexport type { Color, ColorTypes };\n\ntype ColorValidationResult = {\n spaceId: string | null;\n coords: number[];\n isValid: boolean;\n alpha: number;\n};\n\n/**\n * The `ColorController` class is responsible for managing and validating color values\n * in various color spaces (RGB, HSL, HSV, Hex). It provides methods to set, get, and\n * validate colors, as well as convert between different color formats.\n *\n * @class\n * @property {Color} color - Gets or sets the current color value.\n * @property {ColorTypes} colorValue - Gets the color value in various formats based on the original color input.\n * @property {number} hue - Gets or sets the hue value of the current color.\n *\n * @method validateColorString(color: string): ColorValidationResult - Validates a color string and returns the validation result.\n * @method getColor(format: string | ColorSpace): ColorObject - Converts the current color to the specified format.\n * @method getHslString(): string - Returns the current color in HSL string format.\n * @method savePreviousColor(): void - Saves the current color as the previous color.\n * @method restorePreviousColor(): void - Restores the previous color.\n *\n * @constructor\n * @param {ReactiveElement} host - The host element that uses this controller.\n * @param {Object} [options] - Optional configuration options.\n * @param {string} [options.manageAs] - Specifies the color space to manage the color as.\n */\n\nexport class ColorController {\n get color(): Color {\n return this._color;\n }\n\n /**\n * Validates a color string and returns a result indicating the color space,\n * coordinates, alpha value, and whether the color is valid.\n *\n * @param color - The color string to validate. Supported formats include:\n * - RGB: `rgb(r, g, b)`, `rgba(r, g, b, a)`, `rgb r g b`, `rgba r g b a`\n * - HSL: `hsl(h, s, l)`, `hsla(h, s, l, a)`, `hsl h s l`, `hsla h s l a`\n * - HSV: `hsv(h, s, v)`, `hsva(h, s, v, a)`, `hsv h s v`, `hsva h s v a`\n * - HEX: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`\n *\n * @returns An object containing the following properties:\n * - `spaceId`: The color space identifier (`'srgb'`, `'hsl'`, or `'hsv'`).\n * - `coords`: An array of numeric values representing the color coordinates.\n * - `alpha`: The alpha value of the color (0 to 1).\n * - `isValid`: A boolean indicating whether the color string is valid.\n */\n public validateColorString(color: string): ColorValidationResult {\n const result: ColorValidationResult = {\n spaceId: null,\n coords: [0, 0, 0],\n isValid: false,\n alpha: 1,\n };\n\n const rgbRegExpArray = [\n /rgba\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d*\\.?\\d+)\\s*\\)/i,\n /rgb\\(\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*,\\s*(\\d{1,3})\\s*\\)/i,\n /^rgba\\s+(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3})\\s+(0|0?\\.\\d+|1)\\s*$/i,\n /^rgb\\s+(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3})\\s*$/i,\n /^rgba\\(\\s*(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d*\\.?\\d+)\\s*\\)$/i,\n /^rgb\\(\\s*(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3})\\s*\\)$/i,\n /rgb\\(\\s*(100|[0-9]{1,2}%)\\s*,\\s*(100|[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d+)\\s*\\)$/i,\n /^hsv\\(\\s*(\\d{1,3})\\s+(\\d{1,3}%?)\\s+(\\d{1,3}%?)\\s*\\)$/i,\n ];\n const hexRegExpArray = [\n /^#([A-Fa-f0-9]{6})(?:\\s*([01](?:\\.\\d+)?))?$/,\n /^#([A-Fa-f0-9]{3})(?:\\s*([01](?:\\.\\d+)?))?$/,\n ];\n\n const rgbaMatch = rgbRegExpArray\n .find((regex) => regex.test(color))\n ?.exec(color);\n const hslaMatch = hslRegExpArray\n .find((regex) => regex.test(color))\n ?.exec(color);\n const hsvaMatch = hsvRegExpArray\n .find((regex) => regex.test(color))\n ?.exec(color);\n const hexMatch = hexRegExpArray\n .find((regex) => regex.test(color))\n ?.exec(color);\n\n if (rgbaMatch) {\n const [, r, g, b, a] = rgbaMatch.filter(\n (element) => typeof element === 'string'\n );\n const alpha = a === undefined ? 1 : Number(a);\n const processValue = (value: string): number => {\n if (value.includes('%')) {\n return Number(value.replace('%', '')) / 100;\n } else {\n return Number(value) / 255;\n }\n };\n const numericR = processValue(r);\n const numericG = processValue(g);\n const numericB = processValue(b);\n\n result.spaceId = 'srgb';\n result.coords = [numericR, numericG, numericB];\n result.alpha = alpha;\n result.isValid =\n numericR >= 0 &&\n numericR <= 1 &&\n numericG >= 0 &&\n numericG <= 1 &&\n numericB >= 0 &&\n numericB <= 1 &&\n alpha >= 0 &&\n alpha <= 1;\n } else if (hslaMatch) {\n const [, h, s, l, a] = hslaMatch;\n const values = [h, s, l, a === undefined ? '1' : a].map((value) =>\n Number(value.replace(/[^\\d.]/g, ''))\n );\n const [numericH, numericS, numericL, numericA] = values;\n\n result.spaceId = 'hsl';\n result.coords = [numericH, numericS, numericL];\n result.alpha = numericA;\n result.isValid =\n numericH >= 0 &&\n numericH <= 360 &&\n numericS >= 0 &&\n numericS <= 100 &&\n numericL >= 0 &&\n numericL <= 100 &&\n numericA >= 0 &&\n numericA <= 1;\n } else if (hsvaMatch) {\n const [, h, s, v, a] = hsvaMatch;\n const values = [h, s, v, a === undefined ? '1' : a].map((value) =>\n Number(value.replace(/[^\\d.]/g, ''))\n );\n const [numericH, numericS, numericV, numericA] = values;\n\n result.spaceId = 'hsv';\n result.coords = [numericH, numericS, numericV];\n result.alpha = numericA;\n result.isValid =\n numericH >= 0 &&\n numericH <= 360 &&\n numericS >= 0 &&\n numericS <= 100 &&\n numericV >= 0 &&\n numericV <= 100 &&\n numericA >= 0 &&\n numericA <= 1;\n } else if (hexMatch) {\n const [, hex, alpha] = hexMatch;\n\n // Function to process 2-digit or repeated 1-digit hex\n const processHex = (hex: string): number => {\n // For 3-digit hex values, repeat each digit\n if (hex.length === 1) {\n hex = hex + hex;\n }\n return parseInt(hex, 16) / 255;\n };\n\n // Handle both 3-digit and 6-digit hex\n let numericR, numericG, numericB;\n if (hex.length === 3) {\n // 3-digit hex (e.g., #3a7 -> #33aa77)\n numericR = processHex(hex.substring(0, 1));\n numericG = processHex(hex.substring(1, 2));\n numericB = processHex(hex.substring(2, 3));\n } else {\n // 6-digit hex (e.g., #33aa77)\n numericR = processHex(hex.substring(0, 2));\n numericG = processHex(hex.substring(2, 4));\n numericB = processHex(hex.substring(4, 6));\n }\n\n // Numeric alpha: if not provided, default to 1\n const numericA = alpha ? Number(alpha) : 1;\n\n // Validate the color values\n result.spaceId = 'srgb';\n result.coords = [numericR, numericG, numericB];\n result.alpha = numericA;\n result.isValid =\n numericR >= 0 &&\n numericR <= 1 &&\n numericG >= 0 &&\n numericG <= 1 &&\n numericB >= 0 &&\n numericB <= 1 &&\n numericA >= 0 &&\n numericA <= 1;\n }\n\n return result;\n }\n\n /**\n * Represents the color state of the component.\n * Initialized with an HSV color model with hue 0, saturation 100, and value 100, and an alpha value of 1.\n *\n * @private\n * @type {Color}\n */\n private _color: Color = new Color('hsv', [0, 100, 100], 1);\n\n /**\n * Represents the original color value provided by the user.\n *\n * @private\n * @type {ColorTypes}\n */\n private _colorOrigin!: ColorTypes;\n\n /**\n * Gets the original color value provided by the user.\n *\n * @returns {ColorTypes} The original color value.\n */\n get colorOrigin(): ColorTypes {\n return this._colorOrigin;\n }\n\n /**\n * Sets the original color value provided by the user.\n *\n * @param {ColorTypes} colorOrigin - The original color value to set.\n */\n set colorOrigin(colorOrigin: ColorTypes) {\n this._colorOrigin = colorOrigin;\n }\n\n /**\n * An optional string property that specifies how the color should be managed(its value is the name of color space in which color object will be managed).\n * This property can be used to define a specific management strategy or identifier.\n */\n private manageAs?: string;\n\n /**\n * Stores the previous color value.\n * This is used to keep track of the color before any changes are made.\n *\n * @private\n */\n private _previousColor!: Color;\n\n /**\n * Sets the color value for the controller. The color can be provided in various formats:\n * - A string representing a color name, hex code, or other color format.\n * - An instance of the `Color` class.\n * - An object containing color properties such as `h`, `s`, `l`, `v`, `r`, `g`, `b`, and optionally `a`.\n *\n * The method validates and parses the input color, converting it to a `Color` instance.\n * If the color is invalid, it attempts to parse it as a hex code or returns without setting a new color.\n *\n * @param {ColorTypes} color - The color value to set. It can be a string, an instance of `Color`, or an object with color properties.\n */\n set color(color: ColorTypes) {\n this._colorOrigin = color;\n let newColor!: Color;\n if (typeof color === 'string') {\n const colorValidationResult = this.validateColorString(\n color as string\n );\n if (colorValidationResult.isValid) {\n const [coord1, coord2, coord3] = colorValidationResult.coords;\n newColor = new Color(\n `${colorValidationResult.spaceId}`,\n [coord1, coord2, coord3],\n colorValidationResult.alpha\n );\n } else {\n try {\n Color.parse(color);\n } catch (error) {\n try {\n newColor = new Color(`#${color}`);\n } catch (error) {\n return;\n }\n }\n }\n } else if (color instanceof Color) {\n newColor = color;\n } else if (!Array.isArray(color)) {\n const { h, s, l, v, r, g, b, a } = color as {\n h: string;\n s: string;\n l: string;\n v: string;\n r: string;\n g: string;\n b: string;\n a?: string;\n };\n if (typeof h !== 'undefined' && typeof s !== 'undefined') {\n const lv = l ?? v;\n newColor = new Color(\n typeof l !== 'undefined' ? 'hsl' : 'hsv',\n [\n parseFloat(h),\n typeof s !== 'string' ? s * 100 : parseFloat(s),\n typeof lv !== 'string' ? lv * 100 : parseFloat(lv),\n ],\n parseFloat(a || '1')\n );\n } else if (\n typeof r !== 'undefined' &&\n typeof g !== 'undefined' &&\n typeof b !== 'undefined'\n ) {\n newColor = new Color(\n 'srgb',\n [\n parseFloat(r) / 255,\n parseFloat(g) / 255,\n parseFloat(b) / 255,\n ],\n parseFloat(a || '1')\n );\n }\n }\n\n if (!newColor) {\n newColor = new Color(color as DefaultColorTypes);\n }\n\n if (this.manageAs) {\n this._color = newColor.to(this.manageAs) as Color;\n } else {\n this._color = newColor;\n }\n this.host.requestUpdate();\n }\n\n /**\n * Gets the color value in various formats based on the original color input.\n *\n * The method determines the color space of the original color input and converts\n * the color to the appropriate format. The supported color spaces are:\n * - HSV (Hue, Saturation, Value)\n * - HSL (Hue, Saturation, Lightness)\n * - Hexadecimal (with or without alpha)\n * - RGB (Red, Green, Blue) with optional alpha\n *\n * @returns {ColorTypes} The color value in the appropriate format.\n *\n * The method handles the following cases:\n * - If the original color input is a string, it checks the prefix to determine the color space.\n * - If the original color input is an object, it checks the properties to determine the color space.\n * - If the original color input is not provided, it defaults to the current color space of the color object.\n *\n * The returned color value can be in one of the following formats:\n * - `hsv(h, s%, v%)` or `hsva(h, s%, v%, a)`\n * - `hsl(h, s%, l%)` or `hsla(h, s%, l%, a)`\n * - `#rrggbb` or `#rrggbbaa`\n * - `rgb(r, g, b)` or `rgba(r, g, b, a)`\n * - `{ h, s, v, a }` for HSV object\n * - `{ h, s, l, a }` for HSL object\n * - `{ r, g, b, a }` for RGB object\n */\n get colorValue(): ColorTypes {\n if (typeof this._colorOrigin === 'string') {\n let spaceId = '';\n if (this._colorOrigin.startsWith('#')) {\n spaceId = 'hex string';\n } else if (this._colorOrigin.startsWith('rgb')) {\n spaceId = 'rgb';\n } else if (this._colorOrigin.startsWith('hsl')) {\n spaceId = 'hsl';\n } else if (this._colorOrigin.startsWith('hsv')) {\n spaceId = 'hsv';\n } else {\n spaceId = 'hex';\n }\n switch (spaceId) {\n case 'hsv': {\n const hadAlpha = this._colorOrigin[3] === 'a';\n const { h, s, v } = (this._color.to('hsv') as Color).hsv;\n const a = this._color.alpha;\n return `hsv${hadAlpha ? `a` : ''}(${Math.round(\n h\n )}, ${Math.round(s)}%, ${Math.round(v)}%${\n hadAlpha ? `, ${a}` : ''\n })`;\n }\n case 'hsl': {\n const hadAlpha = this._colorOrigin[3] === 'a';\n const { h, s, l } = (this._color.to('hsl') as Color).hsl;\n const a = this._color.alpha;\n return `hsl${hadAlpha ? `a` : ''}(${Math.round(\n h\n )}, ${Math.round(s)}%, ${Math.round(l)}%${\n hadAlpha ? `, ${a}` : ''\n })`;\n }\n case 'hex string': {\n const { r, g, b } = (this._color.to('srgb') as Color).srgb;\n const hadAlpha =\n this._colorOrigin.length === 5 ||\n this._colorOrigin.length === 9;\n const a = this._color.alpha;\n const rHex = Math.round(r * 255).toString(16);\n const gHex = Math.round(g * 255).toString(16);\n const bHex = Math.round(b * 255).toString(16);\n const aHex = Math.round(a * 255).toString(16);\n return `#${rHex.padStart(2, '0')}${gHex.padStart(\n 2,\n '0'\n )}${bHex.padStart(2, '0')}${\n hadAlpha ? aHex.padStart(2, '0') : ''\n }`;\n }\n case 'hex': {\n const { r, g, b } = (this._color.to('srgb') as Color).srgb;\n const hadAlpha =\n this._colorOrigin.length === 4 ||\n this._colorOrigin.length === 8;\n const a = this._color.alpha;\n const rHex = Math.round(r * 255).toString(16);\n const gHex = Math.round(g * 255).toString(16);\n const bHex = Math.round(b * 255).toString(16);\n const aHex = Math.round(a * 255).toString(16);\n return `${rHex.padStart(2, '0')}${gHex.padStart(\n 2,\n '0'\n )}${bHex.padStart(2, '0')}${\n hadAlpha ? aHex.padStart(2, '0') : ''\n }`;\n }\n //rgb\n default: {\n const { r, g, b } = (this._color.to('srgb') as Color).srgb;\n const hadAlpha = this._colorOrigin[3] === 'a';\n const a = this._color.alpha;\n if (this._colorOrigin.search('%') > -1) {\n return `rgb${hadAlpha ? `a` : ''}(${Math.round(r * 100)}%, ${Math.round(\n g * 100\n )}%, ${Math.round(b * 100)}%${hadAlpha ? `,${Math.round(a * 100)}%` : ''})`;\n }\n return `rgb${hadAlpha ? `a` : ''}(${Math.round(r * 255)}, ${Math.round(\n g * 255\n )}, ${Math.round(b * 255)}${hadAlpha ? `, ${a}` : ''})`;\n }\n }\n }\n let spaceId;\n if (this._colorOrigin) {\n try {\n ({ spaceId } = new Color(\n this._colorOrigin as DefaultColorTypes\n ));\n } catch (error) {\n const { h, s, l, v, r, g, b } = this._colorOrigin as {\n h: string;\n s: string;\n l: string;\n v: string;\n r: string;\n g: string;\n b: string;\n };\n if (\n typeof h !== 'undefined' &&\n typeof s !== 'undefined' &&\n typeof l !== 'undefined'\n ) {\n spaceId = 'hsl';\n } else if (\n typeof h !== 'undefined' &&\n typeof s !== 'undefined' &&\n typeof v !== 'undefined'\n ) {\n spaceId = 'hsv';\n } else if (\n typeof r !== 'undefined' &&\n typeof g !== 'undefined' &&\n typeof b !== 'undefined'\n ) {\n spaceId = 'srgb';\n }\n }\n } else {\n ({ spaceId } = this.color);\n }\n switch (spaceId) {\n case 'hsv': {\n const { h, s, v } = (this._color.to('hsv') as Color).hsv;\n return {\n h,\n s: s / 100,\n v: v / 100,\n a: this._color.alpha,\n };\n }\n case 'hsl': {\n const { h, s, l } = (this._color.to('hsl') as Color).hsl;\n return {\n h,\n s: s / 100,\n l: l / 100,\n a: this._color.alpha,\n };\n }\n case 'srgb': {\n const { r, g, b } = (this._color.to('srgb') as Color).srgb;\n if (\n this._colorOrigin &&\n typeof (this._colorOrigin as { r: string }).r ===\n 'string' &&\n (this._colorOrigin as { r: string }).r.search('%')\n ) {\n return {\n r: `${Math.round(r * 255)}%`,\n g: `${Math.round(g * 255)}%`,\n b: `${Math.round(b * 255)}%`,\n a: this._color.alpha,\n };\n }\n return {\n r: Math.round(r * 255),\n g: Math.round(g * 255),\n b: Math.round(b * 255),\n a: this._color.alpha,\n };\n }\n }\n return this._color;\n }\n\n protected host: ReactiveElement;\n\n /**\n * Gets the hue value of the current color in HSL format.\n *\n * @returns {number} The hue value as a number.\n */\n get hue(): number {\n return Number((this._color.to('hsl') as Color).hsl.h);\n }\n\n /**\n * Sets the hue value of the color and requests an update from the host.\n *\n * @param hue - The hue value to set, represented as a number.\n */\n set hue(hue: number) {\n this._color.set('h', hue);\n this.host.requestUpdate();\n }\n\n /**\n * Creates an instance of ColorController.\n *\n * @param host - The ReactiveElement that this controller is associated with.\n * @param options - An object containing optional parameters.\n * @param options.manageAs - A string to manage the controller as a specific type.\n */\n constructor(\n host: ReactiveElement,\n {\n manageAs,\n }: {\n manageAs?: string;\n } = {}\n ) {\n this.host = host;\n this.manageAs = manageAs;\n }\n\n /**\n * Converts the current color to the specified format.\n *\n * @param format - The desired color format. It can be a string representing one of the valid formats\n * ('srgb', 'hsva', 'hsv', 'hsl', 'hsla') or a ColorSpace object.\n * @returns The color object in the specified format.\n * @throws Will throw an error if the provided format is not a valid string format.\n */\n getColor(format: string | ColorSpace): ColorObject {\n const validFormats = ['srgb', 'hsva', 'hsv', 'hsl', 'hsla'];\n if (typeof format === 'string' && !validFormats.includes(format)) {\n throw new Error('not a valid format');\n }\n\n return this._color.to(format);\n }\n\n /**\n * Converts the current color to an HSL string representation.\n *\n * @returns {string} The HSL string representation of the current color.\n */\n getHslString(): string {\n return this._color.to('hsl').toString();\n }\n\n /**\n * Saves the current color state by cloning the current color and storing it\n * as the previous color. This allows for the ability to revert to the previous\n * color state if needed.\n *\n * @returns {void}\n */\n savePreviousColor(): void {\n this._previousColor = this._color.clone();\n }\n\n /**\n * Restores the color to the previously saved color value.\n *\n * This method sets the current color (`_color`) to the previously stored color (`_previousColor`).\n */\n restorePreviousColor(): void {\n this._color = this._previousColor;\n }\n}\n"],
|
|
5
|
+
"mappings": "aAaA,OAAOA,MAAW,aAgFX,aAAM,eAAgB,CAmiBzB,YACIC,EACA,CACI,SAAAC,CACJ,EAEI,CAAC,EACP,CAzWF,KAAQ,OAAgB,IAAIF,EAAM,MAA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ACzB,EAAG,GAAG,KAAK,MAAMC,EAAI,GAAG,CAAC,IACzB,EAAG,GAAG,KAAK,MAAMC,EAAI,GAAG,CAAC,IACzB,EAAG,KAAK,OAAO,KACnB,EAEG,CACH,EAAG,KAAK,MAAMF,EAAI,GAAG,EACrB,EAAG,KAAK,MAAMC,EAAI,GAAG,EACrB,EAAG,KAAK,MAAMC,EAAI,GAAG,EACrB,EAAG,KAAK,OAAO,KACnB,CACJ,CACJ,CACA,OAAO,KAAK,MAChB,CASA,IAAI,KAAc,CACd,OAAO,OAAQ,KAAK,OAAO,GAAG,KAAK,EAAY,IAAI,CAAC,CACxD,CAOA,IAAI,IAAImC,EAAa,CACjB,KAAK,OAAO,IAAI,IAAKA,CAAG,EACxB,KAAK,KAAK,cAAc,CAC5B,CA6BA,SAASC,EAA0C,CAE/C,GAAI,OAAOA,GAAW,UAAY,CADb,CAAC,OAAQ,OAAQ,MAAO,MAAO,MAAM,EACV,SAASA,CAAM,EAC3D,MAAM,IAAI,MAAM,oBAAoB,EAGxC,OAAO,KAAK,OAAO,GAAGA,CAAM,CAChC,CAOA,cAAuB,CACnB,OAAO,KAAK,OAAO,GAAG,KAAK,EAAE,SAAS,CAC1C,CASA,mBAA0B,CACtB,KAAK,eAAiB,KAAK,OAAO,MAAM,CAC5C,CAOA,sBAA6B,CACzB,KAAK,OAAS,KAAK,cACvB,CACJ",
|
|
6
|
+
"names": ["Color", "host", "manageAs", "color", "_a", "_b", "_c", "_d", "result", "rgbRegExpArray", "hslRegExpArray", "hsvRegExpArray", "hexRegExpArray", "rgbaMatch", "regex", "hslaMatch", "hsvaMatch", "hexMatch", "r", "g", "b", "a", "element", "alpha", "processValue", "value", "numericR", "numericG", "numericB", "h", "s", "l", "values", "numericH", "numericS", "numericL", "numericA", "v", "numericV", "hex", "processHex", "colorOrigin", "newColor", "colorValidationResult", "coord1", "coord2", "coord3", "error", "lv", "spaceId", "hadAlpha", "rHex", "gHex", "bHex", "aHex", "hue", "format"]
|
|
7
|
+
}
|
package/src/FocusGroup.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ReactiveController, ReactiveElement } from 'lit';
|
|
2
2
|
type DirectionTypes = 'horizontal' | 'vertical' | 'both' | 'grid';
|
|
3
3
|
export type FocusGroupConfig<T> = {
|
|
4
|
+
hostDelegatesFocus?: boolean;
|
|
4
5
|
focusInIndex?: (_elements: T[]) => number;
|
|
5
6
|
direction?: DirectionTypes | (() => DirectionTypes);
|
|
6
7
|
elementEnterAction?: (el: T) => void;
|
|
@@ -18,6 +19,7 @@ export declare class FocusGroupController<T extends HTMLElement> implements Reac
|
|
|
18
19
|
get direction(): DirectionTypes;
|
|
19
20
|
_direction: () => DirectionTypes;
|
|
20
21
|
directionLength: number;
|
|
22
|
+
hostDelegatesFocus: boolean;
|
|
21
23
|
elementEnterAction: (_el: T) => void;
|
|
22
24
|
get elements(): T[];
|
|
23
25
|
private _elements;
|
|
@@ -33,9 +35,14 @@ export declare class FocusGroupController<T extends HTMLElement> implements Reac
|
|
|
33
35
|
_listenerScope: () => HTMLElement;
|
|
34
36
|
offset: number;
|
|
35
37
|
recentlyConnected: boolean;
|
|
36
|
-
constructor(host: ReactiveElement, { direction, elementEnterAction, elements, focusInIndex, isFocusableElement, listenerScope, }?: FocusGroupConfig<T>);
|
|
38
|
+
constructor(host: ReactiveElement, { hostDelegatesFocus, direction, elementEnterAction, elements, focusInIndex, isFocusableElement, listenerScope, }?: FocusGroupConfig<T>);
|
|
37
39
|
handleItemMutation(): void;
|
|
38
40
|
update({ elements }?: FocusGroupConfig<T>): void;
|
|
41
|
+
/**
|
|
42
|
+
* resets the focusedItem to initial item
|
|
43
|
+
*/
|
|
44
|
+
reset(): void;
|
|
45
|
+
focusOnItem(item?: T, options?: FocusOptions): void;
|
|
39
46
|
focus(options?: FocusOptions): void;
|
|
40
47
|
clearElementCache(offset?: number): void;
|
|
41
48
|
setCurrentIndexCircularly(diff: number): void;
|
|
@@ -49,7 +56,7 @@ export declare class FocusGroupController<T extends HTMLElement> implements Reac
|
|
|
49
56
|
*/
|
|
50
57
|
handleClick: () => void;
|
|
51
58
|
handleFocusout: (event: FocusEvent) => void;
|
|
52
|
-
|
|
59
|
+
acceptsEventKey(key: string): boolean;
|
|
53
60
|
handleKeydown: (event: KeyboardEvent) => void;
|
|
54
61
|
manage(): void;
|
|
55
62
|
unmanage(): void;
|
package/src/FocusGroup.dev.js
CHANGED
|
@@ -9,6 +9,7 @@ function ensureMethod(value, type, fallback) {
|
|
|
9
9
|
}
|
|
10
10
|
export class FocusGroupController {
|
|
11
11
|
constructor(host, {
|
|
12
|
+
hostDelegatesFocus,
|
|
12
13
|
direction,
|
|
13
14
|
elementEnterAction,
|
|
14
15
|
elements,
|
|
@@ -20,6 +21,7 @@ export class FocusGroupController {
|
|
|
20
21
|
this.prevIndex = -1;
|
|
21
22
|
this._direction = () => "both";
|
|
22
23
|
this.directionLength = 5;
|
|
24
|
+
this.hostDelegatesFocus = false;
|
|
23
25
|
this.elementEnterAction = (_el) => {
|
|
24
26
|
return;
|
|
25
27
|
};
|
|
@@ -74,12 +76,12 @@ export class FocusGroupController {
|
|
|
74
76
|
}
|
|
75
77
|
};
|
|
76
78
|
this.handleKeydown = (event) => {
|
|
77
|
-
if (!this.
|
|
79
|
+
if (!this.acceptsEventKey(event.key) || event.defaultPrevented) {
|
|
78
80
|
return;
|
|
79
81
|
}
|
|
80
82
|
let diff = 0;
|
|
81
83
|
this.prevIndex = this.currentIndex;
|
|
82
|
-
switch (event.
|
|
84
|
+
switch (event.key) {
|
|
83
85
|
case "ArrowRight":
|
|
84
86
|
diff += 1;
|
|
85
87
|
break;
|
|
@@ -115,6 +117,7 @@ export class FocusGroupController {
|
|
|
115
117
|
this.mutationObserver = new MutationObserver(() => {
|
|
116
118
|
this.handleItemMutation();
|
|
117
119
|
});
|
|
120
|
+
this.hostDelegatesFocus = hostDelegatesFocus || false;
|
|
118
121
|
this.host = host;
|
|
119
122
|
this.host.addController(this);
|
|
120
123
|
this._elements = elements;
|
|
@@ -194,19 +197,54 @@ export class FocusGroupController {
|
|
|
194
197
|
this.clearElementCache();
|
|
195
198
|
this.manage();
|
|
196
199
|
}
|
|
197
|
-
|
|
200
|
+
/**
|
|
201
|
+
* resets the focusedItem to initial item
|
|
202
|
+
*/
|
|
203
|
+
reset() {
|
|
198
204
|
var _a;
|
|
199
205
|
const elements = this.elements;
|
|
200
206
|
if (!elements.length) return;
|
|
207
|
+
this.setCurrentIndexCircularly(this.focusInIndex - this.currentIndex);
|
|
201
208
|
let focusElement = elements[this.currentIndex];
|
|
209
|
+
if (this.currentIndex < 0) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
202
212
|
if (!focusElement || !this.isFocusableElement(focusElement)) {
|
|
203
213
|
this.setCurrentIndexCircularly(1);
|
|
204
214
|
focusElement = elements[this.currentIndex];
|
|
205
215
|
}
|
|
206
216
|
if (focusElement && this.isFocusableElement(focusElement)) {
|
|
207
217
|
(_a = elements[this.prevIndex]) == null ? void 0 : _a.setAttribute("tabindex", "-1");
|
|
218
|
+
focusElement.setAttribute("tabindex", "0");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
focusOnItem(item, options) {
|
|
222
|
+
var _a;
|
|
223
|
+
if (item && this.isFocusableElement(item) && this.elements.indexOf(item)) {
|
|
224
|
+
const diff = this.elements.indexOf(item) - this.currentIndex;
|
|
225
|
+
this.setCurrentIndexCircularly(diff);
|
|
226
|
+
(_a = this.elements[this.prevIndex]) == null ? void 0 : _a.setAttribute("tabindex", "-1");
|
|
227
|
+
}
|
|
228
|
+
this.focus(options);
|
|
229
|
+
}
|
|
230
|
+
focus(options) {
|
|
231
|
+
var _a;
|
|
232
|
+
const elements = this.elements;
|
|
233
|
+
if (!elements.length) return;
|
|
234
|
+
let focusElement = elements[this.currentIndex];
|
|
235
|
+
if (!focusElement || !this.isFocusableElement(focusElement)) {
|
|
236
|
+
this.setCurrentIndexCircularly(1);
|
|
237
|
+
focusElement = elements[this.currentIndex];
|
|
238
|
+
}
|
|
239
|
+
if (focusElement && this.isFocusableElement(focusElement)) {
|
|
240
|
+
if (!this.hostDelegatesFocus || elements[this.prevIndex] !== focusElement) {
|
|
241
|
+
(_a = elements[this.prevIndex]) == null ? void 0 : _a.setAttribute("tabindex", "-1");
|
|
242
|
+
}
|
|
208
243
|
focusElement.tabIndex = 0;
|
|
209
244
|
focusElement.focus(options);
|
|
245
|
+
if (this.hostDelegatesFocus && !this.focused) {
|
|
246
|
+
this.hostContainsFocus();
|
|
247
|
+
}
|
|
210
248
|
}
|
|
211
249
|
}
|
|
212
250
|
clearElementCache(offset = 0) {
|
|
@@ -256,18 +294,18 @@ export class FocusGroupController {
|
|
|
256
294
|
);
|
|
257
295
|
return !(isRelatedTargetAnElement || isRelatedTargetContainedWithinElements);
|
|
258
296
|
}
|
|
259
|
-
|
|
260
|
-
if (
|
|
297
|
+
acceptsEventKey(key) {
|
|
298
|
+
if (key === "End" || key === "Home") {
|
|
261
299
|
return true;
|
|
262
300
|
}
|
|
263
301
|
switch (this.direction) {
|
|
264
302
|
case "horizontal":
|
|
265
|
-
return
|
|
303
|
+
return key === "ArrowLeft" || key === "ArrowRight";
|
|
266
304
|
case "vertical":
|
|
267
|
-
return
|
|
305
|
+
return key === "ArrowUp" || key === "ArrowDown";
|
|
268
306
|
case "both":
|
|
269
307
|
case "grid":
|
|
270
|
-
return
|
|
308
|
+
return key.startsWith("Arrow");
|
|
271
309
|
}
|
|
272
310
|
}
|
|
273
311
|
manage() {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["FocusGroup.ts"],
|
|
4
|
-
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport type { ReactiveController, ReactiveElement } from 'lit';\n\ntype DirectionTypes = 'horizontal' | 'vertical' | 'both' | 'grid';\nexport type FocusGroupConfig<T> = {\n focusInIndex?: (_elements: T[]) => number;\n direction?: DirectionTypes | (() => DirectionTypes);\n elementEnterAction?: (el: T) => void;\n elements: () => T[];\n isFocusableElement?: (el: T) => boolean;\n listenerScope?: HTMLElement | (() => HTMLElement);\n};\n\nfunction ensureMethod<T, RT>(\n value: T | RT | undefined,\n type: string,\n fallback: T\n): T {\n if (typeof value === type) {\n return (() => value) as T;\n } else if (typeof value === 'function') {\n return value as T;\n }\n return fallback;\n}\n\nexport class FocusGroupController<T extends HTMLElement>\n implements ReactiveController\n{\n protected cachedElements?: T[];\n private mutationObserver: MutationObserver;\n\n get currentIndex(): number {\n if (this._currentIndex === -1) {\n this._currentIndex = this.focusInIndex;\n }\n return this._currentIndex - this.offset;\n }\n\n set currentIndex(currentIndex) {\n this._currentIndex = currentIndex + this.offset;\n }\n\n private _currentIndex = -1;\n\n private prevIndex = -1;\n\n get direction(): DirectionTypes {\n return this._direction();\n }\n\n _direction = (): DirectionTypes => 'both';\n\n public directionLength = 5;\n\n elementEnterAction = (_el: T): void => {\n return;\n };\n\n get elements(): T[] {\n if (!this.cachedElements) {\n this.cachedElements = this._elements();\n }\n return this.cachedElements;\n }\n\n private _elements!: () => T[];\n\n protected set focused(focused: boolean) {\n /* c8 ignore next 1 */\n if (focused === this.focused) return;\n this._focused = focused;\n }\n\n protected get focused(): boolean {\n return this._focused;\n }\n\n private _focused = false;\n\n get focusInElement(): T {\n return this.elements[this.focusInIndex];\n }\n\n get focusInIndex(): number {\n return this._focusInIndex(this.elements);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _focusInIndex = (_elements: T[]): number => 0;\n\n host: ReactiveElement;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isFocusableElement = (_el: T): boolean => true;\n\n isEventWithinListenerScope(event: Event): boolean {\n if (this._listenerScope() === this.host) return true;\n return event.composedPath().includes(this._listenerScope());\n }\n\n _listenerScope = (): HTMLElement => this.host;\n\n // When elements are virtualized, the delta between the first element\n // and the first rendered element.\n offset = 0;\n\n recentlyConnected = false;\n\n constructor(\n host: ReactiveElement,\n {\n direction,\n elementEnterAction,\n elements,\n focusInIndex,\n isFocusableElement,\n listenerScope,\n }: FocusGroupConfig<T> = { elements: () => [] }\n ) {\n this.mutationObserver = new MutationObserver(() => {\n this.handleItemMutation();\n });\n this.host = host;\n this.host.addController(this);\n this._elements = elements;\n this.isFocusableElement = isFocusableElement || this.isFocusableElement;\n this._direction = ensureMethod<() => DirectionTypes, DirectionTypes>(\n direction,\n 'string',\n this._direction\n );\n this.elementEnterAction = elementEnterAction || this.elementEnterAction;\n this._focusInIndex = ensureMethod<(_elements: T[]) => number, number>(\n focusInIndex,\n 'number',\n this._focusInIndex\n );\n this._listenerScope = ensureMethod<() => HTMLElement, HTMLElement>(\n listenerScope,\n 'object',\n this._listenerScope\n );\n }\n /* In handleItemMutation() method the first if condition is checking if the element is not focused or if the element's children's length is not decreasing then it means no element has been deleted and we must return.\n Then we are checking if the deleted element was the focused one before the deletion if so then we need to proceed else we casn return;\n */\n handleItemMutation(): void {\n if (\n this._currentIndex == -1 ||\n this.elements.length <= this._elements().length\n )\n return;\n const focusedElement = this.elements[this.currentIndex];\n this.clearElementCache();\n if (this.elements.includes(focusedElement)) return;\n const moveToNextElement = this.currentIndex !== this.elements.length;\n const diff = moveToNextElement ? 1 : -1;\n if (moveToNextElement) {\n this.setCurrentIndexCircularly(-1);\n }\n this.setCurrentIndexCircularly(diff);\n this.focus();\n }\n\n update({ elements }: FocusGroupConfig<T> = { elements: () => [] }): void {\n this.unmanage();\n this._elements = elements;\n this.clearElementCache();\n this.manage();\n }\n\n focus(options?: FocusOptions): void {\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.tabIndex = 0;\n focusElement.focus(options);\n }\n }\n\n clearElementCache(offset = 0): void {\n this.mutationObserver.disconnect();\n delete this.cachedElements;\n this.offset = offset;\n requestAnimationFrame(() => {\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n });\n }\n\n setCurrentIndexCircularly(diff: number): void {\n const { length } = this.elements;\n let steps = length;\n this.prevIndex = this.currentIndex;\n // start at a possibly not 0 index\n let nextIndex = (length + this.currentIndex + diff) % length;\n while (\n // don't cycle the elements more than once\n steps &&\n this.elements[nextIndex] &&\n !this.isFocusableElement(this.elements[nextIndex])\n ) {\n nextIndex = (length + nextIndex + diff) % length;\n steps -= 1;\n }\n this.currentIndex = nextIndex;\n }\n\n hostContainsFocus(): void {\n this.host.addEventListener('focusout', this.handleFocusout);\n this.host.addEventListener('keydown', this.handleKeydown);\n this.focused = true;\n }\n\n hostNoLongerContainsFocus(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.focused = false;\n }\n\n isRelatedTargetOrContainAnElement(event: FocusEvent): boolean {\n const relatedTarget = event.relatedTarget as null | Element;\n\n const isRelatedTargetAnElement = this.elements.includes(\n relatedTarget as T\n );\n const isRelatedTargetContainedWithinElements = this.elements.some(\n (el) => el.contains(relatedTarget)\n );\n return !(\n isRelatedTargetAnElement || isRelatedTargetContainedWithinElements\n );\n }\n\n handleFocusin = (event: FocusEvent): void => {\n if (!this.isEventWithinListenerScope(event)) return;\n\n const path = event.composedPath() as T[];\n let targetIndex = -1;\n path.find((el) => {\n targetIndex = this.elements.indexOf(el);\n return targetIndex !== -1;\n });\n this.prevIndex = this.currentIndex;\n this.currentIndex = targetIndex > -1 ? targetIndex : this.currentIndex;\n\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostContainsFocus();\n }\n };\n\n /**\n * handleClick - Finds the element that was clicked and sets the tabindex to 0\n * @returns void\n */\n handleClick = (): void => {\n // Manually set the tabindex to 0 for the current element on receiving focus (from keyboard or mouse)\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (this.currentIndex < 0) {\n return;\n }\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.setAttribute('tabindex', '0');\n }\n };\n\n handleFocusout = (event: FocusEvent): void => {\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostNoLongerContainsFocus();\n }\n };\n\n acceptsEventCode(code: string): boolean {\n if (code === 'End' || code === 'Home') {\n return true;\n }\n switch (this.direction) {\n case 'horizontal':\n return code === 'ArrowLeft' || code === 'ArrowRight';\n case 'vertical':\n return code === 'ArrowUp' || code === 'ArrowDown';\n case 'both':\n case 'grid':\n return code.startsWith('Arrow');\n }\n }\n\n handleKeydown = (event: KeyboardEvent): void => {\n if (!this.acceptsEventCode(event.code) || event.defaultPrevented) {\n return;\n }\n let diff = 0;\n this.prevIndex = this.currentIndex;\n switch (event.code) {\n case 'ArrowRight':\n diff += 1;\n break;\n case 'ArrowDown':\n diff += this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'ArrowLeft':\n diff -= 1;\n break;\n case 'ArrowUp':\n diff -= this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'End':\n this.currentIndex = 0;\n diff -= 1;\n break;\n case 'Home':\n this.currentIndex = this.elements.length - 1;\n diff += 1;\n break;\n }\n event.preventDefault();\n if (this.direction === 'grid' && this.currentIndex + diff < 0) {\n this.currentIndex = 0;\n } else if (\n this.direction === 'grid' &&\n this.currentIndex + diff > this.elements.length - 1\n ) {\n this.currentIndex = this.elements.length - 1;\n } else {\n this.setCurrentIndexCircularly(diff);\n }\n // To allow the `focusInIndex` to be calculated with the \"after\" state of the keyboard interaction\n // do `elementEnterAction` _before_ focusing the next element.\n this.elementEnterAction(this.elements[this.currentIndex]);\n this.focus();\n };\n\n manage(): void {\n this.addEventListeners();\n }\n\n unmanage(): void {\n this.removeEventListeners();\n }\n\n addEventListeners(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.addEventListener('click', this.handleClick);\n }\n\n removeEventListeners(): void {\n this.host.removeEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.host.removeEventListener('click', this.handleClick);\n }\n\n hostConnected(): void {\n this.recentlyConnected = true;\n this.addEventListeners();\n }\n\n hostDisconnected(): void {\n this.mutationObserver.disconnect();\n this.removeEventListeners();\n }\n\n hostUpdated(): void {\n if (this.recentlyConnected) {\n this.recentlyConnected = false;\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n }\n }\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport type { ReactiveController, ReactiveElement } from 'lit';\n\ntype DirectionTypes = 'horizontal' | 'vertical' | 'both' | 'grid';\nexport type FocusGroupConfig<T> = {\n hostDelegatesFocus?: boolean;\n focusInIndex?: (_elements: T[]) => number;\n direction?: DirectionTypes | (() => DirectionTypes);\n elementEnterAction?: (el: T) => void;\n elements: () => T[];\n isFocusableElement?: (el: T) => boolean;\n listenerScope?: HTMLElement | (() => HTMLElement);\n};\n\nfunction ensureMethod<T, RT>(\n value: T | RT | undefined,\n type: string,\n fallback: T\n): T {\n if (typeof value === type) {\n return (() => value) as T;\n } else if (typeof value === 'function') {\n return value as T;\n }\n return fallback;\n}\n\nexport class FocusGroupController<T extends HTMLElement>\n implements ReactiveController\n{\n protected cachedElements?: T[];\n private mutationObserver: MutationObserver;\n\n get currentIndex(): number {\n if (this._currentIndex === -1) {\n this._currentIndex = this.focusInIndex;\n }\n return this._currentIndex - this.offset;\n }\n\n set currentIndex(currentIndex) {\n this._currentIndex = currentIndex + this.offset;\n }\n\n private _currentIndex = -1;\n\n private prevIndex = -1;\n\n get direction(): DirectionTypes {\n return this._direction();\n }\n\n _direction = (): DirectionTypes => 'both';\n\n public directionLength = 5;\n\n public hostDelegatesFocus = false;\n\n elementEnterAction = (_el: T): void => {\n return;\n };\n\n get elements(): T[] {\n if (!this.cachedElements) {\n this.cachedElements = this._elements();\n }\n return this.cachedElements;\n }\n\n private _elements!: () => T[];\n\n protected set focused(focused: boolean) {\n /* c8 ignore next 1 */\n if (focused === this.focused) return;\n this._focused = focused;\n }\n\n protected get focused(): boolean {\n return this._focused;\n }\n\n private _focused = false;\n\n get focusInElement(): T {\n return this.elements[this.focusInIndex];\n }\n\n get focusInIndex(): number {\n return this._focusInIndex(this.elements);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _focusInIndex = (_elements: T[]): number => 0;\n\n host: ReactiveElement;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isFocusableElement = (_el: T): boolean => true;\n\n isEventWithinListenerScope(event: Event): boolean {\n if (this._listenerScope() === this.host) return true;\n return event.composedPath().includes(this._listenerScope());\n }\n\n _listenerScope = (): HTMLElement => this.host;\n\n // When elements are virtualized, the delta between the first element\n // and the first rendered element.\n offset = 0;\n\n recentlyConnected = false;\n\n constructor(\n host: ReactiveElement,\n {\n hostDelegatesFocus,\n direction,\n elementEnterAction,\n elements,\n focusInIndex,\n isFocusableElement,\n listenerScope,\n }: FocusGroupConfig<T> = { elements: () => [] }\n ) {\n this.mutationObserver = new MutationObserver(() => {\n this.handleItemMutation();\n });\n this.hostDelegatesFocus = hostDelegatesFocus || false;\n this.host = host;\n this.host.addController(this);\n this._elements = elements;\n this.isFocusableElement = isFocusableElement || this.isFocusableElement;\n this._direction = ensureMethod<() => DirectionTypes, DirectionTypes>(\n direction,\n 'string',\n this._direction\n );\n this.elementEnterAction = elementEnterAction || this.elementEnterAction;\n this._focusInIndex = ensureMethod<(_elements: T[]) => number, number>(\n focusInIndex,\n 'number',\n this._focusInIndex\n );\n this._listenerScope = ensureMethod<() => HTMLElement, HTMLElement>(\n listenerScope,\n 'object',\n this._listenerScope\n );\n }\n /* In handleItemMutation() method the first if condition is checking if the element is not focused or if the element's children's length is not decreasing then it means no element has been deleted and we must return.\n Then we are checking if the deleted element was the focused one before the deletion if so then we need to proceed else we casn return;\n */\n handleItemMutation(): void {\n if (\n this._currentIndex == -1 ||\n this.elements.length <= this._elements().length\n )\n return;\n const focusedElement = this.elements[this.currentIndex];\n this.clearElementCache();\n if (this.elements.includes(focusedElement)) return;\n const moveToNextElement = this.currentIndex !== this.elements.length;\n const diff = moveToNextElement ? 1 : -1;\n if (moveToNextElement) {\n this.setCurrentIndexCircularly(-1);\n }\n this.setCurrentIndexCircularly(diff);\n this.focus();\n }\n\n update({ elements }: FocusGroupConfig<T> = { elements: () => [] }): void {\n this.unmanage();\n this._elements = elements;\n this.clearElementCache();\n this.manage();\n }\n\n /**\n * resets the focusedItem to initial item\n */\n reset(): void {\n const elements = this.elements;\n if (!elements.length) return;\n this.setCurrentIndexCircularly(this.focusInIndex - this.currentIndex);\n let focusElement = elements[this.currentIndex];\n if (this.currentIndex < 0) {\n return;\n }\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.setAttribute('tabindex', '0');\n }\n }\n\n focusOnItem(item?: T, options?: FocusOptions): void {\n if (\n item &&\n this.isFocusableElement(item) &&\n this.elements.indexOf(item)\n ) {\n const diff = this.elements.indexOf(item) - this.currentIndex;\n this.setCurrentIndexCircularly(diff);\n this.elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n }\n this.focus(options);\n }\n\n focus(options?: FocusOptions): void {\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n if (\n !this.hostDelegatesFocus ||\n elements[this.prevIndex] !== focusElement\n ) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n }\n focusElement.tabIndex = 0;\n focusElement.focus(options);\n if (this.hostDelegatesFocus && !this.focused) {\n this.hostContainsFocus();\n }\n }\n }\n\n clearElementCache(offset = 0): void {\n this.mutationObserver.disconnect();\n delete this.cachedElements;\n this.offset = offset;\n requestAnimationFrame(() => {\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n });\n }\n\n setCurrentIndexCircularly(diff: number): void {\n const { length } = this.elements;\n let steps = length;\n this.prevIndex = this.currentIndex;\n // start at a possibly not 0 index\n let nextIndex = (length + this.currentIndex + diff) % length;\n while (\n // don't cycle the elements more than once\n steps &&\n this.elements[nextIndex] &&\n !this.isFocusableElement(this.elements[nextIndex])\n ) {\n nextIndex = (length + nextIndex + diff) % length;\n steps -= 1;\n }\n this.currentIndex = nextIndex;\n }\n\n hostContainsFocus(): void {\n this.host.addEventListener('focusout', this.handleFocusout);\n this.host.addEventListener('keydown', this.handleKeydown);\n this.focused = true;\n }\n\n hostNoLongerContainsFocus(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.focused = false;\n }\n\n isRelatedTargetOrContainAnElement(event: FocusEvent): boolean {\n const relatedTarget = event.relatedTarget as null | Element;\n\n const isRelatedTargetAnElement = this.elements.includes(\n relatedTarget as T\n );\n const isRelatedTargetContainedWithinElements = this.elements.some(\n (el) => el.contains(relatedTarget)\n );\n return !(\n isRelatedTargetAnElement || isRelatedTargetContainedWithinElements\n );\n }\n\n handleFocusin = (event: FocusEvent): void => {\n if (!this.isEventWithinListenerScope(event)) return;\n\n const path = event.composedPath() as T[];\n let targetIndex = -1;\n path.find((el) => {\n targetIndex = this.elements.indexOf(el);\n return targetIndex !== -1;\n });\n this.prevIndex = this.currentIndex;\n this.currentIndex = targetIndex > -1 ? targetIndex : this.currentIndex;\n\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostContainsFocus();\n }\n };\n\n /**\n * handleClick - Finds the element that was clicked and sets the tabindex to 0\n * @returns void\n */\n handleClick = (): void => {\n // Manually set the tabindex to 0 for the current element on receiving focus (from keyboard or mouse)\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (this.currentIndex < 0) {\n return;\n }\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.setAttribute('tabindex', '0');\n }\n };\n\n handleFocusout = (event: FocusEvent): void => {\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostNoLongerContainsFocus();\n }\n };\n\n acceptsEventKey(key: string): boolean {\n if (key === 'End' || key === 'Home') {\n return true;\n }\n switch (this.direction) {\n case 'horizontal':\n return key === 'ArrowLeft' || key === 'ArrowRight';\n case 'vertical':\n return key === 'ArrowUp' || key === 'ArrowDown';\n case 'both':\n case 'grid':\n return key.startsWith('Arrow');\n }\n }\n\n handleKeydown = (event: KeyboardEvent): void => {\n if (!this.acceptsEventKey(event.key) || event.defaultPrevented) {\n return;\n }\n let diff = 0;\n this.prevIndex = this.currentIndex;\n switch (event.key) {\n case 'ArrowRight':\n diff += 1;\n break;\n case 'ArrowDown':\n diff += this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'ArrowLeft':\n diff -= 1;\n break;\n case 'ArrowUp':\n diff -= this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'End':\n this.currentIndex = 0;\n diff -= 1;\n break;\n case 'Home':\n this.currentIndex = this.elements.length - 1;\n diff += 1;\n break;\n }\n event.preventDefault();\n if (this.direction === 'grid' && this.currentIndex + diff < 0) {\n this.currentIndex = 0;\n } else if (\n this.direction === 'grid' &&\n this.currentIndex + diff > this.elements.length - 1\n ) {\n this.currentIndex = this.elements.length - 1;\n } else {\n this.setCurrentIndexCircularly(diff);\n }\n // To allow the `focusInIndex` to be calculated with the \"after\" state of the keyboard interaction\n // do `elementEnterAction` _before_ focusing the next element.\n this.elementEnterAction(this.elements[this.currentIndex]);\n this.focus();\n };\n\n manage(): void {\n this.addEventListeners();\n }\n\n unmanage(): void {\n this.removeEventListeners();\n }\n\n addEventListeners(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.addEventListener('click', this.handleClick);\n }\n\n removeEventListeners(): void {\n this.host.removeEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.host.removeEventListener('click', this.handleClick);\n }\n\n hostConnected(): void {\n this.recentlyConnected = true;\n this.addEventListeners();\n }\n\n hostDisconnected(): void {\n this.mutationObserver.disconnect();\n this.removeEventListeners();\n }\n\n hostUpdated(): void {\n if (this.recentlyConnected) {\n this.recentlyConnected = false;\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n }\n }\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A,EAC9B;AAAA,EAEA,oBAA0B;AACtB,SAAK,KAAK,iBAAiB,WAAW,KAAK,aAAa;AACxD,SAAK,KAAK,iBAAiB,SAAS,KAAK,WAAW;AAAA,EACxD;AAAA,EAEA,uBAA6B;AACzB,SAAK,KAAK,oBAAoB,WAAW,KAAK,aAAa;AAC3D,SAAK,KAAK,oBAAoB,YAAY,KAAK,cAAc;AAC7D,SAAK,KAAK,oBAAoB,WAAW,KAAK,aAAa;AAC3D,SAAK,KAAK,oBAAoB,SAAS,KAAK,WAAW;AAAA,EAC3D;AAAA,EAEA,gBAAsB;AAClB,SAAK,oBAAoB;AACzB,SAAK,kBAAkB;AAAA,EAC3B;AAAA,EAEA,mBAAyB;AACrB,SAAK,iBAAiB,WAAW;AACjC,SAAK,qBAAqB;AAAA,EAC9B;AAAA,EAEA,cAAoB;AAChB,QAAI,KAAK,mBAAmB;AACxB,WAAK,oBAAoB;AACzB,WAAK,SAAS,QAAQ,CAAC,YAAY;AAC/B,aAAK,iBAAiB,QAAQ,SAAS;AAAA,UACnC,YAAY;AAAA,QAChB,CAAC;AAAA,MACL,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/src/FocusGroup.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";function o(i,e,t){return typeof i===e?()=>i:typeof i=="function"?i:t}export class FocusGroupController{constructor(e,{
|
|
1
|
+
"use strict";function o(i,e,t){return typeof i===e?()=>i:typeof i=="function"?i:t}export class FocusGroupController{constructor(e,{hostDelegatesFocus:t,direction:n,elementEnterAction:s,elements:r,focusInIndex:h,isFocusableElement:c,listenerScope:l}={elements:()=>[]}){this._currentIndex=-1;this.prevIndex=-1;this._direction=()=>"both";this.directionLength=5;this.hostDelegatesFocus=!1;this.elementEnterAction=e=>{};this._focused=!1;this._focusInIndex=e=>0;this.isFocusableElement=e=>!0;this._listenerScope=()=>this.host;this.offset=0;this.recentlyConnected=!1;this.handleFocusin=e=>{if(!this.isEventWithinListenerScope(e))return;const t=e.composedPath();let n=-1;t.find(s=>(n=this.elements.indexOf(s),n!==-1)),this.prevIndex=this.currentIndex,this.currentIndex=n>-1?n:this.currentIndex,this.isRelatedTargetOrContainAnElement(e)&&this.hostContainsFocus()};this.handleClick=()=>{var n;const e=this.elements;if(!e.length)return;let t=e[this.currentIndex];this.currentIndex<0||((!t||!this.isFocusableElement(t))&&(this.setCurrentIndexCircularly(1),t=e[this.currentIndex]),t&&this.isFocusableElement(t)&&((n=e[this.prevIndex])==null||n.setAttribute("tabindex","-1"),t.setAttribute("tabindex","0")))};this.handleFocusout=e=>{this.isRelatedTargetOrContainAnElement(e)&&this.hostNoLongerContainsFocus()};this.handleKeydown=e=>{if(!this.acceptsEventKey(e.key)||e.defaultPrevented)return;let t=0;switch(this.prevIndex=this.currentIndex,e.key){case"ArrowRight":t+=1;break;case"ArrowDown":t+=this.direction==="grid"?this.directionLength:1;break;case"ArrowLeft":t-=1;break;case"ArrowUp":t-=this.direction==="grid"?this.directionLength:1;break;case"End":this.currentIndex=0,t-=1;break;case"Home":this.currentIndex=this.elements.length-1,t+=1;break}e.preventDefault(),this.direction==="grid"&&this.currentIndex+t<0?this.currentIndex=0:this.direction==="grid"&&this.currentIndex+t>this.elements.length-1?this.currentIndex=this.elements.length-1:this.setCurrentIndexCircularly(t),this.elementEnterAction(this.elements[this.currentIndex]),this.focus()};this.mutationObserver=new MutationObserver(()=>{this.handleItemMutation()}),this.hostDelegatesFocus=t||!1,this.host=e,this.host.addController(this),this._elements=r,this.isFocusableElement=c||this.isFocusableElement,this._direction=o(n,"string",this._direction),this.elementEnterAction=s||this.elementEnterAction,this._focusInIndex=o(h,"number",this._focusInIndex),this._listenerScope=o(l,"object",this._listenerScope)}get currentIndex(){return this._currentIndex===-1&&(this._currentIndex=this.focusInIndex),this._currentIndex-this.offset}set currentIndex(e){this._currentIndex=e+this.offset}get direction(){return this._direction()}get elements(){return this.cachedElements||(this.cachedElements=this._elements()),this.cachedElements}set focused(e){e!==this.focused&&(this._focused=e)}get focused(){return this._focused}get focusInElement(){return this.elements[this.focusInIndex]}get focusInIndex(){return this._focusInIndex(this.elements)}isEventWithinListenerScope(e){return this._listenerScope()===this.host?!0:e.composedPath().includes(this._listenerScope())}handleItemMutation(){if(this._currentIndex==-1||this.elements.length<=this._elements().length)return;const e=this.elements[this.currentIndex];if(this.clearElementCache(),this.elements.includes(e))return;const t=this.currentIndex!==this.elements.length,n=t?1:-1;t&&this.setCurrentIndexCircularly(-1),this.setCurrentIndexCircularly(n),this.focus()}update({elements:e}={elements:()=>[]}){this.unmanage(),this._elements=e,this.clearElementCache(),this.manage()}reset(){var n;const e=this.elements;if(!e.length)return;this.setCurrentIndexCircularly(this.focusInIndex-this.currentIndex);let t=e[this.currentIndex];this.currentIndex<0||((!t||!this.isFocusableElement(t))&&(this.setCurrentIndexCircularly(1),t=e[this.currentIndex]),t&&this.isFocusableElement(t)&&((n=e[this.prevIndex])==null||n.setAttribute("tabindex","-1"),t.setAttribute("tabindex","0")))}focusOnItem(e,t){var n;if(e&&this.isFocusableElement(e)&&this.elements.indexOf(e)){const s=this.elements.indexOf(e)-this.currentIndex;this.setCurrentIndexCircularly(s),(n=this.elements[this.prevIndex])==null||n.setAttribute("tabindex","-1")}this.focus(t)}focus(e){var s;const t=this.elements;if(!t.length)return;let n=t[this.currentIndex];(!n||!this.isFocusableElement(n))&&(this.setCurrentIndexCircularly(1),n=t[this.currentIndex]),n&&this.isFocusableElement(n)&&((!this.hostDelegatesFocus||t[this.prevIndex]!==n)&&((s=t[this.prevIndex])==null||s.setAttribute("tabindex","-1")),n.tabIndex=0,n.focus(e),this.hostDelegatesFocus&&!this.focused&&this.hostContainsFocus())}clearElementCache(e=0){this.mutationObserver.disconnect(),delete this.cachedElements,this.offset=e,requestAnimationFrame(()=>{this.elements.forEach(t=>{this.mutationObserver.observe(t,{attributes:!0})})})}setCurrentIndexCircularly(e){const{length:t}=this.elements;let n=t;this.prevIndex=this.currentIndex;let s=(t+this.currentIndex+e)%t;for(;n&&this.elements[s]&&!this.isFocusableElement(this.elements[s]);)s=(t+s+e)%t,n-=1;this.currentIndex=s}hostContainsFocus(){this.host.addEventListener("focusout",this.handleFocusout),this.host.addEventListener("keydown",this.handleKeydown),this.focused=!0}hostNoLongerContainsFocus(){this.host.addEventListener("focusin",this.handleFocusin),this.host.removeEventListener("focusout",this.handleFocusout),this.host.removeEventListener("keydown",this.handleKeydown),this.focused=!1}isRelatedTargetOrContainAnElement(e){const t=e.relatedTarget,n=this.elements.includes(t),s=this.elements.some(r=>r.contains(t));return!(n||s)}acceptsEventKey(e){if(e==="End"||e==="Home")return!0;switch(this.direction){case"horizontal":return e==="ArrowLeft"||e==="ArrowRight";case"vertical":return e==="ArrowUp"||e==="ArrowDown";case"both":case"grid":return e.startsWith("Arrow")}}manage(){this.addEventListeners()}unmanage(){this.removeEventListeners()}addEventListeners(){this.host.addEventListener("focusin",this.handleFocusin),this.host.addEventListener("click",this.handleClick)}removeEventListeners(){this.host.removeEventListener("focusin",this.handleFocusin),this.host.removeEventListener("focusout",this.handleFocusout),this.host.removeEventListener("keydown",this.handleKeydown),this.host.removeEventListener("click",this.handleClick)}hostConnected(){this.recentlyConnected=!0,this.addEventListeners()}hostDisconnected(){this.mutationObserver.disconnect(),this.removeEventListeners()}hostUpdated(){this.recentlyConnected&&(this.recentlyConnected=!1,this.elements.forEach(e=>{this.mutationObserver.observe(e,{attributes:!0})}))}}
|
|
2
2
|
//# sourceMappingURL=FocusGroup.js.map
|
package/src/FocusGroup.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["FocusGroup.ts"],
|
|
4
|
-
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport type { ReactiveController, ReactiveElement } from 'lit';\n\ntype DirectionTypes = 'horizontal' | 'vertical' | 'both' | 'grid';\nexport type FocusGroupConfig<T> = {\n focusInIndex?: (_elements: T[]) => number;\n direction?: DirectionTypes | (() => DirectionTypes);\n elementEnterAction?: (el: T) => void;\n elements: () => T[];\n isFocusableElement?: (el: T) => boolean;\n listenerScope?: HTMLElement | (() => HTMLElement);\n};\n\nfunction ensureMethod<T, RT>(\n value: T | RT | undefined,\n type: string,\n fallback: T\n): T {\n if (typeof value === type) {\n return (() => value) as T;\n } else if (typeof value === 'function') {\n return value as T;\n }\n return fallback;\n}\n\nexport class FocusGroupController<T extends HTMLElement>\n implements ReactiveController\n{\n protected cachedElements?: T[];\n private mutationObserver: MutationObserver;\n\n get currentIndex(): number {\n if (this._currentIndex === -1) {\n this._currentIndex = this.focusInIndex;\n }\n return this._currentIndex - this.offset;\n }\n\n set currentIndex(currentIndex) {\n this._currentIndex = currentIndex + this.offset;\n }\n\n private _currentIndex = -1;\n\n private prevIndex = -1;\n\n get direction(): DirectionTypes {\n return this._direction();\n }\n\n _direction = (): DirectionTypes => 'both';\n\n public directionLength = 5;\n\n elementEnterAction = (_el: T): void => {\n return;\n };\n\n get elements(): T[] {\n if (!this.cachedElements) {\n this.cachedElements = this._elements();\n }\n return this.cachedElements;\n }\n\n private _elements!: () => T[];\n\n protected set focused(focused: boolean) {\n /* c8 ignore next 1 */\n if (focused === this.focused) return;\n this._focused = focused;\n }\n\n protected get focused(): boolean {\n return this._focused;\n }\n\n private _focused = false;\n\n get focusInElement(): T {\n return this.elements[this.focusInIndex];\n }\n\n get focusInIndex(): number {\n return this._focusInIndex(this.elements);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _focusInIndex = (_elements: T[]): number => 0;\n\n host: ReactiveElement;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isFocusableElement = (_el: T): boolean => true;\n\n isEventWithinListenerScope(event: Event): boolean {\n if (this._listenerScope() === this.host) return true;\n return event.composedPath().includes(this._listenerScope());\n }\n\n _listenerScope = (): HTMLElement => this.host;\n\n // When elements are virtualized, the delta between the first element\n // and the first rendered element.\n offset = 0;\n\n recentlyConnected = false;\n\n constructor(\n host: ReactiveElement,\n {\n direction,\n elementEnterAction,\n elements,\n focusInIndex,\n isFocusableElement,\n listenerScope,\n }: FocusGroupConfig<T> = { elements: () => [] }\n ) {\n this.mutationObserver = new MutationObserver(() => {\n this.handleItemMutation();\n });\n this.host = host;\n this.host.addController(this);\n this._elements = elements;\n this.isFocusableElement = isFocusableElement || this.isFocusableElement;\n this._direction = ensureMethod<() => DirectionTypes, DirectionTypes>(\n direction,\n 'string',\n this._direction\n );\n this.elementEnterAction = elementEnterAction || this.elementEnterAction;\n this._focusInIndex = ensureMethod<(_elements: T[]) => number, number>(\n focusInIndex,\n 'number',\n this._focusInIndex\n );\n this._listenerScope = ensureMethod<() => HTMLElement, HTMLElement>(\n listenerScope,\n 'object',\n this._listenerScope\n );\n }\n /* In handleItemMutation() method the first if condition is checking if the element is not focused or if the element's children's length is not decreasing then it means no element has been deleted and we must return.\n Then we are checking if the deleted element was the focused one before the deletion if so then we need to proceed else we casn return;\n */\n handleItemMutation(): void {\n if (\n this._currentIndex == -1 ||\n this.elements.length <= this._elements().length\n )\n return;\n const focusedElement = this.elements[this.currentIndex];\n this.clearElementCache();\n if (this.elements.includes(focusedElement)) return;\n const moveToNextElement = this.currentIndex !== this.elements.length;\n const diff = moveToNextElement ? 1 : -1;\n if (moveToNextElement) {\n this.setCurrentIndexCircularly(-1);\n }\n this.setCurrentIndexCircularly(diff);\n this.focus();\n }\n\n update({ elements }: FocusGroupConfig<T> = { elements: () => [] }): void {\n this.unmanage();\n this._elements = elements;\n this.clearElementCache();\n this.manage();\n }\n\n focus(options?: FocusOptions): void {\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.tabIndex = 0;\n focusElement.focus(options);\n }\n }\n\n clearElementCache(offset = 0): void {\n this.mutationObserver.disconnect();\n delete this.cachedElements;\n this.offset = offset;\n requestAnimationFrame(() => {\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n });\n }\n\n setCurrentIndexCircularly(diff: number): void {\n const { length } = this.elements;\n let steps = length;\n this.prevIndex = this.currentIndex;\n // start at a possibly not 0 index\n let nextIndex = (length + this.currentIndex + diff) % length;\n while (\n // don't cycle the elements more than once\n steps &&\n this.elements[nextIndex] &&\n !this.isFocusableElement(this.elements[nextIndex])\n ) {\n nextIndex = (length + nextIndex + diff) % length;\n steps -= 1;\n }\n this.currentIndex = nextIndex;\n }\n\n hostContainsFocus(): void {\n this.host.addEventListener('focusout', this.handleFocusout);\n this.host.addEventListener('keydown', this.handleKeydown);\n this.focused = true;\n }\n\n hostNoLongerContainsFocus(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.focused = false;\n }\n\n isRelatedTargetOrContainAnElement(event: FocusEvent): boolean {\n const relatedTarget = event.relatedTarget as null | Element;\n\n const isRelatedTargetAnElement = this.elements.includes(\n relatedTarget as T\n );\n const isRelatedTargetContainedWithinElements = this.elements.some(\n (el) => el.contains(relatedTarget)\n );\n return !(\n isRelatedTargetAnElement || isRelatedTargetContainedWithinElements\n );\n }\n\n handleFocusin = (event: FocusEvent): void => {\n if (!this.isEventWithinListenerScope(event)) return;\n\n const path = event.composedPath() as T[];\n let targetIndex = -1;\n path.find((el) => {\n targetIndex = this.elements.indexOf(el);\n return targetIndex !== -1;\n });\n this.prevIndex = this.currentIndex;\n this.currentIndex = targetIndex > -1 ? targetIndex : this.currentIndex;\n\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostContainsFocus();\n }\n };\n\n /**\n * handleClick - Finds the element that was clicked and sets the tabindex to 0\n * @returns void\n */\n handleClick = (): void => {\n // Manually set the tabindex to 0 for the current element on receiving focus (from keyboard or mouse)\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (this.currentIndex < 0) {\n return;\n }\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.setAttribute('tabindex', '0');\n }\n };\n\n handleFocusout = (event: FocusEvent): void => {\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostNoLongerContainsFocus();\n }\n };\n\n acceptsEventCode(code: string): boolean {\n if (code === 'End' || code === 'Home') {\n return true;\n }\n switch (this.direction) {\n case 'horizontal':\n return code === 'ArrowLeft' || code === 'ArrowRight';\n case 'vertical':\n return code === 'ArrowUp' || code === 'ArrowDown';\n case 'both':\n case 'grid':\n return code.startsWith('Arrow');\n }\n }\n\n handleKeydown = (event: KeyboardEvent): void => {\n if (!this.acceptsEventCode(event.code) || event.defaultPrevented) {\n return;\n }\n let diff = 0;\n this.prevIndex = this.currentIndex;\n switch (event.code) {\n case 'ArrowRight':\n diff += 1;\n break;\n case 'ArrowDown':\n diff += this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'ArrowLeft':\n diff -= 1;\n break;\n case 'ArrowUp':\n diff -= this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'End':\n this.currentIndex = 0;\n diff -= 1;\n break;\n case 'Home':\n this.currentIndex = this.elements.length - 1;\n diff += 1;\n break;\n }\n event.preventDefault();\n if (this.direction === 'grid' && this.currentIndex + diff < 0) {\n this.currentIndex = 0;\n } else if (\n this.direction === 'grid' &&\n this.currentIndex + diff > this.elements.length - 1\n ) {\n this.currentIndex = this.elements.length - 1;\n } else {\n this.setCurrentIndexCircularly(diff);\n }\n // To allow the `focusInIndex` to be calculated with the \"after\" state of the keyboard interaction\n // do `elementEnterAction` _before_ focusing the next element.\n this.elementEnterAction(this.elements[this.currentIndex]);\n this.focus();\n };\n\n manage(): void {\n this.addEventListeners();\n }\n\n unmanage(): void {\n this.removeEventListeners();\n }\n\n addEventListeners(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.addEventListener('click', this.handleClick);\n }\n\n removeEventListeners(): void {\n this.host.removeEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.host.removeEventListener('click', this.handleClick);\n }\n\n hostConnected(): void {\n this.recentlyConnected = true;\n this.addEventListeners();\n }\n\n hostDisconnected(): void {\n this.mutationObserver.disconnect();\n this.removeEventListeners();\n }\n\n hostUpdated(): void {\n if (this.recentlyConnected) {\n this.recentlyConnected = false;\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["ensureMethod", "value", "type", "fallback", "host", "direction", "elementEnterAction", "elements", "focusInIndex", "isFocusableElement", "listenerScope", "_el", "_elements", "event", "path", "targetIndex", "el", "_a", "focusElement", "diff", "currentIndex", "focused", "focusedElement", "moveToNextElement", "options", "offset", "element", "length", "steps", "nextIndex", "relatedTarget", "isRelatedTargetAnElement", "isRelatedTargetContainedWithinElements", "
|
|
4
|
+
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport type { ReactiveController, ReactiveElement } from 'lit';\n\ntype DirectionTypes = 'horizontal' | 'vertical' | 'both' | 'grid';\nexport type FocusGroupConfig<T> = {\n hostDelegatesFocus?: boolean;\n focusInIndex?: (_elements: T[]) => number;\n direction?: DirectionTypes | (() => DirectionTypes);\n elementEnterAction?: (el: T) => void;\n elements: () => T[];\n isFocusableElement?: (el: T) => boolean;\n listenerScope?: HTMLElement | (() => HTMLElement);\n};\n\nfunction ensureMethod<T, RT>(\n value: T | RT | undefined,\n type: string,\n fallback: T\n): T {\n if (typeof value === type) {\n return (() => value) as T;\n } else if (typeof value === 'function') {\n return value as T;\n }\n return fallback;\n}\n\nexport class FocusGroupController<T extends HTMLElement>\n implements ReactiveController\n{\n protected cachedElements?: T[];\n private mutationObserver: MutationObserver;\n\n get currentIndex(): number {\n if (this._currentIndex === -1) {\n this._currentIndex = this.focusInIndex;\n }\n return this._currentIndex - this.offset;\n }\n\n set currentIndex(currentIndex) {\n this._currentIndex = currentIndex + this.offset;\n }\n\n private _currentIndex = -1;\n\n private prevIndex = -1;\n\n get direction(): DirectionTypes {\n return this._direction();\n }\n\n _direction = (): DirectionTypes => 'both';\n\n public directionLength = 5;\n\n public hostDelegatesFocus = false;\n\n elementEnterAction = (_el: T): void => {\n return;\n };\n\n get elements(): T[] {\n if (!this.cachedElements) {\n this.cachedElements = this._elements();\n }\n return this.cachedElements;\n }\n\n private _elements!: () => T[];\n\n protected set focused(focused: boolean) {\n /* c8 ignore next 1 */\n if (focused === this.focused) return;\n this._focused = focused;\n }\n\n protected get focused(): boolean {\n return this._focused;\n }\n\n private _focused = false;\n\n get focusInElement(): T {\n return this.elements[this.focusInIndex];\n }\n\n get focusInIndex(): number {\n return this._focusInIndex(this.elements);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _focusInIndex = (_elements: T[]): number => 0;\n\n host: ReactiveElement;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isFocusableElement = (_el: T): boolean => true;\n\n isEventWithinListenerScope(event: Event): boolean {\n if (this._listenerScope() === this.host) return true;\n return event.composedPath().includes(this._listenerScope());\n }\n\n _listenerScope = (): HTMLElement => this.host;\n\n // When elements are virtualized, the delta between the first element\n // and the first rendered element.\n offset = 0;\n\n recentlyConnected = false;\n\n constructor(\n host: ReactiveElement,\n {\n hostDelegatesFocus,\n direction,\n elementEnterAction,\n elements,\n focusInIndex,\n isFocusableElement,\n listenerScope,\n }: FocusGroupConfig<T> = { elements: () => [] }\n ) {\n this.mutationObserver = new MutationObserver(() => {\n this.handleItemMutation();\n });\n this.hostDelegatesFocus = hostDelegatesFocus || false;\n this.host = host;\n this.host.addController(this);\n this._elements = elements;\n this.isFocusableElement = isFocusableElement || this.isFocusableElement;\n this._direction = ensureMethod<() => DirectionTypes, DirectionTypes>(\n direction,\n 'string',\n this._direction\n );\n this.elementEnterAction = elementEnterAction || this.elementEnterAction;\n this._focusInIndex = ensureMethod<(_elements: T[]) => number, number>(\n focusInIndex,\n 'number',\n this._focusInIndex\n );\n this._listenerScope = ensureMethod<() => HTMLElement, HTMLElement>(\n listenerScope,\n 'object',\n this._listenerScope\n );\n }\n /* In handleItemMutation() method the first if condition is checking if the element is not focused or if the element's children's length is not decreasing then it means no element has been deleted and we must return.\n Then we are checking if the deleted element was the focused one before the deletion if so then we need to proceed else we casn return;\n */\n handleItemMutation(): void {\n if (\n this._currentIndex == -1 ||\n this.elements.length <= this._elements().length\n )\n return;\n const focusedElement = this.elements[this.currentIndex];\n this.clearElementCache();\n if (this.elements.includes(focusedElement)) return;\n const moveToNextElement = this.currentIndex !== this.elements.length;\n const diff = moveToNextElement ? 1 : -1;\n if (moveToNextElement) {\n this.setCurrentIndexCircularly(-1);\n }\n this.setCurrentIndexCircularly(diff);\n this.focus();\n }\n\n update({ elements }: FocusGroupConfig<T> = { elements: () => [] }): void {\n this.unmanage();\n this._elements = elements;\n this.clearElementCache();\n this.manage();\n }\n\n /**\n * resets the focusedItem to initial item\n */\n reset(): void {\n const elements = this.elements;\n if (!elements.length) return;\n this.setCurrentIndexCircularly(this.focusInIndex - this.currentIndex);\n let focusElement = elements[this.currentIndex];\n if (this.currentIndex < 0) {\n return;\n }\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.setAttribute('tabindex', '0');\n }\n }\n\n focusOnItem(item?: T, options?: FocusOptions): void {\n if (\n item &&\n this.isFocusableElement(item) &&\n this.elements.indexOf(item)\n ) {\n const diff = this.elements.indexOf(item) - this.currentIndex;\n this.setCurrentIndexCircularly(diff);\n this.elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n }\n this.focus(options);\n }\n\n focus(options?: FocusOptions): void {\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n if (\n !this.hostDelegatesFocus ||\n elements[this.prevIndex] !== focusElement\n ) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n }\n focusElement.tabIndex = 0;\n focusElement.focus(options);\n if (this.hostDelegatesFocus && !this.focused) {\n this.hostContainsFocus();\n }\n }\n }\n\n clearElementCache(offset = 0): void {\n this.mutationObserver.disconnect();\n delete this.cachedElements;\n this.offset = offset;\n requestAnimationFrame(() => {\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n });\n }\n\n setCurrentIndexCircularly(diff: number): void {\n const { length } = this.elements;\n let steps = length;\n this.prevIndex = this.currentIndex;\n // start at a possibly not 0 index\n let nextIndex = (length + this.currentIndex + diff) % length;\n while (\n // don't cycle the elements more than once\n steps &&\n this.elements[nextIndex] &&\n !this.isFocusableElement(this.elements[nextIndex])\n ) {\n nextIndex = (length + nextIndex + diff) % length;\n steps -= 1;\n }\n this.currentIndex = nextIndex;\n }\n\n hostContainsFocus(): void {\n this.host.addEventListener('focusout', this.handleFocusout);\n this.host.addEventListener('keydown', this.handleKeydown);\n this.focused = true;\n }\n\n hostNoLongerContainsFocus(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.focused = false;\n }\n\n isRelatedTargetOrContainAnElement(event: FocusEvent): boolean {\n const relatedTarget = event.relatedTarget as null | Element;\n\n const isRelatedTargetAnElement = this.elements.includes(\n relatedTarget as T\n );\n const isRelatedTargetContainedWithinElements = this.elements.some(\n (el) => el.contains(relatedTarget)\n );\n return !(\n isRelatedTargetAnElement || isRelatedTargetContainedWithinElements\n );\n }\n\n handleFocusin = (event: FocusEvent): void => {\n if (!this.isEventWithinListenerScope(event)) return;\n\n const path = event.composedPath() as T[];\n let targetIndex = -1;\n path.find((el) => {\n targetIndex = this.elements.indexOf(el);\n return targetIndex !== -1;\n });\n this.prevIndex = this.currentIndex;\n this.currentIndex = targetIndex > -1 ? targetIndex : this.currentIndex;\n\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostContainsFocus();\n }\n };\n\n /**\n * handleClick - Finds the element that was clicked and sets the tabindex to 0\n * @returns void\n */\n handleClick = (): void => {\n // Manually set the tabindex to 0 for the current element on receiving focus (from keyboard or mouse)\n const elements = this.elements;\n if (!elements.length) return;\n let focusElement = elements[this.currentIndex];\n if (this.currentIndex < 0) {\n return;\n }\n if (!focusElement || !this.isFocusableElement(focusElement)) {\n this.setCurrentIndexCircularly(1);\n focusElement = elements[this.currentIndex];\n }\n if (focusElement && this.isFocusableElement(focusElement)) {\n elements[this.prevIndex]?.setAttribute('tabindex', '-1');\n focusElement.setAttribute('tabindex', '0');\n }\n };\n\n handleFocusout = (event: FocusEvent): void => {\n if (this.isRelatedTargetOrContainAnElement(event)) {\n this.hostNoLongerContainsFocus();\n }\n };\n\n acceptsEventKey(key: string): boolean {\n if (key === 'End' || key === 'Home') {\n return true;\n }\n switch (this.direction) {\n case 'horizontal':\n return key === 'ArrowLeft' || key === 'ArrowRight';\n case 'vertical':\n return key === 'ArrowUp' || key === 'ArrowDown';\n case 'both':\n case 'grid':\n return key.startsWith('Arrow');\n }\n }\n\n handleKeydown = (event: KeyboardEvent): void => {\n if (!this.acceptsEventKey(event.key) || event.defaultPrevented) {\n return;\n }\n let diff = 0;\n this.prevIndex = this.currentIndex;\n switch (event.key) {\n case 'ArrowRight':\n diff += 1;\n break;\n case 'ArrowDown':\n diff += this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'ArrowLeft':\n diff -= 1;\n break;\n case 'ArrowUp':\n diff -= this.direction === 'grid' ? this.directionLength : 1;\n break;\n case 'End':\n this.currentIndex = 0;\n diff -= 1;\n break;\n case 'Home':\n this.currentIndex = this.elements.length - 1;\n diff += 1;\n break;\n }\n event.preventDefault();\n if (this.direction === 'grid' && this.currentIndex + diff < 0) {\n this.currentIndex = 0;\n } else if (\n this.direction === 'grid' &&\n this.currentIndex + diff > this.elements.length - 1\n ) {\n this.currentIndex = this.elements.length - 1;\n } else {\n this.setCurrentIndexCircularly(diff);\n }\n // To allow the `focusInIndex` to be calculated with the \"after\" state of the keyboard interaction\n // do `elementEnterAction` _before_ focusing the next element.\n this.elementEnterAction(this.elements[this.currentIndex]);\n this.focus();\n };\n\n manage(): void {\n this.addEventListeners();\n }\n\n unmanage(): void {\n this.removeEventListeners();\n }\n\n addEventListeners(): void {\n this.host.addEventListener('focusin', this.handleFocusin);\n this.host.addEventListener('click', this.handleClick);\n }\n\n removeEventListeners(): void {\n this.host.removeEventListener('focusin', this.handleFocusin);\n this.host.removeEventListener('focusout', this.handleFocusout);\n this.host.removeEventListener('keydown', this.handleKeydown);\n this.host.removeEventListener('click', this.handleClick);\n }\n\n hostConnected(): void {\n this.recentlyConnected = true;\n this.addEventListeners();\n }\n\n hostDisconnected(): void {\n this.mutationObserver.disconnect();\n this.removeEventListeners();\n }\n\n hostUpdated(): void {\n if (this.recentlyConnected) {\n this.recentlyConnected = false;\n this.elements.forEach((element) => {\n this.mutationObserver.observe(element, {\n attributes: true,\n });\n });\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "aAwBA,SAASA,EACLC,EACAC,EACAC,EACC,CACD,OAAI,OAAOF,IAAUC,EACT,IAAMD,EACP,OAAOA,GAAU,WACjBA,EAEJE,CACX,CAEO,aAAM,oBAEb,CAmFI,YACIC,EACA,CACI,mBAAAC,EACA,UAAAC,EACA,mBAAAC,EACA,SAAAC,EACA,aAAAC,EACA,mBAAAC,EACA,cAAAC,CACJ,EAAyB,CAAE,SAAU,IAAM,CAAC,CAAE,EAChD,CA/EF,KAAQ,cAAgB,GAExB,KAAQ,UAAY,GAMpB,gBAAa,IAAsB,OAEnC,KAAO,gBAAkB,EAEzB,KAAO,mBAAqB,GAE5B,wBAAsBC,GAAiB,CAEvC,EAqBA,KAAQ,SAAW,GAWnB,mBAAiBC,GAA2B,EAK5C,wBAAsBD,GAAoB,GAO1C,oBAAiB,IAAmB,KAAK,KAIzC,YAAS,EAET,uBAAoB,GAsLpB,mBAAiBE,GAA4B,CACzC,GAAI,CAAC,KAAK,2BAA2BA,CAAK,EAAG,OAE7C,MAAMC,EAAOD,EAAM,aAAa,EAChC,IAAIE,EAAc,GAClBD,EAAK,KAAME,IACPD,EAAc,KAAK,SAAS,QAAQC,CAAE,EAC/BD,IAAgB,GAC1B,EACD,KAAK,UAAY,KAAK,aACtB,KAAK,aAAeA,EAAc,GAAKA,EAAc,KAAK,aAEtD,KAAK,kCAAkCF,CAAK,GAC5C,KAAK,kBAAkB,CAE/B,EAMA,iBAAc,IAAY,CAnU9B,IAAAI,EA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,EAAM,cAEtBmB,EAA2B,KAAK,SAAS,SAC3CD,CACJ,EACME,EAAyC,KAAK,SAAS,KACxDjB,GAAOA,EAAG,SAASe,CAAa,CACrC,EACA,MAAO,EACHC,GAA4BC,EAEpC,CA+CA,gBAAgBC,EAAsB,CAClC,GAAIA,IAAQ,OAASA,IAAQ,OACzB,MAAO,GAEX,OAAQ,KAAK,UAAW,CACpB,IAAK,aACD,OAAOA,IAAQ,aAAeA,IAAQ,aAC1C,IAAK,WACD,OAAOA,IAAQ,WAAaA,IAAQ,YACxC,IAAK,OACL,IAAK,OACD,OAAOA,EAAI,WAAW,OAAO,CACrC,CACJ,CA+CA,QAAe,CACX,KAAK,kBAAkB,CAC3B,CAEA,UAAiB,CACb,KAAK,qBAAqB,CAC9B,CAEA,mBAA0B,CACtB,KAAK,KAAK,iBAAiB,UAAW,KAAK,aAAa,EACxD,KAAK,KAAK,iBAAiB,QAAS,KAAK,WAAW,CACxD,CAEA,sBAA6B,CACzB,KAAK,KAAK,oBAAoB,UAAW,KAAK,aAAa,EAC3D,KAAK,KAAK,oBAAoB,WAAY,KAAK,cAAc,EAC7D,KAAK,KAAK,oBAAoB,UAAW,KAAK,aAAa,EAC3D,KAAK,KAAK,oBAAoB,QAAS,KAAK,WAAW,CAC3D,CAEA,eAAsB,CAClB,KAAK,kBAAoB,GACzB,KAAK,kBAAkB,CAC3B,CAEA,kBAAyB,CACrB,KAAK,iBAAiB,WAAW,EACjC,KAAK,qBAAqB,CAC9B,CAEA,aAAoB,CACZ,KAAK,oBACL,KAAK,kBAAoB,GACzB,KAAK,SAAS,QAASP,GAAY,CAC/B,KAAK,iBAAiB,QAAQA,EAAS,CACnC,WAAY,EAChB,CAAC,CACL,CAAC,EAET,CACJ",
|
|
6
|
+
"names": ["ensureMethod", "value", "type", "fallback", "host", "hostDelegatesFocus", "direction", "elementEnterAction", "elements", "focusInIndex", "isFocusableElement", "listenerScope", "_el", "_elements", "event", "path", "targetIndex", "el", "_a", "focusElement", "diff", "currentIndex", "focused", "focusedElement", "moveToNextElement", "item", "options", "offset", "element", "length", "steps", "nextIndex", "relatedTarget", "isRelatedTargetAnElement", "isRelatedTargetContainedWithinElements", "key"]
|
|
7
7
|
}
|
|
@@ -23,7 +23,7 @@ export class RovingTabindexController extends FocusGroupController {
|
|
|
23
23
|
);
|
|
24
24
|
}
|
|
25
25
|
manageTabindexes() {
|
|
26
|
-
if (this.focused) {
|
|
26
|
+
if (this.focused && !this.hostDelegatesFocus) {
|
|
27
27
|
this.updateTabindexes(() => ({ tabIndex: -1 }));
|
|
28
28
|
} else {
|
|
29
29
|
this.updateTabindexes((el) => {
|
|
@@ -47,7 +47,6 @@ export class RovingTabindexController extends FocusGroupController {
|
|
|
47
47
|
}
|
|
48
48
|
return;
|
|
49
49
|
}
|
|
50
|
-
el.removeAttribute("tabindex");
|
|
51
50
|
const updatable = el;
|
|
52
51
|
if (updatable.requestUpdate) updatable.requestUpdate();
|
|
53
52
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["RovingTabindex.ts"],
|
|
4
|
-
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport { FocusGroupConfig, FocusGroupController } from './FocusGroup.dev.js'\n\nexport type RovingTabindexConfig<T> = FocusGroupConfig<T>;\ninterface UpdateTabIndexes {\n tabIndex: number;\n removeTabIndex?: boolean;\n}\n\nexport class RovingTabindexController<\n T extends HTMLElement,\n> extends FocusGroupController<T> {\n protected override set focused(focused: boolean) {\n if (focused === this.focused) return;\n super.focused = focused;\n this.manageTabindexes();\n }\n\n protected override get focused(): boolean {\n return super.focused;\n }\n\n private managed = true;\n\n private manageIndexesAnimationFrame = 0;\n\n override clearElementCache(offset = 0): void {\n cancelAnimationFrame(this.manageIndexesAnimationFrame);\n super.clearElementCache(offset);\n if (!this.managed) return;\n\n this.manageIndexesAnimationFrame = requestAnimationFrame(() =>\n this.manageTabindexes()\n );\n }\n\n manageTabindexes(): void {\n if (this.focused) {\n this.updateTabindexes(() => ({ tabIndex: -1 }));\n } else {\n this.updateTabindexes((el: HTMLElement): UpdateTabIndexes => {\n return {\n removeTabIndex:\n el.contains(this.focusInElement) &&\n el !== this.focusInElement,\n tabIndex: el === this.focusInElement ? 0 : -1,\n };\n });\n }\n }\n\n updateTabindexes(getTabIndex: (el: HTMLElement) => UpdateTabIndexes): void {\n this.elements.forEach((el) => {\n const { tabIndex, removeTabIndex } = getTabIndex(el);\n if (!removeTabIndex) {\n if (this.focused) {\n if (el !== this.elements[this.currentIndex]) {\n el.tabIndex = tabIndex;\n }\n } else {\n el.tabIndex = tabIndex;\n }\n return;\n }\n
|
|
5
|
-
"mappings": ";AAWA,SAA2B,4BAA4B;AAQhD,aAAM,iCAEH,qBAAwB;AAAA,EAF3B;AAAA;AAaH,SAAQ,UAAU;AAElB,SAAQ,8BAA8B;AAAA;AAAA,EAZtC,IAAuB,QAAQ,SAAkB;AAC7C,QAAI,YAAY,KAAK,QAAS;AAC9B,UAAM,UAAU;AAChB,SAAK,iBAAiB;AAAA,EAC1B;AAAA,EAEA,IAAuB,UAAmB;AACtC,WAAO,MAAM;AAAA,EACjB;AAAA,EAMS,kBAAkB,SAAS,GAAS;AACzC,yBAAqB,KAAK,2BAA2B;AACrD,UAAM,kBAAkB,MAAM;AAC9B,QAAI,CAAC,KAAK,QAAS;AAEnB,SAAK,8BAA8B;AAAA,MAAsB,MACrD,KAAK,iBAAiB;AAAA,IAC1B;AAAA,EACJ;AAAA,EAEA,mBAAyB;AACrB,QAAI,KAAK,
|
|
4
|
+
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport { FocusGroupConfig, FocusGroupController } from './FocusGroup.dev.js'\n\nexport type RovingTabindexConfig<T> = FocusGroupConfig<T>;\ninterface UpdateTabIndexes {\n tabIndex: number;\n removeTabIndex?: boolean;\n}\n\nexport class RovingTabindexController<\n T extends HTMLElement,\n> extends FocusGroupController<T> {\n protected override set focused(focused: boolean) {\n if (focused === this.focused) return;\n super.focused = focused;\n this.manageTabindexes();\n }\n\n protected override get focused(): boolean {\n return super.focused;\n }\n\n private managed = true;\n\n private manageIndexesAnimationFrame = 0;\n\n override clearElementCache(offset = 0): void {\n cancelAnimationFrame(this.manageIndexesAnimationFrame);\n super.clearElementCache(offset);\n if (!this.managed) return;\n\n this.manageIndexesAnimationFrame = requestAnimationFrame(() =>\n this.manageTabindexes()\n );\n }\n\n manageTabindexes(): void {\n if (this.focused && !this.hostDelegatesFocus) {\n this.updateTabindexes(() => ({ tabIndex: -1 }));\n } else {\n this.updateTabindexes((el: HTMLElement): UpdateTabIndexes => {\n return {\n removeTabIndex:\n el.contains(this.focusInElement) &&\n el !== this.focusInElement,\n tabIndex: el === this.focusInElement ? 0 : -1,\n };\n });\n }\n }\n\n updateTabindexes(getTabIndex: (el: HTMLElement) => UpdateTabIndexes): void {\n this.elements.forEach((el) => {\n const { tabIndex, removeTabIndex } = getTabIndex(el);\n if (!removeTabIndex) {\n if (this.focused) {\n if (el !== this.elements[this.currentIndex]) {\n el.tabIndex = tabIndex;\n }\n } else {\n el.tabIndex = tabIndex;\n }\n return;\n }\n const updatable = el as unknown as {\n requestUpdate?: () => void;\n };\n if (updatable.requestUpdate) updatable.requestUpdate();\n });\n }\n\n override manage(): void {\n this.managed = true;\n this.manageTabindexes();\n super.manage();\n }\n\n override unmanage(): void {\n this.managed = false;\n this.updateTabindexes(() => ({ tabIndex: 0 }));\n super.unmanage();\n }\n\n override hostUpdated(): void {\n super.hostUpdated();\n if (!this.host.hasUpdated) {\n this.manageTabindexes();\n }\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAWA,SAA2B,4BAA4B;AAQhD,aAAM,iCAEH,qBAAwB;AAAA,EAF3B;AAAA;AAaH,SAAQ,UAAU;AAElB,SAAQ,8BAA8B;AAAA;AAAA,EAZtC,IAAuB,QAAQ,SAAkB;AAC7C,QAAI,YAAY,KAAK,QAAS;AAC9B,UAAM,UAAU;AAChB,SAAK,iBAAiB;AAAA,EAC1B;AAAA,EAEA,IAAuB,UAAmB;AACtC,WAAO,MAAM;AAAA,EACjB;AAAA,EAMS,kBAAkB,SAAS,GAAS;AACzC,yBAAqB,KAAK,2BAA2B;AACrD,UAAM,kBAAkB,MAAM;AAC9B,QAAI,CAAC,KAAK,QAAS;AAEnB,SAAK,8BAA8B;AAAA,MAAsB,MACrD,KAAK,iBAAiB;AAAA,IAC1B;AAAA,EACJ;AAAA,EAEA,mBAAyB;AACrB,QAAI,KAAK,WAAW,CAAC,KAAK,oBAAoB;AAC1C,WAAK,iBAAiB,OAAO,EAAE,UAAU,GAAG,EAAE;AAAA,IAClD,OAAO;AACH,WAAK,iBAAiB,CAAC,OAAsC;AACzD,eAAO;AAAA,UACH,gBACI,GAAG,SAAS,KAAK,cAAc,KAC/B,OAAO,KAAK;AAAA,UAChB,UAAU,OAAO,KAAK,iBAAiB,IAAI;AAAA,QAC/C;AAAA,MACJ,CAAC;AAAA,IACL;AAAA,EACJ;AAAA,EAEA,iBAAiB,aAA0D;AACvE,SAAK,SAAS,QAAQ,CAAC,OAAO;AAC1B,YAAM,EAAE,UAAU,eAAe,IAAI,YAAY,EAAE;AACnD,UAAI,CAAC,gBAAgB;AACjB,YAAI,KAAK,SAAS;AACd,cAAI,OAAO,KAAK,SAAS,KAAK,YAAY,GAAG;AACzC,eAAG,WAAW;AAAA,UAClB;AAAA,QACJ,OAAO;AACH,aAAG,WAAW;AAAA,QAClB;AACA;AAAA,MACJ;AACA,YAAM,YAAY;AAGlB,UAAI,UAAU,cAAe,WAAU,cAAc;AAAA,IACzD,CAAC;AAAA,EACL;AAAA,EAES,SAAe;AACpB,SAAK,UAAU;AACf,SAAK,iBAAiB;AACtB,UAAM,OAAO;AAAA,EACjB;AAAA,EAES,WAAiB;AACtB,SAAK,UAAU;AACf,SAAK,iBAAiB,OAAO,EAAE,UAAU,EAAE,EAAE;AAC7C,UAAM,SAAS;AAAA,EACnB;AAAA,EAES,cAAoB;AACzB,UAAM,YAAY;AAClB,QAAI,CAAC,KAAK,KAAK,YAAY;AACvB,WAAK,iBAAiB;AAAA,IAC1B;AAAA,EACJ;AACJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/src/RovingTabindex.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";import{FocusGroupController as i}from"./FocusGroup.js";export class RovingTabindexController extends i{constructor(){super(...arguments);this.managed=!0;this.manageIndexesAnimationFrame=0}set focused(e){e!==this.focused&&(super.focused=e,this.manageTabindexes())}get focused(){return super.focused}clearElementCache(e=0){cancelAnimationFrame(this.manageIndexesAnimationFrame),super.clearElementCache(e),this.managed&&(this.manageIndexesAnimationFrame=requestAnimationFrame(()=>this.manageTabindexes()))}manageTabindexes(){this.focused?this.updateTabindexes(()=>({tabIndex:-1})):this.updateTabindexes(e=>({removeTabIndex:e.contains(this.focusInElement)&&e!==this.focusInElement,tabIndex:e===this.focusInElement?0:-1}))}updateTabindexes(e){this.elements.forEach(a=>{const{tabIndex:n,removeTabIndex:s}=e(a);if(!s){this.focused?a!==this.elements[this.currentIndex]&&(a.tabIndex=n):a.tabIndex=n;return}
|
|
1
|
+
"use strict";import{FocusGroupController as i}from"./FocusGroup.js";export class RovingTabindexController extends i{constructor(){super(...arguments);this.managed=!0;this.manageIndexesAnimationFrame=0}set focused(e){e!==this.focused&&(super.focused=e,this.manageTabindexes())}get focused(){return super.focused}clearElementCache(e=0){cancelAnimationFrame(this.manageIndexesAnimationFrame),super.clearElementCache(e),this.managed&&(this.manageIndexesAnimationFrame=requestAnimationFrame(()=>this.manageTabindexes()))}manageTabindexes(){this.focused&&!this.hostDelegatesFocus?this.updateTabindexes(()=>({tabIndex:-1})):this.updateTabindexes(e=>({removeTabIndex:e.contains(this.focusInElement)&&e!==this.focusInElement,tabIndex:e===this.focusInElement?0:-1}))}updateTabindexes(e){this.elements.forEach(a=>{const{tabIndex:n,removeTabIndex:s}=e(a);if(!s){this.focused?a!==this.elements[this.currentIndex]&&(a.tabIndex=n):a.tabIndex=n;return}const t=a;t.requestUpdate&&t.requestUpdate()})}manage(){this.managed=!0,this.manageTabindexes(),super.manage()}unmanage(){this.managed=!1,this.updateTabindexes(()=>({tabIndex:0})),super.unmanage()}hostUpdated(){super.hostUpdated(),this.host.hasUpdated||this.manageTabindexes()}}
|
|
2
2
|
//# sourceMappingURL=RovingTabindex.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["RovingTabindex.ts"],
|
|
4
|
-
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport { FocusGroupConfig, FocusGroupController } from './FocusGroup.js';\n\nexport type RovingTabindexConfig<T> = FocusGroupConfig<T>;\ninterface UpdateTabIndexes {\n tabIndex: number;\n removeTabIndex?: boolean;\n}\n\nexport class RovingTabindexController<\n T extends HTMLElement,\n> extends FocusGroupController<T> {\n protected override set focused(focused: boolean) {\n if (focused === this.focused) return;\n super.focused = focused;\n this.manageTabindexes();\n }\n\n protected override get focused(): boolean {\n return super.focused;\n }\n\n private managed = true;\n\n private manageIndexesAnimationFrame = 0;\n\n override clearElementCache(offset = 0): void {\n cancelAnimationFrame(this.manageIndexesAnimationFrame);\n super.clearElementCache(offset);\n if (!this.managed) return;\n\n this.manageIndexesAnimationFrame = requestAnimationFrame(() =>\n this.manageTabindexes()\n );\n }\n\n manageTabindexes(): void {\n if (this.focused) {\n this.updateTabindexes(() => ({ tabIndex: -1 }));\n } else {\n this.updateTabindexes((el: HTMLElement): UpdateTabIndexes => {\n return {\n removeTabIndex:\n el.contains(this.focusInElement) &&\n el !== this.focusInElement,\n tabIndex: el === this.focusInElement ? 0 : -1,\n };\n });\n }\n }\n\n updateTabindexes(getTabIndex: (el: HTMLElement) => UpdateTabIndexes): void {\n this.elements.forEach((el) => {\n const { tabIndex, removeTabIndex } = getTabIndex(el);\n if (!removeTabIndex) {\n if (this.focused) {\n if (el !== this.elements[this.currentIndex]) {\n el.tabIndex = tabIndex;\n }\n } else {\n el.tabIndex = tabIndex;\n }\n return;\n }\n
|
|
5
|
-
"mappings": "aAWA,OAA2B,wBAAAA,MAA4B,kBAQhD,aAAM,iCAEHA,CAAwB,CAF3B,kCAaH,KAAQ,QAAU,GAElB,KAAQ,4BAA8B,EAZtC,IAAuB,QAAQC,EAAkB,CACzCA,IAAY,KAAK,UACrB,MAAM,QAAUA,EAChB,KAAK,iBAAiB,EAC1B,CAEA,IAAuB,SAAmB,CACtC,OAAO,MAAM,OACjB,CAMS,kBAAkBC,EAAS,EAAS,CACzC,qBAAqB,KAAK,2BAA2B,EACrD,MAAM,kBAAkBA,CAAM,EACzB,KAAK,UAEV,KAAK,4BAA8B,sBAAsB,IACrD,KAAK,iBAAiB,CAC1B,EACJ,CAEA,kBAAyB,CACjB,KAAK,
|
|
4
|
+
"sourcesContent": ["/*\nCopyright 2020 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\nimport { FocusGroupConfig, FocusGroupController } from './FocusGroup.js';\n\nexport type RovingTabindexConfig<T> = FocusGroupConfig<T>;\ninterface UpdateTabIndexes {\n tabIndex: number;\n removeTabIndex?: boolean;\n}\n\nexport class RovingTabindexController<\n T extends HTMLElement,\n> extends FocusGroupController<T> {\n protected override set focused(focused: boolean) {\n if (focused === this.focused) return;\n super.focused = focused;\n this.manageTabindexes();\n }\n\n protected override get focused(): boolean {\n return super.focused;\n }\n\n private managed = true;\n\n private manageIndexesAnimationFrame = 0;\n\n override clearElementCache(offset = 0): void {\n cancelAnimationFrame(this.manageIndexesAnimationFrame);\n super.clearElementCache(offset);\n if (!this.managed) return;\n\n this.manageIndexesAnimationFrame = requestAnimationFrame(() =>\n this.manageTabindexes()\n );\n }\n\n manageTabindexes(): void {\n if (this.focused && !this.hostDelegatesFocus) {\n this.updateTabindexes(() => ({ tabIndex: -1 }));\n } else {\n this.updateTabindexes((el: HTMLElement): UpdateTabIndexes => {\n return {\n removeTabIndex:\n el.contains(this.focusInElement) &&\n el !== this.focusInElement,\n tabIndex: el === this.focusInElement ? 0 : -1,\n };\n });\n }\n }\n\n updateTabindexes(getTabIndex: (el: HTMLElement) => UpdateTabIndexes): void {\n this.elements.forEach((el) => {\n const { tabIndex, removeTabIndex } = getTabIndex(el);\n if (!removeTabIndex) {\n if (this.focused) {\n if (el !== this.elements[this.currentIndex]) {\n el.tabIndex = tabIndex;\n }\n } else {\n el.tabIndex = tabIndex;\n }\n return;\n }\n const updatable = el as unknown as {\n requestUpdate?: () => void;\n };\n if (updatable.requestUpdate) updatable.requestUpdate();\n });\n }\n\n override manage(): void {\n this.managed = true;\n this.manageTabindexes();\n super.manage();\n }\n\n override unmanage(): void {\n this.managed = false;\n this.updateTabindexes(() => ({ tabIndex: 0 }));\n super.unmanage();\n }\n\n override hostUpdated(): void {\n super.hostUpdated();\n if (!this.host.hasUpdated) {\n this.manageTabindexes();\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "aAWA,OAA2B,wBAAAA,MAA4B,kBAQhD,aAAM,iCAEHA,CAAwB,CAF3B,kCAaH,KAAQ,QAAU,GAElB,KAAQ,4BAA8B,EAZtC,IAAuB,QAAQC,EAAkB,CACzCA,IAAY,KAAK,UACrB,MAAM,QAAUA,EAChB,KAAK,iBAAiB,EAC1B,CAEA,IAAuB,SAAmB,CACtC,OAAO,MAAM,OACjB,CAMS,kBAAkBC,EAAS,EAAS,CACzC,qBAAqB,KAAK,2BAA2B,EACrD,MAAM,kBAAkBA,CAAM,EACzB,KAAK,UAEV,KAAK,4BAA8B,sBAAsB,IACrD,KAAK,iBAAiB,CAC1B,EACJ,CAEA,kBAAyB,CACjB,KAAK,SAAW,CAAC,KAAK,mBACtB,KAAK,iBAAiB,KAAO,CAAE,SAAU,EAAG,EAAE,EAE9C,KAAK,iBAAkBC,IACZ,CACH,eACIA,EAAG,SAAS,KAAK,cAAc,GAC/BA,IAAO,KAAK,eAChB,SAAUA,IAAO,KAAK,eAAiB,EAAI,EAC/C,EACH,CAET,CAEA,iBAAiBC,EAA0D,CACvE,KAAK,SAAS,QAASD,GAAO,CAC1B,KAAM,CAAE,SAAAE,EAAU,eAAAC,CAAe,EAAIF,EAAYD,CAAE,EACnD,GAAI,CAACG,EAAgB,CACb,KAAK,QACDH,IAAO,KAAK,SAAS,KAAK,YAAY,IACtCA,EAAG,SAAWE,GAGlBF,EAAG,SAAWE,EAElB,MACJ,CACA,MAAME,EAAYJ,EAGdI,EAAU,eAAeA,EAAU,cAAc,CACzD,CAAC,CACL,CAES,QAAe,CACpB,KAAK,QAAU,GACf,KAAK,iBAAiB,EACtB,MAAM,OAAO,CACjB,CAES,UAAiB,CACtB,KAAK,QAAU,GACf,KAAK,iBAAiB,KAAO,CAAE,SAAU,CAAE,EAAE,EAC7C,MAAM,SAAS,CACnB,CAES,aAAoB,CACzB,MAAM,YAAY,EACb,KAAK,KAAK,YACX,KAAK,iBAAiB,CAE9B,CACJ",
|
|
6
6
|
"names": ["FocusGroupController", "focused", "offset", "el", "getTabIndex", "tabIndex", "removeTabIndex", "updatable"]
|
|
7
7
|
}
|