ArticleBubble.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <!-- Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. /* eslint-disable vue/no-v-html */
  4. import { computed, nextTick, onMounted, ref, watch } from 'vue'
  5. import { useRouter } from 'vue-router'
  6. import CommonUserAvatar from '#shared/components/CommonUserAvatar/CommonUserAvatar.vue'
  7. import type { ImageViewerFile } from '#shared/composables/useImageViewer.ts'
  8. import { useImageViewer } from '#shared/composables/useImageViewer.ts'
  9. import type { TicketArticleAttachment } from '#shared/entities/ticket/types.ts'
  10. import type {
  11. TicketArticleSecurityState,
  12. TicketArticlesQuery,
  13. } from '#shared/graphql/types.ts'
  14. import { getIdFromGraphQLId } from '#shared/graphql/utils.ts'
  15. import { i18n } from '#shared/i18n.ts'
  16. import { useApplicationStore } from '#shared/stores/application.ts'
  17. import { useSessionStore } from '#shared/stores/session.ts'
  18. import type { ConfidentTake } from '#shared/types/utils.ts'
  19. import stopEvent from '#shared/utils/events.ts'
  20. import { textToHtml } from '#shared/utils/helpers.ts'
  21. import { isStandalone } from '#shared/utils/pwa.ts'
  22. import CommonFilePreview from '#mobile/components/CommonFilePreview/CommonFilePreview.vue'
  23. import { useArticleAttachments } from '../../composable/useArticleAttachments.ts'
  24. import { useArticleSeen } from '../../composable/useArticleSeen.ts'
  25. import { useArticleToggleMore } from '../../composable/useArticleToggleMore.ts'
  26. import ArticleRemoteContentBadge from './ArticleRemoteContentBadge.vue'
  27. import ArticleSecurityBadge from './ArticleSecurityBadge.vue'
  28. import ArticleWhatsappMediaBadge from './ArticleWhatsappMediaBadge.vue'
  29. interface Props {
  30. position: 'left' | 'right'
  31. content: string
  32. internal: boolean
  33. user?: Maybe<ConfidentTake<TicketArticlesQuery, 'articles.edges.node.author'>>
  34. security?: Maybe<TicketArticleSecurityState>
  35. contentType: string
  36. ticketInternalId: number
  37. articleId: string
  38. attachments: TicketArticleAttachment[]
  39. remoteContentWarning?: string
  40. mediaError?: boolean | null
  41. }
  42. const props = defineProps<Props>()
  43. const emit = defineEmits<{
  44. showContext: []
  45. seen: []
  46. }>()
  47. const session = useSessionStore()
  48. const colorClasses = computed(() => {
  49. const { internal, position } = props
  50. if (internal) return 'border border-blue bg-black'
  51. if (position === 'left') return 'border border-black bg-white text-black'
  52. return 'border border-black bg-blue text-black'
  53. })
  54. const bubbleClasses = computed(() => {
  55. const { internal, position } = props
  56. if (internal) return undefined
  57. return {
  58. 'rounded-bl-sm': position === 'left',
  59. 'rounded-br-sm': position === 'right',
  60. }
  61. })
  62. const username = computed(() => {
  63. const { user } = props
  64. if (!user) return ''
  65. if (session.user?.id === user.id) {
  66. return i18n.t('Me')
  67. }
  68. return user.fullname
  69. })
  70. const body = computed(() => {
  71. if (props.contentType !== 'text/html') {
  72. return textToHtml(props.content)
  73. }
  74. return props.content
  75. })
  76. const colorsClasses = computed(() => {
  77. if (props.internal) {
  78. return {
  79. top: body.value.length ? 'border-t-[0.5px] border-t-white/50' : '',
  80. amount: 'text-white/60',
  81. file: 'border-white/40',
  82. icon: 'border-white/40',
  83. }
  84. }
  85. return {
  86. top: body.value.length ? 'border-t-[0.5px] border-black' : '',
  87. amount: 'text-black/60',
  88. file: 'border-black',
  89. icon: 'border-black',
  90. }
  91. })
  92. const { shownMore, bubbleElement, hasShowMore, toggleShowMore } =
  93. useArticleToggleMore()
  94. const articleInternalId = computed(() => getIdFromGraphQLId(props.articleId))
  95. const { attachments: articleAttachments } = useArticleAttachments({
  96. ticketInternalId: props.ticketInternalId,
  97. articleInternalId: articleInternalId.value,
  98. attachments: computed(() => props.attachments),
  99. })
  100. const inlineAttachments = ref<ImageViewerFile[]>([])
  101. const { showImage } = useImageViewer(
  102. computed(() => [...inlineAttachments.value, ...articleAttachments.value]),
  103. )
  104. const previewImage = (event: Event, attachment: TicketArticleAttachment) => {
  105. stopEvent(event)
  106. showImage(attachment)
  107. }
  108. const router = useRouter()
  109. const app = useApplicationStore()
  110. const getRedirectRoute = (url: URL): string | undefined => {
  111. if (url.pathname.startsWith('/mobile')) {
  112. return url.href.slice(`${url.origin}/mobile`.length)
  113. }
  114. const route = router.resolve(`/${url.hash.slice(1)}${url.search}`)
  115. if (route.name !== 'Error') {
  116. return route.fullPath
  117. }
  118. }
  119. const openLink = (target: string, path: string) => {
  120. // keep links inside PWA inside the app
  121. if (!isStandalone() && target && target !== '_self') {
  122. window.open(`/mobile${path}`, target)
  123. } else {
  124. router.push(path)
  125. }
  126. }
  127. const handleLinkClick = (link: HTMLAnchorElement, event: Event) => {
  128. const fqdnOrigin = `${window.location.protocol}//${app.config.fqdn}${
  129. window.location.port ? `:${window.location.port}` : ''
  130. }`
  131. try {
  132. const url = new URL(link.href)
  133. if (url.origin === window.location.origin || url.origin === fqdnOrigin) {
  134. const redirectRoute = getRedirectRoute(url)
  135. if (redirectRoute) {
  136. openLink(link.target, redirectRoute)
  137. event.preventDefault()
  138. }
  139. }
  140. } catch {
  141. // skip
  142. }
  143. }
  144. // user links has fqdn in its href, but if it changes the link becomes invalid
  145. // to bypass that we replace the href with the correct one
  146. const patchUserMentionLinks = (link: HTMLAnchorElement) => {
  147. const userId = link.dataset.mentionUserId
  148. if (userId) {
  149. link.href = `${window.location.origin}/mobile/users/${userId}`
  150. }
  151. }
  152. const setupLinksHandlers = (element: HTMLDivElement) => {
  153. const links = element.querySelectorAll('a')
  154. links.forEach((link) => {
  155. if ('__handled' in link) return
  156. Object.defineProperty(link, '__handled', { value: true })
  157. patchUserMentionLinks(link)
  158. link.addEventListener('click', (event) => handleLinkClick(link, event))
  159. })
  160. }
  161. const populateInlineAttachments = (element: HTMLDivElement) => {
  162. const images = element.querySelectorAll('img')
  163. inlineAttachments.value = []
  164. images.forEach((image) => {
  165. const mime = image.alt?.match(/\.(jpe?g)$/i) ? 'image/jpeg' : 'image/png'
  166. const preview: ImageViewerFile = {
  167. name: image.alt,
  168. inline: image.src,
  169. type: mime,
  170. }
  171. image.classList.add('cursor-pointer')
  172. const index = inlineAttachments.value.push(preview) - 1
  173. image.onclick = () => showImage(inlineAttachments.value[index])
  174. })
  175. }
  176. watch(
  177. () => props.content,
  178. async () => {
  179. await nextTick()
  180. if (bubbleElement.value) {
  181. setupLinksHandlers(bubbleElement.value)
  182. populateInlineAttachments(bubbleElement.value)
  183. }
  184. },
  185. )
  186. onMounted(() => {
  187. if (bubbleElement.value) {
  188. setupLinksHandlers(bubbleElement.value)
  189. populateInlineAttachments(bubbleElement.value)
  190. }
  191. })
  192. useArticleSeen(bubbleElement, emit)
  193. const onContextClick = () => {
  194. emit('showContext')
  195. nextTick(() => {
  196. // remove selection because pointerdown event will leave it as is,
  197. // all actions inside the context should already have accessed it synchronously
  198. window.getSelection()?.removeAllRanges()
  199. })
  200. }
  201. </script>
  202. <template>
  203. <!-- It is the correct role comment -->
  204. <!-- eslint-disable vuejs-accessibility/aria-role -->
  205. <div
  206. :id="`article-${articleInternalId}`"
  207. role="comment"
  208. class="Article relative flex pb-4"
  209. :class="{
  210. Internal: internal,
  211. 'Right flex-row-reverse': position === 'right',
  212. Left: position === 'left',
  213. }"
  214. :data-created-by="user?.id"
  215. >
  216. <div
  217. class="h-6 w-6 self-end"
  218. :class="{
  219. 'ltr:mr-2 rtl:ml-2': position === 'left',
  220. 'ltr:ml-2 rtl:mr-2': position === 'right',
  221. }"
  222. >
  223. <CommonUserAvatar v-if="user" size="xs" :entity="user" />
  224. </div>
  225. <div class="Border">
  226. <div
  227. class="content flex flex-col overflow-hidden rounded-3xl px-4 pb-3 pt-2"
  228. :class="[bubbleClasses, colorClasses]"
  229. >
  230. <div
  231. class="flex items-center text-xs font-bold"
  232. data-test-id="article-username"
  233. >
  234. <span class="truncate break-words">
  235. {{ username }}
  236. </span>
  237. </div>
  238. <div
  239. ref="bubbleElement"
  240. data-test-id="article-content"
  241. class="overflow-hidden text-base"
  242. >
  243. <div class="Content" v-html="body" />
  244. </div>
  245. <div
  246. v-if="hasShowMore"
  247. class="relative"
  248. :class="{
  249. BubbleGradient: hasShowMore && !shownMore,
  250. }"
  251. ></div>
  252. <div
  253. v-if="attachments.length"
  254. class="mb-2 mt-1"
  255. :class="colorsClasses.top"
  256. >
  257. <div class="py-1 text-xs" :class="colorsClasses.amount">
  258. {{
  259. attachments.length === 1
  260. ? $t('1 attached file')
  261. : $t('%s attached files', attachments.length)
  262. }}
  263. </div>
  264. <CommonFilePreview
  265. v-for="attachment of articleAttachments"
  266. :key="attachment.internalId"
  267. :file="attachment"
  268. :download-url="attachment.downloadUrl"
  269. :preview-url="attachment.preview"
  270. :no-preview="!$c.ui_ticket_zoom_attachments_preview"
  271. :wrapper-class="colorsClasses.file"
  272. :icon-class="colorsClasses.icon"
  273. :size-class="colorsClasses.amount"
  274. no-remove
  275. @preview="previewImage($event, attachment)"
  276. />
  277. </div>
  278. <div
  279. class="absolute bottom-0 flex gap-1"
  280. :class="[
  281. position === 'left'
  282. ? 'flex-row-reverse ltr:left-10 rtl:right-10'
  283. : 'ltr:right-10 rtl:left-10',
  284. ]"
  285. >
  286. <ArticleWhatsappMediaBadge
  287. v-if="props.mediaError"
  288. :article-id="articleId"
  289. :media-error="props.mediaError"
  290. />
  291. <ArticleSecurityBadge
  292. v-if="security"
  293. :article-id="articleId"
  294. :success-class="colorClasses"
  295. :security="security"
  296. />
  297. <ArticleRemoteContentBadge
  298. v-if="remoteContentWarning"
  299. :original-formatting-url="remoteContentWarning"
  300. />
  301. <button
  302. v-if="hasShowMore"
  303. :class="[
  304. colorClasses,
  305. 'flex h-7 items-center justify-center rounded-md px-2 font-semibold',
  306. ]"
  307. type="button"
  308. @click="toggleShowMore()"
  309. @keydown.enter.prevent="toggleShowMore()"
  310. >
  311. {{ shownMore ? $t('See less') : $t('See more') }}
  312. </button>
  313. <button
  314. :class="[
  315. colorClasses,
  316. 'flex h-7 w-7 items-center justify-center rounded-md',
  317. ]"
  318. type="button"
  319. data-name="article-context"
  320. :aria-label="$t('Article actions')"
  321. @pointerdown="onContextClick()"
  322. @keydown.enter.prevent="onContextClick()"
  323. >
  324. <CommonIcon
  325. name="more-vertical"
  326. size="small"
  327. decorative
  328. data-ignore-click
  329. />
  330. </button>
  331. </div>
  332. </div>
  333. </div>
  334. </div>
  335. </template>
  336. <style scoped>
  337. .Content {
  338. word-break: break-word;
  339. }
  340. .Article:not(.Internal) {
  341. &.Right .Content,
  342. &.Left .Content {
  343. :deep(a) {
  344. @apply text-black underline;
  345. }
  346. }
  347. }
  348. .BubbleGradient::before {
  349. content: '';
  350. position: absolute;
  351. left: 0;
  352. right: 0;
  353. bottom: 0;
  354. height: 50px;
  355. pointer-events: none;
  356. }
  357. .Right:not(.Internal) .BubbleGradient::before {
  358. background: linear-gradient(
  359. rgba(255, 255, 255, 0),
  360. theme('colors.blue.DEFAULT')
  361. );
  362. }
  363. .Left:not(.Internal) .BubbleGradient::before {
  364. background: linear-gradient(rgba(255, 255, 255, 0), theme('colors.white'));
  365. }
  366. .Border {
  367. overflow: hidden;
  368. }
  369. .Internal .Border {
  370. background: repeating-linear-gradient(
  371. 45deg,
  372. theme('colors.blue.DEFAULT'),
  373. theme('colors.blue.DEFAULT') 5px,
  374. theme('colors.blue.dark') 5px,
  375. theme('colors.blue.dark') 10px
  376. );
  377. background-size: 14px 14px;
  378. background-position: -1px;
  379. padding: 4px;
  380. border-radius: calc(1.5rem + 4px);
  381. margin: -4px;
  382. }
  383. .Internal .BubbleGradient::before {
  384. background: linear-gradient(
  385. rgba(255, 255, 255, 0),
  386. theme('colors.black.DEFAULT')
  387. );
  388. }
  389. </style>