delta-to-changespecs.ts 681 B

123456789101112131415161718192021222324252627282930313233
  1. import type { ChangeSpec } from '@codemirror/state';
  2. import type { Delta } from '../interfaces';
  3. export const deltaToChangeSpecs = (delta: Delta): ChangeSpec[] => {
  4. const changes: ChangeSpec[] = [];
  5. let pos = 0;
  6. for (const op of delta) {
  7. if (op.retain != null) {
  8. pos += op.retain;
  9. }
  10. if (op.delete != null) {
  11. changes.push({
  12. from: pos,
  13. to: pos + op.delete,
  14. });
  15. }
  16. if (op.insert != null) {
  17. changes.push({
  18. from: pos,
  19. insert: typeof op.insert === 'string' ? op.insert : '',
  20. });
  21. if (typeof op.insert === 'string') {
  22. pos += op.insert.length;
  23. }
  24. }
  25. }
  26. return changes;
  27. };