Skip to content

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

:bug: Align list controls with automatic text direction https://github.com/siyuan-note/siyuan/issues/19915

Daniel6134f296030b
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
index ca1cce6f2d..4578424349 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-h361q1i/20200924093441-ft2rhps.sy
@@ -8,7 +8,7 @@
"title": "Formatting elements",
"title-img": "background-color:#269;background-image: linear-gradient(white 2px, transparent 2px),linear-gradient(90deg, white 2px, transparent 2px),linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px),linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px);background-size: 100px 100px, 100px 100px, 20px 20px, 20px 20px;background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;",
"type": "doc",
- "updated": "20260928143000"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5371,7 +5371,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260928090424-voiqqta",
- "updated": "20260928090424"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5403,7 +5403,7 @@
},
{
"Type": "NodeText",
- "Data": " below Right to Left (RTL). This option is off by default. Paragraphs and headings use their first strong directional character to choose RTL or LTR; numbers, punctuation, and emoji at the beginning do not decide the direction. Manual block and inline directions take priority. List marker positions and table column order keep their existing settings. Preview and HTML/PDF export also use automatic text direction."
+ "Data": " below Right to Left (RTL). This option is off by default. Paragraphs and headings use their first strong directional character to choose RTL or LTR; numbers, punctuation, and emoji at the beginning do not decide the direction. Manual block and inline directions take priority. Each list item, including nested items, independently follows the direction of its own first text block: checkboxes, bullets, numbers, and indentation move to the corresponding side. Manual list directions take priority. Table column order keeps its existing setting. Preview and HTML/PDF export also use automatic text direction."
}
]
}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
index e9877f7180..73e4ef0198 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180320-abz7w6k/20200825162036-4dx365o.sy
@@ -8,7 +8,7 @@
"title": "排版元素",
"title-img": "background-color: hsl(2, 57%, 40%);background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(270deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(125deg, transparent, transparent 2px, rgba(0,0,0,.2) 2px, rgba(0,0,0,.2) 3px, transparent 3px, transparent 5px, rgba(0,0,0,.2) 5px);",
"type": "doc",
- "updated": "20260928143000"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5373,7 +5373,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260928090424-i3j9suz",
- "updated": "20260928090424"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5405,7 +5405,7 @@
},
{
"Type": "NodeText",
- "Data": " 中启用该功能,开关位于「从右到左(RTL)」下方,默认关闭。段落和标题根据首个具有强方向性的字符自动选择从右到左或从左到右,开头的数字、标点和表情不决定方向。手动设置的块级和行内方向优先。列表标记位置和表格列顺序保持原有设置。预览及 HTML、PDF 导出也会应用自动文本方向。"
+ "Data": " 中启用该功能,开关位于「从右到左(RTL)」下方,默认关闭。段落和标题根据首个具有强方向性的字符自动选择从右到左或从左到右,开头的数字、标点和表情不决定方向。手动设置的块级和行内方向优先。各列表项(包括子列表项)独立跟随自身首个正文块的方向,复选框、项目符号、编号和缩进同步调整到对应一侧,手动设置的列表方向优先。表格列顺序保持原有设置。预览及 HTML、PDF 导出也会应用自动文本方向。"
}
]
}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
index 8fb3026f71..1325644741 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226120854-dr1jfx2/20211226121319-emrk2yy.sy
@@ -8,7 +8,7 @@
"title": "排版元素",
"title-img": "background-color: hsl(2, 57%, 40%);background-image: repeating-linear-gradient(transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(270deg, transparent, transparent 50px, rgba(0,0,0,.4) 50px, rgba(0,0,0,.4) 53px, transparent 53px, transparent 63px, rgba(0,0,0,.4) 63px, rgba(0,0,0,.4) 66px, transparent 66px, transparent 116px, rgba(0,0,0,.5) 116px, rgba(0,0,0,.5) 166px, rgba(255,255,255,.2) 166px, rgba(255,255,255,.2) 169px, rgba(0,0,0,.5) 169px, rgba(0,0,0,.5) 179px, rgba(255,255,255,.2) 179px, rgba(255,255,255,.2) 182px, rgba(0,0,0,.5) 182px, rgba(0,0,0,.5) 232px, transparent 232px),repeating-linear-gradient(125deg, transparent, transparent 2px, rgba(0,0,0,.2) 2px, rgba(0,0,0,.2) 3px, transparent 3px, transparent 5px, rgba(0,0,0,.2) 5px);",
"type": "doc",
- "updated": "20260928143000"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5349,7 +5349,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260928090424-testof8",
- "updated": "20260928090424"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5381,7 +5381,7 @@
},
{
"Type": "NodeText",
- "Data": " 中啟用此功能,開關位於「從右到左(RTL)」下方,預設關閉。段落和標題根據首個具有強方向性的字元自動選擇從右到左或從左到右,開頭的數字、標點和表情不決定方向。手動設定的區塊層級和行內方向優先。清單標記位置和表格欄位順序維持原有設定。預覽及 HTML、PDF 匯出也會套用自動文字方向。"
+ "Data": " 中啟用此功能,開關位於「從右到左(RTL)」下方,預設關閉。段落和標題根據首個具有強方向性的字元自動選擇從右到左或從左到右,開頭的數字、標點和表情不決定方向。手動設定的區塊層級和行內方向優先。各清單項目(包含子清單項目)獨立跟隨自身首個正文區塊的方向,覈取方塊、項目符號、編號及縮排同步調整到對應一側,手動設定的清單方向優先。表格欄位順序維持原有設定。預覽及 HTML、PDF 匯出也會套用自動文字方向。"
}
]
}
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
index 36c829f30d..4f55bc1fc5 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-hnu6o79/20240530101000-3qhz7br.sy
@@ -9,7 +9,7 @@
"title": "書式要素",
"title-img": "background-color:#269;background-image: linear-gradient(white 2px, transparent 2px),linear-gradient(90deg, white 2px, transparent 2px),linear-gradient(rgba(255,255,255,.3) 1px, transparent 1px),linear-gradient(90deg, rgba(255,255,255,.3) 1px, transparent 1px);background-size: 100px 100px, 100px 100px, 20px 20px, 20px 20px;background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;",
"type": "doc",
- "updated": "20260928143000"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5609,7 +5609,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260928090424-8to4vwd",
- "updated": "20260928090424"
+ "updated": "20260929221400"
},
"Children": [
{
@@ -5641,7 +5641,7 @@
},
{
"Type": "NodeText",
- "Data": " で有効にできます。スイッチは「右から左へ(RTL)」の下にあり、初期状態では無効です。段落と見出しの最初の強い方向性を持つ文字に基づいて、右から左または左から右を自動判定します。先頭の数字、句読点、絵文字は方向を決定しません。手動で指定したブロック単位とインラインの方向が優先されます。リスト記号の位置と表の列順序は従来の設定を維持します。プレビューおよび HTML・PDF エクスポートにも自動判定が適用されます。"
+ "Data": " で有効にできます。スイッチは「右から左へ(RTL)」の下にあり、初期状態では無効です。段落と見出しの最初の強い方向性を持つ文字に基づいて、右から左または左から右を自動判定します。先頭の数字、句読点、絵文字は方向を決定しません。手動で指定したブロック単位とインラインの方向が優先されます。入れ子の項目を含む各リスト項目は、自身の最初の本文ブロックの方向に個別に従います。チェックボックス、箇条書き記号、番号、インデントも対応する側に移動し、手動で指定したリストの方向が優先されます。表の列順序は従来の設定を維持します。プレビューおよび HTML・PDF エクスポートにも自動判定が適用されます。"
}
]
}
diff --git a/app/src/assets/scss/component/_typography.scss b/app/src/assets/scss/component/_typography.scss
index d78ae2bea6..57f0dc8991 100644
--- a/app/src/assets/scss/component/_typography.scss
+++ b/app/src/assets/scss/component/_typography.scss
@@ -750,6 +750,22 @@
ol {
padding: revert-layer;
margin: 4px 0;
+
+ &[data-auto-direction="list"] {
+ padding-left: 0;
+ padding-right: 0;
+
+ & > li {
+ margin-left: 2em;
+ margin-right: 0;
+ }
+
+ & > li[data-auto-list-direction="rtl"],
+ & > li[dir="rtl"] {
+ margin-left: 0;
+ margin-right: 2em;
+ }
+ }
}
hr {
diff --git a/app/src/assets/scss/protyle/_content.scss b/app/src/assets/scss/protyle/_content.scss
index ee532da86f..7d42d64bb5 100644
--- a/app/src/assets/scss/protyle/_content.scss
+++ b/app/src/assets/scss/protyle/_content.scss
@@ -17,18 +17,18 @@
direction: rtl
}
- .protyle-wysiwyg [data-node-id].li > .protyle-action {
+ .protyle-wysiwyg [data-node-id].li:not([data-auto-direction]) > .protyle-action {
right: 0;
left: auto;
direction: rtl;
}
- .protyle-wysiwyg [data-node-id].li > [data-node-id] {
+ .protyle-wysiwyg [data-node-id].li:not([data-auto-direction]) > [data-node-id] {
margin-right: 34px;
margin-left: 0;
}
- .protyle-wysiwyg [data-node-id].li::before {
+ .protyle-wysiwyg [data-node-id].li:not([data-auto-direction])::before {
right: 17px;
left: auto;
}
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scss
index d7398c1636..a5df484121 100644
--- a/app/src/assets/scss/protyle/_wysiwyg.scss
+++ b/app/src/assets/scss/protyle/_wysiwyg.scss
@@ -315,21 +315,21 @@
}
&[style*="direction: rtl"] {
- .li > .protyle-action,
- & > .protyle-action {
+ .li:not([data-auto-direction]) > .protyle-action,
+ &:not([data-auto-direction]) > .protyle-action {
right: 0;
left: auto;
direction: rtl;
}
- .li > :is([data-node-id], [data-table-cell-node]),
- & > :is([data-node-id], [data-table-cell-node]) {
+ .li:not([data-auto-direction]) > :is([data-node-id], [data-table-cell-node]),
+ &:not([data-auto-direction]) > :is([data-node-id], [data-table-cell-node]) {
margin-right: 34px;
margin-left: 0;
}
- .li::before,
- &::before {
+ .li:not([data-auto-direction])::before,
+ &:not([data-auto-direction])::before {
right: 17px;
left: auto;
}
@@ -352,6 +352,51 @@
}
}
+ &.li[data-auto-direction] {
+ & > .protyle-action {
+ left: auto;
+ right: auto;
+ inset-inline-start: 0;
+ direction: inherit;
+ }
+
+ & > :is([data-node-id], [data-table-cell-node]) {
+ margin-left: 34px;
+ margin-right: 0;
+ }
+
+ &[data-auto-list-direction="rtl"] > :is([data-node-id], [data-table-cell-node]) {
+ margin-left: 0;
+ margin-right: 34px;
+ }
+
+ &::before {
+ left: auto;
+ right: auto;
+ inset-inline-start: 17px;
+ }
+
+ &:is(.dragover__top--sibling, .dragover__bottom--sibling, .dragover__top--child, .dragover__bottom--child) {
+ &::before {
+ left: auto;
+ right: auto;
+ inset-inline-start: calc(var(--drag-indent) / 2);
+ transform: translateX(-50%);
+ }
+
+ &[data-auto-list-direction="rtl"]::before {
+ transform: translateX(50%);
+ }
+
+ &::after {
+ left: auto;
+ right: auto;
+ inset-inline-start: var(--drag-line-left);
+ inset-inline-end: 0;
+ }
+ }
+ }
+
&.dragover__top--sibling::before,
&.dragover__bottom--sibling::before,
&.dragover__top--child::before,
diff --git a/app/src/protyle/gutter/index.ts b/app/src/protyle/gutter/index.ts
index 237d3f5a10..50b9550e12 100644
--- a/app/src/protyle/gutter/index.ts
+++ b/app/src/protyle/gutter/index.ts
@@ -124,6 +124,7 @@ import {
import {applyHeadingLevelUpdates, getHeadingLevelUpdateOperations} from "../util/headingTransform";
import {getEmbedHeadingLevel, isHeadingEmbed, renderEmbedHeadings} from "../render/embedHeading";
import {getBlockSelectionModeElement} from "../wysiwyg/blockSelection";
+import {getAutoListDirection} from "../render/autoDirection";
import {
getBacklinkGutterContentTop,
getContainerGutterSpace,
@@ -3922,7 +3923,9 @@ data-type="fold"${viewOccurrenceID ? ` data-view-occurrence-id="${encodeURICompo
// 脑图中的原始列表项已隐藏,使用可见面板定位列表块标。
let rect = (mindmapElement || element).getBoundingClientRect();
let marginHeight = 0;
- const isRTL = window.siyuan.config.editor.rtl || getComputedStyle(element).direction === "rtl";
+ const autoListDirection = getAutoListDirection(element);
+ const isRTL = autoListDirection ? autoListDirection === "rtl" :
+ window.siyuan.config.editor.rtl || getComputedStyle(element).direction === "rtl";
if (mindmapElement) {
space = 0;
} else if (listItem && !isRTL) {
diff --git a/app/src/protyle/render/autoDirection.ts b/app/src/protyle/render/autoDirection.ts
index fb3ba6ba4d..4f1664af90 100644
--- a/app/src/protyle/render/autoDirection.ts
+++ b/app/src/protyle/render/autoDirection.ts
@@ -4,6 +4,14 @@ const excludedSelector = 'pre, code, .render-node, [data-type="NodeCodeBlock"],
'[data-type="NodeMathBlock"], [data-type="NodeHTMLBlock"], [data-type="NodeAttributeView"], protyle-html';
const disposers = new WeakMap<HTMLElement, () => void>();
const directionAttribute = "data-auto-direction";
+const listDirectionAttribute = "data-auto-list-direction";
+const listSelector = '[data-type="NodeListItem"], li';
+
+/** 列表控件按当前项的方向定位,不继承全局开关对其他列表项的判断。 */
+export const getAutoListDirection = (element: Element) => {
+ const item = element.closest<HTMLElement>(listSelector);
+ return item?.hasAttribute(directionAttribute) ? getComputedStyle(item).direction : undefined;
+};
/** 文档标题使用浏览器的实时方向判定,保留显式指定的方向。 */
export const setTitleAutoDirection = (element: HTMLElement, enabled: boolean) => {
@@ -22,6 +30,7 @@ const clearDirection = (element: HTMLElement) => {
element.removeAttribute("dir");
}
element.removeAttribute(directionAttribute);
+ element.removeAttribute(listDirectionAttribute);
};
export const destroyAutoDirection = (root: HTMLElement) => {
@@ -29,10 +38,19 @@ export const destroyAutoDirection = (root: HTMLElement) => {
disposers.delete(root);
};
-/** 自动方向只作用于正文,不改变容器布局或持久化手动方向。 */
+/** 自动方向用于正文和各列表项的布局,不持久化推导出的方向。 */
export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
destroyAutoDirection(root);
const managed = new Set<HTMLElement>();
+ const applyDirection = (element: HTMLElement, direction: string) => {
+ managed.add(element);
+ if (element.getAttribute(directionAttribute) !== direction) {
+ element.setAttribute(directionAttribute, direction);
+ }
+ if (element.dir !== direction) {
+ element.dir = direction;
+ }
+ };
const getExplicitDirection = (element: HTMLElement) => {
for (let current = element; current; current = current.parentElement) {
if (current.style.direction) {
@@ -48,6 +66,44 @@ export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
}
return "auto";
};
+ const updateList = (item: HTMLElement) => {
+ if (!root.contains(item)) {
+ return;
+ }
+ if (item.closest(excludedSelector)) {
+ clearDirection(item);
+ managed.delete(item);
+ return;
+ }
+ if (item.tagName === "LI" && item.parentElement?.matches("ul, ol")) {
+ const list = item.parentElement;
+ managed.add(list);
+ if (list.getAttribute(directionAttribute) !== "list") {
+ list.setAttribute(directionAttribute, "list");
+ }
+ }
+ if (item.dir && item.dir !== "auto" && item.dir !== item.getAttribute(directionAttribute)) {
+ item.removeAttribute(directionAttribute);
+ item.removeAttribute(listDirectionAttribute);
+ managed.delete(item);
+ return;
+ }
+ let direction = getExplicitDirection(item);
+ if (direction === "auto") {
+ // 只读取本项的首个正文区域,避免子列表文字或任务图标决定父项方向。
+ const content = Array.from(item.children).find(child =>
+ !child.matches('.protyle-action, .protyle-attr, [data-type="NodeList"], ul, ol, input'));
+ const text = content?.matches(textSelector) ? content : content?.querySelector<HTMLElement>(textSelector);
+ if (text && text.closest(listSelector) === item) {
+ direction = getComputedStyle(text).direction;
+ }
+ }
+ applyDirection(item, direction);
+ const layoutDirection = direction === "auto" ? getComputedStyle(item).direction : direction;
+ if (item.getAttribute(listDirectionAttribute) !== layoutDirection) {
+ item.setAttribute(listDirectionAttribute, layoutDirection);
+ }
+ };
const update = (scope: HTMLElement) => {
if (!enabled) {
scope.querySelectorAll<HTMLElement>(`[${directionAttribute}]`).forEach(clearDirection);
@@ -67,28 +123,36 @@ export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
managed.delete(element);
} else if (!element.dir || element.dir === "auto" ||
element.dir === element.getAttribute(directionAttribute)) {
- managed.add(element);
const direction = getExplicitDirection(element);
- if (element.getAttribute(directionAttribute) !== direction) {
- element.setAttribute(directionAttribute, direction);
- }
- if (element.dir !== direction) {
- element.dir = direction;
- }
+ applyDirection(element, direction);
} else {
element.removeAttribute(directionAttribute);
managed.delete(element);
}
});
+ // 先更新子项,原生 HTML 列表的自动判定即可跳过具有独立方向的子列表项。
+ const items = Array.from(scope.querySelectorAll<HTMLElement>(listSelector)).reverse();
+ const owner = scope.closest<HTMLElement>(listSelector);
+ if (owner) {
+ items.push(owner);
+ }
+ items.forEach(updateList);
};
update(root);
- // 浏览器负责随正文变化重新判定方向,只监听结构和手动样式变化。
+ // 浏览器判定文字方向,内容变化时只同步受影响列表项的布局。
const observer = new MutationObserver(records => {
const scopes = new Set<HTMLElement>();
records.forEach(record => {
- if (record.type === "attributes") {
+ if (record.type === "characterData") {
+ if (record.target.parentElement?.closest(listSelector)) {
+ scopes.add(record.target.parentElement);
+ }
+ } else if (record.type === "attributes") {
scopes.add(record.target as HTMLElement);
} else {
+ if ((record.target as HTMLElement).closest(listSelector)) {
+ scopes.add(record.target as HTMLElement);
+ }
record.addedNodes.forEach(node => {
if (node.nodeType === 1) {
scopes.add(node as HTMLElement);
@@ -111,7 +175,7 @@ export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
scopes.forEach(update);
});
observer.observe(root, {subtree: true, childList: true, ...(enabled ? {
- attributes: true, attributeFilter: ["style", "dir", "contenteditable", "data-type"],
+ characterData: true, attributes: true, attributeFilter: ["style", "dir", "contenteditable", "data-type"],
} : {})});
disposers.set(root, () => {
observer.disconnect();
diff --git a/app/src/protyle/util/listDragTarget.ts b/app/src/protyle/util/listDragTarget.ts
index 0ab9ce3ad9..0a3186954b 100644
--- a/app/src/protyle/util/listDragTarget.ts
+++ b/app/src/protyle/util/listDragTarget.ts
@@ -8,28 +8,39 @@ export const cleanupDragIndicators = (scope: ParentNode) => {
};
export const createListDragTarget = () => {
- let dragCache: {node: HTMLElement, indent: number, rgb: {r: number, g: number, b: number}, guides: string};
+ let dragCache: {node: HTMLElement, rtl: boolean, indent: number, rgb: {r: number, g: number, b: number}, guides: string};
return (htmlTarget: HTMLElement, event: Pick<DragEvent, "clientX" | "clientY">) => {
const node = htmlTarget;
- if (!dragCache || dragCache.node !== node) {
+ const isRTL = getComputedStyle(htmlTarget).direction === "rtl";
+ if (!dragCache || dragCache.node !== node || dragCache.rtl !== isRTL) {
const contentBlock = Array.from(htmlTarget.children).find(c => (c.hasAttribute("data-node-id") || c.hasAttribute("data-table-cell-node"))) as HTMLElement;
- const indent = contentBlock ? parseFloat(getComputedStyle(contentBlock).marginLeft) || 34 : 34;
+ const indent = contentBlock ? parseFloat(getComputedStyle(contentBlock)[isRTL ? "marginRight" : "marginLeft"]) || 34 : 34;
const depth = getListDepth(htmlTarget);
const computedColor = getComputedStyle(htmlTarget).getPropertyValue("--b3-theme-primary-lighter").trim();
const rgb = parseHexColor(computedColor) || {r: 53, g: 115, b: 217};
let siblingGuides = "";
+ let ancestor = htmlTarget.parentElement?.closest<HTMLElement>(".li");
+ const rect = htmlTarget.getBoundingClientRect();
+ const anchor = isRTL ? rect.right - indent / 2 : rect.left + indent / 2;
for (let n = 1; n <= depth; n++) {
if (siblingGuides) siblingGuides += ", ";
// guide 竖线透明度从 0.5(最近)渐变到 0.1(最远),均低于插入线(0.6)以突出目标位置
const opacity = depth <= 1 ? 0.3 : 0.5 - (n - 1) / (depth - 1) * 0.4;
- siblingGuides += `${-n * indent}px 0 0 0 rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${opacity.toFixed(2)})`;
+ let offset = (isRTL ? n : -n) * indent;
+ if (htmlTarget.hasAttribute("data-auto-direction") && ancestor) {
+ // 混合方向的祖先引导线使用实际位置,避免将另一侧的层级线镜像到当前侧。
+ const ancestorRect = ancestor.getBoundingClientRect();
+ offset = (getComputedStyle(ancestor).direction === "rtl" ?
+ ancestorRect.right - indent / 2 : ancestorRect.left + indent / 2) - anchor;
+ ancestor = ancestor.parentElement?.closest<HTMLElement>(".li");
+ }
+ siblingGuides += `${offset}px 0 0 0 rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${opacity.toFixed(2)})`;
}
- dragCache = {node, indent, rgb, guides: siblingGuides || "none"};
+ dragCache = {node, rtl: isRTL, indent, rgb, guides: siblingGuides || "none"};
}
const {indent, rgb, guides} = dragCache;
const liRect = htmlTarget.getBoundingClientRect();
- const isRTL = getComputedStyle(htmlTarget).direction === "rtl";
const offsetX = isRTL ? (liRect.right - event.clientX) : (event.clientX - liRect.left);
// 用内容块(不含子列表)的 rect 判断上下半,避免有子列表时下半区域过小难以命中
const contentBlockForRect = Array.from(htmlTarget.children).find(c =>
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 355d9d89ea..45eee6eb5d 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -761,7 +761,7 @@ declare namespace Config {
* Whether to enable RTL (left-to-right chirography) mode
*/
rtl: boolean;
- /** 默认关闭;自动判定段落和标题的文本方向,手动方向优先,不改变列表和表格布局 */
+ /** 默认关闭;自动判定段落和标题方向,各列表项独立调整标记和缩进,手动方向优先,表格列顺序不变 */
autoDirection: boolean;
/**
* Whether to enable spell checking
diff --git a/app/tests/autoDirection.test.js b/app/tests/autoDirection.test.js
index 3cb4928513..6dd63b60e2 100644
--- a/app/tests/autoDirection.test.js
+++ b/app/tests/autoDirection.test.js
@@ -79,7 +79,7 @@ const runCases = async () => {
assert.equal(direction(hebrew), "rtl");
assert.equal(root.querySelector('[data-type="NodeCodeBlock"] [dir]'), null);
assert.equal(root.querySelector(".protyle-attr[dir]"), null);
- assert.equal(root.querySelector('[data-type="NodeListItem"]').hasAttribute("dir"), false);
+ assert.equal(root.querySelector('[data-type="NodeListItem"]').dir, "rtl");
assert.equal(lute.BlockDOM2StdMd(root.innerHTML), markdown, "automatic direction must not change stored content");
assert.doesNotMatch(lute.SpinBlockDOM(root.innerHTML), /data-auto-direction|dir="auto"/);
@@ -160,6 +160,141 @@ const runCases = async () => {
assert.equal(root.querySelector("[data-auto-direction]"), null);
};
+const runListCases = async () => {
+ const assert = require("node:assert/strict");
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
+ const {setAutoDirection, destroyAutoDirection, getAutoListDirection} = window.direction;
+ const lute = window.Lute.New();
+ lute.SetProtyleWYSIWYG(true);
+ document.body.innerHTML = '<div class="protyle"><div class="protyle-wysiwyg"></div></div>';
+ const container = document.querySelector(".protyle");
+ const root = container.firstElementChild;
+ const markdown = "- [ ] سلام task\n - [ ] English child\n - [ ] שלום child\n- [ ] English task\n\n" +
+ "1. عنوان numbered\n2. English numbered\n\n- שלום bullet\n- English bullet\n";
+ const original = lute.Md2BlockDOM(markdown);
+ const expectedMarkdown = lute.BlockDOM2StdMd(original);
+ const items = () => [...root.querySelectorAll('[data-type="NodeListItem"]')];
+ const content = item => item.querySelector(':scope > [data-type="NodeParagraph"]');
+ const editable = item => content(item).querySelector("[contenteditable]");
+ const check = (item, direction) => {
+ assert.equal(getComputedStyle(item).direction, direction, editable(item).textContent);
+ const action = item.querySelector(":scope > .protyle-action");
+ const itemRect = item.getBoundingClientRect();
+ const actionRect = action.getBoundingClientRect();
+ assert.ok(Math.abs(direction === "rtl" ? actionRect.right - itemRect.right :
+ actionRect.left - itemRect.left) < 1, `marker ${direction}: ${editable(item).textContent}`);
+ const style = getComputedStyle(content(item));
+ assert.equal(style.marginLeft, direction === "rtl" ? "0px" : "34px");
+ assert.equal(style.marginRight, direction === "rtl" ? "34px" : "0px");
+ assert.equal(getAutoListDirection(action), direction);
+ };
+ for (const rtl of [false, true]) {
+ container.classList.toggle("rtl", rtl);
+ root.innerHTML = original;
+ setAutoDirection(root, true);
+ for (const [width, fontSize] of [[640, 16], [260, 28]]) {
+ root.style.width = `${width}px`;
+ root.style.fontSize = `${fontSize}px`;
+ items().forEach((item, index) => check(item, ["rtl", "ltr", "rtl", "ltr", "rtl", "ltr", "rtl", "ltr"][index]));
+ }
+ assert.equal(lute.BlockDOM2StdMd(root.innerHTML), expectedMarkdown);
+ assert.doesNotMatch(lute.SpinBlockDOM(root.innerHTML), /data-auto-(?:list-)?direction|dir="(?:auto|ltr|rtl)"/);
+
+ const [parent, child, sibling] = items();
+ editable(parent).firstChild.data = "English parent";
+ await settle();
+ check(parent, "ltr");
+ check(child, "ltr");
+ check(sibling, "rtl");
+ editable(child).textContent = "123 😀 مرحبا";
+ await settle();
+ check(child, "rtl");
+ check(parent, "ltr");
+ editable(parent).textContent = "سلام parent";
+ editable(child).textContent = "English child";
+ await settle();
+ const drag = window.listDrag.createListDragTarget();
+ let rect = child.getBoundingClientRect();
+ const childTarget = drag(child, {clientX: rect.left + 60, clientY: rect.bottom - 1});
+ assert.equal(childTarget.isChild, true);
+ childTarget.apply();
+ assert.ok(parseFloat(child.style.getPropertyValue("--drag-guides")) > 0,
+ "LTR child keeps its RTL parent's guide on the right");
+ assert.equal(getComputedStyle(child, "::after").left, "34px");
+ window.listDrag.cleanupDragIndicators(root);
+ editable(child).firstChild.data = "שלום child";
+ await settle();
+ rect = child.getBoundingClientRect();
+ const rtlChildTarget = drag(child, {clientX: rect.right - 60, clientY: rect.bottom - 1});
+ assert.equal(rtlChildTarget.isChild, true);
+ rtlChildTarget.apply();
+ assert.equal(getComputedStyle(child, "::after").right, "34px");
+ window.listDrag.cleanupDragIndicators(root);
+ assert.equal(drag(child, {clientX: rect.right - 5, clientY: rect.bottom - 1}).isChild, false);
+
+ parent.style.direction = "ltr";
+ await settle();
+ check(parent, "ltr");
+ check(child, "ltr");
+ sibling.style.direction = "rtl";
+ await settle();
+ check(sibling, "rtl");
+ parent.style.direction = "";
+ sibling.style.direction = "";
+ await settle();
+ check(parent, "rtl");
+ const list = parent.parentElement;
+ list.style.direction = "rtl";
+ child.style.direction = "ltr";
+ await settle();
+ check(child, "ltr");
+ check(items()[3], "rtl");
+ list.style.direction = "";
+ child.style.direction = "";
+ content(parent).style.direction = "ltr";
+ await settle();
+ check(parent, "ltr");
+ content(parent).style.direction = "";
+
+ root.innerHTML = original;
+ await settle();
+ check(items()[0], "rtl");
+ check(items()[1], "ltr");
+ root.insertAdjacentHTML("beforeend", lute.Md2BlockDOM("- [ ] مرحبا new\n"));
+ await settle();
+ check(items().at(-1), "rtl");
+ setAutoDirection(root, false);
+ assert.equal(root.querySelector("[data-auto-direction]"), null);
+ assert.equal(root.querySelector("[data-auto-list-direction]"), null);
+ assert.equal(root.querySelector("[dir]"), null);
+ const first = items()[0];
+ const box = first.getBoundingClientRect();
+ const marker = first.querySelector(".protyle-action").getBoundingClientRect();
+ assert.ok(Math.abs(rtl ? marker.right - box.right : marker.left - box.left) < 1);
+ first.style.direction = "rtl";
+ const manualMarker = first.querySelector(".protyle-action").getBoundingClientRect();
+ assert.ok(Math.abs(manualMarker.right - box.right) < 1);
+ setAutoDirection(root, true);
+ setAutoDirection(root, false);
+ assert.equal(first.style.direction, "rtl");
+ }
+ destroyAutoDirection(root);
+ const preview = document.createElement("div");
+ preview.className = "b3-typography";
+ preview.innerHTML = "<ul><li><p>سلام</p><ul><li>English child</li></ul></li><li>English</li></ul>";
+ document.body.append(preview);
+ setAutoDirection(preview, true);
+ const nativeItems = preview.querySelectorAll("li");
+ assert.equal(getComputedStyle(nativeItems[0]).direction, "rtl");
+ assert.equal(getComputedStyle(nativeItems[1]).direction, "ltr");
+ assert.equal(getComputedStyle(nativeItems[2]).direction, "ltr");
+ assert.equal(getComputedStyle(nativeItems[0]).marginLeft, "0px");
+ assert.equal(getComputedStyle(nativeItems[2]).marginRight, "0px");
+ setAutoDirection(preview, false);
+ assert.equal(preview.querySelector("[data-auto-direction]"), null);
+ destroyAutoDirection(preview);
+};
+
const runElectron = async () => {
const {app, BrowserWindow} = require("electron");
app.setPath("userData", process.argv[2]);
@@ -183,6 +318,14 @@ const runElectron = async () => {
window.direction = exports;
})()`);
await win.webContents.executeJavaScript(`(${runCases.toString()})()`);
+ for (const file of ["protyle/_wysiwyg.scss", "component/_typography.scss"]) {
+ await win.webContents.insertCSS(require("sass").compile(path.join(__dirname, "../src/assets/scss", file)).css);
+ }
+ const dragSource = ts.transpileModule(readFileSync(path.join(__dirname, "../src/protyle/util/listDragTarget.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ await win.webContents.executeJavaScript(`(() => {const exports = {}; ${dragSource}; window.listDrag = exports;})()`);
+ await win.webContents.executeJavaScript(`(${runListCases.toString()})()`);
console.log("Automatic direction cases passed");
} catch (error) {
console.error(error);
diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.go
index 73fe02aa0e..6a34a5f980 100644
--- a/kernel/apicontract/setting.go
+++ b/kernel/apicontract/setting.go
@@ -218,7 +218,8 @@ type SettingEditor struct {
DynamicLoadBlocks int `json:"dynamicLoadBlocks" api:"optional,nullable"`
Justify bool `json:"justify" api:"optional,nullable"`
RTL bool `json:"rtl" api:"optional,nullable"`
- // AutoDirection 默认关闭;启用后段落和标题按首个强方向字符排版,手动方向优先,不改变列表和表格布局。
+ // AutoDirection 默认关闭;段落和标题按首个强方向字符排版,列表项独立调整标记和缩进。
+ // 手动方向优先,表格列顺序不变。
AutoDirection bool `json:"autoDirection" api:"optional,nullable"`
Spellcheck bool `json:"spellcheck" api:"optional,nullable"`
SpellcheckLanguages []string `json:"spellcheckLanguages" api:"optional,nullable"`