ArticleBubble.vue 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 CommonUserAvatar from '#shared/components/CommonUserAvatar/CommonUserAvatar.vue'
  5. import { computed, nextTick, onMounted, ref, watch } from 'vue'
  6. import { i18n } from '#shared/i18n.ts'
  7. import { textToHtml } from '#shared/utils/helpers.ts'
  8. import { useSessionStore } from '#shared/stores/session.ts'
  9. import type {
  10. TicketArticleSecurityState,
  11. TicketArticlesQuery,
  12. } from '#shared/graphql/types.ts'
  13. import type { ConfidentTake } from '#shared/types/utils.ts'
  14. import type { ImageViewerFile } from '#shared/composables/useImageViewer.ts'
  15. import { useImageViewer } from '#shared/composables/useImageViewer.ts'
  16. import CommonFilePreview from '#mobile/components/CommonFilePreview/CommonFilePreview.vue'
  17. import stopEvent from '#shared/utils/events.ts'
  18. import { getIdFromGraphQLId } from '#shared/graphql/utils.ts'
  19. import type { TicketArticleAttachment } from '#shared/entities/ticket/types.ts'
  20. import { useRouter } from 'vue-router'
  21. import { useApplicationStore } from '#shared/stores/application.ts'
  22. import { isStandalone } from '#shared/utils/pwa.ts'
  23. import { useArticleToggleMore } from '../../composable/useArticleToggleMore.ts'
  24. import { useArticleAttachments } from '../../composable/useArticleAttachments.ts'
  25. import ArticleRemoteContentBadge from './ArticleRemoteContentBadge.vue'
  26. import ArticleSecurityBadge from './ArticleSecurityBadge.vue'
  27. import ArticleWhatsappMediaBadge from './ArticleWhatsappMediaBadge.vue'
  28. import { useArticleSeen } from '../../composable/useArticleSeen.ts'
  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. (e: 'showContext'): void
  45. (e: 'seen'): void
  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. <div
  204. :id="`article-${articleInternalId}`"
  205. role="comment"
  206. class="Article relative flex pb-4"
  207. :class="{
  208. Internal: internal,
  209. 'Right flex-row-reverse': position === 'right',
  210. Left: position === 'left',
  211. }"
  212. :data-created-by="user?.id"
  213. >
  214. <div
  215. class="h-6 w-6 self-end"
  216. :class="{
  217. 'ltr:mr-2 rtl:ml-2': position === 'left',
  218. 'ltr:ml-2 rtl:mr-2': position === 'right',
  219. }"
  220. >
  221. <CommonUserAvatar v-if="user" size="xs" :entity="user" />
  222. </div>
  223. <div class="Border">
  224. <div
  225. class="content flex flex-col overflow-hidden rounded-3xl px-4 pb-3 pt-2"
  226. :class="[bubbleClasses, colorClasses]"
  227. >
  228. <div
  229. class="flex items-center text-xs font-bold"
  230. data-test-id="article-username"
  231. >
  232. <span class="truncate break-words">
  233. {{ username }}
  234. </span>
  235. </div>
  236. <div
  237. ref="bubbleElement"
  238. data-test-id="article-content"
  239. class="overflow-hidden text-base"
  240. >
  241. <div class="Content" v-html="body" />
  242. </div>
  243. <div
  244. v-if="hasShowMore"
  245. class="relative"
  246. :class="{
  247. BubbleGradient: hasShowMore && !shownMore,
  248. }"
  249. ></div>
  250. <div
  251. v-if="attachments.length"
  252. class="mb-2 mt-1"
  253. :class="colorsClasses.top"
  254. >
  255. <div class="py-1 text-xs" :class="colorsClasses.amount">
  256. {{
  257. attachments.length === 1
  258. ? $t('1 attached file')
  259. : $t('%s attached files', attachments.length)
  260. }}
  261. </div>
  262. <CommonFilePreview
  263. v-for="attachment of articleAttachments"
  264. :key="attachment.internalId"
  265. :file="attachment"
  266. :download-url="attachment.downloadUrl"
  267. :preview-url="attachment.preview"
  268. :no-preview="!$c.ui_ticket_zoom_attachments_preview"
  269. :wrapper-class="colorsClasses.file"
  270. :icon-class="colorsClasses.icon"
  271. :size-class="colorsClasses.amount"
  272. no-remove
  273. @preview="previewImage($event, attachment)"
  274. />
  275. </div>
  276. <div
  277. class="absolute bottom-0 flex gap-1"
  278. :class="[
  279. position === 'left'
  280. ? 'flex-row-reverse ltr:left-10 rtl:right-10'
  281. : 'ltr:right-10 rtl:left-10',
  282. ]"
  283. >
  284. <ArticleWhatsappMediaBadge
  285. v-if="props.mediaError"
  286. :article-id="articleId"
  287. :media-error="props.mediaError"
  288. />
  289. <ArticleSecurityBadge
  290. v-if="security"
  291. :article-id="articleId"
  292. :success-class="colorClasses"
  293. :security="security"
  294. />
  295. <ArticleRemoteContentBadge
  296. v-if="remoteContentWarning"
  297. :class="colorClasses"
  298. :original-formatting-url="remoteContentWarning"
  299. />
  300. <button
  301. v-if="hasShowMore"
  302. :class="[
  303. colorClasses,
  304. 'flex h-7 items-center justify-center rounded-md px-2 font-semibold',
  305. ]"
  306. type="button"
  307. @click="toggleShowMore()"
  308. @keydown.enter.prevent="toggleShowMore()"
  309. >
  310. {{ shownMore ? $t('See less') : $t('See more') }}
  311. </button>
  312. <button
  313. :class="[
  314. colorClasses,
  315. 'flex h-7 w-7 items-center justify-center rounded-md',
  316. ]"
  317. type="button"
  318. data-name="article-context"
  319. :aria-label="$t('Article actions')"
  320. @pointerdown="onContextClick()"
  321. @keydown.enter.prevent="onContextClick()"
  322. >
  323. <CommonIcon
  324. name="more-vertical"
  325. size="small"
  326. decorative
  327. data-ignore-click
  328. />
  329. </button>
  330. </div>
  331. </div>
  332. </div>
  333. </div>
  334. </template>
  335. <style scoped>
  336. .Content {
  337. word-break: break-word;
  338. }
  339. .Article:not(.Internal) {
  340. &.Right .Content,
  341. &.Left .Content {
  342. :deep(a) {
  343. @apply text-black underline;
  344. }
  345. }
  346. }
  347. .BubbleGradient::before {
  348. content: '';
  349. position: absolute;
  350. left: 0;
  351. right: 0;
  352. bottom: 0;
  353. height: 50px;
  354. pointer-events: none;
  355. }
  356. .Right:not(.Internal) .BubbleGradient::before {
  357. background: linear-gradient(
  358. rgba(255, 255, 255, 0),
  359. theme('colors.blue.DEFAULT')
  360. );
  361. }
  362. .Left:not(.Internal) .BubbleGradient::before {
  363. background: linear-gradient(rgba(255, 255, 255, 0), theme('colors.white'));
  364. }
  365. .Border {
  366. overflow: hidden;
  367. }
  368. .Internal .Border {
  369. background: repeating-linear-gradient(
  370. 45deg,
  371. theme('colors.blue.DEFAULT'),
  372. theme('colors.blue.DEFAULT') 5px,
  373. theme('colors.blue.dark') 5px,
  374. theme('colors.blue.dark') 10px
  375. );
  376. background-size: 14px 14px;
  377. background-position: -1px;
  378. padding: 4px;
  379. border-radius: calc(1.5rem + 4px);
  380. margin: -4px;
  381. }
  382. .Internal .BubbleGradient::before {
  383. background: linear-gradient(
  384. rgba(255, 255, 255, 0),
  385. theme('colors.black.DEFAULT')
  386. );
  387. }
  388. </style>