Skip to content

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

:sparkles: Support custom ordered list numbering https://github.com/siyuan-note/siyuan/issues/11990

Danielb5df73388340
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 2d177d21c3..f6c534390e 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "رقم البداية",
+ "continueListNumbering": "متابعة ترقيم القائمة",
"msgFormatPainterTip": "إشعارات تنشيط نسخ التنسيق والخروج منه",
"formatPainterInactive": "تم إلغاء تنشيط نسخ التنسيق",
"pluginDisabledInPublishTip": "عطّل مؤلف الإضافة هذه الإضافة في خدمة النشر",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 4eb14385b5..999e063e81 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Startnummer",
+ "continueListNumbering": "Listennummerierung fortsetzen",
"msgFormatPainterTip": "Benachrichtigungen beim Aktivieren und Beenden der Formatübertragung",
"formatPainterInactive": "Formatübertragung deaktiviert",
"pluginDisabledInPublishTip": "Der Plugin-Autor hat dieses Plugin im Veröffentlichungsdienst deaktiviert",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index af4410a893..ce8c623096 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Starting number",
+ "continueListNumbering": "Continue list numbering",
"msgFormatPainterTip": "Format Painter activation and exit notifications",
"formatPainterInactive": "Format Painter deactivated",
"pluginDisabledInPublishTip": "The plugin author has disabled this plugin in the publish service",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 9017ff5b33..e346656e86 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Número inicial",
+ "continueListNumbering": "Continuar numeración de la lista",
"msgFormatPainterTip": "Notificaciones al activar y desactivar Copiar formato",
"formatPainterInactive": "Copia de formato desactivada",
"pluginDisabledInPublishTip": "El autor del complemento ha deshabilitado este complemento en el servicio de publicación",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 0f4082282f..092195ea39 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Numéro de départ",
+ "continueListNumbering": "Continuer la numérotation de la liste",
"msgFormatPainterTip": "Notifications d’activation et de désactivation de la reproduction de mise en forme",
"formatPainterInactive": "Reproduction de la mise en forme désactivée",
"pluginDisabledInPublishTip": "L’auteur du plugin a désactivé ce plugin dans le service de publication",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 5d217042bc..86a5fc3705 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "מספר התחלתי",
+ "continueListNumbering": "המשך מספור הרשימה",
"msgFormatPainterTip": "התראות על הפעלה ויציאה ממברשת העיצוב",
"formatPainterInactive": "מברשת העיצוב הושבתה",
"pluginDisabledInPublishTip": "מחבר התוסף השבית תוסף זה בשירות הפרסום",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index e9e863b2ff..0559b90187 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "प्रारंभिक संख्या",
+ "continueListNumbering": "सूची क्रमांकन जारी रखें",
"msgFormatPainterTip": "फ़ॉर्मैट पेंटर चालू करने और बाहर निकलने की सूचनाएँ",
"formatPainterInactive": "फ़ॉर्मैट पेंटर निष्क्रिय कर दिया गया है",
"pluginDisabledInPublishTip": "प्लगइन लेखक ने इस प्लगइन को प्रकाशन सेवा में अक्षम किया है",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 6c30adf38e..7fa554db72 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Nomor awal",
+ "continueListNumbering": "Lanjutkan penomoran daftar",
"msgFormatPainterTip": "Notifikasi aktivasi dan keluar penyalinan format",
"formatPainterInactive": "Penyalinan format dinonaktifkan",
"pluginDisabledInPublishTip": "Pembuat plugin telah menonaktifkan plugin ini di layanan penerbitan",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index c88e6592da..726016644b 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Numero iniziale",
+ "continueListNumbering": "Continua la numerazione dell'elenco",
"msgFormatPainterTip": "Notifiche di attivazione e uscita di Copia formato",
"formatPainterInactive": "Copia formato disattivata",
"pluginDisabledInPublishTip": "L'autore del plugin ha disabilitato questo plugin nel servizio di pubblicazione",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index b3ba5803a2..c3e0829b60 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "開始番号",
+ "continueListNumbering": "リストの番号を継続",
"msgFormatPainterTip": "書式のコピーの有効化と終了の通知",
"formatPainterInactive": "書式のコピーを終了しました",
"pluginDisabledInPublishTip": "プラグインの作者が公開サービスでこのプラグインを無効にしています",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 3b196afa33..19fb105df6 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "시작 번호",
+ "continueListNumbering": "목록 번호 계속",
"msgFormatPainterTip": "서식 복사 활성화 및 종료 알림",
"formatPainterInactive": "서식 복사가 비활성화됨",
"pluginDisabledInPublishTip": "플러그인 작성자가 게시 서비스에서 이 플러그인을 비활성화했습니다",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index ccacb40e49..0695af2f90 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Startnummer",
+ "continueListNumbering": "Lijstnummering voortzetten",
"msgFormatPainterTip": "Meldingen bij activeren en afsluiten van Opmaak kopiëren",
"formatPainterInactive": "Opmaak kopiëren uitgeschakeld",
"pluginDisabledInPublishTip": "De auteur van de plug-in heeft deze plug-in uitgeschakeld in de publicatieservice",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 898a23ed52..da727afdcc 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Numer początkowy",
+ "continueListNumbering": "Kontynuuj numerację listy",
"msgFormatPainterTip": "Powiadomienia o włączeniu i wyłączeniu Malarza formatów",
"formatPainterInactive": "Malarz formatów wyłączony",
"pluginDisabledInPublishTip": "Autor wtyczki wyłączył tę wtyczkę w usłudze publikowania",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index ab30318af9..3b5f2f2607 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Número inicial",
+ "continueListNumbering": "Continuar numeração da lista",
"msgFormatPainterTip": "Notificações ao ativar e sair do Pincel de formatação",
"formatPainterInactive": "Pincel de formatação desativado",
"pluginDisabledInPublishTip": "O autor do plugin desativou este plugin no serviço de publicação",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index c58ab3e51d..eaea4a4c12 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Начальный номер",
+ "continueListNumbering": "Продолжить нумерацию списка",
"msgFormatPainterTip": "Уведомления о включении и отключении формата по образцу",
"formatPainterInactive": "Формат по образцу отключён",
"pluginDisabledInPublishTip": "Автор плагина отключил этот плагин в службе публикации",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 140a2e357f..94a83942a5 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Počiatočné číslo",
+ "continueListNumbering": "Pokračovať v číslovaní zoznamu",
"msgFormatPainterTip": "Upozornenia na aktiváciu a ukončenie kopírovania formátu",
"formatPainterInactive": "Kopírovanie formátu je deaktivované",
"pluginDisabledInPublishTip": "Autor doplnku zakázal tento doplnok v publikačnej službe",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 7b2e69767a..d8d1c365b2 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "หมายเลขเริ่มต้น",
+ "continueListNumbering": "ดำเนินการลำดับเลขรายการต่อ",
"msgFormatPainterTip": "การแจ้งเตือนเมื่อเปิดและออกจากการคัดลอกรูปแบบ",
"formatPainterInactive": "ปิดการคัดลอกรูปแบบแล้ว",
"pluginDisabledInPublishTip": "ผู้เขียนปลั๊กอินได้ปิดใช้งานปลั๊กอินนี้ในบริการเผยแพร่",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 1314bfb618..11a0ad8694 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Başlangıç numarası",
+ "continueListNumbering": "Liste numaralandırmasına devam et",
"msgFormatPainterTip": "Biçim Boyacısını etkinleştirme ve kapatma bildirimleri",
"formatPainterInactive": "Biçim Boyacısı devre dışı bırakıldı",
"pluginDisabledInPublishTip": "Eklenti yazarı bu eklentiyi yayımlama hizmetinde devre dışı bıraktı",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 709b256092..8eeec795ea 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "Початковий номер",
+ "continueListNumbering": "Продовжити нумерацію списку",
"msgFormatPainterTip": "Сповіщення про ввімкнення та вимкнення формату за зразком",
"formatPainterInactive": "Формат за зразком вимкнено",
"pluginDisabledInPublishTip": "Автор плагіна вимкнув цей плагін у службі публікації",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 8cdff62e78..bb7fb570be 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "起始编号",
+ "continueListNumbering": "继续编号",
"msgFormatPainterTip": "格式刷启用和退出提示",
"formatPainterInactive": "格式刷已退出",
"pluginDisabledInPublishTip": "插件作者已禁止该插件在发布服务中运行",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index fac6382b92..f2769d7574 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,6 @@
{
+ "orderedListStart": "起始編號",
+ "continueListNumbering": "繼續編號",
"msgFormatPainterTip": "格式刷啟用與退出提示",
"formatPainterInactive": "格式刷已退出",
"pluginDisabledInPublishTip": "插件作者已禁止該插件在發布服務中執行",
diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.ts
index 2f56a09cdb..f8a1cff484 100644
--- a/app/src/config/entryVisibility/catalog.test.ts
+++ b/app/src/config/entryVisibility/catalog.test.ts
@@ -85,7 +85,13 @@ test("list block submenu follows the base block entries", () => {
assert.equal(listBlock?.key, "listBlock");
assert.equal(listBlock?.type, "entry");
assert.equal(listBlock?.simple, true);
- assert.deepEqual(listBlock?.children?.map((item) => item.key), ["prependListItem", "appendListItem"]);
+ assert.deepEqual(listBlock?.children?.map((item) => item.key), [
+ "orderedListStart",
+ "continueListNumbering",
+ "separator_numbering",
+ "prependListItem",
+ "appendListItem",
+ ]);
});
test("super block actions and vertical alignment use their respective menu groups", () => {
diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.ts
index 44524fbbd7..1792174d26 100644
--- a/app/src/config/entryVisibility/catalog.ts
+++ b/app/src/config/entryVisibility/catalog.ts
@@ -298,6 +298,9 @@ const gutterSingle = () => [
...gutterBase(false),
separator("separator_listBlock"),
node("listBlock", lang("listBlock"), true, [
+ node("orderedListStart", lang("orderedListStart")),
+ node("continueListNumbering", lang("continueListNumbering")),
+ separator("separator_numbering"),
node("prependListItem", lang("prependListItem")),
node("appendListItem", lang("appendListItem")),
]),
diff --git a/app/src/mobile/util/keyboardToolbar.ts b/app/src/mobile/util/keyboardToolbar.ts
index 23437b37f3..cf7d3723fc 100644
--- a/app/src/mobile/util/keyboardToolbar.ts
+++ b/app/src/mobile/util/keyboardToolbar.ts
@@ -894,7 +894,7 @@ export const initKeyboardToolbar = () => {
event.preventDefault();
}
});
- toolbarElement.addEventListener(isInAndroid() || isInHarmony() ? "touchend" : "click", (event) => {
+ toolbarElement.addEventListener(isInAndroid() || isInHarmony() ? "touchend" : "click", async (event) => {
if (moved) {
return;
}
@@ -1081,7 +1081,7 @@ export const initKeyboardToolbar = () => {
tabCodeBlock(protyle, nodeElement, range, true);
}
} else {
- listOutdent(protyle, [nodeElement.parentElement], range);
+ await listOutdent(protyle, [nodeElement.parentElement], range);
}
focusByRange(range);
return;
@@ -1091,7 +1091,7 @@ export const initKeyboardToolbar = () => {
tabCodeBlock(protyle, nodeElement, range);
}
} else {
- listIndent(protyle, [nodeElement.parentElement], range);
+ await listIndent(protyle, [nodeElement.parentElement], range);
}
focusByRange(range);
return;
diff --git a/app/src/protyle/breadcrumb/index.ts b/app/src/protyle/breadcrumb/index.ts
index 688d4bf259..feec259522 100644
--- a/app/src/protyle/breadcrumb/index.ts
+++ b/app/src/protyle/breadcrumb/index.ts
@@ -75,7 +75,7 @@ ${padHTML}
<button class="block__icon fn__flex-center ariaLabel" data-type="more" aria-label="${window.siyuan.languages.more}"><svg><use xlink:href="#iconMore"></use></svg></button>
<button class="block__icon fn__flex-center fn__none ariaLabel" data-type="context" aria-label="${window.siyuan.languages.context}"><svg><use xlink:href="#iconAlignCenter"></use></svg></button>`;
this.element = element.firstElementChild as HTMLElement;
- element.addEventListener("click", (event) => {
+ element.addEventListener("click", async (event) => {
let target = event.target as HTMLElement;
const arrowElement = target.closest(".protyle-breadcrumb__arrow");
if (arrowElement && this.element.contains(arrowElement)) {
@@ -199,24 +199,24 @@ ${padHTML}
event.stopPropagation();
break;
} else if (type === "outdent") {
+ event.preventDefault();
+ event.stopPropagation();
if (protyle.toolbar.range) {
const blockElement = hasClosestBlock(protyle.toolbar.range.startContainer);
if (blockElement) {
- listOutdent(protyle, [blockElement.parentElement], protyle.toolbar.range);
+ await listOutdent(protyle, [blockElement.parentElement], protyle.toolbar.range);
}
}
- event.preventDefault();
- event.stopPropagation();
break;
} else if (type === "indent") {
+ event.preventDefault();
+ event.stopPropagation();
if (protyle.toolbar.range) {
const blockElement = hasClosestBlock(protyle.toolbar.range.startContainer);
if (blockElement) {
- listIndent(protyle, [blockElement.parentElement], protyle.toolbar.range);
+ await listIndent(protyle, [blockElement.parentElement], protyle.toolbar.range);
}
}
- event.preventDefault();
- event.stopPropagation();
break;
}
target = target.parentElement;
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index cdcfd1a679..500bd1db2c 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -91,7 +91,12 @@ import {showMessage} from "../../dialog/message";
import {checkFold} from "../../util/noRelyPCFunction";
import {clearSelect} from "../util/clear";
import {chartRender} from "../render/chartRender";
-import {appendListItem, prependListItem} from "../wysiwyg/list";
+import {
+ appendListItem,
+ openOrderedListStartDialog,
+ prependListItem,
+ setOrderedListStart
+} from "../wysiwyg/list";
import {applyHeadingLevelUpdates, getHeadingLevelUpdateOperations} from "../util/headingTransform";
import {getGutterMarginHeight} from "./layout";
@@ -1920,7 +1925,33 @@ export class Gutter {
}).element);
}
if ((type === "NodeList" || type === "NodeListItem") && allowStructuralMutation) {
- const listBlockSubmenu: IMenu[] = [{
+ const isOrderedList = type === "NodeList" && nodeElement.getAttribute("data-subtype") === "o";
+ let continueListStart: number;
+ const listBlockSubmenu: IMenu[] = [];
+ if (isOrderedList) {
+ listBlockSubmenu.push({
+ id: "orderedListStart",
+ icon: "iconEdit",
+ label: window.siyuan.languages.orderedListStart,
+ click() {
+ openOrderedListStartDialog(protyle, nodeElement as HTMLElement, range);
+ }
+ }, {
+ id: "continueListNumbering",
+ icon: "iconRefresh",
+ label: window.siyuan.languages.continueListNumbering,
+ disabled: true,
+ click() {
+ if (Number.isInteger(continueListStart)) {
+ setOrderedListStart(protyle, nodeElement as HTMLElement, continueListStart);
+ }
+ }
+ }, {
+ id: "separator_numbering",
+ type: "separator",
+ });
+ }
+ listBlockSubmenu.push({
id: "prependListItem",
icon: "iconBefore",
label: window.siyuan.languages.prependListItem,
@@ -1940,15 +1971,32 @@ export class Gutter {
countBlockWord([], protyle.block.rootID);
void appendListItem(protyle, nodeElement as HTMLElement, range);
}
- }];
+ });
window.siyuan.menus.menu.append(new MenuItem({id: "separator_listBlock", type: "separator"}).element);
- window.siyuan.menus.menu.append(new MenuItem({
+ const listBlockMenuItem = new MenuItem({
id: "listBlock",
icon: "iconList",
label: window.siyuan.languages.listBlock,
type: "submenu",
submenu: listBlockSubmenu,
- }).element);
+ });
+ window.siyuan.menus.menu.append(listBlockMenuItem.element);
+ if (isOrderedList) {
+ const continueElement = listBlockMenuItem.element.querySelector<HTMLElement>(
+ '[data-id="continueListNumbering"]'
+ );
+ fetchPost("/api/block/getOrderedListContinueStart", {
+ id,
+ notebook: protyle.notebookId,
+ }, (response) => {
+ if (!continueElement?.isConnected || !response.data?.found ||
+ !Number.isInteger(response.data.start)) {
+ return;
+ }
+ continueListStart = response.data.start;
+ continueElement.removeAttribute("disabled");
+ });
+ }
} else if (type === "NodeSuperBlock" && !protyle.disabled) {
window.siyuan.menus.menu.append(new MenuItem({
id: "separator_cancelSuperBlock",
diff --git a/app/src/protyle/wysiwyg/enter.ts b/app/src/protyle/wysiwyg/enter.ts
index e5d42df171..25793c7ec1 100644
--- a/app/src/protyle/wysiwyg/enter.ts
+++ b/app/src/protyle/wysiwyg/enter.ts
@@ -12,7 +12,14 @@ import {
IEmbedChildOperationContext
} from "./getBlock";
import {transaction, turnsIntoOneTransaction, updateTransaction} from "./transaction";
-import {breakList, genListItemElement, listOutdent, updateListOrder} from "./list";
+import {
+ breakList,
+ genListItemElement,
+ getFocusedOrderedListInsertOperations,
+ getFocusedParentOrderedList,
+ listOutdent,
+ updateListOrder
+} from "./list";
import {highlightRender} from "../render/highlightRender";
import {Constants} from "../../constants";
import {scrollCenter} from "../../util/highlightById";
@@ -213,7 +220,7 @@ export const enter = async (blockElement: HTMLElement, range: Range, protyle: IP
if ("none" === embedListEnterMode) {
return;
}
- if ("list" === embedListEnterMode && listEnter(protyle, blockElement, range)) {
+ if ("list" === embedListEnterMode && await listEnter(protyle, blockElement, range)) {
return true;
}
}
@@ -431,7 +438,7 @@ const getEmbedListEnterMode = (blockElement: HTMLElement, embedContext: IEmbedCh
return embedContext.boundaryElement.contains(exitsList ? listElement.parentElement : listElement) ? "list" : "none";
};
-const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) => {
+const listEnter = async (protyle: IProtyle, blockElement: HTMLElement, range: Range) => {
const listItemElement = blockElement.parentElement;
const editableElement = getContenteditableElement(blockElement);
if (// \n 是因为 https://github.com/siyuan-note/siyuan/issues/3846
@@ -440,7 +447,7 @@ const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) =
!blockElement.querySelector("img") // https://ld246.com/article/1651820644238
) {
if (listItemElement.nextElementSibling?.classList.contains("protyle-attr")) {
- listOutdent(protyle, [blockElement.parentElement], range);
+ await listOutdent(protyle, [blockElement.parentElement], range);
return true;
} else if (!listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
// 打断列表
@@ -486,6 +493,16 @@ const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) =
return true;
}
+ const shouldUpdateParentList = listItemElement.getAttribute("data-subtype") === "o" &&
+ listItemElement.parentElement.classList.contains("protyle-wysiwyg");
+ const focusedParentListElement = shouldUpdateParentList ?
+ await getFocusedParentOrderedList(protyle, listItemElement.parentElement) : undefined;
+ if (shouldUpdateParentList && !focusedParentListElement) {
+ return true;
+ }
+ if (!listItemElement.isConnected) {
+ return true;
+ }
const subListElement = listItemElement.querySelector(".list");
let newElement;
if (subListElement && listItemElement.getAttribute("fold") !== "1" &&
@@ -540,6 +557,9 @@ const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) =
updateListOrder(listItemElement.parentElement);
}
if (listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
+ const orderOperations = focusedParentListElement ?
+ getFocusedOrderedListInsertOperations(focusedParentListElement, listItemElement, newElement) :
+ {doOperations: [], undoOperations: []};
listItemElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
transaction(protyle, [{
action: "update",
@@ -550,14 +570,14 @@ const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) =
id: newElement.getAttribute("data-node-id"),
data: newElement.outerHTML,
previousID: listItemElement.getAttribute("data-node-id")
- }], [{
+ }, ...orderOperations.doOperations], [{
action: "delete",
id: newElement.getAttribute("data-node-id"),
}, {
action: "update",
data: listItemHTML,
id: listItemElement.getAttribute("data-node-id")
- }]);
+ }, ...orderOperations.undoOperations]);
} else {
updateTransaction(protyle, listItemElement.parentElement, html);
}
@@ -629,6 +649,9 @@ const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) =
updateListOrder(listItemElement.parentElement);
}
if (listItemElement.parentElement.classList.contains("protyle-wysiwyg")) {
+ const orderOperations = focusedParentListElement ?
+ getFocusedOrderedListInsertOperations(focusedParentListElement, listItemElement, newElement) :
+ {doOperations: [], undoOperations: []};
listItemElement.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
transaction(protyle, [{
action: "update",
@@ -639,14 +662,14 @@ const listEnter = (protyle: IProtyle, blockElement: HTMLElement, range: Range) =
id: newElement.getAttribute("data-node-id"),
data: newElement.outerHTML,
previousID: listItemElement.getAttribute("data-node-id")
- }], [{
+ }, ...orderOperations.doOperations], [{
action: "delete",
id: newElement.getAttribute("data-node-id"),
}, {
action: "update",
id: listItemElement.getAttribute("data-node-id"),
data: listItemHTML
- }]);
+ }, ...orderOperations.undoOperations]);
} else {
updateTransaction(protyle, listItemElement.parentElement, oldHTML);
}
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index cb275fa0d0..655bb4cf47 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -1376,9 +1376,9 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
// 回车
if (matchHotKey("↩", event) ||
(matchHotKey("⇧↩", event) && nodeType === "NodeHeading")) {
- enter(nodeElement, range, protyle);
event.stopPropagation();
event.preventDefault();
+ await enter(nodeElement, range, protyle);
return;
}
@@ -1880,6 +1880,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
if (isListOutdent) {
const selectElements = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");
if (selectElements.length > 0) {
+ event.preventDefault();
+ event.stopPropagation();
let isContinuous = true;
selectElements.forEach((item, index) => {
if (item.nextElementSibling && selectElements[index + 1]) {
@@ -1890,10 +1892,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
});
if (isContinuous &&
(selectElements[0].classList.contains("li") || selectElements[0].parentElement.classList.contains("li"))) {
- listOutdent(protyle, Array.from(selectElements), range);
+ await listOutdent(protyle, Array.from(selectElements), range);
}
- event.preventDefault();
- event.stopPropagation();
return true;
} else if (rangeListItemElements.length > 0) {
event.preventDefault();
@@ -1904,9 +1904,9 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
return true;
} else if (nodeElement.parentElement.classList.contains("li") && nodeType !== "NodeCodeBlock") {
- listOutdent(protyle, [nodeElement.parentElement], range);
event.preventDefault();
event.stopPropagation();
+ await listOutdent(protyle, [nodeElement.parentElement], range);
return true;
}
}
@@ -1914,6 +1914,8 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
if (isListIndent) {
const selectElements = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");
if (selectElements.length > 0) {
+ event.preventDefault();
+ event.stopPropagation();
let isContinuous = true;
selectElements.forEach((item, index) => {
if (item.nextElementSibling && selectElements[index + 1]) {
@@ -1924,23 +1926,21 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
});
if (isContinuous &&
(selectElements[0].classList.contains("li") || selectElements[0].parentElement.classList.contains("li"))) {
- listIndent(protyle, Array.from(selectElements), range);
+ await listIndent(protyle, Array.from(selectElements), range);
}
- event.preventDefault();
- event.stopPropagation();
return true;
} else if (rangeListItemElements.length > 0) {
- listIndent(protyle, rangeListItemElements, range);
+ event.preventDefault();
+ event.stopPropagation();
+ await listIndent(protyle, rangeListItemElements, range);
if (rangeListItemFocusContext) {
restoreFocusContext(protyle, rangeListItemFocusContext);
}
- event.preventDefault();
- event.stopPropagation();
return true;
} else if (nodeElement.parentElement.classList.contains("li") && nodeType !== "NodeCodeBlock") {
- listIndent(protyle, [nodeElement.parentElement], range);
event.preventDefault();
event.stopPropagation();
+ await listIndent(protyle, [nodeElement.parentElement], range);
return true;
}
}
@@ -2047,7 +2047,7 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
});
}
} else if (action === "insertListItem") {
- insertEmptyListItem(protyle, listContext.listItemElement, range);
+ await insertEmptyListItem(protyle, listContext.listItemElement, range);
} else if (action === "convertChildToList") {
turnsIntoOneTransaction({
protyle,
diff --git a/app/src/protyle/wysiwyg/list.ts b/app/src/protyle/wysiwyg/list.ts
index a5a2c36b84..b76dbdf680 100644
--- a/app/src/protyle/wysiwyg/list.ts
+++ b/app/src/protyle/wysiwyg/list.ts
@@ -1,4 +1,4 @@
-import {focusByWbr, getEditorRange, getUndoFocusContext} from "../util/selection";
+import {focusByRange, focusByWbr, getEditorRange, getUndoFocusContext} from "../util/selection";
import {transaction, turnsIntoOneTransaction, updateTransaction} from "./transaction";
import {genEmptyBlock} from "../../block/util";
import * as dayjs from "dayjs";
@@ -14,9 +14,14 @@ import {
getFollowingOrderedListMarkerUpdates,
getLastListItemElement,
getOrderedListMarkerUpdates,
+ getOrderedListMaxStart,
+ parseOrderedListStart,
type TListSubtype
} from "./listContext";
import {fetchSyncPost} from "../../util/fetch";
+import {Dialog} from "../../dialog";
+import {isMobile} from "../../util/functions";
+import {showMessage} from "../../dialog/message";
const getLastChildBlock = (element: Element) => {
if (!element || !element.lastElementChild) {
@@ -64,6 +69,68 @@ export const updateListOrder = (listElement: Element, sIndex?: number) => {
return true;
};
+const getOrderedListItemElements = (listElement: Element) => Array.from(listElement.children).filter((item) =>
+ item.getAttribute("data-type") === "NodeListItem") as HTMLElement[];
+
+export const setOrderedListStart = (protyle: IProtyle, listElement: HTMLElement, start: number) => {
+ if (listElement.getAttribute("data-type") !== "NodeList" ||
+ listElement.getAttribute("data-subtype") !== "o") {
+ return false;
+ }
+ const listItemElements = getOrderedListItemElements(listElement);
+ if (parseOrderedListStart(start.toString(), listItemElements.length) === undefined) {
+ return false;
+ }
+ const oldHTML = listElement.outerHTML;
+ updateListOrder(listElement, start);
+ updateTransaction(protyle, listElement, oldHTML);
+ return true;
+};
+
+export const openOrderedListStartDialog = (protyle: IProtyle, listElement: HTMLElement, range?: Range) => {
+ const listItemElements = getOrderedListItemElements(listElement);
+ const maxStart = getOrderedListMaxStart(listItemElements.length);
+ if (maxStart === undefined) {
+ return;
+ }
+ const initialStart = Number.parseInt(listItemElements[0].getAttribute("data-marker"), 10);
+ const dialog = new Dialog({
+ title: window.siyuan.languages.orderedListStart,
+ content: `<div class="b3-dialog__content"><input class="b3-text-field fn__block" type="number" min="0" max="${maxStart}" step="1"></div>
+<div class="b3-dialog__action">
+ <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>
+ <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button>
+</div>`,
+ width: isMobile() ? "92vw" : "360px",
+ destroyCallback() {
+ if (range?.startContainer?.isConnected) {
+ focusByRange(range);
+ }
+ }
+ });
+ const inputElement = dialog.element.querySelector("input") as HTMLInputElement;
+ const buttonElements = dialog.element.querySelectorAll<HTMLButtonElement>(".b3-button");
+ inputElement.value = Number.isFinite(initialStart) ? Math.trunc(initialStart).toString() : "1";
+ dialog.bindInput(inputElement, () => {
+ buttonElements[1].click();
+ });
+ inputElement.select();
+ buttonElements[0].addEventListener("click", () => {
+ dialog.destroy();
+ });
+ buttonElements[1].addEventListener("click", () => {
+ const start = parseOrderedListStart(inputElement.value, listItemElements.length);
+ if (start === undefined) {
+ showMessage(window.siyuan.languages.invalid, 3000, "error");
+ inputElement.focus();
+ inputElement.select();
+ return;
+ }
+ setOrderedListStart(protyle, listElement, start);
+ dialog.destroy();
+ });
+};
+
export const toggleTaskListItem = (protyle: IProtyle, taskItemElement: Element): void => {
const html = taskItemElement.outerHTML;
const marker = taskItemElement.getAttribute("data-task");
@@ -96,84 +163,152 @@ export const genListItemElement = (listItemElement: Element, offset = 0, wbr = f
return element.content.firstElementChild as HTMLElement;
};
-const getFocusedOrderedListUpdates = async (protyle: IProtyle, listItemElement: HTMLElement) => {
- const doOperations: IOperation[] = [];
- const undoOperations: IOperation[] = [];
- if (listItemElement.getAttribute("data-subtype") !== "o" || !protyle.block.parentID) {
- return {doOperations, undoOperations};
+const getListElementByID = async (protyle: IProtyle, listID: string) => {
+ const response = await fetchSyncPost("/api/block/getBlockDOM", {
+ id: listID,
+ notebook: protyle.notebookId,
+ });
+ const template = document.createElement("template");
+ template.innerHTML = response.data?.dom || "";
+ const listElement = template.content.firstElementChild as HTMLElement;
+ if (listElement?.getAttribute("data-type") !== "NodeList") {
+ return;
}
+ return listElement;
+};
+
+const isFocusedListItemEditor = (protyle: IProtyle, editorElement: Element) =>
+ editorElement.classList.contains("protyle-wysiwyg") &&
+ editorElement.getAttribute("data-doc-type") === "NodeListItem" && !!protyle.block.parentID;
+export const getFocusedParentOrderedList = async (protyle: IProtyle, editorElement: Element) => {
+ if (!isFocusedListItemEditor(protyle, editorElement)) {
+ return;
+ }
try {
- const response = await fetchSyncPost("/api/block/getBlockDOM", {
- id: protyle.block.parentID,
- notebook: protyle.notebookId,
- });
- const template = document.createElement("template");
- template.innerHTML = response.data?.dom || "";
- const listElement = template.content.firstElementChild as HTMLElement;
- if (listElement?.getAttribute("data-type") !== "NodeList" ||
- listElement.getAttribute("data-subtype") !== "o") {
- return {doOperations, undoOperations};
+ const listElement = await getListElementByID(protyle, protyle.block.parentID);
+ if (listElement?.getAttribute("data-subtype") === "o") {
+ return listElement;
}
+ } catch {
+ return;
+ }
+};
- const listItemElements = Array.from(listElement.children).filter((item) =>
- item.getAttribute("data-type") === "NodeListItem") as HTMLElement[];
- const currentIndex = listItemElements.findIndex((item) =>
- item.getAttribute("data-node-id") === listItemElement.getAttribute("data-node-id"));
- if (currentIndex < 0) {
- return {doOperations, undoOperations};
- }
+const getDirectListItemByID = (listElement: Element, id: string) => Array.from(listElement.children).find((item) =>
+ item.getAttribute("data-type") === "NodeListItem" && item.getAttribute("data-node-id") === id) as
+ HTMLElement | undefined;
- const followingElements = listItemElements.slice(currentIndex + 1);
- const markerUpdates = getFollowingOrderedListMarkerUpdates(
- listItemElements[currentIndex].getAttribute("data-marker"),
- followingElements.map((item) => item.getAttribute("data-marker")));
- followingElements.forEach((item, index) => {
- const marker = markerUpdates[index];
- if (!marker) {
- return;
- }
- const id = item.getAttribute("data-node-id");
- undoOperations.push({
- action: "update",
- id,
- data: item.outerHTML,
- });
- item.setAttribute("data-marker", marker);
- const actionElement = item.querySelector(".protyle-action--order");
- if (actionElement) {
- actionElement.textContent = marker;
- }
- doOperations.push({
- action: "update",
- id,
- data: item.outerHTML,
- });
- });
- } catch (error) {
- console.warn("get focused ordered list failed", error);
+const appendFocusedListUpdate = (listElement: HTMLElement, oldHTML: string,
+ doOperations: IOperation[], undoOperations: IOperation[], startIndex?: number) => {
+ updateListOrder(listElement, startIndex);
+ const id = listElement.getAttribute("data-node-id");
+ doOperations.push({
+ action: "update",
+ id,
+ data: listElement.outerHTML,
+ });
+ undoOperations.push({
+ action: "update",
+ id,
+ data: oldHTML,
+ });
+};
+
+export const getFocusedOrderedListInsertOperations = (listElement: HTMLElement, listItemElement: HTMLElement,
+ newListItemElement: HTMLElement) => {
+ const doOperations: IOperation[] = [];
+ const undoOperations: IOperation[] = [];
+ if (listItemElement.getAttribute("data-subtype") !== "o") {
+ return {doOperations, undoOperations};
}
+ const currentElement = getDirectListItemByID(listElement,
+ listItemElement.getAttribute("data-node-id"));
+ if (!currentElement) {
+ return {doOperations, undoOperations};
+ }
+ const oldHTML = listElement.outerHTML;
+ const startIndex = Number.parseInt(getOrderedListItemElements(listElement)[0]?.getAttribute("data-marker"), 10);
+ currentElement.replaceWith(listItemElement.cloneNode(true));
+ const updatedCurrentElement = getDirectListItemByID(listElement,
+ listItemElement.getAttribute("data-node-id"));
+ if (!updatedCurrentElement) {
+ return {doOperations, undoOperations};
+ }
+ updatedCurrentElement.insertAdjacentElement("afterend", newListItemElement.cloneNode(true) as HTMLElement);
+ appendFocusedListUpdate(listElement, oldHTML, doOperations, undoOperations, startIndex);
return {doOperations, undoOperations};
};
-const insertingFocusedListItems = new WeakSet<IProtyle>();
-
-const insertingBoundaryListItems = new WeakSet<IProtyle>();
-
-const getFocusedListElement = async (protyle: IProtyle, listID: string) => {
- const response = await fetchSyncPost("/api/block/getBlockDOM", {
- id: listID,
- notebook: protyle.notebookId,
+const appendFocusedIndentListUpdate = (listElement: HTMLElement, previousElement: HTMLElement,
+ movedElements: Element[], doOperations: IOperation[],
+ undoOperations: IOperation[]) => {
+ const previousID = previousElement.getAttribute("data-node-id");
+ const previousClone = getDirectListItemByID(listElement, previousID);
+ if (!previousClone) {
+ return;
+ }
+ const oldHTML = listElement.outerHTML;
+ const startIndex = Number.parseInt(getOrderedListItemElements(listElement)[0]?.getAttribute("data-marker"), 10);
+ previousClone.replaceWith(previousElement.cloneNode(true));
+ movedElements.forEach((item) => {
+ getDirectListItemByID(listElement, item.getAttribute("data-node-id"))?.remove();
});
- const template = document.createElement("template");
- template.innerHTML = response.data?.dom || "";
- const listElement = template.content.firstElementChild as HTMLElement;
- if (listElement?.getAttribute("data-type") !== "NodeList") {
+ appendFocusedListUpdate(listElement, oldHTML, doOperations, undoOperations, startIndex);
+};
+
+const appendFocusedOutdentListUpdate = (listElement: HTMLElement, parentListItemElement: HTMLElement,
+ movedElements: HTMLElement[], doOperations: IOperation[],
+ undoOperations: IOperation[]) => {
+ const parentClone = getDirectListItemByID(listElement,
+ parentListItemElement.getAttribute("data-node-id"));
+ if (!parentClone) {
return;
}
- return listElement;
+ const oldHTML = listElement.outerHTML;
+ const startIndex = Number.parseInt(getOrderedListItemElements(listElement)[0]?.getAttribute("data-marker"), 10);
+ const referenceElement = parentClone.nextElementSibling;
+ if (parentListItemElement.isConnected) {
+ parentClone.replaceWith(parentListItemElement.cloneNode(true));
+ } else {
+ parentClone.remove();
+ }
+ movedElements.forEach((item) => {
+ listElement.insertBefore(item.cloneNode(true), referenceElement);
+ });
+ updateListOrder(listElement, startIndex);
+ movedElements.forEach((item) => {
+ const updatedElement = getDirectListItemByID(listElement, item.getAttribute("data-node-id"));
+ const marker = updatedElement?.getAttribute("data-marker");
+ if (!marker || marker === item.getAttribute("data-marker")) {
+ return;
+ }
+ undoOperations.push({
+ action: "update",
+ id: item.getAttribute("data-node-id"),
+ data: item.outerHTML,
+ });
+ item.setAttribute("data-marker", marker);
+ const actionElement = item.querySelector(".protyle-action--order");
+ if (actionElement) {
+ actionElement.textContent = marker;
+ }
+ item.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
+ doOperations.push({
+ action: "update",
+ id: item.getAttribute("data-node-id"),
+ data: item.outerHTML,
+ });
+ });
+ appendFocusedListUpdate(listElement, oldHTML, doOperations, undoOperations, startIndex);
};
+const insertingFocusedListItems = new WeakSet<IProtyle>();
+
+const insertingBoundaryListItems = new WeakSet<IProtyle>();
+
+const getFocusedListElement = (protyle: IProtyle, listID: string) => getListElementByID(protyle, listID);
+
const getFocusedListTailItem = async (protyle: IProtyle, listID: string, currentListItem?: HTMLElement) => {
const tailResponse = await fetchSyncPost("/api/block/getTailChildBlocks", {
id: listID,
@@ -276,6 +411,7 @@ export const prependListItem = async (protyle: IProtyle, nodeElement: HTMLElemen
if (!firstListItemElement || !firstID) {
return;
}
+ const oldListHTML = listElement.outerHTML;
let startIndex: number | undefined;
if (firstListItemElement.getAttribute("data-subtype") === "o") {
@@ -303,22 +439,31 @@ export const prependListItem = async (protyle: IProtyle, nodeElement: HTMLElemen
return;
}
const itemID = item.getAttribute("data-node-id");
- undoOperations.push({
- action: "update",
- id: itemID,
- data: item.outerHTML,
- });
+ if (context.listElement) {
+ undoOperations.push({
+ action: "update",
+ id: itemID,
+ data: item.outerHTML,
+ });
+ }
item.setAttribute("data-marker", marker);
const actionElement = item.querySelector(".protyle-action--order");
if (actionElement) {
actionElement.textContent = marker;
}
- doOperations.push({
- action: "update",
- id: itemID,
- data: item.outerHTML,
- });
+ if (context.listElement) {
+ doOperations.push({
+ action: "update",
+ id: itemID,
+ data: item.outerHTML,
+ });
+ }
});
+ if (!context.listElement) {
+ firstListItemElement.insertAdjacentElement("beforebegin",
+ newListItemElement.cloneNode(true) as HTMLElement);
+ appendFocusedListUpdate(listElement, oldListHTML, doOperations, undoOperations, startIndex);
+ }
}
const editorRange = range || getEditorRange(protyle.wysiwyg.element);
@@ -367,7 +512,15 @@ export const insertEmptyListItem = async (protyle: IProtyle, listItemElement: HT
}
insertingFocusedListItems.add(protyle);
try {
- const orderOperations = await getFocusedOrderedListUpdates(protyle, listItemElement);
+ const shouldUpdateParentList = listItemElement.getAttribute("data-subtype") === "o";
+ const parentListElement = shouldUpdateParentList ?
+ await getFocusedParentOrderedList(protyle, listElement) : undefined;
+ if (shouldUpdateParentList && !parentListElement) {
+ return;
+ }
+ const orderOperations = parentListElement ?
+ getFocusedOrderedListInsertOperations(parentListElement, listItemElement, newListItemElement) :
+ {doOperations: [], undoOperations: []};
if (!listItemElement.isConnected) {
return;
}
@@ -498,7 +651,7 @@ export const addSubList = (protyle: IProtyle, nodeElement: Element, range: Range
return true;
};
-export const listIndent = (protyle: IProtyle, liItemElements: Element[], range: Range) => {
+export const listIndent = async (protyle: IProtyle, liItemElements: Element[], range: Range) => {
liItemElements.forEach(item => {
item.removeAttribute("select-start");
item.removeAttribute("select-end");
@@ -515,6 +668,16 @@ export const listIndent = (protyle: IProtyle, liItemElements: Element[], range:
if (!listElement || !previousElement) {
return;
}
+ const shouldUpdateParentList = isFocusedListItemEditor(protyle, listElement) &&
+ liItemElements[0].getAttribute("data-subtype") === "o";
+ const focusedParentListElement = shouldUpdateParentList ?
+ await getFocusedParentOrderedList(protyle, listElement) : undefined;
+ if (shouldUpdateParentList && !focusedParentListElement) {
+ return;
+ }
+ if (!previousElement.isConnected || liItemElements.some((item) => !item.isConnected)) {
+ return;
+ }
range.collapse(false);
range.insertNode(document.createElement("wbr"));
const html = listElement.outerHTML;
@@ -586,6 +749,10 @@ export const listIndent = (protyle: IProtyle, liItemElements: Element[], range:
data: previousLastListHTML,
id: newLastPreviousElement.getAttribute("data-node-id")
});
+ if (focusedParentListElement) {
+ appendFocusedIndentListUpdate(focusedParentListElement, previousElement as HTMLElement,
+ liItemElements, doOperations, undoOperations);
+ }
transaction(protyle, doOperations, undoOperations);
}
} else {
@@ -679,6 +846,10 @@ export const listIndent = (protyle: IProtyle, liItemElements: Element[], range:
const foldOperations = setFold(protyle, foldElement, true, false, false, true);
doOperations.push(...foldOperations.doOperations);
undoOperations.push(...foldOperations.undoOperations);
+ if (focusedParentListElement) {
+ appendFocusedIndentListUpdate(focusedParentListElement, previousElement as HTMLElement,
+ liItemElements, doOperations, undoOperations);
+ }
transaction(protyle, doOperations, undoOperations);
focusByWbr(protyle.wysiwyg.element, range);
return;
@@ -698,6 +869,10 @@ export const listIndent = (protyle: IProtyle, liItemElements: Element[], range:
data: previousHTML,
id: previousElement.getAttribute("data-node-id")
});
+ if (focusedParentListElement) {
+ appendFocusedIndentListUpdate(focusedParentListElement, previousElement as HTMLElement,
+ liItemElements, doOperations, undoOperations);
+ }
transaction(protyle, doOperations, undoOperations);
}
}
@@ -851,6 +1026,18 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],
// https://ld246.com/article/1691981936960 情况下 zoom in 列表项
return;
}
+ const shouldUpdateParentList = isFocusedListItemEditor(protyle, parentParentElement) &&
+ parentLiItemElement.getAttribute("data-subtype") === "o";
+ const focusedParentListElement = shouldUpdateParentList ?
+ await getFocusedParentOrderedList(protyle, parentParentElement) : undefined;
+ if (shouldUpdateParentList && !focusedParentListElement) {
+ return;
+ }
+ if (!liElement.isConnected || !parentLiItemElement.isConnected ||
+ liItemElements.some((item) => !item.isConnected)) {
+ return;
+ }
+ const movedListItemElements = [...liItemElements] as HTMLElement[];
if (parentLiItemElement.classList.contains("protyle-wysiwyg") || parentLiItemElement.classList.contains("sb") ||
parentLiItemElement.classList.contains("bq") || parentLiItemElement.classList.contains("callout")) {
// 顶层列表
@@ -1268,6 +1455,10 @@ export const listOutdent = async (protyle: IProtyle, liItemElements: Element[],
});
}
if (parentParentElement.classList.contains("protyle-wysiwyg")) {
+ if (focusedParentListElement) {
+ appendFocusedOutdentListUpdate(focusedParentListElement, parentLiItemElement as HTMLElement,
+ movedListItemElements, doOperations, undoOperations);
+ }
transaction(protyle, doOperations, undoOperations);
} else {
if (parentLiItemElement && parentLiItemElement.getAttribute("data-subtype") === "o") {
diff --git a/app/src/protyle/wysiwyg/listContext.test.ts b/app/src/protyle/wysiwyg/listContext.test.ts
index 4e9d16dccb..03a34ade9f 100644
--- a/app/src/protyle/wysiwyg/listContext.test.ts
+++ b/app/src/protyle/wysiwyg/listContext.test.ts
@@ -8,7 +8,9 @@ import {
getListContext,
getListConversionType,
getOrderedListMarkerUpdates,
+ getOrderedListMaxStart,
getListShortcutAction,
+ parseOrderedListStart,
shouldIgnoreListShortcut,
type TListSubtype
} from "./listContext";
@@ -263,10 +265,41 @@ describe("getOrderedListMarkerUpdates", () => {
assert.deepEqual(getOrderedListMarkerUpdates(["1.", "2."], 0), ["0.", "1."]);
});
+ it("preserves an explicit custom start when the original first item is removed", () => {
+ assert.deepEqual(getOrderedListMarkerUpdates(["1.", "12.", "13."], 10), ["10.", "11.", "12."]);
+ });
+
it("replaces invalid markers instead of producing NaN", () => {
assert.deepEqual(getOrderedListMarkerUpdates(["NaN.", "NaN."]), ["1.", "2."]);
assert.deepEqual(getOrderedListMarkerUpdates(["2.", "3."], Number.NaN), ["1.", "2."]);
});
+
+ it("renumbers the complete parent list after focused list edits", () => {
+ assert.deepEqual(getOrderedListMarkerUpdates(["10.", "11.", "12.", "12.", "13.", "14.", "15."]),
+ [undefined, undefined, undefined, "13.", "14.", "15.", "16."]);
+ assert.deepEqual(getOrderedListMarkerUpdates(["10.", "11.", "13.", "14.", "15.", "16."]),
+ [undefined, undefined, "12.", "13.", "14.", "15."]);
+ assert.deepEqual(getOrderedListMarkerUpdates(["10.", "11.", "1.", "12.", "13.", "14.", "15."]),
+ [undefined, undefined, "12.", "13.", "14.", "15.", "16."]);
+ });
+});
+
+describe("parseOrderedListStart", () => {
+ it("accepts non-negative integers within the list range", () => {
+ assert.equal(parseOrderedListStart("0", 3), 0);
+ assert.equal(parseOrderedListStart("0005", 3), 5);
+ assert.equal(parseOrderedListStart("999999997", 3), 999999997);
+ assert.equal(getOrderedListMaxStart(3), 999999997);
+ });
+
+ it("rejects malformed and overflowing values", () => {
+ assert.equal(parseOrderedListStart("-1", 3), undefined);
+ assert.equal(parseOrderedListStart("1.5", 3), undefined);
+ assert.equal(parseOrderedListStart("1x", 3), undefined);
+ assert.equal(parseOrderedListStart("999999998", 3), undefined);
+ assert.equal(parseOrderedListStart("1000000000", 1), undefined);
+ assert.equal(parseOrderedListStart("1", 0), undefined);
+ });
});
describe("shouldIgnoreListShortcut", () => {
diff --git a/app/src/protyle/wysiwyg/listContext.ts b/app/src/protyle/wysiwyg/listContext.ts
index c2ea4a87aa..502428f09f 100644
--- a/app/src/protyle/wysiwyg/listContext.ts
+++ b/app/src/protyle/wysiwyg/listContext.ts
@@ -17,6 +17,8 @@ export type TAppendListContext = {
listItemElement?: HTMLElement,
};
+export const ORDERED_LIST_MAX_NUMBER = 999999999;
+
const LIST_CONVERSION_TYPES: Record<TListSubtype, Partial<Record<TListSubtype, string>>> = {
u: {o: "UL2OL", t: "UL2TL"},
o: {u: "OL2UL", t: "OL2TL"},
@@ -131,6 +133,25 @@ export const getOrderedListMarkerUpdates = (markers: string[], startIndex?: numb
});
};
+export const getOrderedListMaxStart = (itemCount: number) => {
+ if (!Number.isInteger(itemCount) || itemCount < 1 || itemCount > ORDERED_LIST_MAX_NUMBER) {
+ return;
+ }
+ return ORDERED_LIST_MAX_NUMBER - itemCount + 1;
+};
+
+export const parseOrderedListStart = (value: string, itemCount: number) => {
+ const maxStart = getOrderedListMaxStart(itemCount);
+ if (maxStart === undefined || !/^\d{1,9}$/.test(value)) {
+ return;
+ }
+ const start = Number(value);
+ if (!Number.isSafeInteger(start) || start > maxStart) {
+ return;
+ }
+ return start;
+};
+
export const shouldIgnoreListShortcut = (hasBlockSelection: boolean, selectedType?: string) => {
return hasBlockSelection && selectedType === "NodeListItem";
};
diff --git a/app/src/protyle/wysiwyg/remove.ts b/app/src/protyle/wysiwyg/remove.ts
index 2a51eb825c..28c1c60402 100644
--- a/app/src/protyle/wysiwyg/remove.ts
+++ b/app/src/protyle/wysiwyg/remove.ts
@@ -1498,7 +1498,7 @@ const confirmRefRemoval = async (protyle: IProtyle, ids: string[], elements: Ele
const removeLi = async (protyle: IProtyle, blockElement: Element, range: Range, isDelete = false) => {
if (!blockElement.parentElement.previousElementSibling && blockElement.parentElement.nextElementSibling && blockElement.parentElement.nextElementSibling.classList.contains("protyle-attr")) {
- listOutdent(protyle, [blockElement.parentElement], range, isDelete, blockElement);
+ await listOutdent(protyle, [blockElement.parentElement], range, isDelete, blockElement);
return;
}
// 第一个子列表合并到上一个块的末尾
diff --git a/kernel/api/block.go b/kernel/api/block.go
index fb9cc2c96f..86a5e5e5c7 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -1349,6 +1349,33 @@ func getBlockDOM(c *gin.Context) {
}
}
+func getOrderedListContinueStart(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var id string
+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) {
+ return
+ }
+ if util.InvalidIDPattern(id, ret) {
+ return
+ }
+ boxID := encryptedNotebookFromArg(arg)
+ if !holdBlockRequest(c, ret, boxID) {
+ return
+ }
+ start, found := model.GetOrderedListContinueStartInBox(id, boxID)
+ ret.Data = map[string]any{
+ "start": start,
+ "found": found,
+ }
+}
+
func getBlockDOMs(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
diff --git a/kernel/api/router.go b/kernel/api/router.go
index b3f775016c..5313d29c37 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -242,6 +242,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/block/getBlockInfo", model.CheckAuth, getBlockInfo)
ginServer.Handle("POST", "/api/block/getBlockDOM", model.CheckAuth, getBlockDOM)
+ ginServer.Handle("POST", "/api/block/getOrderedListContinueStart", model.CheckAuth, model.CheckAdminRole, getOrderedListContinueStart)
ginServer.Handle("POST", "/api/block/getBlockDOMs", model.CheckAuth, getBlockDOMs)
ginServer.Handle("POST", "/api/block/getBlockDOMWithEmbed", model.CheckAuth, getBlockDOMWithEmbed)
ginServer.Handle("POST", "/api/block/getBlockDOMsWithEmbed", model.CheckAuth, getBlockDOMsWithEmbed)
diff --git a/kernel/model/block.go b/kernel/model/block.go
index eeb98b1edd..c2b794641f 100644
--- a/kernel/model/block.go
+++ b/kernel/model/block.go
@@ -1531,6 +1531,51 @@ type ChildBlock struct {
Markdown string `json:"markdown,omitempty"`
}
+const maxOrderedListNumber = 999999999
+
+// GetOrderedListContinueStartInBox 返回同一父级中最近前置有序列表的续编起始编号。
+func GetOrderedListContinueStartInBox(id, boxID string) (start int, found bool) {
+ tree := loadTreeForBlockDOM(id, boxID)
+ if nil == tree {
+ return
+ }
+ return getOrderedListContinueStartFromTree(id, tree)
+}
+
+func getOrderedListContinueStartFromTree(id string, tree *parse.Tree) (start int, found bool) {
+ node := treenode.GetNodeInTree(tree, id)
+ if nil == node || ast.NodeList != node.Type || nil == node.ListData || 1 != node.ListData.Typ {
+ return
+ }
+
+ itemCount := 0
+ for item := node.FirstChild; nil != item; item = item.Next {
+ if ast.NodeListItem == item.Type {
+ itemCount++
+ }
+ }
+ if 1 > itemCount {
+ return
+ }
+
+ for previous := node.Previous; nil != previous; previous = previous.Previous {
+ if ast.NodeList != previous.Type || nil == previous.ListData || 1 != previous.ListData.Typ {
+ continue
+ }
+ for item := previous.LastChild; nil != item; item = item.Previous {
+ if ast.NodeListItem != item.Type || nil == item.ListData {
+ continue
+ }
+ if 0 > item.ListData.Num || item.ListData.Num > maxOrderedListNumber-itemCount {
+ return
+ }
+ return item.ListData.Num + 1, true
+ }
+ return
+ }
+ return
+}
+
func GetChildBlocks(id string) (ret []*ChildBlock) {
return GetChildBlocksInBox(id, "")
}
diff --git a/kernel/model/block_child_test.go b/kernel/model/block_child_test.go
index c93120c2bc..622fb47642 100644
--- a/kernel/model/block_child_test.go
+++ b/kernel/model/block_child_test.go
@@ -71,3 +71,46 @@ func TestHeadingChildBlocksSkipSuperBlockCloseMarker(t *testing.T) {
t.Fatalf("unexpected heading child IDs: [%v]", ids)
}
}
+
+func TestGetOrderedListContinueStartFromTree(t *testing.T) {
+ newList := func(id string, numbers ...int) *ast.Node {
+ list := &ast.Node{Type: ast.NodeList, ID: id, ListData: &ast.ListData{Typ: 1}}
+ for _, number := range numbers {
+ list.AppendChild(&ast.Node{Type: ast.NodeListItem, ID: id + "-item", ListData: &ast.ListData{Typ: 1, Num: number}})
+ }
+ return list
+ }
+
+ root := &ast.Node{Type: ast.NodeDocument, ID: "root"}
+ previousList := newList("previous", 6, 7)
+ root.AppendChild(previousList)
+ root.AppendChild(&ast.Node{Type: ast.NodeList, ID: "unordered", ListData: &ast.ListData{Typ: 0}})
+ root.AppendChild(&ast.Node{Type: ast.NodeParagraph, ID: "paragraph"})
+ currentList := newList("current", 1, 2, 3)
+ root.AppendChild(currentList)
+ tree := &parse.Tree{Root: root, ID: root.ID}
+
+ start, found := getOrderedListContinueStartFromTree(currentList.ID, tree)
+ if !found || 8 != start {
+ t.Fatalf("unexpected continue start: [%d, %v]", start, found)
+ }
+
+ innerCurrent := newList("inner-current", 1)
+ previousList.FirstChild.AppendChild(innerCurrent)
+ if _, found = getOrderedListContinueStartFromTree(innerCurrent.ID, tree); found {
+ t.Fatal("expected list numbering not to continue across parent boundaries")
+ }
+
+ if _, found = getOrderedListContinueStartFromTree(previousList.FirstChild.ID, tree); found {
+ t.Fatal("expected a list item to be rejected")
+ }
+
+ overflowRoot := &ast.Node{Type: ast.NodeDocument, ID: "overflow-root"}
+ overflowRoot.AppendChild(newList("overflow-previous", maxOrderedListNumber))
+ overflowCurrent := newList("overflow-current", 1)
+ overflowRoot.AppendChild(overflowCurrent)
+ overflowTree := &parse.Tree{Root: overflowRoot, ID: overflowRoot.ID}
+ if _, found = getOrderedListContinueStartFromTree(overflowCurrent.ID, overflowTree); found {
+ t.Fatal("expected overflowing list numbering to be unavailable")
+ }
+}