copy_paste.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { BlockData, DocumentBlockJSON, DocumentState, NestedBlock, RangeState } from '$app/interfaces/document';
  2. import { getDeltaByRange } from '$app/utils/document/delta';
  3. import Delta from 'quill-delta';
  4. import { generateId } from '$app/utils/document/block';
  5. import { DocumentController } from '$app/stores/effects/document/document_controller';
  6. export function getCopyData(
  7. node: NestedBlock,
  8. range: {
  9. index: number;
  10. length: number;
  11. }
  12. ): BlockData<any> {
  13. const nodeDeltaOps = node.data.delta;
  14. if (!nodeDeltaOps) {
  15. return {
  16. ...node.data,
  17. };
  18. }
  19. const delta = getDeltaByRange(new Delta(node.data.delta), range);
  20. return {
  21. ...node.data,
  22. delta: delta.ops,
  23. };
  24. }
  25. export function getCopyBlock(id: string, document: DocumentState, documentRange: RangeState): DocumentBlockJSON {
  26. const node = document.nodes[id];
  27. const range = documentRange.ranges[id] || { index: 0, length: 0 };
  28. const copyData = getCopyData(node, range);
  29. return {
  30. type: node.type,
  31. data: copyData,
  32. children: [],
  33. };
  34. }
  35. export function generateBlocks(data: DocumentBlockJSON[], parentId: string) {
  36. const blocks: NestedBlock[] = [];
  37. function dfs(data: DocumentBlockJSON[], parentId: string) {
  38. data.forEach((item) => {
  39. const block = {
  40. id: generateId(),
  41. type: item.type,
  42. data: item.data,
  43. parent: parentId,
  44. children: generateId(),
  45. };
  46. blocks.push(block);
  47. if (item.children) {
  48. dfs(item.children, block.id);
  49. }
  50. });
  51. }
  52. dfs(data, parentId);
  53. return blocks;
  54. }
  55. export function getInsertBlockActions(blocks: NestedBlock[], prevId: string, controller: DocumentController) {
  56. return blocks.map((block, index) => {
  57. const prevBlockId = index === 0 ? prevId : blocks[index - 1].id;
  58. return controller.getInsertAction(block, prevBlockId);
  59. });
  60. }
  61. export function getAppendBlockDeltaAction(
  62. block: NestedBlock,
  63. appendDelta: Delta,
  64. isForward: boolean,
  65. controller: DocumentController
  66. ) {
  67. const nodeDelta = new Delta(block.data.delta);
  68. const mergeDelta = isForward ? appendDelta.concat(nodeDelta) : nodeDelta.concat(appendDelta);
  69. return controller.getUpdateAction({
  70. ...block,
  71. data: {
  72. ...block.data,
  73. delta: mergeDelta.ops,
  74. },
  75. });
  76. }
  77. export function copyText(text: string) {
  78. return navigator.clipboard.writeText(text);
  79. }