Utils.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // @ts-check
  2. /**
  3. * @typedef {import('./types').CommentOp} CommentOp
  4. * @typedef {import('./types').DeleteOp} DeleteOp
  5. * @typedef {import('./types').InsertOp} InsertOp
  6. * @typedef {import('./types').Op} Op
  7. * @typedef {import('./types').TrackedChange} TrackedChange
  8. */
  9. /**
  10. * Returns true if the op is an insert
  11. *
  12. * @param {Op} op
  13. * @returns {op is InsertOp}
  14. */
  15. function isInsert(op) {
  16. return 'i' in op && op.i != null
  17. }
  18. /**
  19. * Returns true if the op is an insert
  20. *
  21. * @param {Op} op
  22. * @returns {op is DeleteOp}
  23. */
  24. function isDelete(op) {
  25. return 'd' in op && op.d != null
  26. }
  27. /**
  28. * Returns true if the op is a comment
  29. *
  30. * @param {Op} op
  31. * @returns {op is CommentOp}
  32. */
  33. function isComment(op) {
  34. return 'c' in op && op.c != null
  35. }
  36. /**
  37. * Adds given tracked deletes to the given content.
  38. *
  39. * The history system includes tracked deletes in the document content.
  40. *
  41. * @param {string} content
  42. * @param {TrackedChange[]} trackedChanges
  43. * @return {string} content for the history service
  44. */
  45. function addTrackedDeletesToContent(content, trackedChanges) {
  46. let cursor = 0
  47. let result = ''
  48. for (const change of trackedChanges) {
  49. if (isDelete(change.op)) {
  50. // Add the content before the tracked delete
  51. result += content.slice(cursor, change.op.p)
  52. cursor = change.op.p
  53. // Add the content of the tracked delete
  54. result += change.op.d
  55. }
  56. }
  57. // Add the content after all tracked deletes
  58. result += content.slice(cursor)
  59. return result
  60. }
  61. module.exports = { isInsert, isDelete, isComment, addTrackedDeletesToContent }