@ecomcx/ecomweb-editor 1.22.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 +3 -3
- package/src/legacy/dynamic.tsx +6 -2
- package/src/locales/en/v2.ts +9 -1
- package/src/locales/vi/v2.ts +9 -1
- package/src/shared/block-defs.ts +2 -0
- package/src/v2/blocks/compat.tsx +3 -0
- package/src/v2/blocks/theme.tsx +88 -12
- 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/clipboard.ts +2 -2
- 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/text/rich-schema.ts +2 -0
- package/src/v2/ui/inserter.tsx +3 -3
- package/src/v2/ui/toolbar.tsx +8 -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": {
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"*.css"
|
|
30
30
|
],
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@ecomcx/ecomweb-content": "^1.
|
|
32
|
+
"@ecomcx/ecomweb-content": "^1.18.0",
|
|
33
33
|
"react": ">=18",
|
|
34
34
|
"react-dom": ">=18"
|
|
35
35
|
},
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
"prosemirror-view": "1.42.7"
|
|
61
61
|
},
|
|
62
62
|
"devDependencies": {
|
|
63
|
-
"@ecomcx/ecomweb-content": "^1.
|
|
63
|
+
"@ecomcx/ecomweb-content": "^1.18.0",
|
|
64
64
|
"@playwright/test": "1.53.0",
|
|
65
65
|
"@types/react": "19.2.2",
|
|
66
66
|
"@types/react-dom": "19.2.2",
|
package/src/legacy/dynamic.tsx
CHANGED
|
@@ -24,7 +24,7 @@ const SPECS: Array<[string, LucideIcon, "none" | "blocks", Record<string, BlockA
|
|
|
24
24
|
["siteLogo", Image, "none", { width: i("width", { min: 16, max: 600, default: 120 }), link: b("link", { default: true }) }],
|
|
25
25
|
["siteTagline", Text, "none", { textAlign: align }],
|
|
26
26
|
["navigation", Menu, "none", { location: s("location", { default: "primary" }), orientation: s("orientation", { enum: ["horizontal", "vertical"], enumLabels: ["horizontal", "vertical"], default: "horizontal" }), mobile: b("mobile", { default: true }) }],
|
|
27
|
-
["search", Search, "none", { placeholder: s("placeholder"), buttonText: s("buttonText") }],
|
|
27
|
+
["search", Search, "none", { placeholder: s("placeholder"), buttonText: s("buttonText"), postType: s("postType"), showLabel: b("showLabel", { default: false }), buttonPosition: s("buttonPosition", { enum: ["right", "left", "below"], enumLabels: ["right", "left", "below"], default: "right" }) }],
|
|
28
28
|
["languageSwitcher", Languages, "none", { display: s("display", { enum: ["inline", "dropdown"], enumLabels: ["inline", "dropdown"], default: "inline" }) }],
|
|
29
29
|
["copyright", Copyright, "none", { text: s("text"), textAlign: align }],
|
|
30
30
|
["postTitle", Heading1, "none", { level: i("level", { min: 1, max: 6, default: 1 }), link: b("link", { default: false }), textAlign: align }],
|
|
@@ -34,11 +34,15 @@ const SPECS: Array<[string, LucideIcon, "none" | "blocks", Record<string, BlockA
|
|
|
34
34
|
["postDate", Calendar, "none", { textAlign: align }],
|
|
35
35
|
["postAuthor", User, "none", { avatar: b("avatar", { default: false }), showName: b("showName", { default: true }), showBio: b("showBio", { default: false }), avatarSize: i("avatarSize", { min: 16, max: 128, default: 32 }), link: b("link", { default: true }) }],
|
|
36
36
|
["postTerms", Tags, "none", { taxonomy: s("taxonomy", { default: "category" }), separator: s("separator", { default: ", " }) }],
|
|
37
|
-
["comments", MessageSquare, "none", { title: s("title") }],
|
|
37
|
+
["comments", MessageSquare, "none", { title: s("title"), perPage: i("perPage", { min: 1, max: 50 }), order: s("order", { enum: ["asc", "desc"], enumLabels: ["asc", "desc"] }), avatarSize: i("avatarSize", { min: 16, max: 128, default: 40 }), showDate: b("showDate", { default: true }) }],
|
|
38
38
|
["readMore", ChevronsRight, "none", { text: s("text"), textAlign: align }],
|
|
39
39
|
["commentsCount", MessageSquare, "none", { textAlign: align }],
|
|
40
40
|
["avatar", User, "none", { size: i("size", { min: 16, max: 256, default: 48 }), link: b("link", { default: true }) }],
|
|
41
41
|
["queryTotal", List, "none", { textAlign: align }],
|
|
42
|
+
["termList", Tags, "none", { taxonomy: s("taxonomy", { default: "category" }), display: s("display", { enum: ["list", "cloud"], enumLabels: ["list", "cloud"], default: "list" }), showCount: b("showCount", { default: false }), hierarchical: b("hierarchical", { default: false }), hideEmpty: b("hideEmpty", { default: true }) }],
|
|
43
|
+
["pageList", List, "none", { parentId: i("parentId", { min: 1 }), depth: i("depth", { min: 1, max: 3, default: 2 }) }],
|
|
44
|
+
["archives", Calendar, "none", { showCount: b("showCount", { default: true }), limit: i("limit", { min: 1, max: 60, default: 12 }) }],
|
|
45
|
+
["loginout", User, "none", { loginText: s("loginText"), logoutText: s("logoutText"), textAlign: align }],
|
|
42
46
|
["queryTitle", Heading1, "none", { level: i("level", { min: 1, max: 6, default: 1 }), prefix: b("prefix", { default: false }), textAlign: align }],
|
|
43
47
|
["termDescription", AlignLeft, "none", { textAlign: align }],
|
|
44
48
|
["breadcrumbs", ChevronsRight, "none", { separator: s("separator", { default: "›" }), showHome: b("showHome", { default: true }), showCurrent: b("showCurrent", { default: true }) }],
|
package/src/locales/en/v2.ts
CHANGED
|
@@ -31,6 +31,8 @@ export const v2 = {
|
|
|
31
31
|
highlight: "Highlight",
|
|
32
32
|
moreFormats: "More formatting",
|
|
33
33
|
code: "Code",
|
|
34
|
+
kbd: "Keyboard key",
|
|
35
|
+
footnote: "Footnote",
|
|
34
36
|
link: "Link",
|
|
35
37
|
unlink: "Remove link",
|
|
36
38
|
linkUrl: "Link URL",
|
|
@@ -40,6 +42,12 @@ export const v2 = {
|
|
|
40
42
|
alignLeft: "Align left",
|
|
41
43
|
alignCenter: "Align center",
|
|
42
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",
|
|
43
51
|
undo: "Undo",
|
|
44
52
|
redo: "Redo",
|
|
45
53
|
listView: "List view",
|
|
@@ -55,7 +63,7 @@ export const v2 = {
|
|
|
55
63
|
saving: "Saving…",
|
|
56
64
|
saved: "Saved",
|
|
57
65
|
unsaved: "Unsaved changes",
|
|
58
|
-
unknownBlock: "
|
|
66
|
+
unknownBlock: "Block from a plugin or theme that is no longer installed — content is kept, reinstall it to edit",
|
|
59
67
|
paragraph: "Paragraph",
|
|
60
68
|
heading: "Heading",
|
|
61
69
|
list: "List",
|
package/src/locales/vi/v2.ts
CHANGED
|
@@ -31,6 +31,8 @@ export const v2 = {
|
|
|
31
31
|
highlight: "Làm nổi bật",
|
|
32
32
|
moreFormats: "Định dạng khác",
|
|
33
33
|
code: "Mã",
|
|
34
|
+
kbd: "Phím bấm",
|
|
35
|
+
footnote: "Chú thích",
|
|
34
36
|
link: "Liên kết",
|
|
35
37
|
unlink: "Bỏ liên kết",
|
|
36
38
|
linkUrl: "Địa chỉ liên kết",
|
|
@@ -40,6 +42,12 @@ export const v2 = {
|
|
|
40
42
|
alignLeft: "Căn trái",
|
|
41
43
|
alignCenter: "Căn giữa",
|
|
42
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",
|
|
43
51
|
undo: "Hoàn tác",
|
|
44
52
|
redo: "Làm lại",
|
|
45
53
|
listView: "Cây khối",
|
|
@@ -55,7 +63,7 @@ export const v2 = {
|
|
|
55
63
|
saving: "Đang lưu…",
|
|
56
64
|
saved: "Đã lưu",
|
|
57
65
|
unsaved: "Có thay đổi chưa lưu",
|
|
58
|
-
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",
|
|
59
67
|
paragraph: "Đoạn văn",
|
|
60
68
|
heading: "Tiêu đề",
|
|
61
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
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { AlignLeft, ArrowLeftRight, CalendarDays, ChevronsRight, Heading1, Copyright, FileText, Globe2, Image as ImageIcon, LayoutTemplate, ListOrdered, Menu, MessageSquare, PanelTop, Repeat2, Rows3, Search, SquareDashed, Tag, Type, User } from "lucide-react";
|
|
1
|
+
import { Star, AlignLeft, ArrowLeftRight, CalendarDays, ChevronsRight, Heading1, Copyright, FileText, Globe2, Image as ImageIcon, LayoutTemplate, ListOrdered, Menu, MessageSquare, PanelTop, Repeat2, Rows3, Search, SquareDashed, Tag, Type, User } from "lucide-react";
|
|
2
2
|
import { useCallback, useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";
|
|
3
3
|
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();
|
|
@@ -114,6 +127,33 @@ function AvatarEdit({ block, blockProps }: BlockEditProps) {
|
|
|
114
127
|
function QueryTotalEdit({ blockProps, block }: BlockEditProps) {
|
|
115
128
|
return <p {...merge(blockProps, "ecx-query-total", align(block.attrs))}>0</p>;
|
|
116
129
|
}
|
|
130
|
+
function TermListEdit({ block, blockProps }: BlockEditProps) {
|
|
131
|
+
const cloud = block.attrs.display === "cloud";
|
|
132
|
+
const sample = block.attrs.taxonomy === "post_tag" ? ["Thẻ A", "Thẻ B", "Thẻ C"] : ["Chuyên mục A", "Chuyên mục B", "Chuyên mục C"];
|
|
133
|
+
const n = (i: number) => (block.attrs.showCount ? ` (${3 - i})` : "");
|
|
134
|
+
return cloud
|
|
135
|
+
? <p {...merge(blockProps, "ecx-term-list is-cloud")}>{sample.map((x, i) => <span key={x} style={{ marginRight: "0.5em", fontSize: `${1.3 - i * 0.2}em` }}>{x}{n(i)}</span>)}</p>
|
|
136
|
+
: <ul {...merge(blockProps, "ecx-term-list")}>{sample.map((x, i) => <li key={x}>{x}{n(i)}</li>)}</ul>;
|
|
137
|
+
}
|
|
138
|
+
function LoginOutEdit({ block, blockProps }: BlockEditProps) {
|
|
139
|
+
return <p {...merge(blockProps, "ecx-loginout", align(block.attrs))}><a href="#" onClick={(e) => e.preventDefault()}>{String(block.attrs.loginText || "Đăng nhập")}</a></p>;
|
|
140
|
+
}
|
|
141
|
+
function IconEdit({ block, blockProps }: BlockEditProps) {
|
|
142
|
+
const size = Math.min(128, Math.max(12, Number(block.attrs.size) || 24));
|
|
143
|
+
return <div {...merge(blockProps, "ecx-icon-block", align(block.attrs))}><span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Star width={size} height={size} />{String(block.attrs.name ?? "star")}</span></div>;
|
|
144
|
+
}
|
|
145
|
+
function FootnotesEdit({ block, blockProps }: BlockEditProps) {
|
|
146
|
+
return <aside {...merge(blockProps, "ecx-footnotes")}>{block.attrs.title ? <p className="ecx-footnotes-title">{String(block.attrs.title)}</p> : null}<ol><li>Chú thích 1</li><li>Chú thích 2</li></ol></aside>;
|
|
147
|
+
}
|
|
148
|
+
function PageBreakEdit({ blockProps }: BlockEditProps) {
|
|
149
|
+
return <div {...merge(blockProps, "ecx-page-break")} style={{ ...(blockProps.style ?? {}), borderTop: "2px dashed currentColor", opacity: 0.5, textAlign: "center", fontSize: 12 }}>Ngắt trang</div>;
|
|
150
|
+
}
|
|
151
|
+
function PageListEdit({ blockProps }: BlockEditProps) {
|
|
152
|
+
return <nav {...merge(blockProps, "ecx-page-list")}><ul><li>Trang A<ul><li>Trang con</li></ul></li><li>Trang B</li></ul></nav>;
|
|
153
|
+
}
|
|
154
|
+
function ArchivesEdit({ block, blockProps }: BlockEditProps) {
|
|
155
|
+
return <ul {...merge(blockProps, "ecx-archives")}>{["11/2026", "10/2026"].map((m, i) => <li key={m}>{m}{block.attrs.showCount === false ? "" : ` (${4 - i})`}</li>)}</ul>;
|
|
156
|
+
}
|
|
117
157
|
function CommentsEdit({ blockProps }: BlockEditProps) {
|
|
118
158
|
const d = useDynamic();
|
|
119
159
|
return <div {...merge(blockProps, "ecx-comments")}><MessageSquare className="ecx-icon" /> {d.post?.comments ?? 0}</div>;
|
|
@@ -153,8 +193,16 @@ function PostNavigationEdit({ block, blockProps, labels }: BlockEditProps) {
|
|
|
153
193
|
);
|
|
154
194
|
}
|
|
155
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
|
+
}
|
|
156
203
|
function PostContentEdit({ blockProps }: BlockEditProps) {
|
|
157
204
|
const { labels } = useEditor();
|
|
205
|
+
const sample = sampleContentNodes(useDynamicData().post?.content);
|
|
158
206
|
const t = useMsgs("blocks");
|
|
159
207
|
const scope = useDocScope();
|
|
160
208
|
const frameId = useEditorState((s) => s.frameId);
|
|
@@ -167,6 +215,8 @@ function PostContentEdit({ blockProps }: BlockEditProps) {
|
|
|
167
215
|
</div>
|
|
168
216
|
);
|
|
169
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>;
|
|
170
220
|
return <div {...merge(blockProps, "ecx-post-content ecx-content-placeholder")}><FileText className="ecx-icon" /> {t.postContent}</div>;
|
|
171
221
|
}
|
|
172
222
|
|
|
@@ -236,11 +286,30 @@ function PostTemplateEdit({ block, blockProps, editable, labels }: BlockEditProp
|
|
|
236
286
|
</ul>
|
|
237
287
|
);
|
|
238
288
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
|
|
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
|
+
);
|
|
244
313
|
}
|
|
245
314
|
|
|
246
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. */
|
|
@@ -280,7 +349,7 @@ export function themeBlocks(): BlockType[] {
|
|
|
280
349
|
{ name: "siteLogo", title: "Logo", icon: ImageIcon, category: theme, keywords: "logo", kind: "atom", edit: SiteLogoEdit, attributes: { width: { type: "number", default: 120 }, link: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
281
350
|
{ name: "siteTagline", title: "Khẩu hiệu", icon: Type, category: theme, keywords: "khau hieu tagline mo ta", kind: "atom", edit: SiteTaglineEdit, attributes: { textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
282
351
|
{ name: "navigation", title: "Menu", icon: Menu, category: theme, keywords: "menu dieu huong navigation", kind: "atom", edit: NavigationEdit, attributes: { location: { type: "string", default: "primary" }, orientation: { type: "string", enum: ["horizontal", "vertical"], default: "horizontal" }, mobile: { type: "boolean", default: true }, overlayMenu: { type: "string", enum: ["never", "mobile", "always"], default: "mobile" } }, supports: { style: true, className: true }, summary: (a) => a.location },
|
|
283
|
-
{ name: "search", title: "Tìm kiếm", icon: Search, category: theme, keywords: "tim kiem search", kind: "atom", edit: SearchEdit, attributes: { placeholder: { type: "string" }, buttonText: { type: "string" } }, supports: { style: true, className: true } },
|
|
352
|
+
{ name: "search", title: "Tìm kiếm", icon: Search, category: theme, keywords: "tim kiem search", kind: "atom", edit: SearchEdit, attributes: { placeholder: { type: "string" }, buttonText: { type: "string" }, postType: { type: "string" }, showLabel: { type: "boolean", default: false }, buttonPosition: { type: "string", enum: ["right", "left", "below"], default: "right" } }, supports: { style: true, className: true } },
|
|
284
353
|
{ name: "languageSwitcher", title: "Chọn ngôn ngữ", icon: Globe2, category: theme, keywords: "ngon ngu language", kind: "atom", edit: LanguageEdit, attributes: { display: { type: "string", enum: ["inline", "dropdown"], default: "inline" } }, supports: { style: true, className: true } },
|
|
285
354
|
{ name: "copyright", title: "Bản quyền", icon: Copyright, category: theme, keywords: "ban quyen copyright", kind: "atom", edit: CopyrightEdit, attributes: { text: { type: "string" }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
286
355
|
{ name: "postTitle", title: "Tiêu đề bài", icon: Type, category: theme, keywords: "tieu de bai post title", kind: "atom", edit: PostTitleEdit, attributes: { level: { type: "integer", default: 1, min: 1, max: 6 }, link: { type: "boolean", default: false }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
@@ -290,11 +359,18 @@ export function themeBlocks(): BlockType[] {
|
|
|
290
359
|
{ name: "postDate", title: "Ngày đăng", icon: CalendarDays, category: theme, keywords: "ngay dang date", kind: "atom", edit: PostDateEdit, attributes: { textAlign: TEXT_ALIGN, displayType: { type: "string", enum: ["published", "modified"], default: "published" } }, supports: { style: true, className: true } },
|
|
291
360
|
{ name: "postAuthor", title: "Tác giả", icon: User, category: theme, keywords: "tac gia author", kind: "atom", edit: PostAuthorEdit, attributes: { avatar: { type: "boolean", default: false }, showName: { type: "boolean", default: true }, showBio: { type: "boolean", default: false }, avatarSize: { type: "integer", default: 32, min: 16, max: 128 }, link: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
292
361
|
{ name: "postTerms", title: "Chuyên mục / thẻ", icon: Tag, category: theme, keywords: "chuyen muc the category tag terms", kind: "atom", edit: PostTermsEdit, attributes: { taxonomy: { type: "string", default: "category" }, separator: { type: "string", default: ", " } }, supports: { style: true, className: true } },
|
|
293
|
-
{ name: "comments", title: "Bình luận", icon: MessageSquare, category: theme, keywords: "binh luan comments", kind: "atom", edit: CommentsEdit, attributes: { title: { type: "string" } } },
|
|
362
|
+
{ name: "comments", title: "Bình luận", icon: MessageSquare, category: theme, keywords: "binh luan comments", kind: "atom", edit: CommentsEdit, attributes: { title: { type: "string" }, perPage: { type: "integer", min: 1, max: 50 }, order: { type: "string", enum: ["asc", "desc"] }, avatarSize: { type: "integer", default: 40, min: 16, max: 128 }, showDate: { type: "boolean", default: true } } },
|
|
294
363
|
{ name: "readMore", title: "Đọc tiếp", icon: ChevronsRight, category: theme, keywords: "doc tiep read more", kind: "atom", edit: ReadMoreEdit, attributes: { text: { type: "string" }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
295
364
|
{ name: "commentsCount", title: "Số bình luận", icon: MessageSquare, category: theme, keywords: "so binh luan comments count", kind: "atom", edit: CommentsCountEdit, attributes: { textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
296
365
|
{ name: "avatar", title: "Ảnh đại diện tác giả", icon: ImageIcon, category: theme, keywords: "avatar anh dai dien tac gia", kind: "atom", edit: AvatarEdit, attributes: { size: { type: "integer", default: 48, min: 16, max: 256 }, link: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
297
366
|
{ name: "queryTotal", title: "Tổng số bài", icon: ListOrdered, category: theme, keywords: "tong so bai total", kind: "atom", edit: QueryTotalEdit, attributes: { textAlign: TEXT_ALIGN }, supports: { style: true, className: true }, structure: { parents: ["query"] } },
|
|
367
|
+
{ name: "termList", title: "Danh sách chuyên mục / thẻ", icon: Tag, category: theme, keywords: "danh sach chuyen muc the category tag cloud term list", kind: "atom", edit: TermListEdit, attributes: { taxonomy: { type: "string", default: "category" }, display: { type: "string", enum: ["list", "cloud"], default: "list" }, showCount: { type: "boolean", default: false }, hierarchical: { type: "boolean", default: false }, hideEmpty: { type: "boolean", default: true } }, supports: { style: true, className: true }, summary: (a) => a.taxonomy },
|
|
368
|
+
{ name: "loginout", title: "Đăng nhập / Đăng xuất", icon: User, category: theme, keywords: "dang nhap dang xuat login logout", kind: "atom", edit: LoginOutEdit, attributes: { loginText: { type: "string" }, logoutText: { type: "string" }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
369
|
+
{ name: "icon", title: "Icon", icon: Star, category: theme, keywords: "icon bieu tuong", kind: "atom", edit: IconEdit, attributes: { name: { type: "string", enum: ["check", "x", "star", "heart", "arrowRight", "phone", "mail", "mapPin", "clock", "info", "alert", "externalLink"], default: "star" }, size: { type: "integer", default: 24, min: 12, max: 128 }, label: { type: "string" }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true }, summary: (a) => a.name },
|
|
370
|
+
{ name: "footnotes", title: "Chú thích cuối bài", icon: ListOrdered, category: theme, keywords: "chu thich cuoi bai footnotes", kind: "atom", edit: FootnotesEdit, attributes: { title: { type: "string" } }, supports: { style: true, className: true } },
|
|
371
|
+
{ name: "pageBreak", title: "Ngắt trang", icon: PanelTop, category: theme, keywords: "ngat trang page break nextpage", kind: "atom", edit: PageBreakEdit, supports: { className: true } },
|
|
372
|
+
{ name: "pageList", title: "Danh sách trang", icon: ListOrdered, category: theme, keywords: "danh sach trang page list sitemap", kind: "atom", edit: PageListEdit, attributes: { parentId: { type: "integer", min: 1 }, depth: { type: "integer", default: 2, min: 1, max: 3 } }, supports: { style: true, className: true } },
|
|
373
|
+
{ name: "archives", title: "Lưu trữ theo tháng", icon: CalendarDays, category: theme, keywords: "luu tru thang archives", kind: "atom", edit: ArchivesEdit, attributes: { showCount: { type: "boolean", default: true }, limit: { type: "integer", default: 12, min: 1, max: 60 } }, supports: { style: true, className: true } },
|
|
298
374
|
{ name: "queryTitle", title: "Tiêu đề trang lưu trữ", icon: Heading1, category: theme, keywords: "tieu de luu tru chuyen muc archive query title h1", kind: "atom", edit: QueryTitleEdit, attributes: { level: { type: "integer", default: 1, min: 1, max: 6 }, prefix: { type: "boolean", default: false }, textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
299
375
|
{ name: "termDescription", title: "Mô tả chuyên mục", icon: AlignLeft, category: theme, keywords: "mo ta chuyen muc term description", kind: "atom", edit: TermDescriptionEdit, attributes: { textAlign: TEXT_ALIGN }, supports: { style: true, className: true } },
|
|
300
376
|
{ name: "breadcrumbs", title: "Breadcrumb", icon: ChevronsRight, category: theme, keywords: "breadcrumb duong dan dieu huong", kind: "atom", edit: BreadcrumbsEdit, attributes: { separator: { type: "string", default: "›" }, showHome: { type: "boolean", default: true }, showCurrent: { type: "boolean", default: true } }, supports: { style: true, className: true } },
|
|
@@ -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/clipboard.ts
CHANGED
|
@@ -10,7 +10,7 @@ export const BLOCKS_MIME = "application/x-ecx-blocks";
|
|
|
10
10
|
// ---------------------------------------------------------------------------
|
|
11
11
|
// HTML → khối
|
|
12
12
|
// ---------------------------------------------------------------------------
|
|
13
|
-
const MARK_TAGS: Record<string, string> = { STRONG: "bold", B: "bold", EM: "italic", I: "italic", U: "underline", S: "strike", DEL: "strike", STRIKE: "strike", CODE: "code", SUB: "subscript", SUP: "superscript", MARK: "highlight" };
|
|
13
|
+
const MARK_TAGS: Record<string, string> = { STRONG: "bold", B: "bold", EM: "italic", I: "italic", U: "underline", S: "strike", DEL: "strike", STRIKE: "strike", CODE: "code", KBD: "kbd", SUB: "subscript", SUP: "superscript", MARK: "highlight" };
|
|
14
14
|
const BLOCK_TAGS = new Set(["P", "DIV", "H1", "H2", "H3", "H4", "H5", "H6", "UL", "OL", "LI", "BLOCKQUOTE", "PRE", "HR", "TABLE", "FIGURE", "IMG", "SECTION", "ARTICLE", "HEADER", "FOOTER", "MAIN", "ASIDE", "NAV", "DL", "DT", "DD"]);
|
|
15
15
|
|
|
16
16
|
function inlineOf(node: globalThis.Node, marks: RichMark[] = [], out: RichNode[] = []): RichNode[] {
|
|
@@ -187,7 +187,7 @@ export function serializeBlocks(nodes: BNode[]): { json: string; text: string; h
|
|
|
187
187
|
}
|
|
188
188
|
|
|
189
189
|
const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!);
|
|
190
|
-
const MARK_HTML: Record<string, string> = { bold: "strong", italic: "em", underline: "u", strike: "s", code: "code", subscript: "sub", superscript: "sup", highlight: "mark" };
|
|
190
|
+
const MARK_HTML: Record<string, string> = { bold: "strong", italic: "em", underline: "u", strike: "s", code: "code", kbd: "kbd", subscript: "sub", superscript: "sup", highlight: "mark" };
|
|
191
191
|
/** HTML đơn giản (dán sang Word, email…). */
|
|
192
192
|
export function richToHtml(nodes: RichNode[]): string {
|
|
193
193
|
const inl = (list: RichNode[] = []) => list.map((n) => {
|
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}
|
|
@@ -23,6 +23,8 @@ const marks: Record<string, MarkSpec> = {
|
|
|
23
23
|
underline: simple("u"),
|
|
24
24
|
strike: simple("s", ["del", "strike"]),
|
|
25
25
|
code: { ...simple("code"), excludes: "_" },
|
|
26
|
+
footnote: { attrs: { note: { default: "" } }, inclusive: false, parseDOM: [{ tag: "span[data-ecx-footnote]", getAttrs: (d) => ({ note: (d as HTMLElement).getAttribute("data-ecx-footnote") ?? "" }) }], toDOM: (m) => ["span", { "data-ecx-footnote": String(m.attrs.note), class: "ecx-footnote-mark" }, 0] },
|
|
27
|
+
kbd: { ...simple("kbd"), excludes: "_" },
|
|
26
28
|
subscript: { ...simple("sub"), excludes: "superscript" },
|
|
27
29
|
superscript: { ...simple("sup"), excludes: "subscript" },
|
|
28
30
|
highlight: { attrs: { color: { default: null } }, parseDOM: [{ tag: "mark" }], toDOM: (m) => ["mark", m.attrs.color ? { style: `background:${m.attrs.color}` } : {}, 0] },
|
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. */
|
package/src/v2/ui/toolbar.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AlignCenter, AlignLeft, AlignRight, ArrowUpLeft, Bold, ChevronDown, ChevronUp, Code, Copy, CopyPlus, GripVertical, IndentDecrease, IndentIncrease, Italic, Link2, Link2Off, MoreVertical, PanelTop, Strikethrough, Trash2, Underline, Ungroup, Group as GroupIcon, Blocks, ArrowUpToLine, ArrowDownToLine, Shapes, Lock, Subscript, Superscript, Highlighter } from "lucide-react";
|
|
1
|
+
import { StickyNote, Keyboard, AlignCenter, AlignLeft, AlignRight, ArrowUpLeft, Bold, ChevronDown, ChevronUp, Code, Copy, CopyPlus, GripVertical, IndentDecrease, IndentIncrease, Italic, Link2, Link2Off, MoreVertical, PanelTop, Strikethrough, Trash2, Underline, Ungroup, Group as GroupIcon, Blocks, ArrowUpToLine, ArrowDownToLine, Shapes, Lock, Subscript, Superscript, Highlighter } from "lucide-react";
|
|
2
2
|
import { TextSelection } from "prosemirror-state";
|
|
3
3
|
import type { EditorView } from "prosemirror-view";
|
|
4
4
|
import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type ReactNode } from "react";
|
|
@@ -276,14 +276,19 @@ function MarkTools({ view, onLink }: { view: EditorView; onLink(): void }) {
|
|
|
276
276
|
const type = view.state.schema.marks[name];
|
|
277
277
|
const { from, to, empty } = view.state.selection;
|
|
278
278
|
const tr = view.state.tr;
|
|
279
|
-
if (
|
|
279
|
+
if (name === "footnote") {
|
|
280
|
+
// shortcut: hỏi nội dung bằng prompt() của trình duyệt, nâng thành popover khi cần sửa chú thích có sẵn
|
|
281
|
+
if (empty) return;
|
|
282
|
+
if (isActive(name)) tr.removeMark(from, to, type);
|
|
283
|
+
else { const note = window.prompt(labels.footnote)?.trim(); if (!note) return; tr.addMark(from, to, type.create({ note })); }
|
|
284
|
+
} else if (empty) tr.setStoredMarks(isActive(name) ? (view.state.storedMarks ?? view.state.selection.$from.marks()).filter((m) => m.type !== type) : [...(view.state.storedMarks ?? view.state.selection.$from.marks()), type.create()]);
|
|
280
285
|
else if (isActive(name)) tr.removeMark(from, to, type);
|
|
281
286
|
else tr.addMark(from, to, type.create());
|
|
282
287
|
view.dispatch(tr);
|
|
283
288
|
view.focus();
|
|
284
289
|
};
|
|
285
290
|
const main: Array<[string, typeof Bold, string, string]> = [["bold", Bold, labels.bold, `${mod}B`], ["italic", Italic, labels.italic, `${mod}I`], ["underline", Underline, labels.underline, `${mod}U`]];
|
|
286
|
-
const more: Array<[string, typeof Bold, string]> = [["strike", Strikethrough, labels.strike], ["code", Code, labels.code], ["subscript", Subscript, labels.subscript], ["superscript", Superscript, labels.superscript], ["highlight", Highlighter, labels.highlight]];
|
|
291
|
+
const more: Array<[string, typeof Bold, string]> = [["strike", Strikethrough, labels.strike], ["code", Code, labels.code], ["kbd", Keyboard, labels.kbd], ["footnote", StickyNote, labels.footnote], ["subscript", Subscript, labels.subscript], ["superscript", Superscript, labels.superscript], ["highlight", Highlighter, labels.highlight]];
|
|
287
292
|
return (
|
|
288
293
|
<div className="ecx-tool-group">
|
|
289
294
|
{main.map(([name, I, l, k]) => <ToolButton key={name} label={`${l} (${k})`} active={isActive(name)} onClick={() => toggle(name)}><I className="ecx-icon" /></ToolButton>)}
|