Skip to content

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

:zap: Reduce editor style invalidation and expand selector keys https://github.com/siyuan-note/siyuan/issues/20495

Daniel432920060fbd
diff --git a/app/scripts/css-contracts.test.js b/app/scripts/css-contracts.test.js
index e7492bd43f..678ef3996d 100644
--- a/app/scripts/css-contracts.test.js
+++ b/app/scripts/css-contracts.test.js
@@ -33,6 +33,52 @@ test("repository CSS contracts have no new violations", async () => {
await checkContracts();
});
+test("optimized editor and PDF selectors keep explicit keys and static exports retain inline RTL", () => {
+ const sass = require("sass");
+ const path = require("node:path");
+ const postcss = require("postcss");
+ const selectorParser = require("postcss-selector-parser");
+ const expandedSubjects = new Set([
+ "[data-node-id],[data-table-cell-node]", ".p,.h1,.h2,.h3,.h4,.h5,.h6", "input,textarea", "span,br",
+ ]);
+ // 仅约束已经优化的热点,不禁止其他具有不同特异性或匹配语义的伪类。
+ for (const entry of ["base", "mobile", "export"]) {
+ const css = sass.compile(path.join(__dirname, "../src/assets/scss", `${entry}.scss`), {
+ logger: sass.Logger.silent,
+ }).css;
+ let inlineListRules = 0;
+ let markedListRules = 0;
+ postcss.parse(css).walkRules(rule => {
+ const selectors = selectorParser().astSync(rule.selector);
+ selectors.walkPseudos(node => {
+ if (node.value === ":is") {
+ assert.equal(expandedSubjects.has(node.nodes.map(option => option.toString().trim()).join(",")), false,
+ `${entry}: ${rule.selector}`);
+ }
+ });
+ if (!rule.nodes.some(node => node.prop === "margin-right" && node.value === "34px")) {
+ return;
+ }
+ selectors.walkAttributes(node => {
+ if (node.attribute === "style" && node.operator === "*=" && node.value === "direction: rtl") {
+ inlineListRules++;
+ }
+ });
+ selectors.walkClasses(node => {
+ if (node.value === "protyle-block--rtl") {
+ markedListRules++;
+ }
+ });
+ });
+ if (entry === "export") {
+ assert.ok(inlineListRules > 0, "static exports must lay out existing inline RTL without scripts");
+ } else {
+ assert.equal(inlineListRules, 0, "editor list layout must not invalidate descendants on unrelated style changes");
+ assert.ok(markedListRules > 0);
+ }
+ }
+});
+
test("shared token defaults preserve local var resolution and runtime overrides", async () => {
const sass = require("sass");
const path = require("node:path");
diff --git a/app/src/assets/scss/export.scss b/app/src/assets/scss/export.scss
index 01fad08601..84b5c76e75 100644
--- a/app/src/assets/scss/export.scss
+++ b/app/src/assets/scss/export.scss
@@ -1,6 +1,6 @@
@use "util/mixin" as *;
@use "component/tooltips" as *;
-@use "protyle/wysiwyg" as *;
+@use "protyle/wysiwyg" as * with ($block-rtl-selector: '[style*="direction: rtl"]');
@use "component/typography" as *;
@use "protyle/attr" as *;
@use "protyle/mindmap-view" as *;
diff --git a/app/src/assets/scss/pdf/annotation_layer_builder.scss b/app/src/assets/scss/pdf/annotation_layer_builder.scss
index fe823050db..307e0b6750 100644
--- a/app/src/assets/scss/pdf/annotation_layer_builder.scss
+++ b/app/src/assets/scss/pdf/annotation_layer_builder.scss
@@ -32,7 +32,8 @@
--input-hover-border-color: Highlight;
--link-outline: 1.5px solid LinkText;
- .textWidgetAnnotation :is(input, textarea):required,
+ .textWidgetAnnotation input:required,
+ .textWidgetAnnotation textarea:required,
.choiceWidgetAnnotation select:required,
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
outline: 1.5px solid selectedItem;
@@ -142,7 +143,8 @@
/* A field rendered to its own canvas shows that canvas and keeps its editable
element hidden. Once the field is modified the canvas is outdated, so it's
hidden and the element is shown instead. */
- .hasOwnCanvas:not(.sandboxModified) :is(input, textarea) {
+ .hasOwnCanvas:not(.sandboxModified) input,
+ .hasOwnCanvas:not(.sandboxModified) textarea {
display: none;
}
@@ -186,7 +188,8 @@
left: 0;
}
- .textWidgetAnnotation :is(input, textarea),
+ .textWidgetAnnotation input,
+ .textWidgetAnnotation textarea,
.choiceWidgetAnnotation select,
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input {
background-color: rgba(0, 54, 255, 0.13);
@@ -200,7 +203,8 @@
width: 100%;
}
- .textWidgetAnnotation :is(input, textarea):required,
+ .textWidgetAnnotation input:required,
+ .textWidgetAnnotation textarea:required,
.choiceWidgetAnnotation select:required,
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input:required {
outline: 1.5px solid red;
@@ -214,7 +218,8 @@
resize: none;
}
- .textWidgetAnnotation :is(input, textarea)[disabled],
+ .textWidgetAnnotation input[disabled],
+ .textWidgetAnnotation textarea[disabled],
.choiceWidgetAnnotation select[disabled],
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input[disabled] {
background: none;
@@ -222,18 +227,21 @@
cursor: not-allowed;
}
- .textWidgetAnnotation :is(input, textarea):hover,
+ .textWidgetAnnotation input:hover,
+ .textWidgetAnnotation textarea:hover,
.choiceWidgetAnnotation select:hover,
.buttonWidgetAnnotation:is(.checkBox, .radioButton) input:hover {
border: 2px solid var(--input-hover-border-color);
}
- .textWidgetAnnotation :is(input, textarea):hover,
+ .textWidgetAnnotation input:hover,
+ .textWidgetAnnotation textarea:hover,
.choiceWidgetAnnotation select:hover,
.buttonWidgetAnnotation.checkBox input:hover {
border-radius: 2px;
}
- .textWidgetAnnotation :is(input, textarea):focus,
+ .textWidgetAnnotation input:focus,
+ .textWidgetAnnotation textarea:focus,
.choiceWidgetAnnotation select:focus {
background: none;
border: 2px solid var(--input-focus-border-color);
diff --git a/app/src/assets/scss/pdf/text_layer_builder.scss b/app/src/assets/scss/pdf/text_layer_builder.scss
index 30ae58d924..8fb3b6427a 100644
--- a/app/src/assets/scss/pdf/text_layer_builder.scss
+++ b/app/src/assets/scss/pdf/text_layer_builder.scss
@@ -33,7 +33,8 @@
touch-action: none;
}
- :is(span, br) {
+ span,
+ br {
color: transparent;
position: absolute;
white-space: pre;
diff --git a/app/src/assets/scss/pdf/xfa_layer_builder.scss b/app/src/assets/scss/pdf/xfa_layer_builder.scss
index 532aa5409f..e7b764cf04 100644
--- a/app/src/assets/scss/pdf/xfa_layer_builder.scss
+++ b/app/src/assets/scss/pdf/xfa_layer_builder.scss
@@ -311,7 +311,8 @@
flex: 1;
}
-:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) :is(input, textarea) {
+:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) input,
+:is(.xfaNonInteractive, .xfaDisabled, .xfaReadOnly) textarea {
background: initial;
}
diff --git a/app/src/assets/scss/protyle/_protyle.scss b/app/src/assets/scss/protyle/_protyle.scss
index 6f1f595854..91883f35bc 100644
--- a/app/src/assets/scss/protyle/_protyle.scss
+++ b/app/src/assets/scss/protyle/_protyle.scss
@@ -1116,8 +1116,20 @@
text-align: inherit;
}
-.table__cell-rich > :is(.p, .h1, .h2, .h3, .h4, .h5, .h6)[data-table-cell-node],
-.table__cell-editor .protyle-wysiwyg > :is(.p, .h1, .h2, .h3, .h4, .h5, .h6) {
+.table__cell-rich > .p[data-table-cell-node],
+.table__cell-rich > .h1[data-table-cell-node],
+.table__cell-rich > .h2[data-table-cell-node],
+.table__cell-rich > .h3[data-table-cell-node],
+.table__cell-rich > .h4[data-table-cell-node],
+.table__cell-rich > .h5[data-table-cell-node],
+.table__cell-rich > .h6[data-table-cell-node],
+.table__cell-editor .protyle-wysiwyg > .p,
+.table__cell-editor .protyle-wysiwyg > .h1,
+.table__cell-editor .protyle-wysiwyg > .h2,
+.table__cell-editor .protyle-wysiwyg > .h3,
+.table__cell-editor .protyle-wysiwyg > .h4,
+.table__cell-editor .protyle-wysiwyg > .h5,
+.table__cell-editor .protyle-wysiwyg > .h6 {
// 单元格已提供侧边留白,多段落和标题与普通文本使用相同的对齐边界。
padding-inline: 0;
}
diff --git a/app/src/assets/scss/protyle/_wysiwyg.scss b/app/src/assets/scss/protyle/_wysiwyg.scss
index 948fcab584..fd9cc10506 100644
--- a/app/src/assets/scss/protyle/_wysiwyg.scss
+++ b/app/src/assets/scss/protyle/_wysiwyg.scss
@@ -3,6 +3,9 @@
@use "tabs";
@use "task";
+// 导出样式可使用原始方向属性,支持未执行脚本的静态内容。
+$block-rtl-selector: ".protyle-block--rtl" !default;
+
// 任务点击保持隐藏布局,正文编辑时恢复引用块;折叠的列表项和标题保留定位内容。
.protyle-wysiwyg[data-backlink-hide-reference]:is(:not(:focus-within), [data-backlink-task-focus]) {
[data-backlink-reference]:not([fold="1"]):not(.li[fold="1"] *) {
@@ -208,11 +211,13 @@
border-left-color: var(--b3-scroll-color);
}
- & > :is([data-node-id], [data-table-cell-node]) {
+ & > [data-node-id],
+ & > [data-table-cell-node] {
margin-left: 34px;
}
- & > :is([data-node-id], [data-table-cell-node]):not(.p):not(.code-block) {
+ & > [data-node-id]:not(.p):not(.code-block),
+ & > [data-table-cell-node]:not(.p):not(.code-block) {
padding-right: 0;
}
@@ -314,7 +319,7 @@
}
}
- &[style*="direction: rtl"] {
+ &#{$block-rtl-selector} {
.li:not([data-auto-direction]) > .protyle-action,
&:not([data-auto-direction]) > .protyle-action {
right: 0;
@@ -322,8 +327,10 @@
direction: rtl;
}
- .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]) {
+ .li:not([data-auto-direction]) > [data-node-id],
+ .li:not([data-auto-direction]) > [data-table-cell-node],
+ &:not([data-auto-direction]) > [data-node-id],
+ &:not([data-auto-direction]) > [data-table-cell-node] {
margin-right: 34px;
margin-left: 0;
}
@@ -360,12 +367,14 @@
direction: inherit;
}
- & > :is([data-node-id], [data-table-cell-node]) {
+ & > [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]) {
+ &[data-auto-list-direction="rtl"] > [data-node-id],
+ &[data-auto-list-direction="rtl"] > [data-table-cell-node] {
margin-left: 0;
margin-right: 34px;
}
diff --git a/app/src/protyle/render/autoDirection.ts b/app/src/protyle/render/autoDirection.ts
index 4f1664af90..67bbbc0d96 100644
--- a/app/src/protyle/render/autoDirection.ts
+++ b/app/src/protyle/render/autoDirection.ts
@@ -1,3 +1,5 @@
+import {clearBlockDirection, renderBlockDirection, syncBlockDirection} from "./blockDirection";
+
const textSelector = '[data-type="NodeParagraph"] > div[contenteditable]:not(.protyle-attr), ' +
'[data-type="NodeHeading"] > div[contenteditable]:not(.protyle-attr), p, h1, h2, h3, h4, h5, h6';
const excludedSelector = 'pre, code, .render-node, [data-type="NodeCodeBlock"], ' +
@@ -41,6 +43,7 @@ export const destroyAutoDirection = (root: HTMLElement) => {
/** 自动方向用于正文和各列表项的布局,不持久化推导出的方向。 */
export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
destroyAutoDirection(root);
+ renderBlockDirection(root);
const managed = new Set<HTMLElement>();
const applyDirection = (element: HTMLElement, direction: string) => {
managed.add(element);
@@ -148,13 +151,18 @@ export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
scopes.add(record.target.parentElement);
}
} else if (record.type === "attributes") {
- scopes.add(record.target as HTMLElement);
+ const element = record.target as HTMLElement;
+ syncBlockDirection(element);
+ if (enabled) {
+ scopes.add(element);
+ }
} else {
if ((record.target as HTMLElement).closest(listSelector)) {
scopes.add(record.target as HTMLElement);
}
record.addedNodes.forEach(node => {
if (node.nodeType === 1) {
+ renderBlockDirection(node as Element);
scopes.add(node as HTMLElement);
}
});
@@ -174,11 +182,14 @@ export const setAutoDirection = (root: HTMLElement, enabled: boolean) => {
});
scopes.forEach(update);
});
- observer.observe(root, {subtree: true, childList: true, ...(enabled ? {
- characterData: true, attributes: true, attributeFilter: ["style", "dir", "contenteditable", "data-type"],
- } : {})});
+ observer.observe(root, {
+ subtree: true, childList: true, attributes: true, characterData: enabled,
+ attributeFilter: ["style", "data-node-id", "data-table-cell-node",
+ ...(enabled ? ["dir", "contenteditable", "data-type"] : [])],
+ });
disposers.set(root, () => {
observer.disconnect();
managed.forEach(clearDirection);
+ clearBlockDirection(root);
});
};
diff --git a/app/src/protyle/render/blockDirection.ts b/app/src/protyle/render/blockDirection.ts
new file mode 100644
index 0000000000..7c3b1ae30c
--- /dev/null
+++ b/app/src/protyle/render/blockDirection.ts
@@ -0,0 +1,24 @@
+const blockSelector = "[data-node-id], [data-table-cell-node]";
+const rtlClass = "protyle-block--rtl";
+
+/** 从原始内联方向派生布局标记,不修改文档属性或读取计算样式。 */
+export const syncBlockDirection = (element: Element) => {
+ const rtl = element.matches(blockSelector) && (element as HTMLElement).style.direction === "rtl";
+ if (element.classList.contains(rtlClass) !== rtl) {
+ element.classList.toggle(rtlClass, rtl);
+ }
+};
+
+/** 在布局测量前同步新渲染的块,也清理克隆内容中失效的标记。 */
+export const renderBlockDirection = (root: Element) => {
+ syncBlockDirection(root);
+ root.querySelectorAll(`[data-node-id][style], [data-table-cell-node][style], .${rtlClass}`)
+ .forEach(syncBlockDirection);
+};
+
+export const clearBlockDirection = (root: Element) => {
+ if (root.classList.contains(rtlClass)) {
+ root.classList.remove(rtlClass);
+ }
+ root.querySelectorAll(`.${rtlClass}`).forEach(element => element.classList.remove(rtlClass));
+};
diff --git a/app/src/protyle/render/tableCellRich.ts b/app/src/protyle/render/tableCellRich.ts
index 47f4747c3d..f949a2ddef 100644
--- a/app/src/protyle/render/tableCellRich.ts
+++ b/app/src/protyle/render/tableCellRich.ts
@@ -2,6 +2,7 @@ import {highlightRender} from "./highlightRender";
import {mathRender} from "./mathRender";
import {getTableCellRichBlockDOM, updateTableCellContentLayout} from "../util/tableCellRich";
import {TABLE_CELL_RICH_ATTRIBUTE} from "../util/tableCellRichValue";
+import {renderBlockDirection} from "./blockDirection";
export const renderTableCellRichElements = (root: Element) => {
const elements = [...root.querySelectorAll<HTMLElement>(".table__cell-rich")];
@@ -31,6 +32,7 @@ export const renderTableCellRichElements = (root: Element) => {
}
});
element.replaceChildren(template.content);
+ renderBlockDirection(element);
element.classList.remove("b3-typography");
element.dataset.protyleLiteRender = "safe";
mathRender(element);
diff --git a/app/src/protyle/util/processCode.ts b/app/src/protyle/util/processCode.ts
index 919404b1cd..a93865b152 100644
--- a/app/src/protyle/util/processCode.ts
+++ b/app/src/protyle/util/processCode.ts
@@ -17,6 +17,7 @@ import {renderLongTextRuns} from "./longTextWrap";
import {renderImageActions} from "../render/imageActions";
import {renderImageDisplay} from "../render/imageDisplay";
import {renderIFrameResize} from "../render/iframeResize";
+import {renderBlockDirection} from "../render/blockDirection";
export const processPasteCode = (html: string, text: string, originalTextHTML: string, protyle: IProtyle) => {
const tempElement = document.createElement("div");
@@ -66,6 +67,7 @@ const RENDER_MAP: Record<string, (previewPanel: Element) => void> = {
};
export const processRender = (previewPanel: Element) => {
+ renderBlockDirection(previewPanel);
renderImageActions(previewPanel);
renderImageDisplay(previewPanel);
normalizeInlineElementBoundaries(previewPanel);
diff --git a/app/src/protyle/wysiwyg/transaction.ts b/app/src/protyle/wysiwyg/transaction.ts
index 1da3663f47..d2b6657d92 100644
--- a/app/src/protyle/wysiwyg/transaction.ts
+++ b/app/src/protyle/wysiwyg/transaction.ts
@@ -24,6 +24,7 @@ import {
} from "./getBlock";
import {Constants} from "../../constants";
import {blockRender} from "../render/blockRender";
+import {renderBlockDirection, syncBlockDirection} from "../render/blockDirection";
import {renderEmbedHeadings} from "../render/embedHeading";
import {processRender} from "../util/processCode";
import {renderImageDisplay} from "../render/imageDisplay";
@@ -1163,6 +1164,7 @@ export const onTransaction = (protyle: IProtyle, operations: IOperation[], isUnd
}, 450);
}
});
+ syncBlockDirection(item);
// 已渲染数据库的布局类型随新内容一起更新,避免旧内容提前套用新布局样式。
if (data["data-av-type"] && !item.querySelector(".av__container")) {
item.setAttribute("data-av-type", data["data-av-type"]);
@@ -2787,6 +2789,7 @@ export const updateBatchTransaction = (nodeElements: Element[], protyle: IProtyl
context: index === 0 ? focusContext : undefined,
});
cb(element as HTMLElement);
+ renderBlockDirection(element);
element.setAttribute(Constants.ATTRIBUTE_EDITING, "true");
operations.push({
action: "update",
diff --git a/app/tests/autoDirection.test.js b/app/tests/autoDirection.test.js
index 6dd63b60e2..7b2db8b4e7 100644
--- a/app/tests/autoDirection.test.js
+++ b/app/tests/autoDirection.test.js
@@ -272,6 +272,7 @@ const runListCases = async () => {
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";
+ await settle();
const manualMarker = first.querySelector(".protyle-action").getBoundingClientRect();
assert.ok(Math.abs(manualMarker.right - box.right) < 1);
setAutoDirection(root, true);
@@ -295,6 +296,123 @@ const runListCases = async () => {
destroyAutoDirection(preview);
};
+const runManualDirectionCases = async (staticExport) => {
+ const assert = require("node:assert/strict");
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
+ const {setAutoDirection, destroyAutoDirection} = window.direction;
+ const {renderBlockDirection} = window.blockDirection;
+ const lute = window.Lute.New();
+ lute.SetProtyleWYSIWYG(true);
+ lute.SetKramdownIAL(true);
+ const html = lute.Md2BlockDOM("- Parent\n - Child\n- Sibling\n");
+ const rtlClass = "protyle-block--rtl";
+ for (const rich of [false, true]) {
+ document.body.innerHTML = '<div class="protyle"><div></div></div>';
+ const root = document.body.firstElementChild.firstElementChild;
+ root.className = rich ? "table__cell-rich" : "protyle-wysiwyg";
+ root.innerHTML = html;
+ if (rich) {
+ root.querySelectorAll("[data-node-id]").forEach(element => {
+ element.removeAttribute("data-node-id");
+ element.setAttribute("data-table-cell-node", "");
+ });
+ }
+ let list = root.querySelector(".list");
+ list.setAttribute("style", "direction: rtl; color: rgb(1, 2, 3)");
+ const original = root.innerHTML;
+ const markdown = lute.BlockDOM2Md(original);
+ const check = (rtl) => {
+ root.querySelectorAll(".li").forEach(item => {
+ const content = item.querySelector(":scope > .p");
+ const style = getComputedStyle(content);
+ assert.equal(style.marginLeft, rtl ? "0px" : "34px");
+ assert.equal(style.marginRight, rtl ? "34px" : "0px");
+ const marker = item.querySelector(":scope > .protyle-action").getBoundingClientRect();
+ const rect = item.getBoundingClientRect();
+ assert.ok(Math.abs(rtl ? marker.right - rect.right : marker.left - rect.left) < 1);
+ });
+ };
+ if (!staticExport) {
+ setAutoDirection(root, false);
+ assert.ok(list.classList.contains(rtlClass));
+ }
+ for (const [width, fontSize] of [[720, 16], [280, 32]]) {
+ root.style.width = `${width}px`;
+ root.style.fontSize = `${fontSize}px`;
+ check(true);
+ }
+ assert.equal(list.getAttribute("style"), "direction: rtl; color: rgb(1, 2, 3)");
+ assert.equal(lute.BlockDOM2Md(root.innerHTML), markdown);
+ assert.doesNotMatch(lute.SpinBlockDOM(root.innerHTML), /protyle-block--rtl/);
+ if (staticExport) {
+ list.style.direction = "ltr";
+ check(false);
+ continue;
+ }
+
+ // 属性更新及删除不依赖自动方向开关,也不重写原始样式。
+ list.style.direction = "ltr";
+ await settle();
+ check(false);
+ assert.equal(list.classList.contains(rtlClass), false);
+ list.setAttribute("style", "direction:rtl!important");
+ await settle();
+ check(true);
+ assert.equal(list.getAttribute("style"), "direction:rtl!important");
+ list.removeAttribute("style");
+ await settle();
+ check(false);
+
+ // 菜单和快捷键共用的事务入口在调用返回前同步布局。
+ if (!rich) {
+ window.updateBatchTransaction([list], {}, element => { element.style.direction = "rtl"; });
+ check(true);
+ const transaction = window.directionTransactions.at(-1);
+ assert.doesNotMatch(lute.SpinBlockDOM(transaction.operations[0].data), /protyle-block--rtl/);
+ list.outerHTML = transaction.undoOperations[0].data;
+ await settle();
+ check(false);
+ root.querySelector(".list").outerHTML = transaction.operations[0].data;
+ await settle();
+ check(true);
+ }
+
+ // 模拟重载、撤销重做和克隆粘贴;已有标记必须按恢复后的 style 重新推导。
+ root.innerHTML = original;
+ await settle();
+ check(true);
+ list = root.querySelector(".list");
+ const clone = list.cloneNode(true);
+ clone.style.direction = "ltr";
+ list.replaceWith(clone);
+ await settle();
+ check(false);
+ assert.equal(clone.classList.contains(rtlClass), false);
+ clone.style.direction = "rtl";
+ renderBlockDirection(clone);
+ check(true);
+ setAutoDirection(root, true);
+ check(true);
+ setAutoDirection(root, false);
+ check(true);
+
+ // 重复渲染及无关样式更新不能反复写入类名或造成观察器循环。
+ let classChanges = 0;
+ const observer = new MutationObserver(records => { classChanges += records.length; });
+ observer.observe(root, {subtree: true, attributes: true, attributeFilter: ["class"]});
+ renderBlockDirection(root);
+ renderBlockDirection(root);
+ root.style.outlineWidth = "1px";
+ clone.style.color = "red";
+ await settle();
+ assert.equal(classChanges, 0);
+ observer.disconnect();
+ destroyAutoDirection(root);
+ assert.equal(root.querySelector(`.${rtlClass}`), null);
+ assert.equal(clone.style.direction, "rtl");
+ }
+};
+
const runElectron = async () => {
const {app, BrowserWindow} = require("electron");
app.setPath("userData", process.argv[2]);
@@ -313,8 +431,17 @@ const runElectron = async () => {
path.join(__dirname, "../src/assets/scss/protyle/_content.scss")).css);
await win.webContents.executeJavaScript(readFileSync(path.join(__dirname, "../stage/protyle/js/lute/lute.min.js"), "utf8"));
await win.webContents.executeJavaScript(`(() => {
+ const module = {exports: {}};
+ new Function("exports", ${JSON.stringify(ts.transpileModule(
+ readFileSync(path.join(__dirname, "../src/protyle/render/blockDirection.ts"), "utf8"), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText)})(module.exports);
const exports = {};
- ${compiled}
+ new Function("exports", "require", ${JSON.stringify(compiled)})(exports, name => {
+ if (name === "./blockDirection") return module.exports;
+ throw new Error(name);
+ });
+ window.blockDirection = module.exports;
window.direction = exports;
})()`);
await win.webContents.executeJavaScript(`(${runCases.toString()})()`);
@@ -326,6 +453,33 @@ const runElectron = async () => {
}).outputText;
await win.webContents.executeJavaScript(`(() => {const exports = {}; ${dragSource}; window.listDrag = exports;})()`);
await win.webContents.executeJavaScript(`(${runListCases.toString()})()`);
+ const transactionSource = ts.createSourceFile("transaction.ts", readFileSync(
+ path.join(__dirname, "../src/protyle/wysiwyg/transaction.ts"), "utf8"), ts.ScriptTarget.Latest, true);
+ const batch = transactionSource.statements.find(statement => ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(declaration => declaration.name.getText() === "updateBatchTransaction"));
+ const batchJS = ts.transpileModule(batch.getText(), {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},
+ }).outputText;
+ await win.webContents.executeJavaScript(`(() => {
+ window.directionTransactions = [];
+ window.updateBatchTransaction = new Function("renderBlockDirection", "Constants", "cleanHeadingNumberHTML", "transaction",
+ "const exports = {}; " + ${JSON.stringify(batchJS)} + "; return exports.updateBatchTransaction;")(
+ window.blockDirection.renderBlockDirection, {ATTRIBUTE_EDITING: "data-editing"}, html => html,
+ (protyle, operations, undoOperations) => window.directionTransactions.push({operations, undoOperations}));
+ })()`);
+ for (const entry of ["base", "mobile", "export"]) {
+ const css = require("sass").compile(path.join(__dirname, "../src/assets/scss", `${entry}.scss`), {
+ logger: require("sass").Logger.silent,
+ }).css;
+ const key = await win.webContents.insertCSS(css);
+ for (const theme of ["daylight", "midnight"]) {
+ const themeKey = await win.webContents.insertCSS(readFileSync(
+ path.join(__dirname, "../appearance/themes", theme, "theme.css"), "utf8"));
+ await win.webContents.executeJavaScript(`(${runManualDirectionCases.toString()})(${entry === "export"})`);
+ await win.webContents.removeInsertedCSS(themeKey);
+ }
+ await win.webContents.removeInsertedCSS(key);
+ }
console.log("Automatic direction cases passed");
} catch (error) {
console.error(error);