diff --git a/.bundlewatch.config.json b/.bundlewatch.config.json index 3d52a9ba24..2eee2e7d43 100644 --- a/.bundlewatch.config.json +++ b/.bundlewatch.config.json @@ -2,11 +2,11 @@ "files": [ { "path": "./dist/css/bootstrap-grid.css", - "maxSize": "12.5 kB" + "maxSize": "13.75 kB" }, { "path": "./dist/css/bootstrap-grid.min.css", - "maxSize": "11.0 kB" + "maxSize": "12.0 kB" }, { "path": "./dist/css/bootstrap-reboot.css", @@ -26,19 +26,19 @@ }, { "path": "./dist/css/bootstrap.css", - "maxSize": "54.25 kB" + "maxSize": "55.5 kB" }, { "path": "./dist/css/bootstrap.min.css", - "maxSize": "50.5 kB" + "maxSize": "52 kB" }, { "path": "./dist/js/bootstrap.bundle.js", - "maxSize": "75.25 kB" + "maxSize": "79.75 kB" }, { "path": "./dist/js/bootstrap.bundle.min.js", - "maxSize": "59.25 kB" + "maxSize": "62.75 kB" }, { "path": "./dist/js/bootstrap.js", @@ -46,7 +46,7 @@ }, { "path": "./dist/js/bootstrap.min.js", - "maxSize": "35.5 kB" + "maxSize": "39.0 kB" } ], "ci": { diff --git a/.cspell.json b/.cspell.json index 06e29d2b36..f06670ecad 100644 --- a/.cspell.json +++ b/.cspell.json @@ -1,6 +1,7 @@ { "version": "0.2", "words": [ + "activedescendant", "affordance", "allowfullscreen", "Analyser", @@ -124,6 +125,7 @@ "mkdir", "monospace", "mouseleave", + "multiselectable", "navbars", "navs", "navoverflow", diff --git a/.github/workflows/css.yml b/.github/workflows/css.yml index 01c53f62b4..53b80a01fe 100644 --- a/.github/workflows/css.yml +++ b/.github/workflows/css.yml @@ -37,3 +37,12 @@ jobs: - name: Run CSS tests run: npm run css-test + + - name: Install grid test browsers + run: npx playwright install --with-deps chromium firefox webkit + + - name: Test grid layout in Chromium, Firefox, and WebKit + run: | + npm run css-test-grid + GRID_TEST_BROWSER=firefox npm run css-test-grid + GRID_TEST_BROWSER=webkit npm run css-test-grid diff --git a/AGENTS.md b/AGENTS.md index 4a1001f14e..d096362488 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -84,6 +84,7 @@ Act as a teacher for JavaScript, TypeScript, React, and all JavaScript-family to - Astro 5 + MDX in `site/src/content/docs/` - Frontmatter schema: `title` (required), `description` (required), `toc`, `aliases`, `added`, `mdn`, `reference`, etc. - Shortcodes: `Example`, `Callout`, `Code`, `Details` +- For multiline `` template literals that start on the same line as the shortcode, add two extra spaces to each following line of code. Top-level markup starts with two spaces in the source, and its children start with four. The rendered snippet removes the extra level. Follow `site/src/content/docs/forms/field.mdx` and check the rendered code before committing. - Internal links: `[[docsref:/path/]]` - JS component "Dependencies" tables are auto-generated — add a `### Dependencies` heading with `` (before `### Options`) on any doc for a `js/src/*.ts` component. The table is derived at build time by walking the component's import graph in `site/src/libs/js-dependencies.ts`; never hand-write the file list. When a new source file or third-party package enters the graph, add its human-readable label to `FILE_DESCRIPTIONS` / `PACKAGE_DESCRIPTIONS` in that lib (the build throws if a label is missing). diff --git a/build/test-grid-layout.mjs b/build/test-grid-layout.mjs new file mode 100644 index 0000000000..9d3a141773 --- /dev/null +++ b/build/test-grid-layout.mjs @@ -0,0 +1,287 @@ +/* eslint-disable no-await-in-loop -- Cases share one browser page and must run sequentially. */ +import assert from 'node:assert/strict' +import process from 'node:process' +import { fileURLToPath } from 'node:url' +import path from 'node:path' +import * as sass from 'sass' +import { chromium, firefox, webkit } from 'playwright' + +const root = + process.env.GRID_TEST_ROOT || + fileURLToPath(new URL('../', import.meta.url)) +const engine = process.env.GRID_TEST_BROWSER || 'chromium' +const browsers = { chromium, firefox, webkit } +assert.ok(browsers[engine], `Unknown browser: ${engine}`) +const browser = await browsers[engine].launch({ + headless: true, + timeout: 15000, + ...(process.env.GRID_TEST_EXECUTABLE ? + { executablePath: process.env.GRID_TEST_EXECUTABLE } : + {}), + ...(process.env.GRID_TEST_CHANNEL ? + { channel: process.env.GRID_TEST_CHANNEL } : + {}) +}) +const compile = columns => + sass.compileString( + `@use "bootstrap"${columns ? ` with ($grid-columns: ${columns})` : ''};`, + { + loadPaths: [path.join(root, 'scss')] + } + ).css +const css = compile() +const near = (actual, expected, name) => + assert.ok( + Math.abs(actual - expected) < 0.15, + `${name}: ${actual} != ${expected}` + ) +const column = (span, extra = '') => + `
` +let checks = 0 + +try { + const page = await browser.newPage() + await page.route('**/*', route => route.abort()) + async function render( + markup, + { width = 1200, dir = 'ltr', viewport = 1400, styles = css } = {} + ) { + await page.setViewportSize({ width: viewport, height: 900 }) + await page.setContent( + `
${markup}
` + ) + } + + async function boxes(selector = '.fixture > .row') { + return page.locator(selector).evaluateAll(rows => + rows.map(row => { + // eslint-disable-next-line unicorn/consistent-function-scoping -- This callback runs in the browser. + const rect = element => { + const r = element.getBoundingClientRect() + return { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + right: r.right, + bottom: r.bottom + } + } + + return { row: rect(row), children: [...row.children].map(rect) } + }) + ) + } + + // Every ordered two- and three-column partition of twelve, including fractional widths. + const partitions = [] + for (let a = 1; a < 12; a++) { + partitions.push([a, 12 - a]) + for (let b = 1; b < 12 - a; b++) { + partitions.push([a, b, 12 - a - b]) + } + } + + const scenarios = [1200, 671.5, 320].flatMap(width => + ['ltr', 'rtl'].map(dir => ({ width, dir })) + ) + for (const { width, dir } of scenarios) { + await render( + partitions + .map( + spans => + `
${spans.map(s => column(s)).join('')}
` + ) + .join(''), + { width, dir } + ) + const layouts = await boxes() + for (const [index, { row, children }] of layouts.entries()) { + for (const [j, child] of children.entries()) { + near( + child.width, + (((width + 24) * partitions[index][j]) / 12) - 24, + 'numbered width' + ) + near(child.y, row.y, 'partition must not wrap') + const previous = children[j - 1] || row + near( + dir === 'ltr' ? + child.x - (j ? previous.right : row.x) : + (j ? previous.x : row.right) - child.right, + j ? 24 : 0, + 'horizontal gap and row edge' + ) + } + + checks++ + } + } + + for (const dir of ['ltr', 'rtl']) { + await render( + `${Array.from( + { length: 11 }, + (_, i) => `
${column(11 - i, `offset-${i + 1}`)}
` + ).join('') + }
${column(3)}${column(6, 'offset-3')}
`, + { dir } + ) + const offsetLayouts = await boxes() + for (const [i, { row, children }] of offsetLayouts.entries()) { + const last = children.at(-1) + near( + dir === 'ltr' ? last.right : row.right - last.x, + 1200, + 'offset reaches row end' + ) + if (i < 11) { + near( + dir === 'ltr' ? last.x - row.x : row.right - last.right, + (1224 * (i + 1)) / 12, + 'offset tracks' + ) + } + + checks++ + } + } + + await render(`
${column(8)}${column(6)}
`) + let [layout] = await boxes() + near(layout.children[1].y - layout.children[0].bottom, 16, 'wrapped row gap') + near(layout.children[1].x, layout.row.x, 'wrapped column starts at row edge') + checks++ + + await render( + `
Auto
${column(6)}
` + ); + [layout] = await boxes() + near(layout.children[2].width, 588, 'fixed column alongside auto columns') + near( + layout.children[0].width + + layout.children[1].width + + layout.children[2].width + + 48, + 1200, + 'auto fills remaining width' + ) + checks++ + + await render( + `
${Array.from({ length: 5 }, () => '
').join('')}
` + ); + [layout] = await boxes() + for (const child of layout.children) { + near(child.width, 384, 'row-cols width') + } + + near(layout.children[3].x, layout.row.x, 'row-cols wraps') + near( + layout.children[3].y - layout.children[0].bottom, + 16, + 'row-cols vertical gap' + ) + checks++ + + await render( + `
${column(3)}${column(9)}
${column(6)}
` + ) + const [nested] = await boxes('.row .row') + near(nested.row.width, 588, 'nested row has no negative margins') + near(nested.children[0].width, 129, 'nested span') + near(nested.children[1].right, nested.row.right, 'nested row fills parent') + near( + await page + .locator('.fixture > .standalone') + .evaluate(e => e.getBoundingClientRect().width), + 600, + 'standalone percentage width' + ) + near( + await page + .locator('.row .standalone') + .evaluate(e => e.getBoundingClientRect().width), + 294, + 'non-direct child keeps percentage width' + ) + checks++ + + // Responsive row-cols must retain the original specificity against numbered columns. + for (const viewport of [375, 900]) { + await render( + `
${column(6)}${column(6)}${column(6)}
${column(6, 'offset-6 md:offset-0')}
`, + { width: viewport, viewport } + ) + const [responsive, offset] = await boxes() + const count = viewport < 768 ? 2 : 3 + near( + responsive.children[0].width, + ((responsive.row.width + 24) / count) - 24, + 'responsive row-cols overrides' + ) + near( + offset.children[0].x, + viewport < 768 ? (offset.row.width + 24) / 2 : 0, + 'responsive offset reset' + ) + checks++ + } + + await render(`
${column(6)}${column(6)}
`); + [layout] = await boxes() + near(layout.children[0].width, 600, 'zero gutter width') + near(layout.children[1].x - layout.children[0].right, 0, 'zero gutter gap') + checks++ + + await render( + '
' + ); + [layout] = await boxes() + for (const child of layout.children) { + near(child.width, 400, 'zero gutter row-cols') + } + + checks++ + + await render(`
${column(3)}${column(7)}
`, { + styles: compile(10) + }); + [layout] = await boxes() + near(layout.children[0].width, 343.2, 'custom column count') + near(layout.children[1].right, 1200, 'custom grid fills row') + checks++ + + const gridOnly = sass.compile(path.join(root, 'scss/bootstrap-grid.scss')).css + for (const styles of [css, gridOnly]) { + for (const dir of ['ltr', 'rtl']) { + await render( + `
${column(6)}${column(6)}
`, + { dir, styles: `${styles} .cell { padding: 12px; border: 2px solid; }` } + ); + [layout] = await boxes() + near(layout.children[0].width, 588, 'padded column includes borders and padding') + near(layout.children[1].y, layout.children[0].y, 'padded columns do not wrap without reboot') + checks++ + } + } + + if (process.env.GRID_TEST_SCREENSHOT) { + await render( + `
${column(3)}${column(3)}${column(6)}
${column(9, 'offset-3')}
` + ) + await page + .locator('.fixture') + .screenshot({ path: process.env.GRID_TEST_SCREENSHOT }) + } + + console.log(`${checks} grid layouts passed in ${engine}.`) +} finally { + await browser.close() +} diff --git a/js/src/chips.ts b/js/src/chips.ts deleted file mode 100644 index 8341a590f8..0000000000 --- a/js/src/chips.ts +++ /dev/null @@ -1,668 +0,0 @@ -/** - * -------------------------------------------------------------------------- - * Bootstrap chips.ts - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - * -------------------------------------------------------------------------- - */ - -import BaseComponent from './base-component.js' -import EventHandler, { type BootstrapEvent } from './dom/event-handler.js' -import SelectorEngine from './dom/selector-engine.js' -import { onDocumentReady } from './util/component-functions.js' -import { DefaultIconAllowlist, sanitizeHtml } from './util/sanitizer.js' - -/** - * Constants - */ - -const NAME = 'chips' -const DATA_KEY = 'bs.chips' -const EVENT_KEY = `.${DATA_KEY}` -const DATA_API_KEY = '.data-api' - -const EVENT_ADD = `add${EVENT_KEY}` -const EVENT_REMOVE = `remove${EVENT_KEY}` -const EVENT_CHANGE = `change${EVENT_KEY}` -const EVENT_SELECT = `select${EVENT_KEY}` - -const SELECTOR_DATA_CHIPS = '[data-bs-chips]' -const SELECTOR_GHOST_INPUT = '.form-ghost' -const SELECTOR_CHIP = '.chip' -const SELECTOR_CHIP_DISMISS = '.chip-dismiss' - -const CLASS_NAME_CHIP = 'chip' -const CLASS_NAME_CHIP_DISMISS = 'chip-dismiss' -const CLASS_NAME_ACTIVE = 'active' - -const DEFAULT_DISMISS_ICON = '' - -type ChipsConfig = { - separator: string | null - allowDuplicates: boolean - maxChips: number | null - placeholder: string - dismissible: boolean - dismissIcon: string - createOnBlur: boolean -} - -const Default: ChipsConfig = { - separator: ',', - allowDuplicates: false, - maxChips: null, - placeholder: '', - dismissible: true, - dismissIcon: DEFAULT_DISMISS_ICON, - createOnBlur: true -} - -const DefaultType = { - separator: '(string|null)', - allowDuplicates: 'boolean', - maxChips: '(number|null)', - placeholder: 'string', - dismissible: 'boolean', - dismissIcon: 'string', - createOnBlur: 'boolean' -} - -/** - * Class definition - */ - -class Chips extends BaseComponent { - protected declare _config: ChipsConfig - protected declare _input: HTMLInputElement - protected declare _chips: string[] - protected declare _selectedChips: Set - protected declare _anchorChip: HTMLElement | null - - constructor(element?: string | Element | null, config?: Partial | null) { - super(element, config) - - const ghostInput = SelectorEngine.findOne(SELECTOR_GHOST_INPUT, this._element) - this._chips = [] - this._selectedChips = new Set() - this._anchorChip = null // For shift+click range selection - - if (ghostInput) { - this._input = ghostInput - } else { - this._createInput() - } - - this._initializeExistingChips() - this._addEventListeners() - } - - // Getters - static override get Default(): ChipsConfig { - return Default - } - - static override get DefaultType(): Record { - return DefaultType - } - - static override get NAME(): string { - return NAME - } - - // Public - add(value: string): HTMLElement | null { - const trimmedValue = String(value).trim() - - if (!trimmedValue) { - return null - } - - // Check for duplicates - if (!this._config.allowDuplicates && this._chips.includes(trimmedValue)) { - return null - } - - // Check max chips limit - if (this._config.maxChips !== null && this._chips.length >= this._config.maxChips) { - return null - } - - const addEvent = EventHandler.trigger(this._element, EVENT_ADD, { - value: trimmedValue, - relatedTarget: this._input - }) - - if (addEvent.defaultPrevented) { - return null - } - - const chip = this._createChip(trimmedValue) - this._element.insertBefore(chip, this._input) - this._chips.push(trimmedValue) - - EventHandler.trigger(this._element, EVENT_CHANGE, { - values: this.getValues() - }) - - return chip - } - - remove(chipOrValue: string | HTMLElement): boolean { - let chip: HTMLElement | undefined - let value: string - - if (typeof chipOrValue === 'string') { - value = chipOrValue - chip = this._findChipByValue(value) - } else { - chip = chipOrValue - value = this._getChipValue(chip) - } - - if (!chip || !value) { - return false - } - - const removeEvent = EventHandler.trigger(this._element, EVENT_REMOVE, { - value, - chip, - relatedTarget: this._input - }) - - if (removeEvent.defaultPrevented) { - return false - } - - // Remove from selection - this._selectedChips.delete(chip) - if (this._anchorChip === chip) { - this._anchorChip = null - } - - // Remove from DOM, then rebuild the value array from the remaining chips. - // This keeps `_chips` in the same order as the rendered chips even with - // duplicates, where splicing the first matching value would desync order. - chip.remove() - this._chips = this._getChipElements() - .map(chipElement => this._getChipValue(chipElement)) - .filter(Boolean) - - EventHandler.trigger(this._element, EVENT_CHANGE, { - values: this.getValues() - }) - - return true - } - - removeSelected(): void { - const chipsToRemove = [...this._selectedChips] - for (const chip of chipsToRemove) { - this.remove(chip) - } - - this._input?.focus() - } - - getValues(): string[] { - return [...this._chips] - } - - getSelectedValues(): string[] { - return [...this._selectedChips].map(chip => this._getChipValue(chip)) - } - - clear(): void { - const chips = SelectorEngine.find(SELECTOR_CHIP, this._element) - for (const chip of chips) { - chip.remove() - } - - this._chips = [] - this._selectedChips.clear() - this._anchorChip = null - - EventHandler.trigger(this._element, EVENT_CHANGE, { - values: [] - }) - } - - clearSelection(): void { - for (const chip of this._selectedChips) { - chip.classList.remove(CLASS_NAME_ACTIVE) - } - - this._selectedChips.clear() - this._anchorChip = null - - EventHandler.trigger(this._element, EVENT_SELECT, { - selected: [] - }) - } - - selectChip(chip: HTMLElement, options: { addToSelection?: boolean, rangeSelect?: boolean } = {}): void { - const { addToSelection = false, rangeSelect = false } = options - const chipElements = this._getChipElements() - - if (!chipElements.includes(chip)) { - return - } - - if (rangeSelect && this._anchorChip) { - // Range selection from anchor to chip - const anchorIndex = chipElements.indexOf(this._anchorChip) - const chipIndex = chipElements.indexOf(chip) - const start = Math.min(anchorIndex, chipIndex) - const end = Math.max(anchorIndex, chipIndex) - - if (!addToSelection) { - // clearSelection() resets the anchor, keep it for the next range selection - const anchorChip = this._anchorChip - this.clearSelection() - this._anchorChip = anchorChip - } - - for (let i = start; i <= end; i++) { - this._selectedChips.add(chipElements[i]) - chipElements[i].classList.add(CLASS_NAME_ACTIVE) - } - } else if (addToSelection) { - // Toggle selection - if (this._selectedChips.has(chip)) { - this._selectedChips.delete(chip) - chip.classList.remove(CLASS_NAME_ACTIVE) - } else { - this._selectedChips.add(chip) - chip.classList.add(CLASS_NAME_ACTIVE) - this._anchorChip = chip - } - } else { - // Single selection - this.clearSelection() - this._selectedChips.add(chip) - chip.classList.add(CLASS_NAME_ACTIVE) - this._anchorChip = chip - } - - EventHandler.trigger(this._element, EVENT_SELECT, { - selected: this.getSelectedValues() - }) - } - - focus(): void { - this._input?.focus() - } - - override dispose(): void { - EventHandler.off(this._input, EVENT_KEY) - super.dispose() - } - - // Private - protected _getChipElements(): HTMLElement[] { - return SelectorEngine.find(SELECTOR_CHIP, this._element) - } - - protected _createInput(): void { - const input = document.createElement('input') - input.type = 'text' - input.className = 'form-ghost' - if (this._config.placeholder) { - input.placeholder = this._config.placeholder - } - - this._element.append(input) - this._input = input - } - - protected _initializeExistingChips(): void { - const existingChips = SelectorEngine.find(SELECTOR_CHIP, this._element) - for (const chip of existingChips) { - const value = this._getChipValue(chip) - if (value) { - this._chips.push(value) - this._setupChip(chip) - } - } - } - - protected _setupChip(chip: HTMLElement): void { - // Make chip focusable - chip.setAttribute('tabindex', '0') - - // Add dismiss button if needed - if (this._config.dismissible && !SelectorEngine.findOne(SELECTOR_CHIP_DISMISS, chip)) { - chip.append(this._createDismissButton()) - } - } - - protected _createChip(value: string): HTMLElement { - const chip = document.createElement('span') - chip.className = CLASS_NAME_CHIP - chip.dataset.bsChipValue = value - - // Add text node - chip.append(document.createTextNode(value)) - - // Setup chip (tabindex, dismiss button) - this._setupChip(chip) - - return chip - } - - protected _createDismissButton(): HTMLButtonElement { - const button = document.createElement('button') - button.type = 'button' - button.className = CLASS_NAME_CHIP_DISMISS - button.setAttribute('aria-label', 'Remove') - button.setAttribute('tabindex', '-1') // Not in tab order, chips handle keyboard - // dismissIcon accepts HTML (SVGs, icon fonts) and is also settable via the - // data API, so run it through the icon allowlist before insertion. - button.innerHTML = sanitizeHtml(this._config.dismissIcon, DefaultIconAllowlist) - return button - } - - protected _findChipByValue(value: string): HTMLElement | undefined { - const chips = this._getChipElements() - return chips.find(chip => this._getChipValue(chip) === value) - } - - protected _getChipValue(chip: HTMLElement): string { - if (chip.dataset.bsChipValue) { - return chip.dataset.bsChipValue - } - - const clone = chip.cloneNode(true) as HTMLElement - const dismiss = SelectorEngine.findOne(SELECTOR_CHIP_DISMISS, clone) - if (dismiss) { - dismiss.remove() - } - - return clone.textContent?.trim() || '' - } - - protected _addEventListeners(): void { - // Input events - EventHandler.on(this._input, `keydown${EVENT_KEY}`, event => this._handleInputKeydown(event)) - EventHandler.on(this._input, `input${EVENT_KEY}`, event => this._handleInput(event)) - EventHandler.on(this._input, `paste${EVENT_KEY}`, event => this._handlePaste(event)) - EventHandler.on(this._input, `focus${EVENT_KEY}`, () => this.clearSelection()) - - if (this._config.createOnBlur) { - EventHandler.on(this._input, `blur${EVENT_KEY}`, event => { - // Don't create chip if clicking on a chip - if (!event.relatedTarget?.closest(SELECTOR_CHIP)) { - this._createChipFromInput() - } - }) - } - - // Chip click events (delegated) - EventHandler.on(this._element, `click${EVENT_KEY}`, SELECTOR_CHIP, event => { - // Ignore clicks on dismiss button - if ((event.target as Element).closest(SELECTOR_CHIP_DISMISS)) { - return - } - - const chip = (event.target as Element).closest(SELECTOR_CHIP) - if (chip) { - event.preventDefault() - this.selectChip(chip, { - addToSelection: event.metaKey || event.ctrlKey, - rangeSelect: event.shiftKey - }) - chip.focus() - } - }) - - // Dismiss button clicks (delegated) - EventHandler.on(this._element, `click${EVENT_KEY}`, SELECTOR_CHIP_DISMISS, event => { - event.stopPropagation() - const chip = (event.target as Element).closest(SELECTOR_CHIP) - if (chip) { - this.remove(chip) - this._input?.focus() - } - }) - - // Chip keyboard events (delegated) - EventHandler.on(this._element, `keydown${EVENT_KEY}`, SELECTOR_CHIP, event => { - this._handleChipKeydown(event) - }) - - // Focus input when clicking container background - EventHandler.on(this._element, `click${EVENT_KEY}`, event => { - if (event.target === this._element) { - this.clearSelection() - this._input?.focus() - } - }) - } - - protected _handleInputKeydown(event: BootstrapEvent): void { - const { key } = event - - switch (key) { - case 'Enter': { - event.preventDefault() - this._createChipFromInput() - break - } - - case 'Backspace': - case 'Delete': { - if (this._input.value === '') { - event.preventDefault() - const chips = this._getChipElements() - - if (chips.length > 0) { - // Select last chip and focus it - const lastChip = chips.at(-1)! - this.selectChip(lastChip) - lastChip.focus() - } - } - - break - } - - case 'ArrowLeft': { - if (this._input.selectionStart === 0 && this._input.selectionEnd === 0) { - event.preventDefault() - const chips = this._getChipElements() - if (chips.length > 0) { - const lastChip = chips.at(-1)! - if (event.shiftKey) { - this.selectChip(lastChip, { addToSelection: true }) - } else { - this.selectChip(lastChip) - } - - lastChip.focus() - } - } - - break - } - - case 'Escape': { - this._input.value = '' - this.clearSelection() - this._input.blur() - break - } - - // No default - } - } - - protected _handleChipKeydown(event: BootstrapEvent): void { - const { key } = event - const chip = (event.target as Element).closest(SELECTOR_CHIP) - if (!chip) { - return - } - - const chips = this._getChipElements() - const currentIndex = chips.indexOf(chip) - - switch (key) { - case 'Backspace': - case 'Delete': { - event.preventDefault() - this._handleChipDelete(currentIndex, chips) - break - } - - case 'ArrowLeft': { - event.preventDefault() - this._navigateChip(chips, currentIndex, -1, event.shiftKey) - break - } - - case 'ArrowRight': { - event.preventDefault() - this._navigateChip(chips, currentIndex, 1, event.shiftKey) - break - } - - case 'Home': { - event.preventDefault() - this._navigateToEdge(chips, 0, event.shiftKey) - break - } - - case 'End': { - event.preventDefault() - this.clearSelection() - this._input?.focus() - break - } - - case 'a': { - this._handleSelectAll(event, chips) - break - } - - case 'Escape': { - event.preventDefault() - this.clearSelection() - this._input?.focus() - break - } - - // No default - } - } - - protected _handleChipDelete(currentIndex: number, chips: HTMLElement[]): void { - if (this._selectedChips.size === 0) { - return - } - - const nextIndex = Math.min(currentIndex, chips.length - this._selectedChips.size - 1) - this.removeSelected() - - const remainingChips = this._getChipElements() - if (remainingChips.length > 0) { - const focusIndex = Math.max(0, Math.min(nextIndex, remainingChips.length - 1)) - remainingChips[focusIndex].focus() - this.selectChip(remainingChips[focusIndex]) - } else { - this._input?.focus() - } - } - - protected _navigateChip(chips: HTMLElement[], currentIndex: number, direction: number, shiftKey: boolean): void { - const targetIndex = currentIndex + direction - - if (direction < 0 && targetIndex >= 0) { - const targetChip = chips[targetIndex] - this.selectChip(targetChip, shiftKey ? { addToSelection: true, rangeSelect: true } : {}) - targetChip.focus() - } else if (direction > 0 && targetIndex < chips.length) { - const targetChip = chips[targetIndex] - this.selectChip(targetChip, shiftKey ? { addToSelection: true, rangeSelect: true } : {}) - targetChip.focus() - } else if (direction > 0) { - this.clearSelection() - this._input?.focus() - } - } - - protected _navigateToEdge(chips: HTMLElement[], targetIndex: number, shiftKey: boolean): void { - if (chips.length === 0) { - return - } - - const targetChip = chips[targetIndex] - this.selectChip(targetChip, shiftKey ? { rangeSelect: true } : {}) - targetChip.focus() - } - - protected _handleSelectAll(event: BootstrapEvent, chips: HTMLElement[]): void { - if (!(event.metaKey || event.ctrlKey)) { - return - } - - event.preventDefault() - for (const c of chips) { - this._selectedChips.add(c) - c.classList.add(CLASS_NAME_ACTIVE) - } - - EventHandler.trigger(this._element, EVENT_SELECT, { - selected: this.getSelectedValues() - }) - } - - protected _handleInput(event: BootstrapEvent): void { - const { value } = event.target as HTMLInputElement - const { separator } = this._config - - if (separator && value.includes(separator)) { - const parts = value.split(separator) - for (const part of parts.slice(0, -1)) { - this.add(part.trim()) - } - - this._input.value = parts.at(-1)! - } - } - - protected _handlePaste(event: BootstrapEvent): void { - const { separator } = this._config - if (!separator) { - return - } - - const pastedData = (event.clipboardData || (window as any).clipboardData).getData('text') - if (pastedData.includes(separator)) { - event.preventDefault() - - const parts = pastedData.split(separator) - for (const part of parts) { - this.add(part.trim()) - } - } - } - - protected _createChipFromInput(): void { - const value = this._input.value.trim() - if (value) { - this.add(value) - this._input.value = '' - } - } -} - -/** - * Data API implementation - */ - -onDocumentReady(`DOMContentLoaded${EVENT_KEY}${DATA_API_KEY}`, () => { - for (const element of SelectorEngine.find(SELECTOR_DATA_CHIPS)) { - Chips.getOrCreateInstance(element) - } -}) - -export default Chips -export type { ChipsConfig } diff --git a/js/src/collapse.ts b/js/src/collapse.ts index cf6a8f9af7..f0bb1a6f70 100644 --- a/js/src/collapse.ts +++ b/js/src/collapse.ts @@ -9,6 +9,7 @@ import BaseComponent from './base-component.js' import EventHandler from './dom/event-handler.js' import SelectorEngine from './dom/selector-engine.js' import type { ComponentConfig } from './util/config.js' +import { enableHashTarget } from './util/hash-target.js' import { getElement, getTransitionDurationFromElement, @@ -245,5 +246,38 @@ EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function ( } }) +/** + * Find a trigger that targets this collapse. + */ +const getCollapseTrigger = (collapseEl: HTMLElement): HTMLElement | null => { + for (const trigger of SelectorEngine.find(SELECTOR_DATA_TOGGLE)) { + if (SelectorEngine.getMultipleElementsFromSelector(trigger).includes(collapseEl)) { + return trigger + } + } + + return null +} + +/** + * Open opted-in collapses when the URL fragment matches their id. + * Put `data-bs-hash` on the collapsible target. + */ +enableHashTarget(`${EVENT_KEY}${DATA_API_KEY}`, { + matches: element => element.classList.contains(CLASS_NAME_COLLAPSE), + getAnchor: getCollapseTrigger, + async open(element, done) { + if (element.classList.contains(CLASS_NAME_SHOW)) { + done() + return + } + + await Collapse.getOrCreateInstance(element).show() + if (element.classList.contains(CLASS_NAME_SHOW)) { + done() + } + } +}) + export default Collapse export type { CollapseConfig } diff --git a/js/src/combobox.ts b/js/src/combobox.ts index 40abefdddc..04f6f9a379 100644 --- a/js/src/combobox.ts +++ b/js/src/combobox.ts @@ -5,14 +5,16 @@ * -------------------------------------------------------------------------- */ +import type { MiddlewareState } from '@floating-ui/dom' import BaseComponent from './base-component.js' import EventHandler, { type BootstrapEvent } from './dom/event-handler.js' import SelectorEngine from './dom/selector-engine.js' import Menu from './menu.js' import { onDocumentReady } from './util/component-functions.js' +import type { ComponentConfig } from './util/config.js' import type { FloatingOffsetOption } from './util/floating-ui.js' import { - getNextActiveElement, isDisabled, isVisible, setAriaAttribute + getElement, getNextActiveElement, getUID, isDisabled, isVisible, setAriaAttribute } from './util/index.js' /** @@ -34,16 +36,14 @@ const ENTER_KEY = 'Enter' const SPACE_KEY = ' ' const EVENT_CHANGE = `change${EVENT_KEY}` -const EVENT_SHOW = `show${EVENT_KEY}` -const EVENT_SHOWN = `shown${EVENT_KEY}` -const EVENT_HIDE = `hide${EVENT_KEY}` -const EVENT_HIDDEN = `hidden${EVENT_KEY}` const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}` const CLASS_NAME_SHOW = 'show' const CLASS_NAME_SELECTED = 'selected' const CLASS_NAME_PLACEHOLDER = 'combobox-placeholder' +const DISMISS_ICON = '' + const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="combobox"]' const SELECTOR_MENU = '.menu' const SELECTOR_MENU_ITEM = '.menu-item[data-bs-value]' @@ -52,8 +52,19 @@ const SELECTOR_VALUE = '.combobox-value' const SELECTOR_SEARCH_INPUT = '.combobox-search-input' const SELECTOR_NO_RESULTS = '.combobox-no-results' +class ComboboxMenu extends Menu { + override show(focus?: () => void): Promise { + return this._show(focus) + } +} + type ComboboxConfig = { + allowCustom: boolean + createOnBlur: boolean + maxItems: number | null + separator: string | null boundary: string | Element + input: string | HTMLInputElement | null multiple: boolean name: string | null offset: FloatingOffsetOption @@ -64,7 +75,12 @@ type ComboboxConfig = { } const Default: ComboboxConfig = { + allowCustom: false, + createOnBlur: false, + maxItems: null, + separator: null, boundary: 'clippingParents', + input: null, multiple: false, name: null, offset: [0, 2], @@ -75,7 +91,12 @@ const Default: ComboboxConfig = { } const DefaultType = { + allowCustom: 'boolean', + createOnBlur: 'boolean', + maxItems: '(number|null)', + separator: '(string|null)', boundary: '(string|element)', + input: '(null|element)', multiple: 'boolean', name: '(string|null)', offset: '(array|string|function)', @@ -97,22 +118,108 @@ class Combobox extends BaseComponent { protected declare _searchInput: HTMLInputElement | null protected declare _noResults: HTMLElement | null protected declare _hiddenInput: HTMLInputElement | null - protected declare _menuInstance: Menu | null + protected declare _menuInstance: ComboboxMenu | null + protected declare _ownsInput: boolean + protected declare _inputDisabled: boolean + protected declare _extraInputs: HTMLInputElement[] + protected declare _initialSelection: HTMLElement[] + protected declare _form: HTMLFormElement | null + protected declare _formObserver: MutationObserver + protected declare _submitHandler: () => void + protected declare _resetTimeouts: Set + protected declare _resetHandler: (event: BootstrapEvent) => void + protected declare _menuEventHandlers: Map void> + protected declare _changeId: number + protected declare _editor: HTMLInputElement | null + protected declare _activeItem: HTMLElement | null + protected declare _chips: Map + protected declare _selectedChips: Set + protected declare _anchorChip: HTMLElement | null + protected declare _focusingChip: boolean + protected declare _composing: boolean + protected declare _query: string | null + protected declare _ownsMenu: boolean + protected declare _status: HTMLElement | null + protected declare _menuMinWidth: string + protected declare _attributes: Map> constructor(element?: string | Element | null, config?: Partial | null) { super(element, config) - this._toggle = this._element - this._menu = SelectorEngine.next(this._toggle, SELECTOR_MENU)[0] as HTMLElement + this._editor = this._element.matches('input') ? + this._element as HTMLInputElement : + SelectorEngine.findOne('.combobox-input, .form-ghost', this._element) + if (this._editor === this._element && this._config.multiple) { + throw new TypeError('COMBOBOX: Multiple selection requires a wrapping element.') + } + + this._toggle = this._editor ?? this._element + const field = this._editor && !this._element.matches('input') ? this._element : this._toggle + this._menu = SelectorEngine.next(field, SELECTOR_MENU)[0] as HTMLElement + this._ownsMenu = !this._menu && Boolean(this._editor) + if (this._ownsMenu) { + this._menu = document.createElement('div') + this._menu.className = 'menu' + field.after(this._menu) + } + + this._menuMinWidth = this._menu.style.minWidth this._valueDisplay = SelectorEngine.findOne(SELECTOR_VALUE, this._toggle)! - this._searchInput = SelectorEngine.findOne(SELECTOR_SEARCH_INPUT, this._menu) + this._searchInput = this._editor ?? SelectorEngine.findOne(SELECTOR_SEARCH_INPUT, this._menu) this._noResults = SelectorEngine.findOne(SELECTOR_NO_RESULTS, this._menu) + this._activeItem = null + this._chips = new Map() + this._selectedChips = new Set() + this._anchorChip = null + this._focusingChip = false + this._composing = false + this._query = null + this._status = null + this._attributes = new Map() + if (this._editor) { + this._setupEditor() + } + this._hiddenInput = null this._menuInstance = null + this._ownsInput = false + this._inputDisabled = false + this._extraInputs = [] + this._initialSelection = this._getSelectedItems() + this._form = null + this._menuEventHandlers = new Map() + this._changeId = 0 + this._formObserver = new MutationObserver(records => { + this._readInputDisabled(records) + this.update() + }) + this._submitHandler = () => this.update() + this._resetTimeouts = new Set() + this._resetHandler = event => { + // Trusted reset clicks can run microtasks before the native default action. + const timeout = window.setTimeout(() => { + this._resetTimeouts.delete(timeout) + if (!this._element || event.defaultPrevented || event.target !== this._form) { + return + } + + const selected = new Set(this._initialSelection) + for (const item of SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu)) { + item.classList.toggle(CLASS_NAME_SELECTED, selected.has(item)) + setAriaAttribute(item, 'aria-selected', selected.has(item)) + } + + this._query = null + this._selectedChips.clear() + this._anchorChip = null + this.update() + }) + this._resetTimeouts.add(timeout) + } this._createHiddenInput() this._createMenuInstance() - this._syncInitialSelection() + this.update() this._addEventListeners() } @@ -134,52 +241,79 @@ class Combobox extends BaseComponent { return this._isShown() ? this.hide() : this.show() } - async show(): Promise { - if (isDisabled(this._toggle) || this._isShown()) { - return - } - - const showEvent = EventHandler.trigger(this._toggle, EVENT_SHOW) - if (showEvent.defaultPrevented) { - return - } - - this._menuInstance!.show() - - if (this._searchInput) { - this._searchInput.value = '' - this._filterItems('') - requestAnimationFrame(() => this._searchInput!.focus()) - } - - EventHandler.trigger(this._toggle, EVENT_SHOWN) + show(): Promise { + return this._showMenu() } async hide(): Promise { - if (!this._isShown()) { - return - } + await this._menuInstance!.hide() + } - const hideEvent = EventHandler.trigger(this._toggle, EVENT_HIDE) - if (hideEvent.defaultPrevented) { - return + update(): void { + this._changeId++ + this._readInputDisabled(this._formObserver.takeRecords()) + this._syncOptionRoles() + this._updateToggleText() + this._updateHiddenInput() + this._observeFormState() + if (this._editor && this._activeItem && !this._getVisibleItems().includes(this._activeItem)) { + this._setActiveItem(null) } - - this._menuInstance!.hide() - EventHandler.trigger(this._toggle, EVENT_HIDDEN) } override dispose(): void { + this._resetTimeouts.forEach(timeout => clearTimeout(timeout)) + this._readInputDisabled(this._formObserver.takeRecords()) + this._formObserver.disconnect() + EventHandler.off(this._form, `reset${EVENT_KEY}`, this._resetHandler) + EventHandler.off(this._form, `submit${EVENT_KEY}`, this._submitHandler) + + for (const [event, handler] of this._menuEventHandlers) { + EventHandler.off(this._toggle, event, handler) + } + + this._removeExtraInputs() + if (this._hiddenInput && !this._ownsInput) { + this._hiddenInput.disabled = this._inputDisabled + } + if (this._menuInstance) { this._menuInstance.dispose() this._menuInstance = null } - if (this._hiddenInput) { + if (this._hiddenInput && this._ownsInput) { this._hiddenInput.remove() this._hiddenInput = null } + for (const chip of this._chips.values()) { + chip.remove() + } + + if (this._editor) { + this._editor.classList.remove(CLASS_NAME_SHOW) + this._element.classList.remove(CLASS_NAME_SHOW) + this._menu.classList.remove(CLASS_NAME_SHOW) + this._activeItem?.classList.remove('active') + } + + this._status?.remove() + this._menu.style.minWidth = this._menuMinWidth + for (const [element, attributes] of this._attributes) { + for (const [name, value] of attributes) { + if (value === null) { + element.removeAttribute(name) + } else { + element.setAttribute(name, value) + } + } + } + + if (this._ownsMenu) { + this._menu.remove() + } + EventHandler.off(this._menu, EVENT_KEY) EventHandler.off(this._toggle, EVENT_KEY) EventHandler.off(this._searchInput, EVENT_KEY) @@ -187,45 +321,820 @@ class Combobox extends BaseComponent { super.dispose() } + getValues(): string[] { + return this._getSelectedItems().map(item => item.dataset.bsValue ?? '') + } + + add(value: string): HTMLElement | null { + if (this._isDisabled() || (this._config.multiple && this._config.maxItems !== null && this.getValues().length >= this._config.maxItems)) { + return null + } + + let item = SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu).find(option => option.dataset.bsValue === value) + if (!item && this._config.allowCustom && value.trim()) { + item = document.createElement('button') + item.setAttribute('type', 'button') + item.className = 'menu-item' + item.dataset.bsValue = value + item.textContent = value + this._menu.append(item) + } + + if (!item || item.classList.contains(CLASS_NAME_SELECTED) || isDisabled(item)) { + return null + } + + this._selectItem(item) + return this._element && item.classList.contains(CLASS_NAME_SELECTED) ? this._chips.get(item) ?? item : null + } + + remove(value: string | HTMLElement): boolean { + const item = this._getSelectedItems().find(option => typeof value === 'string' ? option.dataset.bsValue === value : option === value || this._chips.get(option) === value) + if (!item || isDisabled(item) || this._isDisabled()) { + return false + } + + return this._removeItems([item]) + } + + clear(): void { + this._clearSelection(null) + } + + protected _clearSelection(query: string | null): void { + this._removeItems(this._getSelectedItems(), query) + } + + focus(): void { + this._toggle?.focus() + } + + getSelectedValues(): string[] { + return this._getSelectedItems() + .filter(item => this._selectedChips.has(this._chips.get(item)!)) + .map(item => item.dataset.bsValue ?? '') + } + + selectChip(chip: HTMLElement, options: { addToSelection?: boolean, rangeSelect?: boolean } = {}): void { + const chips = this._getChipElements() + if (this._isDisabled() || !chips.includes(chip)) { + return + } + + const previous = new Set(this._selectedChips) + const { addToSelection = false, rangeSelect = false } = options + if (rangeSelect && this._anchorChip && chips.includes(this._anchorChip)) { + const anchor = chips.indexOf(this._anchorChip) + const target = chips.indexOf(chip) + if (!addToSelection) { + this._selectedChips.clear() + } + + for (let index = Math.min(anchor, target); index <= Math.max(anchor, target); index++) { + this._selectedChips.add(chips[index]) + } + } else if (addToSelection) { + if (this._selectedChips.has(chip)) { + this._selectedChips.delete(chip) + } else { + this._selectedChips.add(chip) + this._anchorChip = chip + } + } else { + this._selectedChips = new Set([chip]) + this._anchorChip = chip + } + + if (previous.size !== this._selectedChips.size || [...previous].some(element => !this._selectedChips.has(element))) { + this._notifyChipSelection() + } + } + + clearSelection(): void { + this._anchorChip = null + if (!this._selectedChips.size) { + return + } + + this._selectedChips.clear() + this._notifyChipSelection() + } + + removeSelected(): boolean { + const chips = this._getChipElements() + const active = (document.activeElement as HTMLElement | null)?.closest('.chip') + const index = Math.max(0, chips.indexOf(active!)) + const items = this._getSelectedItems().filter(item => this._selectedChips.has(this._chips.get(item)!)) + const changed = this._removeItems(items) + if (changed && this._element) { + const remaining = this._getChipElements() + const target = remaining[Math.min(index, remaining.length - 1)] + if (target) { + this._focusChip(target) + } else { + this._editor!.focus() + } + } + + return changed + } + + protected _getChipElements(): HTMLElement[] { + return this._getSelectedItems() + .filter(item => !isDisabled(item)) + .map(item => this._chips.get(item)) + .filter((chip): chip is HTMLElement => Boolean(chip)) + } + + protected _syncChipSelection(): void { + for (const chip of this._chips.values()) { + const selected = this._selectedChips.has(chip) + chip.classList.toggle('active', selected) + if (selected) { + chip.setAttribute('aria-description', 'Selected for removal') + } else { + chip.removeAttribute('aria-description') + } + } + } + + protected _notifyChipSelection(): void { + this._syncChipSelection() + const items = this._getSelectedItems().filter(item => this._selectedChips.has(this._chips.get(item)!)) + const selected = items.map(item => item.dataset.bsValue ?? '') + if (this._status) { + this._status.textContent = selected.length ? `${selected.length} chip${selected.length === 1 ? '' : 's'} selected for removal` : 'Chip selection cleared' + } + + EventHandler.trigger(this._element, `select${EVENT_KEY}`, { selected, items }) + } + + protected _focusChip(chip: HTMLElement, options: { addToSelection?: boolean, rangeSelect?: boolean } = {}): void { + this.selectChip(chip, options) + if (!this._element) { + return + } + + this.hide() + if (this._element) { + this._focusSelectedChip(chip) + } + } + + protected _focusSelectedChip(chip: HTMLElement): void { + this._focusingChip = true + try { + chip.focus() + } finally { + if (this._element) { + this._focusingChip = false + } + } + } + + protected _selectAllChips(): void { + const chips = this._getChipElements() + if (!chips.length) { + return + } + + this._selectedChips = new Set(chips) + this._anchorChip ??= chips[0] + this._notifyChipSelection() + } + + protected _removeItems(items: HTMLElement[], query: string | null = null): boolean { + if (this._isDisabled() || !items.length) { + return false + } + + const allowed: HTMLElement[] = [] + const changeId = this._changeId + for (const item of items) { + if (isDisabled(item)) { + continue + } + + const event = EventHandler.trigger(this._element, `remove${EVENT_KEY}`, { value: item.dataset.bsValue, item }) + if (!this._element || changeId !== this._changeId) { + return false + } + + if (!event.defaultPrevented) { + allowed.push(item) + } + } + + for (const item of allowed) { + item.classList.remove(CLASS_NAME_SELECTED) + setAriaAttribute(item, 'aria-selected', false) + } + + if (allowed.length) { + this._selectionChanged(allowed.length === 1 ? allowed[0] : null, query) + } + + return allowed.length > 0 + } + // Private + protected _isDisabled(): boolean { + return isDisabled(this._element) || isDisabled(this._toggle) || this._toggle.matches(':disabled') + } + + protected _setAttribute(element: Element, name: string, value: string): void { + if (!this._attributes.has(element)) { + this._attributes.set(element, new Map()) + } + + const attributes = this._attributes.get(element)! + if (!attributes.has(name)) { + attributes.set(name, element.getAttribute(name)) + } + + element.setAttribute(name, value) + } + + protected _syncOptionRoles(): void { + if (!this._menu.id) { + this._setAttribute(this._menu, 'id', getUID('combobox-')) + } + + this._setAttribute(this._toggle, 'aria-controls', this._menu.id) + this._setAttribute(this._toggle, 'aria-haspopup', 'listbox') + this._setAttribute(this._menu, 'role', 'listbox') + if (this._config.multiple) { + this._setAttribute(this._menu, 'aria-multiselectable', 'true') + } + + for (const item of SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu)) { + this._setAttribute(item, 'role', 'option') + this._setAttribute(item, 'aria-selected', String(item.classList.contains(CLASS_NAME_SELECTED))) + } + } + + protected _setupEditor(): void { + const editor = this._editor! + if (this._config.placeholder && !editor.placeholder) { + this._setAttribute(editor, 'placeholder', this._config.placeholder) + } + + if (!this._menu.id) { + this._setAttribute(this._menu, 'id', getUID('combobox-')) + } + + this._setAttribute(editor, 'role', 'combobox') + this._setAttribute(editor, 'aria-autocomplete', 'list') + this._setAttribute(editor, 'aria-expanded', 'false') + this._setAttribute(editor, 'aria-controls', this._menu.id) + this._setAttribute(editor, 'autocomplete', 'off') + this._setAttribute(editor, 'aria-activedescendant', '') + editor.removeAttribute('aria-activedescendant') + this._setAttribute(this._menu, 'role', 'listbox') + if (this._config.multiple) { + this._setAttribute(this._menu, 'aria-multiselectable', 'true') + } + + this._status = document.createElement('span') + this._status.className = 'visually-hidden' + this._status.setAttribute('role', 'status') + this._menu.after(this._status) + } + + protected _getItemLabel(item: HTMLElement): string { + const label = SelectorEngine.findOne('.menu-item-content > span:first-child', item) + return label?.textContent ?? item.textContent!.trim() + } + + protected _renderEditor(): void { + const editor = this._editor! + const selected = this._getSelectedItems() + const selectedSet = new Set(selected) + for (const [item, chip] of this._chips) { + if (!selectedSet.has(item)) { + chip.remove() + this._chips.delete(item) + this._selectedChips.delete(chip) + if (this._anchorChip === chip) { + this._anchorChip = null + } + } + } + + for (const item of SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu)) { + if (!item.id) { + this._setAttribute(item, 'id', getUID('combobox-option-')) + } + + this._setAttribute(item, 'tabindex', '-1') + } + + if (!this._config.multiple) { + const value = this._query ?? (selected.length ? this._getItemLabel(selected[0]) : '') + if (editor.value !== value) { + editor.value = value + } + + return + } + + const inputBeforeEditor = this._hiddenInput?.parentElement === editor.parentElement && this._hiddenInput.compareDocumentPosition(editor) === Node.DOCUMENT_POSITION_FOLLOWING + let next: Element = inputBeforeEditor ? this._hiddenInput! : editor + for (let index = selected.length - 1; index >= 0; index--) { + const item = selected[index] + let chip = this._chips.get(item) + const label = this._getItemLabel(item) + if (!chip) { + chip = document.createElement('span') + chip.className = 'chip' + chip.tabIndex = -1 + const text = document.createElement('span') + const button = document.createElement('button') + button.type = 'button' + button.className = 'chip-dismiss' + button.innerHTML = DISMISS_ICON + chip.append(text, button) + this._chips.set(item, chip) + } + + this._updateChipState(item, chip, label) + if (chip.nextElementSibling !== next) { + next.before(chip) + } + + next = chip + } + + this._syncChipSelection() + const value = this._query ?? '' + if (editor.value !== value) { + editor.value = value + } + + this._menuInstance?.update() + } + + protected _updateChipState(item: HTMLElement, chip: HTMLElement, label: string): void { + chip.firstElementChild!.textContent = label + const button = chip.lastElementChild as HTMLButtonElement + button.setAttribute('aria-label', `Remove ${label}`) + button.disabled = this._isDisabled() || isDisabled(item) + chip.setAttribute('role', 'group') + chip.setAttribute('aria-label', label) + chip.classList.toggle('disabled', button.disabled) + if (button.disabled) { + chip.setAttribute('aria-disabled', 'true') + this._selectedChips.delete(chip) + if (this._anchorChip === chip) { + this._anchorChip = null + } + } else { + chip.removeAttribute('aria-disabled') + } + } + + protected _setActiveItem(item: HTMLElement | null): void { + this._activeItem?.classList.remove('active') + this._activeItem = item + if (!item) { + this._editor!.removeAttribute('aria-activedescendant') + return + } + + item.classList.add('active') + this._editor!.setAttribute('aria-activedescendant', item.id) + item.scrollIntoView({ block: 'nearest' }) + } + + protected _addEditorListeners(): void { + const editor = this._editor! + EventHandler.on(this._menu, `mousedown${EVENT_KEY}`, SELECTOR_MENU_ITEM, event => event.preventDefault()) + EventHandler.on(editor, `input${EVENT_KEY}`, event => { + if (this._composing || event.isComposing) { + this._query = editor.value + return + } + + if (this._isDisabled()) { + return + } + + this._handleEditorInput() + }) + EventHandler.on(editor, `compositionstart${EVENT_KEY}`, () => { + this._composing = true + }) + EventHandler.on(editor, `compositionend${EVENT_KEY}`, () => { + this._composing = false + if (this._element && !this._isDisabled()) { + this._handleEditorInput(document.activeElement === editor) + } + }) + EventHandler.on(editor, `paste${EVENT_KEY}`, event => { + const { separator, allowCustom } = this._config + const text = event.clipboardData?.getData('text') ?? '' + if (!allowCustom || !separator || !text.includes(separator) || this._isDisabled()) { + return + } + + event.preventDefault() + for (const value of text.split(separator)) { + this.add(value.trim()) + if (!this._element) { + return + } + } + }) + EventHandler.on(editor, `blur${EVENT_KEY}`, event => { + if (!this._composing && this._config.allowCustom && this._config.createOnBlur && !(event.relatedTarget as Element | null)?.closest('.chip, .menu')) { + this.add(editor.value.trim()) + } + }) + EventHandler.on(editor, `focus${EVENT_KEY}`, () => this.clearSelection()) + EventHandler.on(this._element, `mousedown${EVENT_KEY}`, '.chip', event => { + // The click handler owns modifier selection and focus on the chip body. + if (!(event.target as Element).closest('.chip-dismiss')) { + event.preventDefault() + } + }) + EventHandler.on(this._element, `focusin${EVENT_KEY}`, '.chip', event => { + if (this._focusingChip || this._isDisabled()) { + return + } + + const chip = (event.target as Element).closest('.chip')! + if (!this._selectedChips.has(chip)) { + this.selectChip(chip) + } + + if (this._element) { + this.hide() + } + }) + EventHandler.on(this._element, `click${EVENT_KEY}`, '.chip', event => { + if ((event.target as Element).closest('.chip-dismiss') || this._isDisabled()) { + return + } + + event.preventDefault() + event.stopPropagation() + const chip = (event.target as Element).closest('.chip')! + this._focusChip(chip, { addToSelection: event.metaKey || event.ctrlKey, rangeSelect: event.shiftKey }) + }) + EventHandler.on(this._element, `keydown${EVENT_KEY}`, '.chip', event => this._handleChipKeydown(event)) + EventHandler.on(this._element, `click${EVENT_KEY}`, '.chip-dismiss', event => { + event.preventDefault() + event.stopPropagation() + const chip = (event.target as Element).closest('.chip')! + this.remove(chip) + if (this._element) { + editor.focus() + } + }) + } + + protected _handleEditorInput(openMenu = true): void { + const editor = this._editor! + let query = editor.value + if (this._config.allowCustom && this._config.separator && query.includes(this._config.separator)) { + const parts = query.split(this._config.separator) + query = parts.pop()! + for (const part of parts) { + this.add(part.trim()) + if (!this._element) { + return + } + } + } + + // A changed visible label must not submit an old single-selection value. + if (!this._config.multiple && this._getSelectedItems().length) { + this._clearSelection(query) + if (!this._element) { + return + } + + if (this._getSelectedItems().length) { + this._query = null + this._renderEditor() + return + } + } + + this._query = query + if (editor.value !== query) { + editor.value = query + } + + this._filterItems(query) + this._setActiveItem(null) + if (openMenu && this._getVisibleItems().length) { + this.show() + } else { + this.hide() + } + } + + protected _handleEditorKeydown(event: BootstrapEvent): void { + if (this._composing || event.isComposing || event.keyCode === 229 || this._isDisabled()) { + return + } + + const editor = this._editor! + if ([ARROW_DOWN_KEY, ARROW_UP_KEY].includes(event.key)) { + event.preventDefault() + const items = this._getVisibleItems() + if (items.length) { + const item = getNextActiveElement(items, this._activeItem!, event.key === ARROW_DOWN_KEY, true) + this.show() + if (this._element) { + this._setActiveItem(item) + } + } + + return + } + + if (event.key === ENTER_KEY) { + if (this._activeItem && this._isShown()) { + event.preventDefault() + this._selectItem(this._activeItem) + } else if (this._config.allowCustom && editor.value.trim()) { + event.preventDefault() + this.add(editor.value.trim()) + } + + return + } + + if (event.key === ESCAPE_KEY || event.key === TAB_KEY) { + if (event.key === ESCAPE_KEY && this._isShown()) { + event.preventDefault() + } + + this.hide() + if (this._element) { + this._setActiveItem(null) + } + + return + } + + this._handleEditorChipFocus(event) + } + + protected _handleEditorChipFocus(event: BootstrapEvent): void { + const editor = this._editor! + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a' && !editor.value) { + const chips = this._getChipElements() + if (chips.length) { + event.preventDefault() + this._selectAllChips() + if (this._element) { + this.hide() + if (this._element) { + this._focusSelectedChip(chips.at(-1)!) + } + } + } + + return + } + + if (event.metaKey || event.ctrlKey || event.altKey) { + return + } + + const rtl = getComputedStyle(editor).direction === 'rtl' + const previousKey = rtl ? 'ArrowRight' : 'ArrowLeft' + const backwardDelete = ['Backspace', 'Delete'].includes(event.key) && !editor.value + const atStart = event.key === previousKey && editor.selectionStart === 0 && editor.selectionEnd === 0 + if (backwardDelete || atStart) { + const chip = this._getChipElements().at(-1) + if (chip) { + event.preventDefault() + this._focusChip(chip, { addToSelection: event.shiftKey }) + } + } + } + + protected _handleChipKeydown(event: BootstrapEvent): void { + if (this._composing || event.isComposing || event.keyCode === 229 || this._isDisabled()) { + return + } + + const chip = (event.target as Element).closest('.chip')! + const chips = this._getChipElements() + const index = chips.indexOf(chip) + if (index === -1) { + return + } + + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a') { + event.preventDefault() + this._selectAllChips() + return + } + + if (['Backspace', 'Delete'].includes(event.key)) { + event.preventDefault() + this._deleteChipSelection(chip) + + return + } + + const rtl = getComputedStyle(this._editor!).direction === 'rtl' + if (['ArrowLeft', 'ArrowRight'].includes(event.key)) { + event.preventDefault() + const next = index + ((event.key === 'ArrowRight') === rtl ? -1 : 1) + if (next >= chips.length) { + this.clearSelection() + if (this._element) { + this._editor!.focus() + } + } else { + this._focusChip(chips[Math.max(0, next)], { rangeSelect: event.shiftKey }) + } + } else if (event.key === HOME_KEY || (event.key === END_KEY && event.shiftKey)) { + event.preventDefault() + const target = event.key === HOME_KEY ? chips[0] : chips.at(-1)! + this._focusChip(target, { rangeSelect: event.shiftKey }) + } else if ([END_KEY, ESCAPE_KEY].includes(event.key)) { + event.preventDefault() + this.clearSelection() + if (this._element) { + this._editor!.focus() + } + } + } + + protected _deleteChipSelection(chip: HTMLElement): void { + if (!this._selectedChips.has(chip)) { + this.selectChip(chip) + } + + if (this._element) { + this.removeSelected() + } + } + protected _isShown(): boolean { return this._menu.classList.contains(CLASS_NAME_SHOW) } + protected override _configAfterMerge(config: ComponentConfig): ComponentConfig { + if (config.maxItems !== null && (!Number.isSafeInteger(config.maxItems) || config.maxItems < 1)) { + throw new TypeError('COMBOBOX: Option "maxItems" must be a positive integer or null.') + } + + if (config.input !== null) { + const input = getElement(config.input) + if (!(input instanceof HTMLInputElement) || input.type !== 'hidden') { + throw new TypeError('COMBOBOX: Option "input" must reference a hidden input.') + } + + config.input = input + } + + return config + } + protected _createHiddenInput(): void { - const { name } = this._config - if (!name) { + if (this._config.input) { + this._hiddenInput = this._config.input as HTMLInputElement + this._inputDisabled = this._hiddenInput.disabled + return + } + + if (!this._config.name) { return } this._hiddenInput = document.createElement('input') this._hiddenInput.type = 'hidden' - this._hiddenInput.name = name - this._hiddenInput.value = '' - this._toggle.parentNode!.insertBefore(this._hiddenInput, this._toggle) + this._hiddenInput.name = this._config.name + const anchor = this._editor ? this._element : this._toggle + anchor.before(this._hiddenInput) + this._ownsInput = true } - protected _createMenuInstance(): void { - this._menuInstance = new Menu(this._toggle, { - menu: this._menu, - autoClose: this._config.multiple ? 'outside' : true, - boundary: this._config.boundary, - offset: this._config.offset, - placement: this._config.placement - }) + protected _removeExtraInputs(): void { + for (const input of this._extraInputs) { + input.remove() + } + + this._extraInputs = [] } - protected _syncInitialSelection(): void { - const selectedItems = this._getSelectedItems() - if (selectedItems.length > 0) { - this._updateToggleText() - this._updateHiddenInput() - } else { - this._showPlaceholder() + protected _readInputDisabled(records: MutationRecord[]): void { + if (!this._ownsInput && records.some(record => record.target === this._hiddenInput && record.attributeName === 'disabled')) { + this._inputDisabled = this._hiddenInput!.disabled } } + protected _observeFormState(): void { + this._formObserver.disconnect() + if (this._element !== this._toggle) { + this._formObserver.observe(this._element, { attributes: true, attributeFilter: ['class'] }) + } + + this._formObserver.observe(this._toggle, { attributes: true, attributeFilter: ['disabled', 'class', 'form'] }) + if (this._hiddenInput) { + this._formObserver.observe(this._hiddenInput, { attributes: true, attributeFilter: ['disabled', 'name', 'form'] }) + } + + // Watch only relevant fieldset ancestors, not every mutation in the document. + const fieldsets = new Set() + for (const element of [this._toggle, this._hiddenInput]) { + for (let parent = element?.parentElement; parent; parent = parent.parentElement) { + if (parent.matches('fieldset')) { + fieldsets.add(parent) + } + } + } + + for (const fieldset of fieldsets) { + this._formObserver.observe(fieldset, { attributes: true, attributeFilter: ['disabled'] }) + } + + const form = this._hiddenInput ? + this._hiddenInput.form : + (this._toggle instanceof HTMLInputElement || this._toggle instanceof HTMLButtonElement ? + this._toggle.form : + this._toggle.closest('form')) + if (form !== this._form) { + EventHandler.off(this._form, `reset${EVENT_KEY}`, this._resetHandler) + EventHandler.off(this._form, `submit${EVENT_KEY}`, this._submitHandler) + this._form = form + EventHandler.on(this._form, `reset${EVENT_KEY}`, this._resetHandler) + EventHandler.on(this._form, `submit${EVENT_KEY}`, this._submitHandler) + } + } + + protected async _showMenu(focus?: () => void): Promise { + if (this._isDisabled() || this._isShown() || (this._editor && !this._getVisibleItems().length)) { + return + } + + const search = this._editor || isDisabled(this._searchInput) ? null : this._searchInput + await this._menuInstance!.show(focus ?? (search ? () => search.focus({ preventScroll: true }) : undefined)) + } + + protected _createMenuInstance(): void { + this._menuInstance = new ComboboxMenu(this._toggle, { + menu: this._menu, + reference: this._editor ? this._element : 'toggle', + autoClose: this._config.multiple ? 'outside' : true, + boundary: this._config.boundary, + offset: this._config.offset, + placement: this._config.placement, + floatingConfig: this._editor ? + config => ({ + ...config, + middleware: [...config.middleware, { + name: 'comboboxSize', + fn: ({ elements, rects }: MiddlewareState) => { + if (this._element) { + elements.floating.style.minWidth = `${rects.reference.width}px` + } + + return {} + } + }] + }) : + null + }) + } + protected _addEventListeners(): void { + // Menu owns transitions and also handles outside clicks and delegated keys. + for (const type of ['show', 'shown', 'hide', 'hidden']) { + const event = Menu.eventName(type) + const handler = (menuEvent: BootstrapEvent) => { + if (!this._element) { + return + } + + if (type === 'hidden' && this._editor) { + this._setActiveItem(null) + } + + const forwarded = EventHandler.trigger(this._element, this.constructor.eventName(type)) + if (forwarded?.defaultPrevented || !this._element) { + menuEvent.preventDefault() + return + } + + if (type === 'show' && !menuEvent.defaultPrevented && this._searchInput && !this._editor) { + this._searchInput.value = '' + this._filterItems('') + } + } + + this._menuEventHandlers.set(event, handler) + EventHandler.on(this._toggle, event, handler) + } + EventHandler.on(this._menu, `click${EVENT_KEY}`, SELECTOR_MENU_ITEM, event => { const item = (event.target as Element).closest(SELECTOR_MENU_ITEM) if (!item || isDisabled(item)) { @@ -238,19 +1147,39 @@ class Combobox extends BaseComponent { }) EventHandler.on(this._toggle, `keydown${EVENT_KEY}`, event => { - this._handleToggleKeydown(event) + if (this._editor) { + this._handleEditorKeydown(event) + } else { + this._handleToggleKeydown(event) + } }) EventHandler.on(this._menu, `keydown${EVENT_KEY}`, event => { this._handleMenuKeydown(event) }) + if (this._editor) { + this._addEditorListeners() + return + } + if (this._searchInput) { + EventHandler.on(this._toggle, `mousedown${EVENT_KEY}`, event => { + if (event.button === 0 && !this._isShown() && !this._isDisabled() && !isDisabled(this._searchInput)) { + // The search field receives focus when the menu opens on click. + event.preventDefault() + } + }) + EventHandler.on(this._searchInput, `input${EVENT_KEY}`, () => { this._filterItems(this._searchInput!.value) }) EventHandler.on(this._searchInput, `keydown${EVENT_KEY}`, event => { + if (event.isComposing || event.keyCode === 229) { + return + } + if (event.key === ARROW_DOWN_KEY) { event.preventDefault() const items = this._getVisibleItems() @@ -261,46 +1190,90 @@ class Combobox extends BaseComponent { if (event.key === ESCAPE_KEY) { this.hide() - this._toggle.focus() + this._toggle?.focus() } }) } } protected _selectItem(item: HTMLElement): void { + if (this._isDisabled() || isDisabled(item) || !this._menu.contains(item)) { + return + } + + const previous = this._getSelectedItems() + if (this._config.multiple && !previous.includes(item) && this._config.maxItems !== null && previous.length >= this._config.maxItems) { + return + } + + if (!this._config.multiple && previous.length === 1 && previous[0] === item) { + return + } + + const changeId = this._changeId + const type = this._config.multiple && previous.includes(item) ? 'remove' : 'add' + const event = EventHandler.trigger(this._element, `${type}${EVENT_KEY}`, { value: item.dataset.bsValue, item }) + if (!this._element || event.defaultPrevented || changeId !== this._changeId || this._isDisabled() || isDisabled(item) || !this._menu.contains(item)) { + return + } + if (this._config.multiple) { item.classList.toggle(CLASS_NAME_SELECTED) setAriaAttribute(item, 'aria-selected', item.classList.contains(CLASS_NAME_SELECTED)) } else { - const previouslySelected = SelectorEngine.find(`.${CLASS_NAME_SELECTED}`, this._menu) - for (const prev of previouslySelected) { - prev.classList.remove(CLASS_NAME_SELECTED) - prev.setAttribute('aria-selected', 'false') + for (const selected of previous) { + selected.classList.remove(CLASS_NAME_SELECTED) + selected.setAttribute('aria-selected', 'false') } item.classList.add(CLASS_NAME_SELECTED) item.setAttribute('aria-selected', 'true') } - this._updateToggleText() - this._updateHiddenInput() + this._selectionChanged(item) + } - const value = this._config.multiple ? - this._getSelectedItems().map(el => el.dataset.bsValue) : - item.dataset.bsValue + protected _selectionChanged(item: HTMLElement | null, query: string | null = null): void { + this._query = query + this.update() + const changeId = this._changeId + const { multiple } = this._config + const values = this.getValues() + const value = multiple ? values : values[0] ?? '' + const target = this._hiddenInput ?? this._element - EventHandler.trigger(this._toggle, EVENT_CHANGE, { - value, - item - }) + for (const event of ['input', 'change']) { + EventHandler.trigger(target, event) + if (!this._element || changeId !== this._changeId) { + return + } + } - if (!this._config.multiple) { + EventHandler.trigger(this._element, EVENT_CHANGE, { value, item }) + if (!this._element || changeId !== this._changeId) { + return + } + + if (this._editor) { + this._setActiveItem(null) + this._filterItems('') + if (this._status) { + this._status.textContent = `${values.length} selected` + } + } + + if (!multiple && query === null) { this.hide() - this._toggle.focus() + this._toggle?.focus() } } protected _updateToggleText(): void { + if (this._editor) { + this._renderEditor() + return + } + const selectedItems = this._getSelectedItems() if (selectedItems.length === 0) { @@ -321,29 +1294,97 @@ class Combobox extends BaseComponent { protected _showPlaceholder(): void { const { placeholder } = this._config - if (placeholder) { - this._valueDisplay.textContent = placeholder - this._valueDisplay.classList.add(CLASS_NAME_PLACEHOLDER) - } + this._valueDisplay.textContent = placeholder + this._valueDisplay.classList.toggle(CLASS_NAME_PLACEHOLDER, Boolean(placeholder)) } protected _updateHiddenInput(): void { - if (!this._hiddenInput) { + const input = this._hiddenInput + if (!input) { return } - const selectedItems = this._getSelectedItems() - const values = selectedItems.map(el => el.dataset.bsValue) - this._hiddenInput.value = this._config.multiple ? values.join(',') : (values[0] || '') + const selected = this._getSelectedItems() + const values = selected + .filter(item => !isDisabled(item)) + .map(item => item.dataset.bsValue ?? '') + const submittedValues = this._config.multiple ? values : [values[0] ?? ''] + const disabled = this._inputDisabled || this._isDisabled() || (selected.length > 0 && values.length === 0) + + if (this._ownsInput) { + const anchor = this._editor ? this._element : this._toggle + const fields = [input, ...this._extraInputs] + if (fields.at(-1)!.nextElementSibling !== anchor) { + for (const field of fields) { + anchor.before(field) + } + } + + const form = this._toggle.getAttribute('form') + if (form === null) { + input.removeAttribute('form') + } else { + input.setAttribute('form', form) + } + } + + input.value = submittedValues[0] ?? '' + input.disabled = disabled || submittedValues.length === 0 + + for (let index = 1; index < submittedValues.length; index++) { + let extra = this._extraInputs[index - 1] + if (!extra) { + extra = document.createElement('input') + extra.type = 'hidden' + this._extraInputs.push(extra) + } + + const previous = this._extraInputs[index - 2] ?? input + if (!previous.parentNode) { + extra.remove() + } else if (extra.previousElementSibling !== previous) { + previous.after(extra) + } + + extra.name = input.name + extra.value = submittedValues[index] + extra.disabled = disabled + const form = input.getAttribute('form') + if (form === null) { + extra.removeAttribute('form') + } else { + extra.setAttribute('form', form) + } + } + + for (const extra of this._extraInputs.splice(Math.max(0, submittedValues.length - 1))) { + extra.remove() + } + + // Discard our own disabled/form/name writes before observing caller changes. + this._formObserver.takeRecords() } protected _getSelectedItems(): HTMLElement[] { - return SelectorEngine.find(`.${CLASS_NAME_SELECTED}`, this._menu) + return SelectorEngine.find(`${SELECTOR_MENU_ITEM}.${CLASS_NAME_SELECTED}`, this._menu) } protected _getVisibleItems(): HTMLElement[] { - return SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu) - .filter(item => isVisible(item)) + return SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(item => { + if (!this._editor) { + return isVisible(item) + } + + // A closed popup has no client rects; inspect the option and its groups. + for (let current: HTMLElement | null = item; current && current !== this._menu; current = current.parentElement) { + const style = getComputedStyle(current) + if (current.hidden || style.display === 'none' || style.visibility === 'hidden') { + return false + } + } + + return true + }) } protected _filterItems(query: string): void { @@ -374,23 +1415,37 @@ class Combobox extends BaseComponent { } protected _handleToggleKeydown(event: BootstrapEvent): void { + if (event.isComposing || event.keyCode === 229) { + return + } + const { key } = event if (key === ARROW_DOWN_KEY || key === ARROW_UP_KEY) { event.preventDefault() - if (!this._isShown()) { - this.show() + const focusItem = () => { + const items = this._getVisibleItems() + const item = key === ARROW_DOWN_KEY ? items[0] : items.at(-1) + const target = item ?? (isDisabled(this._searchInput) ? this._toggle : this._searchInput) + target?.focus() } - const items = this._getVisibleItems() - if (items.length > 0) { - const target = key === ARROW_DOWN_KEY ? items[0] : items.at(-1)! - target.focus() + if (this._isShown()) { + focusItem() + } else { + this._showMenu(focusItem) } return } + if (key === ESCAPE_KEY && this._isShown()) { + event.preventDefault() + event.stopPropagation() + this.hide() + return + } + if ((key === ENTER_KEY || key === SPACE_KEY) && !this._isShown()) { event.preventDefault() this.show() @@ -398,13 +1453,17 @@ class Combobox extends BaseComponent { } protected _handleMenuKeydown(event: BootstrapEvent): void { + if (event.isComposing || event.keyCode === 229) { + return + } + const { key, target } = event if (key === ESCAPE_KEY) { event.preventDefault() event.stopPropagation() this.hide() - this._toggle.focus() + this._toggle?.focus() return } @@ -425,7 +1484,7 @@ class Combobox extends BaseComponent { return } - if (key === HOME_KEY || key === END_KEY) { + if ((key === HOME_KEY || key === END_KEY) && !isInput) { event.preventDefault() const items = this._getVisibleItems() if (items.length > 0) { @@ -451,8 +1510,18 @@ class Combobox extends BaseComponent { */ EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) { + const instance = Combobox.getOrCreateInstance(this) + if (this.matches('input') || this.querySelector('.combobox-input, .form-ghost')) { + if (!(event.target as Element).closest('.chip')) { + instance.focus() + instance.show() + } + + return + } + event.preventDefault() - Combobox.getOrCreateInstance(this).toggle() + instance.toggle() }) onDocumentReady('DOMContentLoaded', () => { diff --git a/js/src/dom/event-handler.ts b/js/src/dom/event-handler.ts index 24715a9094..c3979868ea 100644 --- a/js/src/dom/event-handler.ts +++ b/js/src/dom/event-handler.ts @@ -62,6 +62,9 @@ const nativeEvents = new Set([ 'keypress', 'keyup', 'input', + 'compositionstart', + 'compositionupdate', + 'compositionend', 'paste', 'orientationchange', 'touchstart', @@ -94,7 +97,8 @@ const nativeEvents = new Set([ 'error', 'abort', 'scroll', - 'scrollend' + 'scrollend', + 'hashchange' ]) /** diff --git a/js/src/index.ts b/js/src/index.ts index e817a4f2df..2d5ce72094 100644 --- a/js/src/index.ts +++ b/js/src/index.ts @@ -17,7 +17,6 @@ export { default as NavOverflow } from './nav-overflow.js' export { default as Drawer } from './drawer.js' export { default as Strength } from './strength.js' export { default as OtpInput } from './otp-input.js' -export { default as Chips } from './chips.js' export { default as Popover } from './popover.js' export { default as Range } from './range.js' export { default as ScrollSpy } from './scrollspy.js' diff --git a/js/src/menu.ts b/js/src/menu.ts index 23e26f9e55..6c9c42b1d6 100644 --- a/js/src/menu.ts +++ b/js/src/menu.ts @@ -218,7 +218,11 @@ class Menu extends BaseComponent { return this._isShown() ? this.hide() : this.show() } - async show(): Promise { + show(): Promise { + return this._show() + } + + protected async _show(focus?: () => void): Promise { if (isDisabled(this._element) || this._isShown()) { return } @@ -242,7 +246,6 @@ class Menu extends BaseComponent { } } - this._element.focus({ focusVisible: false }) this._element.setAttribute('aria-expanded', 'true') this._menu.classList.add(CLASS_NAME_SHOW) @@ -253,6 +256,15 @@ class Menu extends BaseComponent { } Menu._openInstances.add(this) + if (focus) { + focus() + } else { + this._element.focus({ focusVisible: false }) + } + + if (!this._element || !this._isShown()) { + return + } // Wait for the CSS entry transition (opacity/transform) to finish before // announcing `shown`, so listeners run against the settled menu. @@ -1041,6 +1053,10 @@ class Menu extends BaseComponent { } static dataApiKeydownHandler(this: HTMLElement, event: BootstrapEvent): void { + if (event.isComposing || event.keyCode === 229) { + return + } + // Treat contenteditable hosts (e.g. rich-text editors) like inputs so the // menu doesn't hijack their arrow keys. const isInput = /input|textarea/i.test((event.target as HTMLElement).tagName) || (event.target as HTMLElement).isContentEditable diff --git a/js/src/range.ts b/js/src/range.ts index fd8c9b6030..0288cf1aa5 100644 --- a/js/src/range.ts +++ b/js/src/range.ts @@ -11,6 +11,10 @@ import SelectorEngine from './dom/selector-engine.js' import { onDocumentReady } from './util/component-functions.js' import type { ComponentConfig } from './util/config.js' +// Future consideration: opt-in clickable labels for sparse tick presets. +// Use real buttons with keyboard activation, visible focus, and usable targets. +// Keep decorative ticks as the default; do not add a tab stop for every tick. + /** * Constants */ @@ -23,9 +27,9 @@ const DATA_API_KEY = '.data-api' const EVENT_CHANGED = `changed${EVENT_KEY}` const EVENT_DOM_CONTENT_LOADED = `DOMContentLoaded${EVENT_KEY}${DATA_API_KEY}` -// `input` is not in EventHandler's native-event list, so it can't be namespaced; bind it raw const EVENT_INPUT = 'input' const EVENT_CHANGE = 'change' +const EVENT_RESET = 'reset' const SELECTOR_RANGE = '.form-range' const SELECTOR_INPUT = '.form-range-input' @@ -46,7 +50,7 @@ type RangeConfig = { const Default: RangeConfig = { bubble: false, // Show a value bubble above the thumb - formatter: null // (value) => string, for the bubble and tick labels + formatter: null // (value) => string, for the bubble } const DefaultType = { @@ -65,6 +69,10 @@ class Range extends BaseComponent { protected declare _bubbleText: HTMLElement | null protected declare _ticks: HTMLElement | null protected declare _updateHandler: () => void + protected declare _initialConfig: Partial + protected declare _form: HTMLFormElement | null + protected declare _resetHandler: (event: Event) => void + protected declare _resetTimeouts: Set constructor(element?: string | Element | null, config?: Partial | null) { super(element, config) @@ -84,11 +92,23 @@ class Range extends BaseComponent { this._bubbleText = null this._ticks = null this._updateHandler = () => this._update() - - if (this._config.bubble) { - this._createBubble() + this._initialConfig = { ...config } + this._form = null + this._resetTimeouts = new Set() + this._resetHandler = event => { + // Native reset restores values after dispatching the reset event. + const timeout = window.setTimeout(() => { + this._resetTimeouts.delete(timeout) + if (!event.defaultPrevented) { + this._update() + } + }, 0) + this._resetTimeouts.add(timeout) } + this._syncBubble() + this._syncForm() + this._createTicks() this._addEventListeners() this._update() @@ -109,6 +129,16 @@ class Range extends BaseComponent { // Public update(): void { + if (!this._input) { + return + } + + this._config = this._getConfig(this._initialConfig) as RangeConfig + this._syncBubble() + this._ticks?.remove() + this._ticks = null + this._createTicks() + this._syncForm() this._update() } @@ -116,6 +146,9 @@ class Range extends BaseComponent { EventHandler.off(this._input, EVENT_INPUT, this._updateHandler) EventHandler.off(this._input, EVENT_CHANGE, this._updateHandler) + EventHandler.off(this._form, EVENT_RESET, this._resetHandler) + this._resetTimeouts?.forEach(timeout => clearTimeout(timeout)) + this._bubble?.remove() this._ticks?.remove() @@ -132,6 +165,31 @@ class Range extends BaseComponent { return config } + protected _syncBubble(): void { + if (this._config.bubble) { + if (!this._bubble) { + this._createBubble() + } + } else { + this._bubble?.remove() + this._bubble = null + this._bubbleText = null + } + } + + protected _syncForm(): void { + const { form } = this._input! + if (form === this._form) { + return + } + + EventHandler.off(this._form, EVENT_RESET, this._resetHandler) + this._resetTimeouts.forEach(timeout => clearTimeout(timeout)) + this._resetTimeouts.clear() + this._form = form + EventHandler.on(this._form, EVENT_RESET, this._resetHandler) + } + protected _addEventListeners(): void { EventHandler.on(this._input, EVENT_INPUT, this._updateHandler) EventHandler.on(this._input, EVENT_CHANGE, this._updateHandler) @@ -171,7 +229,7 @@ class Range extends BaseComponent { protected _createBubble(): void { // Reuse the tooltip markup so we don't duplicate the pill and arrow styles - this._bubble = document.createElement('output') + this._bubble = document.createElement('div') this._bubble.className = `${CLASS_NAME_BUBBLE} tooltip bs-tooltip-top show` this._bubble.setAttribute('aria-hidden', 'true') diff --git a/js/src/tab.ts b/js/src/tab.ts index 1b0f7bde66..41a61f3663 100644 --- a/js/src/tab.ts +++ b/js/src/tab.ts @@ -8,6 +8,7 @@ import BaseComponent from './base-component.js' import EventHandler, { type BootstrapEvent } from './dom/event-handler.js' import SelectorEngine from './dom/selector-engine.js' +import { enableHashTarget } from './util/hash-target.js' import { getNextActiveElement, getTransitionDurationFromElement, isDisabled, setAriaAttribute } from './util/index.js' @@ -311,4 +312,52 @@ EventHandler.on(window, EVENT_LOAD_DATA_API, () => { } }) +/** + * Find the tab trigger that targets a pane. + */ +const getTabTriggerFromPane = (pane: HTMLElement): HTMLElement | null => { + const labelledBy = pane.getAttribute('aria-labelledby') + if (labelledBy) { + const byLabel = document.getElementById(labelledBy) + if (byLabel?.matches(SELECTOR_DATA_TOGGLE)) { + return byLabel + } + } + + const { id } = pane + if (!id) { + return null + } + + const escapedId = CSS.escape(id) + return SelectorEngine.findOne( + `${SELECTOR_DATA_TOGGLE}[data-bs-target="#${escapedId}"], ${SELECTOR_DATA_TOGGLE}[href="#${escapedId}"]` + ) +} + +/** + * Open opted-in tab panes when the URL fragment matches their id. + * Put `data-bs-hash` on the tab pane. + */ +enableHashTarget(`${EVENT_KEY}.data-api`, { + matches: element => Boolean(getTabTriggerFromPane(element)), + getAnchor: getTabTriggerFromPane, + async open(element, done) { + const trigger = getTabTriggerFromPane(element) + if (!trigger) { + return + } + + if (trigger.classList.contains(CLASS_NAME_ACTIVE)) { + done() + return + } + + await Tab.getOrCreateInstance(trigger).show() + if (trigger.classList.contains(CLASS_NAME_ACTIVE)) { + done() + } + } +}) + export default Tab diff --git a/js/src/util/hash-target.ts b/js/src/util/hash-target.ts new file mode 100644 index 0000000000..6958aeef12 --- /dev/null +++ b/js/src/util/hash-target.ts @@ -0,0 +1,106 @@ +/** + * -------------------------------------------------------------------------- + * Bootstrap util/hash-target.ts + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + +import EventHandler from '../dom/event-handler.js' + +/** + * Constants + */ + +const ATTR_HASH = 'data-bs-hash' + +type HashTargetHandler = { + /** Return true when this component should open the hashed element. */ + matches: (element: HTMLElement) => boolean + /** + * Optional visible anchor to scroll before opening (usually the trigger). + * Closed collapses and inactive tab panes use `display: none`, so they cannot + * be scrolled to until after they open. + */ + getAnchor?: (element: HTMLElement) => HTMLElement | null + /** + * Open the target. Call `done` after the open animation finishes, + * or immediately when the target is already open. + */ + open: (element: HTMLElement, done: () => void) => void +} + +/** + * Decode a URL fragment id, tolerating malformed escapes (returns it as-is). + */ +const decodeFragment = (value: string): string => { + try { + return decodeURIComponent(value) + } catch { + return value + } +} + +/** + * Resolve the element named by `location.hash` when it opts in with `data-bs-hash`. + */ +const getHashTarget = (): HTMLElement | null => { + const { hash } = window.location + if (!hash || hash === '#') { + return null + } + + const id = decodeFragment(hash.slice(1)) + if (!id) { + return null + } + + const element = document.getElementById(id) + if (!element?.hasAttribute(ATTR_HASH)) { + return null + } + + return element +} + +/** + * Open an opted-in hash target on `load` and `hashchange`. + * Put `data-bs-hash` on the collapse or tab pane that the URL fragment names. + * + * Scrolls a visible anchor first when one exists, then opens the target, then + * scrolls the target into view after it is shown. + */ +const enableHashTarget = (namespace: string, handler: HashTargetHandler): void => { + let generation = 0 + const onHash = (): void => { + const current = ++generation + const element = getHashTarget() + if (!element || !handler.matches(element)) { + return + } + + const anchor = handler.getAnchor?.(element) + if (anchor) { + anchor.scrollIntoView() + } + + handler.open(element, () => { + if (current === generation && element.isConnected && getHashTarget() === element) { + element.scrollIntoView() + } + }) + } + + EventHandler.on(window, `load${namespace}`, onHash) + EventHandler.on(window, `hashchange${namespace}`, onHash) + if (document.readyState === 'complete') { + onHash() + } +} + +export { + ATTR_HASH, + decodeFragment, + enableHashTarget, + getHashTarget +} +export type { HashTargetHandler } diff --git a/js/src/util/sanitizer.ts b/js/src/util/sanitizer.ts index 08f30ba107..23f1e1b48c 100644 --- a/js/src/util/sanitizer.ts +++ b/js/src/util/sanitizer.ts @@ -50,7 +50,7 @@ export const DefaultAllowlist: SanitizerAllowList = { // js-docs-start icon-allow-list /** - * Allowlist for icon HTML options (Chips `dismissIcon`, NavOverflow `moreIcon`, + * Allowlist for icon HTML options (NavOverflow `moreIcon`, * and markup supplied via `[data-bs-overflow-icon]`). Covers the default SVG * icons plus common inline-icon markup. Event-handler attributes and tags not * listed here are stripped by `sanitizeHtml`. diff --git a/js/tests/types/api.ts b/js/tests/types/api.ts index 5a694768d9..8fbbeca454 100644 --- a/js/tests/types/api.ts +++ b/js/tests/types/api.ts @@ -11,7 +11,6 @@ import { Alert, Button, Carousel, - Chips, Collapse, Combobox, Datepicker, @@ -33,7 +32,6 @@ import BaseComponent from '../../src/base-component.js' import EventHandler from '../../src/dom/event-handler.js' import SelectorEngine from '../../src/dom/selector-engine.js' import type { CarouselConfig } from '../../src/carousel.js' -import type { ChipsConfig } from '../../src/chips.js' import type { CollapseConfig } from '../../src/collapse.js' import type { ComboboxConfig } from '../../src/combobox.js' import type { DatepickerConfig } from '../../src/datepicker.js' @@ -59,8 +57,27 @@ const dialog: Dialog = new Dialog(element, { modal: true, keyboard: false }) const drawer: Drawer = new Drawer(element, { scroll: true }) const popover: Popover = new Popover(element, { content: 'Hello', animation: true }) const range: Range = new Range(element, { formatter: value => `${value} %` }) -const chips: Chips = new Chips(element, { separator: ';', maxChips: 5, allowDuplicates: true }) const combobox: Combobox = new Combobox(element, { multiple: true, placeholder: 'Pick one' }) +const comboboxInput = document.createElement('input') +comboboxInput.type = 'hidden' +new Combobox(element, { input: comboboxInput }) +new Combobox(element, { input: '#combobox-input' }) +combobox.update() +combobox.add('design') +combobox.remove('design') +combobox.clear() +combobox.focus() +combobox.selectChip(element, { rangeSelect: true, addToSelection: true }) +combobox.clearSelection() +const selectedChipValues: string[] = combobox.getSelectedValues() +const removedSelectedChips: boolean = combobox.removeSelected() +void selectedChipValues +void removedSelectedChips +const comboboxValues: string[] = combobox.getValues() +new Combobox(element, { + allowCustom: true, multiple: true, separator: ';', maxItems: 5 +}) +void comboboxValues const navOverflow: NavOverflow = new NavOverflow(element, { moreText: 'More', collapseBelow: 768 }) const navOverflowIconOnly: NavOverflow = new NavOverflow(element, { moreText: false }) const otpInput: OtpInput = new OtpInput(element, { length: 6, type: 'alphanumeric', mask: true }) @@ -102,7 +119,6 @@ const collapseDefault: CollapseConfig = Collapse.Default const carouselDefault: CarouselConfig = Carousel.Default const dialogDefault: DialogConfig = Dialog.Default const drawerDefault: DrawerConfig = Drawer.Default -const chipsDefault: ChipsConfig = Chips.Default const comboboxDefault: ComboboxConfig = Combobox.Default const datepickerDefault: DatepickerConfig = Datepicker.Default const navOverflowDefault: NavOverflowConfig = NavOverflow.Default diff --git a/js/tests/types/consumer.ts b/js/tests/types/consumer.ts index cf03c087ec..64aa22cbb3 100644 --- a/js/tests/types/consumer.ts +++ b/js/tests/types/consumer.ts @@ -18,7 +18,6 @@ import { Alert, Button, Carousel, - Chips, Collapse, Combobox, Datepicker, @@ -41,7 +40,6 @@ import DeepTooltip, { type TooltipConfig } from 'bootstrap/js/src/tooltip.js' import EventHandler from 'bootstrap/js/src/dom/event-handler.js' import SelectorEngine from 'bootstrap/js/src/dom/selector-engine.js' import type { CarouselConfig } from 'bootstrap/js/src/carousel.js' -import type { ChipsConfig } from 'bootstrap/js/src/chips.js' import type { CollapseConfig } from 'bootstrap/js/src/collapse.js' import type { ComboboxConfig } from 'bootstrap/js/src/combobox.js' import type { DatepickerConfig } from 'bootstrap/js/src/datepicker.js' @@ -66,8 +64,27 @@ const dialog: Dialog = new Dialog(element, { modal: true, keyboard: false }) const drawer: Drawer = new Drawer(element, { scroll: true }) const popover: Popover = new Popover(element, { content: 'Hello', animation: true }) const range: Range = new Range(element, { formatter: value => `${value} %` }) -const chips: Chips = new Chips(element, { separator: ';', maxChips: 5, allowDuplicates: true }) const combobox: Combobox = new Combobox(element, { multiple: true, placeholder: 'Pick one' }) +const comboboxInput = document.createElement('input') +comboboxInput.type = 'hidden' +new Combobox(element, { input: comboboxInput }) +new Combobox(element, { input: '#combobox-input' }) +combobox.update() +combobox.add('design') +combobox.remove('design') +combobox.clear() +combobox.focus() +combobox.selectChip(element, { rangeSelect: true, addToSelection: true }) +combobox.clearSelection() +const selectedChipValues: string[] = combobox.getSelectedValues() +const removedSelectedChips: boolean = combobox.removeSelected() +void selectedChipValues +void removedSelectedChips +const comboboxValues: string[] = combobox.getValues() +new Combobox(element, { + allowCustom: true, multiple: true, separator: ';', maxItems: 5 +}) +void comboboxValues const navOverflow: NavOverflow = new NavOverflow(element, { moreText: 'More', collapseBelow: 768 }) const navOverflowIconOnly: NavOverflow = new NavOverflow(element, { moreText: false }) const otpInput: OtpInput = new OtpInput(element, { length: 6, type: 'alphanumeric', mask: true }) @@ -118,7 +135,6 @@ const collapseDefault: CollapseConfig = Collapse.Default const carouselDefault: CarouselConfig = Carousel.Default const dialogDefault: DialogConfig = Dialog.Default const drawerDefault: DrawerConfig = Drawer.Default -const chipsDefault: ChipsConfig = Chips.Default const comboboxDefault: ComboboxConfig = Combobox.Default const datepickerDefault: DatepickerConfig = Datepicker.Default const navOverflowDefault: NavOverflowConfig = NavOverflow.Default diff --git a/js/tests/unit/chip.spec.js b/js/tests/unit/chip.spec.js new file mode 100644 index 0000000000..8eb5faa56f --- /dev/null +++ b/js/tests/unit/chip.spec.js @@ -0,0 +1,64 @@ +import { userEvent } from 'vitest/browser' +import css from '../../../scss/bootstrap.scss?inline' +import { clearFixture, getFixture } from '../helpers/fixture.js' + +describe('Chip focus themes', () => { + let fixture + let style + + beforeEach(() => { + fixture = getFixture() + style = document.createElement('style') + style.textContent = css + document.head.append(style) + }) + + afterEach(() => { + style.remove() + clearFixture() + }) + + const variants = { + button: theme => ``, + link: theme => `Link`, + inherited: theme => `
`, + active: theme => ``, + dismiss: theme => `Value` + } + + for (const mode of ['light', 'dark']) { + for (const theme of ['primary', 'accent', 'success', 'danger', 'warning', 'info', 'inverse', 'secondary']) { + for (const [name, markup] of Object.entries(variants)) { + it(`uses the ${theme} focus color for a ${name} chip in ${mode} mode`, async () => { + fixture.style.colorScheme = mode + fixture.innerHTML = `${markup(theme)}` + const target = fixture.querySelector('button, a') + target.focus() + await userEvent.keyboard('{ArrowRight}') + expect(target.matches(':focus-visible')).toBe(true) + const focused = getComputedStyle(target) + expect(focused.outlineStyle).toBe('solid') + expect(focused.outlineWidth).toBe('3px') + expect(focused.outlineColor).toBe(getComputedStyle(fixture.lastElementChild).color) + }) + } + } + } + + for (const classes of ['', 'theme-reset']) { + it(`keeps the global focus color for ${classes || 'unthemed'} chips`, async () => { + fixture.classList.add('theme-danger') + fixture.innerHTML = `` + if (!classes) { + fixture.classList.remove('theme-danger') + } + + fixture.style.setProperty('--focus-ring-color', 'rgb(12, 34, 56)') + const target = fixture.querySelector('button') + target.focus() + await userEvent.keyboard('{ArrowRight}') + expect(target.matches(':focus-visible')).toBe(true) + expect(getComputedStyle(target).outlineColor).toBe('rgb(12, 34, 56)') + }) + } +}) diff --git a/js/tests/unit/chips.spec.js b/js/tests/unit/chips.spec.js deleted file mode 100644 index b09b980ccc..0000000000 --- a/js/tests/unit/chips.spec.js +++ /dev/null @@ -1,695 +0,0 @@ -import Chips from '../../src/chips.js' -import EventHandler from '../../src/dom/event-handler.js' -import { clearFixture, createEvent, getFixture } from '../helpers/fixture.js' - -describe('Chips', () => { - let fixtureEl - - const makeChips = (options, html = '
') => { - fixtureEl.innerHTML = html - const chipsEl = fixtureEl.querySelector('.chips') - return { chipsEl, chips: new Chips(chipsEl, options) } - } - - const keydown = (target, key, modifiers = {}) => { - target.dispatchEvent(new KeyboardEvent('keydown', { - key, - bubbles: true, - cancelable: true, - ...modifiers - })) - } - - beforeAll(() => { - fixtureEl = getFixture() - }) - - afterEach(() => { - clearFixture() - }) - - describe('static properties', () => { - it('should expose version, name, default and default type', () => { - expect(Chips.VERSION).toEqual(jasmine.any(String)) - expect(Chips.NAME).toEqual('chips') - expect(Chips.Default).toEqual(jasmine.any(Object)) - expect(Chips.DefaultType).toEqual(jasmine.any(Object)) - }) - }) - - describe('constructor', () => { - it('should create a ghost input when none is present', () => { - const { chipsEl } = makeChips() - - expect(chipsEl.querySelector('.form-ghost')).not.toBeNull() - }) - - it('should reuse an existing ghost input and set the placeholder from config', () => { - const { chipsEl } = makeChips( - { placeholder: 'Add tag' }, - '
' - ) - - expect(chipsEl.querySelectorAll('.form-ghost').length).toEqual(1) - }) - - it('should initialize from existing chips in the markup', () => { - const { chips, chipsEl } = makeChips( - {}, - '
alpha
' - ) - - expect(chips.getValues()).toEqual(['alpha']) - // Existing chips get a dismiss button and become focusable - expect(chipsEl.querySelector('.chip').getAttribute('tabindex')).toEqual('0') - expect(chipsEl.querySelector('.chip-dismiss')).not.toBeNull() - }) - - it('should derive a chip value from text content when no data attribute is set', () => { - const { chips } = makeChips( - {}, - '
beta
' - ) - - expect(chips.getValues()).toEqual(['beta']) - }) - - it('should derive a chip value from text while ignoring an existing dismiss button', () => { - const { chips } = makeChips( - {}, - '
gamma
' - ) - - expect(chips.getValues()).toEqual(['gamma']) - }) - }) - - describe('add / getValues', () => { - it('should add a chip and reflect it in the DOM and values', () => { - const { chips, chipsEl } = makeChips() - - chips.add('alpha') - - expect(chips.getValues()).toEqual(['alpha']) - expect(chipsEl.querySelectorAll('.chip').length).toEqual(1) - }) - - it('should ignore empty values', () => { - const { chips } = makeChips() - - expect(chips.add(' ')).toBeNull() - expect(chips.getValues()).toEqual([]) - }) - - it('should reject duplicates when allowDuplicates is false', () => { - const { chips, chipsEl } = makeChips() - - chips.add('alpha') - chips.add('alpha') - - expect(chips.getValues()).toEqual(['alpha']) - expect(chipsEl.querySelectorAll('.chip').length).toEqual(1) - }) - - it('should allow duplicates when allowDuplicates is true', () => { - const { chips, chipsEl } = makeChips({ allowDuplicates: true }) - - chips.add('alpha') - chips.add('alpha') - - expect(chips.getValues()).toEqual(['alpha', 'alpha']) - expect(chipsEl.querySelectorAll('.chip').length).toEqual(2) - }) - - it('should enforce the maxChips limit', () => { - const { chips } = makeChips({ maxChips: 2 }) - - chips.add('a') - chips.add('b') - - expect(chips.add('c')).toBeNull() - expect(chips.getValues()).toEqual(['a', 'b']) - }) - - it('should not add a chip when the add event is prevented', () => { - const { chips, chipsEl } = makeChips() - - EventHandler.on(chipsEl, 'add.bs.chips', event => event.preventDefault()) - - expect(chips.add('alpha')).toBeNull() - expect(chips.getValues()).toEqual([]) - }) - - it('should fire the add event with the value and related target', () => { - const { chips, chipsEl } = makeChips() - const spy = jasmine.createSpy('add') - - EventHandler.on(chipsEl, 'add.bs.chips', spy) - chips.add('alpha') - - expect(spy).toHaveBeenCalled() - expect(spy.calls.mostRecent().args[0].value).toEqual('alpha') - }) - - it('should not create a dismiss button when dismissible is false', () => { - const { chips, chipsEl } = makeChips({ dismissible: false }) - chips.add('alpha') - - expect(chipsEl.querySelector('.chip-dismiss')).toBeNull() - }) - - it('should keep the default dismiss SVG after sanitization', () => { - const { chips, chipsEl } = makeChips() - chips.add('alpha') - - const dismiss = chipsEl.querySelector('.chip-dismiss') - expect(dismiss.querySelector('svg')).not.toBeNull() - expect(dismiss.querySelector('line')).not.toBeNull() - }) - - it('should sanitize dismissIcon HTML before inserting it', () => { - const { chips, chipsEl } = makeChips({ - dismissIcon: '' - }) - chips.add('alpha') - - const dismiss = chipsEl.querySelector('.chip-dismiss') - expect(dismiss.querySelector('img')).toBeNull() - expect(dismiss.innerHTML).not.toMatch(/onerror/i) - expect(dismiss.querySelector('svg.safe-icon')).not.toBeNull() - expect(window.__chipsXss).toBeUndefined() - }) - - it('should sanitize dismissIcon supplied via data attributes', () => { - const { chips, chipsEl } = makeChips( - null, - '
x\'>
' - ) - chips.add('alpha') - - const dismiss = chipsEl.querySelector('.chip-dismiss') - expect(dismiss.querySelector('img')).toBeNull() - expect(dismiss.innerHTML).not.toMatch(/onerror/i) - expect(dismiss.querySelector('.icon-ok')).not.toBeNull() - expect(window.__chipsDataXss).toBeUndefined() - }) - }) - - describe('remove', () => { - it('should remove a single chip and keep values in sync with the DOM', () => { - const { chips, chipsEl } = makeChips() - - chips.add('alpha') - chips.add('beta') - - expect(chips.remove('alpha')).toBeTrue() - expect(chips.getValues()).toEqual(['beta']) - expect(chipsEl.querySelectorAll('.chip').length).toEqual(1) - }) - - it('should only remove one entry per duplicate value, keeping values and DOM in sync', () => { - const { chips, chipsEl } = makeChips({ allowDuplicates: true }) - - chips.add('alpha') - chips.add('alpha') - chips.add('beta') - - const firstChip = chipsEl.querySelector('.chip') - expect(chips.remove(firstChip)).toBeTrue() - - // One 'alpha' entry must remain — both state and DOM stay aligned - expect(chips.getValues()).toEqual(['alpha', 'beta']) - expect(chipsEl.querySelectorAll('.chip').length).toEqual(2) - }) - - it('should keep values in rendered order when a later duplicate is removed', () => { - const { chips, chipsEl } = makeChips({ allowDuplicates: true }) - - chips.add('a') - chips.add('b') - chips.add('a') // DOM order: a, b, a - - // Remove the LAST 'a' chip element (not the first) - const chipElements = chipsEl.querySelectorAll('.chip') - expect(chips.remove(chipElements[2])).toBeTrue() - - // Values must match the rendered order a, b — not the mis-ordered b, a - expect(chips.getValues()).toEqual(['a', 'b']) - }) - - it('should return false when the value is not present', () => { - const { chips } = makeChips() - - expect(chips.remove('missing')).toBeFalse() - }) - - it('should not remove a chip when the remove event is prevented', () => { - const { chips, chipsEl } = makeChips() - chips.add('alpha') - - EventHandler.on(chipsEl, 'remove.bs.chips', event => event.preventDefault()) - - expect(chips.remove('alpha')).toBeFalse() - expect(chips.getValues()).toEqual(['alpha']) - }) - - it('should clear a removed chip from the current selection', () => { - const { chips } = makeChips() - const chip = chips.add('alpha') - - chips.selectChip(chip) - expect(chips.getSelectedValues()).toEqual(['alpha']) - - chips.remove(chip) - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should remove a chip when its dismiss button is clicked', () => { - const { chips, chipsEl } = makeChips() - chips.add('alpha') - - chipsEl.querySelector('.chip-dismiss').click() - - expect(chips.getValues()).toEqual([]) - }) - }) - - describe('selection', () => { - it('should select a single chip', () => { - const { chips } = makeChips() - const chip = chips.add('alpha') - - chips.selectChip(chip) - - expect(chip).toHaveClass('active') - expect(chips.getSelectedValues()).toEqual(['alpha']) - }) - - it('should toggle selection when addToSelection is set', () => { - const { chips } = makeChips() - const chip = chips.add('alpha') - - chips.selectChip(chip, { addToSelection: true }) - expect(chips.getSelectedValues()).toEqual(['alpha']) - - chips.selectChip(chip, { addToSelection: true }) - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should range-select from the anchor chip', () => { - const { chips } = makeChips() - const first = chips.add('a') - chips.add('b') - const third = chips.add('c') - - chips.selectChip(first) - chips.selectChip(third, { rangeSelect: true }) - - expect(chips.getSelectedValues()).toEqual(['a', 'b', 'c']) - }) - - it('should keep the anchor chip across range selections', () => { - const { chips } = makeChips() - const first = chips.add('a') - const second = chips.add('b') - chips.add('c') - const fourth = chips.add('d') - - chips.selectChip(first) - chips.selectChip(second, { rangeSelect: true }) - chips.selectChip(fourth, { rangeSelect: true }) - - expect(chips.getSelectedValues()).toEqual(['a', 'b', 'c', 'd']) - }) - - it('should ignore selection requests for foreign elements', () => { - const { chips } = makeChips() - chips.add('a') - - chips.selectChip(document.createElement('span')) - - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should clear the selection', () => { - const { chips } = makeChips() - const chip = chips.add('alpha') - chips.selectChip(chip) - - chips.clearSelection() - - expect(chip).not.toHaveClass('active') - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should remove every selected chip with removeSelected', () => { - const { chips } = makeChips() - const a = chips.add('a') - const b = chips.add('b') - chips.selectChip(a) - chips.selectChip(b, { addToSelection: true }) - - chips.removeSelected() - - expect(chips.getValues()).toEqual([]) - }) - - it('should select a chip and focus it on click', () => { - const { chips, chipsEl } = makeChips() - chips.add('alpha') - - chipsEl.querySelector('.chip').click() - - expect(chips.getSelectedValues()).toEqual(['alpha']) - }) - - it('should clear the selection when clicking the container background', () => { - const { chips, chipsEl } = makeChips() - const chip = chips.add('alpha') - chips.selectChip(chip) - - chipsEl.click() - - expect(chips.getSelectedValues()).toEqual([]) - }) - }) - - describe('clear', () => { - it('should remove all chips and reset state', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - chips.add('b') - - chips.clear() - - expect(chips.getValues()).toEqual([]) - expect(chipsEl.querySelectorAll('.chip').length).toEqual(0) - }) - }) - - describe('input handling', () => { - it('should split input on the separator and keep the trailing part', () => { - const { chips } = makeChips() - const input = chips._input - - input.value = 'a,b,c' - input.dispatchEvent(createEvent('input', { bubbles: true })) - - expect(chips.getValues()).toEqual(['a', 'b']) - expect(input.value).toEqual('c') - }) - - it('should create a chip from the input on Enter', () => { - const { chips } = makeChips() - const input = chips._input - - input.value = 'alpha' - keydown(input, 'Enter') - - expect(chips.getValues()).toEqual(['alpha']) - expect(input.value).toEqual('') - }) - - it('should select the last chip on Backspace with an empty input', () => { - const { chips } = makeChips() - chips.add('alpha') - const input = chips._input - - input.value = '' - keydown(input, 'Backspace') - - expect(chips.getSelectedValues()).toEqual(['alpha']) - }) - - it('should clear input and blur on Escape', () => { - const { chips } = makeChips() - const input = chips._input - input.value = 'typing' - - keydown(input, 'Escape') - - expect(input.value).toEqual('') - }) - - it('should select the last chip on ArrowLeft at the start of an empty input', () => { - const { chips } = makeChips() - chips.add('alpha') - const input = chips._input - input.value = '' - - keydown(input, 'ArrowLeft') - - expect(chips.getSelectedValues()).toEqual(['alpha']) - }) - - it('should add the last chip to the selection on shift+ArrowLeft from the input', () => { - const { chips } = makeChips() - chips.add('alpha') - const input = chips._input - input.value = '' - - keydown(input, 'ArrowLeft', { shiftKey: true }) - - expect(chips.getSelectedValues()).toEqual(['alpha']) - }) - - it('should create a chip on blur when createOnBlur is enabled', () => { - const { chips } = makeChips() - const input = chips._input - input.value = 'alpha' - - input.dispatchEvent(new FocusEvent('blur', { bubbles: true })) - - expect(chips.getValues()).toEqual(['alpha']) - }) - - it('should not create a chip on blur when createOnBlur is disabled', () => { - const { chips } = makeChips({ createOnBlur: false }) - const input = chips._input - input.value = 'alpha' - - input.dispatchEvent(new FocusEvent('blur', { bubbles: true })) - - expect(chips.getValues()).toEqual([]) - }) - - it('should not create a chip on blur when focus moves to a chip', () => { - const { chips, chipsEl } = makeChips() - chips.add('existing') - const input = chips._input - input.value = 'pending' - - input.dispatchEvent(new FocusEvent('blur', { - bubbles: true, - relatedTarget: chipsEl.querySelector('.chip') - })) - - expect(chips.getValues()).toEqual(['existing']) - }) - - it('should ignore pastes when the separator is null', () => { - const { chips } = makeChips({ separator: null }) - const input = chips._input - - const pasteEvent = createEvent('paste', { bubbles: true, cancelable: true }) - pasteEvent.clipboardData = { getData: () => 'a,b,c' } - input.dispatchEvent(pasteEvent) - - expect(chips.getValues()).toEqual([]) - }) - - it('should add chips from pasted text containing the separator', () => { - const { chips } = makeChips() - const input = chips._input - - const pasteEvent = createEvent('paste', { bubbles: true, cancelable: true }) - pasteEvent.clipboardData = { getData: () => 'a,b,c' } - input.dispatchEvent(pasteEvent) - - expect(chips.getValues()).toEqual(['a', 'b', 'c']) - }) - - it('should ignore pasted text without the separator', () => { - const { chips } = makeChips() - const input = chips._input - - const pasteEvent = createEvent('paste', { bubbles: true, cancelable: true }) - pasteEvent.clipboardData = { getData: () => 'single' } - input.dispatchEvent(pasteEvent) - - expect(chips.getValues()).toEqual([]) - }) - }) - - describe('chip keyboard navigation', () => { - it('should delete the selected chip on Backspace', () => { - const { chips, chipsEl } = makeChips() - const chip = chips.add('alpha') - chips.selectChip(chip) - - keydown(chipsEl.querySelector('.chip'), 'Backspace') - - expect(chips.getValues()).toEqual([]) - }) - - it('should move selection left with the arrow key', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - const second = chips.add('b') - chips.selectChip(second) - - keydown(chipsEl.querySelectorAll('.chip')[1], 'ArrowLeft') - - expect(chips.getSelectedValues()).toEqual(['a']) - }) - - it('should move selection right with the arrow key', () => { - const { chips, chipsEl } = makeChips() - const first = chips.add('a') - chips.add('b') - chips.selectChip(first) - - keydown(chipsEl.querySelectorAll('.chip')[0], 'ArrowRight') - - expect(chips.getSelectedValues()).toEqual(['b']) - }) - - it('should extend the selection with shift+arrow', () => { - const { chips, chipsEl } = makeChips() - const first = chips.add('a') - chips.add('b') - chips.selectChip(first) - - keydown(chipsEl.querySelectorAll('.chip')[0], 'ArrowRight', { shiftKey: true }) - - expect(chips.getSelectedValues().sort()).toEqual(['a', 'b']) - }) - - it('should keep focus on the first chip when arrowing left past the start', () => { - const { chips, chipsEl } = makeChips() - const first = chips.add('a') - chips.add('b') - chips.selectChip(first) - - keydown(chipsEl.querySelectorAll('.chip')[0], 'ArrowLeft') - - expect(chips.getSelectedValues()).toEqual(['a']) - }) - - it('should focus and keep the remaining chip after deleting one of several', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - chips.add('b') - const third = chips.add('c') - chips.selectChip(third) - - keydown(chipsEl.querySelectorAll('.chip')[2], 'Backspace') - - expect(chips.getValues()).toEqual(['a', 'b']) - }) - - it('should select all chips with modifier+a', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - const second = chips.add('b') - chips.selectChip(second) - - keydown(chipsEl.querySelectorAll('.chip')[1], 'a', { ctrlKey: true }) - - expect(chips.getSelectedValues().sort()).toEqual(['a', 'b']) - }) - - it('should jump to the first chip on Home', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - const second = chips.add('b') - chips.selectChip(second) - - keydown(chipsEl.querySelectorAll('.chip')[1], 'Home') - - expect(chips.getSelectedValues()).toEqual(['a']) - }) - - it('should range-select to the start on shift+Home', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - const second = chips.add('b') - chips.selectChip(second) - - keydown(chipsEl.querySelectorAll('.chip')[1], 'Home', { shiftKey: true }) - - expect(chips.getSelectedValues().sort()).toEqual(['a', 'b']) - }) - - it('should return focus to the input when navigating right past the last chip', () => { - const { chips, chipsEl } = makeChips() - const only = chips.add('a') - chips.selectChip(only) - - keydown(chipsEl.querySelector('.chip'), 'ArrowRight') - - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should clear selection and focus the input on End', () => { - const { chips, chipsEl } = makeChips() - const chip = chips.add('a') - chips.selectChip(chip) - - keydown(chipsEl.querySelector('.chip'), 'End') - - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should clear selection and focus the input on Escape', () => { - const { chips, chipsEl } = makeChips() - const chip = chips.add('a') - chips.selectChip(chip) - - keydown(chipsEl.querySelector('.chip'), 'Escape') - - expect(chips.getSelectedValues()).toEqual([]) - }) - - it('should do nothing on Backspace when no chip is selected', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - chips.clearSelection() - - keydown(chipsEl.querySelector('.chip'), 'Backspace') - - expect(chips.getValues()).toEqual(['a']) - }) - - it('should not select all on a plain "a" keypress without a modifier', () => { - const { chips, chipsEl } = makeChips() - chips.add('a') - const second = chips.add('b') - chips.selectChip(second) - - keydown(chipsEl.querySelectorAll('.chip')[1], 'a') - - expect(chips.getSelectedValues()).toEqual(['b']) - }) - }) - - describe('dispose', () => { - it('should remove component listeners and keep consumer listeners', () => { - const { chips, chipsEl } = makeChips() - const inputEl = chipsEl.querySelector('.form-ghost') - const chipEl = chips.add('alpha') - const inputSpy = jasmine.createSpy('input') - const clickSpy = jasmine.createSpy('click') - - inputEl.addEventListener('input', inputSpy) - chipsEl.addEventListener('click', clickSpy) - chips.dispose() - - inputEl.value = 'beta,' - expect(() => inputEl.dispatchEvent(createEvent('input'))).not.toThrow() - expect(() => chipEl.click()).not.toThrow() - expect(inputSpy).toHaveBeenCalled() - expect(clickSpy).toHaveBeenCalled() - }) - }) -}) diff --git a/js/tests/unit/collapse.spec.js b/js/tests/unit/collapse.spec.js index f277cb9665..85edc6ffbf 100644 --- a/js/tests/unit/collapse.spec.js +++ b/js/tests/unit/collapse.spec.js @@ -1,6 +1,16 @@ import Collapse from '../../src/collapse.js' import EventHandler from '../../src/dom/event-handler.js' -import { clearFixture, getFixture } from '../helpers/fixture.js' +import { clearFixture, createEvent, getFixture } from '../helpers/fixture.js' + +const setHash = hash => { + const url = new URL(window.location.href) + url.hash = hash + window.history.replaceState(null, '', url) +} + +const clearHash = () => { + setHash('') +} describe('Collapse', () => { let fixtureEl @@ -11,6 +21,7 @@ describe('Collapse', () => { afterEach(() => { clearFixture() + clearHash() }) describe('VERSION', () => { @@ -955,4 +966,77 @@ describe('Collapse', () => { expect(collapse2._config.parent).toEqual(fixtureEl) }) }) + + describe('hash target', () => { + it('should scroll the trigger, show the collapse, then scroll the target on load', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + 'Toggle', + '
' + ].join('') + + const triggerEl = fixtureEl.querySelector('#collapseHashTrigger') + const collapseEl = fixtureEl.querySelector('#collapseHash') + const triggerScrollSpy = spyOn(triggerEl, 'scrollIntoView') + + spyOn(collapseEl, 'scrollIntoView').and.callFake(() => { + expect(triggerScrollSpy).toHaveBeenCalled() + expect(collapseEl).toHaveClass('show') + resolve() + }) + + setHash('collapseHash') + window.dispatchEvent(createEvent('load')) + }) + }) + + it('should scroll the trigger, show the collapse, then scroll the target on hashchange', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + 'Toggle', + '
' + ].join('') + + const triggerEl = fixtureEl.querySelector('#collapseHashChangeTrigger') + const collapseEl = fixtureEl.querySelector('#collapseHashChange') + const triggerScrollSpy = spyOn(triggerEl, 'scrollIntoView') + + spyOn(collapseEl, 'scrollIntoView').and.callFake(() => { + expect(triggerScrollSpy).toHaveBeenCalled() + expect(collapseEl).toHaveClass('show') + resolve() + }) + + setHash('collapseHashChange') + window.dispatchEvent(createEvent('hashchange')) + }) + }) + + it('should scroll an already-open hash target into view', () => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('#collapseHashOpen') + const scrollSpy = spyOn(collapseEl, 'scrollIntoView') + const showSpy = spyOn(Collapse.prototype, 'show').and.callThrough() + + setHash('collapseHashOpen') + window.dispatchEvent(createEvent('load')) + + expect(showSpy).not.toHaveBeenCalled() + expect(scrollSpy).toHaveBeenCalled() + }) + + it('should ignore hash targets without data-bs-hash', () => { + fixtureEl.innerHTML = '
' + + const collapseEl = fixtureEl.querySelector('#collapseNoHash') + const showSpy = spyOn(Collapse.prototype, 'show').and.callThrough() + + setHash('collapseNoHash') + window.dispatchEvent(createEvent('load')) + + expect(collapseEl).not.toHaveClass('show') + expect(showSpy).not.toHaveBeenCalled() + }) + }) }) diff --git a/js/tests/unit/combobox-editor.spec.js b/js/tests/unit/combobox-editor.spec.js new file mode 100644 index 0000000000..9320d4fc8f --- /dev/null +++ b/js/tests/unit/combobox-editor.spec.js @@ -0,0 +1,741 @@ +import Combobox from '../../src/combobox.js' +import Menu from '../../src/menu.js' +import { clearFixture, getFixture } from '../helpers/fixture.js' + +describe('Combobox editor', () => { + let fixture + let instance + const key = (target, value, options = {}) => { + const event = new KeyboardEvent('keydown', { + key: value, bubbles: true, cancelable: true, ...options + }) + target.dispatchEvent(event) + return event + } + + const make = (config = {}, { selected = [], values = ['design', 'art,music', 'science'] } = {}) => { + fixture.innerHTML = `
+
+ +
` + const root = fixture.querySelector('.combobox-control') + const input = root.querySelector('input') + const menu = fixture.querySelector('.menu') + const items = values.map((value, index) => { + const item = document.createElement('button') + item.type = 'button' + item.className = `menu-item${selected.includes(index) ? ' selected' : ''}` + item.dataset.bsValue = value + item.textContent = `Label ${index}` + menu.append(item) + return item + }) + instance = new Combobox(root, { name: 'interests', multiple: true, ...config }) + return { + root, input, menu, items, form: fixture.querySelector('form') + } + } + + const type = (input, value) => { + input.value = value + input.dispatchEvent(new InputEvent('input', { bubbles: true })) + } + + const values = form => new FormData(form).getAll('interests') + + beforeEach(() => { + fixture = getFixture() + }) + afterEach(() => { + instance?.dispose() + instance = null + document.documentElement.dir = '' + clearFixture() + }) + + it('should keep input focus while navigating suggestions without committing', async () => { + const x = make() + x.input.focus() + key(x.input, 'ArrowDown') + await instance.show() + expect(document.activeElement).toBe(x.input) + expect(x.input.getAttribute('aria-activedescendant')).toEqual(x.items[0].id) + expect(values(x.form)).toEqual([]) + key(x.input, 'Enter') + expect(values(x.form)).toEqual(['design']) + expect(x.input.value).toEqual('') + expect(x.root.querySelector('.chip').textContent).toContain('Label 0') + expect(document.activeElement).toBe(x.input) + }) + + it('should filter from the visible editor and retain query through Menu transitions', async () => { + const x = make() + type(x.input, 'Label 1') + await instance.show() + await new Promise(resolve => { + requestAnimationFrame(resolve) + }) + expect(x.input.value).toEqual('Label 1') + expect(x.items[0].style.display).toEqual('none') + expect(x.items[1].style.display).toEqual('') + }) + + it('should remove a chip by option identity with duplicate submitted values', () => { + const x = make({}, { values: ['same', 'same'], selected: [0, 1] }) + x.root.querySelectorAll('.chip-dismiss')[1].click() + expect(values(x.form)).toEqual(['same']) + expect(x.items[0]).toHaveClass('selected') + expect(x.items[1]).not.toHaveClass('selected') + }) + + it('should keep existing chips stable while filtering or adding another value', () => { + const x = make({}, { selected: [0] }) + const chip = x.root.querySelector('.chip') + type(x.input, 'Label') + expect(x.root.querySelector('.chip')).toBe(chip) + instance.add('science') + expect(x.root.querySelector('.chip')).toBe(chip) + expect(values(x.form)).toEqual(['design', 'science']) + }) + + it('should expose labelled removal buttons and commit one change through native fields', () => { + const x = make({}, { selected: [0] }) + const events = [] + for (const name of ['input', 'change', 'change.bs.combobox']) { + x.form.addEventListener(name, () => events.push([name, values(x.form)])) + } + + const button = x.root.querySelector('.chip-dismiss') + expect(button.getAttribute('aria-label')).toEqual('Remove Label 0') + button.click() + expect(events).toEqual([['input', []], ['change', []], ['change.bs.combobox', []]]) + expect(document.activeElement).toBe(x.input) + }) + + it('should leave ordinary input editing and composition keys alone', () => { + const x = make({ allowCustom: true }) + for (const options of [{ isComposing: true }, { keyCode: 229 }]) { + x.input.value = '東京' + expect(key(x.input, 'Enter', options).defaultPrevented).toBeFalse() + expect(instance.getValues()).toEqual([]) + expect(x.input.value).toEqual('東京') + } + + for (const value of ['Home', 'End', 'ArrowLeft', 'ArrowRight', 'Backspace', 'Delete']) { + expect(key(x.input, value).defaultPrevented).toBeFalse() + } + }) + + it('should create custom values only when explicitly allowed', () => { + const x = make() + type(x.input, 'Custom') + key(x.input, 'Enter') + expect(values(x.form)).toEqual([]) + expect(instance.add('Custom')).toBeNull() + }) + + it('should submit custom values and preserve commas when no separator is configured', () => { + const x = make({ allowCustom: true }) + type(x.input, 'Art, music') + key(x.input, 'Enter') + expect(values(x.form)).toEqual(['Art, music']) + expect(x.input.value).toEqual('') + expect(x.root.querySelector('.chip').textContent).toContain('Art, music') + expect(instance.add('Art, music')).toBeNull() + expect(instance.add(' ')).toBeNull() + }) + + it('should split custom text only with an explicit separator', () => { + const x = make({ allowCustom: true, separator: ';' }) + type(x.input, 'alpha;beta;gamma') + expect(values(x.form)).toEqual(['alpha', 'beta']) + expect(x.input.value).toEqual('gamma') + }) + + it('should enforce maxItems for custom and predefined options', () => { + const x = make({ allowCustom: true, maxItems: 1 }) + instance.add('design') + expect(instance.add('custom')).toBeNull() + x.items[1].click() + expect(values(x.form)).toEqual(['design']) + }) + + it('should preserve disabled option selections and reject their removal', () => { + const x = make({}, { selected: [0] }) + x.items[0].disabled = true + instance.update() + expect(x.root.querySelector('.chip-dismiss').disabled).toBeTrue() + expect(instance.remove('design')).toBeFalse() + instance.clear() + expect(instance.getValues()).toEqual(['design']) + expect(values(x.form)).toEqual([]) + }) + + it('should focus a chip before removing it with Backspace', () => { + const x = make({}, { selected: [0, 1] }) + x.input.focus() + key(x.input, 'Backspace') + const chip = x.root.querySelectorAll('.chip')[1] + expect(document.activeElement).toBe(chip) + expect(values(x.form)).toEqual(['design', 'art,music']) + key(chip, 'Backspace') + expect(values(x.form)).toEqual(['design']) + expect(document.activeElement).toBe(x.root.querySelector('.chip')) + }) + + it('should navigate chips in RTL without changing input text editing', () => { + document.documentElement.dir = 'rtl' + const x = make({}, { selected: [0, 1] }) + x.input.focus() + key(x.input, 'ArrowRight') + expect(document.activeElement).toBe(x.root.querySelectorAll('.chip')[1]) + key(document.activeElement, 'ArrowRight') + expect(document.activeElement).toBe(x.root.querySelector('.chip')) + key(document.activeElement, 'End') + expect(document.activeElement).toBe(x.input) + }) + + it('should clear active-descendant state when dismissed outside', async () => { + const x = make() + key(x.input, 'ArrowDown') + await instance.show() + await Menu.getInstance(x.input).hide() + expect(x.input.hasAttribute('aria-activedescendant')).toBeFalse() + }) + + it('should restore initial chips and fields on reset without selection events', async () => { + const x = make({}, { selected: [0] }) + instance.add('science') + const changed = jasmine.createSpy('changed') + x.root.addEventListener('change.bs.combobox', changed) + x.form.reset() + await new Promise(resolve => { + setTimeout(resolve, 0) + }) + expect(values(x.form)).toEqual(['design']) + expect(x.root.querySelectorAll('.chip').length).toEqual(1) + expect(changed).not.toHaveBeenCalled() + }) + + it('should clear a stale single value when its visible label is edited', () => { + const x = make({ multiple: false }, { selected: [0] }) + expect(x.input.value).toEqual('Label 0') + type(x.input, 'other') + expect(values(x.form)).toEqual(['']) + expect(x.input.value).toEqual('other') + instance.add('science') + expect(x.input.value).toEqual('Label 2') + expect(values(x.form)).toEqual(['science']) + }) + + it('should restore editor attributes and dispose its owned Menu', () => { + const x = make() + instance.add('design') + instance.dispose() + instance = null + expect(x.root.querySelector('.chip')).toBeNull() + expect(x.input.hasAttribute('role')).toBeFalse() + expect(x.input.hasAttribute('aria-controls')).toBeFalse() + expect(Menu.getInstance(x.input)).toBeNull() + expect(x.menu.hasAttribute('role')).toBeFalse() + }) + + it('should generate and remove a popup for a standalone free-entry field', () => { + fixture.innerHTML = '
' + const root = fixture.firstElementChild + instance = new Combobox(root, { multiple: true, allowCustom: true }) + instance.add('') + expect(root.querySelector('img')).toBeNull() + expect(instance.getValues()).toEqual(['']) + instance.dispose() + instance = null + expect(fixture.querySelector('.menu')).toBeNull() + }) + it('should let applications cancel add and remove operations', () => { + const x = make({ allowCustom: true }) + x.root.addEventListener('add.bs.combobox', event => event.preventDefault(), { once: true }) + expect(instance.add('custom')).toBeNull() + expect(values(x.form)).toEqual([]) + instance.add('design') + x.root.addEventListener('remove.bs.combobox', event => event.preventDefault(), { once: true }) + expect(instance.remove('design')).toBeFalse() + expect(values(x.form)).toEqual(['design']) + }) + + it('should restore a single label if removing its committed value is canceled', () => { + const x = make({ multiple: false }, { selected: [0] }) + x.root.addEventListener('remove.bs.combobox', event => event.preventDefault()) + type(x.input, 'other') + expect(values(x.form)).toEqual(['design']) + expect(x.input.value).toEqual('Label 0') + }) + + it('should show the new query before announcing a cleared single value', () => { + const x = make({ multiple: false }, { selected: [0] }) + let query + x.root.addEventListener('change.bs.combobox', () => { + query = x.input.value + }) + type(x.input, 'new query') + expect(query).toEqual('new query') + expect(values(x.form)).toEqual(['']) + }) + + it('should preserve all chip nodes and their focused node during reconciliation', () => { + const x = make({}, { selected: [0, 1] }) + const chips = [...x.root.querySelectorAll('.chip')] + chips[0].focus() + instance.update() + expect([...x.root.querySelectorAll('.chip')]).toEqual(chips) + expect(document.activeElement).toBe(chips[0]) + }) + + it('should paste delimited values through the same selection and form path', () => { + const x = make({ allowCustom: true, separator: ';' }) + const clipboardData = new DataTransfer() + clipboardData.setData('text', 'alpha;beta') + const event = new ClipboardEvent('paste', { clipboardData, bubbles: true, cancelable: true }) + x.input.dispatchEvent(event) + expect(event.defaultPrevented).toBeTrue() + expect(values(x.form)).toEqual(['alpha', 'beta']) + }) + + it('should not split paste without a configured separator', () => { + const x = make({ allowCustom: true }) + const clipboardData = new DataTransfer() + clipboardData.setData('text', 'alpha,beta') + const event = new ClipboardEvent('paste', { clipboardData, bubbles: true, cancelable: true }) + x.input.dispatchEvent(event) + expect(event.defaultPrevented).toBeFalse() + expect(values(x.form)).toEqual([]) + }) + + it('should create on blur only when explicitly enabled', () => { + const x = make({ allowCustom: true, createOnBlur: true }) + type(x.input, 'new tag') + x.input.dispatchEvent(new FocusEvent('blur', { relatedTarget: x.form })) + expect(values(x.form)).toEqual(['new tag']) + }) + + it('should ignore blur toward a chip removal control', () => { + const x = make({ allowCustom: true, createOnBlur: true }, { selected: [0] }) + type(x.input, 'unfinished') + x.input.dispatchEvent(new FocusEvent('blur', { relatedTarget: x.root.querySelector('.chip-dismiss') })) + expect(values(x.form)).toEqual(['design']) + }) + + it('should block edits and removal when its wrapping field is disabled', () => { + const x = make({ allowCustom: true }, { selected: [0] }) + x.root.classList.add('disabled') + instance.update() + expect(instance.add('new tag')).toBeNull() + expect(instance.remove('design')).toBeFalse() + expect(x.root.querySelector('.chip-dismiss').disabled).toBeTrue() + expect(values(x.form)).toEqual([]) + }) + + it('should reject invalid selection limits', () => { + const x = make() + for (const maxItems of [0, -1, 1.5]) { + expect(() => new Combobox(x.root, { maxItems })).toThrowError(TypeError) + } + }) + + it('should safely stop when a removal listener disposes the component', () => { + const x = make({}, { selected: [0] }) + x.root.addEventListener('remove.bs.combobox', () => { + instance.dispose() + instance = null + }) + const component = instance + expect(component.remove('design')).toBeFalse() + }) + + it('should clear enabled selections with one native change notification', () => { + const x = make({}, { selected: [0, 1] }) + const changed = jasmine.createSpy('changed') + x.form.addEventListener('change', changed) + instance.clear() + expect(values(x.form)).toEqual([]) + expect(changed).toHaveBeenCalledTimes(1) + instance.clear() + expect(changed).toHaveBeenCalledTimes(1) + }) + it('should open and highlight an option when CSS hides the closed popup', () => { + const x = make() + x.menu.style.display = 'none' + key(x.input, 'ArrowDown') + expect(x.menu).toHaveClass('show') + expect(x.input.getAttribute('aria-activedescendant')).toEqual(x.items[0].id) + }) + it('should preserve the caret when updates leave the query unchanged', () => { + const x = make() + type(x.input, 'Label') + x.input.setSelectionRange(2, 2) + instance.update() + expect(x.input.selectionStart).toEqual(2) + expect(x.input.selectionEnd).toEqual(2) + }) + + it('should preserve composing text during observer reconciliation', () => { + const x = make({ allowCustom: true }) + x.input.value = 'とうきょう' + x.input.dispatchEvent(new InputEvent('input', { bubbles: true, isComposing: true })) + instance.update() + expect(x.input.value).toEqual('とうきょう') + expect(values(x.form)).toEqual([]) + }) + it('should highlight the last chip without changing form values on Backspace', () => { + const x = make({}, { selected: [0, 1, 2] }) + const changed = jasmine.createSpy('changed') + x.form.addEventListener('change', changed) + x.input.focus() + key(x.input, 'Backspace') + const chip = x.root.querySelectorAll('.chip')[2] + expect(chip).toHaveClass('active') + expect(chip.getAttribute('aria-description')).toEqual('Selected for removal') + expect(instance.getSelectedValues()).toEqual(['science']) + expect(instance.getValues()).toEqual(['design', 'art,music', 'science']) + expect(changed).not.toHaveBeenCalled() + }) + + it('should select a chip on click and support modifier toggles', () => { + const x = make({}, { selected: [0, 1, 2] }) + const chips = x.root.querySelectorAll('.chip') + chips[0].click() + expect(instance.getSelectedValues()).toEqual(['design']) + chips[2].dispatchEvent(new MouseEvent('click', { bubbles: true, ctrlKey: true })) + expect(instance.getSelectedValues()).toEqual(['design', 'science']) + chips[0].dispatchEvent(new MouseEvent('click', { bubbles: true, metaKey: true })) + expect(instance.getSelectedValues()).toEqual(['science']) + expect(document.activeElement).toBe(chips[0]) + }) + + it('should extend and shrink a range without losing its anchor', () => { + const x = make({}, { selected: [0, 1, 2] }) + const chips = x.root.querySelectorAll('.chip') + chips[2].click() + key(chips[2], 'ArrowLeft', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['art,music', 'science']) + key(chips[1], 'ArrowLeft', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['design', 'art,music', 'science']) + key(chips[0], 'ArrowRight', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['art,music', 'science']) + }) + + it('should support shift-click and shift-Home/End range selection', () => { + const x = make({}, { selected: [0, 1, 2] }) + const chips = x.root.querySelectorAll('.chip') + chips[0].click() + chips[2].dispatchEvent(new MouseEvent('click', { bubbles: true, shiftKey: true })) + expect(instance.getSelectedValues()).toEqual(['design', 'art,music', 'science']) + chips[1].click() + key(chips[1], 'Home', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['design', 'art,music']) + key(chips[0], 'End', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['art,music', 'science']) + }) + + it('should emit UI selection events with values and option identities', () => { + const x = make({}, { values: ['same', 'same'], selected: [0, 1] }) + const events = [] + x.root.addEventListener('select.bs.combobox', event => events.push([event.selected, event.items])) + const chips = x.root.querySelectorAll('.chip') + instance.selectChip(chips[1]) + instance.clearSelection() + expect(events).toEqual([[['same'], [x.items[1]]], [[], []]]) + expect(values(x.form)).toEqual(['same', 'same']) + }) + + it('should delete a selected range in one native change and focus a remaining chip', () => { + const x = make({}, { selected: [0, 1, 2] }) + const chips = x.root.querySelectorAll('.chip') + chips[2].click() + key(chips[2], 'ArrowLeft', { shiftKey: true }) + const changes = [] + x.form.addEventListener('change', () => changes.push(values(x.form))) + key(chips[1], 'Delete') + expect(values(x.form)).toEqual(['design']) + expect(changes).toEqual([['design']]) + expect(document.activeElement).toBe(chips[0]) + expect(chips[0]).toHaveClass('active') + }) + + it('should select all chips with modifier+A but preserve native query selection', () => { + const x = make({}, { selected: [0, 1, 2] }) + x.input.focus() + expect(key(x.input, 'a', { ctrlKey: true }).defaultPrevented).toBeTrue() + expect(instance.getSelectedValues()).toEqual(['design', 'art,music', 'science']) + key(document.activeElement, 'Delete') + expect(values(x.form)).toEqual([]) + expect(document.activeElement).toBe(x.input) + type(x.input, 'query') + expect(key(x.input, 'a', { metaKey: true }).defaultPrevented).toBeFalse() + }) + + it('should clear highlighted chips when returning to the editor', () => { + const x = make({}, { selected: [0, 1] }) + x.input.focus() + key(x.input, 'Backspace') + const last = x.root.querySelectorAll('.chip')[1] + key(last, 'ArrowRight') + expect(document.activeElement).toBe(x.input) + expect(instance.getSelectedValues()).toEqual([]) + expect(last).not.toHaveClass('active') + expect(last.hasAttribute('aria-description')).toBeFalse() + }) + + it('should clear UI selection on Escape without removing committed values', () => { + const x = make({}, { selected: [0, 1] }) + const chip = x.root.querySelector('.chip') + chip.click() + key(chip, 'Escape') + expect(instance.getSelectedValues()).toEqual([]) + expect(instance.getValues()).toEqual(['design', 'art,music']) + expect(document.activeElement).toBe(x.input) + }) + + it('should preserve query text when arrowing back from a chip', () => { + const x = make({}, { selected: [0, 1] }) + type(x.input, 'query') + x.input.setSelectionRange(0, 0) + key(x.input, 'ArrowLeft') + const chip = x.root.querySelectorAll('.chip')[1] + expect(chip).toHaveClass('active') + key(chip, 'End') + expect(x.input.value).toEqual('query') + expect(instance.getSelectedValues()).toEqual([]) + }) + + it('should honor individual removal cancellation during bulk deletion', () => { + const x = make({}, { selected: [0, 1, 2] }) + const chip = x.root.querySelector('.chip') + chip.click() + key(chip, 'a', { ctrlKey: true }) + x.root.addEventListener('remove.bs.combobox', event => { + if (event.item === x.items[1]) { + event.preventDefault() + } + }) + key(chip, 'Delete') + expect(instance.getValues()).toEqual(['art,music']) + expect(x.root.querySelector('.chip')).toHaveClass('active') + }) + + it('should exclude disabled chips from focus and range selection', () => { + const x = make({}, { selected: [0, 1, 2] }) + x.items[2].disabled = true + instance.update() + x.input.focus() + key(x.input, 'Backspace') + expect(document.activeElement).toBe(x.root.querySelectorAll('.chip')[1]) + key(document.activeElement, 'a', { ctrlKey: true }) + expect(instance.getSelectedValues()).toEqual(['design', 'art,music']) + }) + + it('should navigate and extend chip ranges in RTL', () => { + document.documentElement.dir = 'rtl' + const x = make({}, { selected: [0, 1, 2] }) + x.input.focus() + key(x.input, 'ArrowRight') + const chips = x.root.querySelectorAll('.chip') + key(chips[2], 'ArrowRight', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['art,music', 'science']) + expect(document.activeElement).toBe(chips[1]) + key(chips[1], 'ArrowLeft') + expect(instance.getSelectedValues()).toEqual(['science']) + }) + + it('should stop safely when a chip-selection listener disposes the component', () => { + const x = make({}, { selected: [0] }) + const component = instance + x.root.addEventListener('select.bs.combobox', () => { + component.dispose() + instance = null + }) + expect(() => key(x.input, 'Backspace')).not.toThrow() + }) + + it('should clear UI selection quietly on reset', async () => { + const x = make({}, { selected: [0, 1] }) + x.root.querySelector('.chip').click() + const selected = jasmine.createSpy('selected') + x.root.addEventListener('select.bs.combobox', selected) + x.form.reset() + await new Promise(resolve => { + setTimeout(resolve, 0) + }) + expect(instance.getSelectedValues()).toEqual([]) + expect(x.root.querySelectorAll('.chip.active').length).toEqual(0) + expect(selected).not.toHaveBeenCalled() + }) + + it('should prune highlighted chips when their options are removed on update', () => { + const x = make({}, { selected: [0, 1] }) + x.root.querySelector('.chip').click() + x.items[0].remove() + instance.update() + expect(instance.getSelectedValues()).toEqual([]) + expect(instance._anchorChip).toBeNull() + }) + it('should fill a chip when it receives direct focus', () => { + const x = make({}, { selected: [0, 1] }) + const chip = x.root.querySelectorAll('.chip')[1] + chip.focus() + expect(chip).toHaveClass('active') + expect(instance.getSelectedValues()).toEqual(['art,music']) + expect(values(x.form)).toEqual(['design', 'art,music']) + }) + + it('should fill the owning chip when its remove button receives focus', () => { + const x = make({}, { selected: [0, 1] }) + const chip = x.root.querySelectorAll('.chip')[1] + chip.querySelector('button').focus() + expect(chip).toHaveClass('active') + expect(instance.getSelectedValues()).toEqual(['art,music']) + }) + + it('should preserve a range while focusing a member through keyboard navigation', () => { + const x = make({}, { selected: [0, 1, 2] }) + const chips = x.root.querySelectorAll('.chip') + chips[2].click() + key(chips[2], 'Home', { shiftKey: true }) + expect(instance.getSelectedValues()).toEqual(['design', 'art,music', 'science']) + expect(document.activeElement).toBe(chips[0]) + }) + + it('should stop an outer single selection when an add listener selects another option', () => { + const x = make({ multiple: false }) + x.root.addEventListener('add.bs.combobox', () => instance.add('science'), { once: true }) + instance.add('design') + expect(instance.getValues()).toEqual(['science']) + expect(x.menu.querySelectorAll('.selected').length).toEqual(1) + expect(x.input.value).toEqual('Label 2') + }) + + it('should preserve the insertion caret during a native input event', () => { + const x = make() + x.input.value = 'LaXbel' + x.input.setSelectionRange(3, 3) + x.input.dispatchEvent(new InputEvent('input', { bubbles: true })) + expect(x.input.selectionStart).toEqual(3) + expect(x.input.selectionEnd).toEqual(3) + }) + + it('should reconcile the committed single value when composition ends', () => { + const x = make({ multiple: false }, { selected: [0] }) + x.input.dispatchEvent(new CompositionEvent('compositionstart')) + x.input.value = '東京' + x.input.dispatchEvent(new InputEvent('input', { bubbles: true, isComposing: true })) + x.input.dispatchEvent(new CompositionEvent('compositionend')) + expect(values(x.form)).toEqual(['']) + expect(x.input.value).toEqual('東京') + }) + + it('should not create a value on blur while composition is in progress', () => { + const x = make({ allowCustom: true, createOnBlur: true }) + x.input.dispatchEvent(new CompositionEvent('compositionstart')) + x.input.value = 'とうきょう' + x.input.dispatchEvent(new InputEvent('input', { bubbles: true, isComposing: true })) + x.input.dispatchEvent(new FocusEvent('blur', { relatedTarget: x.form })) + expect(instance.getValues()).toEqual([]) + expect(x.input.value).toEqual('とうきょう') + }) + + it('should follow an external reset form without a submitted field', async () => { + const x = make({ name: null, multiple: false }, { selected: [0] }) + x.form.id = 'external-editor-form' + fixture.append(x.root, x.menu) + x.input.setAttribute('form', x.form.id) + instance.update() + instance.add('science') + x.form.reset() + await new Promise(resolve => { + setTimeout(resolve, 0) + }) + expect(instance.getValues()).toEqual(['design']) + expect(x.input.value).toEqual('Label 0') + }) + + it('should omit a disabled selected single option from submission', () => { + const x = make({ multiple: false }, { selected: [0] }) + x.items[0].disabled = true + instance.update() + expect(values(x.form)).toEqual([]) + x.items[0].disabled = false + instance.update() + expect(values(x.form)).toEqual(['design']) + }) + + it('should not rewrite restored popup width after disposal during show', async () => { + const x = make() + const showing = instance.show() + instance.dispose() + instance = null + await showing + await new Promise(resolve => { + requestAnimationFrame(resolve) + }) + expect(x.menu.style.minWidth).toEqual('') + }) + + it('should clear an active descendant when its option is removed or disabled', async () => { + const x = make() + key(x.input, 'ArrowDown') + await instance.show() + x.items[0].remove() + instance.update() + expect(x.input.hasAttribute('aria-activedescendant')).toBeFalse() + key(x.input, 'ArrowDown') + x.items[1].disabled = true + instance.update() + expect(x.input.hasAttribute('aria-activedescendant')).toBeFalse() + }) + it('should leave Escape to an IME in the popup search input', async () => { + const x = make() + const search = document.createElement('input') + x.menu.prepend(search) + await instance.show() + search.focus() + key(search, 'Escape', { isComposing: true }) + expect(x.menu.classList.contains('show')).toBeTrue() + key(search, 'Escape') + expect(x.menu.classList.contains('show')).toBeFalse() + }) + + it('should stop selection if an add listener disables the option', () => { + const x = make() + x.root.addEventListener('add.bs.combobox', () => { + x.items[0].disabled = true + }, { once: true }) + instance.add('design') + expect(instance.getValues()).toEqual([]) + expect(values(x.form)).toEqual([]) + }) + + it('should stop focus work when a hide listener disposes the editor', async () => { + const x = make({ multiple: false }) + await instance.show() + x.root.addEventListener('hide.bs.combobox', event => { + event.preventDefault() + instance.dispose() + instance = null + }, { once: true }) + const editor = instance + expect(() => editor.add('design')).not.toThrow() + }) + it('should reconcile composition after blur without stealing focus', () => { + const x = make({ multiple: false }, { selected: [0] }) + const other = document.createElement('button') + other.type = 'button' + fixture.append(other) + x.input.focus() + x.input.dispatchEvent(new CompositionEvent('compositionstart')) + x.input.value = '東京' + other.focus() + x.input.dispatchEvent(new CompositionEvent('compositionend')) + expect(values(x.form)).toEqual(['']) + expect(document.activeElement).toBe(other) + expect(x.menu.classList.contains('show')).toBeFalse() + }) +}) diff --git a/js/tests/unit/combobox-form.spec.js b/js/tests/unit/combobox-form.spec.js new file mode 100644 index 0000000000..08369c0a2d --- /dev/null +++ b/js/tests/unit/combobox-form.spec.js @@ -0,0 +1,411 @@ +import Combobox from '../../src/combobox.js' +import Menu from '../../src/menu.js' +import { clearFixture, getFixture } from '../helpers/fixture.js' + +describe('Combobox form contract', () => { + let fixture + let instances + + const tick = () => new Promise(resolve => { + requestAnimationFrame(resolve) + }) + const make = (config = {}, { form, input, selected = [], values = ['a,b', 'c', 'd'] } = {}) => { + form ??= document.createElement('form') + if (!form.parentNode) { + fixture.append(form) + } + + if (input) { + form.append(input) + } + + const toggle = document.createElement('button') + toggle.type = 'button' + toggle.className = 'form-control combobox-toggle' + toggle.innerHTML = '' + form.append(toggle) + const menu = document.createElement('div') + menu.className = 'menu' + menu.innerHTML = '' + const items = values.map((value, index) => { + const item = document.createElement('button') + item.type = 'button' + item.className = `menu-item${selected.includes(index) ? ' selected' : ''}` + item.dataset.bsValue = value + item.textContent = `Option ${index}` + menu.append(item) + return item + }) + form.append(menu) + const instance = new Combobox(toggle, { name: 'choices', ...config, ...(input ? { input } : {}) }) + instances.push(instance) + return { + form, toggle, menu, items, instance, search: menu.querySelector('input') + } + } + + const field = () => { + const input = document.createElement('input') + input.type = 'hidden' + input.id = 'provided' + input.name = 'provided-name' + input.dataset.validation = 'preserve' + return input + } + + const values = form => new FormData(form).getAll('choices') + + beforeEach(() => { + fixture = getFixture() + instances = [] + }) + + afterEach(() => { + for (const instance of instances) { + if (instance._element) { + instance.dispose() + } + } + + document.documentElement.removeAttribute('dir') + clearFixture() + }) + + it('should submit repeated values in menu order and preserve commas', () => { + const x = make({ multiple: true }) + x.items[1].click() + x.items[0].click() + expect(values(x.form)).toEqual(['a,b', 'c']) + expect(new URLSearchParams(new FormData(x.form)).toString()).toEqual('choices=a%2Cb&choices=c') + }) + + it('should preserve its event field across empty multiple selections', () => { + const x = make({ multiple: true }) + const input = x.form.querySelector('input[type="hidden"]') + const events = [] + x.form.addEventListener('change', event => events.push([event.target, values(x.form)])) + expect(values(x.form)).toEqual([]) + x.items[0].click() + x.items[0].click() + x.items[2].click() + expect(events).toEqual([[input, ['a,b']], [input, []], [input, ['d']]]) + expect(input.isConnected).toBeTrue() + }) + + it('should support empty and repeated option values without conflating selection identity', () => { + const x = make({}, { values: ['', 'same', 'same'] }) + const events = [] + x.form.addEventListener('change', event => events.push(event.target.value)) + x.items[1].click() + x.items[2].click() + x.items[2].click() + x.items[0].click() + expect(events).toEqual(['same', 'same', '']) + expect(values(x.form)).toEqual(['']) + }) + + it('should update fields before input, change, and the component event', () => { + const x = make() + const events = [] + for (const type of ['input', 'change', 'change.bs.combobox']) { + x.form.addEventListener(type, event => events.push([type, values(x.form), event.value])) + } + + x.items[1].click() + expect(events).toEqual([['input', ['c'], undefined], ['change', ['c'], undefined], ['change.bs.combobox', ['c'], 'c']]) + }) + + it('should announce unnamed selections from the toggle without creating a form field', () => { + const x = make({ name: null }) + const targets = [] + x.form.addEventListener('change', event => targets.push(event.target)) + x.items[1].click() + expect(targets).toEqual([x.toggle]) + expect(x.form.querySelector('input[type="hidden"]')).toBeNull() + }) + + it('should not emit changes during initialization, updates, or reset', async () => { + const form = document.createElement('form') + fixture.append(form) + const events = [] + form.addEventListener('change', event => events.push(event.type)) + const x = make({}, { form, selected: [0] }) + x.instance.update() + form.reset() + await tick() + expect(events).toEqual([]) + }) + + it('should retain a completed reset when a second reset is canceled', async () => { + const x = make({}, { selected: [0] }) + x.items[1].click() + x.form.reset() + x.form.addEventListener('reset', event => event.preventDefault(), { once: true }) + x.form.reset() + await new Promise(resolve => { + setTimeout(resolve, 10) + }) + expect(x.instance.getValues()).toEqual(['a,b']) + expect(values(x.form)).toEqual(['a,b']) + }) + + it('should close from Escape while the button keeps focus', async () => { + const x = make({ search: false }) + await x.instance.show() + x.toggle.focus() + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }) + x.toggle.dispatchEvent(event) + await tick() + expect(event.defaultPrevented).toBeTrue() + expect(x.menu.classList.contains('show')).toBeFalse() + expect(x.toggle.getAttribute('aria-expanded')).toEqual('false') + expect(document.activeElement).toBe(x.toggle) + }) + + it('should set and restore option roles in button mode', () => { + const x = make({ multiple: true }, { selected: [0] }) + expect(x.menu.getAttribute('role')).toEqual('listbox') + expect(x.menu.getAttribute('aria-multiselectable')).toEqual('true') + expect(x.toggle.getAttribute('aria-controls')).toEqual(x.menu.id) + expect(x.items[0].getAttribute('role')).toEqual('option') + expect(x.items[0].getAttribute('aria-selected')).toEqual('true') + x.instance.dispose() + expect(x.menu.hasAttribute('role')).toBeFalse() + expect(x.items[0].hasAttribute('role')).toBeFalse() + }) + + it('should retain a provided field and its attributes when disposed', () => { + const input = field() + const x = make({}, { input }) + x.items[1].click() + x.instance.dispose() + expect(input.isConnected).toBeTrue() + expect(input.id).toEqual('provided') + expect(input.dataset.validation).toEqual('preserve') + expect(new FormData(x.form).getAll('provided-name')).toEqual(['c']) + expect(values(x.form)).toEqual([]) + }) + + it('should preserve a provided field while removing only generated multiple fields', () => { + const input = field() + const x = make({ multiple: true }, { input }) + x.items[0].click() + x.items[1].click() + expect(new FormData(x.form).getAll('provided-name')).toEqual(['a,b', 'c']) + x.instance.dispose() + expect(x.form.querySelectorAll('input[type="hidden"]').length).toEqual(1) + expect(input.disabled).toBeFalse() + expect(input.value).toEqual('a,b') + }) + + it('should preserve caller-disabled fields, including changes made before disposal', () => { + const input = field() + const x = make({ multiple: true }, { input }) + input.disabled = true + x.instance.dispose() + expect(input.disabled).toBeTrue() + }) + + it('should resolve an explicit input selector and reject an invalid field', () => { + const input = field() + fixture.append(input) + const x = make({ input: '#provided' }) + expect(x.instance._hiddenInput).toBe(input) + expect(() => new Combobox(x.toggle, { input: '.combobox-value' })).toThrowError(TypeError) + }) + + it('should isolate widgets that share a field name', () => { + const first = make({ multiple: true }) + const second = make({ multiple: true }, { form: first.form }) + first.items[0].click() + second.items[2].click() + first.instance.dispose() + expect(values(second.form)).toEqual(['d']) + }) + + it('should omit disabled controls and restore them after reenabling', async () => { + const x = make({ multiple: true }) + x.items[0].click() + x.items[1].click() + x.toggle.disabled = true + await tick() + expect(values(x.form)).toEqual([]) + x.toggle.disabled = false + await tick() + expect(values(x.form)).toEqual(['a,b', 'c']) + x.items[2].disabled = true + x.items[2].classList.add('selected') + x.instance.update() + expect(values(x.form)).toEqual(['a,b', 'c']) + }) + + it('should reconcile synchronous changes before FormData when update is called', () => { + const x = make() + x.items[1].click() + x.toggle.disabled = true + x.instance.update() + expect(values(x.form)).toEqual([]) + }) + + it('should reconcile before an immediate native submit', () => { + const x = make() + x.items[1].click() + x.toggle.disabled = true + let submitted + x.form.addEventListener('submit', event => { + event.preventDefault() + submitted = values(x.form) + }) + x.form.requestSubmit() + expect(submitted).toEqual([]) + }) + + it('should follow a disabled fieldset when the provided input is outside it', async () => { + const input = field() + const x = make({}, { input }) + const fieldset = document.createElement('fieldset') + x.form.append(fieldset) + fieldset.append(x.toggle, x.menu) + x.instance.update() + x.items[1].click() + fieldset.disabled = true + await tick() + expect(new FormData(x.form).getAll(input.name)).toEqual([]) + fieldset.disabled = false + await tick() + expect(new FormData(x.form).getAll(input.name)).toEqual(['c']) + }) + + it('should keep a control inside the first legend enabled', async () => { + const x = make() + const fieldset = document.createElement('fieldset') + const legend = document.createElement('legend') + x.form.append(fieldset) + fieldset.append(legend) + legend.append(x.toggle, x.menu) + x.instance.update() + fieldset.disabled = true + await tick() + x.items[1].click() + expect(values(x.form)).toEqual(['c']) + }) + + it('should ignore selected decoration that is not an option', () => { + const x = make() + const decoration = document.createElement('span') + decoration.className = 'selected' + x.menu.append(decoration) + x.instance.update() + expect(values(x.form)).toEqual(['']) + expect(x.toggle.textContent).toEqual('') + }) + + it('should follow an external form owner', () => { + const x = make({ multiple: true }) + x.form.id = 'external-combobox-form' + fixture.append(x.toggle, x.menu) + x.toggle.setAttribute('form', x.form.id) + x.items[0].click() + x.items[1].click() + expect(values(x.form)).toEqual(['a,b', 'c']) + x.form.reset() + }) + + it('should restore initial selection on reset and honor cancellation', async () => { + const x = make({ multiple: true }, { selected: [0, 2] }) + x.items[0].click() + x.items[1].click() + x.form.addEventListener('reset', event => event.preventDefault(), { once: true }) + x.form.reset() + await tick() + expect(values(x.form)).toEqual(['c', 'd']) + x.form.reset() + await tick() + expect(values(x.form)).toEqual(['a,b', 'd']) + }) + + it('should ignore a queued reset after the component changes form owner', async () => { + const x = make() + x.items[1].click() + x.form.reset() + const otherForm = document.createElement('form') + fixture.append(otherForm) + otherForm.append(x.toggle, x.menu) + x.instance.update() + await tick() + expect(values(otherForm)).toEqual(['c']) + }) + + it('should clear the displayed value after the last deselection without a placeholder', () => { + const x = make({ multiple: true }) + x.items[1].click() + x.items[1].click() + expect(x.toggle.textContent).toEqual('') + }) + + it('should stop notifications safely when an input listener disposes the component', () => { + const x = make() + const events = [] + x.form.addEventListener('input', () => { + events.push('input') + x.instance.dispose() + }) + x.form.addEventListener('change', () => events.push('change')) + expect(() => x.items[1].click()).not.toThrow() + expect(events).toEqual(['input']) + }) + + it('should honor a nested selection without announcing stale outer state', () => { + const x = make() + const customValues = [] + x.form.addEventListener('input', () => x.items[2].click(), { once: true }) + x.toggle.addEventListener('change.bs.combobox', event => customValues.push(event.value)) + x.items[1].click() + expect(values(x.form)).toEqual(['d']) + expect(customValues).toEqual(['d']) + }) + + it('should forward Menu cancellation and completion after the real transition', async () => { + const x = make() + x.menu.style.transitionDuration = '.03s' + const events = [] + x.toggle.addEventListener('shown.bs.combobox', () => events.push('shown')) + const showing = x.instance.show() + expect(events).toEqual([]) + await showing + expect(events).toEqual(['shown']) + x.toggle.addEventListener('hide.bs.combobox', event => event.preventDefault(), { once: true }) + await Menu.getInstance(x.toggle).hide() + expect(x.menu).toHaveClass('show') + await x.instance.hide() + expect(x.menu).not.toHaveClass('show') + }) + + it('should not move focus after disposal during the opening transition', async () => { + const x = make() + x.menu.style.transitionDuration = '.03s' + const showing = x.instance.show() + expect(document.activeElement).toBe(x.search) + x.instance.dispose() + x.toggle.focus() + await showing + expect(document.activeElement).toBe(x.toggle) + }) + + it('should permit Home and End text editing in RTL while retaining option navigation', async () => { + document.documentElement.dir = 'rtl' + const x = make() + await x.instance.show() + x.search.focus() + for (const key of ['Home', 'End']) { + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }) + x.search.dispatchEvent(event) + expect(event.defaultPrevented).toBeFalse() + expect(document.activeElement).toBe(x.search) + } + + x.items[1].focus() + x.items[1].dispatchEvent(new KeyboardEvent('keydown', { key: 'End', bubbles: true, cancelable: true })) + expect(document.activeElement).toBe(x.items[2]) + }) +}) diff --git a/js/tests/unit/combobox-layout.spec.js b/js/tests/unit/combobox-layout.spec.js new file mode 100644 index 0000000000..f4c91e9d14 --- /dev/null +++ b/js/tests/unit/combobox-layout.spec.js @@ -0,0 +1,46 @@ +import css from '../../../scss/bootstrap.scss?inline' +import { clearFixture, getFixture } from '../helpers/fixture.js' + +describe('Combobox control sizing', () => { + let fixture + let style + + beforeEach(() => { + fixture = getFixture() + style = document.createElement('style') + style.textContent = css + document.head.append(style) + }) + + afterEach(() => { + style.remove() + clearFixture() + }) + + for (const [name, height, padding, fontSize, lineHeight] of [ + ['compact', 30, 4, 14, 20], + ['default', 38, 6, 16, 24], + ['spacious', 48, 10, 18, 26] + ]) { + it(`should match other controls with ${name} sizing tokens`, () => { + fixture.style.setProperty('--btn-input-min-height', `${height}px`) + fixture.style.setProperty('--btn-input-padding-y', `${padding}px`) + fixture.style.setProperty('--btn-input-font-size', `${fontSize}px`) + fixture.style.setProperty('--btn-input-line-height', `${lineHeight}px`) + fixture.innerHTML = ` + +
+ Design + +
+ ` + const input = fixture.querySelector('.form-control') + const control = fixture.querySelector('.combobox-control') + expect(input.getBoundingClientRect().height).toBeCloseTo(height, 1) + expect(control.getBoundingClientRect().height).toBeCloseTo(height, 1) + const chip = control.querySelector('.chip').getBoundingClientRect() + const dismiss = control.querySelector('.chip-dismiss').getBoundingClientRect() + expect(dismiss.height).toBeLessThanOrEqual(chip.height) + }) + } +}) diff --git a/js/tests/unit/combobox.spec.js b/js/tests/unit/combobox.spec.js index 6eb17b6b9e..5489b587f0 100644 --- a/js/tests/unit/combobox.spec.js +++ b/js/tests/unit/combobox.spec.js @@ -1,3 +1,4 @@ +import { page, userEvent } from 'vitest/browser' import Combobox from '../../src/combobox.js' import EventHandler from '../../src/dom/event-handler.js' import Menu from '../../src/menu.js' @@ -316,7 +317,7 @@ describe('Combobox', () => { items[1].click() expect(valueEl.textContent).toEqual('2 selected') - expect(fixtureEl.querySelector('input[type="hidden"]').value).toEqual('us,uk') + expect([...fixtureEl.querySelectorAll('input[type="hidden"]')].map(input => input.value)).toEqual(['us', 'uk']) }) it('should fire change with every selected value', () => { @@ -344,6 +345,33 @@ describe('Combobox', () => { describe('search', () => { const searchMarkup = () => markup({ search: SEARCH_HTML, noResults: NO_RESULTS_HTML }) + it('should focus search directly on click and return to the toggle on Escape', async () => { + const { combobox, menuEl, toggleEl } = makeCombobox({ search: true, placeholder: 'Select a country' }, searchMarkup()) + const searchEl = menuEl.querySelector('.combobox-search-input') + const focusOrder = [] + toggleEl.style.cssText = 'position: fixed; top: 1rem; left: 1rem' + toggleEl.addEventListener('focus', () => focusOrder.push(toggleEl)) + searchEl.addEventListener('focus', () => focusOrder.push(searchEl)) + + try { + const toggle = page.getByRole('button', { name: 'Select a country' }) + await toggle.click() + + expect(focusOrder).toEqual([searchEl]) + expect(document.activeElement).toBe(searchEl) + + keydown(searchEl, 'Escape') + + expect(document.activeElement).toBe(toggleEl) + + await userEvent.keyboard('{Enter}') + + expect(document.activeElement).toBe(searchEl) + } finally { + combobox.dispose() + } + }) + const typeSearch = (searchEl, value) => { searchEl.value = value searchEl.dispatchEvent(new Event('input', { bubbles: true })) diff --git a/js/tests/unit/range.spec.js b/js/tests/unit/range.spec.js index 4c8acebd53..9cf48b39fa 100644 --- a/js/tests/unit/range.spec.js +++ b/js/tests/unit/range.spec.js @@ -116,6 +116,219 @@ describe('Range', () => { }) }) + describe('explicit refresh', () => { + it('should refresh a programmatic value without a native input event', () => { + fixtureEl.innerHTML = getRangeHtml('data-bs-bubble') + const wrapper = fixtureEl.querySelector('.form-range') + const input = wrapper.querySelector('input') + const range = new Range(wrapper) + input.value = '75' + expect(wrapper.style.getPropertyValue('--bs-range-fill')).toEqual('0.5') + range.update() + expect(wrapper.style.getPropertyValue('--bs-range-fill')).toEqual('0.75') + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('75') + }) + + it('should apply added, false, removed, and bare bubble attributes without duplicates', () => { + fixtureEl.innerHTML = getRangeHtml() + const wrapper = fixtureEl.querySelector('.form-range') + const range = new Range(wrapper) + for (const value of ['true', 'false', '', null, 'true']) { + if (value === null) { + wrapper.removeAttribute('data-bs-bubble') + } else { + wrapper.setAttribute('data-bs-bubble', value) + } + + range.update() + range.update() + const enabled = value === 'true' || value === '' + expect(wrapper.querySelectorAll('.form-range-bubble').length).toEqual(enabled ? 1 : 0) + if (enabled) { + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('50') + } + } + }) + + it('should preserve copied JavaScript options over current data configuration', () => { + fixtureEl.innerHTML = getRangeHtml('data-bs-bubble="false"') + const wrapper = fixtureEl.querySelector('.form-range') + const options = { bubble: true, formatter: value => `${value}%` } + const range = new Range(wrapper, options) + options.bubble = false + wrapper.dataset.bsConfig = '{"bubble":false}' + range.update() + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('50%') + }) + + it('should reread JSON configuration and validate before changing decorations', () => { + fixtureEl.innerHTML = getRangeHtml() + const wrapper = fixtureEl.querySelector('.form-range') + const range = new Range(wrapper) + wrapper.dataset.bsConfig = '{"bubble":true}' + range.update() + expect(wrapper.querySelector('.form-range-bubble')).not.toBeNull() + wrapper.dataset.bsBubble = 'invalid' + expect(() => range.update()).toThrowError(TypeError) + expect(wrapper.querySelectorAll('.form-range-bubble').length).toEqual(1) + }) + + it('should not refresh configuration or rebuild ticks during input events', () => { + fixtureEl.innerHTML = ` + ${getRangeHtml('', 'list="live-ticks"')} + + ` + const wrapper = fixtureEl.querySelector('.form-range') + const range = new Range(wrapper) + const ticks = wrapper.querySelector('.form-range-ticks') + wrapper.dataset.bsBubble = 'true' + wrapper.querySelector('input').dispatchEvent(createEvent('input')) + expect(wrapper.querySelector('.form-range-bubble')).toBeNull() + expect(wrapper.querySelector('.form-range-ticks')).toEqual(ticks) + range.dispose() + }) + + it('should tolerate an instance without an input', () => { + fixtureEl.innerHTML = '
' + const range = new Range(fixtureEl.firstElementChild) + expect(() => range.update()).not.toThrow() + expect(() => range.dispose()).not.toThrow() + }) + + it('should rebuild current tick values, labels, bounds, and list association', () => { + fixtureEl.innerHTML = ` + ${getRangeHtml('', 'list="first-list"')} + + + ` + const wrapper = fixtureEl.querySelector('.form-range') + const input = wrapper.querySelector('input') + const range = new Range(wrapper) + const option = fixtureEl.querySelector('#second-list option') + input.setAttribute('list', 'second-list') + input.max = '200' + range.update() + expect(wrapper.querySelector('.form-range-ticks').style.gridTemplateColumns).toEqual('0.25fr 0.75fr') + expect(wrapper.querySelector('.form-range-tick-label').textContent).toEqual('Center') + option.value = '100' + option.label = 'New label' + input.min = '50' + range.update() + range.update() + expect(wrapper.querySelectorAll('.form-range-ticks').length).toEqual(1) + expect(wrapper.querySelectorAll('.form-range-tick').length).toEqual(1) + expect(wrapper.querySelector('.form-range-tick-label').textContent).toEqual('New label') + fixtureEl.querySelector('#second-list').replaceChildren() + range.update() + expect(wrapper.querySelector('.form-range-ticks')).toBeNull() + fixtureEl.querySelector('#second-list').append(option) + range.update() + input.removeAttribute('list') + range.update() + expect(wrapper.querySelector('.form-range-ticks')).toBeNull() + }) + }) + + describe('native reset', () => { + const settle = () => new Promise(resolve => { + setTimeout(resolve, 10) + }) + const prepare = (external = false) => { + const control = getRangeHtml('data-bs-bubble', external ? 'form="range-form"' : '') + fixtureEl.innerHTML = ` +
${external ? '' : control}
+ ${external ? control : ''} + ` + const wrapper = fixtureEl.querySelector('.form-range') + const input = wrapper.querySelector('input') + const form = fixtureEl.querySelector('form') + const range = new Range(wrapper) + input.value = '80' + range.update() + return { + wrapper, input, form, range + } + } + + for (const external of [false, true]) { + it(`should refresh after a real reset button restores an ${external ? 'externally associated' : 'enclosed'} input`, async () => { + const { wrapper, form, range } = prepare(external) + form.querySelector('button').click() + await settle() + expect(wrapper.style.getPropertyValue('--bs-range-fill')).toEqual('0.5') + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('50') + expect(wrapper.querySelector('.tooltip-arrow')).not.toBeNull() + expect(wrapper.querySelector('.form-range-bubble').tagName).toEqual('DIV') + range.dispose() + }) + } + + it('should respect reset cancellation by a later listener', async () => { + const { wrapper, input, form, range } = prepare() + let events = 0 + input.addEventListener('changed.bs.range', () => events++) + form.addEventListener('reset', event => event.preventDefault()) + form.reset() + await settle() + expect(input.value).toEqual('80') + expect(wrapper.style.getPropertyValue('--bs-range-fill')).toEqual('0.8') + expect(events).toEqual(0) + range.dispose() + }) + + it('should keep a completed reset when a subsequent reset is canceled', async () => { + const { wrapper, form, range } = prepare() + form.reset() + form.addEventListener('reset', event => event.preventDefault(), { once: true }) + form.reset() + await settle() + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('50') + range.dispose() + }) + + it('should cancel pending resets and release the listener on disposal', async () => { + const { input, form, range } = prepare() + let events = 0 + input.addEventListener('changed.bs.range', () => events++) + form.reset() + range.dispose() + await settle() + form.reset() + await settle() + expect(events).toEqual(0) + }) + + it('should preserve other Range listeners when one instance is disposed', async () => { + const { wrapper, form, range } = prepare() + form.insertAdjacentHTML('beforeend', getRangeHtml('data-bs-bubble')) + const second = form.querySelectorAll('.form-range')[1] + const other = new Range(second) + second.querySelector('input').value = '90' + other.update() + range.dispose() + form.reset() + await settle() + expect(second.querySelector('.tooltip-inner').textContent).toEqual('50') + expect(wrapper.querySelector('.form-range-bubble')).toBeNull() + other.dispose() + }) + + it('should rebind the form association on explicit update', async () => { + const { wrapper, input, form, range } = prepare(true) + form.insertAdjacentHTML('afterend', '
') + input.setAttribute('form', 'other-form') + range.update() + input.value = '70' + form.reset() + await settle() + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('80') + fixtureEl.querySelector('#other-form').reset() + await settle() + expect(wrapper.querySelector('.tooltip-inner').textContent).toEqual('50') + range.dispose() + }) + }) + describe('bubble', () => { it('should create a tooltip-based value bubble when enabled', () => { fixtureEl.innerHTML = getRangeHtml('data-bs-bubble') diff --git a/js/tests/unit/tab.spec.js b/js/tests/unit/tab.spec.js index 396c54107a..7a9ce37849 100644 --- a/js/tests/unit/tab.spec.js +++ b/js/tests/unit/tab.spec.js @@ -3,6 +3,16 @@ import { clearFixture, createEvent, getFixture } from '../helpers/fixture.js' +const setHash = hash => { + const url = new URL(window.location.href) + url.hash = hash + window.history.replaceState(null, '', url) +} + +const clearHash = () => { + setHash('') +} + describe('Tab', () => { let fixtureEl @@ -12,6 +22,7 @@ describe('Tab', () => { afterEach(() => { clearFixture() + clearHash() }) describe('VERSION', () => { @@ -1295,4 +1306,107 @@ describe('Tab', () => { }) }) }) + + describe('hash target', () => { + it('should scroll the trigger, show the pane, then scroll the pane on load', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#triggerProfileHash') + const pane = fixtureEl.querySelector('#profileHash') + const triggerScrollSpy = spyOn(trigger, 'scrollIntoView') + + spyOn(pane, 'scrollIntoView').and.callFake(() => { + expect(triggerScrollSpy).toHaveBeenCalled() + expect(trigger).toHaveClass('active') + expect(pane).toHaveClass('active') + resolve() + }) + + setHash('profileHash') + window.dispatchEvent(createEvent('load')) + }) + }) + + it('should scroll the trigger, show the pane, then scroll the pane on hashchange', () => { + return new Promise(resolve => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#triggerProfileHashChange') + const pane = fixtureEl.querySelector('#profileHashChange') + const triggerScrollSpy = spyOn(trigger, 'scrollIntoView') + + spyOn(pane, 'scrollIntoView').and.callFake(() => { + expect(triggerScrollSpy).toHaveBeenCalled() + expect(trigger).toHaveClass('active') + expect(pane).toHaveClass('active') + resolve() + }) + + setHash('profileHashChange') + window.dispatchEvent(createEvent('hashchange')) + }) + }) + + it('should scroll an already-active hash tab pane into view', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
' + ].join('') + + const pane = fixtureEl.querySelector('#homeHashOpen') + const scrollSpy = spyOn(pane, 'scrollIntoView') + const showSpy = spyOn(Tab.prototype, 'show').and.callThrough() + + setHash('homeHashOpen') + window.dispatchEvent(createEvent('load')) + + expect(showSpy).not.toHaveBeenCalled() + expect(scrollSpy).toHaveBeenCalled() + }) + + it('should ignore tab panes without data-bs-hash', () => { + fixtureEl.innerHTML = [ + '', + '
', + '
', + '
', + '
' + ].join('') + + const trigger = fixtureEl.querySelector('#triggerProfileNoHash') + const showSpy = spyOn(Tab.prototype, 'show').and.callThrough() + + setHash('profileNoHash') + window.dispatchEvent(createEvent('load')) + + expect(trigger).not.toHaveClass('active') + expect(showSpy).not.toHaveBeenCalled() + }) + }) }) diff --git a/js/tests/unit/util/hash-target.spec.js b/js/tests/unit/util/hash-target.spec.js new file mode 100644 index 0000000000..7133da4e69 --- /dev/null +++ b/js/tests/unit/util/hash-target.spec.js @@ -0,0 +1,83 @@ +import EventHandler from '../../../src/dom/event-handler.js' +import { decodeFragment, enableHashTarget, getHashTarget } from '../../../src/util/hash-target.js' +import { clearFixture, getFixture } from '../../helpers/fixture.js' + +describe('Hash targets', () => { + let fixture + const namespace = '.hash-target-test' + const setHash = hash => { + const url = new URL(window.location.href) + url.hash = hash + window.history.replaceState(null, '', url) + } + + beforeEach(() => { + fixture = getFixture() + setHash('') + }) + + afterEach(() => { + EventHandler.off(window, namespace) + setHash('') + clearFixture() + }) + + it('should decode valid escapes and retain malformed escapes', () => { + expect(decodeFragment('a%3Ab')).toEqual('a:b') + expect(decodeFragment('a%zz')).toEqual('a%zz') + }) + + it('should resolve punctuation without treating the fragment as a selector', () => { + fixture.innerHTML = '
' + setHash('a%3Ab.c%2F%25') + expect(getHashTarget()).toBe(fixture.firstElementChild) + fixture.firstElementChild.removeAttribute('data-bs-hash') + expect(getHashTarget()).toBeNull() + }) + + it('should open the current hash when initialized after load', () => { + fixture.innerHTML = '
' + setHash('late-target') + const open = jasmine.createSpy('open') + spyOnProperty(document, 'readyState', 'get').and.returnValue('complete') + enableHashTarget(namespace, { matches: () => true, open }) + expect(open).toHaveBeenCalledWith(fixture.firstElementChild, jasmine.any(Function)) + }) + + it('should ignore a completed animation after navigation to another hash', () => { + fixture.innerHTML = '
' + const first = fixture.firstElementChild + const second = fixture.lastElementChild + const firstScroll = spyOn(first, 'scrollIntoView') + const secondScroll = spyOn(second, 'scrollIntoView') + const pending = [] + enableHashTarget(namespace, { matches: () => true, open: (element, done) => pending.push(done) }) + setHash('first') + window.dispatchEvent(new Event('hashchange')) + setHash('second') + window.dispatchEvent(new Event('hashchange')) + pending[0]() + pending[1]() + expect(firstScroll).not.toHaveBeenCalled() + expect(secondScroll).toHaveBeenCalledTimes(1) + }) + + it('should ignore a removed target and a cleared fragment', () => { + fixture.innerHTML = '
' + let finish + const target = fixture.firstElementChild + const scroll = spyOn(target, 'scrollIntoView') + enableHashTarget(namespace, { + matches: () => true, + open(element, done) { + finish = done + } + }) + setHash('removed') + window.dispatchEvent(new Event('hashchange')) + target.remove() + setHash('') + finish() + expect(scroll).not.toHaveBeenCalled() + }) +}) diff --git a/package-lock.json b/package-lock.json index 2986aab6a1..ffffb3a329 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41,7 +41,7 @@ "eslint": "^10.14.0", "eslint-config-xo": "^0.53.2", "eslint-plugin-html": "^8.2.1", - "eslint-plugin-import-x": "^4.18.1", + "eslint-plugin-import-x": "^4.17.1", "eslint-plugin-markdown": "^5.1.0", "eslint-plugin-unicorn": "^68.0.0", "find-unused-sass-variables": "^6.2.1", @@ -2075,17 +2075,16 @@ } }, "node_modules/@eslint/config-array/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.5" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -3068,12 +3067,95 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@isaacs/nonrecursive-glob-match": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", - "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", "dev": true, - "license": "BlueOak-1.0.0" + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } }, "node_modules/@istanbuljs/schema": { "version": "0.1.6", @@ -3749,6 +3831,17 @@ "node": ">=0.10" } }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, "node_modules/@pkgr/core": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", @@ -4837,17 +4930,16 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.8" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -6686,13 +6778,6 @@ "node": ">=8" } }, - "node_modules/cjs-module-lexer": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.3.0.tgz", - "integrity": "sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==", - "dev": true, - "license": "MIT" - }, "node_modules/clipboard": { "version": "2.0.11", "resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.11.tgz", @@ -7567,6 +7652,13 @@ "node": ">=4" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "dev": true, + "license": "MIT" + }, "node_modules/electron-to-chromium": { "version": "1.5.428", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.428.tgz", @@ -8048,20 +8140,18 @@ } }, "node_modules/eslint-plugin-import-x": { - "version": "4.18.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-import-x/-/eslint-plugin-import-x-4.18.1.tgz", - "integrity": "sha512-D1h++38NS2Z40zf8jbd2OHqDrnIFRKpdp8sL0jP4xSDGZj6MNwEQua8F+r3tOWjcHrsWuhHOJ7wASWioJ31tfg==", + "version": "4.17.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-import-x/-/eslint-plugin-import-x-4.17.1.tgz", + "integrity": "sha512-4cdstYkKCyjumM2Q9NSI03K8D2a9F4Ssz33K2lv2hQa4KmR9jPLwk3uWGtNvclfqBrPGfGuMBwsGMbe6dMRbfg==", "dev": true, "license": "MIT", "dependencies": { "@typescript-eslint/types": "^8.56.0", - "cjs-module-lexer": "^2.2.1", "comment-parser": "^1.4.1", "debug": "^4.4.1", - "es-module-lexer": "^3.0.3", "eslint-import-context": "^0.1.9", "is-glob": "^4.0.3", - "minimatch": "^9.0.3 || ^10.1.2 || ^11.0.1", + "minimatch": "^9.0.3 || ^10.1.2", "semver": "^7.7.2", "stable-hash-x": "^0.2.0", "unrs-resolver": "^1.9.2" @@ -8109,25 +8199,17 @@ "node": "20 || >=22" } }, - "node_modules/eslint-plugin-import-x/node_modules/es-module-lexer": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-3.0.4.tgz", - "integrity": "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==", - "dev": true, - "license": "MIT" - }, "node_modules/eslint-plugin-import-x/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.8" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -8443,17 +8525,16 @@ "license": "MIT" }, "node_modules/eslint/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.8" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -9034,6 +9115,36 @@ "node": ">=20" } }, + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", + "dev": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/format": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz", @@ -10272,6 +10383,22 @@ "dev": true, "license": "ISC" }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/jasmine": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/jasmine/-/jasmine-7.0.0.tgz", @@ -10294,59 +10421,72 @@ "dev": true, "license": "MIT" }, - "node_modules/jasmine/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, "node_modules/jasmine/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" + "balanced-match": "^1.0.0" } }, "node_modules/jasmine/node_modules/glob": { - "version": "14.0.4", - "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.4.tgz", - "integrity": "sha512-mMiwNKoJZ4HAIRVJxotO6LsNRReA30gQwP9E2/p94tfLv+jygCNpKDjhhSL6OLY6LE371EZm5EAf7RpYuUqlsw==", + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", "dev": true, - "license": "BlueOak-1.0.0", + "license": "ISC", "dependencies": { - "minimatch": "^11.0.5", - "minipass": "^7.1.3", - "path-scurry": "^3.0.0" + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" }, - "engines": { - "node": "18 || 20 || >=22" + "bin": { + "glob": "dist/esm/bin.mjs" }, "funding": { "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/jasmine/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, "node_modules/jasmine/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jasmine/node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" }, "engines": { - "node": "20 || >=22" + "node": ">=16 || 14 >=14.18" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -10963,16 +11103,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/magic-string": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", @@ -11183,17 +11313,16 @@ } }, "node_modules/markdownlint-cli/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.8" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -13241,11 +13370,11 @@ } }, "node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", "dev": true, - "license": "BlueOak-1.0.0", + "license": "ISC", "engines": { "node": ">=16 || 14 >=14.17" } @@ -13484,17 +13613,16 @@ } }, "node_modules/nodemon/node_modules/minimatch": { - "version": "11.0.7", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz", - "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==", + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/nonrecursive-glob-match": "^1.1.0", - "brace-expansion": "^5.0.12" + "brace-expansion": "^5.0.5" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -13848,6 +13976,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/package-manager-detector": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz", @@ -14022,23 +14157,6 @@ "node": ">=8" } }, - "node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/path-type": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", @@ -15881,6 +15999,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/string-width/node_modules/ansi-regex": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", @@ -15949,6 +16083,20 @@ "node": ">=8" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-final-newline": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", @@ -17191,6 +17339,16 @@ } } }, + "node_modules/unstorage/node_modules/lru-cache": { + "version": "11.5.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.0.tgz", + "integrity": "sha512-5YgH9UJd7wVb9hIouI2adWpgqrrICkt070Dnj8EUY1+B4B2P9eRLPAkAAo6NICA7CEhOIeBHl46u9zSNpNu7zA==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/update-browserslist-db": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz", @@ -18130,6 +18288,56 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/wrap-ansi/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", diff --git a/package.json b/package.json index a43c1d408a..19556a3ac4 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,7 @@ "css-prefix-main": "postcss --config build/postcss.config.mjs --replace \"dist/css/*.css\" \"!dist/css/*.min.css\" \"!dist/css/*.tmp.css\"", "css-prefix-examples": "postcss --config build/postcss.config.mjs --replace \"site/src/assets/examples/**/*.css\"", "css-test": "jasmine --config=scss/tests/jasmine.cjs", + "css-test-grid": "node build/test-grid-layout.mjs", "js": "npm-run-all --aggregate-output --parallel js-emit-types js-build", "js-build": "npm-run-all js-compile js-minify", "js-compile": "npm-run-all --aggregate-output --parallel js-compile-*", @@ -153,7 +154,7 @@ "eslint": "^10.14.0", "eslint-config-xo": "^0.53.2", "eslint-plugin-html": "^8.2.1", - "eslint-plugin-import-x": "^4.18.1", + "eslint-plugin-import-x": "^4.17.1", "eslint-plugin-markdown": "^5.1.0", "eslint-plugin-unicorn": "^68.0.0", "find-unused-sass-variables": "^6.2.1", @@ -206,25 +207,7 @@ ".browserslistrc" ], "overrides": { - "@typescript-eslint/typescript-estree": { - "minimatch": "^11.0.1" - }, "axios": "^1.16.0", - "eslint": { - "minimatch": "^11.0.1" - }, - "eslint-plugin-import-x": { - "minimatch": "^11.0.1" - }, - "jasmine": { - "glob": "^14.0.4" - }, - "markdownlint-cli": { - "minimatch": "^11.0.1" - }, - "nodemon": { - "minimatch": "^11.0.1" - }, "re2js": "^2.8.7" } } diff --git a/scss/_chip.scss b/scss/_chip.scss index dd0bce94f0..3ff81378ef 100644 --- a/scss/_chip.scss +++ b/scss/_chip.scss @@ -41,31 +41,36 @@ $chip-tokens: defaults( height: var(--chip-height); padding-inline: var(--chip-padding-x); font-size: var(--chip-font-size, var(--font-size-sm)); - font-weight: var(--chip-font-weight, var(--font-weight-base)); + font-weight: var(--chip-font-weight, var(--font-weight-normal)); line-height: var(--chip-line-height, 1.25rem); color: var(--chip-color); text-decoration: none; white-space: nowrap; vertical-align: middle; - cursor: pointer; background-color: var(--chip-bg); border: var(--border-width) solid var(--chip-border-color); @include border-radius(var(--chip-border-radius)); - &:hover { - --chip-bg: var(--theme-bg-muted, var(--bg-3)); - } - &:focus-visible { - outline: 0; + @include focus-ring(false, var(--theme-focus-ring, var(--focus-ring-color))); } &.active { --chip-color: var(--chip-selected-color); --chip-bg: var(--chip-selected-bg); --chip-border-color: var(--chip-selected-border-color); + } + + &:is(:any-link, button, [role="button"], [role="link"]):not(:disabled, .disabled, [aria-disabled="true"]), + :is(:any-link, button, [role="button"], [role="link"]):not(:disabled, .disabled, [aria-disabled="true"]) &, + .combobox-control > & { + cursor: pointer; &:hover { + --chip-bg: var(--theme-bg-muted, var(--bg-3)); + } + + &.active:hover { --chip-bg: var(--chip-selected-bg); opacity: .9; } @@ -74,7 +79,7 @@ $chip-tokens: defaults( &.disabled, &:disabled { pointer-events: none; - opacity: .65; + opacity: var(--control-disabled-opacity); } } @@ -133,7 +138,7 @@ $chip-tokens: defaults( &:focus-visible { outline: 0; opacity: 1; - @include focus-ring(); + @include focus-ring(false, var(--theme-focus-ring, var(--focus-ring-color))); } > svg { diff --git a/scss/content/_prose.scss b/scss/content/_prose.scss index fc977cbd62..59eef57318 100644 --- a/scss/content/_prose.scss +++ b/scss/content/_prose.scss @@ -62,11 +62,11 @@ $prose-tokens: defaults( :where(h1, h2, h3, h4, h5, h6):not([class], :where(.not-prose, .not-prose *)) { margin-top: 0; margin-bottom: calc(var(--content-gap) / -2); - font-weight: 500; + font-weight: var(--font-weight-medium); line-height: 1.25; code { - font-weight: 600; + font-weight: var(--font-weight-semibold); color: inherit; } } @@ -112,16 +112,16 @@ $prose-tokens: defaults( } } - :where(img):not(:where(.not-prose, .not-prose *)) { - max-width: 100%; - } - :where(blockquote):not(:where(.not-prose, .not-prose *)) { padding-inline-start: calc(var(--content-gap) / 2); margin: 0; border-inline-start: 4px solid var(--border-color); } + :where(blockquote, details):not(:where(.not-prose, .not-prose *)) > :not(:first-child, :where(.not-prose, .not-prose *)) { + margin-block-start: calc(var(--content-gap) / 2); + } + :where(table):not(:where(.not-prose, .not-prose *)) { width: 100%; border-spacing: 0; @@ -138,11 +138,16 @@ $prose-tokens: defaults( } :where(dt):not(:where(.not-prose, .not-prose *)) { - font-weight: 500; + font-weight: var(--font-weight-medium); } :where(video, img):not(:where(.not-prose, .not-prose *)) { max-width: 100%; + height: auto; // Keep the aspect ratio reserved by `width` and `height` attributes + } + + > :where(video, img):not(:where(.not-prose)) { + align-self: flex-start; // Do not stretch across the flex column } } } diff --git a/scss/forms/_chip-input.scss b/scss/forms/_combobox-control.scss similarity index 52% rename from scss/forms/_chip-input.scss rename to scss/forms/_combobox-control.scss index 1fb6db3101..bbb793465b 100644 --- a/scss/forms/_chip-input.scss +++ b/scss/forms/_combobox-control.scss @@ -3,42 +3,53 @@ @use "../mixins/focus-ring" as *; @use "../mixins/tokens" as *; -$chip-input-tokens: () !default; +$combobox-control-tokens: () !default; -// scss-docs-start chip-input-tokens +// scss-docs-start combobox-control-tokens // stylelint-disable-next-line scss/dollar-variable-default -$chip-input-tokens: defaults( +$combobox-control-tokens: defaults( ( - --chip-input-padding-y: .75rem, - --chip-input-padding-x: .75rem, - --chip-input-gap: .375rem, - --chip-input-ghost-min-width: 5rem, + --combobox-control-padding-y: var(--btn-input-padding-y), + --combobox-control-padding-x: var(--btn-input-padding-x), + --combobox-control-gap: .25rem, + --combobox-control-chip-height: calc(var(--control-min-height) - 2 * var(--combobox-control-padding-y) - 2 * var(--control-border-width)), + --control-min-height: var(--btn-input-min-height), + --control-font-size: var(--btn-input-font-size), + --control-line-height: var(--btn-input-line-height), + --combobox-control-ghost-min-width: 5rem, --control-fg: var(--btn-input-fg), --control-bg: var(--btn-input-bg), --control-border-width: var(--border-width), --control-border-color: var(--border-color), --control-border-radius: var(--radius-5), ), - $chip-input-tokens + $combobox-control-tokens ); -// scss-docs-end chip-input-tokens +// scss-docs-end combobox-control-tokens @layer forms { - .chip-input { - @include tokens($chip-input-tokens); + .combobox-control { + @include tokens($combobox-control-tokens); // Flexbox wrapping layout display: flex; flex-wrap: wrap; - gap: var(--chip-input-gap); + gap: var(--combobox-control-gap); align-items: center; - padding: var(--chip-input-padding-y) var(--chip-input-padding-x); + min-block-size: var(--control-min-height); + padding: var(--combobox-control-padding-y) var(--combobox-control-padding-x); + font-size: var(--control-font-size); + line-height: var(--control-line-height); color: var(--control-fg); background-color: var(--control-bg); border: var(--control-border-width) solid var(--control-border-color); @include border-radius(var(--control-border-radius), 0); + &:has(> .chip) { + padding-inline: var(--combobox-control-padding-y); + } + // Focus state when ghost input is focused &:focus-within { --focus-ring-offset: -1px; @@ -47,10 +58,11 @@ $chip-input-tokens: defaults( } // Ghost input fills remaining space - > .form-ghost { + > .form-ghost, + > .combobox-input { flex: 1 1 0; - min-width: var(--chip-input-ghost-min-width); - min-height: 1.75rem; + min-inline-size: var(--combobox-control-ghost-min-width); + min-block-size: 1lh; } // Disabled state diff --git a/scss/forms/_combobox.scss b/scss/forms/_combobox.scss index 9b99994f38..f1e8dd3227 100644 --- a/scss/forms/_combobox.scss +++ b/scss/forms/_combobox.scss @@ -1,12 +1,42 @@ +@use "../mixins/focus-ring" as *; @use "../mixins/transition" as *; @layer components { + .combobox-control > .chip { + --chip-height: var(--combobox-control-chip-height); + --chip-border-radius: max(0px, calc(var(--control-border-radius) / 2)); + --chip-padding-x: .5rem; + --chip-gap: .25rem; + --chip-dismiss-size: var(--combobox-control-chip-height); + + > .chip-dismiss { + margin-inline: -.25rem -.5rem; + + > svg { + width: .75rem; + height: .75rem; + } + } + + &:focus-visible, + > .chip-dismiss:focus-visible { + @include focus-ring(); + } + } + + .combobox-control + .menu, + .combobox + .menu { + --menu-max-height: 300px; + --menu-overflow-y: auto; + } + .combobox-toggle { display: inline-flex; gap: .5rem; align-items: center; justify-content: space-between; width: 100%; + min-width: 0; padding-inline-end: var(--control-padding-x); text-align: start; cursor: pointer; @@ -18,22 +48,21 @@ &:disabled, &.disabled { cursor: not-allowed; - opacity: .65; + opacity: var(--control-disabled-opacity); } } .combobox-value { - display: flex; + display: block; flex: 1; - gap: .5rem; - align-items: center; + min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .combobox-placeholder { - color: color-mix(in oklch, currentcolor 65%, transparent); + color: var(--control-placeholder-color); } .combobox-caret { @@ -52,7 +81,7 @@ .combobox-search { position: sticky; - top: 0; + inset-block-start: calc(-1 * var(--menu-padding-y, .25rem)); z-index: 1; padding: var(--menu-padding-x, .25rem); background-color: var(--menu-bg, var(--bg-body)); diff --git a/scss/forms/_form-range.scss b/scss/forms/_form-range.scss index 4bd99fe4c0..9f093c5bfd 100644 --- a/scss/forms/_form-range.scss +++ b/scss/forms/_form-range.scss @@ -17,14 +17,16 @@ $range-tokens: defaults( --range-track-height: .5rem, --range-track-cursor: pointer, --range-track-bg: var(--bg-3), - --range-track-border-radius: 1rem, + --range-track-border-radius: var(--radius-pill), + --range-track-box-shadow: var(--box-shadow-inset), --range-track-fill-bg: var(--theme-bg, var(--primary-base)), + --range-track-fill-direction: to right, --range-track-disabled-bg: color-mix(in oklch, var(--bg-4), var(--fg-3)), --range-thumb-width: 1rem, --range-thumb-height: var(--range-thumb-width), --range-thumb-bg: var(--theme-bg, var(--primary-base)), --range-thumb-border: var(--range-thumb-bg) solid var(--border-color), - --range-thumb-border-radius: 1rem, + --range-thumb-border-radius: var(--radius-pill), --range-thumb-box-shadow: "0 1px 2px rgb(0 0 0 / 7.5%), 0 2px 4px rgb(0 0 0 / 7.5%)", --range-thumb-active-bg: color-mix(in oklch, var(--theme-bg, var(--primary-base)) 70%, var(--bg-body)), --range-thumb-disabled-bg: var(--fg-3), @@ -69,7 +71,7 @@ $range-tokens: defaults( background-color: var(--range-track-bg); background-image: linear-gradient( - to right, + var(--range-track-fill-direction), var(--range-track-fill-bg) calc(var(--range-fill, 0) * 100%), transparent calc(var(--range-fill, 0) * 100%) ); @@ -86,6 +88,10 @@ $range-tokens: defaults( position: relative; display: block; width: 100%; + + &:dir(rtl) { + --range-track-fill-direction: to left; + } } .form-range-input { @@ -164,26 +170,34 @@ $range-tokens: defaults( // pill and arrow. We only add the static positioning the Tooltip plugin would normally do. .form-range-bubble { position: absolute; + inset-inline-start: calc((var(--range-thumb-width) * .5) + var(--range-fill, 0) * (100% - var(--range-thumb-width))); bottom: 100%; - left: calc((var(--range-thumb-width) * .5) + var(--range-fill, 0) * (100% - var(--range-thumb-width))); margin-bottom: var(--tooltip-arrow-height); pointer-events: none; transform: translateX(-50%); + &:dir(rtl) { + transform: translateX(50%); + } + .tooltip-arrow { position: absolute; + inset-inline-start: 50%; bottom: calc(-1 * var(--tooltip-arrow-height)); - left: 50%; transform: translateX(-50%); + + &:dir(rtl) { + transform: translateX(50%); + } } } // Tick marks generated from the linked . Plugin builds `grid-template-columns` // from the gaps between values so each tick lands on a grid line (handles uneven values). - // Track is inset by 1/4th of the thumb width to keep alignment. + // Track is inset by half the thumb width to match its center at each end. .form-range-ticks { display: grid; - padding-inline: calc(var(--range-thumb-width) * .25); + padding-inline: calc(var(--range-thumb-width) * .5); } .form-range-tick { diff --git a/scss/forms/_validation.scss b/scss/forms/_validation.scss index acf51fd20b..f29dde410c 100644 --- a/scss/forms/_validation.scss +++ b/scss/forms/_validation.scss @@ -201,9 +201,9 @@ $validation-states: defaults( } } - // Chip input — wrapper has the visible border; the .form-ghost inside + // Combobox — wrapper has the visible border; the .form-ghost inside // receives the native pseudo-class. - .chip-input:has(.form-ghost.is-#{$state}) { + .combobox-control:has(.form-ghost.is-#{$state}) { border-color: var(--#{$theme}-border); &:focus-within { @@ -216,7 +216,7 @@ $validation-states: defaults( } @if $state == "invalid" { - [data-bs-validate] .chip-input:has(.form-ghost:user-invalid) { + [data-bs-validate] .combobox-control:has(.form-ghost:user-invalid) { border-color: var(--#{$theme}-border); &:focus-within { @@ -228,7 +228,7 @@ $validation-states: defaults( ~ .invalid-tooltip { display: block; } } } @else if $state == "valid" { - [data-bs-validate~="valid"] .chip-input:has(.form-ghost:user-valid) { + [data-bs-validate~="valid"] .combobox-control:has(.form-ghost:user-valid) { border-color: var(--#{$theme}-border); &:focus-within { diff --git a/scss/forms/index.scss b/scss/forms/index.scss index 58cd150f1f..e5bd08058e 100644 --- a/scss/forms/index.scss +++ b/scss/forms/index.scss @@ -10,7 +10,7 @@ @forward "strength"; @forward "otp-input"; @forward "form-adorn"; -@forward "chip-input"; +@forward "combobox-control"; @forward "combobox"; @forward "form-field"; @forward "validation"; diff --git a/scss/layout/_grid.scss b/scss/layout/_grid.scss index f779c0316b..9541bb11d5 100644 --- a/scss/layout/_grid.scss +++ b/scss/layout/_grid.scss @@ -2,8 +2,6 @@ @use "breakpoints" as *; @use "../mixins/grid" as *; -// TODO: check gap utilities as replacement for gutter classes from v5 - @layer layout { @if $enable-grid-classes { .row { diff --git a/scss/mixins/_grid.scss b/scss/mixins/_grid.scss index d925210195..36fb482920 100644 --- a/scss/mixins/_grid.scss +++ b/scss/mixins/_grid.scss @@ -1,6 +1,6 @@ +// stylelint-disable length-zero-no-unit -- Zero gaps need a length type inside calc(). @use "sass:map"; @use "sass:math"; -@use "sass:meta"; @use "../config" as *; @use "../layout/breakpoints" as *; @@ -9,33 +9,29 @@ // Generate semantic grid columns with these mixins. @mixin make-row($gutter-x: $grid-gutter-x, $gutter-y: $grid-gutter-y) { - --gutter-x: #{$gutter-x}; + // stylelint-disable-next-line scss/at-function-named-arguments + --gutter-x: #{if(sass($gutter-x == 0): 0px; else: $gutter-x)}; --gutter-y: #{$gutter-y}; display: flex; flex-wrap: wrap; - // TODO: Revisit calc order after https://github.com/react-bootstrap/react-bootstrap/issues/6039 is fixed - margin-inline: calc(-.5 * var(--gutter-x)); - margin-top: calc(-1 * var(--gutter-y)); + gap: var(--gutter-y) var(--gutter-x); } @mixin make-col-ready() { - // Add box sizing if only the grid is loaded - // stylelint-disable-next-line scss/at-function-named-arguments - box-sizing: if(sass(meta.variable-exists(include-column-box-sizing) and $include-column-box-sizing): border-box; else: null); + box-sizing: border-box; // Prevent columns from becoming too narrow when at smaller grid tiers by // always setting `width: 100%;`. This works because we set the width // later on to override this initial width. flex-shrink: 0; width: 100%; max-width: 100%; // Prevent `.col-auto`, `.col` (& responsive variants) from breaking out the grid - padding-inline: calc(var(--gutter-x) * .5); - margin-top: var(--gutter-y); } -@mixin make-col($size: false, $columns: $grid-columns) { +@mixin make-col($size: false, $columns: $grid-columns, $gap: var(--gutter-x, 0px)) { @if $size { flex: 0 0 auto; - width: math.percentage(math.div($size, $columns)); + // A span includes its internal gaps and leaves one gap before the next column. + width: calc((100% + $gap) * #{math.div($size, $columns)} - $gap); } @else { flex: 1 1 0; @@ -48,10 +44,10 @@ width: auto; } -@mixin make-col-offset($size, $columns: $grid-columns) { +@mixin make-col-offset($size, $columns: $grid-columns, $gap: var(--gutter-x, 0px)) { $num: math.div($size, $columns); // stylelint-disable-next-line scss/at-function-named-arguments - margin-inline-start: if(sass($num == 0): 0; else: math.percentage($num)); + margin-inline-start: if(sass($num == 0): 0; else: calc((100% + $gap) * #{$num})); } // Row columns @@ -62,7 +58,7 @@ @mixin row-cols($count) { > * { flex: 0 0 auto; - width: math.percentage(math.div(1, $count)); + width: calc((100% + var(--gutter-x, 0px)) / #{$count} - var(--gutter-x, 0px)); } } @@ -99,7 +95,12 @@ @if $columns > 0 { @for $i from 1 through $columns { .#{$prefix}col-#{$i} { - @include make-col($i, $columns); + // Keep percentage sizing when column classes are used outside rows. + @include make-col($i, $columns, 0px); + + :where(.row) > & { + @include make-col($i, $columns); + } } } @@ -107,7 +108,11 @@ @for $i from 0 through ($columns - 1) { @if not ($prefix == "" and $i == 0) { // Avoid emitting useless .offset-0 .#{$prefix}offset-#{$i} { - @include make-col-offset($i, $columns); + @include make-col-offset($i, $columns, 0px); + + :where(.row) > & { + @include make-col-offset($i, $columns); + } } } } @@ -119,7 +124,8 @@ @each $key, $value in $gutters { .#{$prefix}g-#{$key}, .#{$prefix}gx-#{$key} { - --gutter-x: #{$value}; + // stylelint-disable-next-line scss/at-function-named-arguments + --gutter-x: #{if(sass($value == 0): 0px; else: $value)}; } .#{$prefix}g-#{$key}, diff --git a/site/data/sidebar.yml b/site/data/sidebar.yml index 73dee44b39..23b13d651c 100644 --- a/site/data/sidebar.yml +++ b/site/data/sidebar.yml @@ -93,9 +93,6 @@ - title: Form adorn meta: - added: 6.0.0 - - title: Chips - meta: - - added: 6.0.0 - title: Combobox meta: - added: 6.0.0 @@ -131,6 +128,9 @@ - title: Carousel meta: - added: 6.0.0 + - title: Chips + meta: + - added: 6.0.0 - title: Close button - title: Collapse - title: Dialog diff --git a/site/src/assets/examples/heroes/bootstrap-themes.png b/site/src/assets/examples/heroes/bootstrap-themes.png deleted file mode 100644 index 13c32337d6..0000000000 Binary files a/site/src/assets/examples/heroes/bootstrap-themes.png and /dev/null differ diff --git a/site/src/assets/examples/heroes/index.astro b/site/src/assets/examples/heroes/index.astro index b769110d5a..9d9cdae4f9 100644 --- a/site/src/assets/examples/heroes/index.astro +++ b/site/src/assets/examples/heroes/index.astro @@ -43,7 +43,7 @@ export const extra_css = ['heroes.css']
- Bootstrap Themes + Bootstrap documentation

Responsive left-aligned hero with image

diff --git a/site/src/assets/stackblitz.js b/site/src/assets/stackblitz.js index 05afdf2c37..51cda0ea75 100644 --- a/site/src/assets/stackblitz.js +++ b/site/src/assets/stackblitz.js @@ -37,7 +37,6 @@ const LOAD_PLUGINS = { // starts them at once when it loads after the page, but not 6.0.0-alpha.1, the // version the playground installs const READY_PLUGINS = { - Chips: '[data-bs-chips]', Combobox: '[data-bs-toggle="combobox"]', Datepicker: '[data-bs-toggle="datepicker"][data-bs-inline="true"], [data-bs-toggle="datepicker"][data-bs-selected-dates]', NavOverflow: '[data-bs-toggle="nav-overflow"]', diff --git a/site/src/content/docs/components/chips.mdx b/site/src/content/docs/components/chips.mdx new file mode 100644 index 0000000000..8531d0fa82 --- /dev/null +++ b/site/src/content/docs/components/chips.mdx @@ -0,0 +1,90 @@ +--- +title: Chips +description: Small elements for people, places, tags, and values, with optional icons, avatars, and dismiss buttons. +toc: true +aliases: + - /docs/[[config:docs_version]]/forms/chips/ +css_layer: components +--- + +import { getData } from '@libs/data' + +## Overview + +Chips represent people, places, tags, or values. Use them on their own or within components such as [Combobox]([[docsref:/forms/combobox]]), where they display selected values. They're similar to [Badges]([[docsref:/components/badge]]), but have some meaningful differences. + +- Chips support active states and dismiss buttons. +- Chips have one size—they don't scale with the parent `font-size` like Badges. +- Chips can have icons, avatars, and dismiss buttons. +- Chips can be themed, individually or as a group on the parent container. By default, chips use the `subtle` and `text` theme tokens, while active state uses the `bg` and `contrast` tokens. +- Chips can be active or disabled. + +See examples of all of this in action below. + +## Chips + +Use `.chip` for standalone chips. Add `.chip-icon` for a leading icon, `.chip-img` for an image like an avatar, and `.chip-dismiss` for a remove button. Note that we use an inline SVG for the dismiss button icon—you can modify this as needed. + +Static chips have no hover effect. A dismiss button has its own hover state without changing the whole chip. + +Basic chip + + + + With avatar + + + + + + + + + With icon + + + + Dismissible + + `} /> + +### Interactive chips + +Use a button for an action or a link for navigation. Chips on or inside interactive elements have a pointer cursor and hover feedback. Combobox also provides these states for its selectable chips. + +Keyboard focus uses the chip’s theme color, including on dismiss buttons. Chips without a theme use the default focus color. + +Action chip + Link chip`} /> + +### Themed chips + +Apply `.theme-*` classes to color your chips. Chips are subtle by default as this allows for a clear, themed active state. + +Default`, + ...getData('theme-colors').map((themeColor) => `${themeColor.title}`) +]} /> + +### Active state + +Add `.active` to make chips use the solid appearance (bg/contrast). This is useful for toggle-style chip selections. + +Default + Active + Default + Active`} /> + +## Multiple-value inputs + +Use [Combobox]([[docsref:/forms/combobox]]) for selectable options and free-entry values. Its multiple mode renders chips beside an editable input. The `.chip` classes on this page provide the visual treatment; Combobox owns keyboard behavior, removal, and form submission. + +## CSS + +### Chip variables + + + + diff --git a/site/src/content/docs/components/collapse.mdx b/site/src/content/docs/components/collapse.mdx index ec50dabff1..debfd2f8d4 100644 --- a/site/src/content/docs/components/collapse.mdx +++ b/site/src/content/docs/components/collapse.mdx @@ -85,6 +85,24 @@ Conversely, multiple `
`} /> +## Hash links + +Hash links also work when Bootstrap loads after the page. A later fragment change cancels an earlier target’s pending scroll. + +Add `data-bs-hash` to a collapsible target to open it when the URL fragment matches its `id`. Use a normal in-page link (without `data-bs-toggle`) to try it. You may need to use `scroll-margin-block-start` for some viewport offsetting if using a stickied or fixed navbar. + + + Open via hash link + +

+
+
+

Some placeholder content for a hash-linked collapse. Visiting #collapseHashExample opens this panel and scrolls it into view.

+
+
`} /> + ## Accessibility Be sure to add `aria-expanded` to the control element. This attribute explicitly conveys the current state of the collapsible element tied to the control to screen readers and similar assistive technologies. If the collapsible element is closed by default, the attribute on the control element should have a value of `aria-expanded="false"`. If you’ve set the collapsible element to be open by default using the `show` class, set `aria-expanded="true"` on the control instead. The plugin will automatically toggle this attribute on the control based on whether or not the collapsible element has been opened or closed (via JavaScript, or because the user triggered another control element also tied to the same collapsible element). If the control element’s HTML element is not a button (e.g., an `` or `
`), the attribute `role="button"` should be added to the element. @@ -128,6 +146,7 @@ To add accordion-like group management to a collapsible area, add the data attri | `data-bs-toggle="collapse"` | Initializes the collapse plugin on the trigger element. | | `data-bs-target` | CSS selector for the element(s) to expand and collapse. | | `data-bs-parent` | When set on the collapsible element, closes sibling collapses under the same parent (accordion behavior). | +| `data-bs-hash` | When set on the collapsible target, opens that collapse when the URL fragment matches its `id` (on load and `hashchange`). See [Hash links](#hash-links). | ### Via JavaScript diff --git a/site/src/content/docs/components/tab.mdx b/site/src/content/docs/components/tab.mdx index 96be7764c3..d192e775af 100644 --- a/site/src/content/docs/components/tab.mdx +++ b/site/src/content/docs/components/tab.mdx @@ -162,6 +162,40 @@ The tab plugin also works with [list groups]([[docsref:/components/list-group]])
`} /> +## Hash links + +Hash links also work when Bootstrap loads after the page. A later fragment change cancels an earlier target’s pending scroll. + +Add `data-bs-hash` to a tab pane to show it when the URL fragment matches its `id`. Use a normal in-page link to try it. You may need to use `scroll-margin-block-start` for some viewport offsetting if using a stickied or fixed navbar. + + + #hash-home + #hash-profile + #hash-contact +

