@ecomcx/ecomweb-editor 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/package.json +25 -7
  2. package/src/index.ts +26 -25
  3. package/src/{ask.tsx → legacy/ask.tsx} +2 -2
  4. package/src/{blockMeta.ts → legacy/block-meta.ts} +1 -1
  5. package/src/{blocks.tsx → legacy/blocks.tsx} +8 -32
  6. package/src/{content.ts → legacy/content.ts} +1 -1
  7. package/src/{handle.tsx → legacy/drag-handle.tsx} +3 -3
  8. package/src/{dynamic.tsx → legacy/dynamic.tsx} +7 -3
  9. package/src/{Editor.tsx → legacy/editor.tsx} +9 -9
  10. package/src/{extensions.ts → legacy/extensions.ts} +1 -1
  11. package/src/legacy/insert-pattern.ts +13 -0
  12. package/src/{inserter.tsx → legacy/inserter.tsx} +6 -5
  13. package/src/{inspector.tsx → legacy/inspector.tsx} +7 -7
  14. package/src/{layoutUi.tsx → legacy/layout-ui.tsx} +6 -5
  15. package/src/{layout.tsx → legacy/layout.tsx} +2 -2
  16. package/src/{media.ts → legacy/media.ts} +1 -1
  17. package/src/{nodes.tsx → legacy/nodes.tsx} +2 -2
  18. package/src/{outline.tsx → legacy/outline.tsx} +4 -4
  19. package/src/legacy/panels.ts +22 -0
  20. package/src/{rank.ts → legacy/rank.ts} +2 -2
  21. package/src/{registry.ts → legacy/registry.ts} +1 -1
  22. package/src/{handles.tsx → legacy/resize-handles.tsx} +1 -1
  23. package/src/{styleattr.ts → legacy/style-attr.ts} +15 -1
  24. package/src/{synced.tsx → legacy/synced.tsx} +2 -2
  25. package/src/{toolbar.tsx → legacy/toolbar.tsx} +7 -7
  26. package/src/{unknown.tsx → legacy/unknown.tsx} +1 -1
  27. package/src/shared/block-defs.ts +38 -0
  28. package/src/shared/color-swatch.tsx +19 -0
  29. package/src/{panels.ts → shared/panel-store.ts} +4 -21
  30. package/src/{patterns.ts → shared/patterns.ts} +0 -12
  31. package/src/{stylepanel.tsx → shared/style-panel.tsx} +2 -2
  32. package/src/{types.ts → shared/types.ts} +2 -0
  33. package/src/v2/blocks/compat.tsx +51 -0
  34. package/src/v2/blocks/index.ts +42 -0
  35. package/src/v2/blocks/layout.tsx +281 -0
  36. package/src/v2/blocks/media-actions.tsx +76 -0
  37. package/src/v2/blocks/media.tsx +234 -0
  38. package/src/v2/blocks/resize.tsx +111 -0
  39. package/src/v2/blocks/text.tsx +149 -0
  40. package/src/v2/blocks/theme.tsx +293 -0
  41. package/src/v2/blocks/tools.tsx +72 -0
  42. package/src/v2/canvas/block-list.tsx +216 -0
  43. package/src/v2/canvas/canvas-css.ts +131 -0
  44. package/src/v2/canvas/canvas.tsx +379 -0
  45. package/src/v2/canvas/dnd.ts +192 -0
  46. package/src/v2/context.tsx +146 -0
  47. package/src/v2/core/bindings.ts +64 -0
  48. package/src/v2/core/clipboard.ts +238 -0
  49. package/src/v2/core/host.ts +80 -0
  50. package/src/v2/core/model.ts +157 -0
  51. package/src/v2/core/ops.ts +151 -0
  52. package/src/v2/core/patterns.ts +10 -0
  53. package/src/v2/core/registry.ts +135 -0
  54. package/src/v2/core/store.ts +804 -0
  55. package/src/v2/core/structure.ts +106 -0
  56. package/src/v2/core/tables.ts +194 -0
  57. package/src/v2/editor.css +310 -0
  58. package/src/v2/editor.tsx +288 -0
  59. package/src/v2/index.ts +28 -0
  60. package/src/v2/labels.ts +341 -0
  61. package/src/v2/prefs.ts +69 -0
  62. package/src/v2/text/paste.ts +75 -0
  63. package/src/v2/text/rich-schema.ts +96 -0
  64. package/src/v2/text/rich-text.tsx +512 -0
  65. package/src/v2/ui/attr-form.tsx +182 -0
  66. package/src/v2/ui/attr-hints.ts +109 -0
  67. package/src/v2/ui/bindings.tsx +91 -0
  68. package/src/v2/ui/block-descriptions.ts +34 -0
  69. package/src/v2/ui/color-field.tsx +17 -0
  70. package/src/v2/ui/doc-title.tsx +45 -0
  71. package/src/v2/ui/inserter.tsx +300 -0
  72. package/src/v2/ui/inspector.tsx +85 -0
  73. package/src/v2/ui/layout-panel.tsx +159 -0
  74. package/src/v2/ui/list-view.tsx +65 -0
  75. package/src/v2/ui/options.tsx +242 -0
  76. package/src/v2/ui/style-controls.tsx +57 -0
  77. package/src/v2/ui/style-tab.tsx +158 -0
  78. package/src/v2/ui/toolbar.tsx +397 -0
  79. package/src/v2/ui/unit-controls.tsx +99 -0
  80. /package/src/{basic.tsx → legacy/basic.tsx} +0 -0
  81. /package/src/{blockops.ts → legacy/block-ops.ts} +0 -0
  82. /package/src/{boundary.tsx → legacy/boundary.tsx} +0 -0
  83. /package/src/{editor.css → legacy/editor.css} +0 -0
  84. /package/src/{insert.ts → legacy/insert.ts} +0 -0
  85. /package/src/{labels.ts → shared/labels.ts} +0 -0
  86. /package/src/{paste.ts → shared/paste.ts} +0 -0
  87. /package/src/{util.ts → shared/util.ts} +0 -0
