Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support block type conversion in the editing toolbar https://github.com/siyuan-note/siyuan/issues/19985

Daniel5fe0b916461b
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 076b7ab913..8922c0a054 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "سيؤدي هذا التحويل إلى تغيير بنية الكتلة الخارجية أو تخطيطها",
"attributePanelVisibility": "ظهور الحقل في لوحة الخصائص",
"alwaysShow": "إظهار دائمًا",
"hideWhenEmpty": "إخفاء عندما يكون فارغًا",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 7266fed5bf..8aa78a5669 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Diese Umwandlung würde die Struktur oder das Layout des äußeren Blocks ändern",
"attributePanelVisibility": "Feldsichtbarkeit im Eigenschaftsbereich",
"alwaysShow": "Immer anzeigen",
"hideWhenEmpty": "Ausblenden, wenn leer",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index e9352d91af..eb0194c1e2 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "This conversion would change the outer block structure or layout",
"attributePanelVisibility": "Attribute panel field visibility",
"alwaysShow": "Always show",
"hideWhenEmpty": "Hide when empty",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 2f4df1d671..3202f62f39 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Esta conversión cambiaría la estructura o el diseño del bloque exterior",
"attributePanelVisibility": "Visibilidad del campo en el panel de propiedades",
"alwaysShow": "Mostrar siempre",
"hideWhenEmpty": "Ocultar cuando esté vacío",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 398b96d50c..aab8b00299 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Cette conversion modifierait la structure ou la disposition du bloc extérieur",
"attributePanelVisibility": "Visibilité du champ dans le panneau des propriétés",
"alwaysShow": "Toujours afficher",
"hideWhenEmpty": "Masquer si vide",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 2795d7c6c5..859cbe309b 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "המרה זו תשנה את המבנה או הפריסה של הבלוק החיצוני",
"attributePanelVisibility": "נראות שדה בחלונית המאפיינים",
"alwaysShow": "הצג תמיד",
"hideWhenEmpty": "הסתר כשהשדה ריק",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 44b796091e..b43e8ac5c7 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "इस रूपांतरण से बाहरी ब्लॉक की संरचना या लेआउट बदल जाएगा",
"attributePanelVisibility": "गुण पैनल में फ़ील्ड की दृश्यता",
"alwaysShow": "हमेशा दिखाएँ",
"hideWhenEmpty": "खाली होने पर छिपाएँ",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 00803d42dd..1e88778ca6 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Konversi ini akan mengubah struktur atau tata letak blok luar",
"attributePanelVisibility": "Visibilitas kolom di panel properti",
"alwaysShow": "Selalu tampilkan",
"hideWhenEmpty": "Sembunyikan saat kosong",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index c2d648f5ce..48d845a738 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Questa conversione modificherebbe la struttura o la disposizione del blocco esterno",
"attributePanelVisibility": "Visibilità del campo nel pannello delle proprietà",
"alwaysShow": "Mostra sempre",
"hideWhenEmpty": "Nascondi se vuoto",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 04cb8368b0..def82c25a7 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "この変換は外側のブロックの構造やレイアウトを変更するため実行できません",
"attributePanelVisibility": "属性パネルのフィールド表示",
"alwaysShow": "常に表示",
"hideWhenEmpty": "空の場合は非表示",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index d97c76328c..d705d9d407 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "이 변환은 바깥쪽 블록의 구조나 레이아웃을 변경합니다",
"attributePanelVisibility": "속성 패널 필드 표시",
"alwaysShow": "항상 표시",
"hideWhenEmpty": "비어 있으면 숨기기",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 828591ce12..db4f32851b 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Deze conversie zou de structuur of indeling van het buitenste blok wijzigen",
"attributePanelVisibility": "Veldzichtbaarheid in het eigenschappenpaneel",
"alwaysShow": "Altijd tonen",
"hideWhenEmpty": "Verbergen indien leeg",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index a09423f7a1..3a9a0bf770 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Ta konwersja zmieniłaby strukturę lub układ bloku zewnętrznego",
"attributePanelVisibility": "Widoczność pola w panelu właściwości",
"alwaysShow": "Zawsze pokazuj",
"hideWhenEmpty": "Ukryj, gdy puste",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 7b364c8885..b78a27b16d 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Esta conversão alteraria a estrutura ou o layout do bloco externo",
"attributePanelVisibility": "Visibilidade do campo no painel de propriedades",
"alwaysShow": "Sempre mostrar",
"hideWhenEmpty": "Ocultar quando vazio",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 1c781ae479..157521b4fc 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Это преобразование изменит структуру или расположение внешнего блока",
"attributePanelVisibility": "Видимость поля в панели свойств",
"alwaysShow": "Всегда показывать",
"hideWhenEmpty": "Скрывать, если пусто",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 27df9ac854..512a87f57d 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Táto konverzia by zmenila štruktúru alebo rozloženie vonkajšieho bloku",
"attributePanelVisibility": "Viditeľnosť poľa na paneli vlastností",
"alwaysShow": "Vždy zobraziť",
"hideWhenEmpty": "Skryť, ak je prázdne",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 09f3c504ed..d4c8e65ff9 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Ова конверзија би променила структуру или распоред спољног блока",
"attributePanelVisibility": "Видљивост поља у панелу својстава",
"alwaysShow": "Увек прикажи",
"hideWhenEmpty": "Сакриј када је празно",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index bf7e73bcc3..bdec3c07ed 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "การแปลงนี้จะเปลี่ยนโครงสร้างหรือเค้าโครงของบล็อกภายนอก",
"attributePanelVisibility": "การแสดงฟิลด์ในแผงคุณสมบัติ",
"alwaysShow": "แสดงเสมอ",
"hideWhenEmpty": "ซ่อนเมื่อว่าง",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 31ddf9581a..e709bdcf85 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Bu dönüştürme dış bloğun yapısını veya düzenini değiştirir",
"attributePanelVisibility": "Özellik panelindeki alan görünürlüğü",
"alwaysShow": "Her zaman göster",
"hideWhenEmpty": "Boş olduğunda gizle",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 596fda0ab4..3889db0582 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "Це перетворення змінить структуру або розташування зовнішнього блоку",
"attributePanelVisibility": "Видимість поля в панелі властивостей",
"alwaysShow": "Завжди показувати",
"hideWhenEmpty": "Приховувати, якщо порожнє",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 65c4c04bf9..353037e7b7 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "此转换会改变外层块的结构或布局",
"attributePanelVisibility": "属性面板字段可见性",
"alwaysShow": "始终显示",
"hideWhenEmpty": "空白时隐藏",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 02349453ee..83915f6636 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "blockTypeParentChange": "此轉換會改變外層區塊的結構或版面配置",
"attributePanelVisibility": "屬性面板欄位可見性",
"alwaysShow": "始終顯示",
"hideWhenEmpty": "空白時隱藏",
diff --git a/app/src/assets/scss/protyle/_toolbar.scss b/app/src/assets/scss/protyle/_toolbar.scss
index e2eb2a3c20..2720d9a5f2 100644
--- a/app/src/assets/scss/protyle/_toolbar.scss
+++ b/app/src/assets/scss/protyle/_toolbar.scss
@@ -65,7 +65,8 @@
margin: 6px 4px;
}
- &__font {
+ &__font,
+ &__select {
display: inline-flex;
align-items: center;
flex-shrink: 0;
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 6a3c70b322..22bbb79843 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -52,9 +52,10 @@ test("image OCR actions retain their configurable paths and order", () => {
assert.equal(getEntryParentPath("inline.image.ocr.copyOCRText"), "inline.image.ocr");
});
-test("remove list leads single and multiple block conversion menus", () => {
+test("remove list precedes list types in single and multiple block conversion menus", () => {
for (const path of ["gutter.single.turnInto", "gutter.multi.turnInto"]) {
- assert.deepEqual(getEntryCatalogChildren(path).slice(0, 2).map(item => item.key), ["removeList", "list"]);
+ const keys = getEntryCatalogChildren(path).map(item => item.key);
+ assert.equal(keys[keys.indexOf("list") - 1], "removeList");
const entry = getEntryCatalogNode(`${path}.removeList`);
assert.equal(entry.type, "entry");
assert.equal(entry.simple, true);
@@ -362,6 +363,9 @@ test("plugin top bar entries use the legacy unpinned list as their default visib
});
test("toolbar catalog follows the default toolbar declaration", () => {
+ const blockType = getEntryCatalogNode("editor.toolbar.block-type");
+ assert.equal(blockType.simple, true);
+ assert.equal(blockType.key, "block-type");
const children = getEntryCatalogChildren(TOOLBAR_ENTRY_ROOT_PATH).filter(item => !item.key.startsWith("mobile-"));
assert.deepEqual(children.map((item) => item.key), DESKTOP_TOOLBAR_ENTRIES.map((item) => item.key));
assert.equal(children.filter((item) => item.type === "separator").length, 2);
@@ -693,15 +697,18 @@ test("callout presets stay aligned across block menu scopes", () => {
});
});
-test("heading conversions follow list conversions across block menu scopes", () => {
+test("paragraph and headings precede list conversions across block menu scopes", () => {
const headingKeys = ["heading1", "heading2", "heading3", "heading4", "heading5", "heading6"];
["gutter.single.turnInto", "gutter.multi.turnInto"].forEach((path) => {
const keys = getEntryCatalogChildren(path).map(item => item.key);
- assert.equal(keys[0], "removeList");
+ assert.equal(keys[0], "paragraph");
assert.equal(getEntryCatalogNode(`${path}.paragraph`)?.simple, true);
const headingIndex = keys.indexOf("heading1");
- assert.equal(headingIndex, keys.indexOf(path === "gutter.single.turnInto" ? "tabs" : "calloutCustom") + 1);
+ assert.equal(headingIndex, 1);
assert.deepEqual(keys.slice(headingIndex, headingIndex + headingKeys.length), headingKeys);
+ assert.deepEqual(keys.filter(key => ["list", "orderedList", "check", "quote", "callout"].includes(key)),
+ ["list", "orderedList", "check", "quote", "callout"]);
+ assert.equal(keys[headingIndex + headingKeys.length], "removeList");
headingKeys.forEach(key => {
const entry = getEntryCatalogNode(`${path}.${key}`);
assert.equal(entry?.type, "entry");
@@ -713,11 +720,11 @@ test("heading conversions follow list conversions across block menu scopes", ()
test("tab conversion belongs to the single block conversion menu", () => {
const keys = getEntryCatalogChildren("gutter.single.turnInto").map(item => item.key);
assert.equal(keys[keys.indexOf("tabs") - 1], "calloutCustom");
- assert.equal(keys[keys.indexOf("tabs") + 1], "heading1");
+ assert.equal(keys[keys.indexOf("tabs") + 1], "superBlock");
assert.equal(getEntryCatalogNode("gutter.single.turnInto.tabs")?.simple, true);
assert.equal(getEntryCatalogNode("gutter.single.turnInto.tabs")?.type, "entry");
assert.equal(getEntryCatalogNode("gutter.multi.turnInto.tabs"), undefined);
- assert.equal(keys[keys.indexOf("superBlock") - 1], "heading6");
+ assert.equal(keys[keys.indexOf("superBlock") - 1], "tabs");
assert.equal(keys[keys.indexOf("superBlock") + 1], "code");
assert.equal(getEntryCatalogNode("gutter.single.turnInto.superBlock")?.simple, true);
assert.equal(getEntryCatalogNode("gutter.single.turnInto.superBlock")?.type, "entry");
@@ -1340,12 +1347,13 @@ test("simple profile follows the reviewed defaults", () => {
hidden.forEach((path) => assert.equal(getEntryCatalogNode(path)?.simple, false, path));
});
-test("list conversion prioritizes list actions and keeps recursive entry identities", () => {
+test("list conversion groups list actions and keeps recursive entry identities", () => {
for (const root of ["gutter.single", "gutter.multi"]) {
const keys = getEntryCatalogChildren(`${root}.turnInto`).map(item => item.key);
- assert.deepEqual(keys.slice(0, root === "gutter.single" ? 7 : 6), [
+ const start = keys.indexOf("removeList");
+ assert.deepEqual(keys.slice(start, start + (root === "gutter.single" ? 6 : 5)), [
"removeList", "list", "orderedList", "check",
- ...(root === "gutter.single" ? ["listMindmap"] : []), "includeSublists", "paragraph",
+ ...(root === "gutter.single" ? ["listMindmap"] : []), "includeSublists",
]);
const children = getEntryCatalogChildren(`${root}.turnInto.includeSublists`);
assert.deepEqual(children.map(item => item.key), [
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index acc723a376..a93b7c91e8 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -1,4 +1,5 @@
import {CODE_TAB_SPACE_VALUES} from "../../protyle/wysiwyg/codeBlockUtil";
+import {orderGutterTurnIntoItems} from "../../protyle/gutter/turnIntoMenu";
import {
DESKTOP_TOOLBAR_ENTRIES,
getToolbarEntryId,
@@ -212,7 +213,7 @@ const gutterCopyChildren = (single = false) => [
] : []),
];
-const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), true, [
+const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), true, orderGutterTurnIntoItems([
node("removeList", lang("removeList")),
node("list", lang("list")),
node("orderedList", lang("ordered-list")),
@@ -235,7 +236,6 @@ const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), tr
node("calloutCaution", location(lang("callout"), literal("Caution"))),
node("calloutCustom", location(lang("callout"), () => `${window.siyuan.languages.custom}...`)),
...(!multi ? [node("tabs", lang("tabs"))] : []),
- // 列表及列表项复用段落和标题入口,保持单选、多选的配置标识和默认顺序一致。
node("heading1", lang("heading1")),
node("heading2", lang("heading2")),
node("heading3", lang("heading3")),
@@ -247,7 +247,7 @@ const gutterTurnInto = (multi: boolean) => node("turnInto", lang("turnInto"), tr
node("table", lang("tableBlock")),
node("line", lang("line")),
node("math", lang("math")),
- ]);
+ ], item => item.key));
const gutterHeadingTransform = () => node("tWithSubtitle", lang("tWithSubtitle"), true, [
node("heading1", lang("heading1")),
@@ -501,7 +501,7 @@ const gutterSingle = () => [
export const SLASH_MENU_ROOT_PATH = "editor.slash.menu";
-// 共享工具栏声明决定目录默认顺序,字体和字号位于外观之前。
+// 共享工具栏声明决定目录默认顺序,块类型位于首位,字体和字号位于外观之前。
const toolbarBuiltinChildren = [
...MOBILE_TOOLBAR_ACTIONS.map(item => node(getMobileToolbarActionKey(item.name), lang(item.lang), true)),
separator("mobile-separator"),
diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.ts
index c08e5b477b..e0acbc68a1 100644
--- a/app/src/config/entryVisibility/order.test.ts
+++ b/app/src/config/entryVisibility/order.test.ts
@@ -106,10 +106,10 @@ test("remove list merges into saved conversion menus and preserves plugin slots"
saved.splice(1, 0, "plugin:example:item");
const merged = mergeEntryOrderPreservingUnknown(defaults, saved);
assert.deepEqual(merged.filter(key => key !== "removeList"), saved);
- assert.equal(merged[merged.indexOf("list") - 1], "removeList");
+ assert.equal(merged[merged.indexOf("heading6") + 1], "removeList");
const separators = new Set(entries.filter(item => item.type === "separator").map(item => item.key));
assert.deepEqual(resolveEntryOrder([...defaults, "plugin:example:item"], merged, separators), merged);
- assert.deepEqual(resolveEntryOrder(["paragraph", "removeList"], merged, separators), ["paragraph", "removeList"]);
+ assert.deepEqual(resolveEntryOrder(["paragraph", "removeList"], merged, separators), ["removeList", "paragraph"]);
}
});
@@ -273,7 +273,7 @@ test("tab conversion merges into saved block menus without moving plugin slots",
const merged = mergeEntryOrderPreservingUnknown(defaults, saved);
assert.deepEqual(merged.filter(key => key !== "tabs"), saved);
assert.equal(merged[1], "plugin:example:item");
- assert.equal(merged[merged.indexOf("tabs") + 1], "heading1");
+ assert.equal(merged[merged.indexOf("tabs") + 1], "superBlock");
});
test("document tree profiles merge sibling creation while preserving custom order and plugin slots", () => {
diff --git a/app/src/config/entryVisibility/runtime.ts b/app/src/config/entryVisibility/runtime.ts
index 8f31eaf860..f60c9fea3c 100644
--- a/app/src/config/entryVisibility/runtime.ts
+++ b/app/src/config/entryVisibility/runtime.ts
@@ -401,7 +401,8 @@ export const applyToolbarEntryVisibility = (toolbarElement: HTMLElement) => {
const result = resolveToolbarItems(children, {
getKey: resolveKey,
isSeparator: (item) => item.classList.contains("protyle-toolbar__divider"),
- isVisible: (key) => isEntryVisible(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}`),
+ isVisible: (key) => isEntryVisible(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}`) &&
+ children.some(item => resolveKey(item) === key && item.dataset.entryUnavailable !== "true"),
order: getEntryOrder(TOOLBAR_ENTRY_ROOT_PATH),
});
result.ordered.forEach((item) => toolbarElement.append(item));
diff --git a/app/src/config/entryVisibility/ui.test.ts b/app/src/config/entryVisibility/ui.test.ts
index 64b72eff85..282ad9cbdd 100644
--- a/app/src/config/entryVisibility/ui.test.ts
+++ b/app/src/config/entryVisibility/ui.test.ts
@@ -34,8 +34,8 @@ test("entry settings show exit only on native tablets without changing the persi
assert.equal(hasExit(exports.catalog()), true);
mobile = true;
const catalog = exports.catalog();
- assert.deepEqual(Array.from(catalog, item => item.key), [TOOLBAR_ENTRY_ROOT_PATH, "editor.slash"]);
- assert.equal(catalog[1], entryCatalog.find(item => item.key === "editor.slash"));
+ assert.deepEqual(Array.from(catalog, item => item.key), [TOOLBAR_ENTRY_ROOT_PATH, "editor.image", "editor.slash"]);
+ assert.equal(catalog.find(item => item.key === "editor.slash"), entryCatalog.find(item => item.key === "editor.slash"));
assert.ok(catalog[0].children.every(item => item.type === "separator" ||
item.key.startsWith("mobile-") || MOBILE_TOOLBAR_NAMES.includes(item.key)));
for (const name of ["undo", "indent", "heading1", "table", "template"]) {
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 2666cec14e..3874257e6b 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -90,6 +90,8 @@ import {insertEmptyBlock} from "../../block/util";
import {getIconByType} from "../../editor/getIcon";
import {MOBILE_TOOLBAR_ACTIONS, MOBILE_TOOLBAR_INSERTS} from "./toolbarActions";
import {pauseMobileBarsScroll} from "./mobileBars";
+import {getBlockTypeSelection, openBlockTypeMenu, updateBlockTypeButton} from "../../protyle/toolbar/BlockType";
+import {TTextBlockSelection} from "../../protyle/toolbar/blockTypeCore";
const getCurrentEditor = () => getMobileToolbarProtyle()?.getInstance() || getDocumentEditor();
let toolbarProtyle: IProtyle;
@@ -101,6 +103,11 @@ const applyKeyboardToolbarEntries = (element: HTMLElement, toolbar: Array<string
isVisible: key => isEntryVisible(`${TOOLBAR_ENTRY_ROOT_PATH}.${key}`),
isAvailable: name => {
const protyle = getCurrentEditor()?.protyle;
+ if (name === "block-type") {
+ const selection = getSelection();
+ return !!protyle && selection?.rangeCount > 0 &&
+ !!getBlockTypeSelection(protyle, selection.getRangeAt(0));
+ }
if (name === "copy" || name === "cut") {
const selection = getSelection();
return !!protyle && !protyle.disabled && selection?.rangeCount > 0 && !selection.isCollapsed &&
@@ -162,7 +169,7 @@ export const updateMobilePluginToolbar = (protyle: IProtyle) => {
return;
}
inlineToolbarElement.querySelectorAll('[data-plugin-toolbar="true"]').forEach(item => item.remove());
- getMobilePluginToolbarItems(protyle.options.toolbar, Constants.INLINE_TYPE.concat("font-family", "font-size")).forEach(toolbarItem => {
+ getMobilePluginToolbarItems(protyle.options.toolbar, Constants.INLINE_TYPE.concat("font-family", "font-size", "block-type")).forEach(toolbarItem => {
const itemElement = document.createElement("button");
itemElement.className = "keyboard__action";
itemElement.dataset.type = toolbarItem.name;
@@ -986,6 +993,7 @@ const renderKeyboardToolbar = () => {
actions.classList.remove("fn__none");
applyKeyboardToolbarEntries(actions, protyle.options.toolbar);
protyle.toolbar.range = range;
+ updateBlockTypeButton(protyle, actions.querySelector('[data-type="block-type"]'), range);
const blockButton = actions.querySelector<HTMLElement>('[data-type="block"]');
const blockType = nodeElement.getAttribute("data-type");
@@ -1450,6 +1458,7 @@ export const initKeyboardToolbar = () => {
${[...MOBILE_TOOLBAR_ACTIONS, ...MOBILE_TOOLBAR_INSERTS].map(item =>
`<button class="keyboard__action" data-type="${item.name}" aria-label="${window.siyuan.languages[item.lang]}"><svg><use xlink:href="#${item.icon}"></use></svg></button>`).join("")}
<span class="keyboard__split" data-id="mobile-separator"></span>
+ <button class="keyboard__action" data-type="block-type" aria-haspopup="menu" aria-label="${window.siyuan.languages.turnInto}">${window.siyuan.languages.paragraph}</button>
<button class="keyboard__action" data-type="block-ref" aria-label="${window.siyuan.languages.ref}"><svg><use xlink:href="#iconRef"></use></svg></button>
<button class="keyboard__action" data-type="a" aria-label="${window.siyuan.languages.link}"><svg><use xlink:href="#iconLink"></use></svg></button>
<span class="keyboard__split" data-id="separator_1"></span>
@@ -1487,8 +1496,20 @@ export const initKeyboardToolbar = () => {
let startY = 0;
let startX = 0;
let moved = false;
- const takeMenuKeyboard = bindMobileMenuKeyboard(toolbarElement, 'button[data-type="block"]',
+ const takeMenuKeyboard = bindMobileMenuKeyboard(toolbarElement, 'button[data-type="block"], button[data-type="block-type"]',
() => getCurrentEditor()?.protyle);
+ let blockTypeSelection: {protyle: IProtyle, snapshot: TTextBlockSelection} | undefined;
+ toolbarElement.addEventListener("pointerdown", event => {
+ blockTypeSelection = undefined;
+ if (!(event.target as Element).closest('button[data-type="block-type"]')) {
+ return;
+ }
+ const protyle = getCurrentEditor()?.protyle;
+ const selection = getSelection();
+ if (protyle && selection?.rangeCount > 0) {
+ blockTypeSelection = {protyle, snapshot: getBlockTypeSelection(protyle, selection.getRangeAt(0))};
+ }
+ }, true);
toolbarElement.addEventListener("touchstart", e => {
startY = e.touches[0].clientY;
startX = e.touches[0].clientX;
@@ -1502,7 +1523,7 @@ export const initKeyboardToolbar = () => {
toolbarElement.addEventListener("mousedown", event => {
const buttonElement = hasClosestByTag(event.target as HTMLElement, "BUTTON");
const type = buttonElement && buttonElement.getAttribute("data-type");
- if (type === "undo" || type === "redo" || type === "block") {
+ if (type === "undo" || type === "redo" || type === "block" || type === "block-type") {
// 保持编辑器焦点,避免工具栏操作期间软键盘收起。
event.preventDefault();
}
@@ -1632,6 +1653,18 @@ export const initKeyboardToolbar = () => {
event.stopPropagation();
const selection = getSelection();
const currentRange = selection.rangeCount > 0 ? selection.getRangeAt(0) : undefined;
+ if (type === "block-type") {
+ const saved = blockTypeSelection;
+ blockTypeSelection = undefined;
+ if (protyle && (!saved || saved.protyle === protyle)) {
+ const snapshot = saved?.snapshot || (currentRange ? getBlockTypeSelection(protyle, currentRange) : undefined);
+ openBlockTypeMenu(protyle, buttonElement, snapshot, {
+ onClose: () => restoreMenuKeyboard?.(),
+ isCurrent: () => getCurrentEditor()?.protyle === protyle,
+ });
+ }
+ return;
+ }
// 收起菜单不依赖实时选区,编辑器失焦后使用保存的选区恢复光标。
const closeAddMenu = type === "add" && buttonElement.classList.contains("protyle-toolbar__item--current");
if (type === "done" || closeAddMenu) {
diff --git a/app/src/mobile/util/pluginToolbar.test.ts b/app/src/mobile/util/pluginToolbar.test.ts
index 231f0cad7c..4a48d8cdbc 100644
--- a/app/src/mobile/util/pluginToolbar.test.ts
+++ b/app/src/mobile/util/pluginToolbar.test.ts
@@ -1,6 +1,8 @@
import {describe, it} from "node:test";
import * as assert from "node:assert/strict";
import {getMobilePluginToolbarItems} from "./pluginToolbar";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
describe("getMobilePluginToolbarItems", () => {
const builtinTypes = ["strong", "em", "inline-memo"];
@@ -32,4 +34,12 @@ describe("getMobilePluginToolbarItems", () => {
assert.deepEqual(pluginItems.map(item => item.name), ["plugin-b", "plugin-a"]);
assert.equal(pluginItems[1].icon, "iconANew");
});
+
+ it("does not duplicate the built-in block type picker as a plugin", () => {
+ const source = readFileSync(resolve(process.cwd(), "src/mobile/util/keyboardToolbar.ts"), "utf8");
+ assert.match(source, /getMobilePluginToolbarItems\(protyle.options.toolbar, Constants.INLINE_TYPE.concat\("font-family", "font-size", "block-type"\)\)/);
+ assert.equal((source.match(/<button class="keyboard__action" data-type="block-type"/g) || []).length, 1);
+ assert.deepEqual(getMobilePluginToolbarItems([{name: "block-type"}, {name: "plugin-a"}],
+ builtinTypes.concat("block-type")), [{name: "plugin-a"}]);
+ });
});
diff --git a/app/src/mobile/util/toolbarEntries.test.ts b/app/src/mobile/util/toolbarEntries.test.ts
index 5b754c4e37..4b6a003847 100644
--- a/app/src/mobile/util/toolbarEntries.test.ts
+++ b/app/src/mobile/util/toolbarEntries.test.ts
@@ -5,6 +5,26 @@ import {getDefaultToolbar, getPluginToolbarEntryKey, markPluginToolbarEntries} f
import {getEntryCatalogChildren} from "../../config/entryVisibility/catalog";
import {resolveEntryOrder} from "../../config/entryVisibility/order";
+test("mobile block type availability and visibility do not change the existing block menu", () => {
+ const root = new ToolbarElement();
+ const type = new ToolbarElement("block-type");
+ const block = new ToolbarElement("block");
+ root.children = [type, block];
+ const apply = (available: boolean, visible = true) => applyMobileToolbarEntries(root as unknown as HTMLElement,
+ getDefaultToolbar(true), {order: ["block-type", "mobile-block"],
+ isVisible: key => key !== "block-type" || visible,
+ isAvailable: name => name !== "block-type" || available});
+ apply(false);
+ assert.equal(type.classList.contains("fn__none"), true);
+ assert.equal(block.classList.contains("fn__none"), false);
+ assert.equal(block.dataset.id, "mobile-block");
+ apply(true);
+ assert.equal(type.classList.contains("fn__none"), false);
+ apply(true, false);
+ assert.equal(type.classList.contains("fn__none"), true);
+ assert.equal(block.classList.contains("fn__none"), false);
+});
+
class ToolbarElement {
public children: ToolbarElement[] = [];
public dataset: {type?: string; id?: string};
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 50b9550e12..9513eb562e 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -46,6 +46,7 @@ import {highlightRender} from "../render/highlightRender";
import {blockRender} from "../render/blockRender";
import {toggleListMindmap} from "../render/listMindmap";
import {getBlockHeightTarget, setBlockHeight} from "./height";
+import {orderGutterTurnIntoItems} from "./turnIntoMenu";
import {
getContenteditableElement,
getEmbedGutterOperationContext,
@@ -1214,7 +1215,7 @@ export class Gutter {
icon: "iconTurnInto",
label: window.siyuan.languages.turnInto,
type: "submenu",
- submenu: turnIntoSubmenu
+ submenu: orderGutterTurnIntoItems(turnIntoSubmenu, item => item.id)
}).element);
if (headingLevel) {
const ids = selectsElement.map((item) => item.getAttribute("data-node-id"));
@@ -1269,7 +1270,7 @@ export class Gutter {
icon: "iconTurnInto",
label: window.siyuan.languages.turnInto,
type: "submenu",
- submenu,
+ submenu: orderGutterTurnIntoItems(submenu, item => item.id),
}).element);
}
}
@@ -1993,7 +1994,7 @@ export class Gutter {
icon: "iconTurnInto",
label: window.siyuan.languages.turnInto,
type: "submenu",
- submenu: turnIntoSubmenu
+ submenu: orderGutterTurnIntoItems(turnIntoSubmenu, item => item.id)
}).element);
}
if (!isEmbedMenu && !protyle.disabled && !nodeElement.classList.contains("hr") &&
diff --git a/app/src/protyle/gutter/turnIntoMenu.test.ts b/app/src/protyle/gutter/turnIntoMenu.test.ts
new file mode 100644
index 0000000000..1ab31ad52b
--- /dev/null
+++ b/app/src/protyle/gutter/turnIntoMenu.test.ts
@@ -0,0 +1,90 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import test from "node:test";
+import {getEntryCatalogChildren} from "../../config/entryVisibility/catalog";
+import {mergeEntryOrderPreservingUnknown, reorderEntrySlots, resolveEntryOrder} from "../../config/entryVisibility/order";
+import {normalizeEntryVisibilityImportProfile} from "../../config/entryVisibility/profile";
+import {orderGutterTurnIntoItems} from "./turnIntoMenu";
+
+const headings = ["heading1", "heading2", "heading3", "heading4", "heading5", "heading6"];
+const common = ["paragraph", ...headings, "list", "orderedList", "check", "quote", "callout"];
+const legacyOrder = (multi: boolean) => [
+ "removeList", "list", "orderedList", "check", ...(!multi ? ["listMindmap"] : []), "includeSublists",
+ "paragraph", "quote", "callout", "calloutNote", "calloutTip", "calloutImportant", "calloutWarning",
+ "calloutCaution", "calloutCustom", ...(!multi ? ["tabs"] : []), ...headings,
+ ...(!multi ? ["superBlock"] : []), "code", "table", "line", "math",
+];
+
+test("default conversion order matches the toolbar while retaining every extra item", () => {
+ for (const multi of [false, true]) {
+ const defaults = getEntryCatalogChildren(`gutter.${multi ? "multi" : "single"}.turnInto`).map(item => item.key);
+ assert.deepEqual(defaults.filter(key => common.includes(key)), common);
+ assert.deepEqual([...defaults].sort(), legacyOrder(multi).sort());
+ assert.deepEqual(defaults.filter(key => !common.includes(key)), legacyOrder(multi).filter(key => !common.includes(key)));
+ assert.deepEqual(resolveEntryOrder(defaults, undefined, new Set()), defaults);
+ assert.deepEqual(resolveEntryOrder(defaults, [], new Set()), defaults);
+ assert.deepEqual(orderGutterTurnIntoItems(legacyOrder(multi), key => key), defaults);
+ }
+});
+
+test("partial paragraph and heading menus keep their candidates and callbacks", () => {
+ const cases = [
+ {input: ["list", "orderedList", "check", "quote", "callout", ...headings],
+ expected: [...headings, "list", "orderedList", "check", "quote", "callout"]},
+ {input: ["paragraph", "quote", "callout", ...headings.filter(key => key !== "heading2")],
+ expected: ["paragraph", ...headings.filter(key => key !== "heading2"), "quote", "callout"]},
+ {input: ["removeList", "check", "paragraph", "heading2", "heading1"],
+ expected: ["paragraph", "heading1", "heading2", "removeList", "check"]},
+ ];
+ for (const {input, expected} of cases) {
+ const items = input.map(id => ({id, label: id, accelerator: id, click: () => id}));
+ const sorted = orderGutterTurnIntoItems(items, item => item.id);
+ assert.deepEqual(sorted.map(item => item.id), expected);
+ assert.deepEqual(items.map(item => item.id), input);
+ sorted.forEach(item => assert.equal(item, items.find(original => original.id === item.id)));
+ }
+});
+
+test("saved conversion orders and visibility survive profile migration and default changes", () => {
+ for (const multi of [false, true]) {
+ const path = `gutter.${multi ? "multi" : "single"}.turnInto`;
+ const defaults = getEntryCatalogChildren(path).map(item => item.key);
+ const saved = legacyOrder(multi);
+ saved.splice(2, 0, "plugin:example:item");
+ const input = {name: "Custom", entries: {[`${path}.quote`]: false}, orders: {[path]: saved}};
+ for (const version of [3, 4, 5, 6]) {
+ const profile = normalizeEntryVisibilityImportProfile(input, version, {[path]: defaults});
+ assert.deepEqual(profile, input);
+ assert.deepEqual(mergeEntryOrderPreservingUnknown(defaults, profile.orders[path]), saved);
+ assert.deepEqual(resolveEntryOrder(defaults, profile.orders[path], new Set()),
+ saved.filter(key => key !== "plugin:example:item"));
+ }
+ const custom = ["callout", "heading2", "paragraph", "list"];
+ const resolved = resolveEntryOrder(defaults, custom, new Set());
+ assert.deepEqual(resolved.filter(key => custom.includes(key)), custom);
+ const items = orderGutterTurnIntoItems(custom, key => key);
+ assert.deepEqual(reorderEntrySlots(items, resolved, key => key), custom);
+ }
+});
+
+test("conversion ordering preserves plugin slots and separators", () => {
+ const separator = {type: "separator"};
+ const plugin = {id: "plugin:example:item"};
+ const items: Array<{id?: string, type?: string}> = [
+ {id: "list"}, plugin, {id: "quote"}, separator, {id: "heading2"}, {id: "paragraph"},
+ ];
+ const sorted = orderGutterTurnIntoItems(items, item => item.id);
+ assert.deepEqual(sorted.map(item => item.id || item.type),
+ ["paragraph", "plugin:example:item", "heading2", "separator", "list", "quote"]);
+ assert.equal(sorted[1], plugin);
+ assert.equal(sorted[3], separator);
+ assert.notEqual(sorted[0].type, "separator");
+ assert.notEqual(sorted[sorted.length - 1].type, "separator");
+});
+
+test("single, multiple and list-item menus share ordering before platform configuration", () => {
+ const source = readFileSync(resolve(process.cwd(), "src/protyle/gutter/index.ts"), "utf8");
+ assert.equal(Array.from(source.matchAll(/submenu: orderGutterTurnIntoItems\(turnIntoSubmenu, item => item.id\)/g)).length, 2);
+ assert.match(source, /const submenu = this.listTurnIntoMenu\(protyle, selectsElement\);[\s\S]*?submenu: orderGutterTurnIntoItems\(submenu, item => item.id\)/);
+});
diff --git a/app/src/protyle/gutter/turnIntoMenu.ts b/app/src/protyle/gutter/turnIntoMenu.ts
new file mode 100644
index 0000000000..4884c02ea4
--- /dev/null
+++ b/app/src/protyle/gutter/turnIntoMenu.ts
@@ -0,0 +1,14 @@
+import {reorderEntrySlots} from "../../config/entryVisibility/order";
+
+// 块标菜单与配置目录共用默认顺序,附加操作保留在对应类型附近。
+const turnIntoOrder = [
+ "paragraph",
+ "heading1", "heading2", "heading3", "heading4", "heading5", "heading6",
+ "removeList", "list", "orderedList", "check", "listMindmap", "includeSublists",
+ "quote", "callout",
+ "calloutNote", "calloutTip", "calloutImportant", "calloutWarning", "calloutCaution", "calloutCustom",
+ "tabs", "superBlock", "code", "table", "line", "math",
+];
+
+export const orderGutterTurnIntoItems = <T>(items: T[], getKey: (item: T) => string | undefined) =>
+ reorderEntrySlots(items, turnIntoOrder, getKey);
diff --git a/app/src/protyle/toolbar/BlockType.test.ts b/app/src/protyle/toolbar/BlockType.test.ts
new file mode 100644
index 0000000000..264c090965
--- /dev/null
+++ b/app/src/protyle/toolbar/BlockType.test.ts
@@ -0,0 +1,227 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import {resolve} from "node:path";
+import {test} from "node:test";
+import {runInNewContext} from "node:vm";
+import {createSourceFile, isClassDeclaration, isMethodDeclaration, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {getBlockTypeOptions, isSameTextRange} from "./blockTypeCore";
+
+const source = transpileModule(readFileSync(resolve(process.cwd(), "src/protyle/toolbar/BlockType.ts"), "utf8"),
+ {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;
+
+const menuSource = createSourceFile("Menu.ts", readFileSync("src/menus/Menu.ts", "utf8"), ScriptTarget.ES2021, true);
+const menuClass = menuSource.statements.find(statement => isClassDeclaration(statement) && statement.name?.text === "Menu");
+const closeSheet = isClassDeclaration(menuClass) && menuClass.members.find(member =>
+ isMethodDeclaration(member) && member.name.getText(menuSource) === "closeSheet").getText(menuSource);
+const sheetExports = {} as {close: (this: object) => void};
+runInNewContext(transpileModule(`class Sheet { ${closeSheet} } exports.close = Sheet.prototype.closeSheet;`,
+ {compilerOptions: {target: ScriptTarget.ES2021}}).outputText, {
+ exports: sheetExports,
+ window: {setTimeout: () => { throw new Error("Keyboard restoration must stay in the close gesture"); }},
+});
+
+const setup = (mobile = false) => {
+ const classes = new Set<string>();
+ const block = {dataset: {nodeId: "target", type: "NodeParagraph", subtype: ""},
+ style: {width: "", flex: ""}, closest: (): Element => null,
+ parentElement: {classList: {contains: (value: string) => classes.has(value)}, querySelectorAll: () => [block]},
+ } as unknown as HTMLElement;
+ const range = {startContainer: {}, endContainer: {}, startOffset: 1, endOffset: 5,
+ collapsed: false} as Range;
+ const editorFocus = {};
+ const protyle = {block: {rootID: "doc"}, wysiwyg: {element: {contains: (element: unknown) => element === editorFocus}}, toolbar: {range,
+ element: {classList: {add: (): void => undefined}}, subElement: {classList: {add: (): void => undefined}}},
+ disabled: false, lite: false} as unknown as IProtyle;
+ const snapshot = {block, range};
+ const items: IMenu[] = [];
+ const transactions: Record<string, unknown>[] = [];
+ const listeners = new Map<string, (event?: {target: unknown}) => void>();
+ const state = {valid: true, current: true, mobile, readonly: false, restored: 0, closed: 0, mobileOpened: 0,
+ selection: {rangeCount: 1, isCollapsed: false, getRangeAt: () => range},
+ embed: undefined as {allowChildOperation: boolean, targetElement?: HTMLElement} | undefined};
+ const menu = {close: (): void => undefined};
+ const commonMenu = {
+ restoreKeyboard: undefined as (() => void) | undefined,
+ element: {classList: {contains: () => true}},
+ fullscreen: (_position: string, restore: () => void) => {
+ state.mobileOpened++;
+ commonMenu.restoreKeyboard = restore;
+ },
+ removeImmediately: () => {
+ menu.close();
+ commonMenu.restoreKeyboard = undefined;
+ },
+ };
+ class FakeMenu {
+ isOpen = false;
+ element = {contains: (): boolean => false};
+ constructor(_id: string, private onClose: () => void) {
+ menu.close = () => this.close();
+ }
+ addItem(item: IMenu) { items.push(item); }
+ open() { return; }
+ fullscreen() { state.mobileOpened++; }
+ close() {
+ state.closed++;
+ this.onClose();
+ }
+ }
+ const exports = {} as typeof import("./BlockType");
+ const modules: Record<string, unknown> = {
+ "../../plugin/Menu": {Menu: FakeMenu},
+ "./ToolbarItem": {ToolbarItem: class {}},
+ "./blockTypeCore": {
+ getTextSelectionBlock: (context: {disabled: boolean, lite: boolean}) =>
+ context.disabled || context.lite || !state.valid ? undefined : block,
+ captureTextBlockSelection: () => snapshot,
+ isTextBlockSelectionValid: () => state.valid,
+ getBlockTypeOptions, isSameTextRange,
+ },
+ "../wysiwyg/getBlock": {getEmbedGutterOperationContext: () => state.embed},
+ "../wysiwyg/transaction": {
+ turnsIntoTransaction: (options: Record<string, unknown>) => transactions.push(options),
+ turnsIntoOneTransaction: (options: Record<string, unknown>) => transactions.push(options),
+ },
+ "../util/selection": {focusByRange: () => state.restored++},
+ "./subElementLifecycle": {closeSubElement: (): void => undefined},
+ "../../util/escape": {escapeHtml: (value: string) => value},
+ "../../util/functions": {isMobile: () => state.mobile},
+ };
+ const document = {
+ activeElement: undefined as unknown,
+ body: {},
+ addEventListener: (name: string, listener: () => void) => listeners.set(name, listener),
+ removeEventListener: (name: string) => listeners.delete(name),
+ };
+ runInNewContext(source, {exports,
+ require: (name: string) => {
+ assert.ok(modules[name], name);
+ return modules[name];
+ },
+ document,
+ window: {getSelection: () => state.selection,
+ siyuan: {config: {get readonly() { return state.readonly; }},
+ menus: {menu: commonMenu},
+ languages: new Proxy({blockTypeParentChange: "Changes outer block"} as Record<string, string>,
+ {get: (target, key: string) => target[key] || key})}},
+ });
+ const button = {isConnected: true, contains: (): boolean => false,
+ getBoundingClientRect: () => ({left: 0, bottom: 30, height: 30, width: 60})} as unknown as HTMLElement;
+ const open = () => exports.openBlockTypeMenu(protyle, button, snapshot as Parameters<typeof exports.openBlockTypeMenu>[2],
+ {isCurrent: () => state.current, onClose: () => state.restored++});
+ const click = (key: string) => items.find(item => item.label.startsWith(key)).click({} as HTMLElement, {} as MouseEvent);
+ return {block, protyle, snapshot, items, transactions, listeners, state, menu, classes, button, open, click,
+ document, editorFocus, closeSheet: () => sheetExports.close.call(commonMenu)};
+};
+
+test("selecting the current type is a no-op including an existing heading", () => {
+ for (const heading of [false, true]) {
+ const fixture = setup();
+ if (heading) {
+ fixture.block.dataset.type = "NodeHeading";
+ fixture.block.dataset.subtype = "h2";
+ }
+ fixture.open();
+ fixture.click(heading ? "heading2" : "paragraph");
+ assert.equal(fixture.transactions.length, 0);
+ }
+});
+
+test("type actions pass exactly one explicit child and never invoke shortcut or batch selection", () => {
+ for (const [key, type] of [["heading2", "Blocks2Hs"], ["list", "Blocks2ULs"], ["ordered-list", "Blocks2OLs"],
+ ["check", "Blocks2TLs"], ["quote", "Blocks2Blockquote"], ["callout", "Blocks2Callout"]]) {
+ const fixture = setup();
+ fixture.open();
+ fixture.click(key);
+ assert.equal(fixture.transactions.length, 1);
+ const operation = fixture.transactions[0];
+ assert.equal(operation.type, type);
+ assert.equal((operation.selectsElement as Element[]).length, 1);
+ assert.equal((operation.selectsElement as Element[])[0], fixture.block);
+ assert.equal(operation.nodeElement, undefined);
+ assert.equal(operation.getOperations, undefined);
+ assert.equal(fixture.state.restored, 0);
+ assert.equal(fixture.listeners.size, 0);
+ }
+});
+
+test("unsafe wrappers are disabled with a persistent reason and cannot send operations", () => {
+ const fixture = setup(true);
+ fixture.classes.add("sb");
+ fixture.open();
+ assert.equal(fixture.state.mobileOpened, 1);
+ const option = fixture.items.find(item => item.label.startsWith("quote"));
+ assert.equal(option.disabled, true);
+ assert.match(option.label, /Changes outer block/);
+ let accessibleLabel = "";
+ option.bind({setAttribute: (_name: string, value: string) => { accessibleLabel = value; }} as HTMLElement);
+ assert.match(accessibleLabel, /Changes outer block/);
+ fixture.click("quote");
+ assert.equal(fixture.transactions.length, 0);
+});
+
+test("execution rechecks safety after the menu opens", () => {
+ for (const change of ["readonly", "disabled", "lite", "disconnected", "document", "selection", "superblock", "embed"]) {
+ const fixture = setup();
+ fixture.open();
+ if (change === "readonly") { fixture.state.readonly = true; }
+ if (change === "disabled") { fixture.protyle.disabled = true; }
+ if (change === "lite") { fixture.protyle.lite = true; }
+ if (change === "disconnected") { fixture.state.valid = false; }
+ if (change === "document") { fixture.state.current = false; }
+ if (change === "selection") {
+ fixture.state.selection.getRangeAt = () => ({...fixture.snapshot.range, startOffset: 2});
+ }
+ if (change === "superblock") { fixture.classes.add("sb"); }
+ if (change === "embed") {
+ fixture.block.closest = () => ({}) as Element;
+ fixture.state.embed = {allowChildOperation: false};
+ }
+ fixture.click("quote");
+ assert.equal(fixture.transactions.length, 0, change);
+ }
+});
+
+test("cancel restores a valid selection but does not revive an invalid or replaced selection", () => {
+ for (const changed of [false, true]) {
+ const fixture = setup(true);
+ fixture.open();
+ if (changed) {
+ fixture.state.selection.getRangeAt = () => ({...fixture.snapshot.range, endOffset: 6});
+ fixture.listeners.get("selectionchange")();
+ }
+ fixture.menu.close();
+ assert.equal(fixture.state.restored, changed ? 0 : 1);
+ assert.equal(fixture.listeners.size, 0);
+ assert.equal(fixture.transactions.length, 0);
+ }
+});
+
+test("closing the menu does not steal focus from a new caret, another input or an outside pointer", () => {
+ for (const change of ["caret", "input", "pointer"]) {
+ const fixture = setup();
+ fixture.open();
+ if (change === "caret") {
+ fixture.document.activeElement = fixture.editorFocus;
+ fixture.state.selection.isCollapsed = true;
+ fixture.state.selection.getRangeAt = () => ({...fixture.snapshot.range, endOffset: 1, collapsed: true});
+ } else if (change === "input") {
+ fixture.document.activeElement = {};
+ } else {
+ fixture.listeners.get("pointerdown")({target: {}});
+ }
+ fixture.menu.close();
+ assert.equal(fixture.state.restored, 0, change);
+ assert.equal(fixture.listeners.size, 0);
+ }
+});
+
+test("tapping the mobile scrim restores once through the real synchronous sheet close path", () => {
+ const fixture = setup(true);
+ fixture.open();
+ fixture.listeners.get("pointerdown")({target: {closest: () => ({id: "commonMenuScrim"})}});
+ fixture.closeSheet();
+ assert.equal(fixture.state.restored, 1);
+ assert.equal(fixture.listeners.size, 0);
+ assert.equal(fixture.transactions.length, 0);
+});
diff --git a/app/src/protyle/toolbar/BlockType.ts b/app/src/protyle/toolbar/BlockType.ts
new file mode 100644
index 0000000000..6dba79617d
--- /dev/null
+++ b/app/src/protyle/toolbar/BlockType.ts
@@ -0,0 +1,167 @@
+import {Menu} from "../../plugin/Menu";
+import {ToolbarItem} from "./ToolbarItem";
+import {
+ captureTextBlockSelection,
+ getBlockTypeKey,
+ getBlockTypeOptions,
+ getTextSelectionBlock,
+ isSameTextRange,
+ isTextBlockSelectionValid,
+ TTextBlockSelection,
+} from "./blockTypeCore";
+import {getEmbedGutterOperationContext} from "../wysiwyg/getBlock";
+import {turnsIntoOneTransaction, turnsIntoTransaction} from "../wysiwyg/transaction";
+import {focusByRange} from "../util/selection";
+import {closeSubElement} from "./subElementLifecycle";
+import {escapeHtml} from "../../util/escape";
+import {isMobile} from "../../util/functions";
+
+const context = (protyle: IProtyle, range = protyle.toolbar.range) => ({
+ editor: protyle.wysiwyg.element, range, lite: protyle.lite,
+ disabled: protyle.disabled || window.siyuan.config.readonly,
+});
+
+export const getBlockTypeSelection = (protyle: IProtyle, range = protyle?.toolbar.range) => {
+ if (!protyle) {
+ return;
+ }
+ const block = getTextSelectionBlock(context(protyle, range));
+ if (!block) {
+ return;
+ }
+ if (block.closest('[data-type="NodeBlockQueryEmbed"]')) {
+ const embed = getEmbedGutterOperationContext(block);
+ if (!embed?.allowChildOperation || embed.targetElement === block) {
+ return;
+ }
+ }
+ return captureTextBlockSelection(context(protyle, range), protyle.block.rootID);
+};
+
+export const updateBlockTypeButton = (protyle: IProtyle, button: HTMLElement, range = protyle.toolbar.range) => {
+ if (!button) {
+ return;
+ }
+ const selection = getBlockTypeSelection(protyle, range);
+ button.dataset.entryUnavailable = selection ? "false" : "true";
+ const label = selection ? window.siyuan.languages[getBlockTypeKey(selection.block)] : window.siyuan.languages.turnInto;
+ const labelElement = button.querySelector(".protyle-toolbar__select-label");
+ if (labelElement) {
+ labelElement.textContent = label;
+ } else {
+ button.textContent = label;
+ }
+ button.setAttribute("aria-label", `${window.siyuan.languages.turnInto} ${label}`);
+};
+
+export const openBlockTypeMenu = (protyle: IProtyle, button: HTMLElement, snapshot: TTextBlockSelection,
+ options: {onClose?: () => void, isCurrent?: () => boolean} = {}) => {
+ const valid = () => options.isCurrent?.() !== false && button.isConnected &&
+ isTextBlockSelectionValid(snapshot, context(protyle), protyle.block.rootID) &&
+ getBlockTypeSelection(protyle, snapshot.range)?.block === snapshot.block;
+ if (!valid()) {
+ return;
+ }
+ closeSubElement(protyle.toolbar);
+ protyle.toolbar.subElement.classList.add("fn__none");
+ let applied = false;
+ let changedSelection = false;
+ let restored = false;
+ const selectionChanged = () => {
+ const selection = window.getSelection();
+ const active = document.activeElement;
+ if (selection?.rangeCount && !isSameTextRange(selection.getRangeAt(0), snapshot.range) &&
+ (!selection.isCollapsed || active && protyle.wysiwyg.element.contains(active))) {
+ changedSelection = true;
+ }
+ };
+ const movedOutside = (event: PointerEvent) => {
+ if ((event.target as Element).closest?.("#commonMenuScrim")) {
+ return;
+ }
+ if (!menu.element.contains(event.target as Node) && !button.contains(event.target as Node)) {
+ changedSelection = true;
+ }
+ };
+ const restoreSelection = () => {
+ const active = document.activeElement;
+ if (active && active !== document.body && active !== button &&
+ !protyle.wysiwyg.element.contains(active) && !menu.element.contains(active)) {
+ return;
+ }
+ selectionChanged();
+ if (!restored && !applied && !changedSelection && valid()) {
+ restored = true;
+ if (options.onClose) {
+ options.onClose();
+ } else if (!isMobile()) {
+ focusByRange(snapshot.range);
+ }
+ }
+ };
+ const menu = new Menu("selectionBlockType", () => {
+ document.removeEventListener("selectionchange", selectionChanged);
+ document.removeEventListener("pointerdown", movedOutside, true);
+ restoreSelection();
+ });
+ if (menu.isOpen) {
+ return;
+ }
+ document.addEventListener("selectionchange", selectionChanged);
+ document.addEventListener("pointerdown", movedOutside, true);
+ getBlockTypeOptions(snapshot.block).forEach(option => {
+ const label = window.siyuan.languages[option.lang];
+ const reason = option.disabled ? window.siyuan.languages.blockTypeParentChange : "";
+ menu.addItem({
+ icon: option.icon,
+ checked: option.current,
+ disabled: option.disabled,
+ label: escapeHtml(label) + (reason ? `<span class="fn__block ft__smaller">${escapeHtml(reason)}</span>` : ""),
+ bind: element => element.setAttribute("aria-label", reason ? `${label} ${reason}` : label),
+ click: () => {
+ selectionChanged();
+ if (changedSelection || !valid()) {
+ return;
+ }
+ const current = getBlockTypeOptions(snapshot.block).find(item => item.key === option.key);
+ if (!current || current.disabled || current.current) {
+ return;
+ }
+ // 菜单显式设置目标类型,不经过快捷键的同级标题切换和整块多选路径。
+ applied = true;
+ menu.close();
+ protyle.toolbar.element.classList.add("fn__none");
+ if (current.type === "Blocks2Ps" || current.type === "Blocks2Hs") {
+ turnsIntoTransaction({protyle, selectsElement: [snapshot.block], type: current.type, level: current.level});
+ } else {
+ void turnsIntoOneTransaction({protyle, selectsElement: [snapshot.block], type: current.type});
+ }
+ },
+ });
+ });
+ if (isMobile()) {
+ window.siyuan.menus.menu.fullscreen("bottom", restoreSelection);
+ } else {
+ const rect = button.getBoundingClientRect();
+ menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: button});
+ }
+};
+
+export class BlockType extends ToolbarItem {
+ constructor(protyle: IProtyle, item: IMenuItem) {
+ super(protyle, item);
+ this.element.classList.add("protyle-toolbar__select");
+ this.element.dataset.entryUnavailable = "true";
+ this.element.innerHTML = '<span class="protyle-toolbar__select-label"></span><svg aria-hidden="true"><use xlink:href="#iconDown"></use></svg>';
+ this.element.setAttribute("aria-haspopup", "menu");
+ this.element.setAttribute("data-menu", "true");
+ this.element.addEventListener("mousedown", event => event.preventDefault());
+ this.element.addEventListener("click", () => {
+ const selection = window.getSelection();
+ const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
+ if (isSameTextRange(range, protyle.toolbar.range)) {
+ openBlockTypeMenu(protyle, this.element, getBlockTypeSelection(protyle, range));
+ }
+ });
+ }
+}
diff --git a/app/src/protyle/toolbar/blockTypeCore.test.ts b/app/src/protyle/toolbar/blockTypeCore.test.ts
new file mode 100644
index 0000000000..95db383c70
--- /dev/null
+++ b/app/src/protyle/toolbar/blockTypeCore.test.ts
@@ -0,0 +1,213 @@
+import * as assert from "node:assert/strict";
+import {test} from "node:test";
+import {
+ captureTextBlockSelection,
+ getBlockTypeOptions,
+ getTextSelectionBlock,
+ ITextBlockContext,
+ isSameTextRange,
+ isTextBlockSelectionValid,
+} from "./blockTypeCore";
+
+class TestElement {
+ nodeType = 1;
+ isConnected = true;
+ parentElement: TestElement;
+ children: TestElement[] = [];
+ dataset: Record<string, string> = {};
+ style = {width: "", flex: ""};
+ textContent = "selected words and remaining content";
+ editable: string;
+ classes = new Set<string>();
+ classList = {contains: (name: string) => this.classes.has(name)};
+ excluded = false;
+
+ constructor(type?: string) {
+ if (type) {
+ this.dataset = {nodeId: type, type};
+ }
+ }
+
+ append(element: TestElement) {
+ element.parentElement = this;
+ this.children.push(element);
+ return element;
+ }
+
+ closest(selector: string): TestElement | null {
+ const match = selector === ".protyle-wysiwyg" ? this.classes.has("protyle-wysiwyg") :
+ selector === "[data-node-id][data-type]" ? !!this.dataset.nodeId && !!this.dataset.type :
+ selector === "[contenteditable]" ? this.editable !== undefined : this.excluded;
+ return match ? this : this.parentElement?.closest(selector) || null;
+ }
+
+ getAttribute(name: string) {
+ return name === "contenteditable" ? this.editable : name.startsWith("data-") ?
+ this.dataset[name.slice(5).replace(/-([a-z])/g, (_match, char: string) => char.toUpperCase())] || null : null;
+ }
+
+ querySelector(selector: string): TestElement | null {
+ for (const child of this.children) {
+ if (selector === ".protyle-wysiwyg--select" && child.classes.has("protyle-wysiwyg--select")) {
+ return child;
+ }
+ const found = child.querySelector(selector);
+ if (found) {
+ return found;
+ }
+ }
+ return null;
+ }
+
+ querySelectorAll() {
+ return this.children.filter(child => child.dataset.nodeId);
+ }
+}
+
+const asElement = (element: TestElement) => element as unknown as HTMLElement;
+
+const fixture = (type = "NodeParagraph", parentType?: string) => {
+ const editor = new TestElement();
+ editor.classes.add("protyle-wysiwyg");
+ const parent = parentType ? editor.append(new TestElement(parentType)) : editor;
+ const block = parent.append(new TestElement(type));
+ if (type === "NodeHeading") {
+ block.dataset.subtype = "h2";
+ }
+ const editable = block.append(new TestElement());
+ editable.editable = "true";
+ const inline = editable.append(new TestElement());
+ const start = {nodeType: 3, parentElement: inline, isConnected: true} as unknown as Node;
+ const end = {nodeType: 3, parentElement: editable, isConnected: true} as unknown as Node;
+ const range = {startContainer: start, endContainer: end, startOffset: 1, endOffset: 5,
+ collapsed: false, toString: () => "selected words",
+ cloneRange() { return {...this}; },
+ } as Range;
+ const context: ITextBlockContext = {editor: asElement(editor), range, disabled: false, lite: false};
+ return {editor, parent, block, editable, inline, start, end, range, context};
+};
+
+test("single text blocks expose explicit targets including structural wrappers", () => {
+ for (const type of ["NodeParagraph", "NodeHeading"]) {
+ const {context, block} = fixture(type);
+ assert.equal(getTextSelectionBlock(context), block);
+ const options = getBlockTypeOptions(asElement(block));
+ assert.deepEqual(options.map(item => item.key), ["paragraph", "heading1", "heading2", "heading3", "heading4",
+ "heading5", "heading6", "list", "orderedList", "check", "quote", "callout"]);
+ assert.equal(options.filter(item => item.current).length, 1);
+ assert.equal(options.find(item => item.current).key, type === "NodeParagraph" ? "paragraph" : "heading2");
+ assert.equal(options.some(item => item.disabled), false);
+ }
+});
+
+test("nested selections keep their actual child as the conversion target", () => {
+ for (const parentType of ["NodeListItem", "NodeBlockquote", "NodeCallout", "NodeTabItem", "NodeSuperBlock"]) {
+ const {context, parent, block} = fixture("NodeParagraph", parentType);
+ const before = JSON.stringify(parent.dataset);
+ assert.equal(getTextSelectionBlock(context), block);
+ assert.notEqual(getTextSelectionBlock(context), parent);
+ assert.equal(JSON.stringify(parent.dataset), before);
+ }
+});
+
+test("cross-child selections are rejected even inside the same container", () => {
+ for (const type of ["NodeListItem", "NodeBlockquote"]) {
+ const {context, parent, range} = fixture("NodeParagraph", type);
+ const other = parent.append(new TestElement("NodeParagraph"));
+ const editable = other.append(new TestElement());
+ editable.editable = "true";
+ Object.assign(range, {endContainer: {nodeType: 3, parentElement: editable, isConnected: true}});
+ assert.equal(getTextSelectionBlock(context), undefined);
+ }
+});
+
+test("editable element offsets are accepted while block boundary ranges are rejected", () => {
+ const {context, range, editable, block} = fixture();
+ Object.assign(range, {startContainer: editable, endContainer: editable});
+ assert.equal(getTextSelectionBlock(context), block);
+ Object.assign(range, {startContainer: block});
+ assert.equal(getTextSelectionBlock(context), undefined);
+});
+
+test("empty, collapsed, readonly, lite, image and explicit block selections have no entry", () => {
+ for (const value of ["", " \n\t", "\u200b", "\u2060\ufeff"]) {
+ const {context, range} = fixture();
+ range.toString = () => value;
+ assert.equal(getTextSelectionBlock(context), undefined);
+ }
+ for (const flag of ["disabled", "lite"] as const) {
+ const {context} = fixture();
+ context[flag] = true;
+ assert.equal(getTextSelectionBlock(context), undefined);
+ }
+ const {context, range, inline, block} = fixture();
+ Object.assign(range, {collapsed: true});
+ assert.equal(getTextSelectionBlock(context), undefined);
+ Object.assign(range, {collapsed: false});
+ inline.editable = "false";
+ assert.equal(getTextSelectionBlock(context), undefined);
+ delete inline.editable;
+ block.classes.add("protyle-wysiwyg--select");
+ assert.equal(getTextSelectionBlock(context), undefined);
+});
+
+test("unsupported sources, table cells, hidden tabs and nested editors cannot convert their parent", () => {
+ for (const type of ["NodeCodeBlock", "NodeTable", "NodeCallout", "NodeTabItem", "NodeList", "NodeBlockquote"]) {
+ const {context, block} = fixture(type);
+ assert.equal(getTextSelectionBlock(context), undefined);
+ assert.deepEqual(getBlockTypeOptions(asElement(block)), []);
+ }
+ const {context, parent, editable} = fixture();
+ parent.excluded = true;
+ assert.equal(getTextSelectionBlock(context), undefined);
+ parent.excluded = false;
+ editable.classes.add("protyle-wysiwyg");
+ assert.equal(getTextSelectionBlock(context), undefined);
+});
+
+test("superblock protection is per operation and preserves safe heading conversion", () => {
+ const {parent, block} = fixture("NodeParagraph", "NodeSuperBlock");
+ parent.classes.add("sb");
+ const disabled = () => getBlockTypeOptions(asElement(block)).filter(option => option.disabled).map(option => option.key);
+ assert.deepEqual(disabled(), ["list", "orderedList", "check", "quote", "callout"]);
+ parent.append(new TestElement("NodeParagraph"));
+ assert.deepEqual(disabled(), []);
+ block.style.width = "30%";
+ assert.deepEqual(disabled(), ["list", "orderedList", "check", "quote", "callout"]);
+});
+
+test("snapshots reject document switches, readonly state and stale or redirected ranges", () => {
+ const {context, block, range} = fixture();
+ const snapshot = captureTextBlockSelection(context, "document");
+ const valid = (root = "document") => isTextBlockSelectionValid(snapshot, context, root);
+ assert.equal(valid(), true);
+ assert.equal(isSameTextRange(range, snapshot.range), true);
+ assert.equal(valid("another-document"), false);
+ assert.equal(isTextBlockSelectionValid(snapshot, fixture().context, "document"), false);
+ context.disabled = true;
+ assert.equal(valid(), false);
+ context.disabled = false;
+ block.textContent += "changed";
+ assert.equal(valid(), false);
+ block.textContent = snapshot.text;
+ block.dataset.subtype = "h3";
+ assert.equal(valid(), false);
+ delete block.dataset.subtype;
+ Object.assign(snapshot.range, {startContainer: block.parentElement});
+ assert.equal(valid(), false);
+ Object.assign(snapshot.range, {startContainer: snapshot.start});
+ block.parentElement = new TestElement();
+ assert.equal(valid(), false);
+});
+
+test("snapshots reject ancestor layout changes and readonly roots", () => {
+ const {context, editor, parent} = fixture("NodeParagraph", "NodeSuperBlock");
+ parent.dataset.sbLayout = "row";
+ const snapshot = captureTextBlockSelection(context, "document");
+ parent.dataset.sbLayout = "col";
+ assert.equal(isTextBlockSelectionValid(snapshot, context, "document"), false);
+ parent.dataset.sbLayout = "row";
+ assert.equal(isTextBlockSelectionValid(snapshot, context, "document"), true);
+ editor.dataset.readonly = "true";
+ assert.equal(getTextSelectionBlock(context), undefined);
+});
diff --git a/app/src/protyle/toolbar/blockTypeCore.ts b/app/src/protyle/toolbar/blockTypeCore.ts
new file mode 100644
index 0000000000..3d027dd3fd
--- /dev/null
+++ b/app/src/protyle/toolbar/blockTypeCore.ts
@@ -0,0 +1,108 @@
+export interface ITextBlockContext {
+ editor: HTMLElement;
+ range: Range;
+ disabled: boolean;
+ lite: boolean;
+}
+
+export interface IBlockTypeOption {
+ key: string;
+ lang: string;
+ icon: string;
+ type: TTurnInto | TTurnIntoOne;
+ level?: number;
+ current: boolean;
+ disabled: boolean;
+}
+
+const elementOf = (node: Node) => node?.nodeType === 1 ? node as Element : node?.parentElement;
+
+// 仅识别实际承载文字的子块,不把容器标题或跨块选区提升为父块。
+export const getTextSelectionBlock = ({editor, range, disabled, lite}: ITextBlockContext): HTMLElement | undefined => {
+ if (disabled || lite || !editor?.isConnected || editor.dataset.readonly === "true" || !range || range.collapsed ||
+ !range.startContainer.isConnected || !range.endContainer.isConnected ||
+ !range.toString().replace(/[\u200b-\u200f\u2060-\u2064\ufeff]/g, "").trim() ||
+ editor.querySelector(".protyle-wysiwyg--select")) {
+ return;
+ }
+ const start = elementOf(range.startContainer);
+ const end = elementOf(range.endContainer);
+ if (start?.closest(".protyle-wysiwyg") !== editor || end?.closest(".protyle-wysiwyg") !== editor) {
+ return;
+ }
+ const block = start.closest<HTMLElement>("[data-node-id][data-type]");
+ if (!block || block !== end.closest("[data-node-id][data-type]") ||
+ !["NodeParagraph", "NodeHeading"].includes(block.dataset.type) ||
+ block.closest('td, th, .tab-item[data-tabs-hidden="true"]')) {
+ return;
+ }
+ const editable = start.closest("[contenteditable]");
+ if (!editable || editable !== end.closest("[contenteditable]") ||
+ editable.getAttribute("contenteditable") !== "true" || editable.parentElement !== block) {
+ return;
+ }
+ return block;
+};
+
+export const getBlockTypeKey = (block: HTMLElement) => block.dataset.type === "NodeHeading" ?
+ `heading${block.dataset.subtype?.slice(1)}` : "paragraph";
+
+export const getBlockTypeOptions = (block: HTMLElement): IBlockTypeOption[] => {
+ if (!["NodeParagraph", "NodeHeading"].includes(block.dataset.type)) {
+ return [];
+ }
+ const current = getBlockTypeKey(block);
+ const parent = block.parentElement;
+ // 包装唯一子块会触发既有转换器取消超级块;带列宽的子块也不能在包装时丢失外层布局。
+ const changesParent = parent?.classList.contains("sb") &&
+ (parent.querySelectorAll(":scope > [data-node-id]").length === 1 || !!block.style.width || !!block.style.flex);
+ return [{key: "paragraph", lang: "paragraph", icon: "iconParagraph", type: "Blocks2Ps" as const},
+ ...[1, 2, 3, 4, 5, 6].map(level => ({
+ key: `heading${level}`, lang: `heading${level}`, icon: `iconH${level}`, type: "Blocks2Hs" as const, level,
+ })),
+ {key: "list", lang: "list", icon: "iconList", type: "Blocks2ULs" as const},
+ {key: "orderedList", lang: "ordered-list", icon: "iconOrderedList", type: "Blocks2OLs" as const},
+ {key: "check", lang: "check", icon: "iconCheck", type: "Blocks2TLs" as const},
+ {key: "quote", lang: "quote", icon: "iconQuote", type: "Blocks2Blockquote" as const},
+ {key: "callout", lang: "callout", icon: "iconCallout", type: "Blocks2Callout" as const},
+ ].map(option => ({...option, current: option.key === current,
+ disabled: Boolean(changesParent && !["Blocks2Ps", "Blocks2Hs"].includes(option.type))}));
+};
+
+export const captureTextBlockSelection = (context: ITextBlockContext, rootID: string) => {
+ const block = getTextSelectionBlock(context);
+ if (!block) {
+ return;
+ }
+ const range = context.range.cloneRange();
+ const ancestors: Array<{element: HTMLElement, parent: HTMLElement, attributes: Array<string | null>}> = [];
+ for (let element = block.parentElement; element && element !== context.editor; element = element.parentElement) {
+ ancestors.push({element, parent: element.parentElement,
+ attributes: ["data-node-id", "data-type", "data-subtype", "data-sb-layout", "style"].map(name => element.getAttribute(name))});
+ }
+ return {
+ editor: context.editor, rootID, block, parent: block.parentElement, ancestors,
+ id: block.dataset.nodeId, type: block.dataset.type, subtype: block.dataset.subtype,
+ text: block.textContent, range,
+ start: range.startContainer, startOffset: range.startOffset,
+ end: range.endContainer, endOffset: range.endOffset,
+ };
+};
+
+export type TTextBlockSelection = ReturnType<typeof captureTextBlockSelection>;
+
+export const isTextBlockSelectionValid = (snapshot: TTextBlockSelection, context: ITextBlockContext,
+ rootID: string) => !!snapshot && snapshot.editor === context.editor &&
+ snapshot.rootID === rootID && snapshot.block === getTextSelectionBlock({...context, range: snapshot.range}) &&
+ snapshot.parent === snapshot.block.parentElement && snapshot.id === snapshot.block.dataset.nodeId &&
+ snapshot.type === snapshot.block.dataset.type && snapshot.subtype === snapshot.block.dataset.subtype &&
+ snapshot.text === snapshot.block.textContent && snapshot.start === snapshot.range.startContainer &&
+ snapshot.startOffset === snapshot.range.startOffset && snapshot.end === snapshot.range.endContainer &&
+ snapshot.endOffset === snapshot.range.endOffset && snapshot.ancestors.every(ancestor =>
+ ancestor.element.parentElement === ancestor.parent &&
+ ["data-node-id", "data-type", "data-subtype", "data-sb-layout", "style"].every((name, index) =>
+ ancestor.element.getAttribute(name) === ancestor.attributes[index]));
+
+export const isSameTextRange = (left: Range, right: Range) => !!left && !!right &&
+ left.startContainer === right.startContainer && left.startOffset === right.startOffset &&
+ left.endContainer === right.endContainer && left.endOffset === right.endOffset;
diff --git a/app/src/protyle/toolbar/defaults.ts b/app/src/protyle/toolbar/defaults.ts
index 08e2e0f561..4b1ce52e18 100644
--- a/app/src/protyle/toolbar/defaults.ts
+++ b/app/src/protyle/toolbar/defaults.ts
@@ -18,6 +18,10 @@ type TConfigurableToolbarItem = IMenuItem & {
export const TOOLBAR_ENTRY_ROOT_PATH = "editor.toolbar";
export const DESKTOP_TOOLBAR_ENTRIES: IToolbarEntry[] = [{
+ key: "block-type",
+ name: "block-type",
+ lang: "turnInto",
+}, {
key: "block-ref",
name: "block-ref",
lang: "ref",
diff --git a/app/src/protyle/toolbar/entryVisibility.test.ts b/app/src/protyle/toolbar/entryVisibility.test.ts
index 0ff3677643..4a423a7e08 100644
--- a/app/src/protyle/toolbar/entryVisibility.test.ts
+++ b/app/src/protyle/toolbar/entryVisibility.test.ts
@@ -22,6 +22,22 @@ test("mobile toolbar shares desktop identifiers and declaration order", () => {
DESKTOP_TOOLBAR_ENTRIES.filter(item => item.name !== "format-painter").map(item => item.key));
});
+test("block type enters old orders without disturbing hidden entries or plugin slots", () => {
+ const defaults = DESKTOP_TOOLBAR_ENTRIES.map(item => item.key);
+ const saved = defaults.filter(key => key !== "block-type");
+ saved.splice(saved.indexOf("strong"), 0, "plugin:missing:action");
+ const merged = mergeEntryOrderPreservingUnknown(defaults, saved);
+ assert.equal(merged.filter(key => key === "block-type").length, 1);
+ assert.equal(merged.indexOf("plugin:missing:action"), saved.indexOf("plugin:missing:action"));
+ assert.deepEqual(merged.filter(key => !["block-type", "plugin:missing:action"].includes(key)),
+ saved.filter(key => key !== "plugin:missing:action"));
+ const items = defaults.map(key => ({key, separator: key.startsWith("separator_")}));
+ const hidden = resolve(items, {order: merged, hidden: ["block-type", "a"]});
+ assert.equal(hidden.visible.some(item => item.key === "block-type" || item.key === "a"), false);
+ assert.equal(hidden.visible[0].separator, false);
+ assert.equal(hidden.visible[hidden.visible.length - 1].separator, false);
+});
+
test("font entries merge into old profiles while preserving plugin slots and hidden entries", () => {
const defaults = DESKTOP_TOOLBAR_ENTRIES.map(item => item.key);
const separators = new Set(DESKTOP_TOOLBAR_ENTRIES.filter(item => item.separator).map(item => item.key));
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 918e1e6c49..62f14b88b2 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -1,4 +1,5 @@
import {Divider} from "./Divider";
+import {BlockType, updateBlockTypeButton} from "./BlockType";
import {prepareInlineElementBoundaryMutation} from "../util/inlineElementBoundary";
import {renderMultiSelectToolbar, updateMultiSelectToolbar} from "../../mobile/util/multiSelectToolbar";
import {selectAllLoadedBlocks} from "../wysiwyg/blockSelection";
@@ -141,7 +142,7 @@ const applyPluginToolbar = (toolbar: Array<string | IMenuItem>, protyle: IProtyl
});
result = filterPluginToolbar(result, protyle.lite);
result.forEach((toolbarItem) => {
- if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|", "font-family", "font-size").includes(toolbarItem.name)) {
+ if (typeof toolbarItem === "string" || Constants.INLINE_TYPE.concat("|", "font-family", "font-size", "block-type").includes(toolbarItem.name)) {
return;
}
if (typeof toolbarItem.hotkey !== "string") {
@@ -296,6 +297,8 @@ export class Toolbar {
return;
}
this.range = range;
+ updateBlockTypeButton(protyle, this.element.querySelector('[data-type="block-type"]'), range);
+ applyToolbarEntryVisibility(this.element);
this.rangePosition = undefined;
this.isMultipleClick = (position?.detail || 0) > 1;
const nodeElement = hasClosestBlock(range.startContainer);
@@ -2530,6 +2533,9 @@ export class Toolbar {
private genItem(protyle: IProtyle, menuItem: IMenuItem) {
let menuItemObj;
switch (menuItem.name) {
+ case "block-type":
+ menuItemObj = new BlockType(protyle, menuItem);
+ break;
case "strong":
case "em":
case "s":
diff --git a/app/src/protyle/toolbar/util.ts b/app/src/protyle/toolbar/util.ts
index 4bc18339d3..cfcfb1c892 100644
--- a/app/src/protyle/toolbar/util.ts
+++ b/app/src/protyle/toolbar/util.ts
@@ -195,6 +195,11 @@ export const removeInlineType = (inlineElement: HTMLElement, type: string, range
export const toolbarKeyToMenu = (toolbar: Array<string | IMenuItem>) => {
const toolbarItem: IMenuItem [] = [{
+ name: "block-type",
+ lang: "turnInto",
+ icon: "iconParagraph",
+ tipPosition: "n",
+ }, {
name: "block-ref",
hotkey: window.siyuan.config.keymap.editor.insert.ref.custom,
lang: "ref",
diff --git a/app/tests/blockTypeConversion.test.js b/app/tests/blockTypeConversion.test.js
new file mode 100644
index 0000000000..f77daaf200
--- /dev/null
+++ b/app/tests/blockTypeConversion.test.js
@@ -0,0 +1,228 @@
+const assert = require("node:assert/strict");
+const {readFileSync, mkdtempSync, rmSync} = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+
+const sources = () => {
+ const ts = require("typescript");
+ const read = file => readFileSync(path.join(__dirname, "../src", file), "utf8");
+ const parsed = ts.createSourceFile("transaction.ts", read("protyle/wysiwyg/transaction.ts"), ts.ScriptTarget.Latest, true);
+ const statements = parsed.statements.filter(statement => ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(declaration =>
+ ["turnsIntoTransaction", "turnsIntoOneTransaction"].includes(declaration.name.getText(parsed))));
+ assert.equal(statements.length, 2);
+ return ts.transpileModule((read("protyle/toolbar/blockTypeCore.ts") + "\n" +
+ statements.map(statement => statement.getText(parsed)).join("\n")).replace(/^export /gm, ""),
+ {compilerOptions: {target: ts.ScriptTarget.ES2021}}).outputText;
+};
+
+const browserCases = async source => {
+ const check = require("node:assert/strict");
+ const lute = window.Lute.New();
+ lute.SetKramdownIAL(true);
+ lute.SetProtyleWYSIWYG(true);
+ lute.SetSuperBlock(true);
+ lute.SetDataTask(true);
+ const editor = document.createElement("div");
+ editor.className = "protyle-wysiwyg";
+ editor.dataset.nodeId = "doc";
+ document.body.append(editor);
+ const batches = [];
+ const noop = () => {};
+ const dependencies = {
+ Constants: {ZWSP: "\u200b", ATTRIBUTE_EDITING: "data-editing"},
+ transaction: (_protyle, forward, backward) => batches.push({forward, backward}),
+ hideElements: noop, processRender: noop, highlightRender: noop, avRender: noop, blockRender: noop,
+ disposeCustomBlocksInElement: noop, focusBlock: noop, focusByWbr: noop, refreshSbs: noop,
+ getPreviousBlockSibling: node => node.previousElementSibling,
+ getNextBlockSibling: node => node.nextElementSibling,
+ getParentBlock: node => node.parentElement.matches(".callout-content, .tab-item-content") ?
+ node.parentElement.parentElement : node.parentElement,
+ getEmbedChildOperationParentID: () => undefined,
+ getSbChildBlockCount: node => node.querySelectorAll(":scope > [data-node-id]").length,
+ isListHeadingContainer: () => false,
+ cancelSB: () => { throw new Error("The unselected superblock must not be cancelled"); },
+ };
+ const api = new Function(...Object.keys(dependencies), source +
+ "\nreturn {turnsIntoTransaction, turnsIntoOneTransaction, getTextSelectionBlock, getBlockTypeOptions};")(...Object.values(dependencies));
+ window.siyuan = {config: {editor: {spellcheck: false}}};
+ const protyle = {lute, wysiwyg: {element: editor}, block: {rootID: "doc", parentID: "doc"},
+ observerLoad: {disconnect: noop}};
+ const find = id => id === "doc" ? editor : editor.querySelector(`[data-node-id="${id}"]`);
+ const replay = operations => operations.forEach(operation => {
+ let node = find(operation.id);
+ if (operation.action === "delete") { node.remove(); return; }
+ if (operation.action === "update") { node.outerHTML = operation.data; return; }
+ if (operation.action === "insert") {
+ const template = document.createElement("template");
+ template.innerHTML = operation.data;
+ node = template.content.firstElementChild;
+ } else {
+ check.equal(operation.action, "move");
+ }
+ if (operation.nextID) {
+ find(operation.nextID).before(node);
+ } else if (operation.previousID) {
+ find(operation.previousID).after(node);
+ } else {
+ let parent = find(operation.parentID);
+ parent = parent.querySelector(":scope > .callout-content, :scope > .tab-item-content") || parent;
+ const first = parent.querySelector(":scope > [data-node-id]");
+ if (first) { first.before(node); }
+ else if (parent.lastElementChild?.classList.contains("protyle-attr")) { parent.lastElementChild.before(node); }
+ else { parent.append(node); }
+ }
+ });
+ const shape = () => Array.from(editor.querySelectorAll("[data-node-id]")).map(node => ({
+ attributes: Array.from(node.attributes).filter(attr => attr.name !== "data-editing")
+ .map(attr => [attr.name, attr.value]).sort(),
+ parent: node.parentElement.closest("[data-node-id]")?.dataset.nodeId,
+ text: node.textContent,
+ }));
+ const actions = [["NodeParagraph", "heading2"], ["NodeHeading", "paragraph"], ["NodeHeading", "heading3"],
+ ...["list", "orderedList", "check", "quote", "callout"].map(key => ["NodeParagraph", key])];
+ for (const parentType of ["root", "NodeListItem", "NodeBlockquote", "NodeCallout", "NodeTabItem", "NodeSuperBlock"]) {
+ for (const [sourceType, key] of actions) {
+ batches.length = 0;
+ editor.innerHTML = "";
+ let parent = editor;
+ if (parentType !== "root") {
+ parent = document.createElement("div");
+ parent.dataset.type = parentType;
+ parent.dataset.nodeId = "parent";
+ parent.setAttribute("custom-test", "keep-parent");
+ if (parentType === "NodeSuperBlock") { parent.className = "sb"; parent.dataset.sbLayout = "row"; }
+ if (parentType === "NodeListItem") {
+ parent.className = "li";
+ parent.dataset.subtype = "u";
+ const list = document.createElement("div");
+ list.className = "list";
+ list.dataset.type = "NodeList";
+ list.dataset.subtype = "u";
+ list.dataset.nodeId = "outer-list";
+ list.setAttribute("custom-test", "keep-list");
+ editor.append(list);
+ list.append(parent);
+ } else {
+ editor.append(parent);
+ }
+ if (["NodeCallout", "NodeTabItem"].includes(parentType)) {
+ const content = document.createElement("div");
+ content.className = parentType === "NodeCallout" ? "callout-content" : "tab-item-content";
+ parent.append(content);
+ parent = content;
+ }
+ }
+ parent.innerHTML = lute.Md2BlockDOM("Before\n\n" + (sourceType === "NodeHeading" ? "## " : "") +
+ "Selected **words** with remaining content\n\nAfter");
+ const blocks = parent.querySelectorAll(":scope > [data-node-id]");
+ const block = blocks[1];
+ block.setAttribute("custom-test", "keep-target");
+ blocks[0].setAttribute("custom-test", "keep-sibling");
+ const targetID = block.dataset.nodeId;
+ const parentElement = block.parentElement;
+ const siblings = [blocks[0].outerHTML, blocks[2].outerHTML];
+ const before = shape();
+ const range = document.createRange();
+ range.setStart(block.firstElementChild.firstChild, 1);
+ range.setEnd(block.firstElementChild.firstChild, 5);
+ check.equal(api.getTextSelectionBlock({editor, range, disabled: false, lite: false}), block);
+ const option = api.getBlockTypeOptions(block).find(item => item.key === key);
+ check.equal(option.disabled, false, parentType + " " + key);
+ const options = {protyle, selectsElement: [block], type: option.type, level: option.level};
+ if (["Blocks2Ps", "Blocks2Hs"].includes(option.type)) { api.turnsIntoTransaction(options); }
+ else { await api.turnsIntoOneTransaction(options); }
+ check.equal(batches.length, 1);
+ check.ok(find(targetID), "keep the content block ID");
+ check.equal(find(targetID).getAttribute("custom-test"), "keep-target");
+ check.equal(parentElement.firstElementChild.outerHTML, siblings[0]);
+ check.equal(parentElement.lastElementChild.outerHTML, siblings[1]);
+ if (parentType !== "root") {
+ check.equal(find("parent").dataset.type, parentType);
+ check.equal(find("parent").getAttribute("custom-test"), "keep-parent");
+ check.equal(batches[0].forward.some(operation => operation.id === "parent"), false);
+ check.equal(batches[0].backward.some(operation => operation.id === "parent"), false);
+ }
+ const after = shape();
+ replay(batches[0].backward);
+ check.deepEqual(shape(), before, parentType + " " + key + " undo");
+ replay(batches[0].forward);
+ check.deepEqual(shape(), after, parentType + " " + key + " redo");
+ }
+ }
+ editor.innerHTML = '<div data-node-id="parent" data-type="NodeSuperBlock" class="sb">' + lute.Md2BlockDOM("Only child") + "</div>";
+ const child = editor.querySelector(".sb > [data-node-id]");
+ const before = editor.innerHTML;
+ for (const key of ["list", "orderedList", "check", "quote", "callout"]) {
+ check.equal(api.getBlockTypeOptions(child).find(item => item.key === key).disabled, true);
+ }
+ check.equal(editor.innerHTML, before, "capability checks must not mutate DOM");
+ editor.remove();
+};
+
+const runElectron = async () => {
+ const {app, BrowserWindow} = require("electron");
+ app.setPath("userData", process.argv[2]);
+ app.commandLine.appendSwitch("disable-gpu");
+ await app.whenReady();
+ const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false, offscreen: true}});
+ let exitCode = 0;
+ try {
+ await win.loadURL("data:text/html,<html><body></body></html>");
+ await win.webContents.executeJavaScript(readFileSync(path.join(__dirname, "../stage/protyle/js/lute/lute.min.js"), "utf8"));
+ await win.webContents.executeJavaScript(`(${browserCases.toString()})(${JSON.stringify(sources())})`);
+ console.log("Block type conversion and undo cases passed");
+ } catch (error) {
+ console.error(error);
+ exitCode = 1;
+ } finally {
+ win.destroy();
+ app.exit(exitCode);
+ }
+};
+
+if (process.versions.electron && process.type === "browser") {
+ runElectron().catch(error => { console.error(error); require("electron").app.exit(1); });
+} else {
+ require("node:test").it("real Lute preserves block IDs, content and custom attributes across paragraph and heading types", () => {
+ require("../stage/protyle/js/lute/lute.min.js");
+ const lute = globalThis.Lute.New();
+ lute.SetProtyleWYSIWYG(true);
+ lute.SetKramdownIAL(true);
+ const paragraph = lute.Md2BlockDOM("Selected **words** and remaining content").replace("<div ", '<div custom-test="keep" ');
+ const id = paragraph.match(/data-node-id="([^"]+)"/)[1];
+ for (let level = 1; level <= 6; level++) {
+ const heading = lute.Blocks2Hs(paragraph, level);
+ assert.ok(heading.includes(`data-node-id="${id}"`));
+ assert.ok(heading.includes(`data-subtype="h${level}"`));
+ const restored = lute.Blocks2Ps(heading);
+ for (const result of [heading, restored]) {
+ assert.ok(result.includes('custom-test="keep"'));
+ assert.ok(result.includes(`data-node-id="${id}"`));
+ assert.ok(result.includes('Selected <span data-type="strong">words</span> and remaining content'));
+ }
+ assert.ok(restored.includes('data-type="NodeParagraph"'));
+ }
+ });
+ require("node:test").it("loads the real conversion functions used by the DOM integration cases", () => {
+ assert.match(sources(), /const turnsIntoTransaction/);
+ assert.match(sources(), /const turnsIntoOneTransaction/);
+ });
+ require("node:test").it("converts the selected text block using real Lute transactions with undo and redo", {
+ skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
+ timeout: 60000,
+ }, async () => {
+ const profile = mkdtempSync(path.join(os.tmpdir(), "siyuan-block-type-"));
+ const env = {...process.env};
+ delete env.ELECTRON_RUN_AS_NODE;
+ try {
+ const {stdout} = await require("node:util").promisify(require("node:child_process").execFile)(
+ require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 55000});
+ assert.match(stdout, /Block type conversion and undo cases passed/);
+ } finally {
+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));
+ assert.ok(path.basename(profile).startsWith("siyuan-block-type-"));
+ rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});
+ }
+ });
+}