useCheckBodyAttachmentReference.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 = __('attachment,attached,enclosed,enclosure')
  7. const removeQuotingFromBody = (body: string) => {
  8. const dom = domFrom(body)
  9. // Remove blockquotes and images
  10. // To not detect matchwords which are not part of the user-written article
  11. dom.querySelectorAll('blockquote, img').forEach((elem) => elem.remove())
  12. // Return the modified HTML content as a string.
  13. return dom.innerHTML
  14. }
  15. const bodyAttachmentReferenceMatchwordExists = (body: string) => {
  16. const cleanBody = removeQuotingFromBody(body)
  17. const matchwords = referenceMatchwords.split(',')
  18. const translatedMatchwords = i18n.t(referenceMatchwords).split(',')
  19. return matchwords.concat(translatedMatchwords).some((word) => {
  20. const findWord = new RegExp(word, 'i')
  21. return findWord.test(cleanBody)
  22. })
  23. }
  24. export const useCheckBodyAttachmentReference = () => {
  25. const { waitForConfirmation } = useConfirmation()
  26. const missingBodyAttachmentReference = (
  27. body: string,
  28. files?: FileUploaded[],
  29. ) => {
  30. if (!body) return false
  31. if (files && files.length > 0) return false
  32. return bodyAttachmentReferenceMatchwordExists(body)
  33. }
  34. const bodyAttachmentReferenceConfirmation = async () => {
  35. const confirmed = await waitForConfirmation(
  36. __('Did you plan to include attachments with this message?'),
  37. {
  38. buttonLabel: __('Yes, add attachments now'),
  39. cancelLabel: __('No, thanks'),
  40. },
  41. )
  42. return confirmed
  43. }
  44. return {
  45. missingBodyAttachmentReference,
  46. bodyAttachmentReferenceConfirmation,
  47. }
  48. }