highlights-from-diff-response.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import moment from 'moment/moment'
  2. import { DocDiffChunk, Highlight } from '../services/types/doc'
  3. import { TFunction } from 'i18next'
  4. import displayNameForUser from './display-name-for-user'
  5. import { getHueForUserId } from '@/shared/utils/colors'
  6. export function highlightsFromDiffResponse(
  7. chunks: DocDiffChunk[],
  8. t: TFunction<'translation'> // Must be called `t` for i18next-scanner to find calls to it
  9. ) {
  10. let pos = 0
  11. const highlights: Highlight[] = []
  12. let doc = ''
  13. for (const entry of chunks) {
  14. const content = entry.u || entry.i || entry.d || ''
  15. doc += content
  16. const from = pos
  17. const to = doc.length
  18. pos = to
  19. const range = { from, to }
  20. const isInsertion = typeof entry.i === 'string'
  21. const isDeletion = typeof entry.d === 'string'
  22. if (isInsertion || isDeletion) {
  23. const meta = entry.meta
  24. if (!meta) {
  25. throw new Error('No meta found')
  26. }
  27. const user = meta.users?.[0]
  28. const name = displayNameForUser(user)
  29. const date = moment(meta.end_ts).format('Do MMM YYYY, h:mm a')
  30. if (isInsertion) {
  31. highlights.push({
  32. type: 'addition',
  33. // There doesn't seem to be a convenient way to make this translatable
  34. label: t('added_by_on', { name, date }),
  35. range,
  36. hue: getHueForUserId(user?.id),
  37. })
  38. } else if (isDeletion) {
  39. highlights.push({
  40. type: 'deletion',
  41. // There doesn't seem to be a convenient way to make this translatable
  42. label: t('deleted_by_on', { name, date }),
  43. range,
  44. hue: getHueForUserId(user?.id),
  45. })
  46. }
  47. }
  48. }
  49. return { doc, highlights }
  50. }