useCheckBodyAttachmentReference.ts 1.9 KB

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