Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 9x 9x 9x 1x 1x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 1x 1x 17x 17x 17x 17x 1x 1x 1x 1x 44x 44x 1x 1x 1x 1x 5x 5x 1x 1x 18x 18x 1x 1x 18x 18x 18x 18x 9x 9x 9x 9x 9x 9x 9x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 17x 17x 26x 26x 26x 17x 17x 32x 32x 192x 192x 32x 17x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 218x 218x 17x 17x 17x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import html from './dynamic-select.element.html'
import css from './dynamic-select.element.css'
import { applyTemplate } from '../utils/templater.js'
import { isPlainObject } from '../utils/object.js'
import { dataObjectOfOption } from '../utils/option-data.js'
import { templatesOf } from '../features/templates/templates.js'
import { configurationOf } from '../features/configuration/configuration.js'
import { dynamicOptionsOf } from '../features/dynamic-loaded-options/dynamic-option.js'
import { computeOnce } from '../utils/memoization.js'
import { dropdownPositionUpdaterOf, updateDropdownPosition } from '../features/dropdown-reflects-select-position-and-visibility/dropdown-position-updater.js'
import { isMobile, MobileDetectionObserver } from '../utils/mobile-detection.js'
import { applyI18nOnSelectInputs } from '../features/dropdown-inputs-are-internationalized/dropdown-i18n.js'
import {
searchInputEl, inputEl, dropdownEl, valueListEl, dropdownOptionList, getHostDynamicSelect, containerEl,
okButtonEl, cancelButtonEl,
isSearchInputEl, isDeselectButton, isClearButton, isDynamicSelect, isDynamicSelectSymbol,
} from '../utils/dynamic-select-dom.js'
/** @import { OptionData } from '../utils/option-data' */
const loadTemplate = computeOnce(() => {
const templateElement = document.createElement('template')
templateElement.innerHTML = html
return templateElement
})
const loadStyles = computeOnce(() => {
const sheet = new CSSStyleSheet()
sheet.replaceSync(css)
return sheet
})
const optionsObserver = new MutationObserver(mutations => {
/** @type {Set<DynamicSelect>} */
const selectsToUpdate = new Set()
for (const mutation of mutations) {
const { target } = mutation
let option
if (target instanceof Element) {
option = target.closest('option')
} else {
option = target.parentElement?.closest('option')
}
if (!option) {
continue
}
const parent = option.parentElement
if (parent instanceof DynamicSelect) {
selectsToUpdate.add(parent)
}
}
selectsToUpdate.forEach(select => {
updateButtonContent(select)
})
})
/** @type {MutationObserverInit} */
const optionsObserverOptions = {
childList: true,
subtree: true,
attributes: true,
characterData: true,
attributeFilter: ['data-of-option'],
}
const mobileDetectionObserver = MobileDetectionObserver(mutations => {
for (const mutation of mutations) {
const { target, isMobile } = mutation
if (!isDynamicSelect(target)) { continue }
target.open = false
const uiModeStyleValue = getComputedStyle(target).getPropertyValue('--ui-mode')
const uiModeParsed = uiModeStyleValue.trim().toLowerCase()
const uiMode = ['mobile', 'desktop'].includes(uiModeParsed) ? uiModeParsed : null
containerEl(target).setAttribute('data-ui-mode', uiMode ?? (isMobile ? 'mobile' : 'desktop'))
updateButtonContent(target)
}
})
/** @type {WeakMap<DynamicSelect, Set<string>>} */
const selectedOptionWeakMap = new WeakMap()
export class DynamicSelect extends HTMLElement {
constructor () {
super()
const shadowRoot = this.attachShadow({ mode: 'open' })
shadowRoot.adoptedStyleSheets = [loadStyles()]
const template = loadTemplate()
shadowRoot.append(document.importNode(template.content, true))
searchInputEl(this).addEventListener('input', handleSearchInputChange)
inputEl(this).addEventListener('click', handleSelectValueButtonClick)
searchInputEl(this).addEventListener('keydown', handleSearchInputKeyDown)
const dropdown = dropdownEl(this)
dropdown.addEventListener('toggle', handleDropdownToggle)
dropdown.addEventListener('pointerdown', handleDropdownPointerDown)
dropdown.addEventListener('click', handleDropdownOptionClick)
okButtonEl(this).addEventListener('click', handleOkButtonClick)
cancelButtonEl(this).addEventListener('click', handleCancelButtonClick)
optionsObserver.observe(this, optionsObserverOptions)
mobileDetectionObserver.observe(this)
applyI18nOnSelectInputs(this)
}
connectedCallback () {
updateDropdownContent(this)
updateButtonContent(this)
}
get searchFilter () {
return this.getAttribute('data-filter') ?? ''
}
set searchFilter (newSearchFilter) {
if (newSearchFilter === '' || newSearchFilter == null) {
this.removeAttribute('data-filter')
}
this.setAttribute('data-filter', String(newSearchFilter))
}
get value () {
return this.valueAsArray[0] ?? ''
}
set value (value) {
if (typeof value !== 'string') { return }
this.valueAsArray = [value]
}
get valueAsArray () {
let iterator = Iterator.from(this.selectedOptions).map(option => option.value)
if (!this.multiple) {
iterator = iterator.take(1)
}
return iterator.toArray()
}
set valueAsArray (valueAsArray) {
if (!Array.isArray(valueAsArray)) { return }
Iterator.from(this.options).forEach(option => {
option.selected = valueAsArray.includes(option.value)
})
dynamicOptionsOf(this).values = valueAsArray
}
get valueAsObjects () {
let iterator = Iterator.from(this.selectedOptions)
.map(dataObjectOfOption)
.map(info => info.data)
if (!this.multiple) {
iterator = iterator.take(1)
}
return iterator.toArray()
}
set valueAsObjects (valueAsObjects) {
if (!Array.isArray(valueAsObjects)) { return }
const validValueEntries = Iterator.from(valueAsObjects)
.filter(isPlainObject)
.filter(obj => typeof obj.value === 'string' || !isNaN(obj.value))
.map(obj => [obj.value, obj])
const map = Object.fromEntries(validValueEntries)
Iterator.from(this.options).forEach(option => {
const data = map[option.value]
if (data) {
option.selected = false
return
}
option.selected = true
if (isPlainObject(data)) {
const { text, value, ...rest } = data
if (Object.keys(rest).length > 0) {
option.setAttribute('data-of-option', JSON.stringify(data))
}
}
})
}
get open () {
return this.hasAttribute('open')
}
set open (openBool) {
if (typeof openBool === 'boolean') {
this.toggleAttribute('open', openBool)
}
}
get [isDynamicSelectSymbol] () { return true }
get multiple () {
return this.hasAttribute('multiple')
}
set multiple (multipleBool) {
if (typeof multipleBool === 'boolean') {
this.toggleAttribute('multiple', multipleBool)
}
}
static get observedAttributes () {
return ['open', 'data-filter']
}
get options () {
return [...this.querySelectorAll('option'), ...dynamicOptionsOf(this).options]
}
get selectedOptions () {
const { options } = this
const result = Iterator.from(options).filter(option => option.selected).toArray()
if (result.length || this.multiple) {
return result
}
const firstOption = options[0]
if (!firstOption) {
return []
}
firstOption.selected = true
return [firstOption]
}
get src () {
return this.querySelectorAll('option[selected]')
}
/**
* @param {string} name - attribute name
* @param {string} oldValue - previous attribute value
* @param {string} newValue - current attribute value
*/
attributeChangedCallback (name, oldValue, newValue) {
switch (name) {
case 'open':
if (this.open) {
const loadData = dynamicOptionsOf(this).loadData()
dropdownPositionUpdaterOf(this).startAnchoringToSelect()
updateDropdownContent(this)
const isOnMobile = isMobile()
if (isOnMobile) {
dropdownEl(this).showModal()
// no need to open on-screen keyboard
searchInputEl(this).blur()
} else {
dropdownEl(this).showPopover()
}
loadData.then(() => {
updateDropdownContent(this)
})
} else {
selectedOptionWeakMap.delete(this)
if (isMobile()) {
dropdownEl(this).close()
} else {
dropdownEl(this).hidePopover()
}
dropdownPositionUpdaterOf(this).stopAnchoringToSelect()
}
break
case 'data-filter':
searchInputEl(this).value = newValue
updateDropdownContent(this)
dynamicOptionsOf(this).loadData().then(() => {
updateDropdownContent(this)
})
}
}
}
/**
* @typedef {{
* ungroupedOptions: OptionData[],
* optionGroups: {[groupName:string]: OptionData[]}
* }} DropdownListData
*/
/**
* Updates dropdown content based on the content in dynamic select in light DOM
* @param {DynamicSelect} dynamicSelect - web component element reference
* @returns {DropdownListData} - dropdown data
*/
function getDropdownListData (dynamicSelect) {
const ungroupedOptions = []
const optionGroups = /** @type {DropdownListData["optionGroups"]} */({})
for (const option of dynamicSelect.querySelectorAll(':scope > option')) {
ungroupedOptions.push(dataObjectOfOption(option))
}
for (const option of dynamicSelect.querySelectorAll(':scope > optgroup option')) {
const groupName = option.closest('optgroup')?.label
const data = dataObjectOfOption(option)
if (!groupName) {
ungroupedOptions.push(data)
} else {
optionGroups[groupName] ??= []
optionGroups[groupName].push(data)
}
}
const { optionsData } = dynamicOptionsOf(dynamicSelect)
for (const data of optionsData) {
const groupName = data.data.group?.toString()
if (!groupName) {
ungroupedOptions.push(data)
} else {
optionGroups[groupName] ??= []
optionGroups[groupName].push(data)
}
}
const { searchFilter } = dynamicSelect
const { minQueryLength } = configurationOf(dynamicSelect)
if (typeof searchFilter === 'string' && searchFilter.trim() !== '' && searchFilter.length >= minQueryLength) {
const matchFilter = filterMatcher(searchFilter)
const filteredUngrouped = ungroupedOptions.filter(option => matchFilter(option.text))
const filteredOptionGroups = /** @type {DropdownListData["optionGroups"]} */({})
for (const [groupName, options] of Object.entries(optionGroups)) {
if (matchFilter(groupName)) {
filteredOptionGroups[groupName] = options
continue
}
const filteredOptions = options.filter(option => matchFilter(option.text))
if (filteredOptions.length > 0) {
filteredOptionGroups[groupName] = filteredOptions
}
}
return {
ungroupedOptions: filteredUngrouped,
optionGroups: filteredOptionGroups,
}
}
return { ungroupedOptions, optionGroups }
}
/**
* Updates dropdown content based on the content in dynamic select in light DOM
* @param {DynamicSelect} dynamicSelect - web component element reference
* @returns {{
* ungroupedOptions: (OptionData & {checkedIndicatorType: "radio" | "checkbox"})[],
* optionGroups: {groupName:string, options: (OptionData & {checkedIndicatorType: "radio" | "checkbox"})[]}[]
* }} - dropdown data
*/
function getDropdownTemplateData (dynamicSelect) {
const { ungroupedOptions, optionGroups } = getDropdownListData(dynamicSelect)
const checkedIndicatorType = dynamicSelect.multiple ? 'checkbox' : 'radio'
const dropdownOptions = [...dropdownOptionList(dynamicSelect)]
let focusIndex = dropdownOptions.findIndex(el => el.hasAttribute('data-focused'))
return {
ungroupedOptions: ungroupedOptions.map(option => ({
...option,
checkedIndicatorType,
focused: focusIndex-- === 0,
})),
optionGroups: Object.entries(optionGroups).map(([groupName, options]) => ({
groupName,
options: options.map(option => ({
...option, checkedIndicatorType,
focused: focusIndex-- === 0,
})),
})),
}
}
/**
* Create a predicate as option filter on dropdown
* @param {string} filter - filter value, generally the filter input on the dropdown
* @returns {(text: string) => boolean} filter predicate
*/
function filterMatcher (filter) {
const caseInsensitiveFilter = filter.trim().toLocaleLowerCase()
return (text) => text.toLowerCase().includes(caseInsensitiveFilter)
}
/**
* Updates dropdown content based on the content in dynamic select in light DOM
* @param {DynamicSelect} dynamicSelect - web component element reference
*/
function updateDropdownContent (dynamicSelect) {
const dropdownData = getDropdownTemplateData(dynamicSelect)
const { dropdownList, option: optionTemplate, loadingNotification } = templatesOf(dynamicSelect)
const listFragment = applyTemplate(dropdownList, dropdownData)
listFragment.querySelectorAll('slot[name="option"]').forEach(slot => {
const data = JSON.parse(slot.dataset.value || '{}')
slot.replaceWith(applyTemplate(optionTemplate, data))
})
listFragment.querySelectorAll('slot[name="loading-notification"]').forEach(slot => {
slot.replaceWith(applyTemplate(loadingNotification, dropdownData))
})
const valueList = valueListEl(dynamicSelect)
valueList.replaceChildren(listFragment)
}
/**
* Updates button content based on the content in dynamic select in light DOM
* @param {DynamicSelect} dynamicSelect - web component element reference
*/
function updateButtonContent (dynamicSelect) {
const {
option: optionTemplate, multiSelectInput, mobileMultiSelectInput, singleSelectInput,
} = templatesOf(dynamicSelect)
const isMultiple = dynamicSelect.multiple
const buttonTemplate = isMultiple ? isMobile() ? mobileMultiSelectInput : multiSelectInput : singleSelectInput
const selectedOptionsVal = dynamicSelect.selectedOptions.map(dataObjectOfOption)
const data = {
isMultiple,
isSingle: !isMultiple,
selectedOptions: selectedOptionsVal,
selectedOption: selectedOptionsVal[0],
}
const button = applyTemplate(buttonTemplate, data)
button.querySelectorAll('slot[name="selected-option"]').forEach(slot => {
const data = JSON.parse(slot.dataset.value || '{}')
slot.replaceWith(applyTemplate(optionTemplate, data))
})
inputEl(dynamicSelect).replaceChildren(button)
}
/**
* @param {Event} event - input event
*/
function handleSearchInputChange (event) {
const { target } = event
if (!isSearchInputEl(target)) { return }
const dynamicSelect = getHostDynamicSelect(target)
dynamicSelect.searchFilter = target.value
}
/**
* @param {KeyboardEvent} event - input event
*/
function handleSearchInputKeyDown (event) {
const { target, code } = event
console.log('AAA')
const focusAttr = 'data-focused'
if (code === 'ArrowDown' || code === 'ArrowUp') {
const dynamicSelect = getHostDynamicSelect(target)
const dropdownOptions = [...dropdownOptionList(dynamicSelect)]
if (dropdownOptions.length <= 0) { return }
const focusIndex = dropdownOptions.findIndex(el => el.hasAttribute(focusAttr))
if (focusIndex >= 0) {
dropdownOptions[focusIndex].removeAttribute(focusAttr)
}
if (event.code === 'ArrowDown') {
const nextFocusIndex = focusIndex + 1 >= dropdownOptions.length ? 0 : focusIndex + 1
dropdownOptions[nextFocusIndex].setAttribute(focusAttr, '')
} else {
const previousFocusIndex = focusIndex <= 0 ? dropdownOptions.length - 1 : focusIndex - 1
dropdownOptions[previousFocusIndex].setAttribute(focusAttr, '')
}
} else if (code === 'Enter') {
const dynamicSelect = getHostDynamicSelect(target)
const dropdownOptions = [...dropdownOptionList(dynamicSelect)]
const focusedElement = dropdownOptions.find(el => el.hasAttribute('data-focused'))
if (focusedElement instanceof HTMLLIElement) {
const value = focusedElement.dataset.value
if (typeof value !== 'string') { return }
handleDropdownSelect(value, dynamicSelect)
}
}
}
/**
* @param {Event} event - input event
*/
function handleSelectValueButtonClick (event) {
const { target } = event
if (isDeselectButton(target)) {
const option = target.closest('.multiselect-option')
if (!(option instanceof HTMLElement)) { return }
const value = option.dataset.value
const dynamicSelect = getHostDynamicSelect(option)
const selectOption = dynamicSelect.selectedOptions.find(option => option.value === value)
if (selectOption == null) { return }
selectOption.selected = false
dynamicOptionsOf(dynamicSelect).toggleValue(selectOption.value, false)
updateButtonContent(dynamicSelect)
} else if (isClearButton(target)) {
const dynamicSelect = getHostDynamicSelect(target)
dynamicSelect.valueAsArray = []
updateButtonContent(dynamicSelect)
} else {
const dynamicSelect = getHostDynamicSelect(event.target)
dynamicSelect.open = !dynamicSelect.open
}
}
/**
* @param {Event} event - input event
*/
function handleDropdownToggle (event) {
const dynamicSelect = getHostDynamicSelect(event.target)
dynamicSelect.open = dropdownEl(dynamicSelect).matches(':popover-open,:open')
}
/**
* @param {PointerEvent} event - input event
*/
function handleDropdownPointerDown (event) {
const { target, currentTarget, clientX, clientY } = event
const isClickingOnDialog = target === currentTarget
if (isClickingOnDialog && currentTarget instanceof HTMLElement) {
const { left, right, bottom, top } = currentTarget.getBoundingClientRect()
if (clientX < left || clientX > right || clientY < top || clientY > bottom) {
getHostDynamicSelect(target).open = false
}
}
}
/**
* @param {Event} event - input event
*/
function handleDropdownOptionClick (event) {
const { target } = event
if (!(target instanceof Element)) { return }
const liTarget = target.closest('li.option-value:not(.option *)')
if (!(liTarget instanceof HTMLLIElement)) { return }
const value = liTarget.dataset.value
if (typeof value !== 'string') { return }
handleDropdownSelect(value, getHostDynamicSelect(liTarget))
}
/**
* @param {string} value - selectValue
* @param {DynamicSelect} dynamicSelect - Dynamic Select
*/
function handleDropdownSelect (value, dynamicSelect) {
if (dynamicSelect.multiple) {
if (isMobile()) {
const valueSet = selectedOptionWeakMap.get(dynamicSelect)
if (!valueSet) {
selectedOptionWeakMap.set(dynamicSelect, new Set(dynamicSelect.valueAsArray))
}
}
const valueSet = new Set(dynamicSelect.valueAsArray)
const toggledValue = valueSet.symmetricDifference(new Set([value]))
dynamicSelect.valueAsArray = [...toggledValue]
updateButtonContent(dynamicSelect)
updateDropdownContent(dynamicSelect)
updateDropdownPosition(dynamicSelect)
} else {
dynamicSelect.value = value
updateButtonContent(dynamicSelect)
updateDropdownContent(dynamicSelect)
dynamicSelect.open = false
inputEl(dynamicSelect).querySelector('button')?.focus()
}
}
/**
*
* @param {Event} event - click event
*/
function handleOkButtonClick (event) {
const { target } = event
const dynamicSelect = getHostDynamicSelect(target)
dynamicSelect.open = false
}
/**
*
* @param {Event} event - click event
*/
function handleCancelButtonClick (event) {
const { target } = event
const dynamicSelect = getHostDynamicSelect(target)
const valueSet = selectedOptionWeakMap.get(dynamicSelect) ?? new Set(dynamicSelect.valueAsArray)
if (valueSet) {
dynamicSelect.valueAsArray = [...valueSet]
}
updateButtonContent(dynamicSelect)
dynamicSelect.open = false
}
|