useTableCheckboxes.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { computed, type ModelRef, type Ref } from 'vue'
  3. import type { TableItem } from '#desktop/components/CommonSimpleTable/types.ts'
  4. export const useTableCheckboxes = (
  5. checkedRowItems: ModelRef<TableItem[]>,
  6. items: Ref<TableItem[]>,
  7. ) => {
  8. const allCheckboxRowsSelected = computed(
  9. () => checkedRowItems.value.length >= items.value.length,
  10. )
  11. const selectAllRowCheckboxes = (value?: boolean) => {
  12. if (allCheckboxRowsSelected.value === value) return
  13. if (value) {
  14. checkedRowItems.value = items.value
  15. } else {
  16. checkedRowItems.value = items.value.filter(
  17. (item) => item.disabled && item.checked,
  18. )
  19. }
  20. }
  21. const handleCheckboxUpdate = (item: TableItem) => {
  22. const isChecked = checkedRowItems.value.some(
  23. (selectedItem) => selectedItem.id === item.id,
  24. )
  25. if (!isChecked) {
  26. // Overwrite entire array to trigger reactivity since defineModel default value is not reactive.
  27. checkedRowItems.value = [...checkedRowItems.value, item]
  28. } else {
  29. checkedRowItems.value = checkedRowItems.value.filter(
  30. (selectedItem) => item.id.toString() !== selectedItem.id.toString(),
  31. )
  32. }
  33. }
  34. const hasCheckboxId = (itemId: string | number) =>
  35. checkedRowItems.value.some(
  36. (selectedItem) => selectedItem.id.toString() === itemId.toString(),
  37. )
  38. return {
  39. allCheckboxRowsSelected,
  40. selectAllRowCheckboxes,
  41. handleCheckboxUpdate,
  42. hasCheckboxId,
  43. }
  44. }