choiceChecklistHelpers.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. function parseLegacyChecklistValue(value) {
  2. return value.split(',').map((segment) => segment.trim()).filter((segment) => segment !== '')
  3. }
  4. export function parseChecklistValue(value) {
  5. if (!value || value === '') {
  6. return []
  7. }
  8. const trimmed = value.trim()
  9. if (trimmed.startsWith('[')) {
  10. try {
  11. const parsed = JSON.parse(trimmed)
  12. if (!Array.isArray(parsed)) {
  13. return []
  14. }
  15. return parsed.map((segment) => String(segment).trim()).filter((segment) => segment !== '')
  16. } catch {
  17. return []
  18. }
  19. }
  20. return parseLegacyChecklistValue(value)
  21. }
  22. export function formatChecklistValue(selected) {
  23. if (!Array.isArray(selected) || selected.length === 0) {
  24. return ''
  25. }
  26. return JSON.stringify(selected)
  27. }
  28. export function toggleChoice(selected, value) {
  29. const current = Array.isArray(selected) ? [...selected] : []
  30. const index = current.indexOf(value)
  31. if (index === -1) {
  32. current.push(value)
  33. return current
  34. }
  35. current.splice(index, 1)
  36. return current
  37. }
  38. export function choiceLabel(choice) {
  39. return choice.title || choice.value || ''
  40. }
  41. export function allChoiceValues(choices) {
  42. return choices.map((choice) => choice.value)
  43. }