highlights-from-diff-response.ts 1.6 KB

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