TreeSelect.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. <!--
  2. Composant de sélection hiérarchique à plusieurs niveaux permettant de naviguer
  3. et sélectionner des éléments organisés en catégories et sous-catégories.
  4. ## Exemple d'utilisation
  5. ```vue
  6. <TreeSelect
  7. v-model="selectedValues"
  8. :items="hierarchicalItems"
  9. :max-visible-chips="3"
  10. label="Sélectionner des éléments"
  11. />
  12. ```
  13. -->
  14. <template>
  15. <v-select
  16. :model-value="modelValue"
  17. :label="$t(label)"
  18. v-bind="$attrs"
  19. :items="flattenedItems"
  20. item-title="label"
  21. item-value="value"
  22. :variant="variant"
  23. multiple
  24. :menu-props="{ maxHeight: 400 }"
  25. @update:menu="onMenuUpdate"
  26. @update:model-value="$emit('update:modelValue', $event)"
  27. >
  28. <template #prepend-item>
  29. <!-- Champs de recherche textuelle -->
  30. <v-text-field
  31. ref="searchInput"
  32. v-model="searchText"
  33. density="compact"
  34. hide-details
  35. :placeholder="$t('search') + '...'"
  36. prepend-inner-icon="fas fa-magnifying-glass"
  37. variant="outlined"
  38. clearable
  39. class="mx-2 my-2"
  40. @click.stop="focusSearchInput"
  41. @mousedown.stop
  42. @keydown.stop="onKeyDown"
  43. @input="onSearchInputDebounced"
  44. @click:clear.stop="onSearchClear"
  45. />
  46. <v-divider class="mt-2" />
  47. </template>
  48. <template #selection="{ item, index }">
  49. <v-chip
  50. v-if="maxVisibleChips && index < maxVisibleChips"
  51. :key="item.raw.value"
  52. closable
  53. @click:close="removeItem(item.raw.value!)"
  54. >
  55. {{ selectedItemsMap[item.raw] || selectedItemsMap[item.raw.value] }}
  56. </v-chip>
  57. <span
  58. v-if="
  59. maxVisibleChips &&
  60. index === maxVisibleChips &&
  61. modelValue.length > maxVisibleChips
  62. "
  63. class="text-grey text-caption align-self-center"
  64. >
  65. (+{{ modelValue.length - maxVisibleChips }} {{ $t('others') }})
  66. </span>
  67. </template>
  68. <template #item="{ item }">
  69. <template v-if="item.raw.type === 'category'">
  70. <v-list-item
  71. :ripple="false"
  72. :class="{
  73. 'v-list-item--active': expandedCategories.has(item.raw.id),
  74. }"
  75. @click.stop="toggleCategory(item.raw.id)"
  76. >
  77. <template #prepend>
  78. <v-icon
  79. :icon="
  80. 'fas ' +
  81. (expandedCategories.has(item.raw.id)
  82. ? 'fa-angle-down'
  83. : 'fa-angle-right')
  84. "
  85. size="small"
  86. />
  87. </template>
  88. <v-list-item-title class="font-weight-medium">
  89. {{ item.raw.label }}
  90. </v-list-item-title>
  91. </v-list-item>
  92. </template>
  93. <template v-else-if="item.raw.type === 'subcategory'">
  94. <v-list-item
  95. :ripple="false"
  96. :class="{
  97. 'v-list-item--active': expandedSubcategories.has(item.raw.id),
  98. 'pl-8': true,
  99. }"
  100. @click.stop="toggleSubcategory(item.raw.id)"
  101. >
  102. <template #prepend>
  103. <v-icon
  104. :icon="
  105. 'fas ' +
  106. (expandedSubcategories.has(item.raw.id)
  107. ? 'fa-angle-down'
  108. : 'fa-angle-right')
  109. "
  110. size="small"
  111. />
  112. </template>
  113. <v-list-item-title>
  114. {{ item.raw.label }}
  115. </v-list-item-title>
  116. </v-list-item>
  117. </template>
  118. <template v-else>
  119. <v-list-item
  120. :active="modelValue.includes(item.raw.value!)"
  121. :class="{
  122. 'd-flex': true,
  123. 'pl-12': item.raw.level === 2,
  124. 'pl-8': item.raw.level === 1,
  125. }"
  126. @click="toggleItem(item.raw.value!)"
  127. >
  128. <template #prepend>
  129. <v-checkbox
  130. :model-value="modelValue.includes(item.raw.value!)"
  131. color="primary"
  132. :hide-details="true"
  133. @click.stop="toggleItem(item.raw.value!)"
  134. />
  135. </template>
  136. <v-list-item-title>
  137. {{ item.raw.label }}
  138. </v-list-item-title>
  139. </v-list-item>
  140. </template>
  141. </template>
  142. </v-select>
  143. </template>
  144. <script setup lang="ts">
  145. import StringUtils from '~/services/utils/stringUtils'
  146. import _ from 'lodash'
  147. import type { PropType } from 'vue'
  148. interface SelectItem {
  149. id: string
  150. label: string
  151. normalizedLabel?: string
  152. value?: number
  153. type: 'category' | 'subcategory' | 'item'
  154. parentId?: string
  155. level: number
  156. }
  157. const props = defineProps({
  158. modelValue: {
  159. type: Array as PropType<string[]>,
  160. required: true,
  161. },
  162. items: {
  163. type: Array as PropType<SelectItem[]>,
  164. required: true,
  165. },
  166. maxVisibleChips: {
  167. type: Number,
  168. required: false,
  169. default: null,
  170. },
  171. /**
  172. * Label du champ
  173. * Si non défini, c'est le nom de propriété qui est utilisé
  174. */
  175. label: {
  176. type: String,
  177. required: false,
  178. default: null,
  179. },
  180. /**
  181. * @see https://vuetifyjs.com/en/api/v-autocomplete/#props-variant
  182. */
  183. variant: {
  184. type: String as PropType<
  185. | 'filled'
  186. | 'outlined'
  187. | 'plain'
  188. | 'underlined'
  189. | 'solo'
  190. | 'solo-inverted'
  191. | 'solo-filled'
  192. | undefined
  193. >,
  194. required: false,
  195. default: 'outlined',
  196. },
  197. })
  198. const searchInput = ref()
  199. /**
  200. * Force le focus sur l'input de recherche
  201. */
  202. const focusSearchInput = () => {
  203. nextTick(() => {
  204. if (searchInput.value?.$el) {
  205. const input = searchInput.value.$el.querySelector('input')
  206. if (input) {
  207. input.focus()
  208. }
  209. }
  210. })
  211. }
  212. /**
  213. * Gère les événements clavier pour éviter les conflits avec la navigation du menu
  214. */
  215. const onKeyDown = (event: KeyboardEvent) => {
  216. // Empêcher la propagation pour tous les caractères alphanumériques
  217. // et les touches spéciales de navigation
  218. if (
  219. event.key.length === 1 || // Caractères simples (a, c, etc.)
  220. ['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(
  221. event.key,
  222. )
  223. ) {
  224. event.stopPropagation()
  225. }
  226. // Empêcher également Escape de fermer le menu quand on est dans l'input
  227. if (event.key === 'Escape') {
  228. event.stopPropagation()
  229. // Optionnel : vider le texte de recherche
  230. if (searchText.value) {
  231. searchText.value = ''
  232. onSearchClear()
  233. }
  234. }
  235. }
  236. /**
  237. * A computed property that normalizes the labels of all items upfront.
  238. * This avoids having to normalize labels during each search operation.
  239. */
  240. const normalizedItems = computed(() => {
  241. return props.items.map((item) => ({
  242. ...item,
  243. normalizedLabel: StringUtils.normalize(item.label),
  244. }))
  245. })
  246. const emit = defineEmits(['update:modelValue'])
  247. const expandedCategories: Ref<Set<string>> = ref(new Set())
  248. const expandedSubcategories: Ref<Set<string>> = ref(new Set())
  249. const searchText: Ref<string> = ref('')
  250. /**
  251. * Expands all parent categories and subcategories of selected items.
  252. */
  253. const expandParentsOfSelectedItems = () => {
  254. expandedCategories.value.clear()
  255. expandedSubcategories.value.clear()
  256. for (const selectedId of props.modelValue) {
  257. const item = normalizedItems.value.find((i) => i.value === selectedId)
  258. if (!item) continue
  259. // Trouver la sous-catégorie
  260. const subcategory = normalizedItems.value.find(
  261. (i) => i.id === item.parentId,
  262. )
  263. if (subcategory) {
  264. expandedSubcategories.value.add(subcategory.id)
  265. // Trouver la catégorie
  266. if (subcategory.parentId) {
  267. const category = normalizedItems.value.find(
  268. (i) => i.id === subcategory.parentId,
  269. )
  270. if (category) {
  271. expandedCategories.value.add(category.id)
  272. }
  273. }
  274. }
  275. }
  276. }
  277. /**
  278. * A callback function that is triggered when the menu's open state is updated.
  279. */
  280. const onMenuUpdate = (isOpen: boolean) => {
  281. if (isOpen) {
  282. expandParentsOfSelectedItems()
  283. }
  284. // Réinitialiser la recherche quand le menu se ferme
  285. else if (searchText.value) {
  286. searchText.value = ''
  287. onSearchInput()
  288. }
  289. }
  290. /**
  291. * Toggles the expanded state of a given category. If the category is currently
  292. * expanded, it will collapse the category and also collapse its subcategories.
  293. * If the category is not expanded, it will expand the category.
  294. *
  295. * @param {string} categoryId - The unique identifier of the category to toggle.
  296. */
  297. const toggleCategory = (categoryId: string) => {
  298. if (expandedCategories.value.has(categoryId)) {
  299. expandedCategories.value.delete(categoryId)
  300. // Fermer aussi les sous-catégories
  301. const subcategories = normalizedItems.value.filter(
  302. (i) => i.parentId === categoryId && i.type === 'subcategory',
  303. )
  304. subcategories.forEach((sub) => {
  305. expandedSubcategories.value.delete(sub.id)
  306. })
  307. } else {
  308. expandedCategories.value.add(categoryId)
  309. }
  310. }
  311. /**
  312. * Toggles the expansion state of a subcategory.
  313. *
  314. * @param {string} subcategoryId - The unique identifier of the subcategory to be toggled.
  315. */
  316. const toggleSubcategory = (subcategoryId: string) => {
  317. if (expandedSubcategories.value.has(subcategoryId)) {
  318. expandedSubcategories.value.delete(subcategoryId)
  319. } else {
  320. expandedSubcategories.value.add(subcategoryId)
  321. }
  322. }
  323. /**
  324. * A function that toggles the inclusion of a specific value in
  325. * the selected items list.
  326. *
  327. * @param {string} value - The value to toggle in the selected items list.
  328. */
  329. const toggleItem = (value: string) => {
  330. const currentSelection = [...props.modelValue]
  331. const index = currentSelection.indexOf(value)
  332. if (index > -1) {
  333. currentSelection.splice(index, 1)
  334. } else {
  335. currentSelection.push(value)
  336. }
  337. emit('update:modelValue', currentSelection)
  338. }
  339. /**
  340. * Removes the specified item from the model value and emits an update event.
  341. *
  342. * @param {string} value - The item to be removed from the model value.
  343. * @emits update:modelValue - A custom event emitted with the updated model value
  344. * after the specified item has been removed.
  345. */
  346. const removeItem = (value: string) => {
  347. emit(
  348. 'update:modelValue',
  349. props.modelValue.filter((item) => item !== value),
  350. )
  351. }
  352. /**
  353. * Fonction appellée lorsque l'input de recherche textuelle est modifié
  354. */
  355. const onSearchInput = () => {
  356. // Réinitialiser les états d'expansion dans tous les cas
  357. expandedCategories.value.clear()
  358. expandedSubcategories.value.clear()
  359. if (searchText.value.trim()) {
  360. // Trouver tous les éléments qui correspondent à la recherche
  361. const matchingItems = normalizedItems.value.filter(
  362. (item) =>
  363. item.type === 'item' && item.level === 2 && itemMatchesSearch(item),
  364. )
  365. // Pour chaque élément correspondant, ajouter ses parents aux ensembles d'expansion
  366. for (const item of matchingItems) {
  367. // Trouver et ajouter la sous-catégorie parente
  368. const subcategory = normalizedItems.value.find(
  369. (i) => i.id === item.parentId,
  370. )
  371. if (subcategory) {
  372. expandedSubcategories.value.add(subcategory.id)
  373. // Trouver et ajouter la catégorie parente
  374. const category = normalizedItems.value.find(
  375. (i) => i.id === subcategory.parentId,
  376. )
  377. if (category) {
  378. expandedCategories.value.add(category.id)
  379. }
  380. }
  381. }
  382. }
  383. }
  384. const onSearchInputDebounced = _.debounce(onSearchInput, 200)
  385. const onSearchClear = () => {
  386. searchText.value = ''
  387. onSearchInput()
  388. }
  389. /**
  390. * Checks if any word in the normalized text starts with the normalized search term.
  391. *
  392. * @param {string} normalizedText - The normalized text to check.
  393. * @param {string} normalizedSearch - The normalized search term.
  394. * @returns {boolean} `true` if any word in the text starts with the search term; otherwise, `false`.
  395. */
  396. const anyWordStartsWith = (
  397. normalizedText: string,
  398. normalizedSearch: string,
  399. ): boolean => {
  400. if (normalizedText.indexOf(normalizedSearch) === 0) return true
  401. const spaceIndex = normalizedText.indexOf(' ')
  402. if (spaceIndex === -1) return false
  403. return normalizedText
  404. .split(' ')
  405. .some((word) => word.startsWith(normalizedSearch))
  406. }
  407. /**
  408. * Determines if a given item matches the current search text by checking its normalized label
  409. * and, for certain items, the normalized labels of its parent elements.
  410. *
  411. * The search text is normalized using `StringUtils.normalize` before comparison.
  412. * If no search text is provided, the item matches by default.
  413. *
  414. * For items of type `item` at level 2, the function checks:
  415. * - The normalized label of the item itself
  416. * - The normalized label of its parent subcategory
  417. * - The normalized label of the grandparent category (if applicable)
  418. *
  419. * For all other item types, only the item's normalized label is checked.
  420. *
  421. * The matching is done by checking if any word in the normalized label starts with the normalized search text.
  422. *
  423. * @param {SelectItem} item - The item to evaluate against the search text.
  424. * @returns {boolean} `true` if the item or its relevant parent(s) match the search text; otherwise, `false`.
  425. */
  426. const itemMatchesSearch = (item: SelectItem): boolean => {
  427. if (!searchText.value) return true
  428. const normalizedSearch = StringUtils.normalize(searchText.value)
  429. // Find the item with normalized label from our computed property
  430. const itemWithNormalizedLabel = normalizedItems.value.find(
  431. (i) => i.id === item.id,
  432. )
  433. if (!itemWithNormalizedLabel) return false
  434. // Si c'est un élément de niveau 2, vérifier son label et les labels de ses parents
  435. if (item.type === 'item' && item.level === 2) {
  436. // Vérifier le label de l'élément
  437. if (
  438. anyWordStartsWith(
  439. itemWithNormalizedLabel.normalizedLabel!,
  440. normalizedSearch,
  441. )
  442. )
  443. return true
  444. // Trouver et vérifier le label de la sous-catégorie parente
  445. const subcategory = normalizedItems.value.find(
  446. (i) => i.id === item.parentId,
  447. )
  448. if (
  449. subcategory &&
  450. anyWordStartsWith(subcategory.normalizedLabel!, normalizedSearch)
  451. )
  452. return true
  453. // Trouver et vérifier le label de la catégorie parente
  454. if (subcategory && subcategory.parentId) {
  455. const category = normalizedItems.value.find(
  456. (i) => i.id === subcategory.parentId,
  457. )
  458. if (
  459. category &&
  460. anyWordStartsWith(category.normalizedLabel!, normalizedSearch)
  461. )
  462. return true
  463. }
  464. return false
  465. }
  466. // Pour les autres types d'éléments, vérifier simplement leur label
  467. return anyWordStartsWith(
  468. itemWithNormalizedLabel.normalizedLabel!,
  469. normalizedSearch,
  470. )
  471. }
  472. /**
  473. * Filtre les éléments de niveau 2 qui correspondent au texte de recherche.
  474. *
  475. * @returns {SelectItem[]} Les éléments de niveau 2 qui correspondent à la recherche.
  476. */
  477. const findMatchingLevel2Items = (): SelectItem[] => {
  478. return normalizedItems.value.filter(
  479. (item) =>
  480. item.type === 'item' && item.level === 2 && itemMatchesSearch(item),
  481. )
  482. }
  483. /**
  484. * Construit une liste hiérarchique d'éléments basée sur les résultats de recherche.
  485. * Pour chaque élément correspondant, ajoute sa hiérarchie complète (catégorie et sous-catégorie).
  486. *
  487. * @param {SelectItem[]} matchingItems - Les éléments correspondant à la recherche.
  488. * @returns {SelectItem[]} Liste hiérarchique incluant les éléments et leurs parents.
  489. */
  490. const buildSearchResultsList = (matchingItems: SelectItem[]): SelectItem[] => {
  491. const result: SelectItem[] = []
  492. const addedCategoryIds = new Set<string>()
  493. const addedSubcategoryIds = new Set<string>()
  494. for (const item of matchingItems) {
  495. // Trouver la sous-catégorie parente
  496. const subcategory = normalizedItems.value.find(
  497. (i) => i.id === item.parentId,
  498. )
  499. if (!subcategory) continue
  500. // Trouver la catégorie parente
  501. const category = normalizedItems.value.find(
  502. (i) => i.id === subcategory.parentId,
  503. )
  504. if (!category) continue
  505. // Ajouter la catégorie si elle n'est pas déjà présente
  506. if (!addedCategoryIds.has(category.id)) {
  507. result.push(category)
  508. addedCategoryIds.add(category.id)
  509. expandedCategories.value.add(category.id)
  510. }
  511. // Ajouter la sous-catégorie si elle n'est pas déjà présente
  512. if (!addedSubcategoryIds.has(subcategory.id)) {
  513. result.push(subcategory)
  514. addedSubcategoryIds.add(subcategory.id)
  515. expandedSubcategories.value.add(subcategory.id)
  516. }
  517. // Ajouter l'élément
  518. result.push(item)
  519. }
  520. return result
  521. }
  522. /**
  523. * Traite récursivement les éléments pour construire une liste hiérarchique
  524. * basée sur l'état d'expansion des catégories et sous-catégories.
  525. *
  526. * @param {SelectItem[]} items - Les éléments à traiter.
  527. * @param {SelectItem[]} result - Le tableau résultat à remplir.
  528. * @param {boolean} parentExpanded - Indique si le parent est développé.
  529. */
  530. const processItemsRecursively = (
  531. items: SelectItem[],
  532. result: SelectItem[],
  533. parentExpanded = true,
  534. ): void => {
  535. for (const item of items) {
  536. if (item.type === 'category') {
  537. result.push(item)
  538. if (expandedCategories.value.has(item.id)) {
  539. const subcategories = normalizedItems.value.filter(
  540. (i) => i.parentId === item.id && i.type === 'subcategory',
  541. )
  542. processItemsRecursively(subcategories, result, true)
  543. }
  544. } else if (item.type === 'subcategory') {
  545. if (parentExpanded) {
  546. result.push(item)
  547. if (expandedSubcategories.value.has(item.id)) {
  548. const subItems = normalizedItems.value.filter(
  549. (i) => i.parentId === item.id && i.type === 'item',
  550. )
  551. processItemsRecursively(subItems, result, true)
  552. }
  553. }
  554. } else if (item.type === 'item' && parentExpanded) {
  555. result.push(item)
  556. }
  557. }
  558. }
  559. /**
  560. * Construit une liste hiérarchique d'éléments en mode normal (sans recherche).
  561. *
  562. * @returns {SelectItem[]} Liste hiérarchique basée sur l'état d'expansion.
  563. */
  564. const buildNormalModeList = (): SelectItem[] => {
  565. const result: SelectItem[] = []
  566. const topLevelItems = normalizedItems.value.filter((item) => !item.parentId)
  567. processItemsRecursively(topLevelItems, result)
  568. return result
  569. }
  570. /**
  571. * A computed property that generates a flattened and organized list of items
  572. * from a hierarchical structure, based on the current search text and
  573. * expanded categories/subcategories.
  574. *
  575. * @returns {SelectItem[]} Flattened and organized list of items.
  576. */
  577. const flattenedItems = computed(() => {
  578. const hasSearch = !!searchText.value.trim()
  579. if (hasSearch) {
  580. const matchingItems = findMatchingLevel2Items()
  581. return buildSearchResultsList(matchingItems)
  582. }
  583. return buildNormalModeList()
  584. })
  585. /**
  586. * A computed property that maps selected values to their corresponding labels.
  587. * This is used to display the correct labels in the chips when the dropdown is closed.
  588. *
  589. * @returns {Record<string, string>} A map of selected values to their labels.
  590. */
  591. const selectedItemsMap = computed(() => {
  592. const map: Record<string, string> = {}
  593. // Find all selectable items (type 'item') in the items array with normalized labels
  594. const selectableItems = normalizedItems.value.filter(
  595. (item) => item.type === 'item' && item.value,
  596. )
  597. // Create a map of values to labels
  598. selectableItems.forEach((item) => {
  599. if (item.value) {
  600. map[item.value] = item.label
  601. }
  602. })
  603. return map
  604. })
  605. </script>
  606. <style scoped lang="scss">
  607. .v-list-item--active {
  608. background-color: rgba(var(--v-theme-primary), 0.1);
  609. }
  610. .v-list-item {
  611. contain: layout style paint;
  612. height: 40px !important; /* Ensure consistent height for virtual scrolling */
  613. min-height: 40px !important;
  614. max-height: 40px !important;
  615. padding-top: 0 !important;
  616. padding-bottom: 0 !important;
  617. }
  618. .search-icon {
  619. color: rgba(var(--v-theme-on-surface), var(--v-medium-emphasis-opacity));
  620. }
  621. :deep(.v-field__prepend-inner) {
  622. padding-top: 0;
  623. }
  624. :deep(.v-list) {
  625. padding-top: 0;
  626. contain: content;
  627. will-change: transform;
  628. transform-style: preserve-3d;
  629. }
  630. </style>