combobox.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.82
  5. */
  6. import { Component, h, Prop, State, Listen, Event, Element, Method, Watch, Host } from "@stencil/core";
  7. import { filter } from "../../utils/filter";
  8. import { debounce } from "lodash-es";
  9. import { createPopper, updatePopper, CSS as PopperCSS, popperMenuComputedPlacements, defaultMenuPlacement, filterComputedPlacements } from "../../utils/popper";
  10. import { guid } from "../../utils/guid";
  11. import { ComboboxChildSelector, ComboboxItem, ComboboxItemGroup, TEXT } from "./resources";
  12. import { getItemAncestors, getItemChildren, hasActiveChildren } from "./utils";
  13. import { connectLabel, disconnectLabel, getLabelText } from "../../utils/label";
  14. import { afterConnectDefaultValueSet, connectForm, disconnectForm, HiddenFormInputSlot, submitForm } from "../../utils/form";
  15. import { createObserver } from "../../utils/observers";
  16. import { updateHostInteraction } from "../../utils/interactive";
  17. import { toAriaBoolean } from "../../utils/dom";
  18. const isGroup = (el) => el.tagName === ComboboxItemGroup;
  19. const itemUidPrefix = "combobox-item-";
  20. const chipUidPrefix = "combobox-chip-";
  21. const labelUidPrefix = "combobox-label-";
  22. const listboxUidPrefix = "combobox-listbox-";
  23. const inputUidPrefix = "combobox-input-";
  24. /**
  25. * @slot - A slot for adding `calcite-combobox-item`s.
  26. */
  27. export class Combobox {
  28. constructor() {
  29. //--------------------------------------------------------------------------
  30. //
  31. // Public Properties
  32. //
  33. //--------------------------------------------------------------------------
  34. /** Opens or closes the combobox */
  35. this.active = false;
  36. /** Disable combobox input */
  37. this.disabled = false;
  38. /** Specify the maximum number of combobox items (including nested children) to display before showing the scroller */
  39. this.maxItems = 0;
  40. /** Describes the type of positioning to use for the overlaid content. If your element is in a fixed container, use the 'fixed' value. */
  41. this.overlayPositioning = "absolute";
  42. /**
  43. * When true, makes the component required for form-submission.
  44. *
  45. * @internal
  46. */
  47. this.required = false;
  48. /** specify the selection mode
  49. * - multi: allow any number of selected items (default)
  50. * - single: only one selection)
  51. * - ancestors: like multi, but show ancestors of selected items as selected, only deepest children shown in chips
  52. */
  53. this.selectionMode = "multi";
  54. /** Specify the scale of the combobox, defaults to m */
  55. this.scale = "m";
  56. /** The value(s) of the selectedItem(s) */
  57. this.value = null;
  58. /** string to override the English "Remove tag" text for when an item is selected.
  59. * @default "Remove tag"
  60. */
  61. this.intlRemoveTag = TEXT.removeTag;
  62. this.internalValueChangeFlag = false;
  63. this.items = [];
  64. this.groupItems = [];
  65. this.selectedItems = [];
  66. this.visibleItems = [];
  67. this.activeItemIndex = -1;
  68. this.activeChipIndex = -1;
  69. this.activeDescendant = "";
  70. this.text = "";
  71. this.textInput = null;
  72. this.mutationObserver = createObserver("mutation", () => this.updateItems());
  73. this.resizeObserver = createObserver("resize", () => this.setMaxScrollerHeight());
  74. this.guid = guid();
  75. this.inputHeight = 0;
  76. this.ignoreSelectedEventsFlag = false;
  77. this.activeTransitionProp = "opacity";
  78. // --------------------------------------------------------------------------
  79. //
  80. // Private Methods
  81. //
  82. // --------------------------------------------------------------------------
  83. this.setFilteredPlacements = () => {
  84. const { el, flipPlacements } = this;
  85. this.filteredFlipPlacements = flipPlacements
  86. ? filterComputedPlacements(flipPlacements, el)
  87. : null;
  88. };
  89. this.getValue = () => {
  90. const items = this.selectedItems.map((item) => { var _a; return (_a = item === null || item === void 0 ? void 0 : item.value) === null || _a === void 0 ? void 0 : _a.toString(); });
  91. return (items === null || items === void 0 ? void 0 : items.length) ? (items.length > 1 ? items : items[0]) : "";
  92. };
  93. this.onLabelClick = () => {
  94. this.setFocus();
  95. };
  96. this.keydownHandler = (event) => {
  97. const { key } = event;
  98. switch (key) {
  99. case "Tab":
  100. this.activeChipIndex = -1;
  101. this.activeItemIndex = -1;
  102. if (this.allowCustomValues && this.text) {
  103. this.addCustomChip(this.text, true);
  104. event.preventDefault();
  105. }
  106. else if (this.active) {
  107. this.active = false;
  108. event.preventDefault();
  109. }
  110. break;
  111. case "ArrowLeft":
  112. this.previousChip();
  113. break;
  114. case "ArrowRight":
  115. this.nextChip();
  116. break;
  117. case "ArrowUp":
  118. this.shiftActiveItemIndex(-1);
  119. if (!this.comboboxInViewport()) {
  120. this.el.scrollIntoView();
  121. }
  122. break;
  123. case "ArrowDown":
  124. if (!this.active) {
  125. event.preventDefault();
  126. this.active = true;
  127. }
  128. this.shiftActiveItemIndex(1);
  129. if (!this.comboboxInViewport()) {
  130. this.el.scrollIntoView();
  131. }
  132. break;
  133. case " ":
  134. if (!this.textInput.value) {
  135. event.preventDefault();
  136. this.active = true;
  137. this.shiftActiveItemIndex(1);
  138. }
  139. break;
  140. case "Home":
  141. if (this.active) {
  142. event.preventDefault();
  143. }
  144. this.updateActiveItemIndex(0);
  145. this.scrollToActiveItem();
  146. if (!this.comboboxInViewport()) {
  147. this.el.scrollIntoView();
  148. }
  149. break;
  150. case "End":
  151. if (this.active) {
  152. event.preventDefault();
  153. }
  154. this.updateActiveItemIndex(this.visibleItems.length - 1);
  155. this.scrollToActiveItem();
  156. if (!this.comboboxInViewport()) {
  157. this.el.scrollIntoView();
  158. }
  159. break;
  160. case "Escape":
  161. this.active = false;
  162. break;
  163. case "Enter":
  164. if (this.activeItemIndex > -1) {
  165. this.toggleSelection(this.visibleItems[this.activeItemIndex]);
  166. }
  167. else if (this.activeChipIndex > -1) {
  168. this.removeActiveChip();
  169. }
  170. else if (this.allowCustomValues && this.text) {
  171. this.addCustomChip(this.text, true);
  172. }
  173. else if (!event.defaultPrevented) {
  174. submitForm(this);
  175. }
  176. break;
  177. case "Delete":
  178. case "Backspace":
  179. if (this.activeChipIndex > -1) {
  180. this.removeActiveChip();
  181. }
  182. else if (!this.text && this.isMulti()) {
  183. this.removeLastChip();
  184. }
  185. break;
  186. }
  187. };
  188. this.toggleCloseEnd = () => {
  189. this.active = false;
  190. this.el.removeEventListener("calciteComboboxClose", this.toggleCloseEnd);
  191. };
  192. this.toggleOpenEnd = () => {
  193. this.active = true;
  194. this.el.removeEventListener("calciteComboboxOpen", this.toggleOpenEnd);
  195. };
  196. this.transitionEnd = (event) => {
  197. if (event.propertyName === this.activeTransitionProp) {
  198. this.active ? this.calciteComboboxOpen.emit() : this.calciteComboboxClose.emit();
  199. }
  200. };
  201. this.setMaxScrollerHeight = () => {
  202. const { active, listContainerEl } = this;
  203. if (!listContainerEl || !active) {
  204. return;
  205. }
  206. this.reposition();
  207. const maxScrollerHeight = this.getMaxScrollerHeight();
  208. listContainerEl.style.maxHeight = maxScrollerHeight > 0 ? `${maxScrollerHeight}px` : "";
  209. this.reposition();
  210. };
  211. this.calciteChipDismissHandler = (event, comboboxItem) => {
  212. this.active = false;
  213. const selection = this.items.find((item) => item === comboboxItem);
  214. if (selection) {
  215. this.toggleSelection(selection, false);
  216. }
  217. this.calciteComboboxChipDismiss.emit(event.detail);
  218. };
  219. this.clickHandler = (event) => {
  220. if (event.composedPath().some((node) => node.tagName === "CALCITE-CHIP")) {
  221. return;
  222. }
  223. this.active = !this.active;
  224. this.updateActiveItemIndex(0);
  225. this.setFocus();
  226. };
  227. this.setInactiveIfNotContained = (event) => {
  228. const composedPath = event.composedPath();
  229. if (!this.active || composedPath.includes(this.el) || composedPath.includes(this.referenceEl)) {
  230. return;
  231. }
  232. if (this.allowCustomValues && this.text.trim().length) {
  233. this.addCustomChip(this.text);
  234. }
  235. if (this.selectionMode === "single") {
  236. if (this.textInput) {
  237. this.textInput.value = "";
  238. }
  239. this.text = "";
  240. this.filterItems("");
  241. this.updateActiveItemIndex(-1);
  242. }
  243. this.active = false;
  244. };
  245. this.setMenuEl = (el) => {
  246. this.menuEl = el;
  247. };
  248. this.setListContainerEl = (el) => {
  249. this.resizeObserver.observe(el);
  250. this.listContainerEl = el;
  251. };
  252. this.setReferenceEl = (el) => {
  253. this.referenceEl = el;
  254. };
  255. this.inputHandler = (event) => {
  256. const value = event.target.value;
  257. this.text = value;
  258. this.filterItems(value);
  259. if (value) {
  260. this.activeChipIndex = -1;
  261. }
  262. };
  263. this.filterItems = (() => {
  264. const find = (item, filteredData) => item &&
  265. filteredData.some(({ label, value }) => {
  266. if (isGroup(item)) {
  267. return value === item.label;
  268. }
  269. return (value === item.textLabel ||
  270. value === item.value ||
  271. label === item.textLabel ||
  272. label === item.value);
  273. });
  274. return debounce((text) => {
  275. const filteredData = filter(this.data, text);
  276. const items = this.getCombinedItems();
  277. items.forEach((item) => {
  278. const hidden = !find(item, filteredData);
  279. item.hidden = hidden;
  280. const [parent, grandparent] = item.ancestors;
  281. if (find(parent, filteredData) || find(grandparent, filteredData)) {
  282. item.hidden = false;
  283. }
  284. if (!hidden) {
  285. item.ancestors.forEach((ancestor) => (ancestor.hidden = false));
  286. }
  287. });
  288. this.visibleItems = this.getVisibleItems();
  289. this.calciteComboboxFilterChange.emit({ visibleItems: [...this.visibleItems], text: text });
  290. }, 100);
  291. })();
  292. this.internalCalciteLookupChangeEvent = () => {
  293. this.calciteLookupChange.emit(this.selectedItems);
  294. };
  295. this.emitCalciteLookupChange = debounce(this.internalCalciteLookupChangeEvent, 0);
  296. this.internalComboboxChangeEvent = () => {
  297. const { selectedItems } = this;
  298. this.calciteComboboxChange.emit({ selectedItems });
  299. };
  300. this.emitComboboxChange = debounce(this.internalComboboxChangeEvent, 0);
  301. this.updateItems = () => {
  302. this.items = this.getItems();
  303. this.groupItems = this.getGroupItems();
  304. this.data = this.getData();
  305. this.selectedItems = this.getSelectedItems();
  306. this.visibleItems = this.getVisibleItems();
  307. this.needsIcon = this.getNeedsIcon();
  308. if (!this.allowCustomValues) {
  309. this.setMaxScrollerHeight();
  310. }
  311. };
  312. this.scrollToActiveItem = () => {
  313. const activeItem = this.visibleItems[this.activeItemIndex];
  314. const height = this.calculateSingleItemHeight(activeItem);
  315. const { offsetHeight, scrollTop } = this.listContainerEl;
  316. if (offsetHeight + scrollTop < activeItem.offsetTop + height) {
  317. this.listContainerEl.scrollTop = activeItem.offsetTop - offsetHeight + height;
  318. }
  319. else if (activeItem.offsetTop < scrollTop) {
  320. this.listContainerEl.scrollTop = activeItem.offsetTop;
  321. }
  322. };
  323. this.comboboxFocusHandler = () => {
  324. var _a;
  325. (_a = this.textInput) === null || _a === void 0 ? void 0 : _a.focus();
  326. };
  327. this.comboboxBlurHandler = (event) => {
  328. this.setInactiveIfNotContained(event);
  329. };
  330. }
  331. activeHandler() {
  332. if (this.disabled) {
  333. this.active = false;
  334. return;
  335. }
  336. this.reposition();
  337. }
  338. handleDisabledChange(value) {
  339. if (!value) {
  340. this.active = false;
  341. }
  342. }
  343. maxItemsHandler() {
  344. this.setMaxScrollerHeight();
  345. }
  346. valueHandler(value) {
  347. if (!this.internalValueChangeFlag) {
  348. const items = this.getItems();
  349. if (Array.isArray(value)) {
  350. items.forEach((item) => (item.selected = value.includes(item.value)));
  351. }
  352. else if (value) {
  353. items.forEach((item) => (item.selected = value === item.value));
  354. }
  355. else {
  356. items.forEach((item) => (item.selected = false));
  357. }
  358. this.updateItems();
  359. }
  360. }
  361. flipPlacementsHandler() {
  362. this.setFilteredPlacements();
  363. }
  364. //--------------------------------------------------------------------------
  365. //
  366. // Event Listeners
  367. //
  368. //--------------------------------------------------------------------------
  369. documentClickHandler(event) {
  370. this.setInactiveIfNotContained(event);
  371. }
  372. calciteComboboxItemChangeHandler(event) {
  373. if (this.ignoreSelectedEventsFlag) {
  374. return;
  375. }
  376. const target = event.target;
  377. const newIndex = this.visibleItems.indexOf(target);
  378. this.updateActiveItemIndex(newIndex);
  379. this.toggleSelection(target, target.selected);
  380. }
  381. //--------------------------------------------------------------------------
  382. //
  383. // Public Methods
  384. //
  385. //--------------------------------------------------------------------------
  386. /** Updates the position of the component. */
  387. async reposition() {
  388. const { popper, menuEl } = this;
  389. const modifiers = this.getModifiers();
  390. popper
  391. ? await updatePopper({
  392. el: menuEl,
  393. modifiers,
  394. placement: defaultMenuPlacement,
  395. popper
  396. })
  397. : this.createPopper();
  398. }
  399. /** Sets focus on the component. */
  400. async setFocus() {
  401. var _a;
  402. (_a = this.textInput) === null || _a === void 0 ? void 0 : _a.focus();
  403. this.activeChipIndex = -1;
  404. this.activeItemIndex = -1;
  405. }
  406. // --------------------------------------------------------------------------
  407. //
  408. // Lifecycle
  409. //
  410. // --------------------------------------------------------------------------
  411. connectedCallback() {
  412. var _a;
  413. this.internalValueChangeFlag = true;
  414. this.value = this.getValue();
  415. this.internalValueChangeFlag = false;
  416. (_a = this.mutationObserver) === null || _a === void 0 ? void 0 : _a.observe(this.el, { childList: true, subtree: true });
  417. this.createPopper();
  418. connectLabel(this);
  419. connectForm(this);
  420. this.setFilteredPlacements();
  421. }
  422. componentWillLoad() {
  423. this.updateItems();
  424. }
  425. componentDidLoad() {
  426. afterConnectDefaultValueSet(this, this.getValue());
  427. }
  428. componentDidRender() {
  429. if (this.el.offsetHeight !== this.inputHeight) {
  430. this.reposition();
  431. this.inputHeight = this.el.offsetHeight;
  432. }
  433. updateHostInteraction(this);
  434. }
  435. disconnectedCallback() {
  436. var _a, _b;
  437. (_a = this.mutationObserver) === null || _a === void 0 ? void 0 : _a.disconnect();
  438. (_b = this.resizeObserver) === null || _b === void 0 ? void 0 : _b.disconnect();
  439. this.destroyPopper();
  440. disconnectLabel(this);
  441. disconnectForm(this);
  442. }
  443. selectedItemsHandler() {
  444. this.internalValueChangeFlag = true;
  445. this.value = this.getValue();
  446. this.internalValueChangeFlag = false;
  447. }
  448. /** when search text is cleared, reset active to */
  449. textHandler() {
  450. this.updateActiveItemIndex(-1);
  451. }
  452. comboboxInViewport() {
  453. const bounding = this.el.getBoundingClientRect();
  454. return (bounding.top >= 0 &&
  455. bounding.left >= 0 &&
  456. bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
  457. bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight));
  458. }
  459. getModifiers() {
  460. const flipModifier = {
  461. name: "flip",
  462. enabled: true
  463. };
  464. flipModifier.options = {
  465. fallbackPlacements: this.filteredFlipPlacements || popperMenuComputedPlacements
  466. };
  467. const eventListenerModifier = {
  468. name: "eventListeners",
  469. enabled: this.active
  470. };
  471. return [flipModifier, eventListenerModifier];
  472. }
  473. createPopper() {
  474. this.destroyPopper();
  475. const { menuEl, referenceEl, overlayPositioning } = this;
  476. const modifiers = this.getModifiers();
  477. this.popper = createPopper({
  478. el: menuEl,
  479. modifiers,
  480. overlayPositioning,
  481. placement: defaultMenuPlacement,
  482. referenceEl
  483. });
  484. }
  485. destroyPopper() {
  486. const { popper } = this;
  487. if (popper) {
  488. popper.destroy();
  489. }
  490. this.popper = null;
  491. }
  492. getMaxScrollerHeight() {
  493. const items = this.getCombinedItems().filter((item) => !item.hidden);
  494. const { maxItems } = this;
  495. let itemsToProcess = 0;
  496. let maxScrollerHeight = 0;
  497. if (items.length > maxItems) {
  498. items.forEach((item) => {
  499. if (itemsToProcess < maxItems && maxItems > 0) {
  500. const height = this.calculateSingleItemHeight(item);
  501. if (height > 0) {
  502. maxScrollerHeight += height;
  503. itemsToProcess++;
  504. }
  505. }
  506. });
  507. }
  508. return maxScrollerHeight;
  509. }
  510. calculateSingleItemHeight(item) {
  511. let height = item.offsetHeight;
  512. // if item has children items, don't count their height twice
  513. const children = Array.from(item.querySelectorAll(ComboboxChildSelector));
  514. children
  515. .map((child) => child === null || child === void 0 ? void 0 : child.offsetHeight)
  516. .forEach((offsetHeight) => {
  517. height -= offsetHeight;
  518. });
  519. return height;
  520. }
  521. getCombinedItems() {
  522. return [...this.groupItems, ...this.items];
  523. }
  524. toggleSelection(item, value = !item.selected) {
  525. if (!item) {
  526. return;
  527. }
  528. if (this.isMulti()) {
  529. item.selected = value;
  530. this.updateAncestors(item);
  531. this.selectedItems = this.getSelectedItems();
  532. this.emitCalciteLookupChange();
  533. this.emitComboboxChange();
  534. this.resetText();
  535. this.filterItems("");
  536. }
  537. else {
  538. this.ignoreSelectedEventsFlag = true;
  539. this.items.forEach((el) => (el.selected = el === item ? value : false));
  540. this.ignoreSelectedEventsFlag = false;
  541. this.selectedItems = this.getSelectedItems();
  542. this.emitComboboxChange();
  543. if (this.textInput) {
  544. this.textInput.value = item.textLabel;
  545. }
  546. this.active = false;
  547. this.updateActiveItemIndex(-1);
  548. this.resetText();
  549. this.filterItems("");
  550. }
  551. }
  552. updateAncestors(item) {
  553. if (this.selectionMode !== "ancestors") {
  554. return;
  555. }
  556. const ancestors = getItemAncestors(item);
  557. const children = getItemChildren(item);
  558. if (item.selected) {
  559. ancestors.forEach((el) => {
  560. el.selected = true;
  561. });
  562. }
  563. else {
  564. children.forEach((el) => (el.selected = false));
  565. [...ancestors].forEach((el) => {
  566. if (!hasActiveChildren(el)) {
  567. el.selected = false;
  568. }
  569. });
  570. }
  571. }
  572. getVisibleItems() {
  573. return this.items.filter((item) => !item.hidden);
  574. }
  575. getSelectedItems() {
  576. if (!this.isMulti()) {
  577. const match = this.items.find(({ selected }) => selected);
  578. return match ? [match] : [];
  579. }
  580. return (this.items
  581. .filter((item) => item.selected && (this.selectionMode !== "ancestors" || !hasActiveChildren(item)))
  582. /** Preserve order of entered tags */
  583. .sort((a, b) => {
  584. const aIdx = this.selectedItems.indexOf(a);
  585. const bIdx = this.selectedItems.indexOf(b);
  586. if (aIdx > -1 && bIdx > -1) {
  587. return aIdx - bIdx;
  588. }
  589. return bIdx - aIdx;
  590. }));
  591. }
  592. getData() {
  593. return this.items.map((item) => ({
  594. constant: item.constant,
  595. value: item.value,
  596. label: item.textLabel
  597. }));
  598. }
  599. getNeedsIcon() {
  600. return this.selectionMode === "single" && this.items.some((item) => item.icon);
  601. }
  602. resetText() {
  603. if (this.textInput) {
  604. this.textInput.value = "";
  605. }
  606. this.text = "";
  607. }
  608. getItems() {
  609. const items = Array.from(this.el.querySelectorAll(ComboboxItem));
  610. return items.filter((item) => !item.disabled);
  611. }
  612. getGroupItems() {
  613. return Array.from(this.el.querySelectorAll(ComboboxItemGroup));
  614. }
  615. addCustomChip(value, focus) {
  616. const existingItem = this.items.find((el) => el.textLabel === value);
  617. if (existingItem) {
  618. this.toggleSelection(existingItem, true);
  619. }
  620. else {
  621. if (!this.isMulti()) {
  622. this.toggleSelection(this.selectedItems[this.selectedItems.length - 1], false);
  623. }
  624. const item = document.createElement(ComboboxItem);
  625. item.value = value;
  626. item.textLabel = value;
  627. item.selected = true;
  628. this.el.appendChild(item);
  629. this.resetText();
  630. if (focus) {
  631. this.setFocus();
  632. }
  633. this.updateItems();
  634. this.filterItems("");
  635. this.emitCalciteLookupChange();
  636. this.emitComboboxChange();
  637. }
  638. }
  639. removeActiveChip() {
  640. this.toggleSelection(this.selectedItems[this.activeChipIndex], false);
  641. this.setFocus();
  642. }
  643. removeLastChip() {
  644. this.toggleSelection(this.selectedItems[this.selectedItems.length - 1], false);
  645. this.setFocus();
  646. }
  647. previousChip() {
  648. if (this.text) {
  649. return;
  650. }
  651. const length = this.selectedItems.length - 1;
  652. const active = this.activeChipIndex;
  653. this.activeChipIndex = active === -1 ? length : Math.max(active - 1, 0);
  654. this.updateActiveItemIndex(-1);
  655. this.focusChip();
  656. }
  657. nextChip() {
  658. if (this.text || this.activeChipIndex === -1) {
  659. return;
  660. }
  661. const last = this.selectedItems.length - 1;
  662. const newIndex = this.activeChipIndex + 1;
  663. if (newIndex > last) {
  664. this.activeChipIndex = -1;
  665. this.setFocus();
  666. }
  667. else {
  668. this.activeChipIndex = newIndex;
  669. this.focusChip();
  670. }
  671. this.updateActiveItemIndex(-1);
  672. }
  673. focusChip() {
  674. var _a;
  675. const guid = (_a = this.selectedItems[this.activeChipIndex]) === null || _a === void 0 ? void 0 : _a.guid;
  676. const chip = guid
  677. ? this.referenceEl.querySelector(`#${chipUidPrefix}${guid}`)
  678. : null;
  679. chip === null || chip === void 0 ? void 0 : chip.setFocus();
  680. }
  681. shiftActiveItemIndex(delta) {
  682. const { length } = this.visibleItems;
  683. const newIndex = (this.activeItemIndex + length + delta) % length;
  684. this.updateActiveItemIndex(newIndex);
  685. this.scrollToActiveItem();
  686. }
  687. updateActiveItemIndex(index) {
  688. var _a;
  689. this.activeItemIndex = index;
  690. let activeDescendant = null;
  691. this.visibleItems.forEach((el, i) => {
  692. if (i === index) {
  693. el.active = true;
  694. activeDescendant = el.guid;
  695. }
  696. else {
  697. el.active = false;
  698. }
  699. });
  700. this.activeDescendant = activeDescendant;
  701. if (this.activeItemIndex > -1) {
  702. this.activeChipIndex = -1;
  703. (_a = this.textInput) === null || _a === void 0 ? void 0 : _a.focus();
  704. }
  705. }
  706. isMulti() {
  707. return this.selectionMode !== "single";
  708. }
  709. //--------------------------------------------------------------------------
  710. //
  711. // Render Methods
  712. //
  713. //--------------------------------------------------------------------------
  714. renderChips() {
  715. const { activeChipIndex, scale, selectionMode, intlRemoveTag } = this;
  716. return this.selectedItems.map((item, i) => {
  717. const chipClasses = {
  718. chip: true,
  719. "chip--active": activeChipIndex === i
  720. };
  721. const ancestors = [...getItemAncestors(item)].reverse();
  722. const pathLabel = [...ancestors, item].map((el) => el.textLabel);
  723. const label = selectionMode !== "ancestors" ? item.textLabel : pathLabel.join(" / ");
  724. return (h("calcite-chip", { class: chipClasses, dismissLabel: intlRemoveTag, dismissible: true, icon: item.icon, id: item.guid ? `${chipUidPrefix}${item.guid}` : null, key: item.textLabel, onCalciteChipDismiss: (event) => this.calciteChipDismissHandler(event, item), scale: scale, title: label, value: item.value }, label));
  725. });
  726. }
  727. renderInput() {
  728. const { guid, active, disabled, placeholder, selectionMode, needsIcon, selectedItems } = this;
  729. const single = selectionMode === "single";
  730. const selectedItem = selectedItems[0];
  731. const showLabel = !active && single && !!selectedItem;
  732. return (h("span", { class: {
  733. "input-wrap": true,
  734. "input-wrap--single": single
  735. } },
  736. showLabel && (h("span", { class: {
  737. label: true,
  738. "label--spaced": needsIcon
  739. }, key: "label" }, selectedItem.textLabel)),
  740. h("input", { "aria-activedescendant": this.activeDescendant, "aria-autocomplete": "list", "aria-controls": `${listboxUidPrefix}${guid}`, "aria-label": getLabelText(this), class: {
  741. input: true,
  742. "input--single": true,
  743. "input--transparent": this.activeChipIndex > -1,
  744. "input--hidden": showLabel,
  745. "input--icon": single && needsIcon
  746. }, disabled: disabled, id: `${inputUidPrefix}${guid}`, key: "input", onBlur: this.comboboxBlurHandler, onFocus: this.comboboxFocusHandler, onInput: this.inputHandler, placeholder: placeholder, ref: (el) => (this.textInput = el), type: "text" })));
  747. }
  748. renderListBoxOptions() {
  749. return this.visibleItems.map((item) => (h("li", { "aria-selected": toAriaBoolean(item.selected), id: item.guid ? `${itemUidPrefix}${item.guid}` : null, role: "option", tabindex: "-1" }, item.textLabel)));
  750. }
  751. renderPopperContainer() {
  752. const { active, setMenuEl, setListContainerEl } = this;
  753. const classes = {
  754. "list-container": true,
  755. [PopperCSS.animation]: true,
  756. [PopperCSS.animationActive]: active
  757. };
  758. return (h("div", { "aria-hidden": "true", class: { "popper-container": true, "popper-container--active": active }, ref: setMenuEl },
  759. h("div", { class: classes, onTransitionEnd: this.transitionEnd, ref: setListContainerEl },
  760. h("ul", { class: { list: true, "list--hide": !active } },
  761. h("slot", null)))));
  762. }
  763. renderIconStart() {
  764. const { selectionMode, needsIcon, selectedItems } = this;
  765. const selectedItem = selectedItems[0];
  766. return (selectionMode === "single" &&
  767. needsIcon && (h("span", { class: "icon-start" }, (selectedItem === null || selectedItem === void 0 ? void 0 : selectedItem.icon) && (h("calcite-icon", { class: "selected-icon", icon: selectedItem.icon, scale: "s" })))));
  768. }
  769. renderIconEnd() {
  770. const { active } = this;
  771. return (h("span", { class: "icon-end" },
  772. h("calcite-icon", { icon: active ? "chevron-up" : "chevron-down", scale: "s" })));
  773. }
  774. render() {
  775. const { active, guid, label } = this;
  776. const single = this.selectionMode === "single";
  777. return (h(Host, { onKeyDown: this.keydownHandler },
  778. h("div", { "aria-autocomplete": "list", "aria-expanded": toAriaBoolean(active), "aria-haspopup": "listbox", "aria-labelledby": `${labelUidPrefix}${guid}`, "aria-owns": `${listboxUidPrefix}${guid}`, class: {
  779. wrapper: true,
  780. "wrapper--single": single || !this.selectedItems.length,
  781. "wrapper--active": active
  782. }, onClick: this.clickHandler, ref: this.setReferenceEl, role: "combobox" },
  783. h("div", { class: "grid-input" },
  784. this.renderIconStart(),
  785. !single && this.renderChips(),
  786. h("label", { class: "screen-readers-only", htmlFor: `${inputUidPrefix}${guid}`, id: `${labelUidPrefix}${guid}` }, label),
  787. this.renderInput()),
  788. this.renderIconEnd()),
  789. h("ul", { "aria-labelledby": `${labelUidPrefix}${guid}`, "aria-multiselectable": "true", class: "screen-readers-only", id: `${listboxUidPrefix}${guid}`, role: "listbox", tabIndex: -1 }, this.renderListBoxOptions()),
  790. this.renderPopperContainer(),
  791. h(HiddenFormInputSlot, { component: this })));
  792. }
  793. static get is() { return "calcite-combobox"; }
  794. static get encapsulation() { return "shadow"; }
  795. static get originalStyleUrls() { return {
  796. "$": ["combobox.scss"]
  797. }; }
  798. static get styleUrls() { return {
  799. "$": ["combobox.css"]
  800. }; }
  801. static get properties() { return {
  802. "active": {
  803. "type": "boolean",
  804. "mutable": true,
  805. "complexType": {
  806. "original": "boolean",
  807. "resolved": "boolean",
  808. "references": {}
  809. },
  810. "required": false,
  811. "optional": false,
  812. "docs": {
  813. "tags": [],
  814. "text": "Opens or closes the combobox"
  815. },
  816. "attribute": "active",
  817. "reflect": true,
  818. "defaultValue": "false"
  819. },
  820. "disabled": {
  821. "type": "boolean",
  822. "mutable": false,
  823. "complexType": {
  824. "original": "boolean",
  825. "resolved": "boolean",
  826. "references": {}
  827. },
  828. "required": false,
  829. "optional": false,
  830. "docs": {
  831. "tags": [],
  832. "text": "Disable combobox input"
  833. },
  834. "attribute": "disabled",
  835. "reflect": true,
  836. "defaultValue": "false"
  837. },
  838. "label": {
  839. "type": "string",
  840. "mutable": false,
  841. "complexType": {
  842. "original": "string",
  843. "resolved": "string",
  844. "references": {}
  845. },
  846. "required": true,
  847. "optional": false,
  848. "docs": {
  849. "tags": [],
  850. "text": "Aria label for combobox (required)"
  851. },
  852. "attribute": "label",
  853. "reflect": false
  854. },
  855. "placeholder": {
  856. "type": "string",
  857. "mutable": false,
  858. "complexType": {
  859. "original": "string",
  860. "resolved": "string",
  861. "references": {}
  862. },
  863. "required": false,
  864. "optional": true,
  865. "docs": {
  866. "tags": [],
  867. "text": "Placeholder text for input"
  868. },
  869. "attribute": "placeholder",
  870. "reflect": false
  871. },
  872. "maxItems": {
  873. "type": "number",
  874. "mutable": false,
  875. "complexType": {
  876. "original": "number",
  877. "resolved": "number",
  878. "references": {}
  879. },
  880. "required": false,
  881. "optional": false,
  882. "docs": {
  883. "tags": [],
  884. "text": "Specify the maximum number of combobox items (including nested children) to display before showing the scroller"
  885. },
  886. "attribute": "max-items",
  887. "reflect": false,
  888. "defaultValue": "0"
  889. },
  890. "name": {
  891. "type": "string",
  892. "mutable": false,
  893. "complexType": {
  894. "original": "string",
  895. "resolved": "string",
  896. "references": {}
  897. },
  898. "required": false,
  899. "optional": false,
  900. "docs": {
  901. "tags": [],
  902. "text": "The name of the switch input"
  903. },
  904. "attribute": "name",
  905. "reflect": true
  906. },
  907. "allowCustomValues": {
  908. "type": "boolean",
  909. "mutable": false,
  910. "complexType": {
  911. "original": "boolean",
  912. "resolved": "boolean",
  913. "references": {}
  914. },
  915. "required": false,
  916. "optional": false,
  917. "docs": {
  918. "tags": [],
  919. "text": "Allow entry of custom values which are not in the original set of items"
  920. },
  921. "attribute": "allow-custom-values",
  922. "reflect": false
  923. },
  924. "overlayPositioning": {
  925. "type": "string",
  926. "mutable": false,
  927. "complexType": {
  928. "original": "OverlayPositioning",
  929. "resolved": "\"absolute\" | \"fixed\"",
  930. "references": {
  931. "OverlayPositioning": {
  932. "location": "import",
  933. "path": "../../utils/popper"
  934. }
  935. }
  936. },
  937. "required": false,
  938. "optional": false,
  939. "docs": {
  940. "tags": [],
  941. "text": "Describes the type of positioning to use for the overlaid content. If your element is in a fixed container, use the 'fixed' value."
  942. },
  943. "attribute": "overlay-positioning",
  944. "reflect": false,
  945. "defaultValue": "\"absolute\""
  946. },
  947. "required": {
  948. "type": "boolean",
  949. "mutable": false,
  950. "complexType": {
  951. "original": "boolean",
  952. "resolved": "boolean",
  953. "references": {}
  954. },
  955. "required": false,
  956. "optional": false,
  957. "docs": {
  958. "tags": [{
  959. "name": "internal",
  960. "text": undefined
  961. }],
  962. "text": "When true, makes the component required for form-submission."
  963. },
  964. "attribute": "required",
  965. "reflect": false,
  966. "defaultValue": "false"
  967. },
  968. "selectionMode": {
  969. "type": "string",
  970. "mutable": false,
  971. "complexType": {
  972. "original": "ComboboxSelectionMode",
  973. "resolved": "\"ancestors\" | \"multi\" | \"single\"",
  974. "references": {
  975. "ComboboxSelectionMode": {
  976. "location": "import",
  977. "path": "./interfaces"
  978. }
  979. }
  980. },
  981. "required": false,
  982. "optional": false,
  983. "docs": {
  984. "tags": [],
  985. "text": "specify the selection mode\n- multi: allow any number of selected items (default)\n- single: only one selection)\n- ancestors: like multi, but show ancestors of selected items as selected, only deepest children shown in chips"
  986. },
  987. "attribute": "selection-mode",
  988. "reflect": true,
  989. "defaultValue": "\"multi\""
  990. },
  991. "scale": {
  992. "type": "string",
  993. "mutable": false,
  994. "complexType": {
  995. "original": "Scale",
  996. "resolved": "\"l\" | \"m\" | \"s\"",
  997. "references": {
  998. "Scale": {
  999. "location": "import",
  1000. "path": "../interfaces"
  1001. }
  1002. }
  1003. },
  1004. "required": false,
  1005. "optional": false,
  1006. "docs": {
  1007. "tags": [],
  1008. "text": "Specify the scale of the combobox, defaults to m"
  1009. },
  1010. "attribute": "scale",
  1011. "reflect": true,
  1012. "defaultValue": "\"m\""
  1013. },
  1014. "value": {
  1015. "type": "string",
  1016. "mutable": true,
  1017. "complexType": {
  1018. "original": "string | string[]",
  1019. "resolved": "string | string[]",
  1020. "references": {}
  1021. },
  1022. "required": false,
  1023. "optional": false,
  1024. "docs": {
  1025. "tags": [],
  1026. "text": "The value(s) of the selectedItem(s)"
  1027. },
  1028. "attribute": "value",
  1029. "reflect": false,
  1030. "defaultValue": "null"
  1031. },
  1032. "intlRemoveTag": {
  1033. "type": "string",
  1034. "mutable": false,
  1035. "complexType": {
  1036. "original": "string",
  1037. "resolved": "string",
  1038. "references": {}
  1039. },
  1040. "required": false,
  1041. "optional": false,
  1042. "docs": {
  1043. "tags": [{
  1044. "name": "default",
  1045. "text": "\"Remove tag\""
  1046. }],
  1047. "text": "string to override the English \"Remove tag\" text for when an item is selected."
  1048. },
  1049. "attribute": "intl-remove-tag",
  1050. "reflect": false,
  1051. "defaultValue": "TEXT.removeTag"
  1052. },
  1053. "flipPlacements": {
  1054. "type": "unknown",
  1055. "mutable": false,
  1056. "complexType": {
  1057. "original": "ComputedPlacement[]",
  1058. "resolved": "ComputedPlacement[]",
  1059. "references": {
  1060. "ComputedPlacement": {
  1061. "location": "import",
  1062. "path": "../../utils/popper"
  1063. }
  1064. }
  1065. },
  1066. "required": false,
  1067. "optional": true,
  1068. "docs": {
  1069. "tags": [],
  1070. "text": "Defines the available placements that can be used when a flip occurs."
  1071. }
  1072. }
  1073. }; }
  1074. static get states() { return {
  1075. "items": {},
  1076. "groupItems": {},
  1077. "selectedItems": {},
  1078. "visibleItems": {},
  1079. "needsIcon": {},
  1080. "activeItemIndex": {},
  1081. "activeChipIndex": {},
  1082. "activeDescendant": {},
  1083. "text": {}
  1084. }; }
  1085. static get events() { return [{
  1086. "method": "calciteLookupChange",
  1087. "name": "calciteLookupChange",
  1088. "bubbles": true,
  1089. "cancelable": true,
  1090. "composed": true,
  1091. "docs": {
  1092. "tags": [{
  1093. "name": "deprecated",
  1094. "text": "use calciteComboboxChange instead"
  1095. }],
  1096. "text": "Called when the selected items set changes"
  1097. },
  1098. "complexType": {
  1099. "original": "HTMLCalciteComboboxItemElement[]",
  1100. "resolved": "HTMLCalciteComboboxItemElement[]",
  1101. "references": {
  1102. "HTMLCalciteComboboxItemElement": {
  1103. "location": "global"
  1104. }
  1105. }
  1106. }
  1107. }, {
  1108. "method": "calciteComboboxChange",
  1109. "name": "calciteComboboxChange",
  1110. "bubbles": true,
  1111. "cancelable": true,
  1112. "composed": true,
  1113. "docs": {
  1114. "tags": [],
  1115. "text": "Called when the selected item(s) changes."
  1116. },
  1117. "complexType": {
  1118. "original": "{ selectedItems: HTMLCalciteComboboxItemElement[] }",
  1119. "resolved": "{ selectedItems: HTMLCalciteComboboxItemElement[]; }",
  1120. "references": {
  1121. "HTMLCalciteComboboxItemElement": {
  1122. "location": "global"
  1123. }
  1124. }
  1125. }
  1126. }, {
  1127. "method": "calciteComboboxFilterChange",
  1128. "name": "calciteComboboxFilterChange",
  1129. "bubbles": true,
  1130. "cancelable": true,
  1131. "composed": true,
  1132. "docs": {
  1133. "tags": [],
  1134. "text": "Called when the user has entered text to filter the options list"
  1135. },
  1136. "complexType": {
  1137. "original": "{\n visibleItems: HTMLCalciteComboboxItemElement[];\n text: string;\n }",
  1138. "resolved": "{ visibleItems: HTMLCalciteComboboxItemElement[]; text: string; }",
  1139. "references": {
  1140. "HTMLCalciteComboboxItemElement": {
  1141. "location": "global"
  1142. }
  1143. }
  1144. }
  1145. }, {
  1146. "method": "calciteComboboxChipDismiss",
  1147. "name": "calciteComboboxChipDismiss",
  1148. "bubbles": true,
  1149. "cancelable": true,
  1150. "composed": true,
  1151. "docs": {
  1152. "tags": [],
  1153. "text": "Called when a selected item in the combobox is dismissed via its chip *"
  1154. },
  1155. "complexType": {
  1156. "original": "any",
  1157. "resolved": "any",
  1158. "references": {}
  1159. }
  1160. }, {
  1161. "method": "calciteComboboxOpen",
  1162. "name": "calciteComboboxOpen",
  1163. "bubbles": true,
  1164. "cancelable": true,
  1165. "composed": true,
  1166. "docs": {
  1167. "tags": [{
  1168. "name": "internal",
  1169. "text": undefined
  1170. }],
  1171. "text": "Fired when the combobox is opened"
  1172. },
  1173. "complexType": {
  1174. "original": "any",
  1175. "resolved": "any",
  1176. "references": {}
  1177. }
  1178. }, {
  1179. "method": "calciteComboboxClose",
  1180. "name": "calciteComboboxClose",
  1181. "bubbles": true,
  1182. "cancelable": true,
  1183. "composed": true,
  1184. "docs": {
  1185. "tags": [{
  1186. "name": "internal",
  1187. "text": undefined
  1188. }],
  1189. "text": "Fired when the combobox is closed"
  1190. },
  1191. "complexType": {
  1192. "original": "any",
  1193. "resolved": "any",
  1194. "references": {}
  1195. }
  1196. }]; }
  1197. static get methods() { return {
  1198. "reposition": {
  1199. "complexType": {
  1200. "signature": "() => Promise<void>",
  1201. "parameters": [],
  1202. "references": {
  1203. "Promise": {
  1204. "location": "global"
  1205. }
  1206. },
  1207. "return": "Promise<void>"
  1208. },
  1209. "docs": {
  1210. "text": "Updates the position of the component.",
  1211. "tags": []
  1212. }
  1213. },
  1214. "setFocus": {
  1215. "complexType": {
  1216. "signature": "() => Promise<void>",
  1217. "parameters": [],
  1218. "references": {
  1219. "Promise": {
  1220. "location": "global"
  1221. }
  1222. },
  1223. "return": "Promise<void>"
  1224. },
  1225. "docs": {
  1226. "text": "Sets focus on the component.",
  1227. "tags": []
  1228. }
  1229. }
  1230. }; }
  1231. static get elementRef() { return "el"; }
  1232. static get watchers() { return [{
  1233. "propName": "active",
  1234. "methodName": "activeHandler"
  1235. }, {
  1236. "propName": "disabled",
  1237. "methodName": "handleDisabledChange"
  1238. }, {
  1239. "propName": "maxItems",
  1240. "methodName": "maxItemsHandler"
  1241. }, {
  1242. "propName": "value",
  1243. "methodName": "valueHandler"
  1244. }, {
  1245. "propName": "flipPlacements",
  1246. "methodName": "flipPlacementsHandler"
  1247. }, {
  1248. "propName": "selectedItems",
  1249. "methodName": "selectedItemsHandler"
  1250. }, {
  1251. "propName": "text",
  1252. "methodName": "textHandler"
  1253. }]; }
  1254. static get listeners() { return [{
  1255. "name": "click",
  1256. "method": "documentClickHandler",
  1257. "target": "document",
  1258. "capture": false,
  1259. "passive": false
  1260. }, {
  1261. "name": "calciteComboboxItemChange",
  1262. "method": "calciteComboboxItemChangeHandler",
  1263. "target": undefined,
  1264. "capture": false,
  1265. "passive": false
  1266. }]; }
  1267. }