TreeSelect.vue 20 KB

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