@@ -0,0 +1,131 @@
1
+ /**
2
+ * CSS của khung soạn (trong iframe): chỉ phần của trình soạn — viền chọn, chữ gợi ý, nút "+", nhãn header/footer.
3
+ * Nạp TRƯỚC CSS của website nên không đè kiểu dáng nội dung; dùng outline (theme hầu như không dùng) để không đổi bố cục.
4
+ */
5
+ export const CANVAS_CSS = String.raw`
6
+ :root { --ecx-ui-font: "Be Vietnam Pro", ui-sans-serif, system-ui, sans-serif; --ecx-ui: #1a597b; --ecx-ui-nested: #f26251; --ecx-ui-soft: color-mix(in srgb, var(--ecx-ui) 8%, transparent); color-scheme: light; }
7
+ html, body { margin: 0; min-height: 100%; }
8
+ body.ecx-canvas-body { padding: 0; background: #fff; }
9
+ .ecx-canvas-root { min-height: 100vh; padding: 2rem clamp(1rem, 4vw, 3rem) 40vh; box-sizing: border-box; outline: none; }
10
+ .ecx-canvas-root > * { max-width: var(--ecx-content-width, 760px); margin-left: auto; margin-right: auto; }
11
+ .ecx-canvas-root > .ecx-nested, .ecx-canvas-root > .ecx-cover, .ecx-canvas-root > [data-type="columns"], .ecx-canvas-root > .ecx-align-wide { max-width: var(--ecx-wide-width, 1200px); }
12
+ .ecx-canvas-root > .ecx-align-full, .ecx-canvas-root > .ecx-template-part { max-width: none; }
13
+ .ecx-canvas-root.is-wide > * { max-width: var(--ecx-wide-width, 1120px); }
14
+
15
+ .ecx-block { position: relative; scroll-margin: 80px; }
16
+ .ecx-block:focus { outline: none; }
17
+ .ecx-block:not([data-ecx-rich]):hover:not(:has(.ecx-block:hover)) { outline: 1px solid color-mix(in srgb, var(--ecx-ui) 45%, transparent); outline-offset: 1px; }
18
+ .ecx-block.is-selected { outline: 2px solid var(--ecx-ui) !important; outline-offset: 1px; }
19
+ .ecx-block.is-selected.ecx-nested { outline-color: var(--ecx-ui-nested) !important; }
20
+ [data-ecx-rich] { outline: none; white-space: pre-wrap; word-wrap: break-word; caret-color: currentColor; min-height: 1em; }
21
+ [data-ecx-rich]:focus { outline: none; }
22
+ pre [data-ecx-rich], pre[data-ecx-rich] { white-space: pre-wrap; }
23
+ [data-ecx-rich][data-empty][data-placeholder]::before { content: attr(data-placeholder); opacity: .45; pointer-events: none; position: absolute; }
24
+ [data-ecx-rich][data-empty]:not([data-placeholder-always]):not(:focus)::before { content: none; }
25
+ [data-ecx-rich][data-empty] { position: relative; }
26
+ /* min(100%, …) = 0 trong khung co theo nội dung (nút) → dùng độ dài chữ gợi ý, chặn tràn bằng max-width */
27
+ [data-ecx-rich][data-empty][data-placeholder] { min-width: calc(var(--ecx-ph, 0) * .6em); max-width: 100%; }
28
+ span[data-ecx-rich][data-empty][data-placeholder] { display: inline-block; vertical-align: top; }
29
+ [data-ecx-rich][data-empty][data-placeholder]::before { white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
30
+ .ProseMirror-hideselection *::selection { background: transparent; }
31
+ .ProseMirror-selectednode { outline: 2px solid var(--ecx-ui); }
32
+ .ecx-inline-atom { padding: 0 .25em; border-radius: 4px; background: var(--ecx-ui-soft); font-size: .85em; }
33
+
34
+ .ecx-block.is-locked { pointer-events: none; }
35
+ .ecx-block.is-locked .ecx-nested:not(.is-locked), .ecx-block.is-locked [data-ecx-editable-doc] { pointer-events: auto; }
36
+
37
+ .ecx-default-appender { cursor: text; color: #5d6a75; margin: 0; padding: .25em 0; }
38
+ .ecx-default-appender:focus { outline: none; }
39
+ .ecx-appender { display: flex; align-items: center; justify-content: center; width: 100%; min-height: 44px; margin: 0; border: 1px dashed color-mix(in srgb, currentColor 30%, transparent); border-radius: 4px; background: transparent; color: inherit; font: 600 20px/1 var(--ecx-ui-font); cursor: pointer; opacity: .6; }
40
+ .ecx-appender:hover { opacity: 1; border-color: var(--ecx-ui); color: var(--ecx-ui); }
41
+
42
+ .ecx-placeholder-block, .ecx-media-placeholder { display: flex; flex-direction: column; gap: .5rem; padding: 1rem; border: 1px dashed color-mix(in srgb, currentColor 30%, transparent); border-radius: 6px; font: 14px/1.4 var(--ecx-ui-font); }
43
+ .ecx-placeholder-block.is-unknown { border-color: #d97706; background: rgba(217, 119, 6, .05); }
44
+ .ecx-placeholder-title { display: inline-flex; align-items: center; gap: .4rem; font-weight: 600; }
45
+ .ecx-placeholder-summary { opacity: .65; font-size: 12px; }
46
+ .ecx-icon { width: 1em; height: 1em; flex: none; }
47
+ .ecx-media-actions { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; }
48
+ .ecx-media-actions form { display: flex; gap: .5rem; flex: 1; min-width: 220px; }
49
+ .ecx-input { flex: 1; min-width: 0; height: 32px; padding: 0 .6rem; border: 1px solid #e2e6ea; border-radius: 6px; font: 13px var(--ecx-ui-font); }
50
+ .ecx-btn { height: 32px; padding: 0 .8rem; border: 1px solid #e2e6ea; border-radius: 6px; background: #fff; color: #0f1e29; font: 500 13px var(--ecx-ui-font); cursor: pointer; }
51
+ .ecx-btn-primary { background: var(--ecx-ui); border-color: var(--ecx-ui); color: #fff; }
52
+ .ecx-media-pick { display: inline-flex; align-items: center; gap: .4rem; padding: 2rem; width: 100%; justify-content: center; border: 1px dashed #c9d0d7; border-radius: 8px; background: #f5f6f8; color: #475561; font: 500 13px var(--ecx-ui-font); cursor: pointer; }
53
+ .ecx-code-input { width: 100%; box-sizing: border-box; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; padding: .75rem; border: 1px solid #e2e6ea; border-radius: 6px; }
54
+ .ecx-html-preview { width: 100%; min-height: 80px; border: 0; pointer-events: none; }
55
+ .ecx-embed-preview { display: flex; align-items: center; gap: .5rem; padding: 1rem; border: 1px solid color-mix(in srgb, currentColor 20%, transparent); border-radius: 6px; font: 14px var(--ecx-ui-font); }
56
+ .ecx-embed-url { opacity: .6; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
57
+ .ecx-block-error { padding: .75rem; border: 1px solid #dc2626; color: #dc2626; border-radius: 6px; font: 13px var(--ecx-ui-font); }
58
+
59
+ .ecx-nested { position: relative; }
60
+ .ecx-nested-label { position: absolute; top: 0; left: 0; transform: translateY(-100%); display: none; align-items: center; gap: .3rem; padding: 2px 8px; background: var(--ecx-ui-nested); color: #fff; font: 600 11px/1.6 var(--ecx-ui-font); border-radius: 6px 6px 0 0; z-index: 5; white-space: nowrap; pointer-events: none; }
61
+ .ecx-nested:hover:not(:has(.ecx-block:hover)) { outline: 1px solid var(--ecx-ui-nested) !important; }
62
+ .ecx-nested:hover > .ecx-nested-label, .ecx-nested.is-selected > .ecx-nested-label { display: inline-flex; }
63
+ .ecx-nested.is-pending { min-height: 48px; }
64
+ .ecx-nested-note { padding: .75rem; font: 13px var(--ecx-ui-font); opacity: .6; }
65
+ .is-focus-mode { background: #f3f4f6; padding-top: 1rem; }
66
+ .is-focus-mode > .ecx-block { background: #fff; }
67
+ .ecx-focus-bar { display: flex; align-items: center; gap: .75rem; max-width: none !important; margin: 0 0 1rem; font: 13px var(--ecx-ui-font); color: #475561; }
68
+ .ecx-focus-back { border: 0; background: none; color: var(--ecx-ui); font: 600 13px var(--ecx-ui-font); cursor: pointer; padding: 0; }
69
+
70
+ .ecx-logo-placeholder, .ecx-image-placeholder { display: inline-flex; align-items: center; justify-content: center; min-height: 48px; width: 100%; height: 100%; background: color-mix(in srgb, currentColor 8%, transparent); }
71
+ .ecx-content-placeholder { display: flex; align-items: center; gap: .5rem; padding: 2rem; border: 1px dashed color-mix(in srgb, currentColor 30%, transparent); border-radius: 6px; }
72
+ .ecx-post-preview { opacity: .8; list-style: none; transition: opacity .15s ease; }
73
+ .ecx-post-preview:hover { opacity: 1; }
74
+ .ecx-preview-bar { height: 1em; margin: .5em 0; border-radius: 3px; background: color-mix(in srgb, currentColor 15%, transparent); }
75
+ .ecx-preview-bar.is-short { width: 60%; }
76
+
77
+ .ecx-drop-indicator { position: absolute; z-index: 50; background: var(--ecx-ui); border-radius: 2px; pointer-events: none; }
78
+ body.is-dragging, body.is-dragging * { cursor: grabbing !important; user-select: none !important; }
79
+ .ecx-block.is-dragging-source { opacity: .35; }
80
+
81
+ /* Làm nổi khối đang sửa: các khối cấp cao nhất khác mờ đi */
82
+ .is-spotlight > .ecx-block:not(.is-selected):not(.is-editing):not(:has(.is-selected, .is-editing)) { opacity: .3; transition: opacity .2s ease; }
83
+ /* Ô tiêu đề bài trong khung soạn: kiểu chữ của h1 theme */
84
+ .ecx-doc-title { margin-top: 0; }
85
+ .ecx-doc-title-input { display: block; width: 100%; margin: 0; padding: 0; border: 0; outline: none; resize: none; overflow: hidden; background: transparent; color: inherit; font: inherit; letter-spacing: inherit; line-height: inherit; text-align: inherit; }
86
+ .ecx-doc-title-input::placeholder { color: inherit; opacity: .35; }
87
+ .ecx-col-handles { position: absolute; inset: 0; pointer-events: none; z-index: 6; }
88
+ .ecx-col-handle { position: absolute; width: 12px; margin-left: -6px; cursor: col-resize; pointer-events: auto; touch-action: none; }
89
+ .ecx-col-handle::after { content: ""; position: absolute; left: 5px; top: 0; bottom: 0; width: 2px; background: var(--ecx-ui); opacity: .35; border-radius: 1px; }
90
+ .ecx-col-handle:hover::after { opacity: 1; }
91
+ .ecx-image-handle { position: absolute; z-index: 6; width: 14px; height: 14px; border: 2px solid #fff; border-radius: 50%; background: var(--ecx-ui); cursor: nwse-resize; touch-action: none; box-shadow: 0 0 0 1px var(--ecx-ui); }
92
+
93
+ .ecx-block.ecx-frame-content { outline: 1px dashed color-mix(in srgb, var(--ecx-ui) 50%, transparent); outline-offset: 4px; pointer-events: auto; }
94
+ .ecx-block.is-locked:not(.ecx-frame-content) { cursor: default; }
95
+
96
+ [data-ecx-bound] { cursor: default; }
97
+ .ecx-bound { box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--ecx-ui) 55%, transparent); }
98
+ .ecx-bound.is-empty { color: color-mix(in srgb, currentColor 55%, transparent); font-style: italic; }
99
+ .ecx-bound-media { display: flex; align-items: center; justify-content: center; min-height: 160px; border: 1px dashed color-mix(in srgb, var(--ecx-ui) 60%, transparent); border-radius: 8px; box-shadow: none; }
100
+ img[data-ecx-bound] { outline: 2px solid color-mix(in srgb, var(--ecx-ui) 45%, transparent); outline-offset: -2px; }
101
+
102
+ .is-zoomed-out .ecx-block, .is-zoomed-out [data-ecx-rich] { cursor: pointer; caret-color: transparent; }
103
+ .is-zoomed-out .ecx-appender, .is-zoomed-out .ecx-default-appender, .is-zoomed-out .ecx-image-handle, .is-zoomed-out .ecx-col-handles { display: none !important; }
104
+ .is-zoomed-out .ecx-block.is-selected { outline-width: 4px; }
105
+
106
+ ::highlight(ecx-range) { background-color: color-mix(in srgb, var(--ecx-ui) 28%, transparent); }
107
+ .has-text-range [data-ecx-rich] { user-select: none; -webkit-user-select: none; caret-color: transparent; }
108
+ .ecx-block.is-in-range { background: color-mix(in srgb, var(--ecx-ui) 14%, transparent); outline: 2px solid color-mix(in srgb, var(--ecx-ui) 45%, transparent); }
109
+
110
+ .ecx-post.is-active { outline: 1px dashed color-mix(in srgb, var(--ecx-ui) 55%, transparent); outline-offset: 6px; }
111
+ .ecx-post-preview { cursor: pointer; }
112
+ .ecx-post-preview:hover { outline: 1px solid color-mix(in srgb, var(--ecx-ui) 35%, transparent); outline-offset: 6px; }
113
+ .ecx-post-preview .ecx-block { pointer-events: none; }
114
+ .ecx-post-none { font-size: .85em; opacity: .7; }
115
+
116
+ /* Chỉ trong trình soạn: khối "vô hình" trên website vẫn thấy được để chọn / sửa */
117
+ .ecx-spacer { background: repeating-linear-gradient(-45deg, transparent 0 6px, color-mix(in srgb, var(--ecx-ui) 8%, transparent) 6px 7px); }
118
+ .ecx-block.ecx-column:not(.is-selected):not(.is-editing) { outline: 1px dashed color-mix(in srgb, currentColor 16%, transparent); outline-offset: -1px; min-height: 48px; }
119
+ .ecx-block.ecx-column:not(.is-selected):hover { outline-color: color-mix(in srgb, var(--ecx-ui) 55%, transparent); }
120
+ .ecx-media-placeholder.is-drop-target { outline: 2px dashed var(--ecx-ui); background: color-mix(in srgb, var(--ecx-ui) 6%, transparent); }
121
+ .ecx-placeholder-hint { margin: 4px 0 10px; font: 13px/1.5 var(--ecx-ui-font); opacity: .75; }
122
+ .ecx-media-buttons { display: flex; flex-wrap: wrap; gap: 8px; }
123
+ .ecx-media-actions form { display: flex; gap: 6px; margin-top: 8px; }
124
+ .ecx-media-actions form .ecx-input { flex: 1; }
125
+ .ecx-media-error { color: #b42318; font: 12px var(--ecx-ui-font); margin: 6px 0 0; }
126
+ .ecx-cover-placeholder { min-height: 220px; }
127
+ .ecx-btn-ghost { background: none; border-color: transparent; }
128
+ .ecx-add-column { position: absolute; right: -14px; top: 50%; transform: translateY(-50%); z-index: 7; width: 28px; height: 28px; padding: 0; border: 0; border-radius: 6px; background: #0f1e29; color: #fff; font: 600 18px/1 var(--ecx-ui-font); cursor: pointer; box-shadow: 0 2px 6px rgb(0 0 0 / .2); }
129
+ .ecx-add-column:hover { background: var(--ecx-ui); }
130
+ .is-zoomed-out .ecx-add-column { display: none; }
131
+ `;
@@ -0,0 +1,379 @@
1
+ import { collectStyles, normalizeStyle, presetCss, type BlockStyle } from "@ecomcx/ecomweb-content";
2
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
3
+ import { createPortal } from "react-dom";
4
+ import { DocBlocks } from "./block-list";
5
+ import { BLOCKS_MIME, blocksFromClipboard, serializeBlocks } from "../core/clipboard";
6
+ import { DocScopeProvider, useEditor, useEditorState, useUiTick } from "../context";
7
+ import { usePrefs } from "../prefs";
8
+ import { CANVAS_CSS } from "./canvas-css";
9
+ import { makeBlock, type BNode } from "../core/model";
10
+ import { flatten, topLevelOrdered } from "../core/ops";
11
+ import { insertSibling, now, richViews } from "../text/rich-text";
12
+
13
+ export type Device = "desktop" | "tablet" | "mobile";
14
+ export const DEVICE_WIDTH: Record<Device, number | null> = { desktop: null, tablet: 768, mobile: 390 };
15
+
16
+ export interface CanvasProps {
17
+ device?: Device;
18
+ className?: string;
19
+ /** Class của vùng nội dung trong iframe (theme thường tạo kiểu .ecx-content / .entry-content). */
20
+ contentClassName?: string;
21
+ /** Vẽ thêm quanh nội dung (vd tiêu đề bài phía trên). */
22
+ before?: ReactNode;
23
+ after?: ReactNode;
24
+ }
25
+
26
+ const SRC_DOC = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head><body class="ecx-canvas-body"></body></html>`;
27
+
28
+ /** Khung soạn: iframe mang CSS của website → soạn thấy đúng phông, màu, khoảng cách; media query theo bề rộng thiết bị. */
29
+ /** Tỉ lệ của chế độ thu nhỏ. */
30
+ export const ZOOM_OUT = 0.5;
31
+
32
+ export function Canvas({ device = "desktop", className, contentClassName = "ecx-content", before, after }: CanvasProps) {
33
+ const { ui, labels } = useEditor();
34
+ const frameRef = useRef<HTMLIFrameElement>(null);
35
+ const [doc, setDoc] = useState<Document | null>(null);
36
+
37
+ const onLoad = useCallback(() => {
38
+ const f = frameRef.current;
39
+ const d = f?.contentDocument;
40
+ if (!f || !d) return;
41
+ ui.canvasFrame = f;
42
+ ui.canvasDoc = d;
43
+ setDoc(d);
44
+ ui.bump();
45
+ }, [ui]);
46
+
47
+ // srcDoc có thể đã nạp xong trước khi React gắn onLoad
48
+ useLayoutEffect(() => {
49
+ const d = frameRef.current?.contentDocument;
50
+ if (d && d.readyState === "complete" && d.body?.classList.contains("ecx-canvas-body")) onLoad();
51
+ }, [onLoad]);
52
+
53
+ useEffect(() => () => { if (ui.canvasFrame === frameRef.current) { ui.canvasFrame = null; ui.canvasDoc = null; } }, [ui]);
54
+
55
+ useUiTick();
56
+ const width = DEVICE_WIDTH[device];
57
+ // Thu nhỏ: khung soạn vẽ ở cỡ gấp đôi rồi thu còn một nửa → thấy cả trang, toạ độ kéo thả / thanh công cụ tự tính theo tỉ lệ
58
+ const zoom = ui.zoomOut ? ZOOM_OUT : 1;
59
+ const style = zoom === 1 ? { width: width ? `${width}px` : "100%" }
60
+ : { width: width ? `${width}px` : `${100 / zoom}%`, height: `${100 / zoom}%`, transform: `scale(${zoom})`, transformOrigin: width ? "top center" : "top left", flex: "none" };
61
+ return (
62
+ <div className={["ecx-canvas-wrap", `is-${device}`, zoom !== 1 && "is-zoomed-out", className].filter(Boolean).join(" ")}>
63
+ <iframe ref={frameRef} className="ecx-canvas-frame" title={labels.canvas} srcDoc={SRC_DOC} onLoad={onLoad}
64
+ style={style} data-ecx-canvas="" />
65
+ {doc && createPortal(<CanvasRoot doc={doc} contentClassName={contentClassName} before={before} after={after} />, doc.body)}
66
+ </div>
67
+ );
68
+ }
69
+
70
+ function CanvasRoot({ doc, contentClassName, before, after }: { doc: Document; contentClassName: string; before?: ReactNode; after?: ReactNode }) {
71
+ const { store, labels, prefs, ui } = useEditor();
72
+ const spotlight = usePrefs(prefs).spotlight;
73
+ useUiTick();
74
+ const focus = useEditorState((s) => s.focus[s.focus.length - 1] ?? null);
75
+ const rootId = useEditorState((s) => s.rootId);
76
+ const frameId = useEditorState((s) => s.frameId);
77
+ const activeId = focus ?? rootId;
78
+ // Sửa trang trong template: vẽ template (khoá), khối "Nội dung bài" bên trong vẽ tài liệu gốc
79
+ const viewId = !focus && frameId ? frameId : activeId;
80
+ const mode = useEditorState(useCallback((s) => s.docs[activeId]?.mode ?? "default", [activeId]));
81
+ const title = useEditorState(useCallback((s) => s.docs[activeId]?.title, [activeId]));
82
+ useCanvasStyles(doc);
83
+ useCanvasKeys(doc);
84
+ useCanvasEvents(doc);
85
+ const hasRange = useRangeHighlight(doc);
86
+ return (
87
+ <div className={["ecx-canvas-root", contentClassName, focus && "is-focus-mode", spotlight && "is-spotlight", ui.zoomOut && "is-zoomed-out", hasRange && "has-text-range"].filter(Boolean).join(" ")} data-ecx-doc={activeId} tabIndex={-1}
88
+ onDoubleClick={() => { if (ui.zoomOut) zoomIn(store, ui); }}
89
+ onMouseDown={(e) => {
90
+ if (ui.zoomOut) return store.clearSelection();
91
+ // Bấm vào chỗ trống: bỏ chọn; bấm dưới khối cuối: thêm / đưa con trỏ vào đoạn trống cuối
92
+ if (e.target !== e.currentTarget) return;
93
+ const d = store.doc(activeId);
94
+ if (!d || d.mode !== "default") return store.clearSelection();
95
+ const last = d.blocks[d.blocks.length - 1];
96
+ const lastEl = last ? doc.querySelector(`[data-ecx-block="${CSS.escape(last.id)}"]`) : null;
97
+ if (lastEl && e.clientY < lastEl.getBoundingClientRect().bottom) return store.clearSelection();
98
+ e.preventDefault();
99
+ if (last?.type === "paragraph" && !(last.inline ?? []).length) store.focusText(last.id, 0);
100
+ else store.insert(activeId, null, d.blocks.length, [makeBlock("paragraph")]);
101
+ }}>
102
+ {focus && <div className="ecx-focus-bar" contentEditable={false}><button type="button" className="ecx-focus-back" onClick={() => store.exitFocus()}>← {labels.back}</button><span>{title}</span></div>}
103
+ {!focus && before}
104
+ {viewId !== activeId
105
+ ? <DocScopeProvider value={{ docId: viewId, mode: "disabled", depth: 0, chain: [viewId] }}><DocBlocks docId={viewId} /></DocScopeProvider>
106
+ : <DocScopeProvider value={{ docId: activeId, mode, depth: 0 }}><DocBlocks docId={activeId} /></DocScopeProvider>}
107
+ {!focus && after}
108
+ </div>
109
+ );
110
+ }
111
+
112
+ /** CSS trong iframe: nền của trình soạn, CSS website (host), preset theme, kiểu dáng các khối. */
113
+ function useCanvasStyles(doc: Document) {
114
+ const { host, store } = useEditor();
115
+ const head = doc.head;
116
+ useLayoutEffect(() => {
117
+ const nodes: HTMLElement[] = [];
118
+ const add = (el: HTMLElement) => { head.appendChild(el); nodes.push(el); };
119
+ const base = doc.createElement("style");
120
+ base.dataset.ecx = "canvas";
121
+ base.textContent = CANVAS_CSS;
122
+ add(base);
123
+ for (const s of host.canvasStyles ?? []) {
124
+ if (typeof s === "string") {
125
+ const l = doc.createElement("link");
126
+ l.rel = "stylesheet";
127
+ l.href = s;
128
+ add(l);
129
+ } else {
130
+ const st = doc.createElement("style");
131
+ st.textContent = s.css;
132
+ add(st);
133
+ }
134
+ }
135
+ // Màu viền chọn / phần dùng chung theo màu của giao diện bên ngoài (thương hiệu, sáng/tối)
136
+ const outer = doc.defaultView?.frameElement as HTMLElement | null;
137
+ if (outer) {
138
+ const cs = getComputedStyle(outer);
139
+ const vars = [["--ecx-ui", "--ecx-ed-accent"], ["--ecx-ui-nested", "--ecx-ed-brand"], ["--ecx-ui-font", "--ecx-ed-font"]]
140
+ .map(([inner, from]) => [inner, cs.getPropertyValue(from).trim()]).filter(([, v]) => v);
141
+ if (vars.length) {
142
+ const st = doc.createElement("style");
143
+ st.dataset.ecx = "chrome";
144
+ st.textContent = `:root{${vars.map(([k, v]) => `${k}:${v}`).join(";")}}`;
145
+ add(st);
146
+ }
147
+ }
148
+ if (host.presets) {
149
+ const p = doc.createElement("style");
150
+ p.dataset.ecx = "presets";
151
+ p.textContent = presetCss(host.presets, ":root");
152
+ add(p);
153
+ }
154
+ return () => nodes.forEach((n) => n.remove());
155
+ }, [doc, head, host.canvasStyles, host.presets]);
156
+
157
+ // Kiểu dáng khối (class ecx-s-…) gom từ mọi tài liệu đang mở — cùng hàm website dùng
158
+ const docs = useEditorState((s) => s.docs);
159
+ // Kiểu dáng gom theo từng cây khối (cache theo tham chiếu): gõ chữ không đổi style → không duyệt lại cả tài liệu dài
160
+ const perTree = useRef(new WeakMap<BNode[], BlockStyle[]>());
161
+ const css = useMemo(() => {
162
+ const styles: BlockStyle[] = [];
163
+ for (const d of Object.values(docs)) {
164
+ let list = perTree.current.get(d.blocks);
165
+ if (!list) {
166
+ list = [];
167
+ for (const b of flatten(d.blocks)) if (b.attrs.style && typeof b.attrs.style === "object") { const st = normalizeStyle(b.attrs.style); if (st) list.push(st); }
168
+ perTree.current.set(d.blocks, list);
169
+ }
170
+ styles.push(...list);
171
+ }
172
+ return collectStyles(styles);
173
+ }, [docs]);
174
+ void store;
175
+ useLayoutEffect(() => {
176
+ let el = head.querySelector<HTMLStyleElement>("style[data-ecx=blocks]");
177
+ if (!el) { el = doc.createElement("style"); el.dataset.ecx = "blocks"; head.appendChild(el); }
178
+ el.textContent = css;
179
+ }, [css, doc, head]);
180
+ }
181
+
182
+ /** Cuộn / đổi cỡ trong iframe → thanh công cụ đo lại vị trí. */
183
+ function useCanvasEvents(doc: Document) {
184
+ const { ui } = useEditor();
185
+ useEffect(() => {
186
+ const win = doc.defaultView!;
187
+ let raf = 0;
188
+ const bump = () => { cancelAnimationFrame(raf); raf = win.requestAnimationFrame(() => ui.bump()); };
189
+ win.addEventListener("scroll", bump, { passive: true });
190
+ // Rê chuột: thôi chế độ đang gõ → thanh công cụ hiện lại
191
+ const moved = () => ui.setTyping(false);
192
+ doc.addEventListener("mousemove", moved, { passive: true });
193
+ document.addEventListener("mousemove", moved, { passive: true });
194
+ win.addEventListener("resize", bump);
195
+ const ro = new ResizeObserver(bump);
196
+ ro.observe(doc.body);
197
+ return () => {
198
+ win.removeEventListener("scroll", bump); win.removeEventListener("resize", bump); ro.disconnect(); cancelAnimationFrame(raf);
199
+ doc.removeEventListener("mousemove", moved); document.removeEventListener("mousemove", moved);
200
+ };
201
+ }, [doc, ui]);
202
+ }
203
+
204
+ /** Đang gõ chữ / ô nhập: phím thuộc về ô đó. */
205
+ const typing = (el: Element | null) => !!el && ((el as HTMLElement).isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
206
+
207
+ /** Phím khi đang chọn khối (không gõ chữ): xoá, nhân bản, di chuyển, chép/cắt/dán, hoàn tác. */
208
+ function useCanvasKeys(doc: Document) {
209
+ const { store, ui } = useEditor();
210
+ useEffect(() => {
211
+ const onKey = (e: KeyboardEvent) => {
212
+ // Ô gõ (ProseMirror) đã xử lý phím này
213
+ if (e.defaultPrevented) return;
214
+ const mod = e.metaKey || e.ctrlKey;
215
+ const k = e.key.toLowerCase();
216
+ if (mod && k === "z") { e.preventDefault(); if (e.shiftKey) store.redo(); else store.undo(); return; }
217
+ if (mod && k === "y") { e.preventDefault(); store.redo(); return; }
218
+ if (typing(doc.activeElement)) return;
219
+ // Phím điều hướng của trình duyệt khi không gõ chữ (Safari: ⌘← / ⌘→ = quay lại / tới trang; Backspace ở trình duyệt cũ)
220
+ // → chặn, không thì rời trình soạn và mất bài đang sửa
221
+ if ((e.metaKey || e.altKey) && (e.key === "ArrowLeft" || e.key === "ArrowRight") && !store.getState().range) { e.preventDefault(); return; }
222
+ // Đang chọn chữ qua nhiều khối: xoá / gõ đè / Enter / mở rộng / thu về
223
+ const range = store.getState().range;
224
+ if (range) {
225
+ if (e.key === "Backspace" || e.key === "Delete") { e.preventDefault(); now(() => store.deleteRange()); return; }
226
+ if (e.key === "Escape") { e.preventDefault(); store.clearSelection(); return; }
227
+ if (e.key === "Enter") {
228
+ e.preventDefault();
229
+ now(() => store.batch(() => { if (store.deleteRange()) { const c = store.getState().caret; if (c) store.splitText(c.id, c.offset); } }));
230
+ return;
231
+ }
232
+ if (e.shiftKey && (e.key === "ArrowDown" || e.key === "ArrowUp")) { e.preventDefault(); store.extendRange(e.key === "ArrowDown" ? 1 : -1); return; }
233
+ if (!e.shiftKey && /^Arrow/.test(e.key)) {
234
+ e.preventDefault();
235
+ const info = store.rangeInfo();
236
+ const p = info && (e.key === "ArrowDown" || e.key === "ArrowRight" ? info.to : info.from);
237
+ if (p) store.focusText(p.id, p.offset);
238
+ return;
239
+ }
240
+ if (!mod && !e.altKey && e.key.length === 1) { e.preventDefault(); now(() => store.deleteRange(e.key)); return; }
241
+ }
242
+ if (e.key === "Backspace" && !store.getState().selection.ids.length) { e.preventDefault(); return; }
243
+ const ids = store.getState().selection.ids;
244
+ if (mod && k === "a") {
245
+ e.preventDefault();
246
+ store.select(store.getState().docs[store.activeDocId].blocks.map((b) => b.id), { editing: null });
247
+ return;
248
+ }
249
+ if (ui.zoomOut) {
250
+ // Thu nhỏ: Enter / Esc về cỡ thường; mũi tên đi giữa các phần
251
+ if (e.key === "Escape" || (e.key === "Enter" && ids.length)) { e.preventDefault(); zoomIn(store, ui); return; }
252
+ if ((e.key === "ArrowDown" || e.key === "ArrowUp") && !e.shiftKey) {
253
+ e.preventDefault();
254
+ const top = store.getState().docs[store.activeDocId]?.blocks ?? [];
255
+ const i = ids.length ? top.findIndex((b) => b.id === ids[0]) : -1;
256
+ const next = top[Math.max(0, Math.min(top.length - 1, i + (e.key === "ArrowDown" ? 1 : -1)))];
257
+ if (next) { store.select([next.id], { editing: null }); ui.blockEl(next.id)?.scrollIntoView({ block: "nearest" }); }
258
+ return;
259
+ }
260
+ }
261
+ if (!ids.length) return;
262
+ if (e.altKey && e.key === "F10") { e.preventDefault(); ui.focusToolbar(); return; }
263
+ if (e.key === "Backspace" || e.key === "Delete") { e.preventDefault(); store.remove(ids); return; }
264
+ if (e.key === "Escape") { e.preventDefault(); store.clearSelection(); ui.openInserter(null); return; }
265
+ if (e.key === "Enter" && ids.length === 1) {
266
+ e.preventDefault();
267
+ const b = store.block(ids[0]);
268
+ if (b?.inline) store.focusText(b.id, -1);
269
+ else insertSibling(store, ids[0], 1);
270
+ return;
271
+ }
272
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
273
+ e.preventDefault();
274
+ const dir = e.key === "ArrowDown" ? 1 : -1;
275
+ const loc = store.locate(ids[dir > 0 ? ids.length - 1 : 0]);
276
+ if (!loc) return;
277
+ const order = flatten(store.getState().docs[loc.docId].blocks).filter((b) => !HIDDEN_NAV.has(b.type));
278
+ const i = order.findIndex((b) => b.id === loc.block.id);
279
+ const next = order[i + dir];
280
+ if (!next) return;
281
+ if (e.shiftKey) store.selectRange(next.id); else store.select([next.id], { editing: null });
282
+ ui.blockEl(next.id)?.focus({ preventScroll: false });
283
+ return;
284
+ }
285
+ if (mod && e.shiftKey && k === "d") { e.preventDefault(); store.duplicate(ids); return; }
286
+ if (e.altKey && e.shiftKey && k === "z") { e.preventDefault(); store.remove(ids); return; }
287
+ if (mod && e.altKey && k === "t") { e.preventDefault(); insertSibling(store, ids[0], 0); return; }
288
+ if (mod && e.altKey && k === "y") { e.preventDefault(); insertSibling(store, ids[ids.length - 1], 1); return; }
289
+ };
290
+ const selectedNodes = (): BNode[] => {
291
+ if (store.getState().range) return store.rangeContent();
292
+ const ids = store.getState().selection.ids;
293
+ const loc = ids.length ? store.locate(ids[0]) : null;
294
+ if (!loc) return [];
295
+ return topLevelOrdered(store.getState().docs[loc.docId].blocks, ids).map((id) => store.block(id)!).filter(Boolean);
296
+ };
297
+ const onCopy = (e: ClipboardEvent, cut = false) => {
298
+ if (typing(doc.activeElement) || !e.clipboardData) return;
299
+ const nodes = selectedNodes();
300
+ if (!nodes.length) return;
301
+ const s = serializeBlocks(nodes);
302
+ e.clipboardData.setData(BLOCKS_MIME, s.json);
303
+ e.clipboardData.setData("text/html", s.html);
304
+ e.clipboardData.setData("text/plain", s.text);
305
+ e.preventDefault();
306
+ if (cut && store.getState().range) store.deleteRange();
307
+ else if (cut) store.remove(nodes.map((n) => n.id));
308
+ };
309
+ const onPaste = (e: ClipboardEvent) => {
310
+ if (typing(doc.activeElement) || !e.clipboardData) return;
311
+ const nodes = blocksFromClipboard(e.clipboardData);
312
+ if (!nodes.length) return;
313
+ e.preventDefault();
314
+ // Dán đè lên dải chữ: xoá rồi chèn sau khối còn lại
315
+ if (store.getState().range && store.deleteRange()) { const c = store.getState().caret; if (c) { store.insertAfter(c.id, nodes, { replaceEmpty: true }); return; } }
316
+ const ids = store.getState().selection.ids;
317
+ if (ids.length) store.insertAfter(ids[ids.length - 1], nodes, { replaceEmpty: false });
318
+ else {
319
+ const docId = store.activeDocId;
320
+ store.insert(docId, null, store.getState().docs[docId].blocks.length, nodes);
321
+ }
322
+ };
323
+ const cut = (e: ClipboardEvent) => onCopy(e, true);
324
+ doc.addEventListener("keydown", onKey);
325
+ doc.addEventListener("copy", onCopy as EventListener);
326
+ doc.addEventListener("cut", cut as EventListener);
327
+ doc.addEventListener("paste", onPaste as EventListener);
328
+ return () => {
329
+ doc.removeEventListener("keydown", onKey);
330
+ doc.removeEventListener("copy", onCopy as EventListener);
331
+ doc.removeEventListener("cut", cut as EventListener);
332
+ doc.removeEventListener("paste", onPaste as EventListener);
333
+ };
334
+ }, [doc, store, ui]);
335
+ }
336
+
337
+ /** Khối không chọn riêng bằng phím mũi tên (đi thẳng vào chữ bên trong). */
338
+ const HIDDEN_NAV = new Set(["listItem", "taskItem", "tableRow"]);
339
+
340
+ /** Thôi thu nhỏ: phần đang chọn cuộn vào giữa màn hình. */
341
+ export function zoomIn(store: { getState(): { selection: { ids: string[] } } }, ui: { setZoomOut(v: boolean): void; blockEl(id: string): HTMLElement | null }) {
342
+ ui.setZoomOut(false);
343
+ const id = store.getState().selection.ids[0];
344
+ if (id) requestAnimationFrame(() => ui.blockEl(id)?.scrollIntoView({ block: "center" }));
345
+ }
346
+
347
+ /**
348
+ * Tô dải chữ chọn qua nhiều khối: CSS Custom Highlight (không đụng vùng chọn / focus của ô gõ); khối nguyên ở giữa (ảnh…)
349
+ * có viền chọn. Trình duyệt chưa có Highlight → tô cả khối chữ.
350
+ */
351
+ function useRangeHighlight(doc: Document): boolean {
352
+ const { store, ui } = useEditor();
353
+ const range = useEditorState((s) => s.range);
354
+ const revision = useEditorState((s) => s.revision);
355
+ useLayoutEffect(() => {
356
+ const win = doc.defaultView as (Window & { Highlight?: new (...r: Range[]) => unknown; CSS: { highlights?: Map<string, unknown> } }) | null;
357
+ const marked: HTMLElement[] = [];
358
+ const info = range ? store.rangeInfo() : null;
359
+ if (info && win) {
360
+ const a = richViews.get(info.from.id), b = richViews.get(info.to.id);
361
+ const highlights = win.CSS?.highlights;
362
+ if (a && b && highlights && win.Highlight) {
363
+ try {
364
+ const r = doc.createRange();
365
+ const s = a.domAtPos(Math.min(info.from.offset, a.state.doc.content.size)), t = b.domAtPos(Math.min(info.to.offset, b.state.doc.content.size));
366
+ r.setStart(s.node, s.offset);
367
+ r.setEnd(t.node, t.offset);
368
+ highlights.set("ecx-range", new win.Highlight(r));
369
+ } catch { highlights.delete("ecx-range"); }
370
+ } else for (const tb of info.texts) { const el = ui.blockEl(tb.id); if (el) { el.classList.add("is-in-range"); marked.push(el); } }
371
+ for (const id of info.whole) { const el = ui.blockEl(id); if (el) { el.classList.add("is-in-range"); marked.push(el); } }
372
+ }
373
+ return () => {
374
+ win?.CSS?.highlights?.delete("ecx-range");
375
+ for (const el of marked) el.classList.remove("is-in-range");
376
+ };
377
+ }, [range, revision, doc, store, ui]);
378
+ return !!range;
379
+ }