useCheckBodyAttachmentReference.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { FileUploaded } from '#shared/components/Form/fields/FieldFile/types.ts'
  3. import { i18n } from '#shared/i18n.ts'
  4. import { domFrom } from '#shared/utils/dom.ts'
  5. import { useConfirmation } from '../useConfirmation.ts'
  6. const referenceMatchwords = [
  7. __('Attachment'),
  8. __('attachment'),
  9. __('Attached'),
  10. __('attached'),
  11. __('Enclosed'),
  12. __('enclosed'),
  13. __('Enclosure'),
  14. __('enclosure'),
  15. ]
  16. const removeQuotingFromBody = (body: string) => {
  17. const dom = domFrom(body)
  18. // Remove blockquotes and images
  19. // To not detect matchwords which are not part of the user-written article
  20. dom.querySelectorAll('blockquote, img').forEach((elem) => elem.remove())
  21. // Return the modified HTML content as a string.
  22. return dom.innerHTML
  23. }
  24. const bodyAttachmentReferenceMatchwordExists = (body: string) => {
  25. const cleanBody = removeQuotingFromBody(body)
  26. return referenceMatchwords.some((word) => {
  27. let findWord = new RegExp(word, 'i')
  28. if (findWord.test(cleanBody)) return true
  29. // Translate the word in the user locale.
  30. findWord = new RegExp(i18n.t(word), 'i')
  31. return findWord.test(cleanBody)
  32. })
  33. }
  34. export const useCheckBodyAttachmentReference = () => {
  35. const { waitForConfirmation } = useConfirmation()
  36. const missingBodyAttachmentReference = (
  37. body: string,
  38. files?: FileUploaded[],
  39. ) => {
  40. if (!body) return false
  41. if (files && files.length > 0) return false
  42. return bodyAttachmentReferenceMatchwordExists(body)
  43. }
  44. const bodyAttachmentReferenceConfirmation = async () => {
  45. const confirmed = await waitForConfirmation(
  46. __('Did you plan to include attachments with this message?'),
  47. {
  48. buttonLabel: __('Yes, add attachments now'),
  49. cancelLabel: __('No, thanks'),
  50. },
  51. )
  52. return confirmed
  53. }
  54. return {
  55. missingBodyAttachmentReference,
  56. bodyAttachmentReferenceConfirmation,
  57. }
  58. }