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 `
This is some placeholder content the Home tab’s associated content.
+
+
+
This is some placeholder content the Profile tab’s associated content.
+
+
+
This is some placeholder content the Contact tab’s associated content.
+
+
`} />
+
## Accessibility
Dynamic tabbed interfaces, as described in the [ARIA Authoring Practices Guide tabs pattern](https://www.w3.org/WAI/ARIA/apg/patterns/tabpanel/), require `role="tablist"`, `role="tab"`, `role="tabpanel"`, and additional `aria-` attributes in order to convey their structure, functionality, and current state to users of assistive technologies (such as screen readers). As a best practice, we recommend using `` elements for the tabs, as these are controls that trigger a dynamic change, rather than links that navigate to a new page or location.
@@ -187,6 +221,7 @@ 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/libs/js-dependencies.ts b/site/src/libs/js-dependencies.ts
index e7a8072e6f..b606ce5c96 100644
--- a/site/src/libs/js-dependencies.ts
+++ b/site/src/libs/js-dependencies.ts
@@ -24,6 +24,7 @@ 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/_scrolling.scss b/site/src/scss/_scrolling.scss
index ddb2974917..45487588be 100644
--- a/site/src/scss/_scrolling.scss
+++ b/site/src/scss/_scrolling.scss
@@ -10,7 +10,8 @@
h2,
h3,
h4,
- [tabindex="0"] {
+ [tabindex="0"],
+ [data-bs-hash] {
scroll-margin-block-start: var(--bd-navbar-offset);
scroll-margin-block-end: 100px;
}
From f9a7a8941e7c1c91b0cae8a0c906537c26086ae2 Mon Sep 17 00:00:00 2001
From: Mark Otto
Date: Thu, 12 Nov 2026 12:48:15 -0800
Subject: [PATCH 4/9] Unify chip input and editable Combobox (#43300)
* fix(combobox): support native form values and events
Multiple selections now submit one field per value. Commas stay in the
value, and an empty multiple selection submits no entries. Reuse an
explicit hidden input without removing application-owned fields.
Keep a stable field for input and change listeners. Sync fields before
notifications, restore initial selections on reset, and follow disabled
state and form ownership. Document the update and disposal contracts.
Forward Menu lifecycle events after its transitions. Keep native search
editing keys and cover the sticky search padding with logical CSS.
* feat(combobox): combine editable selection and chip entry
Search and select values from one editable field. Multiple selections
render as removable chips, and explicit free entry supports tags. Keep
query text separate from committed values and preserve native form data.
Use the existing Menu for positioning and lifecycle. Keep focus in the
editor while suggestions are highlighted. Preserve chip nodes, caret
positions, reset behavior, and input-method text during reconciliation.
Retire the separate Chips plugin and chip-input control. Keep static
chip styles and button-triggered Combobox markup. Document the alpha 2
markup, token, method, and event migration.
* fix(combobox): match chip fields to the default input height
Multiple values should fit the same row height as a normal input.
Use shared input spacing and typography, with smaller contextual chips.
Let the field grow when its values wrap.
Replace the text dismiss glyph with the SVG from the chip documentation.
Keep the named removal button and existing chip interaction behavior.
* fix(combobox): separate chip icon size from its hit area
Render the dismiss icon at 12px inside a 24px removal button. Move chips
closer to the field's inline start while keeping normal text padding
for an empty editor. Use logical spacing so the inset follows RTL.
* fix(combobox): tighten chip dismiss spacing
Use negative inline margins to bring the dismiss button closer to the
label and chip edge. Keep its 24px hit area and 12px SVG artwork.
* fix(combobox): derive chip corners from the field radius
Use a nested chip radius based on the wrapping field's radius, border,
and inset. Clamp the result at zero so square fields keep square chips.
* fix(combobox): balance chip insets within the field
Match the field's inline padding to its vertical padding when chips
are present. Derive chip corners from that inset and pull the dismiss
button's end margin in another 2px without reducing its hit area.
* fix(combobox): soften chip corners within balanced fields
Use half the field radius for chips so equal input padding does not
leave their corners nearly square. Keep square fields square.
* fix(combobox): restore chip selection and keyboard behavior
Highlight chips with the filled active state when users navigate or
select them. Restore modifier clicks, anchored ranges, select-all, and
deletion of highlighted chips. Keep native query editing and RTL keys.
Keep chip highlights separate from committed values. Report UI selection
through select.bs.combobox and restore the chip selection methods on
Combobox. Bulk removal honors each cancellation and emits one value
change before recovering focus.
Document the restored interaction and alpha migration. Cover range
anchors, duplicate values, disabled chips, reset, and disposal.
* fix(combobox): select chips on every focus path
Tabbing to a chip's remove button or focusing a chip directly should
show its primary selected state. Apply that highlight without changing
committed values, and dismiss the suggestion popup.
Guard focus controlled by range navigation and modifier clicks so it
does not collapse or undo the user's chip selection.
* fix(combobox): suppress inner chip focus outlines
Keep the filled selected chip and the wrapping field's focus ring as
focus indicators. Suppress the nested outlines on chips and their
remove buttons during keyboard navigation.
* fix(combobox): guard form and editor edge cases
Selection callbacks can change or dispose the component before an outer
operation completes. Stop stale selection and focus work after those
callbacks, and keep pending popup sizing from changing disposed markup.
Handle native composition events through the shared event system. Keep
unfinished input out of blur commits, reconcile completed composition,
and preserve focus after the editor loses it. Let the IME handle its
keys in both Combobox and Menu.
Follow external reset forms without a backing field, omit disabled
single options, and clear references to removed or disabled suggestions.
Add regressions and clarify the synchronous form update requirement.
* docs(chips): move standalone chips to Components
Chips can stand alone or appear within a form component. Place their
docs in Components and describe that wider use. Keep the old Forms URL
as a redirect, and update navigation and cross-links.
* fix(chips): limit hover feedback to interactive chips
Static chips change color and show a pointer cursor on hover, even
when they have no action. Keep static chips neutral and apply hover
feedback to links, buttons, and Combobox chips. A dismiss button keeps
its own hover state without changing the whole chip.
Add interactive examples and correct the documented CSS layer. Allow
for the extra selectors in the unminified CSS bundle budget.
* docs(combobox): lead with editable examples
Show search and selection in the input from the first example. Use
inputs for the shared examples and group the button variants together.
Use the editable markup in the form and setup guidance too.
* docs(combobox): restore the overview feature list
Describe editable inputs and button toggles in the original overview.
Include chips, free entry, form submission, and selection events.
* docs(combobox): preserve example indentation
Match the form field examples by adding the source indentation that
MDX strips. Record the convention in the docs guidance.
* fix(combobox): focus search directly when opening
Clicking a searchable combobox moved focus to the trigger before
the opening animation moved it to search.
Focus search as soon as the menu opens. Keep the trigger in the
tab order and return focus to it on Escape.
* docs(combobox): style the Language example label
* ci(combobox): fix bundle budgets and spelling
Round the three JavaScript bundle limits up to the next quarter
kilobyte to account for the search focus changes. Reword the docs
indentation rule so it passes the spelling check.
* fix(combobox): preserve resets and expose selection state
A canceled second reset could discard a completed reset. Keep each
pending reset until its own callback runs. Give button-mode options
listbox roles, handle Escape on the toggle, and restore chip focus
rings. Keep long values inside the field and use shared state tokens.
* fix(combobox): fit chips to the shared control size
Compact controls were 30px tall, but their fixed-height chips made
the multiple-selection field 34px tall. Derive chip and dismiss-button
heights from the space left by the control padding and borders. Check
compact, default, and spacious controls in the browser.
* docs(combobox): redirect chip input readers to the merged component
The former chip input page now points to Combobox. Explain the
consolidation at the top of that page and link the migration steps
for existing chip inputs.
* chore(combobox): account for the current main bundle size
The rebased build includes the merged Range and hash-link fixes.
Raise the three affected limits to the next standard budget step.
---
.bundlewatch.config.json | 10 +-
.cspell.json | 2 +
AGENTS.md | 1 +
js/src/chips.ts | 668 ---------
js/src/combobox.ts | 1261 +++++++++++++++--
js/src/dom/event-handler.ts | 3 +
js/src/index.ts | 1 -
js/src/menu.ts | 20 +-
js/src/util/sanitizer.ts | 2 +-
js/tests/types/api.ts | 24 +-
js/tests/types/consumer.ts | 24 +-
js/tests/unit/chips.spec.js | 695 ---------
js/tests/unit/combobox-editor.spec.js | 741 ++++++++++
js/tests/unit/combobox-form.spec.js | 411 ++++++
js/tests/unit/combobox-layout.spec.js | 46 +
js/tests/unit/combobox.spec.js | 30 +-
scss/_chip.scss | 21 +-
...chip-input.scss => _combobox-control.scss} | 44 +-
scss/forms/_combobox.scss | 41 +-
scss/forms/_validation.scss | 8 +-
scss/forms/index.scss | 2 +-
site/data/sidebar.yml | 6 +-
site/src/assets/stackblitz.js | 1 -
site/src/content/docs/components/chips.mdx | 88 ++
site/src/content/docs/forms/chips.mdx | 339 -----
site/src/content/docs/forms/combobox.mdx | 499 ++++---
.../docs/getting-started/javascript.mdx | 2 +-
site/src/content/docs/guides/migration.mdx | 18 +-
skills/bootstrap-v5-v6-migration/SKILL.md | 4 +-
29 files changed, 2960 insertions(+), 2052 deletions(-)
delete mode 100644 js/src/chips.ts
delete mode 100644 js/tests/unit/chips.spec.js
create mode 100644 js/tests/unit/combobox-editor.spec.js
create mode 100644 js/tests/unit/combobox-form.spec.js
create mode 100644 js/tests/unit/combobox-layout.spec.js
rename scss/forms/{_chip-input.scss => _combobox-control.scss} (52%)
create mode 100644 site/src/content/docs/components/chips.mdx
delete mode 100644 site/src/content/docs/forms/chips.mdx
diff --git a/.bundlewatch.config.json b/.bundlewatch.config.json
index 078d3f0f95..2d95e9094b 100644
--- a/.bundlewatch.config.json
+++ b/.bundlewatch.config.json
@@ -26,19 +26,19 @@
},
{
"path": "./dist/css/bootstrap.css",
- "maxSize": "54.25 kB"
+ "maxSize": "54.5 kB"
},
{
"path": "./dist/css/bootstrap.min.css",
- "maxSize": "50.5 kB"
+ "maxSize": "50.75 kB"
},
{
"path": "./dist/js/bootstrap.bundle.js",
- "maxSize": "76.5 kB"
+ "maxSize": "79.75 kB"
},
{
"path": "./dist/js/bootstrap.bundle.min.js",
- "maxSize": "60.0 kB"
+ "maxSize": "62.75 kB"
},
{
"path": "./dist/js/bootstrap.js",
@@ -46,7 +46,7 @@
},
{
"path": "./dist/js/bootstrap.min.js",
- "maxSize": "36.0 kB"
+ "maxSize": "39.0 kB"
}
],
"ci": {
diff --git a/.cspell.json b/.cspell.json
index 06e29d2b36..f06670ecad 100644
--- a/.cspell.json
+++ b/.cspell.json
@@ -1,6 +1,7 @@
{
"version": "0.2",
"words": [
+ "activedescendant",
"affordance",
"allowfullscreen",
"Analyser",
@@ -124,6 +125,7 @@
"mkdir",
"monospace",
"mouseleave",
+ "multiselectable",
"navbars",
"navs",
"navoverflow",
diff --git a/AGENTS.md b/AGENTS.md
index 4a1001f14e..d096362488 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -84,6 +84,7 @@ Act as a teacher for JavaScript, TypeScript, React, and all JavaScript-family to
- Astro 5 + MDX in `site/src/content/docs/`
- Frontmatter schema: `title` (required), `description` (required), `toc`, `aliases`, `added`, `mdn`, `reference`, etc.
- Shortcodes: `Example`, `Callout`, `Code`, `Details`
+- For multiline `` template literals that start on the same line as the shortcode, add two extra spaces to each following line of code. Top-level markup starts with two spaces in the source, and its children start with four. The rendered snippet removes the extra level. Follow `site/src/content/docs/forms/field.mdx` and check the rendered code before committing.
- Internal links: `[[docsref:/path/]]`
- JS component "Dependencies" tables are auto-generated — add a `### Dependencies` heading with `` (before `### Options`) on any doc for a `js/src/*.ts` component. The table is derived at build time by walking the component's import graph in `site/src/libs/js-dependencies.ts`; never hand-write the file list. When a new source file or third-party package enters the graph, add its human-readable label to `FILE_DESCRIPTIONS` / `PACKAGE_DESCRIPTIONS` in that lib (the build throws if a label is missing).
diff --git a/js/src/chips.ts b/js/src/chips.ts
deleted file mode 100644
index 8341a590f8..0000000000
--- a/js/src/chips.ts
+++ /dev/null
@@ -1,668 +0,0 @@
-/**
- * --------------------------------------------------------------------------
- * Bootstrap chips.ts
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
- * --------------------------------------------------------------------------
- */
-
-import BaseComponent from './base-component.js'
-import EventHandler, { type BootstrapEvent } from './dom/event-handler.js'
-import SelectorEngine from './dom/selector-engine.js'
-import { onDocumentReady } from './util/component-functions.js'
-import { DefaultIconAllowlist, sanitizeHtml } from './util/sanitizer.js'
-
-/**
- * Constants
- */
-
-const NAME = 'chips'
-const DATA_KEY = 'bs.chips'
-const EVENT_KEY = `.${DATA_KEY}`
-const DATA_API_KEY = '.data-api'
-
-const EVENT_ADD = `add${EVENT_KEY}`
-const EVENT_REMOVE = `remove${EVENT_KEY}`
-const EVENT_CHANGE = `change${EVENT_KEY}`
-const EVENT_SELECT = `select${EVENT_KEY}`
-
-const SELECTOR_DATA_CHIPS = '[data-bs-chips]'
-const SELECTOR_GHOST_INPUT = '.form-ghost'
-const SELECTOR_CHIP = '.chip'
-const SELECTOR_CHIP_DISMISS = '.chip-dismiss'
-
-const CLASS_NAME_CHIP = 'chip'
-const CLASS_NAME_CHIP_DISMISS = 'chip-dismiss'
-const CLASS_NAME_ACTIVE = 'active'
-
-const DEFAULT_DISMISS_ICON = ''
-
-type ChipsConfig = {
- separator: string | null
- allowDuplicates: boolean
- maxChips: number | null
- placeholder: string
- dismissible: boolean
- dismissIcon: string
- createOnBlur: boolean
-}
-
-const Default: ChipsConfig = {
- separator: ',',
- allowDuplicates: false,
- maxChips: null,
- placeholder: '',
- dismissible: true,
- dismissIcon: DEFAULT_DISMISS_ICON,
- createOnBlur: true
-}
-
-const DefaultType = {
- separator: '(string|null)',
- allowDuplicates: 'boolean',
- maxChips: '(number|null)',
- placeholder: 'string',
- dismissible: 'boolean',
- dismissIcon: 'string',
- createOnBlur: 'boolean'
-}
-
-/**
- * Class definition
- */
-
-class Chips extends BaseComponent {
- protected declare _config: ChipsConfig
- protected declare _input: HTMLInputElement
- protected declare _chips: string[]
- protected declare _selectedChips: Set
- protected declare _anchorChip: HTMLElement | null
-
- constructor(element?: string | Element | null, config?: Partial | null) {
- super(element, config)
-
- const ghostInput = SelectorEngine.findOne(SELECTOR_GHOST_INPUT, this._element)
- this._chips = []
- this._selectedChips = new Set()
- this._anchorChip = null // For shift+click range selection
-
- if (ghostInput) {
- this._input = ghostInput
- } else {
- this._createInput()
- }
-
- this._initializeExistingChips()
- this._addEventListeners()
- }
-
- // Getters
- static override get Default(): ChipsConfig {
- return Default
- }
-
- static override get DefaultType(): Record {
- return DefaultType
- }
-
- static override get NAME(): string {
- return NAME
- }
-
- // Public
- add(value: string): HTMLElement | null {
- const trimmedValue = String(value).trim()
-
- if (!trimmedValue) {
- return null
- }
-
- // Check for duplicates
- if (!this._config.allowDuplicates && this._chips.includes(trimmedValue)) {
- return null
- }
-
- // Check max chips limit
- if (this._config.maxChips !== null && this._chips.length >= this._config.maxChips) {
- return null
- }
-
- const addEvent = EventHandler.trigger(this._element, EVENT_ADD, {
- value: trimmedValue,
- relatedTarget: this._input
- })
-
- if (addEvent.defaultPrevented) {
- return null
- }
-
- const chip = this._createChip(trimmedValue)
- this._element.insertBefore(chip, this._input)
- this._chips.push(trimmedValue)
-
- EventHandler.trigger(this._element, EVENT_CHANGE, {
- values: this.getValues()
- })
-
- return chip
- }
-
- remove(chipOrValue: string | HTMLElement): boolean {
- let chip: HTMLElement | undefined
- let value: string
-
- if (typeof chipOrValue === 'string') {
- value = chipOrValue
- chip = this._findChipByValue(value)
- } else {
- chip = chipOrValue
- value = this._getChipValue(chip)
- }
-
- if (!chip || !value) {
- return false
- }
-
- const removeEvent = EventHandler.trigger(this._element, EVENT_REMOVE, {
- value,
- chip,
- relatedTarget: this._input
- })
-
- if (removeEvent.defaultPrevented) {
- return false
- }
-
- // Remove from selection
- this._selectedChips.delete(chip)
- if (this._anchorChip === chip) {
- this._anchorChip = null
- }
-
- // Remove from DOM, then rebuild the value array from the remaining chips.
- // This keeps `_chips` in the same order as the rendered chips even with
- // duplicates, where splicing the first matching value would desync order.
- chip.remove()
- this._chips = this._getChipElements()
- .map(chipElement => this._getChipValue(chipElement))
- .filter(Boolean)
-
- EventHandler.trigger(this._element, EVENT_CHANGE, {
- values: this.getValues()
- })
-
- return true
- }
-
- removeSelected(): void {
- const chipsToRemove = [...this._selectedChips]
- for (const chip of chipsToRemove) {
- this.remove(chip)
- }
-
- this._input?.focus()
- }
-
- getValues(): string[] {
- return [...this._chips]
- }
-
- getSelectedValues(): string[] {
- return [...this._selectedChips].map(chip => this._getChipValue(chip))
- }
-
- clear(): void {
- const chips = SelectorEngine.find(SELECTOR_CHIP, this._element)
- for (const chip of chips) {
- chip.remove()
- }
-
- this._chips = []
- this._selectedChips.clear()
- this._anchorChip = null
-
- EventHandler.trigger(this._element, EVENT_CHANGE, {
- values: []
- })
- }
-
- clearSelection(): void {
- for (const chip of this._selectedChips) {
- chip.classList.remove(CLASS_NAME_ACTIVE)
- }
-
- this._selectedChips.clear()
- this._anchorChip = null
-
- EventHandler.trigger(this._element, EVENT_SELECT, {
- selected: []
- })
- }
-
- selectChip(chip: HTMLElement, options: { addToSelection?: boolean, rangeSelect?: boolean } = {}): void {
- const { addToSelection = false, rangeSelect = false } = options
- const chipElements = this._getChipElements()
-
- if (!chipElements.includes(chip)) {
- return
- }
-
- if (rangeSelect && this._anchorChip) {
- // Range selection from anchor to chip
- const anchorIndex = chipElements.indexOf(this._anchorChip)
- const chipIndex = chipElements.indexOf(chip)
- const start = Math.min(anchorIndex, chipIndex)
- const end = Math.max(anchorIndex, chipIndex)
-
- if (!addToSelection) {
- // clearSelection() resets the anchor, keep it for the next range selection
- const anchorChip = this._anchorChip
- this.clearSelection()
- this._anchorChip = anchorChip
- }
-
- for (let i = start; i <= end; i++) {
- this._selectedChips.add(chipElements[i])
- chipElements[i].classList.add(CLASS_NAME_ACTIVE)
- }
- } else if (addToSelection) {
- // Toggle selection
- if (this._selectedChips.has(chip)) {
- this._selectedChips.delete(chip)
- chip.classList.remove(CLASS_NAME_ACTIVE)
- } else {
- this._selectedChips.add(chip)
- chip.classList.add(CLASS_NAME_ACTIVE)
- this._anchorChip = chip
- }
- } else {
- // Single selection
- this.clearSelection()
- this._selectedChips.add(chip)
- chip.classList.add(CLASS_NAME_ACTIVE)
- this._anchorChip = chip
- }
-
- EventHandler.trigger(this._element, EVENT_SELECT, {
- selected: this.getSelectedValues()
- })
- }
-
- focus(): void {
- this._input?.focus()
- }
-
- override dispose(): void {
- EventHandler.off(this._input, EVENT_KEY)
- super.dispose()
- }
-
- // Private
- protected _getChipElements(): HTMLElement[] {
- return SelectorEngine.find(SELECTOR_CHIP, this._element)
- }
-
- protected _createInput(): void {
- const input = document.createElement('input')
- input.type = 'text'
- input.className = 'form-ghost'
- if (this._config.placeholder) {
- input.placeholder = this._config.placeholder
- }
-
- this._element.append(input)
- this._input = input
- }
-
- protected _initializeExistingChips(): void {
- const existingChips = SelectorEngine.find(SELECTOR_CHIP, this._element)
- for (const chip of existingChips) {
- const value = this._getChipValue(chip)
- if (value) {
- this._chips.push(value)
- this._setupChip(chip)
- }
- }
- }
-
- protected _setupChip(chip: HTMLElement): void {
- // Make chip focusable
- chip.setAttribute('tabindex', '0')
-
- // Add dismiss button if needed
- if (this._config.dismissible && !SelectorEngine.findOne(SELECTOR_CHIP_DISMISS, chip)) {
- chip.append(this._createDismissButton())
- }
- }
-
- protected _createChip(value: string): HTMLElement {
- const chip = document.createElement('span')
- chip.className = CLASS_NAME_CHIP
- chip.dataset.bsChipValue = value
-
- // Add text node
- chip.append(document.createTextNode(value))
-
- // Setup chip (tabindex, dismiss button)
- this._setupChip(chip)
-
- return chip
- }
-
- protected _createDismissButton(): HTMLButtonElement {
- const button = document.createElement('button')
- button.type = 'button'
- button.className = CLASS_NAME_CHIP_DISMISS
- button.setAttribute('aria-label', 'Remove')
- button.setAttribute('tabindex', '-1') // Not in tab order, chips handle keyboard
- // dismissIcon accepts HTML (SVGs, icon fonts) and is also settable via the
- // data API, so run it through the icon allowlist before insertion.
- button.innerHTML = sanitizeHtml(this._config.dismissIcon, DefaultIconAllowlist)
- return button
- }
-
- protected _findChipByValue(value: string): HTMLElement | undefined {
- const chips = this._getChipElements()
- return chips.find(chip => this._getChipValue(chip) === value)
- }
-
- protected _getChipValue(chip: HTMLElement): string {
- if (chip.dataset.bsChipValue) {
- return chip.dataset.bsChipValue
- }
-
- const clone = chip.cloneNode(true) as HTMLElement
- const dismiss = SelectorEngine.findOne(SELECTOR_CHIP_DISMISS, clone)
- if (dismiss) {
- dismiss.remove()
- }
-
- return clone.textContent?.trim() || ''
- }
-
- protected _addEventListeners(): void {
- // Input events
- EventHandler.on(this._input, `keydown${EVENT_KEY}`, event => this._handleInputKeydown(event))
- EventHandler.on(this._input, `input${EVENT_KEY}`, event => this._handleInput(event))
- EventHandler.on(this._input, `paste${EVENT_KEY}`, event => this._handlePaste(event))
- EventHandler.on(this._input, `focus${EVENT_KEY}`, () => this.clearSelection())
-
- if (this._config.createOnBlur) {
- EventHandler.on(this._input, `blur${EVENT_KEY}`, event => {
- // Don't create chip if clicking on a chip
- if (!event.relatedTarget?.closest(SELECTOR_CHIP)) {
- this._createChipFromInput()
- }
- })
- }
-
- // Chip click events (delegated)
- EventHandler.on(this._element, `click${EVENT_KEY}`, SELECTOR_CHIP, event => {
- // Ignore clicks on dismiss button
- if ((event.target as Element).closest(SELECTOR_CHIP_DISMISS)) {
- return
- }
-
- const chip = (event.target as Element).closest(SELECTOR_CHIP)
- if (chip) {
- event.preventDefault()
- this.selectChip(chip, {
- addToSelection: event.metaKey || event.ctrlKey,
- rangeSelect: event.shiftKey
- })
- chip.focus()
- }
- })
-
- // Dismiss button clicks (delegated)
- EventHandler.on(this._element, `click${EVENT_KEY}`, SELECTOR_CHIP_DISMISS, event => {
- event.stopPropagation()
- const chip = (event.target as Element).closest(SELECTOR_CHIP)
- if (chip) {
- this.remove(chip)
- this._input?.focus()
- }
- })
-
- // Chip keyboard events (delegated)
- EventHandler.on(this._element, `keydown${EVENT_KEY}`, SELECTOR_CHIP, event => {
- this._handleChipKeydown(event)
- })
-
- // Focus input when clicking container background
- EventHandler.on(this._element, `click${EVENT_KEY}`, event => {
- if (event.target === this._element) {
- this.clearSelection()
- this._input?.focus()
- }
- })
- }
-
- protected _handleInputKeydown(event: BootstrapEvent): void {
- const { key } = event
-
- switch (key) {
- case 'Enter': {
- event.preventDefault()
- this._createChipFromInput()
- break
- }
-
- case 'Backspace':
- case 'Delete': {
- if (this._input.value === '') {
- event.preventDefault()
- const chips = this._getChipElements()
-
- if (chips.length > 0) {
- // Select last chip and focus it
- const lastChip = chips.at(-1)!
- this.selectChip(lastChip)
- lastChip.focus()
- }
- }
-
- break
- }
-
- case 'ArrowLeft': {
- if (this._input.selectionStart === 0 && this._input.selectionEnd === 0) {
- event.preventDefault()
- const chips = this._getChipElements()
- if (chips.length > 0) {
- const lastChip = chips.at(-1)!
- if (event.shiftKey) {
- this.selectChip(lastChip, { addToSelection: true })
- } else {
- this.selectChip(lastChip)
- }
-
- lastChip.focus()
- }
- }
-
- break
- }
-
- case 'Escape': {
- this._input.value = ''
- this.clearSelection()
- this._input.blur()
- break
- }
-
- // No default
- }
- }
-
- protected _handleChipKeydown(event: BootstrapEvent): void {
- const { key } = event
- const chip = (event.target as Element).closest(SELECTOR_CHIP)
- if (!chip) {
- return
- }
-
- const chips = this._getChipElements()
- const currentIndex = chips.indexOf(chip)
-
- switch (key) {
- case 'Backspace':
- case 'Delete': {
- event.preventDefault()
- this._handleChipDelete(currentIndex, chips)
- break
- }
-
- case 'ArrowLeft': {
- event.preventDefault()
- this._navigateChip(chips, currentIndex, -1, event.shiftKey)
- break
- }
-
- case 'ArrowRight': {
- event.preventDefault()
- this._navigateChip(chips, currentIndex, 1, event.shiftKey)
- break
- }
-
- case 'Home': {
- event.preventDefault()
- this._navigateToEdge(chips, 0, event.shiftKey)
- break
- }
-
- case 'End': {
- event.preventDefault()
- this.clearSelection()
- this._input?.focus()
- break
- }
-
- case 'a': {
- this._handleSelectAll(event, chips)
- break
- }
-
- case 'Escape': {
- event.preventDefault()
- this.clearSelection()
- this._input?.focus()
- break
- }
-
- // No default
- }
- }
-
- protected _handleChipDelete(currentIndex: number, chips: HTMLElement[]): void {
- if (this._selectedChips.size === 0) {
- return
- }
-
- const nextIndex = Math.min(currentIndex, chips.length - this._selectedChips.size - 1)
- this.removeSelected()
-
- const remainingChips = this._getChipElements()
- if (remainingChips.length > 0) {
- const focusIndex = Math.max(0, Math.min(nextIndex, remainingChips.length - 1))
- remainingChips[focusIndex].focus()
- this.selectChip(remainingChips[focusIndex])
- } else {
- this._input?.focus()
- }
- }
-
- protected _navigateChip(chips: HTMLElement[], currentIndex: number, direction: number, shiftKey: boolean): void {
- const targetIndex = currentIndex + direction
-
- if (direction < 0 && targetIndex >= 0) {
- const targetChip = chips[targetIndex]
- this.selectChip(targetChip, shiftKey ? { addToSelection: true, rangeSelect: true } : {})
- targetChip.focus()
- } else if (direction > 0 && targetIndex < chips.length) {
- const targetChip = chips[targetIndex]
- this.selectChip(targetChip, shiftKey ? { addToSelection: true, rangeSelect: true } : {})
- targetChip.focus()
- } else if (direction > 0) {
- this.clearSelection()
- this._input?.focus()
- }
- }
-
- protected _navigateToEdge(chips: HTMLElement[], targetIndex: number, shiftKey: boolean): void {
- if (chips.length === 0) {
- return
- }
-
- const targetChip = chips[targetIndex]
- this.selectChip(targetChip, shiftKey ? { rangeSelect: true } : {})
- targetChip.focus()
- }
-
- protected _handleSelectAll(event: BootstrapEvent, chips: HTMLElement[]): void {
- if (!(event.metaKey || event.ctrlKey)) {
- return
- }
-
- event.preventDefault()
- for (const c of chips) {
- this._selectedChips.add(c)
- c.classList.add(CLASS_NAME_ACTIVE)
- }
-
- EventHandler.trigger(this._element, EVENT_SELECT, {
- selected: this.getSelectedValues()
- })
- }
-
- protected _handleInput(event: BootstrapEvent): void {
- const { value } = event.target as HTMLInputElement
- const { separator } = this._config
-
- if (separator && value.includes(separator)) {
- const parts = value.split(separator)
- for (const part of parts.slice(0, -1)) {
- this.add(part.trim())
- }
-
- this._input.value = parts.at(-1)!
- }
- }
-
- protected _handlePaste(event: BootstrapEvent): void {
- const { separator } = this._config
- if (!separator) {
- return
- }
-
- const pastedData = (event.clipboardData || (window as any).clipboardData).getData('text')
- if (pastedData.includes(separator)) {
- event.preventDefault()
-
- const parts = pastedData.split(separator)
- for (const part of parts) {
- this.add(part.trim())
- }
- }
- }
-
- protected _createChipFromInput(): void {
- const value = this._input.value.trim()
- if (value) {
- this.add(value)
- this._input.value = ''
- }
- }
-}
-
-/**
- * Data API implementation
- */
-
-onDocumentReady(`DOMContentLoaded${EVENT_KEY}${DATA_API_KEY}`, () => {
- for (const element of SelectorEngine.find(SELECTOR_DATA_CHIPS)) {
- Chips.getOrCreateInstance(element)
- }
-})
-
-export default Chips
-export type { ChipsConfig }
diff --git a/js/src/combobox.ts b/js/src/combobox.ts
index 40abefdddc..04f6f9a379 100644
--- a/js/src/combobox.ts
+++ b/js/src/combobox.ts
@@ -5,14 +5,16 @@
* --------------------------------------------------------------------------
*/
+import type { MiddlewareState } from '@floating-ui/dom'
import BaseComponent from './base-component.js'
import EventHandler, { type BootstrapEvent } from './dom/event-handler.js'
import SelectorEngine from './dom/selector-engine.js'
import Menu from './menu.js'
import { onDocumentReady } from './util/component-functions.js'
+import type { ComponentConfig } from './util/config.js'
import type { FloatingOffsetOption } from './util/floating-ui.js'
import {
- getNextActiveElement, isDisabled, isVisible, setAriaAttribute
+ getElement, getNextActiveElement, getUID, isDisabled, isVisible, setAriaAttribute
} from './util/index.js'
/**
@@ -34,16 +36,14 @@ const ENTER_KEY = 'Enter'
const SPACE_KEY = ' '
const EVENT_CHANGE = `change${EVENT_KEY}`
-const EVENT_SHOW = `show${EVENT_KEY}`
-const EVENT_SHOWN = `shown${EVENT_KEY}`
-const EVENT_HIDE = `hide${EVENT_KEY}`
-const EVENT_HIDDEN = `hidden${EVENT_KEY}`
const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}`
const CLASS_NAME_SHOW = 'show'
const CLASS_NAME_SELECTED = 'selected'
const CLASS_NAME_PLACEHOLDER = 'combobox-placeholder'
+const DISMISS_ICON = ''
+
const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="combobox"]'
const SELECTOR_MENU = '.menu'
const SELECTOR_MENU_ITEM = '.menu-item[data-bs-value]'
@@ -52,8 +52,19 @@ const SELECTOR_VALUE = '.combobox-value'
const SELECTOR_SEARCH_INPUT = '.combobox-search-input'
const SELECTOR_NO_RESULTS = '.combobox-no-results'
+class ComboboxMenu extends Menu {
+ override show(focus?: () => void): Promise {
+ return this._show(focus)
+ }
+}
+
type ComboboxConfig = {
+ allowCustom: boolean
+ createOnBlur: boolean
+ maxItems: number | null
+ separator: string | null
boundary: string | Element
+ input: string | HTMLInputElement | null
multiple: boolean
name: string | null
offset: FloatingOffsetOption
@@ -64,7 +75,12 @@ type ComboboxConfig = {
}
const Default: ComboboxConfig = {
+ allowCustom: false,
+ createOnBlur: false,
+ maxItems: null,
+ separator: null,
boundary: 'clippingParents',
+ input: null,
multiple: false,
name: null,
offset: [0, 2],
@@ -75,7 +91,12 @@ const Default: ComboboxConfig = {
}
const DefaultType = {
+ allowCustom: 'boolean',
+ createOnBlur: 'boolean',
+ maxItems: '(number|null)',
+ separator: '(string|null)',
boundary: '(string|element)',
+ input: '(null|element)',
multiple: 'boolean',
name: '(string|null)',
offset: '(array|string|function)',
@@ -97,22 +118,108 @@ class Combobox extends BaseComponent {
protected declare _searchInput: HTMLInputElement | null
protected declare _noResults: HTMLElement | null
protected declare _hiddenInput: HTMLInputElement | null
- protected declare _menuInstance: Menu | null
+ protected declare _menuInstance: ComboboxMenu | null
+ protected declare _ownsInput: boolean
+ protected declare _inputDisabled: boolean
+ protected declare _extraInputs: HTMLInputElement[]
+ protected declare _initialSelection: HTMLElement[]
+ protected declare _form: HTMLFormElement | null
+ protected declare _formObserver: MutationObserver
+ protected declare _submitHandler: () => void
+ protected declare _resetTimeouts: Set
+ protected declare _resetHandler: (event: BootstrapEvent) => void
+ protected declare _menuEventHandlers: Map void>
+ protected declare _changeId: number
+ protected declare _editor: HTMLInputElement | null
+ protected declare _activeItem: HTMLElement | null
+ protected declare _chips: Map
+ protected declare _selectedChips: Set
+ protected declare _anchorChip: HTMLElement | null
+ protected declare _focusingChip: boolean
+ protected declare _composing: boolean
+ protected declare _query: string | null
+ protected declare _ownsMenu: boolean
+ protected declare _status: HTMLElement | null
+ protected declare _menuMinWidth: string
+ protected declare _attributes: Map>
constructor(element?: string | Element | null, config?: Partial | null) {
super(element, config)
- this._toggle = this._element
- this._menu = SelectorEngine.next(this._toggle, SELECTOR_MENU)[0] as HTMLElement
+ this._editor = this._element.matches('input') ?
+ this._element as HTMLInputElement :
+ SelectorEngine.findOne('.combobox-input, .form-ghost', this._element)
+ if (this._editor === this._element && this._config.multiple) {
+ throw new TypeError('COMBOBOX: Multiple selection requires a wrapping element.')
+ }
+
+ this._toggle = this._editor ?? this._element
+ const field = this._editor && !this._element.matches('input') ? this._element : this._toggle
+ this._menu = SelectorEngine.next(field, SELECTOR_MENU)[0] as HTMLElement
+ this._ownsMenu = !this._menu && Boolean(this._editor)
+ if (this._ownsMenu) {
+ this._menu = document.createElement('div')
+ this._menu.className = 'menu'
+ field.after(this._menu)
+ }
+
+ this._menuMinWidth = this._menu.style.minWidth
this._valueDisplay = SelectorEngine.findOne(SELECTOR_VALUE, this._toggle)!
- this._searchInput = SelectorEngine.findOne(SELECTOR_SEARCH_INPUT, this._menu)
+ this._searchInput = this._editor ?? SelectorEngine.findOne(SELECTOR_SEARCH_INPUT, this._menu)
this._noResults = SelectorEngine.findOne(SELECTOR_NO_RESULTS, this._menu)
+ this._activeItem = null
+ this._chips = new Map()
+ this._selectedChips = new Set()
+ this._anchorChip = null
+ this._focusingChip = false
+ this._composing = false
+ this._query = null
+ this._status = null
+ this._attributes = new Map()
+ if (this._editor) {
+ this._setupEditor()
+ }
+
this._hiddenInput = null
this._menuInstance = null
+ this._ownsInput = false
+ this._inputDisabled = false
+ this._extraInputs = []
+ this._initialSelection = this._getSelectedItems()
+ this._form = null
+ this._menuEventHandlers = new Map()
+ this._changeId = 0
+ this._formObserver = new MutationObserver(records => {
+ this._readInputDisabled(records)
+ this.update()
+ })
+ this._submitHandler = () => this.update()
+ this._resetTimeouts = new Set()
+ this._resetHandler = event => {
+ // Trusted reset clicks can run microtasks before the native default action.
+ const timeout = window.setTimeout(() => {
+ this._resetTimeouts.delete(timeout)
+ if (!this._element || event.defaultPrevented || event.target !== this._form) {
+ return
+ }
+
+ const selected = new Set(this._initialSelection)
+ for (const item of SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu)) {
+ item.classList.toggle(CLASS_NAME_SELECTED, selected.has(item))
+ setAriaAttribute(item, 'aria-selected', selected.has(item))
+ }
+
+ this._query = null
+ this._selectedChips.clear()
+ this._anchorChip = null
+ this.update()
+ })
+ this._resetTimeouts.add(timeout)
+ }
this._createHiddenInput()
this._createMenuInstance()
- this._syncInitialSelection()
+ this.update()
this._addEventListeners()
}
@@ -134,52 +241,79 @@ class Combobox extends BaseComponent {
return this._isShown() ? this.hide() : this.show()
}
- async show(): Promise {
- if (isDisabled(this._toggle) || this._isShown()) {
- return
- }
-
- const showEvent = EventHandler.trigger(this._toggle, EVENT_SHOW)
- if (showEvent.defaultPrevented) {
- return
- }
-
- this._menuInstance!.show()
-
- if (this._searchInput) {
- this._searchInput.value = ''
- this._filterItems('')
- requestAnimationFrame(() => this._searchInput!.focus())
- }
-
- EventHandler.trigger(this._toggle, EVENT_SHOWN)
+ show(): Promise {
+ return this._showMenu()
}
async hide(): Promise {
- if (!this._isShown()) {
- return
- }
+ await this._menuInstance!.hide()
+ }
- const hideEvent = EventHandler.trigger(this._toggle, EVENT_HIDE)
- if (hideEvent.defaultPrevented) {
- return
+ update(): void {
+ this._changeId++
+ this._readInputDisabled(this._formObserver.takeRecords())
+ this._syncOptionRoles()
+ this._updateToggleText()
+ this._updateHiddenInput()
+ this._observeFormState()
+ if (this._editor && this._activeItem && !this._getVisibleItems().includes(this._activeItem)) {
+ this._setActiveItem(null)
}
-
- this._menuInstance!.hide()
- EventHandler.trigger(this._toggle, EVENT_HIDDEN)
}
override dispose(): void {
+ this._resetTimeouts.forEach(timeout => clearTimeout(timeout))
+ this._readInputDisabled(this._formObserver.takeRecords())
+ this._formObserver.disconnect()
+ EventHandler.off(this._form, `reset${EVENT_KEY}`, this._resetHandler)
+ EventHandler.off(this._form, `submit${EVENT_KEY}`, this._submitHandler)
+
+ for (const [event, handler] of this._menuEventHandlers) {
+ EventHandler.off(this._toggle, event, handler)
+ }
+
+ this._removeExtraInputs()
+ if (this._hiddenInput && !this._ownsInput) {
+ this._hiddenInput.disabled = this._inputDisabled
+ }
+
if (this._menuInstance) {
this._menuInstance.dispose()
this._menuInstance = null
}
- if (this._hiddenInput) {
+ if (this._hiddenInput && this._ownsInput) {
this._hiddenInput.remove()
this._hiddenInput = null
}
+ for (const chip of this._chips.values()) {
+ chip.remove()
+ }
+
+ if (this._editor) {
+ this._editor.classList.remove(CLASS_NAME_SHOW)
+ this._element.classList.remove(CLASS_NAME_SHOW)
+ this._menu.classList.remove(CLASS_NAME_SHOW)
+ this._activeItem?.classList.remove('active')
+ }
+
+ this._status?.remove()
+ this._menu.style.minWidth = this._menuMinWidth
+ for (const [element, attributes] of this._attributes) {
+ for (const [name, value] of attributes) {
+ if (value === null) {
+ element.removeAttribute(name)
+ } else {
+ element.setAttribute(name, value)
+ }
+ }
+ }
+
+ if (this._ownsMenu) {
+ this._menu.remove()
+ }
+
EventHandler.off(this._menu, EVENT_KEY)
EventHandler.off(this._toggle, EVENT_KEY)
EventHandler.off(this._searchInput, EVENT_KEY)
@@ -187,45 +321,820 @@ class Combobox extends BaseComponent {
super.dispose()
}
+ getValues(): string[] {
+ return this._getSelectedItems().map(item => item.dataset.bsValue ?? '')
+ }
+
+ add(value: string): HTMLElement | null {
+ if (this._isDisabled() || (this._config.multiple && this._config.maxItems !== null && this.getValues().length >= this._config.maxItems)) {
+ return null
+ }
+
+ let item = SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu).find(option => option.dataset.bsValue === value)
+ if (!item && this._config.allowCustom && value.trim()) {
+ item = document.createElement('button')
+ item.setAttribute('type', 'button')
+ item.className = 'menu-item'
+ item.dataset.bsValue = value
+ item.textContent = value
+ this._menu.append(item)
+ }
+
+ if (!item || item.classList.contains(CLASS_NAME_SELECTED) || isDisabled(item)) {
+ return null
+ }
+
+ this._selectItem(item)
+ return this._element && item.classList.contains(CLASS_NAME_SELECTED) ? this._chips.get(item) ?? item : null
+ }
+
+ remove(value: string | HTMLElement): boolean {
+ const item = this._getSelectedItems().find(option => typeof value === 'string' ? option.dataset.bsValue === value : option === value || this._chips.get(option) === value)
+ if (!item || isDisabled(item) || this._isDisabled()) {
+ return false
+ }
+
+ return this._removeItems([item])
+ }
+
+ clear(): void {
+ this._clearSelection(null)
+ }
+
+ protected _clearSelection(query: string | null): void {
+ this._removeItems(this._getSelectedItems(), query)
+ }
+
+ focus(): void {
+ this._toggle?.focus()
+ }
+
+ getSelectedValues(): string[] {
+ return this._getSelectedItems()
+ .filter(item => this._selectedChips.has(this._chips.get(item)!))
+ .map(item => item.dataset.bsValue ?? '')
+ }
+
+ selectChip(chip: HTMLElement, options: { addToSelection?: boolean, rangeSelect?: boolean } = {}): void {
+ const chips = this._getChipElements()
+ if (this._isDisabled() || !chips.includes(chip)) {
+ return
+ }
+
+ const previous = new Set(this._selectedChips)
+ const { addToSelection = false, rangeSelect = false } = options
+ if (rangeSelect && this._anchorChip && chips.includes(this._anchorChip)) {
+ const anchor = chips.indexOf(this._anchorChip)
+ const target = chips.indexOf(chip)
+ if (!addToSelection) {
+ this._selectedChips.clear()
+ }
+
+ for (let index = Math.min(anchor, target); index <= Math.max(anchor, target); index++) {
+ this._selectedChips.add(chips[index])
+ }
+ } else if (addToSelection) {
+ if (this._selectedChips.has(chip)) {
+ this._selectedChips.delete(chip)
+ } else {
+ this._selectedChips.add(chip)
+ this._anchorChip = chip
+ }
+ } else {
+ this._selectedChips = new Set([chip])
+ this._anchorChip = chip
+ }
+
+ if (previous.size !== this._selectedChips.size || [...previous].some(element => !this._selectedChips.has(element))) {
+ this._notifyChipSelection()
+ }
+ }
+
+ clearSelection(): void {
+ this._anchorChip = null
+ if (!this._selectedChips.size) {
+ return
+ }
+
+ this._selectedChips.clear()
+ this._notifyChipSelection()
+ }
+
+ removeSelected(): boolean {
+ const chips = this._getChipElements()
+ const active = (document.activeElement as HTMLElement | null)?.closest('.chip')
+ const index = Math.max(0, chips.indexOf(active!))
+ const items = this._getSelectedItems().filter(item => this._selectedChips.has(this._chips.get(item)!))
+ const changed = this._removeItems(items)
+ if (changed && this._element) {
+ const remaining = this._getChipElements()
+ const target = remaining[Math.min(index, remaining.length - 1)]
+ if (target) {
+ this._focusChip(target)
+ } else {
+ this._editor!.focus()
+ }
+ }
+
+ return changed
+ }
+
+ protected _getChipElements(): HTMLElement[] {
+ return this._getSelectedItems()
+ .filter(item => !isDisabled(item))
+ .map(item => this._chips.get(item))
+ .filter((chip): chip is HTMLElement => Boolean(chip))
+ }
+
+ protected _syncChipSelection(): void {
+ for (const chip of this._chips.values()) {
+ const selected = this._selectedChips.has(chip)
+ chip.classList.toggle('active', selected)
+ if (selected) {
+ chip.setAttribute('aria-description', 'Selected for removal')
+ } else {
+ chip.removeAttribute('aria-description')
+ }
+ }
+ }
+
+ protected _notifyChipSelection(): void {
+ this._syncChipSelection()
+ const items = this._getSelectedItems().filter(item => this._selectedChips.has(this._chips.get(item)!))
+ const selected = items.map(item => item.dataset.bsValue ?? '')
+ if (this._status) {
+ this._status.textContent = selected.length ? `${selected.length} chip${selected.length === 1 ? '' : 's'} selected for removal` : 'Chip selection cleared'
+ }
+
+ EventHandler.trigger(this._element, `select${EVENT_KEY}`, { selected, items })
+ }
+
+ protected _focusChip(chip: HTMLElement, options: { addToSelection?: boolean, rangeSelect?: boolean } = {}): void {
+ this.selectChip(chip, options)
+ if (!this._element) {
+ return
+ }
+
+ this.hide()
+ if (this._element) {
+ this._focusSelectedChip(chip)
+ }
+ }
+
+ protected _focusSelectedChip(chip: HTMLElement): void {
+ this._focusingChip = true
+ try {
+ chip.focus()
+ } finally {
+ if (this._element) {
+ this._focusingChip = false
+ }
+ }
+ }
+
+ protected _selectAllChips(): void {
+ const chips = this._getChipElements()
+ if (!chips.length) {
+ return
+ }
+
+ this._selectedChips = new Set(chips)
+ this._anchorChip ??= chips[0]
+ this._notifyChipSelection()
+ }
+
+ protected _removeItems(items: HTMLElement[], query: string | null = null): boolean {
+ if (this._isDisabled() || !items.length) {
+ return false
+ }
+
+ const allowed: HTMLElement[] = []
+ const changeId = this._changeId
+ for (const item of items) {
+ if (isDisabled(item)) {
+ continue
+ }
+
+ const event = EventHandler.trigger(this._element, `remove${EVENT_KEY}`, { value: item.dataset.bsValue, item })
+ if (!this._element || changeId !== this._changeId) {
+ return false
+ }
+
+ if (!event.defaultPrevented) {
+ allowed.push(item)
+ }
+ }
+
+ for (const item of allowed) {
+ item.classList.remove(CLASS_NAME_SELECTED)
+ setAriaAttribute(item, 'aria-selected', false)
+ }
+
+ if (allowed.length) {
+ this._selectionChanged(allowed.length === 1 ? allowed[0] : null, query)
+ }
+
+ return allowed.length > 0
+ }
+
// Private
+ protected _isDisabled(): boolean {
+ return isDisabled(this._element) || isDisabled(this._toggle) || this._toggle.matches(':disabled')
+ }
+
+ protected _setAttribute(element: Element, name: string, value: string): void {
+ if (!this._attributes.has(element)) {
+ this._attributes.set(element, new Map())
+ }
+
+ const attributes = this._attributes.get(element)!
+ if (!attributes.has(name)) {
+ attributes.set(name, element.getAttribute(name))
+ }
+
+ element.setAttribute(name, value)
+ }
+
+ protected _syncOptionRoles(): void {
+ if (!this._menu.id) {
+ this._setAttribute(this._menu, 'id', getUID('combobox-'))
+ }
+
+ this._setAttribute(this._toggle, 'aria-controls', this._menu.id)
+ this._setAttribute(this._toggle, 'aria-haspopup', 'listbox')
+ this._setAttribute(this._menu, 'role', 'listbox')
+ if (this._config.multiple) {
+ this._setAttribute(this._menu, 'aria-multiselectable', 'true')
+ }
+
+ for (const item of SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu)) {
+ this._setAttribute(item, 'role', 'option')
+ this._setAttribute(item, 'aria-selected', String(item.classList.contains(CLASS_NAME_SELECTED)))
+ }
+ }
+
+ protected _setupEditor(): void {
+ const editor = this._editor!
+ if (this._config.placeholder && !editor.placeholder) {
+ this._setAttribute(editor, 'placeholder', this._config.placeholder)
+ }
+
+ if (!this._menu.id) {
+ this._setAttribute(this._menu, 'id', getUID('combobox-'))
+ }
+
+ this._setAttribute(editor, 'role', 'combobox')
+ this._setAttribute(editor, 'aria-autocomplete', 'list')
+ this._setAttribute(editor, 'aria-expanded', 'false')
+ this._setAttribute(editor, 'aria-controls', this._menu.id)
+ this._setAttribute(editor, 'autocomplete', 'off')
+ this._setAttribute(editor, 'aria-activedescendant', '')
+ editor.removeAttribute('aria-activedescendant')
+ this._setAttribute(this._menu, 'role', 'listbox')
+ if (this._config.multiple) {
+ this._setAttribute(this._menu, 'aria-multiselectable', 'true')
+ }
+
+ this._status = document.createElement('span')
+ this._status.className = 'visually-hidden'
+ this._status.setAttribute('role', 'status')
+ this._menu.after(this._status)
+ }
+
+ protected _getItemLabel(item: HTMLElement): string {
+ const label = SelectorEngine.findOne('.menu-item-content > span:first-child', item)
+ return label?.textContent ?? item.textContent!.trim()
+ }
+
+ protected _renderEditor(): void {
+ const editor = this._editor!
+ const selected = this._getSelectedItems()
+ const selectedSet = new Set(selected)
+ for (const [item, chip] of this._chips) {
+ if (!selectedSet.has(item)) {
+ chip.remove()
+ this._chips.delete(item)
+ this._selectedChips.delete(chip)
+ if (this._anchorChip === chip) {
+ this._anchorChip = null
+ }
+ }
+ }
+
+ for (const item of SelectorEngine.find(SELECTOR_MENU_ITEM, this._menu)) {
+ if (!item.id) {
+ this._setAttribute(item, 'id', getUID('combobox-option-'))
+ }
+
+ this._setAttribute(item, 'tabindex', '-1')
+ }
+
+ if (!this._config.multiple) {
+ const value = this._query ?? (selected.length ? this._getItemLabel(selected[0]) : '')
+ if (editor.value !== value) {
+ editor.value = value
+ }
+
+ return
+ }
+
+ const inputBeforeEditor = this._hiddenInput?.parentElement === editor.parentElement && this._hiddenInput.compareDocumentPosition(editor) === Node.DOCUMENT_POSITION_FOLLOWING
+ let next: Element = inputBeforeEditor ? this._hiddenInput! : editor
+ for (let index = selected.length - 1; index >= 0; index--) {
+ const item = selected[index]
+ let chip = this._chips.get(item)
+ const label = this._getItemLabel(item)
+ if (!chip) {
+ chip = document.createElement('span')
+ chip.className = 'chip'
+ chip.tabIndex = -1
+ const text = document.createElement('span')
+ const button = document.createElement('button')
+ button.type = 'button'
+ button.className = 'chip-dismiss'
+ button.innerHTML = DISMISS_ICON
+ chip.append(text, button)
+ this._chips.set(item, chip)
+ }
+
+ this._updateChipState(item, chip, label)
+ if (chip.nextElementSibling !== next) {
+ next.before(chip)
+ }
+
+ next = chip
+ }
+
+ this._syncChipSelection()
+ const value = this._query ?? ''
+ if (editor.value !== value) {
+ editor.value = value
+ }
+
+ this._menuInstance?.update()
+ }
+
+ protected _updateChipState(item: HTMLElement, chip: HTMLElement, label: string): void {
+ chip.firstElementChild!.textContent = label
+ const button = chip.lastElementChild as HTMLButtonElement
+ button.setAttribute('aria-label', `Remove ${label}`)
+ button.disabled = this._isDisabled() || isDisabled(item)
+ chip.setAttribute('role', 'group')
+ chip.setAttribute('aria-label', label)
+ chip.classList.toggle('disabled', button.disabled)
+ if (button.disabled) {
+ chip.setAttribute('aria-disabled', 'true')
+ this._selectedChips.delete(chip)
+ if (this._anchorChip === chip) {
+ this._anchorChip = null
+ }
+ } else {
+ chip.removeAttribute('aria-disabled')
+ }
+ }
+
+ protected _setActiveItem(item: HTMLElement | null): void {
+ this._activeItem?.classList.remove('active')
+ this._activeItem = item
+ if (!item) {
+ this._editor!.removeAttribute('aria-activedescendant')
+ return
+ }
+
+ item.classList.add('active')
+ this._editor!.setAttribute('aria-activedescendant', item.id)
+ item.scrollIntoView({ block: 'nearest' })
+ }
+
+ protected _addEditorListeners(): void {
+ const editor = this._editor!
+ EventHandler.on(this._menu, `mousedown${EVENT_KEY}`, SELECTOR_MENU_ITEM, event => event.preventDefault())
+ EventHandler.on(editor, `input${EVENT_KEY}`, event => {
+ if (this._composing || event.isComposing) {
+ this._query = editor.value
+ return
+ }
+
+ if (this._isDisabled()) {
+ return
+ }
+
+ this._handleEditorInput()
+ })
+ EventHandler.on(editor, `compositionstart${EVENT_KEY}`, () => {
+ this._composing = true
+ })
+ EventHandler.on(editor, `compositionend${EVENT_KEY}`, () => {
+ this._composing = false
+ if (this._element && !this._isDisabled()) {
+ this._handleEditorInput(document.activeElement === editor)
+ }
+ })
+ EventHandler.on(editor, `paste${EVENT_KEY}`, event => {
+ const { separator, allowCustom } = this._config
+ const text = event.clipboardData?.getData('text') ?? ''
+ if (!allowCustom || !separator || !text.includes(separator) || this._isDisabled()) {
+ return
+ }
+
+ event.preventDefault()
+ for (const value of text.split(separator)) {
+ this.add(value.trim())
+ if (!this._element) {
+ return
+ }
+ }
+ })
+ EventHandler.on(editor, `blur${EVENT_KEY}`, event => {
+ if (!this._composing && this._config.allowCustom && this._config.createOnBlur && !(event.relatedTarget as Element | null)?.closest('.chip, .menu')) {
+ this.add(editor.value.trim())
+ }
+ })
+ EventHandler.on(editor, `focus${EVENT_KEY}`, () => this.clearSelection())
+ EventHandler.on(this._element, `mousedown${EVENT_KEY}`, '.chip', event => {
+ // The click handler owns modifier selection and focus on the chip body.
+ if (!(event.target as Element).closest('.chip-dismiss')) {
+ event.preventDefault()
+ }
+ })
+ EventHandler.on(this._element, `focusin${EVENT_KEY}`, '.chip', event => {
+ if (this._focusingChip || this._isDisabled()) {
+ return
+ }
+
+ const chip = (event.target as Element).closest('.chip')!
+ if (!this._selectedChips.has(chip)) {
+ this.selectChip(chip)
+ }
+
+ if (this._element) {
+ this.hide()
+ }
+ })
+ EventHandler.on(this._element, `click${EVENT_KEY}`, '.chip', event => {
+ if ((event.target as Element).closest('.chip-dismiss') || this._isDisabled()) {
+ return
+ }
+
+ event.preventDefault()
+ event.stopPropagation()
+ const chip = (event.target as Element).closest('.chip')!
+ this._focusChip(chip, { addToSelection: event.metaKey || event.ctrlKey, rangeSelect: event.shiftKey })
+ })
+ EventHandler.on(this._element, `keydown${EVENT_KEY}`, '.chip', event => this._handleChipKeydown(event))
+ EventHandler.on(this._element, `click${EVENT_KEY}`, '.chip-dismiss', event => {
+ event.preventDefault()
+ event.stopPropagation()
+ const chip = (event.target as Element).closest('.chip')!
+ this.remove(chip)
+ if (this._element) {
+ editor.focus()
+ }
+ })
+ }
+
+ protected _handleEditorInput(openMenu = true): void {
+ const editor = this._editor!
+ let query = editor.value
+ if (this._config.allowCustom && this._config.separator && query.includes(this._config.separator)) {
+ const parts = query.split(this._config.separator)
+ query = parts.pop()!
+ for (const part of parts) {
+ this.add(part.trim())
+ if (!this._element) {
+ return
+ }
+ }
+ }
+
+ // A changed visible label must not submit an old single-selection value.
+ if (!this._config.multiple && this._getSelectedItems().length) {
+ this._clearSelection(query)
+ if (!this._element) {
+ return
+ }
+
+ if (this._getSelectedItems().length) {
+ this._query = null
+ this._renderEditor()
+ return
+ }
+ }
+
+ this._query = query
+ if (editor.value !== query) {
+ editor.value = query
+ }
+
+ this._filterItems(query)
+ this._setActiveItem(null)
+ if (openMenu && this._getVisibleItems().length) {
+ this.show()
+ } else {
+ this.hide()
+ }
+ }
+
+ protected _handleEditorKeydown(event: BootstrapEvent): void {
+ if (this._composing || event.isComposing || event.keyCode === 229 || this._isDisabled()) {
+ return
+ }
+
+ const editor = this._editor!
+ if ([ARROW_DOWN_KEY, ARROW_UP_KEY].includes(event.key)) {
+ event.preventDefault()
+ const items = this._getVisibleItems()
+ if (items.length) {
+ const item = getNextActiveElement(items, this._activeItem!, event.key === ARROW_DOWN_KEY, true)
+ this.show()
+ if (this._element) {
+ this._setActiveItem(item)
+ }
+ }
+
+ return
+ }
+
+ if (event.key === ENTER_KEY) {
+ if (this._activeItem && this._isShown()) {
+ event.preventDefault()
+ this._selectItem(this._activeItem)
+ } else if (this._config.allowCustom && editor.value.trim()) {
+ event.preventDefault()
+ this.add(editor.value.trim())
+ }
+
+ return
+ }
+
+ if (event.key === ESCAPE_KEY || event.key === TAB_KEY) {
+ if (event.key === ESCAPE_KEY && this._isShown()) {
+ event.preventDefault()
+ }
+
+ this.hide()
+ if (this._element) {
+ this._setActiveItem(null)
+ }
+
+ return
+ }
+
+ this._handleEditorChipFocus(event)
+ }
+
+ protected _handleEditorChipFocus(event: BootstrapEvent): void {
+ const editor = this._editor!
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a' && !editor.value) {
+ const chips = this._getChipElements()
+ if (chips.length) {
+ event.preventDefault()
+ this._selectAllChips()
+ if (this._element) {
+ this.hide()
+ if (this._element) {
+ this._focusSelectedChip(chips.at(-1)!)
+ }
+ }
+ }
+
+ return
+ }
+
+ if (event.metaKey || event.ctrlKey || event.altKey) {
+ return
+ }
+
+ const rtl = getComputedStyle(editor).direction === 'rtl'
+ const previousKey = rtl ? 'ArrowRight' : 'ArrowLeft'
+ const backwardDelete = ['Backspace', 'Delete'].includes(event.key) && !editor.value
+ const atStart = event.key === previousKey && editor.selectionStart === 0 && editor.selectionEnd === 0
+ if (backwardDelete || atStart) {
+ const chip = this._getChipElements().at(-1)
+ if (chip) {
+ event.preventDefault()
+ this._focusChip(chip, { addToSelection: event.shiftKey })
+ }
+ }
+ }
+
+ protected _handleChipKeydown(event: BootstrapEvent): void {
+ if (this._composing || event.isComposing || event.keyCode === 229 || this._isDisabled()) {
+ return
+ }
+
+ const chip = (event.target as Element).closest('.chip')!
+ const chips = this._getChipElements()
+ const index = chips.indexOf(chip)
+ if (index === -1) {
+ return
+ }
+
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a') {
+ event.preventDefault()
+ this._selectAllChips()
+ return
+ }
+
+ if (['Backspace', 'Delete'].includes(event.key)) {
+ event.preventDefault()
+ this._deleteChipSelection(chip)
+
+ return
+ }
+
+ const rtl = getComputedStyle(this._editor!).direction === 'rtl'
+ if (['ArrowLeft', 'ArrowRight'].includes(event.key)) {
+ event.preventDefault()
+ const next = index + ((event.key === 'ArrowRight') === rtl ? -1 : 1)
+ if (next >= chips.length) {
+ this.clearSelection()
+ if (this._element) {
+ this._editor!.focus()
+ }
+ } else {
+ this._focusChip(chips[Math.max(0, next)], { rangeSelect: event.shiftKey })
+ }
+ } else if (event.key === HOME_KEY || (event.key === END_KEY && event.shiftKey)) {
+ event.preventDefault()
+ const target = event.key === HOME_KEY ? chips[0] : chips.at(-1)!
+ this._focusChip(target, { rangeSelect: event.shiftKey })
+ } else if ([END_KEY, ESCAPE_KEY].includes(event.key)) {
+ event.preventDefault()
+ this.clearSelection()
+ if (this._element) {
+ this._editor!.focus()
+ }
+ }
+ }
+
+ protected _deleteChipSelection(chip: HTMLElement): void {
+ if (!this._selectedChips.has(chip)) {
+ this.selectChip(chip)
+ }
+
+ if (this._element) {
+ this.removeSelected()
+ }
+ }
+
protected _isShown(): boolean {
return this._menu.classList.contains(CLASS_NAME_SHOW)
}
+ protected override _configAfterMerge(config: ComponentConfig): ComponentConfig {
+ if (config.maxItems !== null && (!Number.isSafeInteger(config.maxItems) || config.maxItems < 1)) {
+ throw new TypeError('COMBOBOX: Option "maxItems" must be a positive integer or null.')
+ }
+
+ if (config.input !== null) {
+ const input = getElement(config.input)
+ if (!(input instanceof HTMLInputElement) || input.type !== 'hidden') {
+ throw new TypeError('COMBOBOX: Option "input" must reference a hidden input.')
+ }
+
+ config.input = input
+ }
+
+ return config
+ }
+
protected _createHiddenInput(): void {
- const { name } = this._config
- if (!name) {
+ if (this._config.input) {
+ this._hiddenInput = this._config.input as HTMLInputElement
+ this._inputDisabled = this._hiddenInput.disabled
+ return
+ }
+
+ if (!this._config.name) {
return
}
this._hiddenInput = document.createElement('input')
this._hiddenInput.type = 'hidden'
- this._hiddenInput.name = name
- this._hiddenInput.value = ''
- this._toggle.parentNode!.insertBefore(this._hiddenInput, this._toggle)
+ this._hiddenInput.name = this._config.name
+ const anchor = this._editor ? this._element : this._toggle
+ anchor.before(this._hiddenInput)
+ this._ownsInput = true
}
- protected _createMenuInstance(): void {
- this._menuInstance = new Menu(this._toggle, {
- menu: this._menu,
- autoClose: this._config.multiple ? 'outside' : true,
- boundary: this._config.boundary,
- offset: this._config.offset,
- placement: this._config.placement
- })
+ protected _removeExtraInputs(): void {
+ for (const input of this._extraInputs) {
+ input.remove()
+ }
+
+ this._extraInputs = []
}
- protected _syncInitialSelection(): void {
- const selectedItems = this._getSelectedItems()
- if (selectedItems.length > 0) {
- this._updateToggleText()
- this._updateHiddenInput()
- } else {
- this._showPlaceholder()
+ protected _readInputDisabled(records: MutationRecord[]): void {
+ if (!this._ownsInput && records.some(record => record.target === this._hiddenInput && record.attributeName === 'disabled')) {
+ this._inputDisabled = this._hiddenInput!.disabled
}
}
+ protected _observeFormState(): void {
+ this._formObserver.disconnect()
+ if (this._element !== this._toggle) {
+ this._formObserver.observe(this._element, { attributes: true, attributeFilter: ['class'] })
+ }
+
+ this._formObserver.observe(this._toggle, { attributes: true, attributeFilter: ['disabled', 'class', 'form'] })
+ if (this._hiddenInput) {
+ this._formObserver.observe(this._hiddenInput, { attributes: true, attributeFilter: ['disabled', 'name', 'form'] })
+ }
+
+ // Watch only relevant fieldset ancestors, not every mutation in the document.
+ const fieldsets = new Set()
+ for (const element of [this._toggle, this._hiddenInput]) {
+ for (let parent = element?.parentElement; parent; parent = parent.parentElement) {
+ if (parent.matches('fieldset')) {
+ fieldsets.add(parent)
+ }
+ }
+ }
+
+ for (const fieldset of fieldsets) {
+ this._formObserver.observe(fieldset, { attributes: true, attributeFilter: ['disabled'] })
+ }
+
+ const form = this._hiddenInput ?
+ this._hiddenInput.form :
+ (this._toggle instanceof HTMLInputElement || this._toggle instanceof HTMLButtonElement ?
+ this._toggle.form :
+ this._toggle.closest('form'))
+ if (form !== this._form) {
+ EventHandler.off(this._form, `reset${EVENT_KEY}`, this._resetHandler)
+ EventHandler.off(this._form, `submit${EVENT_KEY}`, this._submitHandler)
+ this._form = form
+ EventHandler.on(this._form, `reset${EVENT_KEY}`, this._resetHandler)
+ EventHandler.on(this._form, `submit${EVENT_KEY}`, this._submitHandler)
+ }
+ }
+
+ protected async _showMenu(focus?: () => void): Promise {
+ if (this._isDisabled() || this._isShown() || (this._editor && !this._getVisibleItems().length)) {
+ return
+ }
+
+ const search = this._editor || isDisabled(this._searchInput) ? null : this._searchInput
+ await this._menuInstance!.show(focus ?? (search ? () => search.focus({ preventScroll: true }) : undefined))
+ }
+
+ protected _createMenuInstance(): void {
+ this._menuInstance = new ComboboxMenu(this._toggle, {
+ menu: this._menu,
+ reference: this._editor ? this._element : 'toggle',
+ autoClose: this._config.multiple ? 'outside' : true,
+ boundary: this._config.boundary,
+ offset: this._config.offset,
+ placement: this._config.placement,
+ floatingConfig: this._editor ?
+ config => ({
+ ...config,
+ middleware: [...config.middleware, {
+ name: 'comboboxSize',
+ fn: ({ elements, rects }: MiddlewareState) => {
+ if (this._element) {
+ elements.floating.style.minWidth = `${rects.reference.width}px`
+ }
+
+ return {}
+ }
+ }]
+ }) :
+ null
+ })
+ }
+
protected _addEventListeners(): void {
+ // Menu owns transitions and also handles outside clicks and delegated keys.
+ for (const type of ['show', 'shown', 'hide', 'hidden']) {
+ const event = Menu.eventName(type)
+ const handler = (menuEvent: BootstrapEvent) => {
+ if (!this._element) {
+ return
+ }
+
+ if (type === 'hidden' && this._editor) {
+ this._setActiveItem(null)
+ }
+
+ const forwarded = EventHandler.trigger(this._element, this.constructor.eventName(type))
+ if (forwarded?.defaultPrevented || !this._element) {
+ menuEvent.preventDefault()
+ return
+ }
+
+ if (type === 'show' && !menuEvent.defaultPrevented && this._searchInput && !this._editor) {
+ this._searchInput.value = ''
+ this._filterItems('')
+ }
+ }
+
+ this._menuEventHandlers.set(event, handler)
+ EventHandler.on(this._toggle, event, handler)
+ }
+
EventHandler.on(this._menu, `click${EVENT_KEY}`, SELECTOR_MENU_ITEM, event => {
const item = (event.target as Element).closest(SELECTOR_MENU_ITEM)
if (!item || isDisabled(item)) {
@@ -238,19 +1147,39 @@ class Combobox extends BaseComponent {
})
EventHandler.on(this._toggle, `keydown${EVENT_KEY}`, event => {
- this._handleToggleKeydown(event)
+ if (this._editor) {
+ this._handleEditorKeydown(event)
+ } else {
+ this._handleToggleKeydown(event)
+ }
})
EventHandler.on(this._menu, `keydown${EVENT_KEY}`, event => {
this._handleMenuKeydown(event)
})
+ if (this._editor) {
+ this._addEditorListeners()
+ return
+ }
+
if (this._searchInput) {
+ EventHandler.on(this._toggle, `mousedown${EVENT_KEY}`, event => {
+ if (event.button === 0 && !this._isShown() && !this._isDisabled() && !isDisabled(this._searchInput)) {
+ // The search field receives focus when the menu opens on click.
+ event.preventDefault()
+ }
+ })
+
EventHandler.on(this._searchInput, `input${EVENT_KEY}`, () => {
this._filterItems(this._searchInput!.value)
})
EventHandler.on(this._searchInput, `keydown${EVENT_KEY}`, event => {
+ if (event.isComposing || event.keyCode === 229) {
+ return
+ }
+
if (event.key === ARROW_DOWN_KEY) {
event.preventDefault()
const items = this._getVisibleItems()
@@ -261,46 +1190,90 @@ class Combobox extends BaseComponent {
if (event.key === ESCAPE_KEY) {
this.hide()
- this._toggle.focus()
+ this._toggle?.focus()
}
})
}
}
protected _selectItem(item: HTMLElement): void {
+ if (this._isDisabled() || isDisabled(item) || !this._menu.contains(item)) {
+ return
+ }
+
+ const previous = this._getSelectedItems()
+ if (this._config.multiple && !previous.includes(item) && this._config.maxItems !== null && previous.length >= this._config.maxItems) {
+ return
+ }
+
+ if (!this._config.multiple && previous.length === 1 && previous[0] === item) {
+ return
+ }
+
+ const changeId = this._changeId
+ const type = this._config.multiple && previous.includes(item) ? 'remove' : 'add'
+ const event = EventHandler.trigger(this._element, `${type}${EVENT_KEY}`, { value: item.dataset.bsValue, item })
+ if (!this._element || event.defaultPrevented || changeId !== this._changeId || this._isDisabled() || isDisabled(item) || !this._menu.contains(item)) {
+ return
+ }
+
if (this._config.multiple) {
item.classList.toggle(CLASS_NAME_SELECTED)
setAriaAttribute(item, 'aria-selected', item.classList.contains(CLASS_NAME_SELECTED))
} else {
- const previouslySelected = SelectorEngine.find(`.${CLASS_NAME_SELECTED}`, this._menu)
- for (const prev of previouslySelected) {
- prev.classList.remove(CLASS_NAME_SELECTED)
- prev.setAttribute('aria-selected', 'false')
+ for (const selected of previous) {
+ selected.classList.remove(CLASS_NAME_SELECTED)
+ selected.setAttribute('aria-selected', 'false')
}
item.classList.add(CLASS_NAME_SELECTED)
item.setAttribute('aria-selected', 'true')
}
- this._updateToggleText()
- this._updateHiddenInput()
+ this._selectionChanged(item)
+ }
- const value = this._config.multiple ?
- this._getSelectedItems().map(el => el.dataset.bsValue) :
- item.dataset.bsValue
+ protected _selectionChanged(item: HTMLElement | null, query: string | null = null): void {
+ this._query = query
+ this.update()
+ const changeId = this._changeId
+ const { multiple } = this._config
+ const values = this.getValues()
+ const value = multiple ? values : values[0] ?? ''
+ const target = this._hiddenInput ?? this._element
- EventHandler.trigger(this._toggle, EVENT_CHANGE, {
- value,
- item
- })
+ for (const event of ['input', 'change']) {
+ EventHandler.trigger(target, event)
+ if (!this._element || changeId !== this._changeId) {
+ return
+ }
+ }
- if (!this._config.multiple) {
+ EventHandler.trigger(this._element, EVENT_CHANGE, { value, item })
+ if (!this._element || changeId !== this._changeId) {
+ return
+ }
+
+ if (this._editor) {
+ this._setActiveItem(null)
+ this._filterItems('')
+ if (this._status) {
+ this._status.textContent = `${values.length} selected`
+ }
+ }
+
+ if (!multiple && query === null) {
this.hide()
- this._toggle.focus()
+ this._toggle?.focus()
}
}
protected _updateToggleText(): void {
+ if (this._editor) {
+ this._renderEditor()
+ return
+ }
+
const selectedItems = this._getSelectedItems()
if (selectedItems.length === 0) {
@@ -321,29 +1294,97 @@ class Combobox extends BaseComponent {
protected _showPlaceholder(): void {
const { placeholder } = this._config
- if (placeholder) {
- this._valueDisplay.textContent = placeholder
- this._valueDisplay.classList.add(CLASS_NAME_PLACEHOLDER)
- }
+ this._valueDisplay.textContent = placeholder
+ this._valueDisplay.classList.toggle(CLASS_NAME_PLACEHOLDER, Boolean(placeholder))
}
protected _updateHiddenInput(): void {
- if (!this._hiddenInput) {
+ const input = this._hiddenInput
+ if (!input) {
return
}
- const selectedItems = this._getSelectedItems()
- const values = selectedItems.map(el => el.dataset.bsValue)
- this._hiddenInput.value = this._config.multiple ? values.join(',') : (values[0] || '')
+ const selected = this._getSelectedItems()
+ const values = selected
+ .filter(item => !isDisabled(item))
+ .map(item => item.dataset.bsValue ?? '')
+ const submittedValues = this._config.multiple ? values : [values[0] ?? '']
+ const disabled = this._inputDisabled || this._isDisabled() || (selected.length > 0 && values.length === 0)
+
+ if (this._ownsInput) {
+ const anchor = this._editor ? this._element : this._toggle
+ const fields = [input, ...this._extraInputs]
+ if (fields.at(-1)!.nextElementSibling !== anchor) {
+ for (const field of fields) {
+ anchor.before(field)
+ }
+ }
+
+ const form = this._toggle.getAttribute('form')
+ if (form === null) {
+ input.removeAttribute('form')
+ } else {
+ input.setAttribute('form', form)
+ }
+ }
+
+ input.value = submittedValues[0] ?? ''
+ input.disabled = disabled || submittedValues.length === 0
+
+ for (let index = 1; index < submittedValues.length; index++) {
+ let extra = this._extraInputs[index - 1]
+ if (!extra) {
+ extra = document.createElement('input')
+ extra.type = 'hidden'
+ this._extraInputs.push(extra)
+ }
+
+ const previous = this._extraInputs[index - 2] ?? input
+ if (!previous.parentNode) {
+ extra.remove()
+ } else if (extra.previousElementSibling !== previous) {
+ previous.after(extra)
+ }
+
+ extra.name = input.name
+ extra.value = submittedValues[index]
+ extra.disabled = disabled
+ const form = input.getAttribute('form')
+ if (form === null) {
+ extra.removeAttribute('form')
+ } else {
+ extra.setAttribute('form', form)
+ }
+ }
+
+ for (const extra of this._extraInputs.splice(Math.max(0, submittedValues.length - 1))) {
+ extra.remove()
+ }
+
+ // Discard our own disabled/form/name writes before observing caller changes.
+ this._formObserver.takeRecords()
}
protected _getSelectedItems(): HTMLElement[] {
- return SelectorEngine.find(`.${CLASS_NAME_SELECTED}`, this._menu)
+ return SelectorEngine.find(`${SELECTOR_MENU_ITEM}.${CLASS_NAME_SELECTED}`, this._menu)
}
protected _getVisibleItems(): HTMLElement[] {
- return SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu)
- .filter(item => isVisible(item))
+ return SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(item => {
+ if (!this._editor) {
+ return isVisible(item)
+ }
+
+ // A closed popup has no client rects; inspect the option and its groups.
+ for (let current: HTMLElement | null = item; current && current !== this._menu; current = current.parentElement) {
+ const style = getComputedStyle(current)
+ if (current.hidden || style.display === 'none' || style.visibility === 'hidden') {
+ return false
+ }
+ }
+
+ return true
+ })
}
protected _filterItems(query: string): void {
@@ -374,23 +1415,37 @@ class Combobox extends BaseComponent {
}
protected _handleToggleKeydown(event: BootstrapEvent): void {
+ if (event.isComposing || event.keyCode === 229) {
+ return
+ }
+
const { key } = event
if (key === ARROW_DOWN_KEY || key === ARROW_UP_KEY) {
event.preventDefault()
- if (!this._isShown()) {
- this.show()
+ const focusItem = () => {
+ const items = this._getVisibleItems()
+ const item = key === ARROW_DOWN_KEY ? items[0] : items.at(-1)
+ const target = item ?? (isDisabled(this._searchInput) ? this._toggle : this._searchInput)
+ target?.focus()
}
- const items = this._getVisibleItems()
- if (items.length > 0) {
- const target = key === ARROW_DOWN_KEY ? items[0] : items.at(-1)!
- target.focus()
+ if (this._isShown()) {
+ focusItem()
+ } else {
+ this._showMenu(focusItem)
}
return
}
+ if (key === ESCAPE_KEY && this._isShown()) {
+ event.preventDefault()
+ event.stopPropagation()
+ this.hide()
+ return
+ }
+
if ((key === ENTER_KEY || key === SPACE_KEY) && !this._isShown()) {
event.preventDefault()
this.show()
@@ -398,13 +1453,17 @@ class Combobox extends BaseComponent {
}
protected _handleMenuKeydown(event: BootstrapEvent): void {
+ if (event.isComposing || event.keyCode === 229) {
+ return
+ }
+
const { key, target } = event
if (key === ESCAPE_KEY) {
event.preventDefault()
event.stopPropagation()
this.hide()
- this._toggle.focus()
+ this._toggle?.focus()
return
}
@@ -425,7 +1484,7 @@ class Combobox extends BaseComponent {
return
}
- if (key === HOME_KEY || key === END_KEY) {
+ if ((key === HOME_KEY || key === END_KEY) && !isInput) {
event.preventDefault()
const items = this._getVisibleItems()
if (items.length > 0) {
@@ -451,8 +1510,18 @@ class Combobox extends BaseComponent {
*/
EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) {
+ const instance = Combobox.getOrCreateInstance(this)
+ if (this.matches('input') || this.querySelector('.combobox-input, .form-ghost')) {
+ if (!(event.target as Element).closest('.chip')) {
+ instance.focus()
+ instance.show()
+ }
+
+ return
+ }
+
event.preventDefault()
- Combobox.getOrCreateInstance(this).toggle()
+ instance.toggle()
})
onDocumentReady('DOMContentLoaded', () => {
diff --git a/js/src/dom/event-handler.ts b/js/src/dom/event-handler.ts
index 8b97029587..c3979868ea 100644
--- a/js/src/dom/event-handler.ts
+++ b/js/src/dom/event-handler.ts
@@ -62,6 +62,9 @@ const nativeEvents = new Set([
'keypress',
'keyup',
'input',
+ 'compositionstart',
+ 'compositionupdate',
+ 'compositionend',
'paste',
'orientationchange',
'touchstart',
diff --git a/js/src/index.ts b/js/src/index.ts
index e817a4f2df..2d5ce72094 100644
--- a/js/src/index.ts
+++ b/js/src/index.ts
@@ -17,7 +17,6 @@ export { default as NavOverflow } from './nav-overflow.js'
export { default as Drawer } from './drawer.js'
export { default as Strength } from './strength.js'
export { default as OtpInput } from './otp-input.js'
-export { default as Chips } from './chips.js'
export { default as Popover } from './popover.js'
export { default as Range } from './range.js'
export { default as ScrollSpy } from './scrollspy.js'
diff --git a/js/src/menu.ts b/js/src/menu.ts
index 23e26f9e55..6c9c42b1d6 100644
--- a/js/src/menu.ts
+++ b/js/src/menu.ts
@@ -218,7 +218,11 @@ class Menu extends BaseComponent {
return this._isShown() ? this.hide() : this.show()
}
- async show(): Promise {
+ show(): Promise {
+ return this._show()
+ }
+
+ protected async _show(focus?: () => void): Promise {
if (isDisabled(this._element) || this._isShown()) {
return
}
@@ -242,7 +246,6 @@ class Menu extends BaseComponent {
}
}
- this._element.focus({ focusVisible: false })
this._element.setAttribute('aria-expanded', 'true')
this._menu.classList.add(CLASS_NAME_SHOW)
@@ -253,6 +256,15 @@ class Menu extends BaseComponent {
}
Menu._openInstances.add(this)
+ if (focus) {
+ focus()
+ } else {
+ this._element.focus({ focusVisible: false })
+ }
+
+ if (!this._element || !this._isShown()) {
+ return
+ }
// Wait for the CSS entry transition (opacity/transform) to finish before
// announcing `shown`, so listeners run against the settled menu.
@@ -1041,6 +1053,10 @@ class Menu extends BaseComponent {
}
static dataApiKeydownHandler(this: HTMLElement, event: BootstrapEvent): void {
+ if (event.isComposing || event.keyCode === 229) {
+ return
+ }
+
// Treat contenteditable hosts (e.g. rich-text editors) like inputs so the
// menu doesn't hijack their arrow keys.
const isInput = /input|textarea/i.test((event.target as HTMLElement).tagName) || (event.target as HTMLElement).isContentEditable
diff --git a/js/src/util/sanitizer.ts b/js/src/util/sanitizer.ts
index 08f30ba107..23f1e1b48c 100644
--- a/js/src/util/sanitizer.ts
+++ b/js/src/util/sanitizer.ts
@@ -50,7 +50,7 @@ export const DefaultAllowlist: SanitizerAllowList = {
// js-docs-start icon-allow-list
/**
- * Allowlist for icon HTML options (Chips `dismissIcon`, NavOverflow `moreIcon`,
+ * Allowlist for icon HTML options (NavOverflow `moreIcon`,
* and markup supplied via `[data-bs-overflow-icon]`). Covers the default SVG
* icons plus common inline-icon markup. Event-handler attributes and tags not
* listed here are stripped by `sanitizeHtml`.
diff --git a/js/tests/types/api.ts b/js/tests/types/api.ts
index 5a694768d9..8fbbeca454 100644
--- a/js/tests/types/api.ts
+++ b/js/tests/types/api.ts
@@ -11,7 +11,6 @@ import {
Alert,
Button,
Carousel,
- Chips,
Collapse,
Combobox,
Datepicker,
@@ -33,7 +32,6 @@ import BaseComponent from '../../src/base-component.js'
import EventHandler from '../../src/dom/event-handler.js'
import SelectorEngine from '../../src/dom/selector-engine.js'
import type { CarouselConfig } from '../../src/carousel.js'
-import type { ChipsConfig } from '../../src/chips.js'
import type { CollapseConfig } from '../../src/collapse.js'
import type { ComboboxConfig } from '../../src/combobox.js'
import type { DatepickerConfig } from '../../src/datepicker.js'
@@ -59,8 +57,27 @@ const dialog: Dialog = new Dialog(element, { modal: true, keyboard: false })
const drawer: Drawer = new Drawer(element, { scroll: true })
const popover: Popover = new Popover(element, { content: 'Hello', animation: true })
const range: Range = new Range(element, { formatter: value => `${value} %` })
-const chips: Chips = new Chips(element, { separator: ';', maxChips: 5, allowDuplicates: true })
const combobox: Combobox = new Combobox(element, { multiple: true, placeholder: 'Pick one' })
+const comboboxInput = document.createElement('input')
+comboboxInput.type = 'hidden'
+new Combobox(element, { input: comboboxInput })
+new Combobox(element, { input: '#combobox-input' })
+combobox.update()
+combobox.add('design')
+combobox.remove('design')
+combobox.clear()
+combobox.focus()
+combobox.selectChip(element, { rangeSelect: true, addToSelection: true })
+combobox.clearSelection()
+const selectedChipValues: string[] = combobox.getSelectedValues()
+const removedSelectedChips: boolean = combobox.removeSelected()
+void selectedChipValues
+void removedSelectedChips
+const comboboxValues: string[] = combobox.getValues()
+new Combobox(element, {
+ allowCustom: true, multiple: true, separator: ';', maxItems: 5
+})
+void comboboxValues
const navOverflow: NavOverflow = new NavOverflow(element, { moreText: 'More', collapseBelow: 768 })
const navOverflowIconOnly: NavOverflow = new NavOverflow(element, { moreText: false })
const otpInput: OtpInput = new OtpInput(element, { length: 6, type: 'alphanumeric', mask: true })
@@ -102,7 +119,6 @@ const collapseDefault: CollapseConfig = Collapse.Default
const carouselDefault: CarouselConfig = Carousel.Default
const dialogDefault: DialogConfig = Dialog.Default
const drawerDefault: DrawerConfig = Drawer.Default
-const chipsDefault: ChipsConfig = Chips.Default
const comboboxDefault: ComboboxConfig = Combobox.Default
const datepickerDefault: DatepickerConfig = Datepicker.Default
const navOverflowDefault: NavOverflowConfig = NavOverflow.Default
diff --git a/js/tests/types/consumer.ts b/js/tests/types/consumer.ts
index cf03c087ec..64aa22cbb3 100644
--- a/js/tests/types/consumer.ts
+++ b/js/tests/types/consumer.ts
@@ -18,7 +18,6 @@ import {
Alert,
Button,
Carousel,
- Chips,
Collapse,
Combobox,
Datepicker,
@@ -41,7 +40,6 @@ import DeepTooltip, { type TooltipConfig } from 'bootstrap/js/src/tooltip.js'
import EventHandler from 'bootstrap/js/src/dom/event-handler.js'
import SelectorEngine from 'bootstrap/js/src/dom/selector-engine.js'
import type { CarouselConfig } from 'bootstrap/js/src/carousel.js'
-import type { ChipsConfig } from 'bootstrap/js/src/chips.js'
import type { CollapseConfig } from 'bootstrap/js/src/collapse.js'
import type { ComboboxConfig } from 'bootstrap/js/src/combobox.js'
import type { DatepickerConfig } from 'bootstrap/js/src/datepicker.js'
@@ -66,8 +64,27 @@ const dialog: Dialog = new Dialog(element, { modal: true, keyboard: false })
const drawer: Drawer = new Drawer(element, { scroll: true })
const popover: Popover = new Popover(element, { content: 'Hello', animation: true })
const range: Range = new Range(element, { formatter: value => `${value} %` })
-const chips: Chips = new Chips(element, { separator: ';', maxChips: 5, allowDuplicates: true })
const combobox: Combobox = new Combobox(element, { multiple: true, placeholder: 'Pick one' })
+const comboboxInput = document.createElement('input')
+comboboxInput.type = 'hidden'
+new Combobox(element, { input: comboboxInput })
+new Combobox(element, { input: '#combobox-input' })
+combobox.update()
+combobox.add('design')
+combobox.remove('design')
+combobox.clear()
+combobox.focus()
+combobox.selectChip(element, { rangeSelect: true, addToSelection: true })
+combobox.clearSelection()
+const selectedChipValues: string[] = combobox.getSelectedValues()
+const removedSelectedChips: boolean = combobox.removeSelected()
+void selectedChipValues
+void removedSelectedChips
+const comboboxValues: string[] = combobox.getValues()
+new Combobox(element, {
+ allowCustom: true, multiple: true, separator: ';', maxItems: 5
+})
+void comboboxValues
const navOverflow: NavOverflow = new NavOverflow(element, { moreText: 'More', collapseBelow: 768 })
const navOverflowIconOnly: NavOverflow = new NavOverflow(element, { moreText: false })
const otpInput: OtpInput = new OtpInput(element, { length: 6, type: 'alphanumeric', mask: true })
@@ -118,7 +135,6 @@ const collapseDefault: CollapseConfig = Collapse.Default
const carouselDefault: CarouselConfig = Carousel.Default
const dialogDefault: DialogConfig = Dialog.Default
const drawerDefault: DrawerConfig = Drawer.Default
-const chipsDefault: ChipsConfig = Chips.Default
const comboboxDefault: ComboboxConfig = Combobox.Default
const datepickerDefault: DatepickerConfig = Datepicker.Default
const navOverflowDefault: NavOverflowConfig = NavOverflow.Default
diff --git a/js/tests/unit/chips.spec.js b/js/tests/unit/chips.spec.js
deleted file mode 100644
index b09b980ccc..0000000000
--- a/js/tests/unit/chips.spec.js
+++ /dev/null
@@ -1,695 +0,0 @@
-import Chips from '../../src/chips.js'
-import EventHandler from '../../src/dom/event-handler.js'
-import { clearFixture, createEvent, getFixture } from '../helpers/fixture.js'
-
-describe('Chips', () => {
- let fixtureEl
-
- const makeChips = (options, html = '') => {
- fixtureEl.innerHTML = html
- const chipsEl = fixtureEl.querySelector('.chips')
- return { chipsEl, chips: new Chips(chipsEl, options) }
- }
-
- const keydown = (target, key, modifiers = {}) => {
- target.dispatchEvent(new KeyboardEvent('keydown', {
- key,
- bubbles: true,
- cancelable: true,
- ...modifiers
- }))
- }
-
- beforeAll(() => {
- fixtureEl = getFixture()
- })
-
- afterEach(() => {
- clearFixture()
- })
-
- describe('static properties', () => {
- it('should expose version, name, default and default type', () => {
- expect(Chips.VERSION).toEqual(jasmine.any(String))
- expect(Chips.NAME).toEqual('chips')
- expect(Chips.Default).toEqual(jasmine.any(Object))
- expect(Chips.DefaultType).toEqual(jasmine.any(Object))
- })
- })
-
- describe('constructor', () => {
- it('should create a ghost input when none is present', () => {
- const { chipsEl } = makeChips()
-
- expect(chipsEl.querySelector('.form-ghost')).not.toBeNull()
- })
-
- it('should reuse an existing ghost input and set the placeholder from config', () => {
- const { chipsEl } = makeChips(
- { placeholder: 'Add tag' },
- ''
- )
-
- expect(chipsEl.querySelectorAll('.form-ghost').length).toEqual(1)
- })
-
- it('should initialize from existing chips in the markup', () => {
- const { chips, chipsEl } = makeChips(
- {},
- '
alpha
'
- )
-
- expect(chips.getValues()).toEqual(['alpha'])
- // Existing chips get a dismiss button and become focusable
- expect(chipsEl.querySelector('.chip').getAttribute('tabindex')).toEqual('0')
- expect(chipsEl.querySelector('.chip-dismiss')).not.toBeNull()
- })
-
- it('should derive a chip value from text content when no data attribute is set', () => {
- const { chips } = makeChips(
- {},
- '
beta
'
- )
-
- expect(chips.getValues()).toEqual(['beta'])
- })
-
- it('should derive a chip value from text while ignoring an existing dismiss button', () => {
- const { chips } = makeChips(
- {},
- '
+ `
+ const input = fixture.querySelector('.form-control')
+ const control = fixture.querySelector('.combobox-control')
+ expect(input.getBoundingClientRect().height).toBeCloseTo(height, 1)
+ expect(control.getBoundingClientRect().height).toBeCloseTo(height, 1)
+ const chip = control.querySelector('.chip').getBoundingClientRect()
+ const dismiss = control.querySelector('.chip-dismiss').getBoundingClientRect()
+ expect(dismiss.height).toBeLessThanOrEqual(chip.height)
+ })
+ }
+})
diff --git a/js/tests/unit/combobox.spec.js b/js/tests/unit/combobox.spec.js
index 6eb17b6b9e..5489b587f0 100644
--- a/js/tests/unit/combobox.spec.js
+++ b/js/tests/unit/combobox.spec.js
@@ -1,3 +1,4 @@
+import { page, userEvent } from 'vitest/browser'
import Combobox from '../../src/combobox.js'
import EventHandler from '../../src/dom/event-handler.js'
import Menu from '../../src/menu.js'
@@ -316,7 +317,7 @@ describe('Combobox', () => {
items[1].click()
expect(valueEl.textContent).toEqual('2 selected')
- expect(fixtureEl.querySelector('input[type="hidden"]').value).toEqual('us,uk')
+ expect([...fixtureEl.querySelectorAll('input[type="hidden"]')].map(input => input.value)).toEqual(['us', 'uk'])
})
it('should fire change with every selected value', () => {
@@ -344,6 +345,33 @@ describe('Combobox', () => {
describe('search', () => {
const searchMarkup = () => markup({ search: SEARCH_HTML, noResults: NO_RESULTS_HTML })
+ it('should focus search directly on click and return to the toggle on Escape', async () => {
+ const { combobox, menuEl, toggleEl } = makeCombobox({ search: true, placeholder: 'Select a country' }, searchMarkup())
+ const searchEl = menuEl.querySelector('.combobox-search-input')
+ const focusOrder = []
+ toggleEl.style.cssText = 'position: fixed; top: 1rem; left: 1rem'
+ toggleEl.addEventListener('focus', () => focusOrder.push(toggleEl))
+ searchEl.addEventListener('focus', () => focusOrder.push(searchEl))
+
+ try {
+ const toggle = page.getByRole('button', { name: 'Select a country' })
+ await toggle.click()
+
+ expect(focusOrder).toEqual([searchEl])
+ expect(document.activeElement).toBe(searchEl)
+
+ keydown(searchEl, 'Escape')
+
+ expect(document.activeElement).toBe(toggleEl)
+
+ await userEvent.keyboard('{Enter}')
+
+ expect(document.activeElement).toBe(searchEl)
+ } finally {
+ combobox.dispose()
+ }
+ })
+
const typeSearch = (searchEl, value) => {
searchEl.value = value
searchEl.dispatchEvent(new Event('input', { bubbles: true }))
diff --git a/scss/_chip.scss b/scss/_chip.scss
index dd0bce94f0..d50c3fbaee 100644
--- a/scss/_chip.scss
+++ b/scss/_chip.scss
@@ -41,31 +41,36 @@ $chip-tokens: defaults(
height: var(--chip-height);
padding-inline: var(--chip-padding-x);
font-size: var(--chip-font-size, var(--font-size-sm));
- font-weight: var(--chip-font-weight, var(--font-weight-base));
+ font-weight: var(--chip-font-weight, var(--font-weight-normal));
line-height: var(--chip-line-height, 1.25rem);
color: var(--chip-color);
text-decoration: none;
white-space: nowrap;
vertical-align: middle;
- cursor: pointer;
background-color: var(--chip-bg);
border: var(--border-width) solid var(--chip-border-color);
@include border-radius(var(--chip-border-radius));
- &:hover {
- --chip-bg: var(--theme-bg-muted, var(--bg-3));
- }
-
&:focus-visible {
- outline: 0;
+ @include focus-ring();
}
&.active {
--chip-color: var(--chip-selected-color);
--chip-bg: var(--chip-selected-bg);
--chip-border-color: var(--chip-selected-border-color);
+ }
+
+ &:is(:any-link, button, [role="button"], [role="link"]):not(:disabled, .disabled, [aria-disabled="true"]),
+ :is(:any-link, button, [role="button"], [role="link"]):not(:disabled, .disabled, [aria-disabled="true"]) &,
+ .combobox-control > & {
+ cursor: pointer;
&:hover {
+ --chip-bg: var(--theme-bg-muted, var(--bg-3));
+ }
+
+ &.active:hover {
--chip-bg: var(--chip-selected-bg);
opacity: .9;
}
@@ -74,7 +79,7 @@ $chip-tokens: defaults(
&.disabled,
&:disabled {
pointer-events: none;
- opacity: .65;
+ opacity: var(--control-disabled-opacity);
}
}
diff --git a/scss/forms/_chip-input.scss b/scss/forms/_combobox-control.scss
similarity index 52%
rename from scss/forms/_chip-input.scss
rename to scss/forms/_combobox-control.scss
index 1fb6db3101..bbb793465b 100644
--- a/scss/forms/_chip-input.scss
+++ b/scss/forms/_combobox-control.scss
@@ -3,42 +3,53 @@
@use "../mixins/focus-ring" as *;
@use "../mixins/tokens" as *;
-$chip-input-tokens: () !default;
+$combobox-control-tokens: () !default;
-// scss-docs-start chip-input-tokens
+// scss-docs-start combobox-control-tokens
// stylelint-disable-next-line scss/dollar-variable-default
-$chip-input-tokens: defaults(
+$combobox-control-tokens: defaults(
(
- --chip-input-padding-y: .75rem,
- --chip-input-padding-x: .75rem,
- --chip-input-gap: .375rem,
- --chip-input-ghost-min-width: 5rem,
+ --combobox-control-padding-y: var(--btn-input-padding-y),
+ --combobox-control-padding-x: var(--btn-input-padding-x),
+ --combobox-control-gap: .25rem,
+ --combobox-control-chip-height: calc(var(--control-min-height) - 2 * var(--combobox-control-padding-y) - 2 * var(--control-border-width)),
+ --control-min-height: var(--btn-input-min-height),
+ --control-font-size: var(--btn-input-font-size),
+ --control-line-height: var(--btn-input-line-height),
+ --combobox-control-ghost-min-width: 5rem,
--control-fg: var(--btn-input-fg),
--control-bg: var(--btn-input-bg),
--control-border-width: var(--border-width),
--control-border-color: var(--border-color),
--control-border-radius: var(--radius-5),
),
- $chip-input-tokens
+ $combobox-control-tokens
);
-// scss-docs-end chip-input-tokens
+// scss-docs-end combobox-control-tokens
@layer forms {
- .chip-input {
- @include tokens($chip-input-tokens);
+ .combobox-control {
+ @include tokens($combobox-control-tokens);
// Flexbox wrapping layout
display: flex;
flex-wrap: wrap;
- gap: var(--chip-input-gap);
+ gap: var(--combobox-control-gap);
align-items: center;
- padding: var(--chip-input-padding-y) var(--chip-input-padding-x);
+ min-block-size: var(--control-min-height);
+ padding: var(--combobox-control-padding-y) var(--combobox-control-padding-x);
+ font-size: var(--control-font-size);
+ line-height: var(--control-line-height);
color: var(--control-fg);
background-color: var(--control-bg);
border: var(--control-border-width) solid var(--control-border-color);
@include border-radius(var(--control-border-radius), 0);
+ &:has(> .chip) {
+ padding-inline: var(--combobox-control-padding-y);
+ }
+
// Focus state when ghost input is focused
&:focus-within {
--focus-ring-offset: -1px;
@@ -47,10 +58,11 @@ $chip-input-tokens: defaults(
}
// Ghost input fills remaining space
- > .form-ghost {
+ > .form-ghost,
+ > .combobox-input {
flex: 1 1 0;
- min-width: var(--chip-input-ghost-min-width);
- min-height: 1.75rem;
+ min-inline-size: var(--combobox-control-ghost-min-width);
+ min-block-size: 1lh;
}
// Disabled state
diff --git a/scss/forms/_combobox.scss b/scss/forms/_combobox.scss
index 9b99994f38..f1e8dd3227 100644
--- a/scss/forms/_combobox.scss
+++ b/scss/forms/_combobox.scss
@@ -1,12 +1,42 @@
+@use "../mixins/focus-ring" as *;
@use "../mixins/transition" as *;
@layer components {
+ .combobox-control > .chip {
+ --chip-height: var(--combobox-control-chip-height);
+ --chip-border-radius: max(0px, calc(var(--control-border-radius) / 2));
+ --chip-padding-x: .5rem;
+ --chip-gap: .25rem;
+ --chip-dismiss-size: var(--combobox-control-chip-height);
+
+ > .chip-dismiss {
+ margin-inline: -.25rem -.5rem;
+
+ > svg {
+ width: .75rem;
+ height: .75rem;
+ }
+ }
+
+ &:focus-visible,
+ > .chip-dismiss:focus-visible {
+ @include focus-ring();
+ }
+ }
+
+ .combobox-control + .menu,
+ .combobox + .menu {
+ --menu-max-height: 300px;
+ --menu-overflow-y: auto;
+ }
+
.combobox-toggle {
display: inline-flex;
gap: .5rem;
align-items: center;
justify-content: space-between;
width: 100%;
+ min-width: 0;
padding-inline-end: var(--control-padding-x);
text-align: start;
cursor: pointer;
@@ -18,22 +48,21 @@
&:disabled,
&.disabled {
cursor: not-allowed;
- opacity: .65;
+ opacity: var(--control-disabled-opacity);
}
}
.combobox-value {
- display: flex;
+ display: block;
flex: 1;
- gap: .5rem;
- align-items: center;
+ min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.combobox-placeholder {
- color: color-mix(in oklch, currentcolor 65%, transparent);
+ color: var(--control-placeholder-color);
}
.combobox-caret {
@@ -52,7 +81,7 @@
.combobox-search {
position: sticky;
- top: 0;
+ inset-block-start: calc(-1 * var(--menu-padding-y, .25rem));
z-index: 1;
padding: var(--menu-padding-x, .25rem);
background-color: var(--menu-bg, var(--bg-body));
diff --git a/scss/forms/_validation.scss b/scss/forms/_validation.scss
index acf51fd20b..f29dde410c 100644
--- a/scss/forms/_validation.scss
+++ b/scss/forms/_validation.scss
@@ -201,9 +201,9 @@ $validation-states: defaults(
}
}
- // Chip input — wrapper has the visible border; the .form-ghost inside
+ // Combobox — wrapper has the visible border; the .form-ghost inside
// receives the native pseudo-class.
- .chip-input:has(.form-ghost.is-#{$state}) {
+ .combobox-control:has(.form-ghost.is-#{$state}) {
border-color: var(--#{$theme}-border);
&:focus-within {
@@ -216,7 +216,7 @@ $validation-states: defaults(
}
@if $state == "invalid" {
- [data-bs-validate] .chip-input:has(.form-ghost:user-invalid) {
+ [data-bs-validate] .combobox-control:has(.form-ghost:user-invalid) {
border-color: var(--#{$theme}-border);
&:focus-within {
@@ -228,7 +228,7 @@ $validation-states: defaults(
~ .invalid-tooltip { display: block; }
}
} @else if $state == "valid" {
- [data-bs-validate~="valid"] .chip-input:has(.form-ghost:user-valid) {
+ [data-bs-validate~="valid"] .combobox-control:has(.form-ghost:user-valid) {
border-color: var(--#{$theme}-border);
&:focus-within {
diff --git a/scss/forms/index.scss b/scss/forms/index.scss
index 58cd150f1f..e5bd08058e 100644
--- a/scss/forms/index.scss
+++ b/scss/forms/index.scss
@@ -10,7 +10,7 @@
@forward "strength";
@forward "otp-input";
@forward "form-adorn";
-@forward "chip-input";
+@forward "combobox-control";
@forward "combobox";
@forward "form-field";
@forward "validation";
diff --git a/site/data/sidebar.yml b/site/data/sidebar.yml
index 73dee44b39..23b13d651c 100644
--- a/site/data/sidebar.yml
+++ b/site/data/sidebar.yml
@@ -93,9 +93,6 @@
- title: Form adorn
meta:
- added: 6.0.0
- - title: Chips
- meta:
- - added: 6.0.0
- title: Combobox
meta:
- added: 6.0.0
@@ -131,6 +128,9 @@
- title: Carousel
meta:
- added: 6.0.0
+ - title: Chips
+ meta:
+ - added: 6.0.0
- title: Close button
- title: Collapse
- title: Dialog
diff --git a/site/src/assets/stackblitz.js b/site/src/assets/stackblitz.js
index 05afdf2c37..51cda0ea75 100644
--- a/site/src/assets/stackblitz.js
+++ b/site/src/assets/stackblitz.js
@@ -37,7 +37,6 @@ const LOAD_PLUGINS = {
// starts them at once when it loads after the page, but not 6.0.0-alpha.1, the
// version the playground installs
const READY_PLUGINS = {
- Chips: '[data-bs-chips]',
Combobox: '[data-bs-toggle="combobox"]',
Datepicker: '[data-bs-toggle="datepicker"][data-bs-inline="true"], [data-bs-toggle="datepicker"][data-bs-selected-dates]',
NavOverflow: '[data-bs-toggle="nav-overflow"]',
diff --git a/site/src/content/docs/components/chips.mdx b/site/src/content/docs/components/chips.mdx
new file mode 100644
index 0000000000..bcf0179377
--- /dev/null
+++ b/site/src/content/docs/components/chips.mdx
@@ -0,0 +1,88 @@
+---
+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.
+
+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/forms/chips.mdx b/site/src/content/docs/forms/chips.mdx
deleted file mode 100644
index e6e5697298..0000000000
--- a/site/src/content/docs/forms/chips.mdx
+++ /dev/null
@@ -1,339 +0,0 @@
----
-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.
-
-
-
-
- JavaScript
-
-
- TypeScript
-
-
- `} />
-
-### Theme variants
-
-Add a `.theme-*` class to the `.chip-input` container to apply a theme color to all chips within.
-
-
- Approved
- Verified
-
-
-
-
- Bug
- Critical
-
-
`} />
-
-You can also individually apply a theme color to a chip by adding a `.theme-*` class to the chip element.
-
-
- Bug
- Critical
-
- `} />
-
-### Empty state
-
-Start with just the ghost input—chips are created as users type.
-
-
-
- `} />
-
-### With label
-
-Use a form label for better accessibility.
-
-
-
-
-
- React
-
-
-
-
-
-
-
Press Enter or comma to add a skill.
- `} />
-
-### Disabled
-
-Disable the ghost input to prevent adding new chips, and disable the dismiss buttons on existing chips. Existing chips become non-interactive.
-
-
-
- Read only
-
-
-
-
-
- `} />
-
-## Usage
-
-### Via data attributes
-
-Add `data-bs-chips` to your container element to automatically initialize the chip input behavior. Options can be passed as data attributes.
-
-
-| Attribute | Description |
-| --- | --- |
-| `data-bs-chips` | Initializes the chip input on the container element. |
-| `data-bs-separator` | Character that creates a new chip when typed (or `null` to disable). |
-| `data-bs-allow-duplicates` | Whether duplicate chip values are allowed. |
-| `data-bs-max-chips` | Maximum number of chips (`null` for no limit). |
-| `data-bs-create-on-blur` | Create a chip from the input value when focus leaves the field. |
-
-
-```html
-
-
-
-```
-
-### Via JavaScript
-
-Initialize manually with JavaScript:
-
-```js
-const chipInputElement = document.querySelector('.chip-input')
-const chips = new bootstrap.Chips(chipInputElement, {
- separator: ',',
- maxChips: 5
-})
-```
-
-### Dependencies
-
-
-
-### Options
-
-Options can be passed via data attributes or JavaScript:
-
-
-| Name | Type | Default | Description |
-| --- | --- | --- | --- |
-| `separator` | string \| null | `','` | Character that triggers chip creation when typed. Set to `null` to disable. |
-| `allowDuplicates` | boolean | `false` | Allow duplicate chip values. |
-| `maxChips` | number \| null | `null` | Maximum number of chips allowed. `null` for unlimited. |
-| `placeholder` | string | `''` | Placeholder text for dynamically created inputs. |
-| `dismissible` | boolean | `true` | Add dismiss buttons to created chips. |
-| `dismissIcon` | string | `''` | HTML string for the dismiss button icon. Passed through the [icon content sanitizer]([[docsref:/getting-started/javascript#sanitizer]]) before insertion. |
-| `createOnBlur` | boolean | `true` | Create chip from input value when the input loses focus. |
-
-
-### Methods
-
-
-| Method | Description |
-| --- | --- |
-| `add(value)` | Adds a chip with the given value. Returns the chip element or `null` if rejected. |
-| `remove(chipOrValue)` | Removes a chip by element reference or value string. Returns `true` if removed. |
-| `removeSelected()` | Removes all currently selected chips. |
-| `getValues()` | Returns an array of all chip values. |
-| `getSelectedValues()` | Returns an array of selected chip values. |
-| `clear()` | Removes all chips. |
-| `clearSelection()` | Deselects all chips without removing them. |
-| `selectChip(chip, options)` | Selects a chip. Options: `addToSelection`, `rangeSelect`. |
-| `focus()` | Focuses the ghost input. |
-| `dispose()` | Destroys the component instance. |
-
-
-```js
-const chipInputElement = document.querySelector('.chip-input')
-const chips = bootstrap.Chips.getOrCreateInstance(chipInputElement)
-
-// Add chips programmatically
-chips.add('JavaScript')
-chips.add('TypeScript')
-
-// Get all values
-console.log(chips.getValues()) // ['JavaScript', 'TypeScript']
-
-// Remove a specific chip
-chips.remove('JavaScript')
-
-// Clear all chips
-chips.clear()
-```
-
-### Events
-
-
-| Event | Description |
-| --- | --- |
-| `add.bs.chips` | Fired before a chip is added. Call `event.preventDefault()` to cancel. |
-| `remove.bs.chips` | Fired before a chip is removed. Call `event.preventDefault()` to cancel. |
-| `change.bs.chips` | Fired after any chip is added or removed. Contains `values` array. |
-| `select.bs.chips` | Fired when chip selection changes. Contains `selected` array of values. |
-
-
-```js
-const chipInputElement = document.querySelector('.chip-input')
-
-chipInputElement.addEventListener('add.bs.chips', event => {
- console.log('Adding chip:', event.value)
-
- // Validate and optionally prevent
- if (event.value.length < 2) {
- event.preventDefault()
- }
-})
-
-chipInputElement.addEventListener('remove.bs.chips', event => {
- console.log('Removing chip:', event.value)
-})
-
-chipInputElement.addEventListener('change.bs.chips', event => {
- console.log('Current values:', event.values)
- // Sync with hidden input or state
-})
-
-chipInputElement.addEventListener('select.bs.chips', event => {
- console.log('Selected:', event.selected)
-})
-```
-
-## Keyboard behavior
-
-Chip inputs support Mail.app-style keyboard navigation with chip selection.
-
-### When input is focused
-
-
-| Key | Action |
-| --- | --- |
-| `Enter` | Create chip from current input value |
-| `,` (or separator) | Create chip from current input value |
-| `Backspace` / `Delete` | When input is empty, select and focus last chip (first press); pressing again deletes it |
-| `←` | When cursor is at start, move focus to last chip |
-| `Shift+←` | Select last chip and extend selection |
-| `Escape` | Clear selection, clear input, and blur |
-
-
-### When a chip is focused
-
-
-| Key | Action |
-| --- | --- |
-| `Backspace` / `Delete` | Remove selected chips, then select and focus the next closest chip |
-| `←` | Move to previous chip |
-| `→` | Move to next chip (or input if at end) |
-| `Shift+←` / `Shift+→` | Extend selection in that direction |
-| `Home` | Move to first chip |
-| `End` | Move to input |
-| `Cmd/Ctrl+A` | Select all chips |
-| `Escape` | Clear selection and focus input |
-
-
-### Mouse selection
-
-
-| Action | Effect |
-| --- | --- |
-| Click chip | Select chip (deselects others) |
-| `Cmd/Ctrl+Click` | Toggle chip in selection |
-| `Shift+Click` | Range select from anchor to clicked chip |
-
-
-## Accessibility
-
-- Use a `