diff --git a/.bundlewatch.config.json b/.bundlewatch.config.json
index 2eee2e7d43..3d52a9ba24 100644
--- a/.bundlewatch.config.json
+++ b/.bundlewatch.config.json
@@ -2,11 +2,11 @@
"files": [
{
"path": "./dist/css/bootstrap-grid.css",
- "maxSize": "13.75 kB"
+ "maxSize": "12.5 kB"
},
{
"path": "./dist/css/bootstrap-grid.min.css",
- "maxSize": "12.0 kB"
+ "maxSize": "11.0 kB"
},
{
"path": "./dist/css/bootstrap-reboot.css",
@@ -26,19 +26,19 @@
},
{
"path": "./dist/css/bootstrap.css",
- "maxSize": "55.5 kB"
+ "maxSize": "54.25 kB"
},
{
"path": "./dist/css/bootstrap.min.css",
- "maxSize": "52 kB"
+ "maxSize": "50.5 kB"
},
{
"path": "./dist/js/bootstrap.bundle.js",
- "maxSize": "79.75 kB"
+ "maxSize": "75.25 kB"
},
{
"path": "./dist/js/bootstrap.bundle.min.js",
- "maxSize": "62.75 kB"
+ "maxSize": "59.25 kB"
},
{
"path": "./dist/js/bootstrap.js",
@@ -46,7 +46,7 @@
},
{
"path": "./dist/js/bootstrap.min.js",
- "maxSize": "39.0 kB"
+ "maxSize": "35.5 kB"
}
],
"ci": {
diff --git a/.cspell.json b/.cspell.json
index f06670ecad..06e29d2b36 100644
--- a/.cspell.json
+++ b/.cspell.json
@@ -1,7 +1,6 @@
{
"version": "0.2",
"words": [
- "activedescendant",
"affordance",
"allowfullscreen",
"Analyser",
@@ -125,7 +124,6 @@
"mkdir",
"monospace",
"mouseleave",
- "multiselectable",
"navbars",
"navs",
"navoverflow",
diff --git a/.github/workflows/css.yml b/.github/workflows/css.yml
index 53b80a01fe..01c53f62b4 100644
--- a/.github/workflows/css.yml
+++ b/.github/workflows/css.yml
@@ -37,12 +37,3 @@ 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 d096362488..4a1001f14e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -84,7 +84,6 @@ 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
deleted file mode 100644
index 9d3a141773..0000000000
--- a/build/test-grid-layout.mjs
+++ /dev/null
@@ -1,287 +0,0 @@
-/* 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(
- ``
- );
- [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(
- `
`
- )
- 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
new file mode 100644
index 0000000000..8341a590f8
--- /dev/null
+++ b/js/src/chips.ts
@@ -0,0 +1,668 @@
+/**
+ * --------------------------------------------------------------------------
+ * 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 f0bb1a6f70..cf6a8f9af7 100644
--- a/js/src/collapse.ts
+++ b/js/src/collapse.ts
@@ -9,7 +9,6 @@ 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,
@@ -246,38 +245,5 @@ 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 04f6f9a379..40abefdddc 100644
--- a/js/src/combobox.ts
+++ b/js/src/combobox.ts
@@ -5,16 +5,14 @@
* --------------------------------------------------------------------------
*/
-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 {
- getElement, getNextActiveElement, getUID, isDisabled, isVisible, setAriaAttribute
+ getNextActiveElement, isDisabled, isVisible, setAriaAttribute
} from './util/index.js'
/**
@@ -36,14 +34,16 @@ 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,19 +52,8 @@ 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
@@ -75,12 +64,7 @@ type ComboboxConfig = {
}
const Default: ComboboxConfig = {
- allowCustom: false,
- createOnBlur: false,
- maxItems: null,
- separator: null,
boundary: 'clippingParents',
- input: null,
multiple: false,
name: null,
offset: [0, 2],
@@ -91,12 +75,7 @@ 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)',
@@ -118,108 +97,22 @@ class Combobox extends BaseComponent {
protected declare _searchInput: HTMLInputElement | null
protected declare _noResults: HTMLElement | null
protected declare _hiddenInput: HTMLInputElement | 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>
+ protected declare _menuInstance: Menu | null
constructor(element?: string | Element | null, config?: Partial | null) {
super(element, config)
- 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._toggle = this._element
+ this._menu = SelectorEngine.next(this._toggle, SELECTOR_MENU)[0] as HTMLElement
this._valueDisplay = SelectorEngine.findOne(SELECTOR_VALUE, this._toggle)!
- this._searchInput = this._editor ?? SelectorEngine.findOne(SELECTOR_SEARCH_INPUT, this._menu)
+ this._searchInput = 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.update()
+ this._syncInitialSelection()
this._addEventListeners()
}
@@ -241,79 +134,52 @@ class Combobox extends BaseComponent {
return this._isShown() ? this.hide() : this.show()
}
- show(): Promise {
- return this._showMenu()
+ 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)
}
async hide(): Promise {
- await this._menuInstance!.hide()
- }
-
- 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)
+ if (!this._isShown()) {
+ return
}
+
+ const hideEvent = EventHandler.trigger(this._toggle, EVENT_HIDE)
+ if (hideEvent.defaultPrevented) {
+ return
+ }
+
+ 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 && this._ownsInput) {
+ if (this._hiddenInput) {
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)
@@ -321,820 +187,45 @@ 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 {
- if (this._config.input) {
- this._hiddenInput = this._config.input as HTMLInputElement
- this._inputDisabled = this._hiddenInput.disabled
- return
- }
-
- if (!this._config.name) {
+ const { name } = this._config
+ if (!name) {
return
}
this._hiddenInput = document.createElement('input')
this._hiddenInput.type = 'hidden'
- this._hiddenInput.name = this._config.name
- const anchor = this._editor ? this._element : this._toggle
- anchor.before(this._hiddenInput)
- this._ownsInput = true
- }
-
- protected _removeExtraInputs(): void {
- for (const input of this._extraInputs) {
- input.remove()
- }
-
- this._extraInputs = []
- }
-
- 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))
+ this._hiddenInput.name = name
+ this._hiddenInput.value = ''
+ this._toggle.parentNode!.insertBefore(this._hiddenInput, this._toggle)
}
protected _createMenuInstance(): void {
- this._menuInstance = new ComboboxMenu(this._toggle, {
+ this._menuInstance = new Menu(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
+ placement: this._config.placement
})
}
- 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)
+ protected _syncInitialSelection(): void {
+ const selectedItems = this._getSelectedItems()
+ if (selectedItems.length > 0) {
+ this._updateToggleText()
+ this._updateHiddenInput()
+ } else {
+ this._showPlaceholder()
}
+ }
+ protected _addEventListeners(): void {
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)) {
@@ -1147,39 +238,19 @@ class Combobox extends BaseComponent {
})
EventHandler.on(this._toggle, `keydown${EVENT_KEY}`, event => {
- if (this._editor) {
- this._handleEditorKeydown(event)
- } else {
- this._handleToggleKeydown(event)
- }
+ 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()
@@ -1190,90 +261,46 @@ 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 {
- for (const selected of previous) {
- selected.classList.remove(CLASS_NAME_SELECTED)
- selected.setAttribute('aria-selected', 'false')
+ 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')
}
item.classList.add(CLASS_NAME_SELECTED)
item.setAttribute('aria-selected', 'true')
}
- this._selectionChanged(item)
- }
+ this._updateToggleText()
+ this._updateHiddenInput()
- 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
+ const value = this._config.multiple ?
+ this._getSelectedItems().map(el => el.dataset.bsValue) :
+ item.dataset.bsValue
- for (const event of ['input', 'change']) {
- EventHandler.trigger(target, event)
- if (!this._element || changeId !== this._changeId) {
- return
- }
- }
+ EventHandler.trigger(this._toggle, EVENT_CHANGE, {
+ value,
+ item
+ })
- 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) {
+ if (!this._config.multiple) {
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) {
@@ -1294,97 +321,29 @@ class Combobox extends BaseComponent {
protected _showPlaceholder(): void {
const { placeholder } = this._config
- this._valueDisplay.textContent = placeholder
- this._valueDisplay.classList.toggle(CLASS_NAME_PLACEHOLDER, Boolean(placeholder))
+ if (placeholder) {
+ this._valueDisplay.textContent = placeholder
+ this._valueDisplay.classList.add(CLASS_NAME_PLACEHOLDER)
+ }
}
protected _updateHiddenInput(): void {
- const input = this._hiddenInput
- if (!input) {
+ if (!this._hiddenInput) {
return
}
- 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()
+ const selectedItems = this._getSelectedItems()
+ const values = selectedItems.map(el => el.dataset.bsValue)
+ this._hiddenInput.value = this._config.multiple ? values.join(',') : (values[0] || '')
}
protected _getSelectedItems(): HTMLElement[] {
- return SelectorEngine.find(`${SELECTOR_MENU_ITEM}.${CLASS_NAME_SELECTED}`, this._menu)
+ return SelectorEngine.find(`.${CLASS_NAME_SELECTED}`, this._menu)
}
protected _getVisibleItems(): HTMLElement[] {
- 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
- })
+ return SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu)
+ .filter(item => isVisible(item))
}
protected _filterItems(query: string): void {
@@ -1415,37 +374,23 @@ 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()
- 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()
+ if (!this._isShown()) {
+ this.show()
}
- if (this._isShown()) {
- focusItem()
- } else {
- this._showMenu(focusItem)
+ const items = this._getVisibleItems()
+ if (items.length > 0) {
+ const target = key === ARROW_DOWN_KEY ? items[0] : items.at(-1)!
+ target.focus()
}
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()
@@ -1453,17 +398,13 @@ 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
}
@@ -1484,7 +425,7 @@ class Combobox extends BaseComponent {
return
}
- if ((key === HOME_KEY || key === END_KEY) && !isInput) {
+ if (key === HOME_KEY || key === END_KEY) {
event.preventDefault()
const items = this._getVisibleItems()
if (items.length > 0) {
@@ -1510,18 +451,8 @@ 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()
- instance.toggle()
+ Combobox.getOrCreateInstance(this).toggle()
})
onDocumentReady('DOMContentLoaded', () => {
diff --git a/js/src/dom/event-handler.ts b/js/src/dom/event-handler.ts
index c3979868ea..24715a9094 100644
--- a/js/src/dom/event-handler.ts
+++ b/js/src/dom/event-handler.ts
@@ -62,9 +62,6 @@ const nativeEvents = new Set([
'keypress',
'keyup',
'input',
- 'compositionstart',
- 'compositionupdate',
- 'compositionend',
'paste',
'orientationchange',
'touchstart',
@@ -97,8 +94,7 @@ const nativeEvents = new Set([
'error',
'abort',
'scroll',
- 'scrollend',
- 'hashchange'
+ 'scrollend'
])
/**
diff --git a/js/src/index.ts b/js/src/index.ts
index 2d5ce72094..e817a4f2df 100644
--- a/js/src/index.ts
+++ b/js/src/index.ts
@@ -17,6 +17,7 @@ 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 6c9c42b1d6..23e26f9e55 100644
--- a/js/src/menu.ts
+++ b/js/src/menu.ts
@@ -218,11 +218,7 @@ class Menu extends BaseComponent {
return this._isShown() ? this.hide() : this.show()
}
- show(): Promise {
- return this._show()
- }
-
- protected async _show(focus?: () => void): Promise {
+ async show(): Promise {
if (isDisabled(this._element) || this._isShown()) {
return
}
@@ -246,6 +242,7 @@ class Menu extends BaseComponent {
}
}
+ this._element.focus({ focusVisible: false })
this._element.setAttribute('aria-expanded', 'true')
this._menu.classList.add(CLASS_NAME_SHOW)
@@ -256,15 +253,6 @@ 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.
@@ -1053,10 +1041,6 @@ 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 0288cf1aa5..fd8c9b6030 100644
--- a/js/src/range.ts
+++ b/js/src/range.ts
@@ -11,10 +11,6 @@ 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
*/
@@ -27,9 +23,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'
@@ -50,7 +46,7 @@ type RangeConfig = {
const Default: RangeConfig = {
bubble: false, // Show a value bubble above the thumb
- formatter: null // (value) => string, for the bubble
+ formatter: null // (value) => string, for the bubble and tick labels
}
const DefaultType = {
@@ -69,10 +65,6 @@ 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)
@@ -92,22 +84,10 @@ class Range extends BaseComponent {
this._bubbleText = null
this._ticks = null
this._updateHandler = () => this._update()
- 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()
+ if (this._config.bubble) {
+ this._createBubble()
+ }
this._createTicks()
this._addEventListeners()
@@ -129,16 +109,6 @@ 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()
}
@@ -146,9 +116,6 @@ 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()
@@ -165,31 +132,6 @@ 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)
@@ -229,7 +171,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('div')
+ this._bubble = document.createElement('output')
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 41a61f3663..1b0f7bde66 100644
--- a/js/src/tab.ts
+++ b/js/src/tab.ts
@@ -8,7 +8,6 @@
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'
@@ -312,52 +311,4 @@ 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
deleted file mode 100644
index 6958aeef12..0000000000
--- a/js/src/util/hash-target.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * --------------------------------------------------------------------------
- * 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 23f1e1b48c..08f30ba107 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 (NavOverflow `moreIcon`,
+ * Allowlist for icon HTML options (Chips `dismissIcon`, 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 8fbbeca454..5a694768d9 100644
--- a/js/tests/types/api.ts
+++ b/js/tests/types/api.ts
@@ -11,6 +11,7 @@ import {
Alert,
Button,
Carousel,
+ Chips,
Collapse,
Combobox,
Datepicker,
@@ -32,6 +33,7 @@ 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'
@@ -57,27 +59,8 @@ 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 })
@@ -119,6 +102,7 @@ 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 64aa22cbb3..cf03c087ec 100644
--- a/js/tests/types/consumer.ts
+++ b/js/tests/types/consumer.ts
@@ -18,6 +18,7 @@ import {
Alert,
Button,
Carousel,
+ Chips,
Collapse,
Combobox,
Datepicker,
@@ -40,6 +41,7 @@ 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'
@@ -64,27 +66,8 @@ 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 })
@@ -135,6 +118,7 @@ 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
deleted file mode 100644
index 8eb5faa56f..0000000000
--- a/js/tests/unit/chip.spec.js
+++ /dev/null
@@ -1,64 +0,0 @@
-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 => `Action `,
- link: theme => `Link `,
- inherited: theme => `Action
`,
- active: theme => `Selected `,
- 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 = `Action `
- 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
new file mode 100644
index 0000000000..b09b980ccc
--- /dev/null
+++ b/js/tests/unit/chips.spec.js
@@ -0,0 +1,695 @@
+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(
+ {},
+ 'gammax
'
+ )
+
+ 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 85edc6ffbf..f277cb9665 100644
--- a/js/tests/unit/collapse.spec.js
+++ b/js/tests/unit/collapse.spec.js
@@ -1,16 +1,6 @@
import Collapse from '../../src/collapse.js'
import EventHandler from '../../src/dom/event-handler.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('')
-}
+import { clearFixture, getFixture } from '../helpers/fixture.js'
describe('Collapse', () => {
let fixtureEl
@@ -21,7 +11,6 @@ describe('Collapse', () => {
afterEach(() => {
clearFixture()
- clearHash()
})
describe('VERSION', () => {
@@ -966,77 +955,4 @@ 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
deleted file mode 100644
index 9320d4fc8f..0000000000
--- a/js/tests/unit/combobox-editor.spec.js
+++ /dev/null
@@ -1,741 +0,0 @@
-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
deleted file mode 100644
index 08369c0a2d..0000000000
--- a/js/tests/unit/combobox-form.spec.js
+++ /dev/null
@@ -1,411 +0,0 @@
-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
deleted file mode 100644
index f4c91e9d14..0000000000
--- a/js/tests/unit/combobox-layout.spec.js
+++ /dev/null
@@ -1,46 +0,0 @@
-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 5489b587f0..6eb17b6b9e 100644
--- a/js/tests/unit/combobox.spec.js
+++ b/js/tests/unit/combobox.spec.js
@@ -1,4 +1,3 @@
-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'
@@ -317,7 +316,7 @@ describe('Combobox', () => {
items[1].click()
expect(valueEl.textContent).toEqual('2 selected')
- expect([...fixtureEl.querySelectorAll('input[type="hidden"]')].map(input => input.value)).toEqual(['us', 'uk'])
+ expect(fixtureEl.querySelector('input[type="hidden"]').value).toEqual('us,uk')
})
it('should fire change with every selected value', () => {
@@ -345,33 +344,6 @@ 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 9cf48b39fa..4c8acebd53 100644
--- a/js/tests/unit/range.spec.js
+++ b/js/tests/unit/range.spec.js
@@ -116,219 +116,6 @@ 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 : ''}
- `
- 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 7a9ce37849..396c54107a 100644
--- a/js/tests/unit/tab.spec.js
+++ b/js/tests/unit/tab.spec.js
@@ -3,16 +3,6 @@ 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
@@ -22,7 +12,6 @@ describe('Tab', () => {
afterEach(() => {
clearFixture()
- clearHash()
})
describe('VERSION', () => {
@@ -1306,107 +1295,4 @@ 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 = [
- '',
- ' Home ',
- ' Profile ',
- ' ',
- ''
- ].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 = [
- '',
- ' Home ',
- ' Profile ',
- ' ',
- ''
- ].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 = [
- '',
- ' Home ',
- ' Profile ',
- ' ',
- ''
- ].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
deleted file mode 100644
index 7133da4e69..0000000000
--- a/js/tests/unit/util/hash-target.spec.js
+++ /dev/null
@@ -1,83 +0,0 @@
-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 ffffb3a329..2986aab6a1 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.17.1",
+ "eslint-plugin-import-x": "^4.18.1",
"eslint-plugin-markdown": "^5.1.0",
"eslint-plugin-unicorn": "^68.0.0",
"find-unused-sass-variables": "^6.2.1",
@@ -2075,16 +2075,17 @@
}
},
"node_modules/@eslint/config-array/node_modules/minimatch": {
- "version": "10.2.5",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
- "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz",
+ "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.5"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -3067,95 +3068,12 @@
"url": "https://opencollective.com/libvips"
}
},
- "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==",
+ "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==",
"dev": true,
- "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"
- }
+ "license": "BlueOak-1.0.0"
},
"node_modules/@istanbuljs/schema": {
"version": "0.1.6",
@@ -3831,17 +3749,6 @@
"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",
@@ -4930,16 +4837,17 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
- "version": "10.2.6",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
- "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz",
+ "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.8"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -6778,6 +6686,13 @@
"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",
@@ -7652,13 +7567,6 @@
"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",
@@ -8140,18 +8048,20 @@
}
},
"node_modules/eslint-plugin-import-x": {
- "version": "4.17.1",
- "resolved": "https://registry.npmjs.org/eslint-plugin-import-x/-/eslint-plugin-import-x-4.17.1.tgz",
- "integrity": "sha512-4cdstYkKCyjumM2Q9NSI03K8D2a9F4Ssz33K2lv2hQa4KmR9jPLwk3uWGtNvclfqBrPGfGuMBwsGMbe6dMRbfg==",
+ "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==",
"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",
+ "minimatch": "^9.0.3 || ^10.1.2 || ^11.0.1",
"semver": "^7.7.2",
"stable-hash-x": "^0.2.0",
"unrs-resolver": "^1.9.2"
@@ -8199,17 +8109,25 @@
"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": "10.2.6",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
- "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz",
+ "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.8"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -8525,16 +8443,17 @@
"license": "MIT"
},
"node_modules/eslint/node_modules/minimatch": {
- "version": "10.2.6",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
- "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz",
+ "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.8"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -9115,36 +9034,6 @@
"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",
@@ -10383,22 +10272,6 @@
"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",
@@ -10421,72 +10294,59 @@
"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": "2.1.7",
- "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
- "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
+ "version": "5.0.12",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz",
+ "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "balanced-match": "^1.0.0"
+ "balanced-match": "^4.0.2"
+ },
+ "engines": {
+ "node": "20 || >=22"
}
},
"node_modules/jasmine/node_modules/glob": {
- "version": "10.5.0",
- "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
- "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
- "dev": true,
- "license": "ISC",
- "dependencies": {
- "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"
- },
- "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": "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==",
+ "version": "14.0.4",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.4.tgz",
+ "integrity": "sha512-mMiwNKoJZ4HAIRVJxotO6LsNRReA30gQwP9E2/p94tfLv+jygCNpKDjhhSL6OLY6LE371EZm5EAf7RpYuUqlsw==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "lru-cache": "^10.2.0",
- "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
+ "minimatch": "^11.0.5",
+ "minipass": "^7.1.3",
+ "path-scurry": "^3.0.0"
},
"engines": {
- "node": ">=16 || 14 >=14.18"
+ "node": "18 || 20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "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==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -11103,6 +10963,16 @@
"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",
@@ -11313,16 +11183,17 @@
}
},
"node_modules/markdownlint-cli/node_modules/minimatch": {
- "version": "10.2.6",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
- "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz",
+ "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.8"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -13370,11 +13241,11 @@
}
},
"node_modules/minipass": {
- "version": "7.1.2",
- "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz",
- "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==",
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
"dev": true,
- "license": "ISC",
+ "license": "BlueOak-1.0.0",
"engines": {
"node": ">=16 || 14 >=14.17"
}
@@ -13613,16 +13484,17 @@
}
},
"node_modules/nodemon/node_modules/minimatch": {
- "version": "10.2.5",
- "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
- "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
+ "version": "11.0.7",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.7.tgz",
+ "integrity": "sha512-Tnk+M9mPjqKDZlUd77eMSjPjhnlBIa1mABOwetMryIshUwi1YmOBdGFfQnHgn4Z8A66eLT8ENzJrxwYmKfqrZg==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
- "brace-expansion": "^5.0.5"
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
},
"engines": {
- "node": "18 || 20 || >=22"
+ "node": "20 || >=22"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
@@ -13976,13 +13848,6 @@
"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",
@@ -14157,6 +14022,23 @@
"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",
@@ -15999,22 +15881,6 @@
"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",
@@ -16083,20 +15949,6 @@
"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",
@@ -17339,16 +17191,6 @@
}
}
},
- "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",
@@ -18288,56 +18130,6 @@
"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 19556a3ac4..a43c1d408a 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,6 @@
"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-*",
@@ -154,7 +153,7 @@
"eslint": "^10.14.0",
"eslint-config-xo": "^0.53.2",
"eslint-plugin-html": "^8.2.1",
- "eslint-plugin-import-x": "^4.17.1",
+ "eslint-plugin-import-x": "^4.18.1",
"eslint-plugin-markdown": "^5.1.0",
"eslint-plugin-unicorn": "^68.0.0",
"find-unused-sass-variables": "^6.2.1",
@@ -207,7 +206,25 @@
".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 3ff81378ef..dd0bce94f0 100644
--- a/scss/_chip.scss
+++ b/scss/_chip.scss
@@ -41,36 +41,31 @@ $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-normal));
+ font-weight: var(--chip-font-weight, var(--font-weight-base));
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 {
- @include focus-ring(false, var(--theme-focus-ring, var(--focus-ring-color)));
+ outline: 0;
}
&.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;
}
@@ -79,7 +74,7 @@ $chip-tokens: defaults(
&.disabled,
&:disabled {
pointer-events: none;
- opacity: var(--control-disabled-opacity);
+ opacity: .65;
}
}
@@ -138,7 +133,7 @@ $chip-tokens: defaults(
&:focus-visible {
outline: 0;
opacity: 1;
- @include focus-ring(false, var(--theme-focus-ring, var(--focus-ring-color)));
+ @include focus-ring();
}
> svg {
diff --git a/scss/content/_prose.scss b/scss/content/_prose.scss
index 59eef57318..fc977cbd62 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: var(--font-weight-medium);
+ font-weight: 500;
line-height: 1.25;
code {
- font-weight: var(--font-weight-semibold);
+ font-weight: 600;
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,16 +138,11 @@ $prose-tokens: defaults(
}
:where(dt):not(:where(.not-prose, .not-prose *)) {
- font-weight: var(--font-weight-medium);
+ font-weight: 500;
}
: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/_combobox-control.scss b/scss/forms/_chip-input.scss
similarity index 52%
rename from scss/forms/_combobox-control.scss
rename to scss/forms/_chip-input.scss
index bbb793465b..1fb6db3101 100644
--- a/scss/forms/_combobox-control.scss
+++ b/scss/forms/_chip-input.scss
@@ -3,53 +3,42 @@
@use "../mixins/focus-ring" as *;
@use "../mixins/tokens" as *;
-$combobox-control-tokens: () !default;
+$chip-input-tokens: () !default;
-// scss-docs-start combobox-control-tokens
+// scss-docs-start chip-input-tokens
// stylelint-disable-next-line scss/dollar-variable-default
-$combobox-control-tokens: defaults(
+$chip-input-tokens: defaults(
(
- --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,
+ --chip-input-padding-y: .75rem,
+ --chip-input-padding-x: .75rem,
+ --chip-input-gap: .375rem,
+ --chip-input-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),
),
- $combobox-control-tokens
+ $chip-input-tokens
);
-// scss-docs-end combobox-control-tokens
+// scss-docs-end chip-input-tokens
@layer forms {
- .combobox-control {
- @include tokens($combobox-control-tokens);
+ .chip-input {
+ @include tokens($chip-input-tokens);
// Flexbox wrapping layout
display: flex;
flex-wrap: wrap;
- gap: var(--combobox-control-gap);
+ gap: var(--chip-input-gap);
align-items: center;
- min-block-size: var(--control-min-height);
- padding: var(--combobox-control-padding-y) var(--combobox-control-padding-x);
+ padding: var(--chip-input-padding-y) var(--chip-input-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;
@@ -58,11 +47,10 @@ $combobox-control-tokens: defaults(
}
// Ghost input fills remaining space
- > .form-ghost,
- > .combobox-input {
+ > .form-ghost {
flex: 1 1 0;
- min-inline-size: var(--combobox-control-ghost-min-width);
- min-block-size: 1lh;
+ min-width: var(--chip-input-ghost-min-width);
+ min-height: 1.75rem;
}
// Disabled state
diff --git a/scss/forms/_combobox.scss b/scss/forms/_combobox.scss
index f1e8dd3227..9b99994f38 100644
--- a/scss/forms/_combobox.scss
+++ b/scss/forms/_combobox.scss
@@ -1,42 +1,12 @@
-@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;
@@ -48,21 +18,22 @@
&:disabled,
&.disabled {
cursor: not-allowed;
- opacity: var(--control-disabled-opacity);
+ opacity: .65;
}
}
.combobox-value {
- display: block;
+ display: flex;
flex: 1;
- min-width: 0;
+ gap: .5rem;
+ align-items: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.combobox-placeholder {
- color: var(--control-placeholder-color);
+ color: color-mix(in oklch, currentcolor 65%, transparent);
}
.combobox-caret {
@@ -81,7 +52,7 @@
.combobox-search {
position: sticky;
- inset-block-start: calc(-1 * var(--menu-padding-y, .25rem));
+ top: 0;
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 9f093c5bfd..4bd99fe4c0 100644
--- a/scss/forms/_form-range.scss
+++ b/scss/forms/_form-range.scss
@@ -17,16 +17,14 @@ $range-tokens: defaults(
--range-track-height: .5rem,
--range-track-cursor: pointer,
--range-track-bg: var(--bg-3),
- --range-track-border-radius: var(--radius-pill),
- --range-track-box-shadow: var(--box-shadow-inset),
+ --range-track-border-radius: 1rem,
--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: var(--radius-pill),
+ --range-thumb-border-radius: 1rem,
--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),
@@ -71,7 +69,7 @@ $range-tokens: defaults(
background-color: var(--range-track-bg);
background-image:
linear-gradient(
- var(--range-track-fill-direction),
+ to right,
var(--range-track-fill-bg) calc(var(--range-fill, 0) * 100%),
transparent calc(var(--range-fill, 0) * 100%)
);
@@ -88,10 +86,6 @@ $range-tokens: defaults(
position: relative;
display: block;
width: 100%;
-
- &:dir(rtl) {
- --range-track-fill-direction: to left;
- }
}
.form-range-input {
@@ -170,34 +164,26 @@ $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 half the thumb width to match its center at each end.
+ // Track is inset by 1/4th of the thumb width to keep alignment.
.form-range-ticks {
display: grid;
- padding-inline: calc(var(--range-thumb-width) * .5);
+ padding-inline: calc(var(--range-thumb-width) * .25);
}
.form-range-tick {
diff --git a/scss/forms/_validation.scss b/scss/forms/_validation.scss
index f29dde410c..acf51fd20b 100644
--- a/scss/forms/_validation.scss
+++ b/scss/forms/_validation.scss
@@ -201,9 +201,9 @@ $validation-states: defaults(
}
}
- // Combobox — wrapper has the visible border; the .form-ghost inside
+ // Chip input — wrapper has the visible border; the .form-ghost inside
// receives the native pseudo-class.
- .combobox-control:has(.form-ghost.is-#{$state}) {
+ .chip-input: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] .combobox-control:has(.form-ghost:user-invalid) {
+ [data-bs-validate] .chip-input: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"] .combobox-control:has(.form-ghost:user-valid) {
+ [data-bs-validate~="valid"] .chip-input: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 e5bd08058e..58cd150f1f 100644
--- a/scss/forms/index.scss
+++ b/scss/forms/index.scss
@@ -10,7 +10,7 @@
@forward "strength";
@forward "otp-input";
@forward "form-adorn";
-@forward "combobox-control";
+@forward "chip-input";
@forward "combobox";
@forward "form-field";
@forward "validation";
diff --git a/scss/layout/_grid.scss b/scss/layout/_grid.scss
index 9541bb11d5..f779c0316b 100644
--- a/scss/layout/_grid.scss
+++ b/scss/layout/_grid.scss
@@ -2,6 +2,8 @@
@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 36fb482920..d925210195 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,29 +9,33 @@
// Generate semantic grid columns with these mixins.
@mixin make-row($gutter-x: $grid-gutter-x, $gutter-y: $grid-gutter-y) {
- // stylelint-disable-next-line scss/at-function-named-arguments
- --gutter-x: #{if(sass($gutter-x == 0): 0px; else: $gutter-x)};
+ --gutter-x: #{$gutter-x};
--gutter-y: #{$gutter-y};
display: flex;
flex-wrap: wrap;
- gap: var(--gutter-y) var(--gutter-x);
+ // 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));
}
@mixin make-col-ready() {
- box-sizing: border-box;
+ // 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);
// 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, $gap: var(--gutter-x, 0px)) {
+@mixin make-col($size: false, $columns: $grid-columns) {
@if $size {
flex: 0 0 auto;
- // A span includes its internal gaps and leaves one gap before the next column.
- width: calc((100% + $gap) * #{math.div($size, $columns)} - $gap);
+ width: math.percentage(math.div($size, $columns));
} @else {
flex: 1 1 0;
@@ -44,10 +48,10 @@
width: auto;
}
-@mixin make-col-offset($size, $columns: $grid-columns, $gap: var(--gutter-x, 0px)) {
+@mixin make-col-offset($size, $columns: $grid-columns) {
$num: math.div($size, $columns);
// stylelint-disable-next-line scss/at-function-named-arguments
- margin-inline-start: if(sass($num == 0): 0; else: calc((100% + $gap) * #{$num}));
+ margin-inline-start: if(sass($num == 0): 0; else: math.percentage($num));
}
// Row columns
@@ -58,7 +62,7 @@
@mixin row-cols($count) {
> * {
flex: 0 0 auto;
- width: calc((100% + var(--gutter-x, 0px)) / #{$count} - var(--gutter-x, 0px));
+ width: math.percentage(math.div(1, $count));
}
}
@@ -95,12 +99,7 @@
@if $columns > 0 {
@for $i from 1 through $columns {
.#{$prefix}col-#{$i} {
- // Keep percentage sizing when column classes are used outside rows.
- @include make-col($i, $columns, 0px);
-
- :where(.row) > & {
- @include make-col($i, $columns);
- }
+ @include make-col($i, $columns);
}
}
@@ -108,11 +107,7 @@
@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, 0px);
-
- :where(.row) > & {
- @include make-col-offset($i, $columns);
- }
+ @include make-col-offset($i, $columns);
}
}
}
@@ -124,8 +119,7 @@
@each $key, $value in $gutters {
.#{$prefix}g-#{$key},
.#{$prefix}gx-#{$key} {
- // stylelint-disable-next-line scss/at-function-named-arguments
- --gutter-x: #{if(sass($value == 0): 0px; else: $value)};
+ --gutter-x: #{$value};
}
.#{$prefix}g-#{$key},
diff --git a/site/data/sidebar.yml b/site/data/sidebar.yml
index 23b13d651c..73dee44b39 100644
--- a/site/data/sidebar.yml
+++ b/site/data/sidebar.yml
@@ -93,6 +93,9 @@
- title: Form adorn
meta:
- added: 6.0.0
+ - title: Chips
+ meta:
+ - added: 6.0.0
- title: Combobox
meta:
- added: 6.0.0
@@ -128,9 +131,6 @@
- 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
new file mode 100644
index 0000000000..13c32337d6
Binary files /dev/null and b/site/src/assets/examples/heroes/bootstrap-themes.png differ
diff --git a/site/src/assets/examples/heroes/index.astro b/site/src/assets/examples/heroes/index.astro
index 9d9cdae4f9..b769110d5a 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']
-
+
Responsive left-aligned hero with image
diff --git a/site/src/assets/stackblitz.js b/site/src/assets/stackblitz.js
index 51cda0ea75..05afdf2c37 100644
--- a/site/src/assets/stackblitz.js
+++ b/site/src/assets/stackblitz.js
@@ -37,6 +37,7 @@ 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
deleted file mode 100644
index 8531d0fa82..0000000000
--- a/site/src/content/docs/components/chips.mdx
+++ /dev/null
@@ -1,90 +0,0 @@
----
-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 debfd2f8d4..ec50dabff1 100644
--- a/site/src/content/docs/components/collapse.mdx
+++ b/site/src/content/docs/components/collapse.mdx
@@ -85,24 +85,6 @@ Conversely, multiple `` or `` elements can show and hide the same ele
`} />
-## 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
-
- Toggle
-
-
-
-
-
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.
@@ -146,7 +128,6 @@ 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 d192e775af..96be7764c3 100644
--- a/site/src/content/docs/components/tab.mdx
+++ b/site/src/content/docs/components/tab.mdx
@@ -162,40 +162,6 @@ 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
-
-
-
- Home
-
-
- Profile
-
-
- Contact
-
-
-
-
-
This is some placeholder content the Home tab’s associated content.
-
-
-
This is some placeholder content the Profile 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 `` elements for the tabs, as these are controls that trigger a dynamic change, rather than links that navigate to a new page or location.
@@ -221,7 +187,6 @@ You can activate a tab navigation without writing any JavaScript by simply speci
| --- | --- |
| `data-bs-toggle="tab"` | Activates tab navigation on the trigger. |
| `data-bs-target` | CSS selector for the tab pane to show (must pair with a corresponding `.tab-pane`). |
-| `data-bs-hash` | When set on the tab pane, shows that pane when the URL fragment matches its `id` (on load and `hashchange`). See [Hash links](#hash-links). |
```html
diff --git a/site/src/content/docs/content/prose.mdx b/site/src/content/docs/content/prose.mdx
index dcc2b6456d..1345f05d66 100644
--- a/site/src/content/docs/content/prose.mdx
+++ b/site/src/content/docs/content/prose.mdx
@@ -13,9 +13,7 @@ Wrap your content in the `.prose` class to get modified font-size, line-height,
- Normalize the spacing of lists
- Set a default `margin-bottom` for headings.
- Some headings get an additional `margin-top` to ensure proper spacing between headings and other content.
-- Space the children of blockquotes and disclosures.
-- Keep images and videos within the content width without changing their aspect ratio.
-- Use shared font-weight tokens for headings, heading code, and description terms.
+- Style blockquotes, code, and other inline elements.
The `.not-prose` utility class can be used to opt out of `.prose` typography styles in specific elements. This is useful for components that have their own styling, such as code snippets or examples. Adding a `.prose` within a `.not-prose` won’t work.
@@ -25,13 +23,11 @@ Wrap your content in the `.prose` class to get modified font-size, line-height,
Below is an example of Markdown demonstrating several types of HTML content supported in the `.prose` class.
-
+
# Getting started with documentation
Writing clear and effective documentation is essential for any project. When you create content that others will read and use, [proper formatting](#) makes all the difference. *Good documentation* helps users understand complex concepts quickly and efficiently.
-> Documentation is a guide for your future self. Write each instruction so you can follow it later.
->
-> Leave space between paragraphs so readers can see where each thought starts.
+> Documentation is a love letter that you write to your future self. Clear writing today saves countless hours of confusion tomorrow.
The foundation of great documentation starts with **understanding your audience** and their needs. Writers should focus on clarity, consistency, and providing practical examples that readers can follow.
@@ -53,7 +49,7 @@ Most of these elements are styled by browsers with few modifications on our part
Effective documentation requires careful attention to structure and flow. When organizing content, consider how readers will navigate through your material and what information they need first. Clear headings help users scan quickly and find relevant sections.
-### Inline `code`
+### Code
Inline code is available with the `
` element. Snippets of multiple lines of code are supported through Rouge. Longer lines will automatically scroll horizontally when needed. You may also use code fencing (triple backticks) for rendering code.
@@ -112,30 +108,11 @@ Technical definitions should be clear and accessible to your target audience. Av
Visual elements enhance understanding by providing concrete examples of abstract concepts. Choose images that directly support your written content rather than serving as mere decoration.
-Images keep their aspect ratio when the content becomes narrower. Small images keep their own width instead of stretching. These images have no `.img-fluid` or spacing classes. The same sizing rules apply to `` elements.
+
-
+
-
-
-### Disclosures
-
-Use a disclosure to keep supporting information beside the main instructions. Paragraphs inside it keep space between them.
-
-
- Before you publish
- Check each example in a browser. Confirm that the instructions match the result.
- Read the page at a narrow width. Images should fit the content without changing shape.
-
-
-### Content with its own styles
-
-Use `.not-prose` when a block needs its own typography and spacing.
-
-
-
Excluded content
-
This block uses its own heading and paragraph styles.
-
+
### Tables
diff --git a/site/src/content/docs/forms/chips.mdx b/site/src/content/docs/forms/chips.mdx
new file mode 100644
index 0000000000..e6e5697298
--- /dev/null
+++ b/site/src/content/docs/forms/chips.mdx
@@ -0,0 +1,339 @@
+---
+title: Chips
+description: Small interactive elements representing entities like people, places, tags, or values. Combine with inputs for multi-value fields like skills, categories, or email recipients using themed chips.
+toc: true
+css_layer: forms
+js: required
+---
+
+import { getData } from '@libs/data'
+
+## Overview
+
+Chips are small interactive elements representing entities. They can be used to group and select values in forms or other interactive contexts. They're similar to the older [Badges]([[docsref:/components/badge]]) component, but have some meaningful differences.
+
+- Chips are interactive elements, not static like Badges.
+- 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.
+- Chips automatically gain focus when clicked into their active state.
+- Chips support keyboard navigation and selection in their custom `.chip-input` container.
+
+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. JavaScript users can use the `dismissIcon` option for passing a custom SVG.
+
+Basic chip
+
+
+
+ With avatar
+
+
+
+
+
+
+
+
+ With icon
+
+
+
+ Dismissible
+
+
+
+ `} />
+
+### 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.
+
+
+ Skills:
+
+ 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.
+
+
+ Skills
+
+
+ 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 `` element associated with the chip input for screen readers
+- Chips are focusable and support full keyboard navigation
+- Each `.chip-dismiss` button has `aria-label="Remove"`
+- Selected chips have the `.active` class for visual indication
+- Chips are announced as they are added or removed
+
+## CSS
+
+### Chip variables
+
+
+
+
+
+### Chip input variables
+
+These variables are scoped to the `.chip-input` container.
+
+
diff --git a/site/src/content/docs/forms/combobox.mdx b/site/src/content/docs/forms/combobox.mdx
index cddadd7fd3..3394fa65fd 100644
--- a/site/src/content/docs/forms/combobox.mdx
+++ b/site/src/content/docs/forms/combobox.mdx
@@ -1,7 +1,6 @@
---
title: Combobox
-description: Search and select one or more values from a customizable menu.
-aliases: "/docs/[[config:docs_version]]/forms/chips/"
+description: A customizable select-like component built with markup-first HTML, powered by the Menu component for positioning and keyboard navigation.
toc: true
css_layer: components
js: required
@@ -9,49 +8,45 @@ deps:
- title: Menu
---
-
-**Chip input is now part of Combobox.** Use editable Combobox for free-entry values and multiple selections as chips. See the [migration guide]([[docsref:/guides/migration#chip-input-becomes-combobox]]) to update existing chip inputs.
-
-
## Overview
-The combobox component provides a styled select experience using standard HTML markup. Pair an editable input or a [toggle button]([[docsref:/forms/combobox#button-examples]]) with a `.menu` overlay. Combobox is markup-first: you write the control and menu items in HTML, and Bootstrap handles filtering, keyboard navigation, selection, and form submission.
+The combobox component provides a styled select experience using standard HTML markup — a toggle button paired with a `.menu` overlay. Unlike traditional select enhancements, the combobox is markup-first: you write the toggle and menu items directly in HTML. The JavaScript handles show/hide, selection state, form submission via a hidden input, and keyboard navigation.
-- Custom menu item content, including icons, descriptions, badges, and images
-- Live filtering as you type in the field or in a button’s menu search input
-- Optional check marks for selected items
-- Single and multiple selection, with removable chips for multiple values in the editable field
-- Optional free entry for values outside the menu
-- Keyboard navigation for suggestions, with shortcuts for selecting and removing chips
-- Form submission through generated or provided hidden inputs, with one entry per selected value in multiple mode
-- Bubbling `input` and `change` events when a selection changes
+- Full control over menu item content (icons, descriptions, badges, images — anything)
+- Live search/filtering
+- Check mark indicators for selected items
+- Single and multiple selection modes
+- Full keyboard navigation and accessibility
+- Form submission via auto-created hidden input
## Example
-Add `data-bs-toggle="combobox"` to a `.combobox` wrapper with a `.combobox-input` inside. Place a `.menu` after the wrapper, and give each selectable `.menu-item` a `data-bs-value`.
+Add `data-bs-toggle="combobox"` to a `` element, followed by a `.menu` with `.menu-item` buttons. Each selectable item needs a `data-bs-value` attribute.
-Type in the input to filter the options. The input keeps focus while the arrow keys highlight suggestions. Press Enter to commit a highlighted option. Typing alone does not select it.
-
-Language
-
-
-
- `} />
-
- Column
- Column
- Column
- Column
+
+
+
Column
+
Column
+
Column
+
Column
+
`} />
You can also use the accompanying Sass mixin, `row-cols()`:
@@ -320,17 +346,19 @@ You can also use the accompanying Sass mixin, `row-cols()`:
To nest your content with the default grid, add a new `.row` and set of `.sm:col-*` columns within an existing `.sm:col-*` column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).
-
-
- Level 1: .sm:col-3
-
-
-
-
- Level 2: .col-8 .sm:col-6
-
-
- Level 2: .col-4 .sm:col-6
+
+
+
+ Level 1: .sm:col-3
+
+
+
+
+ Level 2: .col-8 .sm:col-6
+
+
+ Level 2: .col-4 .sm:col-6
+
@@ -379,8 +407,6 @@ Mixins are used in conjunction with the grid variables to generate semantic CSS
### Example usage
-When using `make-col()` or `make-col-offset()` outside a gap-based row, pass `$gap: 0px` to keep percentage sizing.
-
You can modify the variables to your own custom values, or just use the mixins with their default values. Here’s an example of using the default settings to create a two-column layout with a gap between.
```scss
@@ -431,7 +457,7 @@ Using our built-in grid Sass variables and maps, it’s possible to completely c
### Columns and gutters
-The number of grid columns can be modified via Sass variables. `$grid-columns` sets the span fractions used by the gap-aware column widths. `$grid-gutter-x` and `$grid-gutter-y` set the horizontal and vertical gutter sizes. `$grid-row-columns` is used to set the maximum number of columns of `.row-cols-*`, any number over this limit is ignored.
+The number of grid columns can be modified via Sass variables. `$grid-columns` is used to generate the widths (in percent) of each individual column. `$grid-gutter-x` and `$grid-gutter-y` set the horizontal and vertical gutter sizes. `$grid-row-columns` is used to set the maximum number of columns of `.row-cols-*`, any number over this limit is ignored.
```scss
$grid-columns: 12 !default;
diff --git a/site/src/content/docs/layout/gutters.mdx b/site/src/content/docs/layout/gutters.mdx
index ea8a502329..3f6ce468c3 100644
--- a/site/src/content/docs/layout/gutters.mdx
+++ b/site/src/content/docs/layout/gutters.mdx
@@ -1,12 +1,12 @@
---
title: Gutters
-description: Gutters are the gaps between your columns, used to responsively space and align content in the Bootstrap grid system.
+description: Gutters are the padding between your columns, used to responsively space and align content in the Bootstrap grid system.
toc: true
---
## How they work
-- **Gutters use native CSS `gap` on the row.** Numbered column widths and offsets account for the horizontal gap. Columns do not add gutter padding, and rows do not use negative margins. Add padding to an inner wrapper when your content needs it.
+- **Gutters are the gaps between column content, created by horizontal `padding`.** We set `padding-right` and `padding-left` on each column, and use negative `margin` to offset that at the start and end of each row to align content.
- **Gutters start at `1.5rem` (`24px`) wide.** This allows us to match our grid to the [margin]([[docsref:/utilities/margin]]) and [padding]([[docsref:/utilities/padding]]) utilities scale.
@@ -14,52 +14,71 @@ toc: true
## Horizontal gutters
-Use `.gx-*` to control horizontal gaps. The row stays inside its parent, so you do not need extra container padding or an overflow wrapper to contain the gutters:
+`.gx-*` classes can be used to control the horizontal gutter widths. The `.container` or `.container-fluid` parent may need to be adjusted if larger gutters are used too to avoid unwanted overflow, using a matching padding utility. For example, in the following example we’ve increased the padding with `.px-4`:
-
-
-
Custom column padding
+
+
+
+
Custom column padding
+
+
+
Custom column padding
+
-
-
Custom column padding
+
`} />
+
+An alternative solution is to add a wrapper around the `.row` with the `.overflow-hidden` class:
+
+
+
+
+
Custom column padding
+
+
+
Custom column padding
+
`} />
## Vertical gutters
-Use `.gy-*` to control the gap between wrapped lines. Vertical gaps appear only between lines, without adding space before the first line or after the last:
+`.gy-*` classes can be used to control the vertical gutter widths within a row when columns wrap to new lines. Like the horizontal gutters, the vertical gutters can cause some overflow below the `.row` at the end of a page. If this occurs, you add a wrapper around `.row` with the `.overflow-hidden` class:
-
-
-
Custom column padding
-
-
-
Custom column padding
-
-
-
Custom column padding
-
-
-
Custom column padding
+
+
+
+
Custom column padding
+
+
+
Custom column padding
+
+
+
Custom column padding
+
+
+
Custom column padding
+
`} />
## Horizontal & vertical gutters
-Use `.g-*` classes to control horizontal and vertical gaps together.
+Use `.g-*` classes to control the horizontal and vertical grid gutters. In the example below, we use a smaller gutter width, so there isn’t a need for the `.overflow-hidden` wrapper class.
-
-
-
Custom column padding
-
-
-
Custom column padding
-
-
-
Custom column padding
-
-
-
Custom column padding
+
+
+
+
Custom column padding
+
+
+
Custom column padding
+
+
+
Custom column padding
+
+
+
Custom column padding
+
`} />
@@ -67,66 +86,58 @@ Use `.g-*` classes to control horizontal and vertical gaps together.
Gutter classes can also be added to [row columns]([[docsref:/layout/grid#row-columns]]). In the following example, we use responsive row columns and responsive gutter classes.
-
-
-
-
-
-
-
-
-
-
- `} />
## No gutters
-Use `.g-0` to remove horizontal and vertical gaps. Column widths and offsets update to match the zero gap.
+The gutters between columns in our predefined grid classes can be removed with `.g-0`. This removes the negative `margin`s from `.row` and the horizontal `padding` from all immediate children columns.
-**Need an edge-to-edge design?** Drop the parent `.container` or `.container-fluid`. Rows no longer need `.mx-0` to prevent gutter overflow.
+**Need an edge-to-edge design?** Drop the parent `.container` or `.container-fluid` and add `.mx-0` to the `.row` to prevent overflow.
In practice, here’s how it looks. Note that you can continue to use this with all other predefined grid classes (including column widths, responsive tiers, reorders, and more).
-
+
.sm:col-6 .md:col-8
.col-6 .md:col-4
`} />
-## Column widths and offsets
-
-For a span of `s` columns in an `N`-column grid, the width is `(row width + horizontal gap) × s / N − horizontal gap`. An offset of `s` columns uses `(row width + horizontal gap) × s / N`. These calculations support mixed numbered spans without needing to count the items on each line.
-
-`.col` shares the remaining space after gaps, while `.col-auto` keeps its content width. Numbered column classes outside a `.row` keep their percentage widths.
-
-Use `.g-*`, `.gx-*`, and `.gy-*` to change flex grid gaps. Generic `.gap-*` utilities change `gap` without updating the gutter variables used by the width calculations. For custom CSS, set `--bs-gutter-x` and `--bs-gutter-y` on the row; include a length unit such as `0px` for a zero horizontal gap.
-
## Change the gutters
Classes are built from the `$gutters` Sass map which is inherited from the `$spacers` Sass map.
-Gutter classes use values from the Sass map. A runtime override of `--bs-spacer-*` does not change those classes. To change gaps at runtime, set `--bs-gutter-x` and `--bs-gutter-y` on the row.
-
```scss
$grid-gutter-x: 1.5rem;
$gutters: $spacers;
diff --git a/site/src/content/docs/utilities/gap.mdx b/site/src/content/docs/utilities/gap.mdx
index 3a25beb081..c6f6ed0853 100644
--- a/site/src/content/docs/utilities/gap.mdx
+++ b/site/src/content/docs/utilities/gap.mdx
@@ -29,8 +29,6 @@ Use gap utilities to control the space between children in flexbox and grid layo
```
-For the flexbox grid’s `.row`, use `.g-*`, `.gx-*`, and `.gy-*` instead. These classes also update the gutter variables used by column widths. See [Gutters]([[docsref:/layout/gutters]]).
-
**Support note:** Gap utilities work with CSS Grid and Flexbox layouts. They are a modern alternative to margin utilities for spacing children within a container.
diff --git a/site/src/libs/js-dependencies.ts b/site/src/libs/js-dependencies.ts
index b606ce5c96..e7a8072e6f 100644
--- a/site/src/libs/js-dependencies.ts
+++ b/site/src/libs/js-dependencies.ts
@@ -24,7 +24,6 @@ const FILE_DESCRIPTIONS: Record
= {
'util/component-functions': 'Shared component helpers',
'util/config': 'Configuration base class',
'util/floating-ui': 'Responsive placement utilities',
- 'util/hash-target': 'URL hash target helpers',
'util/index': 'Core utility functions',
'util/sanitizer': 'HTML content sanitizer',
'util/scroll-lock': 'Page scroll locking and scrollbar compensation',
diff --git a/site/src/scss/_component-examples.scss b/site/src/scss/_component-examples.scss
deleted file mode 100644
index 5517affbab..0000000000
--- a/site/src/scss/_component-examples.scss
+++ /dev/null
@@ -1,14 +0,0 @@
-// check-unused-imports-disable — @use loads shared example styles.
-@use "@twbs/bui/scss/component-examples";
-
-// Include responsive column classes in the shared BUI example highlighting.
-@layer custom {
- .bd-example-row :is([class~="col"], [class*="col-"], [class*=":col"]),
- .bd-example-cols :is([class~="col"], [class*="col-"], [class*=":col"]) > *,
- .bd-example-cssgrid [class*="grid"] > * {
- padding-block: .75rem;
- text-align: center;
- background-color: color-mix(in srgb, var(--bd-violet) 15%, transparent);
- border: 1px solid color-mix(in srgb, var(--bd-violet) 30%, transparent);
- }
-}
diff --git a/site/src/scss/_content.scss b/site/src/scss/_content.scss
index 00c14e6be6..f706a424ab 100644
--- a/site/src/scss/_content.scss
+++ b/site/src/scss/_content.scss
@@ -1,5 +1,4 @@
@use "../../../scss/layout/breakpoints" as *;
-@use "../../../scss/mixins/border-radius" as *;
//
// Bootstrap docs content theming
@@ -102,24 +101,6 @@
}
}
- .bd-example-prose {
- padding: var(--bs-spacer-3);
- border: var(--bs-border-width) solid var(--bs-border-color);
- @include border-radius(var(--bs-radius-3));
-
- @include media-breakpoint-up(lg) {
- padding: var(--bs-spacer-5);
- }
-
- @include media-breakpoint-down(md) {
- padding-block: 2rem;
- padding-inline: calc(var(--bs-gutter-x) * .5);
- margin-inline: calc(var(--bs-gutter-x) * -.5);
- border-inline-width: 0;
- @include border-radius(0);
- }
- }
-
.table-options {
td:nth-child(2) {
min-width: 160px;
diff --git a/site/src/scss/_scrolling.scss b/site/src/scss/_scrolling.scss
index 45487588be..ddb2974917 100644
--- a/site/src/scss/_scrolling.scss
+++ b/site/src/scss/_scrolling.scss
@@ -10,8 +10,7 @@
h2,
h3,
h4,
- [tabindex="0"],
- [data-bs-hash] {
+ [tabindex="0"] {
scroll-margin-block-start: var(--bd-navbar-offset);
scroll-margin-block-end: 100px;
}
diff --git a/site/src/scss/docs.scss b/site/src/scss/docs.scss
index 8d0adc0b13..702edbe061 100644
--- a/site/src/scss/docs.scss
+++ b/site/src/scss/docs.scss
@@ -35,7 +35,7 @@
@use "layout";
@use "toc";
@use "footer";
-@use "component-examples";
+@use "@twbs/bui/scss/component-examples";
@use "badge";
@use "callouts";
@use "details";
diff --git a/site/static/docs/[version]/assets/img/bootstrap-intellisense-autocomplete.png b/site/static/docs/[version]/assets/img/bootstrap-intellisense-autocomplete.png
new file mode 100644
index 0000000000..073675662b
Binary files /dev/null and b/site/static/docs/[version]/assets/img/bootstrap-intellisense-autocomplete.png differ
diff --git a/site/static/docs/[version]/assets/img/bootstrap-themes-collage.png b/site/static/docs/[version]/assets/img/bootstrap-themes-collage.png
new file mode 100644
index 0000000000..da99b30a8a
Binary files /dev/null and b/site/static/docs/[version]/assets/img/bootstrap-themes-collage.png differ
diff --git a/site/static/docs/[version]/assets/img/bootstrap-themes-collage@2x.png b/site/static/docs/[version]/assets/img/bootstrap-themes-collage@2x.png
new file mode 100644
index 0000000000..2ffb1ce9ea
Binary files /dev/null and b/site/static/docs/[version]/assets/img/bootstrap-themes-collage@2x.png differ
diff --git a/site/static/docs/[version]/assets/img/bootstrap-themes.png b/site/static/docs/[version]/assets/img/bootstrap-themes.png
new file mode 100644
index 0000000000..d43dba2a7d
Binary files /dev/null and b/site/static/docs/[version]/assets/img/bootstrap-themes.png differ
diff --git a/site/static/docs/[version]/assets/img/bootstrap-themes@2x.png b/site/static/docs/[version]/assets/img/bootstrap-themes@2x.png
new file mode 100644
index 0000000000..13c32337d6
Binary files /dev/null and b/site/static/docs/[version]/assets/img/bootstrap-themes@2x.png differ
diff --git a/skills/bootstrap-v5-v6-migration/SKILL.md b/skills/bootstrap-v5-v6-migration/SKILL.md
index 1c2dca1ec4..633d9fbd6b 100644
--- a/skills/bootstrap-v5-v6-migration/SKILL.md
+++ b/skills/bootstrap-v5-v6-migration/SKILL.md
@@ -619,8 +619,8 @@ The `data-bs-spy="scroll"` markup and the `activate.bs.scrollspy` event are unch
| Component | Trigger / hook | Purpose |
| --- | --- | --- |
-| Combobox | `data-bs-toggle="combobox"` | Editable single or multiple selection and optional free entry, built on Menu |
-| Chip | `.chip` | Standalone tag / token presentation |
+| Combobox | `data-bs-toggle="combobox"` | Filterable/autocomplete select built on Menu |
+| Chip / Chip input | `.chip`, `.chip-input` (`data-bs-chips`) | Tags / tokens + interactive entry |
| Datepicker | `data-bs-toggle="datepicker"` | Date picker (peer dep `vanilla-calendar-pro`) |
| Range | `.form-range` (+ `data-bs-bubble`, ticks) | Enhanced range slider with a value bubble |
| Strength | `data-bs-strength` | Password-strength meter |