@ecomcx/ecomweb-editor 1.23.0 → 1.24.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.
- package/package.json +1 -1
- package/src/locales/en/v2.ts +7 -1
- package/src/locales/vi/v2.ts +7 -1
- package/src/shared/block-defs.ts +2 -0
- package/src/v2/blocks/compat.tsx +3 -0
- package/src/v2/blocks/theme.tsx +51 -9
- package/src/v2/canvas/block-list.tsx +8 -3
- package/src/v2/canvas/canvas-css.ts +6 -0
- package/src/v2/canvas/canvas.tsx +21 -4
- package/src/v2/canvas/document-attrs.ts +41 -0
- package/src/v2/canvas/server-block.tsx +51 -0
- package/src/v2/canvas/server-html.ts +28 -0
- package/src/v2/canvas/wrapper-props.ts +42 -0
- package/src/v2/core/host.ts +19 -1
- package/src/v2/core/registry.ts +8 -0
- package/src/v2/editor.tsx +15 -5
- package/src/v2/ui/inserter.tsx +3 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecomcx/ecomweb-editor",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.24.0",
|
|
4
4
|
"description": "Trình soạn nội dung dạng khối của CMS — dùng độc lập trong mọi dự án React (1.x: TipTap; ./v2: cây khối, khung soạn iframe, sửa header/footer tại chỗ).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
package/src/locales/en/v2.ts
CHANGED
|
@@ -42,6 +42,12 @@ export const v2 = {
|
|
|
42
42
|
alignLeft: "Align left",
|
|
43
43
|
alignCenter: "Align center",
|
|
44
44
|
alignRight: "Align right",
|
|
45
|
+
devices: "Device",
|
|
46
|
+
deviceDesktop: "Desktop",
|
|
47
|
+
deviceTablet: "Tablet",
|
|
48
|
+
deviceMobile: "Phone",
|
|
49
|
+
editMenu: "Edit this menu",
|
|
50
|
+
queryEmptyCollapsed: "When there are no posts (hidden because the list has posts) — click to edit",
|
|
45
51
|
undo: "Undo",
|
|
46
52
|
redo: "Redo",
|
|
47
53
|
listView: "List view",
|
|
@@ -57,7 +63,7 @@ export const v2 = {
|
|
|
57
63
|
saving: "Saving…",
|
|
58
64
|
saved: "Saved",
|
|
59
65
|
unsaved: "Unsaved changes",
|
|
60
|
-
unknownBlock: "
|
|
66
|
+
unknownBlock: "Block from a plugin or theme that is no longer installed — content is kept, reinstall it to edit",
|
|
61
67
|
paragraph: "Paragraph",
|
|
62
68
|
heading: "Heading",
|
|
63
69
|
list: "List",
|
package/src/locales/vi/v2.ts
CHANGED
|
@@ -42,6 +42,12 @@ export const v2 = {
|
|
|
42
42
|
alignLeft: "Căn trái",
|
|
43
43
|
alignCenter: "Căn giữa",
|
|
44
44
|
alignRight: "Căn phải",
|
|
45
|
+
devices: "Thiết bị",
|
|
46
|
+
deviceDesktop: "Máy tính",
|
|
47
|
+
deviceTablet: "Máy tính bảng",
|
|
48
|
+
deviceMobile: "Điện thoại",
|
|
49
|
+
editMenu: "Sửa menu này",
|
|
50
|
+
queryEmptyCollapsed: "Khi không có bài viết (đang ẩn vì danh sách có bài) — bấm để sửa",
|
|
45
51
|
undo: "Hoàn tác",
|
|
46
52
|
redo: "Làm lại",
|
|
47
53
|
listView: "Cây khối",
|
|
@@ -57,7 +63,7 @@ export const v2 = {
|
|
|
57
63
|
saving: "Đang lưu…",
|
|
58
64
|
saved: "Đã lưu",
|
|
59
65
|
unsaved: "Có thay đổi chưa lưu",
|
|
60
|
-
unknownBlock: "Khối
|
|
66
|
+
unknownBlock: "Khối của plugin hoặc theme không còn được cài — nội dung được giữ nguyên, bật lại để sửa",
|
|
61
67
|
paragraph: "Đoạn văn",
|
|
62
68
|
heading: "Tiêu đề",
|
|
63
69
|
list: "Danh sách",
|
package/src/shared/block-defs.ts
CHANGED
|
@@ -21,6 +21,8 @@ export interface RegisterBlockOptions {
|
|
|
21
21
|
edit?: ComponentType<BlockEditProps>;
|
|
22
22
|
/** Dịch nhãn ("%khoá%" → chữ theo ngôn ngữ admin) — admin truyền vào. */
|
|
23
23
|
translate?(text: string): string;
|
|
24
|
+
/** Khối của theme: chỉ chèn được khi soạn template / phần dùng chung (host.scope = "template"), không chèn vào bài viết. */
|
|
25
|
+
templateOnly?: boolean;
|
|
24
26
|
/** Khối chứa khối khác: nội dung có sẵn khi chèn (mặc định một đoạn văn trống). */
|
|
25
27
|
initialContent?(): Array<Record<string, unknown>>;
|
|
26
28
|
}
|
package/src/v2/blocks/compat.tsx
CHANGED
|
@@ -35,7 +35,10 @@ export function syncPluginBlocks(registry: BlockTypeRegistry): () => void {
|
|
|
35
35
|
title: t(def.title),
|
|
36
36
|
description: def.description ? t(def.description) : undefined,
|
|
37
37
|
icon: o.icon ?? Blocks,
|
|
38
|
+
templateOnly: o.templateOnly,
|
|
38
39
|
edit: o.edit ? wrapV1Edit(o.edit) : undefined,
|
|
40
|
+
// Không có xem trước riêng và không chứa khối con → website vẽ bằng renderer của theme/plugin (viết khối một lần)
|
|
41
|
+
serverRender: !o.edit && def.content !== "blocks",
|
|
39
42
|
create: (attrs) => {
|
|
40
43
|
const defaults = Object.fromEntries(Object.entries(def.attributes).filter(([, s]) => s.default !== undefined).map(([k, s]) => [k, s.default]));
|
|
41
44
|
const content = def.content === "blocks" ? (o.initialContent?.() ?? [{ type: "paragraph" }]).map((n) => fromRich(n as never)) : undefined;
|
package/src/v2/blocks/theme.tsx
CHANGED
|
@@ -4,7 +4,7 @@ import { Block, DocBlocks, InnerBlocks, NestedDoc } from "../canvas/block-list";
|
|
|
4
4
|
import { DocScopeProvider, LoopPostContext, useDocScope, useDynamicData, useEditor, useEditorState } from "../context";
|
|
5
5
|
import type { DynamicPost, QueryArgs } from "../core/host";
|
|
6
6
|
import type { BNode } from "../core/model";
|
|
7
|
-
import { makeBlock } from "../core/model";
|
|
7
|
+
import { blocksFromDoc, makeBlock } from "../core/model";
|
|
8
8
|
import type { BlockEditProps, BlockType } from "../core/registry";
|
|
9
9
|
import { useMsgs } from "../i18n";
|
|
10
10
|
|
|
@@ -20,7 +20,9 @@ function SiteTitleEdit({ block, blockProps }: BlockEditProps) {
|
|
|
20
20
|
const d = useDynamic();
|
|
21
21
|
const level = Number(block.attrs.level) || 0;
|
|
22
22
|
const Tag = (level ? `h${Math.min(6, level)}` : "p") as "p";
|
|
23
|
-
|
|
23
|
+
const title = d.site?.title || "Site Title";
|
|
24
|
+
// Website bọc tên trong liên kết về trang chủ (trừ khi tắt "link") → màu / gạch chân của theme cho <a> áp đúng
|
|
25
|
+
return <Tag {...merge(blockProps, "ecx-site-title", align(block.attrs))}>{block.attrs.link === false ? title : <a href="#" rel="home" onClick={(e) => e.preventDefault()}>{title}</a>}</Tag>;
|
|
24
26
|
}
|
|
25
27
|
function SiteTaglineEdit({ block, blockProps }: BlockEditProps) {
|
|
26
28
|
const d = useDynamic();
|
|
@@ -32,7 +34,14 @@ function SiteLogoEdit({ block, blockProps }: BlockEditProps) {
|
|
|
32
34
|
return <div {...merge(blockProps, "ecx-site-logo")}>{d.site?.logo ? <img src={d.site.logo} alt="" width={w} draggable={false} /> : <span className="ecx-logo-placeholder" style={{ width: w }}><ImageIcon className="ecx-icon" /></span>}</div>;
|
|
33
35
|
}
|
|
34
36
|
/** Menu: cùng markup với website (theme-sdk) — nav.ecx-navigation-menu > ul > li > a, nút ☰ cho điện thoại. */
|
|
35
|
-
|
|
37
|
+
/** Nút nhỏ trên khối Menu đang chọn: mở nơi sửa menu của ứng dụng nhúng. */
|
|
38
|
+
function EditMenuButton({ location, selected }: { location: string; selected: boolean }) {
|
|
39
|
+
const { host, labels } = useEditor();
|
|
40
|
+
if (!selected || !host.editMenu) return null;
|
|
41
|
+
return <button type="button" className="ecx-edit-link" contentEditable={false} onMouseDown={(e) => e.stopPropagation()} onClick={() => host.editMenu!(location)}>{labels.editMenu} ↗</button>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function NavigationEdit({ block, blockProps, selected }: BlockEditProps) {
|
|
36
45
|
const d = useDynamic();
|
|
37
46
|
const { labels } = useEditor();
|
|
38
47
|
const location = String(block.attrs.location ?? "primary");
|
|
@@ -44,6 +53,7 @@ function NavigationEdit({ block, blockProps }: BlockEditProps) {
|
|
|
44
53
|
<div {...merge(blockProps, "ecx-navigation ecx-placeholder-block")}>
|
|
45
54
|
<span className="ecx-placeholder-title"><Menu className="ecx-icon" /> {t.menu} · {location}</span>
|
|
46
55
|
<span className="ecx-placeholder-summary">{t.noMenuIsAssigned}</span>
|
|
56
|
+
<EditMenuButton location={location} selected={selected} />
|
|
47
57
|
</div>
|
|
48
58
|
);
|
|
49
59
|
}
|
|
@@ -52,6 +62,7 @@ function NavigationEdit({ block, blockProps }: BlockEditProps) {
|
|
|
52
62
|
<div {...merge(blockProps, cx("ecx-navigation", `ecx-navigation-${block.attrs.orientation ?? "horizontal"}`, mobile && "has-mobile"))}>
|
|
53
63
|
<div className="ecx-navigation-items">{menu}</div>
|
|
54
64
|
{mobile && <details className="ecx-navigation-toggle"><summary aria-label={t.menu}>☰</summary>{menu}</details>}
|
|
65
|
+
<EditMenuButton location={location} selected={selected} />
|
|
55
66
|
</div>
|
|
56
67
|
);
|
|
57
68
|
}
|
|
@@ -73,7 +84,9 @@ function LanguageEdit({ blockProps }: BlockEditProps) {
|
|
|
73
84
|
function PostTitleEdit({ block, blockProps }: BlockEditProps) {
|
|
74
85
|
const d = useDynamic();
|
|
75
86
|
const Tag = `h${Math.min(6, Math.max(1, Number(block.attrs.level) || 1))}` as "h1";
|
|
76
|
-
|
|
87
|
+
const title = d.post?.title || "Post Title";
|
|
88
|
+
// Website bọc tiêu đề trong liên kết tới bài khi bật "link" (danh sách bài) — màu / gạch chân của theme cho <a>
|
|
89
|
+
return <Tag {...merge(blockProps, "ecx-post-title", align(block.attrs))}>{block.attrs.link ? <a href="#" onClick={(e) => e.preventDefault()}>{title}</a> : title}</Tag>;
|
|
77
90
|
}
|
|
78
91
|
function PostExcerptEdit({ block, blockProps }: BlockEditProps) {
|
|
79
92
|
const d = useDynamic();
|
|
@@ -180,8 +193,16 @@ function PostNavigationEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
|
180
193
|
);
|
|
181
194
|
}
|
|
182
195
|
|
|
196
|
+
/** Nội dung đã lưu của bài mẫu → khối chỉ xem (chỉ phần soạn được "richtext"; khối khác của ContentDoc bỏ qua khi xem). */
|
|
197
|
+
function sampleContentNodes(content: unknown): BNode[] | null {
|
|
198
|
+
const blocks = (content as { blocks?: Array<{ type?: string; data?: unknown }> } | null)?.blocks;
|
|
199
|
+
if (!Array.isArray(blocks)) return null;
|
|
200
|
+
const nodes = blocks.filter((b) => b?.type === "richtext" && b.data).flatMap((b) => blocksFromDoc(b.data as never));
|
|
201
|
+
return nodes.length ? nodes : null;
|
|
202
|
+
}
|
|
183
203
|
function PostContentEdit({ blockProps }: BlockEditProps) {
|
|
184
204
|
const { labels } = useEditor();
|
|
205
|
+
const sample = sampleContentNodes(useDynamicData().post?.content);
|
|
185
206
|
const t = useMsgs("blocks");
|
|
186
207
|
const scope = useDocScope();
|
|
187
208
|
const frameId = useEditorState((s) => s.frameId);
|
|
@@ -194,6 +215,8 @@ function PostContentEdit({ blockProps }: BlockEditProps) {
|
|
|
194
215
|
</div>
|
|
195
216
|
);
|
|
196
217
|
}
|
|
218
|
+
// Có bài mẫu → nội dung thật của bài (chỉ xem; sửa nội dung ở trình soạn bài); chưa có → khung giữ chỗ
|
|
219
|
+
if (sample) return <div {...merge(blockProps, "ecx-post-content ecx-content")}><PreviewBlocks nodes={sample} tag="sample-content" /></div>;
|
|
197
220
|
return <div {...merge(blockProps, "ecx-post-content ecx-content-placeholder")}><FileText className="ecx-icon" /> {t.postContent}</div>;
|
|
198
221
|
}
|
|
199
222
|
|
|
@@ -263,11 +286,30 @@ function PostTemplateEdit({ block, blockProps, editable, labels }: BlockEditProp
|
|
|
263
286
|
</ul>
|
|
264
287
|
);
|
|
265
288
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
|
|
289
|
+
/** Bài thật của khối query cha (cùng thiết lập) — để phân trang / "không có bài" phản ánh đúng dữ liệu thay vì mẫu cố định. */
|
|
290
|
+
function useParentQueryPosts(block: BNode): { posts: DynamicPost[] | undefined; perPage: number } {
|
|
291
|
+
const { store } = useEditor();
|
|
292
|
+
const parentAttrs = useEditorState(useCallback(() => store.locate(block.id)?.parent?.attrs, [block.id, store])) ?? {};
|
|
293
|
+
const q = queryArgs(parentAttrs);
|
|
294
|
+
return { posts: useQueryPosts(q), perPage: q.perPage };
|
|
295
|
+
}
|
|
296
|
+
function PaginationEdit({ block, blockProps }: BlockEditProps) {
|
|
297
|
+
const { posts, perPage } = useParentQueryPosts(block);
|
|
298
|
+
// Ít bài hơn một trang → website không hiện phân trang: vẽ mờ một trang duy nhất
|
|
299
|
+
const single = posts !== undefined && posts.length < perPage;
|
|
300
|
+
return <nav {...(merge(blockProps, cx("ecx-pagination", single && "is-single")) as object)} style={single ? { opacity: 0.45 } : undefined}>{single ? "‹ 1 ›" : "‹ 1 2 3 ›"}</nav>;
|
|
301
|
+
}
|
|
302
|
+
function QueryEmptyEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
303
|
+
const { posts } = useParentQueryPosts(block);
|
|
304
|
+
// Danh sách đang có bài → khối "không có bài" không hiện trên website: thu gọn thành nhãn mờ (vẫn chọn / sửa được khi bấm vào)
|
|
305
|
+
const [open, setOpen] = useState(false);
|
|
306
|
+
const hidden = !!posts?.length && !open;
|
|
307
|
+
return (
|
|
308
|
+
<div {...merge(blockProps, cx("ecx-query-empty", hidden && "is-collapsed"))} style={hidden ? { opacity: 0.55 } : undefined}>
|
|
309
|
+
{hidden && <button type="button" contentEditable={false} className="ecx-edit-link" onClick={() => setOpen(true)}>{labels.queryEmptyCollapsed}</button>}
|
|
310
|
+
{!hidden && <InnerBlocks parent={block} />}
|
|
311
|
+
</div>
|
|
312
|
+
);
|
|
271
313
|
}
|
|
272
314
|
|
|
273
315
|
/** Vỏ của tài liệu lồng (header/footer, mẫu đồng bộ): viền tím + nhãn, bấm đúp để sửa riêng. */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { normalizeStyle, styleClass } from "@ecomcx/ecomweb-content";
|
|
2
|
-
import { Component, memo, useCallback, useEffect, useMemo, useRef, type ErrorInfo, type MouseEvent, type ReactElement, type ReactNode } from "react";
|
|
3
|
-
import { DocScopeProvider, useDocScope, useEditor, useEditorState } from "../context";
|
|
2
|
+
import { Component, memo, useCallback, useContext, useEffect, useMemo, useRef, type ErrorInfo, type MouseEvent, type ReactElement, type ReactNode } from "react";
|
|
3
|
+
import { DocScopeProvider, LoopPostContext, useDocScope, useEditor, useEditorState } from "../context";
|
|
4
|
+
import { ServerBlock } from "./server-block";
|
|
4
5
|
import { docIdOf, type NestedDocRef } from "../core/host";
|
|
5
6
|
import { blocksFromDoc, makeBlock, type BNode } from "../core/model";
|
|
6
7
|
import type { BlockEditProps, BlockProps } from "../core/registry";
|
|
@@ -84,7 +85,7 @@ class BlockBoundary extends Component<{ id: string; type: string; children: Reac
|
|
|
84
85
|
|
|
85
86
|
/** Một khối trên khung soạn (memo theo tham chiếu khối: chỉ vẽ lại khối đổi). */
|
|
86
87
|
export const Block = memo(function Block({ node }: { node: BNode }) {
|
|
87
|
-
const { registry, store, labels } = useEditor();
|
|
88
|
+
const { registry, store, labels, host } = useEditor();
|
|
88
89
|
const scope = useDocScope();
|
|
89
90
|
const selected = useEditorState(useCallback((s) => s.selection.ids.includes(node.id), [node.id]));
|
|
90
91
|
const editing = useEditorState(useCallback((s) => s.selection.editing === node.id, [node.id]));
|
|
@@ -93,6 +94,10 @@ export const Block = memo(function Block({ node }: { node: BNode }) {
|
|
|
93
94
|
const setAttrs = useCallback((attrs: Record<string, unknown>) => store.setAttrs([node.id], attrs), [node.id, store]);
|
|
94
95
|
const Edit = type?.edit ?? FallbackEdit;
|
|
95
96
|
const props: BlockEditProps = { block: node, attrs: node.attrs, setAttrs, blockProps, selected: selected || editing, editable: scope.mode !== "disabled", labels };
|
|
97
|
+
// Khối trong vòng lặp bài (query › postTemplate) giữ giao diện của trình soạn: website chỉ biết bài của trang, không biết bài của vòng lặp
|
|
98
|
+
const loop = useContext(LoopPostContext);
|
|
99
|
+
if (type?.serverRender && host.renderBlock && !loop)
|
|
100
|
+
return <BlockBoundary id={node.id} type={node.type}><ServerBlock node={node} blockProps={blockProps} fallback={<Edit {...props} />} /></BlockBoundary>;
|
|
96
101
|
return <BlockBoundary id={node.id} type={node.type}><Edit {...props} /></BlockBoundary>;
|
|
97
102
|
});
|
|
98
103
|
|
|
@@ -6,6 +6,12 @@ export const CANVAS_CSS = String.raw`
|
|
|
6
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
7
|
html, body { margin: 0; min-height: 100%; }
|
|
8
8
|
body.ecx-canvas-body { padding: 0; background: #fff; }
|
|
9
|
+
/* Khung bao + vùng soạn luôn ở trạng thái cuối của hiệu ứng: theme ẩn chúng tới khi JS chạy (opacity 0, dịch chuyển…) mà khung soạn không có JS đó */
|
|
10
|
+
[data-ecx-wrapper], .ecx-canvas-root { opacity: 1 !important; visibility: visible !important; transform: none !important; animation: none !important; transition: none !important; clip-path: none !important; filter: none !important; }
|
|
11
|
+
.ecx-edit-link { display: inline-block; margin: 6px 0 0; padding: 2px 8px; border: 1px solid var(--ecx-ui, #1a597b); border-radius: 4px; background: #fff; color: var(--ecx-ui, #1a597b); font: 12px/1.6 system-ui, sans-serif; cursor: pointer; }
|
|
12
|
+
.ecx-edit-link:hover { background: var(--ecx-ui, #1a597b); color: #fff; }
|
|
13
|
+
/* HTML do website vẽ (khối theme/plugin): các lớp hiệu ứng "ẩn tới khi JS chạy" thường gặp luôn ở trạng thái cuối. Theme nên đặt trạng thái ẩn dưới html.ecx-js (chỉ có khi JS chạy) để khỏi phụ thuộc đoán tên lớp. */
|
|
14
|
+
.ecx-server-html [class*="stagger"], .ecx-server-html [class*="reveal"], .ecx-server-html [class*="animate"], .ecx-server-html [class*="fade-"], .ecx-server-html [class*="aos"], .ecx-server-html [data-aos] { opacity: 1 !important; visibility: visible !important; transform: none !important; animation: none !important; transition: none !important; }
|
|
9
15
|
.ecx-canvas-root { min-height: 100vh; padding: 2rem clamp(1rem, 4vw, 3rem) 40vh; box-sizing: border-box; outline: none; }
|
|
10
16
|
.ecx-canvas-root > * { max-width: var(--ecx-content-width, 760px); margin-left: auto; margin-right: auto; }
|
|
11
17
|
.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); }
|
package/src/v2/canvas/canvas.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { collectStyles, normalizeStyle, presetCss, type BlockStyle } from "@ecomcx/ecomweb-content";
|
|
2
|
-
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
|
|
2
|
+
import { createElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
|
|
3
3
|
import { onAnimationsChange, pluginAnimations } from "../../shared/animation-store";
|
|
4
4
|
import { createPortal } from "react-dom";
|
|
5
5
|
import { DocBlocks } from "./block-list";
|
|
@@ -7,6 +7,8 @@ import { BLOCKS_MIME, blocksFromClipboard, serializeBlocks } from "../core/clipb
|
|
|
7
7
|
import { DocScopeProvider, useEditor, useEditorState, useUiTick } from "../context";
|
|
8
8
|
import { usePrefs } from "../prefs";
|
|
9
9
|
import { CANVAS_CSS } from "./canvas-css";
|
|
10
|
+
import { applyDocumentAttrs } from "./document-attrs";
|
|
11
|
+
import { wrapperNodes } from "./wrapper-props";
|
|
10
12
|
import { makeBlock, type BNode } from "../core/model";
|
|
11
13
|
import { flatten, topLevelOrdered } from "../core/ops";
|
|
12
14
|
import { insertSibling, now, richViews } from "../text/rich-text";
|
|
@@ -63,13 +65,20 @@ export function Canvas({ device = "desktop", className, contentClassName = "ecx-
|
|
|
63
65
|
<div className={["ecx-canvas-wrap", `is-${device}`, zoom !== 1 && "is-zoomed-out", className].filter(Boolean).join(" ")}>
|
|
64
66
|
<iframe ref={frameRef} className="ecx-canvas-frame" title={labels.canvas} srcDoc={SRC_DOC} onLoad={onLoad}
|
|
65
67
|
style={style} data-ecx-canvas="" />
|
|
66
|
-
{doc && createPortal(<CanvasRoot doc={doc} contentClassName={contentClassName} before={before} after={after}
|
|
68
|
+
{doc && createPortal(<CanvasWrapper><CanvasRoot doc={doc} contentClassName={contentClassName} before={before} after={after} /></CanvasWrapper>, doc.body)}
|
|
67
69
|
</div>
|
|
68
70
|
);
|
|
69
71
|
}
|
|
70
72
|
|
|
73
|
+
/** Khung bao của website (host.canvasWrapper) quanh vùng soạn; không có → vùng soạn đứng trực tiếp trong <body>. */
|
|
74
|
+
function CanvasWrapper({ children }: { children: ReactNode }) {
|
|
75
|
+
const { host } = useEditor();
|
|
76
|
+
const nodes = useMemo(() => wrapperNodes(host.canvasWrapper), [host.canvasWrapper]);
|
|
77
|
+
return <>{nodes.reduceRight<ReactNode>((inner, n) => createElement(n.tag, n.props, inner), children)}</>;
|
|
78
|
+
}
|
|
79
|
+
|
|
71
80
|
function CanvasRoot({ doc, contentClassName, before, after }: { doc: Document; contentClassName: string; before?: ReactNode; after?: ReactNode }) {
|
|
72
|
-
const { store, labels, prefs, ui } = useEditor();
|
|
81
|
+
const { store, labels, prefs, ui, host } = useEditor();
|
|
73
82
|
const spotlight = usePrefs(prefs).spotlight;
|
|
74
83
|
useUiTick();
|
|
75
84
|
const focus = useEditorState((s) => s.focus[s.focus.length - 1] ?? null);
|
|
@@ -80,12 +89,13 @@ function CanvasRoot({ doc, contentClassName, before, after }: { doc: Document; c
|
|
|
80
89
|
const viewId = !focus && frameId ? frameId : activeId;
|
|
81
90
|
const mode = useEditorState(useCallback((s) => s.docs[activeId]?.mode ?? "default", [activeId]));
|
|
82
91
|
const title = useEditorState(useCallback((s) => s.docs[activeId]?.title, [activeId]));
|
|
92
|
+
useCanvasDocument(doc);
|
|
83
93
|
useCanvasStyles(doc);
|
|
84
94
|
useCanvasKeys(doc);
|
|
85
95
|
useCanvasEvents(doc);
|
|
86
96
|
const hasRange = useRangeHighlight(doc);
|
|
87
97
|
return (
|
|
88
|
-
<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}
|
|
98
|
+
<div className={["ecx-canvas-root", contentClassName, host.canvasContentClass, 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}
|
|
89
99
|
onDoubleClick={() => { if (ui.zoomOut) zoomIn(store, ui); }}
|
|
90
100
|
onMouseDown={(e) => {
|
|
91
101
|
if (ui.zoomOut) return store.clearSelection();
|
|
@@ -110,6 +120,13 @@ function CanvasRoot({ doc, contentClassName, before, after }: { doc: Document; c
|
|
|
110
120
|
);
|
|
111
121
|
}
|
|
112
122
|
|
|
123
|
+
/** Thuộc tính <html> / <body> của website (host.canvasDocument) để CSS đã scope của theme khớp. */
|
|
124
|
+
function useCanvasDocument(doc: Document) {
|
|
125
|
+
const { host } = useEditor();
|
|
126
|
+
const spec = host.canvasDocument;
|
|
127
|
+
useLayoutEffect(() => applyDocumentAttrs(doc, spec), [doc, spec]);
|
|
128
|
+
}
|
|
129
|
+
|
|
113
130
|
/** CSS trong iframe: nền của trình soạn, CSS website (host), preset theme, kiểu dáng các khối. */
|
|
114
131
|
function useCanvasStyles(doc: Document) {
|
|
115
132
|
const { host, store } = useEditor();
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thuộc tính của <html> / <body> trên website (data-theme, class, lang…) áp vào khung soạn: CSS của theme được scope theo
|
|
3
|
+
* `html[data-theme~="slug"]` và các class của body — thiếu chúng thì CSS có tải vẫn không khớp.
|
|
4
|
+
* Chỉ nhận những thuộc tính an toàn (không style, không on*, không src/href): ứng dụng nhúng có thể truyền dữ liệu từ website.
|
|
5
|
+
*/
|
|
6
|
+
export interface CanvasDocumentSpec {
|
|
7
|
+
html?: Record<string, string>;
|
|
8
|
+
body?: Record<string, string>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface AttrOp { target: "html" | "body"; name: string; value: string }
|
|
12
|
+
|
|
13
|
+
const SAFE_NAME = /^(class|lang|dir|data-[a-z0-9-]+)$/;
|
|
14
|
+
const SAFE_VALUE = /^[^<>"'`\\]{0,500}$/;
|
|
15
|
+
|
|
16
|
+
/** Danh sách thao tác đặt thuộc tính đã lọc (thuần — kiểm thử không cần DOM). */
|
|
17
|
+
export function attrOps(spec: CanvasDocumentSpec | undefined): AttrOp[] {
|
|
18
|
+
const ops: AttrOp[] = [];
|
|
19
|
+
for (const target of ["html", "body"] as const)
|
|
20
|
+
for (const [name, value] of Object.entries(spec?.[target] ?? {}))
|
|
21
|
+
if (SAFE_NAME.test(name) && typeof value === "string" && SAFE_VALUE.test(value)) ops.push({ target, name, value });
|
|
22
|
+
return ops;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Áp lên tài liệu của khung soạn; trả hàm hoàn tác. `class` được thêm vào (giữ class của khung soạn), thuộc tính khác ghi đè. */
|
|
26
|
+
export function applyDocumentAttrs(doc: Document, spec: CanvasDocumentSpec | undefined): () => void {
|
|
27
|
+
const undo: Array<() => void> = [];
|
|
28
|
+
for (const { target, name, value } of attrOps(spec)) {
|
|
29
|
+
const el = target === "html" ? doc.documentElement : doc.body;
|
|
30
|
+
if (name === "class") {
|
|
31
|
+
const added = value.split(/\s+/).filter((c) => c && !el.classList.contains(c));
|
|
32
|
+
el.classList.add(...added);
|
|
33
|
+
undo.push(() => el.classList.remove(...added));
|
|
34
|
+
} else {
|
|
35
|
+
const prev = el.getAttribute(name);
|
|
36
|
+
el.setAttribute(name, value);
|
|
37
|
+
undo.push(() => (prev === null ? el.removeAttribute(name) : el.setAttribute(name, prev)));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return () => undo.forEach((f) => f());
|
|
41
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { useEffect, useState, type ReactNode } from "react";
|
|
2
|
+
import { useEditor } from "../context";
|
|
3
|
+
import { docFromBlocks, type BNode } from "../core/model";
|
|
4
|
+
import type { BlockEditProps } from "../core/registry";
|
|
5
|
+
import { sanitizeServerHtml } from "./server-html";
|
|
6
|
+
|
|
7
|
+
const MEDIA = "img, svg, video, canvas, picture, iframe, input, select, textarea, button, hr";
|
|
8
|
+
/** Có chữ hoặc ảnh / hình / ô nhập nào thấy được không (khung rỗng thì không). */
|
|
9
|
+
function hasVisibleContent(html: string): boolean {
|
|
10
|
+
const box = document.createElement("div");
|
|
11
|
+
box.innerHTML = html;
|
|
12
|
+
return box.textContent!.trim().length > 0 || box.querySelector(MEDIA) !== null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Kết quả vẽ của website theo (khối, thuộc tính, nội dung): mở lại template / gõ ở khối khác không phải hỏi lại website
|
|
16
|
+
const cache = new Map<string, string | null>();
|
|
17
|
+
const CACHE_LIMIT = 300;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Khối động / khối của theme-plugin do **website** vẽ bằng chính code + CSS của theme (host.renderBlock) — khung soạn thấy
|
|
21
|
+
* đúng menu riêng, breadcrumb thật… như trang thật. Đang tải hoặc website không vẽ được → giao diện của trình soạn (`fallback`).
|
|
22
|
+
*/
|
|
23
|
+
export function ServerBlock({ node, blockProps, fallback }: { node: BNode; blockProps: BlockEditProps["blockProps"]; fallback: ReactNode }) {
|
|
24
|
+
const { host } = useEditor();
|
|
25
|
+
const json = docFromBlocks([node]).content?.[0];
|
|
26
|
+
const key = JSON.stringify(json ?? null);
|
|
27
|
+
const [html, setHtml] = useState<string | null | undefined>(() => cache.get(key));
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
if (cache.has(key)) { setHtml(cache.get(key)); return; }
|
|
30
|
+
let alive = true;
|
|
31
|
+
// Chờ ngừng sửa thuộc tính một chút rồi mới hỏi website
|
|
32
|
+
const timer = setTimeout(() => {
|
|
33
|
+
host.renderBlock!(json as never).then((h) => h ?? null, () => null).then((h) => {
|
|
34
|
+
if (cache.size >= CACHE_LIMIT) cache.delete(cache.keys().next().value!);
|
|
35
|
+
cache.set(key, h);
|
|
36
|
+
if (alive) setHtml(h);
|
|
37
|
+
});
|
|
38
|
+
}, 250);
|
|
39
|
+
return () => { alive = false; clearTimeout(timer); };
|
|
40
|
+
}, [key, host]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
41
|
+
if (!html) return <>{fallback}</>;
|
|
42
|
+
const clean = sanitizeServerHtml(html, document);
|
|
43
|
+
// Website vẽ ra rỗng (thiếu dữ liệu trang mẫu: breadcrumb, danh sách…) → hiện mờ khung của trình soạn để vẫn chọn / xoá được khối
|
|
44
|
+
if (!hasVisibleContent(clean)) return <div className="ecx-server-empty" style={{ opacity: 0.55 }} title="Website không vẽ gì cho khối này ở trang mẫu">{fallback}</div>;
|
|
45
|
+
return (
|
|
46
|
+
<div {...blockProps} className={[blockProps.className, "ecx-server-block"].filter(Boolean).join(" ")} contentEditable={false}>
|
|
47
|
+
{/* pointer-events: none → bấm vào là chọn khối, không mở liên kết / gửi form của trang thật */}
|
|
48
|
+
<div className="ecx-server-html" style={{ pointerEvents: "none" }} dangerouslySetInnerHTML={{ __html: clean }} />
|
|
49
|
+
</div>
|
|
50
|
+
);
|
|
51
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML do website vẽ giúp (host.renderBlock) trước khi đưa vào khung soạn: khung soạn cùng nguồn với ứng dụng nhúng (admin),
|
|
3
|
+
* nên mọi thứ chạy được (script, on*, javascript:) đều bị bỏ — chỉ giữ phần hiển thị.
|
|
4
|
+
*/
|
|
5
|
+
const DROP = "script, noscript, object, embed, base, meta, link[rel=import], frame, frameset, template";
|
|
6
|
+
const URL_ATTRS = ["href", "src", "action", "formaction", "poster", "xlink:href", "srcset", "data"];
|
|
7
|
+
|
|
8
|
+
export function sanitizeServerHtml(html: string, doc: Document): string {
|
|
9
|
+
const box = doc.createElement("template");
|
|
10
|
+
box.innerHTML = html;
|
|
11
|
+
const root = box.content;
|
|
12
|
+
root.querySelectorAll(DROP).forEach((el) => el.remove());
|
|
13
|
+
for (const el of Array.from(root.querySelectorAll("*"))) {
|
|
14
|
+
for (const a of Array.from(el.attributes)) {
|
|
15
|
+
const name = a.name.toLowerCase(), value = a.value.trim().toLowerCase();
|
|
16
|
+
if (name.startsWith("on")) el.removeAttribute(a.name);
|
|
17
|
+
else if (URL_ATTRS.includes(name) && /^(javascript|vbscript|data:text\/html)/.test(value.replace(/[\s\u0000-\u001f]/g, ""))) el.removeAttribute(a.name);
|
|
18
|
+
}
|
|
19
|
+
// Khung con: chỉ http(s), luôn sandbox (không script, không cùng nguồn)
|
|
20
|
+
if (el.tagName === "IFRAME") {
|
|
21
|
+
if (!/^https?:\/\//i.test(el.getAttribute("src") ?? "")) el.remove();
|
|
22
|
+
else el.setAttribute("sandbox", "");
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const out = doc.createElement("div");
|
|
26
|
+
out.appendChild(root.cloneNode(true));
|
|
27
|
+
return out.innerHTML;
|
|
28
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Khung bao nội dung trong khung soạn (host.canvasWrapper): chuỗi phần tử như trên website (div.site > main#x > div.content…) để
|
|
3
|
+
* selector theo cấu trúc trang của theme khớp. Dữ liệu đến từ website → chỉ nhận khối bố cục, class / id / data-* / style đơn giản.
|
|
4
|
+
*/
|
|
5
|
+
export interface WrapperEl { tag: string; attrs?: Record<string, string> }
|
|
6
|
+
export interface WrapperNode { tag: string; props: Record<string, unknown> }
|
|
7
|
+
|
|
8
|
+
const BOX = new Set(["div", "main", "section", "article", "aside", "span"]);
|
|
9
|
+
const SAFE_VALUE = /^[^<>"'`\\]{0,500}$/;
|
|
10
|
+
export const MAX_WRAPPER_DEPTH = 12;
|
|
11
|
+
|
|
12
|
+
const camel = (p: string) => (p.startsWith("--") ? p : p.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()));
|
|
13
|
+
|
|
14
|
+
/** "--a:1;font-size:14px" → { "--a": "1", fontSize: "14px" }; khai báo nguy hiểm (url(), expression…) → bỏ cả style. */
|
|
15
|
+
export function parseStyle(css: string): Record<string, string> | null {
|
|
16
|
+
const out: Record<string, string> = {};
|
|
17
|
+
for (const decl of css.split(";").map((d) => d.trim()).filter(Boolean)) {
|
|
18
|
+
const i = decl.indexOf(":");
|
|
19
|
+
const name = decl.slice(0, i).trim(), value = decl.slice(i + 1).trim();
|
|
20
|
+
if (i < 1 || !/^(--[\w-]+|[a-z-]+)$/i.test(name) || /[{}<>"'`\\]|url\s*\(|expression|@import|javascript:/i.test(value)) return null;
|
|
21
|
+
out[camel(name)] = value;
|
|
22
|
+
}
|
|
23
|
+
return Object.keys(out).length ? out : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Chuỗi đã lọc, từ ngoài vào trong. */
|
|
27
|
+
export function wrapperNodes(chain: WrapperEl[] | undefined): WrapperNode[] {
|
|
28
|
+
const nodes: WrapperNode[] = [];
|
|
29
|
+
for (const el of (chain ?? []).slice(0, MAX_WRAPPER_DEPTH)) {
|
|
30
|
+
const props: Record<string, unknown> = {};
|
|
31
|
+
for (const [name, value] of Object.entries(el.attrs ?? {})) {
|
|
32
|
+
if (typeof value !== "string") continue;
|
|
33
|
+
if (name === "style") { const s = parseStyle(value); if (s) props.style = s; }
|
|
34
|
+
else if (name === "class" && SAFE_VALUE.test(value)) props.className = value;
|
|
35
|
+
else if ((name === "id" || /^data-[a-z0-9-]+$/.test(name)) && SAFE_VALUE.test(value)) props[name] = value;
|
|
36
|
+
}
|
|
37
|
+
// Dấu để CSS của khung soạn ép trạng thái cuối (theme ẩn khung bao tới khi JS chạy hiệu ứng: opacity 0, transform…)
|
|
38
|
+
props["data-ecx-wrapper"] = "";
|
|
39
|
+
nodes.push({ tag: BOX.has(el.tag) ? el.tag : "div", props });
|
|
40
|
+
}
|
|
41
|
+
return nodes;
|
|
42
|
+
}
|
package/src/v2/core/host.ts
CHANGED
|
@@ -18,6 +18,24 @@ export interface EditorHost {
|
|
|
18
18
|
dynamic?: DynamicData;
|
|
19
19
|
/** Khung soạn: CSS của website (đường dẫn hoặc nội dung CSS) để soạn trông giống hệt trang thật. */
|
|
20
20
|
canvasStyles?: Array<string | { css: string }>;
|
|
21
|
+
/** Khung soạn: thuộc tính của <html> / <body> trên website (data-theme, class, lang…) — CSS của theme scope theo chúng. */
|
|
22
|
+
canvasDocument?: { html?: Record<string, string>; body?: Record<string, string> };
|
|
23
|
+
/**
|
|
24
|
+
* Khung soạn: chuỗi phần tử bao quanh nội dung như trên website (div.site > main#x > div.content…), từ ngoài vào trong — theme viết CSS
|
|
25
|
+
* theo cấu trúc trang (`#x .content p em`, biến CSS đặt trên div.site) nên canvas phải dựng đúng chuỗi đó.
|
|
26
|
+
*/
|
|
27
|
+
canvasWrapper?: Array<{ tag: string; attrs?: Record<string, string> }>;
|
|
28
|
+
/** Class thêm cho vùng nội dung của khung soạn (vd "prose max-w-none") — như phần tử nội dung trên website. */
|
|
29
|
+
canvasContentClass?: string;
|
|
30
|
+
/** Mở nơi sửa menu của một vị trí (khối Menu đang chọn hiện nút "Sửa menu"). Không có → không hiện nút. */
|
|
31
|
+
editMenu?(location: string): void;
|
|
32
|
+
/**
|
|
33
|
+
* Website vẽ giúp một khối (nút nội dung dạng JSON như khi lưu) bằng code + CSS của theme → HTML. null = không vẽ được
|
|
34
|
+
* (trình soạn dùng giao diện của mình). Dùng cho khối có `serverRender` (khối động, khối plugin/theme không có `edit`).
|
|
35
|
+
*/
|
|
36
|
+
renderBlock?(node: { type: string; attrs?: Record<string, unknown>; content?: unknown[] }): Promise<string | null>;
|
|
37
|
+
/** Nơi đang soạn: "template" = template / phần dùng chung của theme (chèn được khối riêng của theme); mặc định = nội dung bài. */
|
|
38
|
+
scope?: "template" | "content";
|
|
21
39
|
/** Preset của theme (biến --ecx-*). */
|
|
22
40
|
presets?: StylePresets;
|
|
23
41
|
/** Chữ "%khoá%" của plugin → chữ theo ngôn ngữ. */
|
|
@@ -58,7 +76,7 @@ export interface DocumentHost {
|
|
|
58
76
|
save?(ref: NestedDocRef, blocks: BNode[], content: SavedContent): Promise<void>;
|
|
59
77
|
}
|
|
60
78
|
|
|
61
|
-
export type DynamicPost = { title?: string; date?: string; author?: string; excerpt?: string; image?: string | null; terms?: string[]; comments?: number; link?: string };
|
|
79
|
+
export type DynamicPost = { title?: string; date?: string; author?: string; excerpt?: string; image?: string | null; terms?: string[]; comments?: number; link?: string; /** Nội dung đã lưu của bài (ContentDoc) — khối "Nội dung bài" trong template vẽ nội dung thật thay vì khung giữ chỗ. */ content?: unknown };
|
|
62
80
|
|
|
63
81
|
/** Thiết lập của khối "Danh sách bài" (attrs của query). */
|
|
64
82
|
export interface QueryArgs { inherit: boolean; postType: string; perPage: number; category?: string; tag?: string; orderBy: string; order: "asc" | "desc" }
|
package/src/v2/core/registry.ts
CHANGED
|
@@ -67,10 +67,18 @@ export interface BlockType {
|
|
|
67
67
|
structure?: StructureRule;
|
|
68
68
|
/** Ẩn khỏi trình chèn (khối con như column, listItem). */
|
|
69
69
|
hidden?: boolean;
|
|
70
|
+
/** Khối của theme: chỉ hiện trong trình chèn khi soạn template / phần dùng chung (host.scope = "template"). */
|
|
71
|
+
templateOnly?: boolean;
|
|
70
72
|
/** Tạo khối mới khi chèn (mặc định: thuộc tính mặc định + nội dung tối thiểu). */
|
|
71
73
|
create?(attrs?: Record<string, unknown>): BNode;
|
|
72
74
|
/** Vẽ trên khung soạn. Không có → khung chung (tên khối + tóm tắt thuộc tính). */
|
|
73
75
|
edit?: ComponentType<BlockEditProps>;
|
|
76
|
+
/**
|
|
77
|
+
* Khối hiển thị (không gõ chữ bên trong) mà trình soạn không biết vẽ — khối của plugin/theme chỉ có renderer ở website: khung soạn nhờ
|
|
78
|
+
* website vẽ bằng chính code + CSS của theme khi ứng dụng nhúng có `host.renderBlock`. Khối lõi giữ cách vẽ của trình soạn (như WordPress:
|
|
79
|
+
* ServerSideRender chỉ cho khối động của plugin). `edit` chỉ dùng khi đang tải / website không vẽ được / khối nằm trong vòng lặp bài.
|
|
80
|
+
*/
|
|
81
|
+
serverRender?: boolean;
|
|
74
82
|
/** Thanh công cụ riêng của khối (chèn vào thanh công cụ nổi). */
|
|
75
83
|
toolbar?: ComponentType<BlockEditProps>;
|
|
76
84
|
/**
|
package/src/v2/editor.tsx
CHANGED
|
@@ -158,18 +158,22 @@ export interface BlockEditorProps extends Omit<EditorProviderProps, "children">
|
|
|
158
158
|
defaultDevice?: Device;
|
|
159
159
|
/** Kiểu biến thể khối của theme (theme.json › blockStyles). */
|
|
160
160
|
blockStyles?: Record<string, Array<{ name: string; label: string }>>;
|
|
161
|
+
/** Tay cầm lưu từ bên ngoài (nút "Lưu tất cả" của ứng dụng): trình soạn gắn hàm lưu vào `current` — cùng việc với nút Lưu / ⌘S. */
|
|
162
|
+
saveHandle?: { current: (() => Promise<void>) | null };
|
|
163
|
+
/** Báo khi có / hết thay đổi chưa lưu (kể cả tài liệu lồng). */
|
|
164
|
+
onDirtyChange?(dirty: boolean): void;
|
|
161
165
|
}
|
|
162
166
|
|
|
163
167
|
/** Trình soạn đầy đủ: thanh trên cùng, thư viện khối / cây khối, khung soạn, bảng cài đặt. */
|
|
164
|
-
export function BlockEditor({ className, onSave, header, actions, menuExtra, canvasBefore, defaultDevice = "desktop", blockStyles, ...provider }: BlockEditorProps) {
|
|
168
|
+
export function BlockEditor({ className, onSave, header, actions, menuExtra, canvasBefore, defaultDevice = "desktop", blockStyles, saveHandle, onDirtyChange, ...provider }: BlockEditorProps) {
|
|
165
169
|
return (
|
|
166
170
|
<EditorProvider {...provider}>
|
|
167
|
-
<EditorShell className={className} onSave={onSave} header={header} actions={actions} menuExtra={menuExtra} canvasBefore={canvasBefore} defaultDevice={defaultDevice} blockStyles={blockStyles} />
|
|
171
|
+
<EditorShell className={className} onSave={onSave} header={header} actions={actions} menuExtra={menuExtra} canvasBefore={canvasBefore} defaultDevice={defaultDevice} blockStyles={blockStyles} saveHandle={saveHandle} onDirtyChange={onDirtyChange} />
|
|
168
172
|
</EditorProvider>
|
|
169
173
|
);
|
|
170
174
|
}
|
|
171
175
|
|
|
172
|
-
function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefore, defaultDevice, blockStyles }: Pick<BlockEditorProps, "className" | "onSave" | "header" | "actions" | "menuExtra" | "canvasBefore" | "defaultDevice" | "blockStyles">) {
|
|
176
|
+
function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefore, defaultDevice, blockStyles, saveHandle, onDirtyChange }: Pick<BlockEditorProps, "saveHandle" | "onDirtyChange" | "className" | "onSave" | "header" | "actions" | "menuExtra" | "canvasBefore" | "defaultDevice" | "blockStyles">) {
|
|
173
177
|
const ctx = useEditor();
|
|
174
178
|
const { store, labels } = ctx;
|
|
175
179
|
const p = usePrefs(ctx.prefs);
|
|
@@ -196,6 +200,12 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
196
200
|
};
|
|
197
201
|
const saveRef = useRef(save);
|
|
198
202
|
saveRef.current = save;
|
|
203
|
+
useEffect(() => {
|
|
204
|
+
if (!saveHandle) return;
|
|
205
|
+
saveHandle.current = () => saveRef.current();
|
|
206
|
+
return () => { saveHandle.current = null; };
|
|
207
|
+
}, [saveHandle]);
|
|
208
|
+
useEffect(() => { onDirtyChange?.(dirty); }, [dirty]); // eslint-disable-line react-hooks/exhaustive-deps
|
|
199
209
|
useEffect(() => {
|
|
200
210
|
const onKey = (e: KeyboardEvent) => {
|
|
201
211
|
const mod = e.metaKey || e.ctrlKey;
|
|
@@ -224,8 +234,8 @@ function EditorShell({ className, onSave, header, actions, menuExtra, canvasBefo
|
|
|
224
234
|
{p.mode === "visual" && <ZoomToggle />}
|
|
225
235
|
</div>
|
|
226
236
|
<div className="ecx-topbar-end">
|
|
227
|
-
<div className="ecx-tool-group" role="group" aria-label=
|
|
228
|
-
{([["desktop", Monitor], ["tablet", Tablet], ["mobile", Smartphone]] as const).map(([d, I]) => <ToolButton key={d} label={
|
|
237
|
+
<div className="ecx-tool-group" role="group" aria-label={labels.devices}>
|
|
238
|
+
{([["desktop", Monitor, labels.deviceDesktop], ["tablet", Tablet, labels.deviceTablet], ["mobile", Smartphone, labels.deviceMobile]] as const).map(([d, I, text]) => <ToolButton key={d} label={text} active={device === d} onClick={() => setDevice(d)}><I className="ecx-icon" /></ToolButton>)}
|
|
229
239
|
</div>
|
|
230
240
|
{!p.distractionFree && <ToolButton label={labels.settings} active={right} onClick={() => setRight(!right)}><PanelRight className="ecx-icon" /></ToolButton>}
|
|
231
241
|
{actions}
|
package/src/v2/ui/inserter.tsx
CHANGED
|
@@ -26,7 +26,7 @@ export interface InsertOption {
|
|
|
26
26
|
|
|
27
27
|
/** Các lựa chọn chèn: khối + biến thể có hàm tạo riêng (cột 30/70…). */
|
|
28
28
|
export function useInsertOptions(): InsertOption[] {
|
|
29
|
-
const { registry, prefs } = useEditor();
|
|
29
|
+
const { registry, prefs, host } = useEditor();
|
|
30
30
|
const hidden = usePrefs(prefs).hiddenBlockTypes;
|
|
31
31
|
const [version, setVersion] = useState(registry.getVersion());
|
|
32
32
|
useEffect(() => registry.subscribe(() => setVersion(registry.getVersion())), [registry]);
|
|
@@ -35,7 +35,7 @@ export function useInsertOptions(): InsertOption[] {
|
|
|
35
35
|
const out: InsertOption[] = [];
|
|
36
36
|
const hide = new Set(hidden);
|
|
37
37
|
for (const t of registry.all()) {
|
|
38
|
-
if (t.hidden || hide.has(t.name)) continue;
|
|
38
|
+
if (t.hidden || hide.has(t.name) || (t.templateOnly && host.scope !== "template")) continue;
|
|
39
39
|
out.push({ key: t.name, title: t.title, description: t.description, icon: t.icon, keywords: t.keywords ?? "", category: t.category ?? "other", type: t.name, create: () => registry.create(t.name) });
|
|
40
40
|
for (const v of t.variations ?? []) {
|
|
41
41
|
if (!v.create) continue;
|
|
@@ -43,7 +43,7 @@ export function useInsertOptions(): InsertOption[] {
|
|
|
43
43
|
}
|
|
44
44
|
}
|
|
45
45
|
return out;
|
|
46
|
-
}, [registry, version, hidden]);
|
|
46
|
+
}, [registry, version, hidden, host.scope]);
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
/** Lọc + xếp hạng: tên bắt đầu bằng chữ gõ > một từ trong tên > từ khoá; tiếng Việt không dấu. */
|