+ +
+
+

This is some placeholder content the Home tab’s associated content.

+
+
+

This is some placeholder content the Profile tab’s associated content.

+
+
+

This is some placeholder content the Contact tab’s associated content.

+
+
`} /> + ## Accessibility Dynamic tabbed interfaces, as described in the [ARIA Authoring Practices Guide tabs pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabpanel/), require `role="tablist"`, `role="tab"`, `role="tabpanel"`, and additional `aria-` attributes in order to convey their structure, functionality, and current state to users of assistive technologies (such as screen readers). As a best practice, we recommend using ` - `} /> - -### Themed chips - -Apply `.theme-*` classes to color your chips. Chips are subtle by default as this allows for a clear, themed active state. - -Default`, - ...getData('theme-colors').map((themeColor) => `${themeColor.title}`) -]} /> - -### Active state - -Add `.active` to make chips use the solid appearance (bg/contrast). This is useful for toggle-style chip selections. - -Default - Active - Default - Active`} /> - -## Chip input - -Wrap chips and a ghost input in `.chip-input` to create a tag input field. Add `data-bs-chips` to enable JavaScript behavior. Chips are grayscale by default, with primary blue for active states, but you can apply any theme color to the container so that chips within inherit the color of your choosing. - -Type into the input below and press Enter or , to add new chips. Use the Backspace or Delete keys to remove chips. See the [Keyboard behavior](#keyboard-behavior) section for more details. - - - - - JavaScript - - - TypeScript - - - `} /> - -### Theme variants - -Add a `.theme-*` class to the `.chip-input` container to apply a theme color to all chips within. - - - Approved - Verified - - - -
- Bug - Critical - -
`} /> - -You can also individually apply a theme color to a chip by adding a `.theme-*` class to the chip element. - - - Bug - Critical - - `} /> - -### Empty state - -Start with just the ghost input—chips are created as users type. - - - - `} /> - -### With label - -Use a form label for better accessibility. - - - -
- - React - - - -
-
Press Enter or comma to add a skill.
- `} /> - -### Disabled - -Disable the ghost input to prevent adding new chips, and disable the dismiss buttons on existing chips. Existing chips become non-interactive. - - - - Read only - - - - `} /> - -## Usage - -### Via data attributes - -Add `data-bs-chips` to your container element to automatically initialize the chip input behavior. Options can be passed as data attributes. - - -| Attribute | Description | -| --- | --- | -| `data-bs-chips` | Initializes the chip input on the container element. | -| `data-bs-separator` | Character that creates a new chip when typed (or `null` to disable). | -| `data-bs-allow-duplicates` | Whether duplicate chip values are allowed. | -| `data-bs-max-chips` | Maximum number of chips (`null` for no limit). | -| `data-bs-create-on-blur` | Create a chip from the input value when focus leaves the field. | - - -```html -
- -
-``` - -### Via JavaScript - -Initialize manually with JavaScript: - -```js -const chipInputElement = document.querySelector('.chip-input') -const chips = new bootstrap.Chips(chipInputElement, { - separator: ',', - maxChips: 5 -}) -``` - -### Dependencies - - - -### Options - -Options can be passed via data attributes or JavaScript: - - -| Name | Type | Default | Description | -| --- | --- | --- | --- | -| `separator` | string \| null | `','` | Character that triggers chip creation when typed. Set to `null` to disable. | -| `allowDuplicates` | boolean | `false` | Allow duplicate chip values. | -| `maxChips` | number \| null | `null` | Maximum number of chips allowed. `null` for unlimited. | -| `placeholder` | string | `''` | Placeholder text for dynamically created inputs. | -| `dismissible` | boolean | `true` | Add dismiss buttons to created chips. | -| `dismissIcon` | string | `'...'` | HTML string for the dismiss button icon. Passed through the [icon content sanitizer]([[docsref:/getting-started/javascript#sanitizer]]) before insertion. | -| `createOnBlur` | boolean | `true` | Create chip from input value when the input loses focus. | - - -### Methods - - -| Method | Description | -| --- | --- | -| `add(value)` | Adds a chip with the given value. Returns the chip element or `null` if rejected. | -| `remove(chipOrValue)` | Removes a chip by element reference or value string. Returns `true` if removed. | -| `removeSelected()` | Removes all currently selected chips. | -| `getValues()` | Returns an array of all chip values. | -| `getSelectedValues()` | Returns an array of selected chip values. | -| `clear()` | Removes all chips. | -| `clearSelection()` | Deselects all chips without removing them. | -| `selectChip(chip, options)` | Selects a chip. Options: `addToSelection`, `rangeSelect`. | -| `focus()` | Focuses the ghost input. | -| `dispose()` | Destroys the component instance. | - - -```js -const chipInputElement = document.querySelector('.chip-input') -const chips = bootstrap.Chips.getOrCreateInstance(chipInputElement) - -// Add chips programmatically -chips.add('JavaScript') -chips.add('TypeScript') - -// Get all values -console.log(chips.getValues()) // ['JavaScript', 'TypeScript'] - -// Remove a specific chip -chips.remove('JavaScript') - -// Clear all chips -chips.clear() -``` - -### Events - - -| Event | Description | -| --- | --- | -| `add.bs.chips` | Fired before a chip is added. Call `event.preventDefault()` to cancel. | -| `remove.bs.chips` | Fired before a chip is removed. Call `event.preventDefault()` to cancel. | -| `change.bs.chips` | Fired after any chip is added or removed. Contains `values` array. | -| `select.bs.chips` | Fired when chip selection changes. Contains `selected` array of values. | - - -```js -const chipInputElement = document.querySelector('.chip-input') - -chipInputElement.addEventListener('add.bs.chips', event => { - console.log('Adding chip:', event.value) - - // Validate and optionally prevent - if (event.value.length < 2) { - event.preventDefault() - } -}) - -chipInputElement.addEventListener('remove.bs.chips', event => { - console.log('Removing chip:', event.value) -}) - -chipInputElement.addEventListener('change.bs.chips', event => { - console.log('Current values:', event.values) - // Sync with hidden input or state -}) - -chipInputElement.addEventListener('select.bs.chips', event => { - console.log('Selected:', event.selected) -}) -``` - -## Keyboard behavior - -Chip inputs support Mail.app-style keyboard navigation with chip selection. - -### When input is focused - - -| Key | Action | -| --- | --- | -| `Enter` | Create chip from current input value | -| `,` (or separator) | Create chip from current input value | -| `Backspace` / `Delete` | When input is empty, select and focus last chip (first press); pressing again deletes it | -| `←` | When cursor is at start, move focus to last chip | -| `Shift+←` | Select last chip and extend selection | -| `Escape` | Clear selection, clear input, and blur | - - -### When a chip is focused - - -| Key | Action | -| --- | --- | -| `Backspace` / `Delete` | Remove selected chips, then select and focus the next closest chip | -| `←` | Move to previous chip | -| `→` | Move to next chip (or input if at end) | -| `Shift+←` / `Shift+→` | Extend selection in that direction | -| `Home` | Move to first chip | -| `End` | Move to input | -| `Cmd/Ctrl+A` | Select all chips | -| `Escape` | Clear selection and focus input | - - -### Mouse selection - - -| Action | Effect | -| --- | --- | -| Click chip | Select chip (deselects others) | -| `Cmd/Ctrl+Click` | Toggle chip in selection | -| `Shift+Click` | Range select from anchor to clicked chip | - - -## Accessibility - -- Use a `