Skip to content

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

:sparkles: Support pasting editable Office lists https://github.com/siyuan-note/siyuan/issues/18756

Danielf71189c1c6d2
diff --git a/app/src/protyle/util/officeList.test.ts b/app/src/protyle/util/officeList.test.ts
new file mode 100644
index 0000000000..1228ac16c3
--- /dev/null
+++ b/app/src/protyle/util/officeList.test.ts
@@ -0,0 +1,144 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ buildOfficeListPlan,
+ classifyPptMarker,
+ classifyWordMarker,
+ convertOfficeLists,
+ detectTaskMarker,
+ groupConsecutiveOfficeListItems,
+ parseCssLengthToPoints,
+ parseInlineStyle,
+ parseOrderedMarker,
+ parsePptSpecialFormat,
+ parseWordListStyle,
+} from "./officeList";
+
+describe("Office list style parsing", () => {
+ it("parses case-insensitive Word list identities without head styles", () => {
+ assert.deepEqual(parseWordListStyle(" color:red; MSO-LIST: l12 LEVEL3 lfo7 ;"), {
+ level: 3,
+ identity: "word:l12:lfo7",
+ });
+ assert.equal(parseWordListStyle("mso-list:Ignore"), undefined);
+ });
+
+ it("keeps quoted and parenthesized inline style values intact", () => {
+ assert.deepEqual(parseInlineStyle("font-family:'A; B'; background:url(data:image/png;a:b); COLOR: red"), {
+ "font-family": "'A; B'",
+ background: "url(data:image/png;a:b)",
+ color: "red",
+ });
+ });
+
+ it("only accepts actual PowerPoint bullet formats", () => {
+ assert.equal(parsePptSpecialFormat("mso-special-format: bullet"), "bullet");
+ assert.equal(parsePptSpecialFormat("MSO-SPECIAL-FORMAT:numbullet"), "numbullet");
+ assert.equal(parsePptSpecialFormat("mso-special-format:nobullet"), undefined);
+ assert.equal(parsePptSpecialFormat("mso-special-format:lastCR"), undefined);
+ });
+
+ it("normalizes common PowerPoint margin units", () => {
+ assert.equal(parseCssLengthToPoints(".5in"), 36);
+ assert.equal(parseCssLengthToPoints("48px"), 36);
+ assert.equal(parseCssLengthToPoints("3pc"), 36);
+ assert.equal(parseCssLengthToPoints("invalid"), undefined);
+ });
+});
+
+describe("Office list marker parsing", () => {
+ it("detects numeric, alphabetic, and Roman ordered markers", () => {
+ assert.deepEqual(parseOrderedMarker("12.\u00a0"), {ordinal: 12, format: "number"});
+ assert.deepEqual(parseOrderedMarker("b)"), {ordinal: 2, format: "letter"});
+ assert.deepEqual(parseOrderedMarker("c."), {ordinal: 3, format: "letter"});
+ assert.deepEqual(parseOrderedMarker("(iv)"), {ordinal: 4, format: "roman"});
+ assert.equal(parseOrderedMarker("bullet"), undefined);
+ });
+
+ it("treats Wingdings and Courier markers as unordered", () => {
+ assert.deepEqual(classifyWordMarker("l", "Wingdings"), {type: "ul"});
+ assert.deepEqual(classifyWordMarker("n", "font-family: Wingdings"), {type: "ul"});
+ assert.deepEqual(classifyWordMarker("l", ""), {type: "ul"});
+ assert.deepEqual(classifyWordMarker("o", "Courier New"), {type: "ul"});
+ assert.deepEqual(classifyWordMarker("3.", "Arial"), {type: "ol", markerOrdinal: 3});
+ });
+
+ it("maps explicit Unicode task markers", () => {
+ for (const marker of ["□", "☐"]) {
+ assert.equal(detectTaskMarker(marker, "Arial"), false);
+ }
+ for (const marker of ["✔", "✓", "☑", "☒"]) {
+ assert.equal(detectTaskMarker(marker, "Arial"), true);
+ }
+ });
+
+ it("maps Wingdings task markers only with the matching marker font", () => {
+ for (const marker of ["£", "\uF0A3"]) {
+ assert.equal(detectTaskMarker(marker, "Wingdings 2"), false);
+ }
+ for (const marker of ["P", "\uF050", "R", "\uF052"]) {
+ assert.equal(detectTaskMarker(marker, "Wingdings 2"), true);
+ }
+ for (const marker of ["p", "\uF070", "q", "\uF071"]) {
+ assert.equal(detectTaskMarker(marker, "Wingdings"), false);
+ }
+ for (const marker of ["ü", "\uF0FC"]) {
+ assert.equal(detectTaskMarker(marker, "Wingdings"), true);
+ }
+ assert.equal(detectTaskMarker("P", "Arial"), undefined);
+ assert.equal(detectTaskMarker("p", "Arial"), undefined);
+ });
+
+ it("uses the PowerPoint special format after task detection", () => {
+ assert.deepEqual(classifyPptMarker("☑", "Arial", "bullet"), {type: "task", checked: true});
+ assert.deepEqual(classifyPptMarker("4.", "Arial", "numbullet"), {type: "ol", markerOrdinal: 4});
+ assert.deepEqual(classifyPptMarker("•", "Arial", "bullet"), {type: "ul"});
+ });
+});
+
+describe("Office list planning", () => {
+ it("compresses skipped levels and always nests lists inside list items", () => {
+ const plan = buildOfficeListPlan([
+ {level: 1, type: "ul", identity: "word:l0:lfo1"},
+ {level: 3, type: "ul", identity: "word:l0:lfo1"},
+ {level: 3, type: "ul", identity: "word:l0:lfo1"},
+ {level: 2, type: "ul", identity: "word:l0:lfo1"},
+ {level: 1, type: "ul", identity: "word:l0:lfo1"},
+ ]);
+
+ assert.equal(plan.length, 1);
+ assert.deepEqual(plan[0].items.map(item => item.sourceIndex), [0, 4]);
+ assert.equal(plan[0].items[0].children.length, 1);
+ assert.deepEqual(plan[0].items[0].children[0].items.map(item => item.sourceIndex), [1, 2, 3]);
+ });
+
+ it("splits lists when type, identity, or numbering restarts", () => {
+ const plan = buildOfficeListPlan([
+ {level: 1, type: "ol", identity: "word:l1:lfo1", markerOrdinal: 1},
+ {level: 1, type: "ol", identity: "word:l1:lfo1", markerOrdinal: 2},
+ {level: 1, type: "ol", identity: "word:l1:lfo1", markerOrdinal: 5},
+ {level: 1, type: "ul", identity: "word:l1:lfo1"},
+ {level: 1, type: "ul", identity: "word:l2:lfo2"},
+ ]);
+
+ assert.equal(plan.length, 4);
+ assert.deepEqual(plan.map(item => item.type), ["ol", "ol", "ul", "ul"]);
+ assert.deepEqual(plan.map(item => item.start), [1, 5, undefined, undefined]);
+ assert.deepEqual(plan[0].items.map(item => item.sourceIndex), [0, 1]);
+ });
+
+ it("separates list runs at ordinary paragraphs", () => {
+ assert.deepEqual(groupConsecutiveOfficeListItems([1, 2, undefined, 3, null, 4, 5]), [
+ [1, 2],
+ [3],
+ [4, 5],
+ ]);
+ });
+});
+
+describe("convertOfficeLists", () => {
+ it("is a no-op without DOMParser in the Node test environment", () => {
+ const html = "<p style=\"mso-list:l0 level1 lfo1\">l item</p>";
+ assert.deepEqual(convertOfficeLists(html), {html, convertedCount: 0});
+ });
+});
diff --git a/app/src/protyle/util/officeList.ts b/app/src/protyle/util/officeList.ts
new file mode 100644
index 0000000000..2cba6d72e3
--- /dev/null
+++ b/app/src/protyle/util/officeList.ts
@@ -0,0 +1,558 @@
+export type OfficeListSource = "word" | "ppt";
+
+export type OfficeListType = "ul" | "ol" | "task";
+
+export interface OfficeListModel {
+ level: number;
+ type: OfficeListType;
+ identity: string;
+ checked?: boolean;
+ markerOrdinal?: number;
+}
+
+export interface OfficeListPlanItem {
+ sourceIndex: number;
+ checked?: boolean;
+ children: OfficeListPlan[];
+}
+
+export interface OfficeListPlan {
+ type: OfficeListType;
+ identity: string;
+ start?: number;
+ items: OfficeListPlanItem[];
+}
+
+export interface OfficeListConversionResult {
+ html: string;
+ convertedCount: number;
+ source?: OfficeListSource;
+}
+
+interface ExtractedOfficeListItem {
+ element: Element;
+ content: Element;
+ model: OfficeListModel;
+ source: OfficeListSource;
+}
+
+interface OfficeListFrame {
+ container: OfficeListPlan[];
+ level: number;
+ list: OfficeListPlan;
+}
+
+interface OrderedMarker {
+ ordinal: number;
+ format: "number" | "letter" | "roman";
+}
+
+const LEVEL_EPSILON = 0.5;
+
+const UNCHECKED_TASK_MARKERS = new Set(["□", "☐"]);
+const CHECKED_TASK_MARKERS = new Set(["✔", "✓", "☑", "☒"]);
+const UNORDERED_MARKERS = new Set(["•", "·", "●", "○", "◦", "▪", "▫", "■", "□", "◆", "◇", "‣", "⁃", "-", "–", "—"]);
+
+export const parseInlineStyle = (style: string) => {
+ const result: Record<string, string> = {};
+ let segment = "";
+ let quote = "";
+ let parentheses = 0;
+ const segments: string[] = [];
+
+ for (const character of style) {
+ if (quote) {
+ segment += character;
+ if (character === quote) {
+ quote = "";
+ }
+ continue;
+ }
+ if (character === "\"" || character === "'") {
+ quote = character;
+ segment += character;
+ continue;
+ }
+ if (character === "(") {
+ parentheses++;
+ } else if (character === ")" && parentheses > 0) {
+ parentheses--;
+ }
+ if (character === ";" && parentheses === 0) {
+ segments.push(segment);
+ segment = "";
+ } else {
+ segment += character;
+ }
+ }
+ segments.push(segment);
+
+ for (const item of segments) {
+ const colon = item.indexOf(":");
+ if (colon < 0) {
+ continue;
+ }
+ const name = item.slice(0, colon).trim().toLowerCase();
+ if (name) {
+ result[name] = item.slice(colon + 1).trim();
+ }
+ }
+ return result;
+};
+
+export const parseWordListStyle = (style: string) => {
+ const value = parseInlineStyle(style)["mso-list"];
+ if (!value || /^ignore$/i.test(value.trim())) {
+ return undefined;
+ }
+ const list = value.match(/\bl\s*(\d+)\b/i);
+ const level = value.match(/\blevel\s*(\d+)\b/i);
+ const override = value.match(/\blfo\s*(\d+)\b/i);
+ if (!list || !level || !override) {
+ return undefined;
+ }
+ return {
+ level: Number.parseInt(level[1], 10),
+ identity: `word:l${Number.parseInt(list[1], 10)}:lfo${Number.parseInt(override[1], 10)}`,
+ };
+};
+
+export const parsePptSpecialFormat = (style: string): "bullet" | "numbullet" | undefined => {
+ const value = parseInlineStyle(style)["mso-special-format"]?.trim().toLowerCase();
+ return value === "bullet" || value === "numbullet" ? value : undefined;
+};
+
+export const parseCssLengthToPoints = (value: string) => {
+ const match = value.trim().match(/^(-?(?:\d+(?:\.\d*)?|\.\d+))\s*(in|pt|px|pc|cm|mm)?$/i);
+ if (!match) {
+ return undefined;
+ }
+ const amount = Number.parseFloat(match[1]);
+ switch (match[2]?.toLowerCase()) {
+ case "in":
+ return amount * 72;
+ case "px":
+ return amount * 0.75;
+ case "pc":
+ return amount * 12;
+ case "cm":
+ return amount * 72 / 2.54;
+ case "mm":
+ return amount * 72 / 25.4;
+ default:
+ return amount;
+ }
+};
+
+const normalizeMarkerText = (marker: string) => marker.replace(/[\s\u00a0\u200b\u200e\u200f]+/g, "");
+
+const alphabeticOrdinal = (value: string) => {
+ let result = 0;
+ for (const character of value.toUpperCase()) {
+ result = result * 26 + character.charCodeAt(0) - 64;
+ }
+ return result;
+};
+
+const romanOrdinal = (value: string) => {
+ const values: Record<string, number> = {
+ I: 1,
+ V: 5,
+ X: 10,
+ L: 50,
+ C: 100,
+ D: 500,
+ M: 1000,
+ };
+ let result = 0;
+ let previous = 0;
+ for (const character of Array.from(value.toUpperCase()).reverse()) {
+ const current = values[character];
+ if (!current) {
+ return undefined;
+ }
+ if (current < previous) {
+ result -= current;
+ } else {
+ result += current;
+ previous = current;
+ }
+ }
+ return result;
+};
+
+export const parseOrderedMarker = (marker: string): OrderedMarker | undefined => {
+ const normalized = normalizeMarkerText(marker);
+ const match = normalized.match(/^(?:\(([^()]+)\)|([^().、]+)[.)、])$/);
+ const value = match?.[1] ?? match?.[2];
+ if (!value) {
+ return undefined;
+ }
+ if (/^\d+$/.test(value)) {
+ return {
+ ordinal: Number.parseInt(value, 10),
+ format: "number",
+ };
+ }
+ if (/^[a-z]$/i.test(value)) {
+ return {
+ ordinal: alphabeticOrdinal(value),
+ format: "letter",
+ };
+ }
+ if (/^[ivxlcdm]+$/i.test(value)) {
+ const ordinal = romanOrdinal(value);
+ return ordinal ? {ordinal, format: "roman"} : undefined;
+ }
+ if (/^[a-z]+$/i.test(value)) {
+ return {
+ ordinal: alphabeticOrdinal(value),
+ format: "letter",
+ };
+ }
+ return undefined;
+};
+
+export const detectTaskMarker = (marker: string, font: string): boolean | undefined => {
+ const normalized = normalizeMarkerText(marker);
+ if (UNCHECKED_TASK_MARKERS.has(normalized)) {
+ return false;
+ }
+ if (CHECKED_TASK_MARKERS.has(normalized)) {
+ return true;
+ }
+ if (/wingdings\s*2/i.test(font)) {
+ if (normalized === "£" || normalized === "\uF0A3") {
+ return false;
+ }
+ if (normalized === "P" || normalized === "\uF050" || normalized === "R" || normalized === "\uF052") {
+ return true;
+ }
+ return undefined;
+ }
+ if (/wingdings/i.test(font)) {
+ if (normalized === "p" || normalized === "\uF070" || normalized === "q" || normalized === "\uF071") {
+ return false;
+ }
+ if (normalized === "ü" || normalized === "\uF0FC") {
+ return true;
+ }
+ }
+ return undefined;
+};
+
+export const classifyWordMarker = (marker: string, font: string) => {
+ const checked = detectTaskMarker(marker, font);
+ if (checked !== undefined) {
+ return {type: "task" as const, checked};
+ }
+ const normalized = normalizeMarkerText(marker);
+ if (/wingdings|webdings|symbol|courier\s+new/i.test(font)) {
+ return normalized ? {type: "ul" as const} : undefined;
+ }
+ const ordered = parseOrderedMarker(normalized);
+ if (ordered) {
+ return {
+ type: "ol" as const,
+ markerOrdinal: ordered.ordinal,
+ };
+ }
+ if (normalized === "l" || normalized === "n" || UNORDERED_MARKERS.has(normalized) ||
+ (normalized.length === 1 && /[^\p{L}\p{N}]/u.test(normalized))) {
+ return {type: "ul" as const};
+ }
+ return undefined;
+};
+
+export const classifyPptMarker = (marker: string, font: string, specialFormat: "bullet" | "numbullet") => {
+ const checked = detectTaskMarker(marker, font);
+ if (checked !== undefined) {
+ return {type: "task" as const, checked};
+ }
+ if (specialFormat === "numbullet") {
+ return {
+ type: "ol" as const,
+ markerOrdinal: parseOrderedMarker(marker)?.ordinal,
+ };
+ }
+ return {type: "ul" as const};
+};
+
+export const groupConsecutiveOfficeListItems = <T>(items: Array<T | null | undefined>) => {
+ const groups: T[][] = [];
+ let current: T[] = [];
+ for (const item of items) {
+ if (item === null || item === undefined) {
+ if (current.length > 0) {
+ groups.push(current);
+ current = [];
+ }
+ } else {
+ current.push(item);
+ }
+ }
+ if (current.length > 0) {
+ groups.push(current);
+ }
+ return groups;
+};
+
+const compareLevels = (left: number, right: number) => {
+ if (Math.abs(left - right) < LEVEL_EPSILON) {
+ return 0;
+ }
+ return left < right ? -1 : 1;
+};
+
+const canContinueList = (list: OfficeListPlan, item: OfficeListModel, items: readonly OfficeListModel[]) => {
+ if (list.type !== item.type || list.identity !== item.identity) {
+ return false;
+ }
+ if (item.type !== "ol" || item.markerOrdinal === undefined || list.items.length === 0) {
+ return true;
+ }
+ const previous = items[list.items[list.items.length - 1].sourceIndex].markerOrdinal;
+ return previous === undefined || item.markerOrdinal === previous + 1;
+};
+
+const createPlan = (item: OfficeListModel): OfficeListPlan => ({
+ type: item.type,
+ identity: item.identity,
+ start: item.type === "ol" ? item.markerOrdinal : undefined,
+ items: [],
+});
+
+const appendPlanItem = (list: OfficeListPlan, sourceIndex: number, item: OfficeListModel) => {
+ list.items.push({
+ sourceIndex,
+ checked: item.checked,
+ children: [],
+ });
+};
+
+export const buildOfficeListPlan = (items: readonly OfficeListModel[]) => {
+ const roots: OfficeListPlan[] = [];
+ const stack: OfficeListFrame[] = [];
+
+ items.forEach((item, sourceIndex) => {
+ while (stack.length > 0 && compareLevels(item.level, stack[stack.length - 1].level) < 0) {
+ stack.pop();
+ }
+
+ if (stack.length === 0) {
+ const list = createPlan(item);
+ roots.push(list);
+ appendPlanItem(list, sourceIndex, item);
+ stack.push({container: roots, level: item.level, list});
+ return;
+ }
+
+ const top = stack[stack.length - 1];
+ const relation = compareLevels(item.level, top.level);
+ if (relation > 0) {
+ const parentItem = top.list.items[top.list.items.length - 1];
+ const container = parentItem.children;
+ let list = container[container.length - 1];
+ if (!list || !canContinueList(list, item, items)) {
+ list = createPlan(item);
+ container.push(list);
+ }
+ appendPlanItem(list, sourceIndex, item);
+ stack.push({container, level: item.level, list});
+ return;
+ }
+
+ if (canContinueList(top.list, item, items)) {
+ appendPlanItem(top.list, sourceIndex, item);
+ return;
+ }
+
+ const list = createPlan(item);
+ top.container.push(list);
+ appendPlanItem(list, sourceIndex, item);
+ stack[stack.length - 1] = {container: top.container, level: item.level, list};
+ });
+
+ return roots;
+};
+
+const isWordMarker = (element: Element) => {
+ const value = parseInlineStyle(element.getAttribute("style") ?? "")["mso-list"];
+ return /^ignore$/i.test(value?.trim() ?? "");
+};
+
+const markerFont = (marker: Element, item: Element) => {
+ const fonts: string[] = [];
+ Array.from(marker.querySelectorAll("[style]")).forEach(child => {
+ const style = parseInlineStyle(child.getAttribute("style") ?? "");
+ if (style["font-family"]) {
+ fonts.push(style["font-family"]);
+ }
+ if (style.font) {
+ fonts.push(style.font);
+ }
+ });
+ let current: Element | null = marker;
+ while (current) {
+ const style = parseInlineStyle(current.getAttribute("style") ?? "");
+ if (style["font-family"]) {
+ fonts.push(style["font-family"]);
+ }
+ if (style.font) {
+ fonts.push(style.font);
+ }
+ if (current === item) {
+ break;
+ }
+ current = current.parentElement;
+ }
+ return fonts.join(" ");
+};
+
+const styledDescendants = (element: Element) => Array.from(element.querySelectorAll("[style]"));
+
+const cloneWithoutMarkers = (element: Element, predicate: (item: Element) => boolean) => {
+ const clone = element.cloneNode(true) as Element;
+ styledDescendants(clone).filter(predicate).forEach(item => item.remove());
+ return clone;
+};
+
+const extractWordListItem = (element: Element): ExtractedOfficeListItem | undefined => {
+ const list = parseWordListStyle(element.getAttribute("style") ?? "");
+ if (!list) {
+ return undefined;
+ }
+ const marker = styledDescendants(element).find(isWordMarker);
+ if (!marker) {
+ return undefined;
+ }
+ const classification = classifyWordMarker(marker.textContent ?? "", markerFont(marker, element));
+ if (!classification) {
+ return undefined;
+ }
+ return {
+ element,
+ content: cloneWithoutMarkers(element, isWordMarker),
+ model: {
+ level: list.level,
+ identity: list.identity,
+ ...classification,
+ },
+ source: "word",
+ };
+};
+
+const extractPptListItem = (element: Element): ExtractedOfficeListItem | undefined => {
+ const style = parseInlineStyle(element.getAttribute("style") ?? "");
+ const level = style["margin-left"] === undefined ? undefined : parseCssLengthToPoints(style["margin-left"]);
+ if (level === undefined) {
+ return undefined;
+ }
+ const marker = styledDescendants(element).find(item => parsePptSpecialFormat(item.getAttribute("style") ?? "") !== undefined);
+ if (!marker) {
+ return undefined;
+ }
+ const specialFormat = parsePptSpecialFormat(marker.getAttribute("style") ?? "");
+ if (!specialFormat) {
+ return undefined;
+ }
+ const classification = classifyPptMarker(marker.textContent ?? "", markerFont(marker, element), specialFormat);
+ return {
+ element,
+ content: cloneWithoutMarkers(element, item => parsePptSpecialFormat(item.getAttribute("style") ?? "") !== undefined),
+ model: {
+ level,
+ identity: "ppt",
+ ...classification,
+ },
+ source: "ppt",
+ };
+};
+
+const extractOfficeListItem = (element: Element) => extractWordListItem(element) ?? extractPptListItem(element);
+
+const renderOfficeListPlans = (
+ doc: Document,
+ plans: readonly OfficeListPlan[],
+ items: readonly ExtractedOfficeListItem[],
+): DocumentFragment => {
+ const fragment = doc.createDocumentFragment();
+ for (const plan of plans) {
+ const list = doc.createElement(plan.type === "ol" ? "ol" : "ul");
+ if (plan.type === "task") {
+ list.setAttribute("data-type", "task");
+ } else if (plan.type === "ol" && plan.start !== undefined && plan.start !== 1) {
+ list.setAttribute("start", plan.start.toString());
+ }
+ for (const planItem of plan.items) {
+ const item = items[planItem.sourceIndex];
+ const listItem = doc.createElement("li");
+ if (plan.type === "task") {
+ const checkbox = doc.createElement("input");
+ checkbox.setAttribute("type", "checkbox");
+ if (planItem.checked) {
+ checkbox.setAttribute("checked", "checked");
+ }
+ listItem.classList.add("task-list-item");
+ listItem.appendChild(checkbox);
+ }
+ while (item.content.firstChild) {
+ listItem.appendChild(item.content.firstChild);
+ }
+ listItem.appendChild(renderOfficeListPlans(doc, planItem.children, items));
+ list.appendChild(listItem);
+ }
+ fragment.appendChild(list);
+ }
+ return fragment;
+};
+
+const shouldSkipContainer = (element: Element) => {
+ return element.tagName === "UL" || element.tagName === "OL" || element.tagName === "SCRIPT" || element.tagName === "STYLE";
+};
+
+const convertContainer = (container: Element, convertedSources: Set<OfficeListSource>) => {
+ const children = Array.from(container.children);
+ const extracted = children.map(extractOfficeListItem);
+ let convertedCount = 0;
+
+ children.forEach((child, index) => {
+ if (!extracted[index] && !shouldSkipContainer(child)) {
+ convertedCount += convertContainer(child, convertedSources);
+ }
+ });
+
+ for (const group of groupConsecutiveOfficeListItems(extracted)) {
+ const plans = buildOfficeListPlan(group.map(item => item.model));
+ const fragment = renderOfficeListPlans(container.ownerDocument, plans, group);
+ group[0].element.before(fragment);
+ for (const item of group) {
+ convertedSources.add(item.source);
+ item.element.remove();
+ convertedCount++;
+ }
+ }
+ return convertedCount;
+};
+
+export const convertOfficeLists = (html: string): OfficeListConversionResult => {
+ if (typeof DOMParser === "undefined" || !/mso-(?:list|special-format)\s*:/i.test(html)) {
+ return {html, convertedCount: 0};
+ }
+ try {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ const sources = new Set<OfficeListSource>();
+ const convertedCount = convertContainer(doc.body, sources);
+ if (convertedCount === 0) {
+ return {html, convertedCount};
+ }
+ return {
+ html: doc.body.innerHTML,
+ convertedCount,
+ source: sources.has("ppt") ? "ppt" : "word",
+ };
+ } catch (error) {
+ console.warn("convert office list failed", error);
+ return {html, convertedCount: 0};
+ }
+};
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index 6270081d27..ba76f978a8 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -26,6 +26,13 @@ import {refreshSbAndPersistWidth} from "../../block/util";
import {extractCrossBlockPasteContext, shouldPreservePastedBlockStructure} from "./pasteSource";
import {normalizePasteResponse} from "./pasteResponse";
import {applyLuteMarkdownSyntax} from "../render/luteMarkdownSyntax";
+import {convertOfficeLists} from "./officeList";
+import {
+ extractWPSPresentationClipboard,
+ getWPSPresentationFallback,
+ type IWPSPresentationClipboard,
+ shouldConvertWPSPresentation,
+} from "./wpsPresentation";
/// #if !BROWSER
import {ipcRenderer} from "electron";
/// #endif
@@ -489,6 +496,22 @@ const pasteCrossBlockRange = (protyle: IProtyle, tempElement: HTMLElement, range
return true;
};
+const insertConvertedBlockDOM = (protyle: IProtyle, dom: string) => {
+ insertHTML(dom, protyle, false, false, true);
+ protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
+ if (item.textContent === "") {
+ fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {
+ item.innerHTML = response.data;
+ });
+ }
+ });
+ blockRender(protyle, protyle.wysiwyg.element);
+ processRender(protyle.wysiwyg.element);
+ highlightRender(protyle.wysiwyg.element);
+ avRender(protyle.wysiwyg.element, protyle);
+ scrollCenter(protyle, undefined, "nearest", "smooth");
+};
+
export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEvent | IClipboardData) & {
target: HTMLElement
}, uploadOptions?: IUploadInsertOptions) => {
@@ -504,19 +527,28 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
let mathML = "";
let office = "";
let wps = "";
+ let wpsPresentation: IWPSPresentationClipboard | undefined;
+ let officeListConverted = false;
if ("clipboardData" in event) {
textHTML = event.clipboardData.getData("text/html");
textPlain = event.clipboardData.getData("text/plain");
siyuanHTML = event.clipboardData.getData("text/siyuan");
vscodeEditorData = event.clipboardData.getData("vscode-editor-data");
files = event.clipboardData.files;
+ wpsPresentation = extractWPSPresentationClipboard(event.clipboardData.types,
+ (type) => event.clipboardData.getData(type));
} else if ("dataTransfer" in event) {
textHTML = event.dataTransfer.getData("text/html");
textPlain = event.dataTransfer.getData("text/plain");
siyuanHTML = event.dataTransfer.getData("text/siyuan");
vscodeEditorData = event.dataTransfer.getData("vscode-editor-data");
+ wpsPresentation = extractWPSPresentationClipboard(event.dataTransfer.types,
+ (type) => event.dataTransfer.getData(type));
if (event.dataTransfer.types[0] === "Files") {
files = event.dataTransfer.items;
+ } else if (wpsPresentation && Array.from(event.dataTransfer.types).some((type) => type.toLowerCase() === "files")) {
+ // 混合的 DataTransferItemList 还包含字符串项,上传时仅保留文件
+ files = event.dataTransfer.files;
}
} else {
if (event.localFiles?.length > 0) {
@@ -549,7 +581,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}),
]);
}
- if (!siyuanHTML && !textHTML && !textPlain && ("clipboardData" in event)) {
+ if (!siyuanHTML && !textHTML && !textPlain && !wpsPresentation && ("clipboardData" in event)) {
const localFiles: ILocalFiles[] = await getLocalFiles();
if (localFiles.length > 0) {
readLocalFile(protyle, localFiles);
@@ -626,10 +658,20 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
mathML = "";
office = "";
wps = "";
+ wpsPresentation = undefined;
}
}
}
+ if (!siyuanHTML && textHTML) {
+ const officeList = convertOfficeLists(textHTML);
+ textHTML = officeList.html;
+ if (officeList.convertedCount > 0) {
+ officeListConverted = true;
+ originalTextHTML = textHTML;
+ }
+ }
+
// 插件可能替换完整剪贴板载荷,因此仅从最终保留的内部数据中读取层级上下文
const crossBlockPasteContext = siyuanHTML ? extractCrossBlockPasteContext(textHTML) : {
nestedList: false,
@@ -838,10 +880,33 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
}
hideElements(["hint"], protyle);
} else {
+ if (wpsPresentation && shouldConvertWPSPresentation(wpsPresentation, textHTML, siyuanHTML)) {
+ let response: IWebSocketData | undefined;
+ try {
+ response = await fetchSyncPost("/api/lute/wpsPresentation2BlockDOM", {
+ data: wpsPresentation.data,
+ text: textPlain,
+ type: wpsPresentation.type,
+ });
+ } catch (e) {
+ // 内核不可用时继续使用剪贴板中的纯文本或图片
+ }
+ const result = response?.data as { converted?: unknown, dom?: unknown };
+ if (response?.code === 0 && result?.converted === true && typeof result.dom === "string" && result.dom.trim() !== "") {
+ insertConvertedBlockDOM(protyle, result.dom);
+ return;
+ }
+ const fallback = getWPSPresentationFallback(wpsPresentation.type, Boolean(files?.length));
+ if (fallback === "files") {
+ uploadFiles(protyle, files, undefined, undefined, undefined, uploadOptions);
+ return;
+ }
+ files = [];
+ }
let isHTML = false;
if (textHTML.replace("<!--StartFragment--><!--EndFragment-->", "").trim() !== "") {
textHTML = textHTML.replace("<!--StartFragment-->", "").replace("<!--EndFragment-->", "").trim();
- if (files && files.length === 1 && (
+ if (!officeListConverted && files && files.length === 1 && (
textHTML.startsWith("<img") || // 浏览器上复制单个图片
(textHTML.startsWith("<table") && textHTML.indexOf("<img") > -1) // Excel 或者浏览器中复制带有图片的表格
)) {
@@ -934,19 +999,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
office,
wps,
}, (response) => {
- insertHTML(response.data, protyle, false, false, true);
- protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
- if (item.textContent === "") {
- fetchPost("/api/block/getRefText", {id: item.getAttribute("data-id")}, (response) => {
- item.innerHTML = response.data;
- });
- }
- });
- blockRender(protyle, protyle.wysiwyg.element);
- processRender(protyle.wysiwyg.element);
- highlightRender(protyle.wysiwyg.element);
- avRender(protyle.wysiwyg.element, protyle);
- scrollCenter(protyle, undefined, "nearest", "smooth");
+ insertConvertedBlockDOM(protyle, response.data);
});
return;
} else if (files && files.length > 0) {
diff --git a/app/src/protyle/util/wpsPresentation.test.ts b/app/src/protyle/util/wpsPresentation.test.ts
new file mode 100644
index 0000000000..82e1033b35
--- /dev/null
+++ b/app/src/protyle/util/wpsPresentation.test.ts
@@ -0,0 +1,67 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ extractWPSPresentationClipboard,
+ getWPSPresentationFallback,
+ parseWPSPresentationClipboard,
+ shouldConvertWPSPresentation,
+} from "./wpsPresentation";
+
+describe("WPS presentation clipboard", () => {
+ it("prefers texts and reads the original case-insensitive MIME type", () => {
+ const requested: string[] = [];
+ const payload = extractWPSPresentationClipboard(["WPS/OBJECTS", "Wps/Texts"], (type) => {
+ requested.push(type);
+ return type.toLowerCase() === "wps/texts" ? JSON.stringify({data: "texts-data"}) :
+ JSON.stringify({data: "objects-data"});
+ });
+
+ assert.deepEqual(payload, {data: "texts-data", type: "texts"});
+ assert.deepEqual(requested, ["Wps/Texts"]);
+ });
+
+ it("falls back to objects when texts is invalid", () => {
+ const payload = extractWPSPresentationClipboard(["wps/texts", "wps/objects"], (type) => {
+ return type === "wps/texts" ? "invalid" : JSON.stringify({data: "objects-data"});
+ });
+
+ assert.deepEqual(payload, {data: "objects-data", type: "objects"});
+ });
+
+ it("continues with objects when reading texts throws", () => {
+ const payload = extractWPSPresentationClipboard(["wps/texts", "wps/objects"], (type) => {
+ if (type === "wps/texts") {
+ throw new Error("denied");
+ }
+ return JSON.stringify({data: "objects-data"});
+ });
+
+ assert.deepEqual(payload, {data: "objects-data", type: "objects"});
+ });
+
+ it("rejects malformed, empty, and oversized payload data", () => {
+ assert.equal(parseWPSPresentationClipboard("invalid", "texts"), undefined);
+ assert.equal(parseWPSPresentationClipboard(JSON.stringify({data: 1}), "texts"), undefined);
+ assert.equal(parseWPSPresentationClipboard(JSON.stringify({data: " "}), "texts"), undefined);
+ assert.equal(parseWPSPresentationClipboard(JSON.stringify({data: "1234"}), "texts", 3), undefined);
+ assert.deepEqual(parseWPSPresentationClipboard(JSON.stringify({data: "123"}), "texts", 3), {
+ data: "123",
+ type: "texts",
+ });
+ });
+
+ it("converts only when external HTML and SiYuan HTML are absent", () => {
+ const payload = {data: "data", type: "texts"} as const;
+ assert.equal(shouldConvertWPSPresentation(payload, "", ""), true);
+ assert.equal(shouldConvertWPSPresentation(payload, " \n", "\t"), true);
+ assert.equal(shouldConvertWPSPresentation(payload, "<p>text</p>", ""), false);
+ assert.equal(shouldConvertWPSPresentation(payload, "", "<div data-type=\"NodeParagraph\"></div>"), false);
+ assert.equal(shouldConvertWPSPresentation(undefined, "", ""), false);
+ });
+
+ it("uses plain text for texts and files for objects when available", () => {
+ assert.equal(getWPSPresentationFallback("texts", true), "plainText");
+ assert.equal(getWPSPresentationFallback("objects", true), "files");
+ assert.equal(getWPSPresentationFallback("objects", false), "plainText");
+ });
+});
diff --git a/app/src/protyle/util/wpsPresentation.ts b/app/src/protyle/util/wpsPresentation.ts
new file mode 100644
index 0000000000..fa8da39eca
--- /dev/null
+++ b/app/src/protyle/util/wpsPresentation.ts
@@ -0,0 +1,62 @@
+const MAX_WPS_PRESENTATION_ARCHIVE_LENGTH = 8 * 1024 * 1024;
+
+export const MAX_WPS_PRESENTATION_DATA_LENGTH = Math.ceil(MAX_WPS_PRESENTATION_ARCHIVE_LENGTH / 3) * 4;
+
+const MAX_WPS_PRESENTATION_JSON_LENGTH = MAX_WPS_PRESENTATION_DATA_LENGTH + 64 * 1024;
+
+export type WPSPresentationClipboardType = "texts" | "objects";
+
+export interface IWPSPresentationClipboard {
+ data: string;
+ type: WPSPresentationClipboardType;
+}
+
+export const parseWPSPresentationClipboard = (json: string, type: WPSPresentationClipboardType,
+ maxDataLength = MAX_WPS_PRESENTATION_DATA_LENGTH) => {
+ if (!json || json.length > maxDataLength + 64 * 1024) {
+ return;
+ }
+ try {
+ const payload = JSON.parse(json) as { data?: unknown };
+ if (typeof payload.data !== "string" || payload.data.trim() === "" || payload.data.length > maxDataLength) {
+ return;
+ }
+ return {
+ data: payload.data,
+ type,
+ } as IWPSPresentationClipboard;
+ } catch (e) {
+ return;
+ }
+};
+
+export const extractWPSPresentationClipboard = (types: ArrayLike<string>, getData: (type: string) => string) => {
+ const availableTypes = Array.from(types);
+ for (const type of ["texts", "objects"] as WPSPresentationClipboardType[]) {
+ const mime = availableTypes.find((item) => item.toLowerCase() === `wps/${type}`);
+ if (!mime) {
+ continue;
+ }
+ try {
+ const json = getData(mime);
+ if (json.length > MAX_WPS_PRESENTATION_JSON_LENGTH) {
+ continue;
+ }
+ const payload = parseWPSPresentationClipboard(json, type);
+ if (payload) {
+ return payload;
+ }
+ } catch (e) {
+ // 剪贴板可能拒绝读取自定义格式,继续尝试其他格式
+ }
+ }
+};
+
+export const shouldConvertWPSPresentation = (payload: IWPSPresentationClipboard | undefined,
+ textHTML: string, siyuanHTML: string) => {
+ return Boolean(payload && textHTML.trim() === "" && siyuanHTML.trim() === "");
+};
+
+export const getWPSPresentationFallback = (type: WPSPresentationClipboardType, hasFiles: boolean) => {
+ return type === "objects" && hasFiles ? "files" : "plainText";
+};
diff --git a/kernel/api/lute_wps_presentation.go b/kernel/api/lute_wps_presentation.go
new file mode 100644
index 0000000000..183a8f2d67
--- /dev/null
+++ b/kernel/api/lute_wps_presentation.go
@@ -0,0 +1,830 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ archivezip "archive/zip"
+ "bytes"
+ "encoding/base64"
+ "encoding/xml"
+ stdhtml "html"
+ "io"
+ "net/http"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/88250/gulu"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const (
+ maxWPSPresentationArchiveEntries = 256
+ maxWPSPresentationDrawingEntries = 32
+ maxWPSPresentationEntryBytes = 8 * 1024 * 1024
+ maxWPSPresentationDrawingBytes = 4 * 1024 * 1024
+ maxWPSPresentationUncompressed = 32 * 1024 * 1024
+ maxWPSPresentationXMLTokens = 200000
+ maxWPSPresentationXMLDepth = 128
+ maxWPSPresentationParagraphs = 4096
+ maxWPSPresentationTextBytes = 1024 * 1024
+ maxWPSPresentationOutputBytes = 2 * 1024 * 1024
+ maxWPSPresentationRequestBytes = 13 * 1024 * 1024
+ maxWPSPresentationOrderedListStart = 32767
+ drawingMLNamespace = "http://schemas.openxmlformats.org/drawingml/2006/main"
+ drawingMLStrictNamespace = "http://purl.oclc.org/ooxml/drawingml/main"
+ presentationMLNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main"
+ presentationMLStrictNamespace = "http://purl.oclc.org/ooxml/presentationml/main"
+)
+
+type wpsPresentationConversionResult struct {
+ Converted bool `json:"converted"`
+ DOM string `json:"dom"`
+}
+
+type wpsPresentationBulletKind uint8
+
+const (
+ wpsPresentationBulletNone wpsPresentationBulletKind = iota
+ wpsPresentationBulletUnordered
+ wpsPresentationBulletOrdered
+ wpsPresentationBulletTask
+)
+
+type wpsPresentationBulletChoice struct {
+ set bool
+ kind wpsPresentationBulletKind
+ char string
+ checked bool
+ numType string
+ start int
+ startSet bool
+}
+
+type wpsPresentationParagraphProperties struct {
+ bullet wpsPresentationBulletChoice
+ font string
+ fontSet bool
+}
+
+type wpsPresentationParagraph struct {
+ text string
+ textParts []string
+ level int
+ properties wpsPresentationParagraphProperties
+}
+
+type wpsPresentationContainer struct {
+ defaultProperties wpsPresentationParagraphProperties
+ levelProperties [9]wpsPresentationParagraphProperties
+ paragraphs []wpsPresentationParagraph
+}
+
+type wpsPresentationParseLimits struct {
+ paragraphs int
+ textBytes int
+ tokens int
+}
+
+type wpsPresentationDrawing struct {
+ index int
+ file *archivezip.File
+}
+
+type wpsPresentationArchive struct {
+ containers []wpsPresentationContainer
+ drawingCount int
+ mixedObject bool
+}
+
+type wpsPresentationDrawingContent struct {
+ containers []wpsPresentationContainer
+ mixedObject bool
+}
+
+type wpsPresentationHTMLBlock struct {
+ paragraph *string
+ list *wpsPresentationHTMLList
+}
+
+type wpsPresentationHTMLList struct {
+ kind wpsPresentationBulletKind
+ numType string
+ start int
+ next int
+ items []*wpsPresentationHTMLListItem
+}
+
+type wpsPresentationHTMLListItem struct {
+ text string
+ checked bool
+ children []*wpsPresentationHTMLList
+}
+
+type wpsPresentationListStackEntry struct {
+ rawLevel int
+ list *wpsPresentationHTMLList
+}
+
+func wpsPresentation2BlockDOM(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ result := &wpsPresentationConversionResult{}
+ ret.Data = result
+ defer c.JSON(http.StatusOK, ret)
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxWPSPresentationRequestBytes)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var encoded, text, clipboardType string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("data", &encoded, true, true),
+ util.BindJsonArg("text", &text, false, false),
+ util.BindJsonArg("type", &clipboardType, true, true)) {
+ return
+ }
+ if clipboardType != "texts" && clipboardType != "objects" {
+ return
+ }
+
+ result.DOM, result.Converted = convertWPSPresentation(encoded, text, clipboardType)
+}
+
+func convertWPSPresentation(encoded, text, clipboardType string) (dom string, converted bool) {
+ htmlContent, converted := wpsPresentationHTML(encoded, text, clipboardType)
+ if !converted {
+ return "", false
+ }
+
+ luteEngine := util.NewLute()
+ luteEngine.SetHTMLTag2TextMark(true)
+ dom = luteEngine.HTML2BlockDOM(htmlContent)
+ if dom == "" || len(dom) > maxWPSPresentationOutputBytes || !strings.Contains(dom, "data-node-id=") {
+ return "", false
+ }
+ return dom, true
+}
+
+func wpsPresentationHTML(encoded, text, clipboardType string) (htmlContent string, converted bool) {
+ if clipboardType != "texts" && clipboardType != "objects" {
+ return "", false
+ }
+ if encoded == "" || len(encoded) > base64.StdEncoding.EncodedLen(maxWPSClipboardBytes) ||
+ len(text) > maxWPSPresentationTextBytes {
+ return "", false
+ }
+
+ data, err := base64.StdEncoding.Strict().DecodeString(encoded)
+ if err != nil || len(data) == 0 || len(data) > maxWPSClipboardBytes {
+ return "", false
+ }
+ archive, err := parseWPSPresentationArchive(data)
+ if err != nil || len(archive.containers) == 0 {
+ return "", false
+ }
+ if clipboardType == "objects" &&
+ (archive.drawingCount != 1 || len(archive.containers) != 1 || archive.mixedObject) {
+ return "", false
+ }
+ if clipboardType == "texts" {
+ if text == "" || wpsPresentationNormalizedText(archive.containers) != normalizeWPSClipboardText(text) {
+ return "", false
+ }
+ }
+
+ var builder strings.Builder
+ convertedItems := 0
+ for _, container := range archive.containers {
+ blocks, count := buildWPSPresentationHTMLBlocks(container)
+ convertedItems += count
+ for _, block := range blocks {
+ renderWPSPresentationHTMLBlock(&builder, block)
+ if builder.Len() > maxWPSPresentationOutputBytes {
+ return "", false
+ }
+ }
+ }
+ if convertedItems == 0 {
+ return "", false
+ }
+ return builder.String(), true
+}
+
+func parseWPSPresentationArchive(data []byte) (wpsPresentationArchive, error) {
+ archive, err := archivezip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return wpsPresentationArchive{}, err
+ }
+ if len(archive.File) == 0 || len(archive.File) > maxWPSPresentationArchiveEntries {
+ return wpsPresentationArchive{}, io.ErrUnexpectedEOF
+ }
+
+ var totalUncompressed uint64
+ var drawings []wpsPresentationDrawing
+ drawingIndexes := map[int]struct{}{}
+ for _, file := range archive.File {
+ if file.UncompressedSize64 > maxWPSPresentationEntryBytes ||
+ totalUncompressed > maxWPSPresentationUncompressed-file.UncompressedSize64 {
+ return wpsPresentationArchive{}, io.ErrUnexpectedEOF
+ }
+ totalUncompressed += file.UncompressedSize64
+
+ index, ok := wpsPresentationDrawingIndex(file.Name)
+ if !ok {
+ continue
+ }
+ if file.UncompressedSize64 > maxWPSPresentationDrawingBytes || len(drawings) >= maxWPSPresentationDrawingEntries {
+ return wpsPresentationArchive{}, io.ErrUnexpectedEOF
+ }
+ if _, exists := drawingIndexes[index]; exists {
+ return wpsPresentationArchive{}, io.ErrUnexpectedEOF
+ }
+ drawingIndexes[index] = struct{}{}
+ drawings = append(drawings, wpsPresentationDrawing{index: index, file: file})
+ }
+ if len(drawings) == 0 {
+ return wpsPresentationArchive{}, io.EOF
+ }
+ sort.Slice(drawings, func(i, j int) bool {
+ return drawings[i].index < drawings[j].index
+ })
+
+ limits := &wpsPresentationParseLimits{}
+ var containers []wpsPresentationContainer
+ mixedObject := false
+ for _, drawing := range drawings {
+ reader, openErr := drawing.file.Open()
+ if openErr != nil {
+ return wpsPresentationArchive{}, openErr
+ }
+ drawingXML, readErr := io.ReadAll(io.LimitReader(reader, maxWPSPresentationDrawingBytes+1))
+ closeErr := reader.Close()
+ if readErr != nil {
+ return wpsPresentationArchive{}, readErr
+ }
+ if closeErr != nil {
+ return wpsPresentationArchive{}, closeErr
+ }
+ if len(drawingXML) > maxWPSPresentationDrawingBytes {
+ return wpsPresentationArchive{}, io.ErrUnexpectedEOF
+ }
+ parsed, parseErr := parseWPSPresentationDrawing(drawingXML, limits)
+ if parseErr != nil {
+ return wpsPresentationArchive{}, parseErr
+ }
+ containers = append(containers, parsed.containers...)
+ mixedObject = mixedObject || parsed.mixedObject
+ }
+ return wpsPresentationArchive{containers: containers, drawingCount: len(drawings), mixedObject: mixedObject}, nil
+}
+
+func wpsPresentationDrawingIndex(name string) (int, bool) {
+ const prefix = "clipboard/drawings/drawing"
+ const suffix = ".xml"
+ if !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, suffix) {
+ return 0, false
+ }
+ digits := name[len(prefix) : len(name)-len(suffix)]
+ if digits == "" {
+ return 0, false
+ }
+ for _, char := range digits {
+ if char < '0' || '9' < char {
+ return 0, false
+ }
+ }
+ index, err := strconv.Atoi(digits)
+ if err != nil {
+ return 0, false
+ }
+ return index, true
+}
+
+func parseWPSPresentationDrawing(data []byte, limits *wpsPresentationParseLimits) (wpsPresentationDrawingContent, error) {
+ decoder := xml.NewDecoder(bytes.NewReader(data))
+ var elementStack []xml.Name
+ var containers []wpsPresentationContainer
+ var container *wpsPresentationContainer
+ containerDepth := -1
+ lstStyleDepth := -1
+ var paragraph *wpsPresentationParagraph
+ paragraphDepth := -1
+ var properties *wpsPresentationParagraphProperties
+ propertiesDepth := -1
+ textDepth := -1
+ presentationShapeCount := 0
+ drawingShapeCount := 0
+ drawingTextShapeCount := 0
+ mixedObject := false
+
+ for {
+ token, err := decoder.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return wpsPresentationDrawingContent{}, err
+ }
+ limits.tokens++
+ if limits.tokens > maxWPSPresentationXMLTokens {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+
+ switch element := token.(type) {
+ case xml.StartElement:
+ parent := xml.Name{}
+ if 0 < len(elementStack) {
+ parent = elementStack[len(elementStack)-1]
+ }
+ elementStack = append(elementStack, element.Name)
+ depth := len(elementStack)
+ if depth > maxWPSPresentationXMLDepth {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ if textDepth != -1 {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+
+ if isPresentationMLElement(element.Name, "sp") {
+ presentationShapeCount++
+ mixedObject = mixedObject || 1 < presentationShapeCount
+ } else if isDrawingMLElement(element.Name, "sp") {
+ drawingShapeCount++
+ mixedObject = mixedObject || 1 < drawingShapeCount
+ } else if isDrawingMLElement(element.Name, "txSp") {
+ drawingTextShapeCount++
+ mixedObject = mixedObject || 1 < drawingTextShapeCount
+ } else if isUnsupportedWPSPresentationObject(element.Name) {
+ mixedObject = true
+ }
+
+ if isPresentationTextBody(element.Name) {
+ if container != nil {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ container = &wpsPresentationContainer{}
+ containerDepth = depth
+ continue
+ }
+ if container == nil || !isDrawingMLNamespace(element.Name.Space) {
+ continue
+ }
+
+ switch element.Name.Local {
+ case "lstStyle":
+ if isPresentationTextBody(parent) {
+ lstStyleDepth = depth
+ }
+ case "defPPr":
+ if lstStyleDepth == depth-1 && isDrawingMLElement(parent, "lstStyle") {
+ properties = &container.defaultProperties
+ propertiesDepth = depth
+ }
+ case "p":
+ if isPresentationTextBody(parent) {
+ if paragraph != nil || limits.paragraphs >= maxWPSPresentationParagraphs {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ paragraph = &wpsPresentationParagraph{}
+ paragraphDepth = depth
+ limits.paragraphs++
+ }
+ case "pPr":
+ if paragraph != nil && paragraphDepth == depth-1 && isDrawingMLElement(parent, "p") {
+ level, parseErr := wpsPresentationParagraphLevel(element.Attr)
+ if parseErr != nil {
+ return wpsPresentationDrawingContent{}, parseErr
+ }
+ paragraph.level = level
+ properties = &paragraph.properties
+ propertiesDepth = depth
+ }
+ case "buNone", "buChar", "buAutoNum", "buBlip":
+ if properties != nil && propertiesDepth == depth-1 {
+ if properties.bullet.set {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ bullet, parseErr := parseWPSPresentationBullet(element)
+ if parseErr != nil {
+ return wpsPresentationDrawingContent{}, parseErr
+ }
+ properties.bullet = bullet
+ }
+ case "buFont":
+ if properties != nil && propertiesDepth == depth-1 {
+ font := strings.TrimSpace(wpsPresentationXMLAttribute(element.Attr, "typeface"))
+ if font != "" {
+ properties.font = font
+ properties.fontSet = true
+ }
+ }
+ case "buFontTx":
+ if properties != nil && propertiesDepth == depth-1 {
+ properties.font = ""
+ properties.fontSet = true
+ }
+ case "t":
+ if paragraph != nil {
+ if textDepth != -1 {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ textDepth = depth
+ }
+ case "br":
+ if paragraph != nil && isDrawingMLElement(parent, "p") {
+ if err = appendWPSPresentationText(paragraph, "\n", limits); err != nil {
+ return wpsPresentationDrawingContent{}, err
+ }
+ }
+ case "tab":
+ if paragraph != nil {
+ if err = appendWPSPresentationText(paragraph, "\t", limits); err != nil {
+ return wpsPresentationDrawingContent{}, err
+ }
+ }
+ default:
+ if lstStyleDepth == depth-1 && isDrawingMLElement(parent, "lstStyle") {
+ if level, ok := wpsPresentationStyleLevel(element.Name.Local); ok {
+ properties = &container.levelProperties[level]
+ propertiesDepth = depth
+ }
+ }
+ }
+ case xml.CharData:
+ if paragraph != nil && textDepth != -1 {
+ if err = appendWPSPresentationText(paragraph, string(element), limits); err != nil {
+ return wpsPresentationDrawingContent{}, err
+ }
+ }
+ case xml.EndElement:
+ depth := len(elementStack)
+ if depth == 0 || elementStack[depth-1] != element.Name {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ if textDepth == depth && isDrawingMLElement(element.Name, "t") {
+ textDepth = -1
+ }
+ if propertiesDepth == depth {
+ properties = nil
+ propertiesDepth = -1
+ }
+ if paragraphDepth == depth && isDrawingMLElement(element.Name, "p") {
+ paragraph.text = strings.Join(paragraph.textParts, "")
+ paragraph.textParts = nil
+ container.paragraphs = append(container.paragraphs, *paragraph)
+ paragraph = nil
+ paragraphDepth = -1
+ }
+ if lstStyleDepth == depth && isDrawingMLElement(element.Name, "lstStyle") {
+ lstStyleDepth = -1
+ }
+ if containerDepth == depth && isPresentationTextBody(element.Name) {
+ containers = append(containers, *container)
+ container = nil
+ containerDepth = -1
+ }
+ elementStack = elementStack[:depth-1]
+ case xml.Directive:
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ case xml.ProcInst:
+ if element.Target != "xml" || len(elementStack) != 0 {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ }
+ }
+ if len(elementStack) != 0 || container != nil || paragraph != nil || textDepth != -1 {
+ return wpsPresentationDrawingContent{}, io.ErrUnexpectedEOF
+ }
+ return wpsPresentationDrawingContent{containers: containers, mixedObject: mixedObject}, nil
+}
+
+func isDrawingMLNamespace(namespace string) bool {
+ return namespace == drawingMLNamespace || namespace == drawingMLStrictNamespace
+}
+
+func isDrawingMLElement(name xml.Name, local string) bool {
+ return name.Local == local && isDrawingMLNamespace(name.Space)
+}
+
+func isPresentationTextBody(name xml.Name) bool {
+ return isPresentationMLElement(name, "txBody") || isDrawingMLElement(name, "txBody")
+}
+
+func isPresentationMLElement(name xml.Name, local string) bool {
+ return name.Local == local && (name.Space == presentationMLNamespace || name.Space == presentationMLStrictNamespace)
+}
+
+func isUnsupportedWPSPresentationObject(name xml.Name) bool {
+ switch name.Local {
+ case "pic", "graphicFrame", "grpSp", "cxnSp", "contentPart":
+ return isPresentationMLElement(name, name.Local) || isDrawingMLElement(name, name.Local)
+ }
+ return false
+}
+
+func wpsPresentationXMLAttribute(attributes []xml.Attr, name string) string {
+ for _, attribute := range attributes {
+ if attribute.Name.Space == "" && attribute.Name.Local == name {
+ return attribute.Value
+ }
+ }
+ return ""
+}
+
+func wpsPresentationParagraphLevel(attributes []xml.Attr) (int, error) {
+ value := wpsPresentationXMLAttribute(attributes, "lvl")
+ if value == "" {
+ return 0, nil
+ }
+ level, err := strconv.Atoi(value)
+ if err != nil || level < 0 || 8 < level {
+ return 0, io.ErrUnexpectedEOF
+ }
+ return level, nil
+}
+
+func wpsPresentationStyleLevel(name string) (int, bool) {
+ if !strings.HasPrefix(name, "lvl") || !strings.HasSuffix(name, "pPr") {
+ return 0, false
+ }
+ value := name[len("lvl") : len(name)-len("pPr")]
+ level, err := strconv.Atoi(value)
+ if err != nil || level < 1 || 9 < level {
+ return 0, false
+ }
+ return level - 1, true
+}
+
+func parseWPSPresentationBullet(element xml.StartElement) (wpsPresentationBulletChoice, error) {
+ bullet := wpsPresentationBulletChoice{set: true}
+ switch element.Name.Local {
+ case "buNone":
+ bullet.kind = wpsPresentationBulletNone
+ case "buChar":
+ char := wpsPresentationXMLAttribute(element.Attr, "char")
+ if char == "" {
+ return wpsPresentationBulletChoice{}, io.ErrUnexpectedEOF
+ }
+ bullet.kind = wpsPresentationBulletUnordered
+ bullet.char = char
+ case "buAutoNum":
+ bullet.kind = wpsPresentationBulletOrdered
+ bullet.numType = strings.TrimSpace(wpsPresentationXMLAttribute(element.Attr, "type"))
+ if value := wpsPresentationXMLAttribute(element.Attr, "startAt"); value != "" {
+ start, err := strconv.Atoi(value)
+ if err != nil || start < 1 || maxWPSPresentationOrderedListStart < start {
+ return wpsPresentationBulletChoice{}, io.ErrUnexpectedEOF
+ }
+ bullet.start = start
+ bullet.startSet = true
+ }
+ case "buBlip":
+ bullet.kind = wpsPresentationBulletUnordered
+ default:
+ return wpsPresentationBulletChoice{}, io.ErrUnexpectedEOF
+ }
+ return bullet, nil
+}
+
+func appendWPSPresentationText(paragraph *wpsPresentationParagraph, value string, limits *wpsPresentationParseLimits) error {
+ if len(value) > maxWPSPresentationTextBytes-limits.textBytes {
+ return io.ErrUnexpectedEOF
+ }
+ limits.textBytes += len(value)
+ paragraph.textParts = append(paragraph.textParts, value)
+ return nil
+}
+
+func wpsPresentationNormalizedText(containers []wpsPresentationContainer) string {
+ var builder strings.Builder
+ for _, container := range containers {
+ for _, paragraph := range container.paragraphs {
+ builder.WriteString(paragraph.text)
+ }
+ }
+ return normalizeWPSClipboardText(builder.String())
+}
+
+func resolveWPSPresentationBullet(container wpsPresentationContainer, paragraph wpsPresentationParagraph) wpsPresentationBulletChoice {
+ properties := []wpsPresentationParagraphProperties{
+ paragraph.properties,
+ container.levelProperties[paragraph.level],
+ container.defaultProperties,
+ }
+ bullet := wpsPresentationBulletChoice{}
+ font := ""
+ fontResolved := false
+ for _, candidate := range properties {
+ if !bullet.set && candidate.bullet.set {
+ bullet = candidate.bullet
+ }
+ if !fontResolved && candidate.fontSet {
+ font = candidate.font
+ fontResolved = true
+ }
+ }
+ if !bullet.set {
+ bullet = wpsPresentationBulletChoice{set: true, kind: wpsPresentationBulletNone}
+ }
+ if bullet.kind == wpsPresentationBulletUnordered {
+ if checked, task := wpsPresentationTaskMarker(bullet.char, font); task {
+ bullet.kind = wpsPresentationBulletTask
+ bullet.checked = checked
+ }
+ }
+ return bullet
+}
+
+func wpsPresentationTaskMarker(char, font string) (checked, task bool) {
+ if char == "" {
+ return false, false
+ }
+ runes := []rune(char)
+ if len(runes) != 1 {
+ return false, false
+ }
+ marker := runes[0]
+ switch marker {
+ case '\u25a1', '\u2610':
+ return false, true
+ case '\u2714', '\u2713', '\u2611', '\u2612':
+ return true, true
+ }
+
+ font = strings.TrimSpace(font)
+ if strings.EqualFold(font, "Wingdings 2") {
+ switch marker {
+ case '\u00a3', '\uf0a3':
+ return false, true
+ case 'P', '\uf050', 'R', '\uf052':
+ return true, true
+ }
+ }
+ if strings.EqualFold(font, "Wingdings") {
+ switch marker {
+ case 'p', '\uf070', 'q', '\uf071':
+ return false, true
+ case '\u00fc', '\uf0fc':
+ return true, true
+ }
+ }
+ return false, false
+}
+
+func buildWPSPresentationHTMLBlocks(container wpsPresentationContainer) ([]wpsPresentationHTMLBlock, int) {
+ paragraphs := container.paragraphs
+ for 0 < len(paragraphs) && strings.TrimSpace(paragraphs[len(paragraphs)-1].text) == "" {
+ paragraphs = paragraphs[:len(paragraphs)-1]
+ }
+
+ var blocks []wpsPresentationHTMLBlock
+ var stack []wpsPresentationListStackEntry
+ convertedItems := 0
+ for _, paragraph := range paragraphs {
+ if strings.TrimSpace(paragraph.text) == "" && !paragraph.properties.bullet.set {
+ text := ""
+ blocks = append(blocks, wpsPresentationHTMLBlock{paragraph: &text})
+ stack = nil
+ continue
+ }
+ bullet := resolveWPSPresentationBullet(container, paragraph)
+ if bullet.kind == wpsPresentationBulletNone {
+ text := paragraph.text
+ blocks = append(blocks, wpsPresentationHTMLBlock{paragraph: &text})
+ stack = nil
+ continue
+ }
+
+ for 0 < len(stack) && paragraph.level < stack[len(stack)-1].rawLevel {
+ if len(stack) == 1 {
+ stack[0].rawLevel = paragraph.level
+ break
+ }
+ if 1 < len(stack) && stack[len(stack)-2].rawLevel < paragraph.level {
+ stack[len(stack)-1].rawLevel = paragraph.level
+ break
+ }
+ stack = stack[:len(stack)-1]
+ }
+ if 0 < len(stack) && stack[len(stack)-1].rawLevel == paragraph.level &&
+ !canContinueWPSPresentationList(stack[len(stack)-1].list, bullet, paragraph.properties.bullet.startSet) {
+ stack = stack[:len(stack)-1]
+ }
+
+ var list *wpsPresentationHTMLList
+ if 0 < len(stack) && stack[len(stack)-1].rawLevel == paragraph.level {
+ list = stack[len(stack)-1].list
+ } else {
+ start := 1
+ if bullet.startSet {
+ start = bullet.start
+ }
+ list = &wpsPresentationHTMLList{kind: bullet.kind, numType: bullet.numType, start: start, next: start}
+ if len(stack) == 0 {
+ blocks = append(blocks, wpsPresentationHTMLBlock{list: list})
+ } else {
+ parentItems := stack[len(stack)-1].list.items
+ if len(parentItems) == 0 {
+ text := paragraph.text
+ blocks = append(blocks, wpsPresentationHTMLBlock{paragraph: &text})
+ stack = nil
+ continue
+ }
+ parent := parentItems[len(parentItems)-1]
+ parent.children = append(parent.children, list)
+ }
+ stack = append(stack, wpsPresentationListStackEntry{rawLevel: paragraph.level, list: list})
+ }
+
+ list.items = append(list.items, &wpsPresentationHTMLListItem{text: paragraph.text, checked: bullet.checked})
+ list.next++
+ convertedItems++
+ }
+ return blocks, convertedItems
+}
+
+func canContinueWPSPresentationList(list *wpsPresentationHTMLList, bullet wpsPresentationBulletChoice, paragraphStartSet bool) bool {
+ if list.kind != bullet.kind {
+ return false
+ }
+ if bullet.kind == wpsPresentationBulletOrdered && list.numType != bullet.numType {
+ return false
+ }
+ return bullet.kind != wpsPresentationBulletOrdered || !paragraphStartSet || bullet.start == list.next
+}
+
+func renderWPSPresentationHTMLBlock(builder *strings.Builder, block wpsPresentationHTMLBlock) {
+ if block.paragraph != nil {
+ builder.WriteString("<p>")
+ if *block.paragraph == "" {
+ builder.WriteString("<br>")
+ } else {
+ renderWPSPresentationText(builder, *block.paragraph)
+ }
+ builder.WriteString("</p>")
+ return
+ }
+ if block.list != nil {
+ renderWPSPresentationHTMLList(builder, block.list)
+ }
+}
+
+func renderWPSPresentationHTMLList(builder *strings.Builder, list *wpsPresentationHTMLList) {
+ tag := "ul"
+ if list.kind == wpsPresentationBulletOrdered {
+ tag = "ol"
+ }
+ builder.WriteByte('<')
+ builder.WriteString(tag)
+ if tag == "ol" && list.start != 1 {
+ builder.WriteString(` start="`)
+ builder.WriteString(strconv.Itoa(list.start))
+ builder.WriteByte('"')
+ }
+ builder.WriteByte('>')
+ for _, item := range list.items {
+ builder.WriteString("<li>")
+ if list.kind == wpsPresentationBulletTask {
+ builder.WriteString(`<input type="checkbox"`)
+ if item.checked {
+ builder.WriteString(" checked")
+ }
+ builder.WriteByte('>')
+ }
+ renderWPSPresentationText(builder, item.text)
+ for _, child := range item.children {
+ renderWPSPresentationHTMLList(builder, child)
+ }
+ builder.WriteString("</li>")
+ }
+ builder.WriteString("</")
+ builder.WriteString(tag)
+ builder.WriteByte('>')
+}
+
+func renderWPSPresentationText(builder *strings.Builder, text string) {
+ parts := strings.Split(text, "\n")
+ for index, part := range parts {
+ if 0 < index {
+ builder.WriteString("<br>")
+ }
+ builder.WriteString(stdhtml.EscapeString(part))
+ }
+}
diff --git a/kernel/api/lute_wps_presentation_test.go b/kernel/api/lute_wps_presentation_test.go
new file mode 100644
index 0000000000..41f7dc0e93
--- /dev/null
+++ b/kernel/api/lute_wps_presentation_test.go
@@ -0,0 +1,367 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ archivezip "archive/zip"
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ stdhtml "html"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+type wpsPresentationTestArchiveEntry struct {
+ name string
+ data string
+}
+
+func TestWPSPresentationUnorderedTexts(t *testing.T) {
+ style := `<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr><a:lvl2pPr><a:buChar char="◦"/></a:lvl2pPr>`
+ paragraphs := strings.Join([]string{
+ wpsPresentationTestParagraph(0, `<a:buNone/>`, "无序列表"),
+ wpsPresentationTestParagraph(0, "", "1<&"),
+ wpsPresentationTestParagraph(1, "", "甲"),
+ wpsPresentationTestParagraph(1, "", "乙"),
+ wpsPresentationTestParagraph(0, "", "2"),
+ }, "")
+ drawing := wpsPresentationTestDrawing(style, paragraphs, "")
+ encoded := buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawingEx.xml", data: `<invalid/>`},
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: drawing})
+
+ htmlContent, converted := wpsPresentationHTML(encoded, "无序列表\r\n1<&\r\n甲\r\n乙\r\n2\r\n", "texts")
+ expected := `<p>无序列表</p><ul><li>1&lt;&amp;<ul><li>甲</li><li>乙</li></ul></li><li>2</li></ul>`
+ if !converted || htmlContent != expected {
+ t.Fatalf("unexpected conversion: converted=%v\n got: %s\nwant: %s", converted, htmlContent, expected)
+ }
+ if _, converted = wpsPresentationHTML(encoded, "不匹配", "texts"); converted {
+ t.Fatal("mismatched plain text must not be converted")
+ }
+ renamedPrefixDrawing := strings.ReplaceAll(strings.ReplaceAll(drawing, "a:", "d:"), "xmlns:a=", "xmlns:d=")
+ renamedPrefix := buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: renamedPrefixDrawing})
+ if renamedHTML, ok := wpsPresentationHTML(renamedPrefix, "无序列表\n1<&\n甲\n乙\n2", "texts"); !ok || renamedHTML != expected {
+ t.Fatalf("namespace prefix rename changed conversion: converted=%v html=%s", ok, renamedHTML)
+ }
+
+ dom, converted := convertWPSPresentation(encoded, "无序列表\n1<&\n甲\n乙\n2", "texts")
+ if !converted || !strings.Contains(dom, `data-subtype="u"`) || !strings.Contains(dom, "甲") {
+ t.Fatalf("unexpected BlockDOM: converted=%v dom=%s", converted, dom)
+ }
+}
+
+func TestWPSPresentationOrderedOverrideAndSkippedLevel(t *testing.T) {
+ style := `<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr><a:lvl2pPr><a:buChar char="•"/></a:lvl2pPr><a:lvl3pPr><a:buChar char="•"/></a:lvl3pPr>`
+ paragraphs := strings.Join([]string{
+ wpsPresentationTestParagraph(0, `<a:buNone/>`, "有序列表"),
+ wpsPresentationTestParagraph(0, `<a:buAutoNum type="arabicPeriod" startAt="3"/>`, "A"),
+ wpsPresentationTestParagraph(2, `<a:buAutoNum type="arabicPeriod"/>`, "B"),
+ wpsPresentationTestParagraph(1, `<a:buAutoNum type="arabicPeriod"/>`, "C"),
+ wpsPresentationTestParagraph(0, `<a:buAutoNum type="arabicPeriod"/>`, "D"),
+ wpsPresentationTestParagraph(0, `<a:buAutoNum type="romanUcPeriod"/>`, "E"),
+ }, "")
+ encoded := buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: wpsPresentationTestDrawing(style, paragraphs, "")})
+
+ htmlContent, converted := wpsPresentationHTML(encoded, "", "objects")
+ expected := `<p>有序列表</p><ol start="3"><li>A<ol><li>B</li><li>C</li></ol></li><li>D</li></ol><ol><li>E</li></ol>`
+ if !converted || htmlContent != expected {
+ t.Fatalf("unexpected skipped-level conversion: converted=%v\n got: %s\nwant: %s", converted, htmlContent, expected)
+ }
+ if strings.Contains(htmlContent, `<li>A<ol><li>B</li></ol><ol>`) {
+ t.Fatalf("skipped levels produced adjacent child lists: %s", htmlContent)
+ }
+}
+
+func TestWPSPresentationTaskMarkers(t *testing.T) {
+ style := `<a:lvl1pPr><a:buFont typeface="Wingdings 2"/><a:buChar char="£"/></a:lvl1pPr><a:lvl2pPr><a:buChar char="☑"/></a:lvl2pPr>`
+ paragraphs := strings.Join([]string{
+ wpsPresentationTestParagraph(0, `<a:buNone/>`, "任务列表"),
+ wpsPresentationTestParagraph(0, "", "未完成"),
+ wpsPresentationTestParagraph(1, "", "已完成一"),
+ wpsPresentationTestParagraph(0, `<a:buFont typeface="Wingdings"/><a:buChar char="ü"/>`, "已完成二"),
+ }, "")
+ encoded := buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: wpsPresentationTestDrawing(style, paragraphs, "")})
+
+ htmlContent, converted := wpsPresentationHTML(encoded, "", "objects")
+ expected := `<p>任务列表</p><ul><li><input type="checkbox">未完成<ul><li><input type="checkbox" checked>已完成一</li></ul></li><li><input type="checkbox" checked>已完成二</li></ul>`
+ if !converted || htmlContent != expected {
+ t.Fatalf("unexpected task conversion: converted=%v\n got: %s\nwant: %s", converted, htmlContent, expected)
+ }
+ dom, converted := convertWPSPresentation(encoded, "", "objects")
+ if !converted || !strings.Contains(dom, `data-subtype="t"`) || !strings.Contains(dom, `data-task="X"`) {
+ t.Fatalf("unexpected task BlockDOM: converted=%v dom=%s", converted, dom)
+ }
+
+ tests := []struct {
+ marker rune
+ font string
+ checked bool
+ }{
+ {marker: '□'}, {marker: '☐'},
+ {marker: '✔', checked: true}, {marker: '✓', checked: true}, {marker: '☑', checked: true},
+ {marker: '☒', checked: true},
+ {marker: '£', font: "Wingdings 2"}, {marker: '\uf0a3', font: "Wingdings 2"},
+ {marker: 'P', font: "Wingdings 2", checked: true}, {marker: '\uf050', font: "Wingdings 2", checked: true},
+ {marker: 'R', font: "Wingdings 2", checked: true}, {marker: '\uf052', font: "Wingdings 2", checked: true},
+ {marker: 'p', font: "Wingdings"}, {marker: '\uf070', font: "Wingdings"},
+ {marker: 'q', font: "Wingdings"}, {marker: '\uf071', font: "Wingdings"},
+ {marker: 'ü', font: "Wingdings", checked: true}, {marker: '\uf0fc', font: "Wingdings", checked: true},
+ }
+ for _, test := range tests {
+ checked, task := wpsPresentationTaskMarker(string(test.marker), test.font)
+ if !task || checked != test.checked {
+ t.Errorf("unexpected marker mapping: marker=%U font=%q checked=%v task=%v", test.marker, test.font, checked, task)
+ }
+ }
+ if _, task := wpsPresentationTaskMarker("P", ""); task {
+ t.Fatal("font-dependent marker must not be inferred without its bullet font")
+ }
+}
+
+func TestWPSPresentationEmptyParagraphs(t *testing.T) {
+ style := `<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr>`
+ paragraphs := strings.Join([]string{
+ wpsPresentationTestParagraph(0, "", "A"),
+ wpsPresentationTestParagraph(0, "", ""),
+ wpsPresentationTestParagraph(0, "", "B"),
+ wpsPresentationTestParagraph(0, `<a:buChar char="•"/>`, ""),
+ wpsPresentationTestParagraph(0, "", "C"),
+ wpsPresentationTestParagraph(0, "", ""),
+ }, "")
+ encoded := buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: wpsPresentationTestDrawing(style, paragraphs, "")})
+
+ htmlContent, converted := wpsPresentationHTML(encoded, "", "objects")
+ expected := `<ul><li>A</li></ul><p><br></p><ul><li>B</li><li></li><li>C</li></ul>`
+ if !converted || htmlContent != expected {
+ t.Fatalf("unexpected empty paragraph conversion: converted=%v\n got: %s\nwant: %s", converted, htmlContent, expected)
+ }
+}
+
+func TestWPSPresentationObjectGuards(t *testing.T) {
+ style := `<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr>`
+ paragraph := wpsPresentationTestParagraph(0, "", "A")
+ drawing := wpsPresentationTestDrawing(style, paragraph, "")
+
+ tests := []struct {
+ name string
+ entries []wpsPresentationTestArchiveEntry
+ }{
+ {
+ name: "multiple drawings",
+ entries: []wpsPresentationTestArchiveEntry{
+ {name: "clipboard/drawings/drawing1.xml", data: drawing},
+ {name: "clipboard/drawings/drawing2.xml", data: drawing},
+ },
+ },
+ {
+ name: "multiple text bodies",
+ entries: []wpsPresentationTestArchiveEntry{{
+ name: "clipboard/drawings/drawing1.xml",
+ data: `<a:graphic xmlns:a="` + drawingMLNamespace + `">` +
+ wpsPresentationTestTextBody(style, paragraph) + wpsPresentationTestTextBody(style, paragraph) + `</a:graphic>`,
+ }},
+ },
+ {
+ name: "mixed picture object",
+ entries: []wpsPresentationTestArchiveEntry{{
+ name: "clipboard/drawings/drawing1.xml",
+ data: wpsPresentationTestDrawing(style, paragraph, `<a:pic/>`),
+ }},
+ },
+ {
+ name: "multiple DrawingML shapes",
+ entries: []wpsPresentationTestArchiveEntry{{
+ name: "clipboard/drawings/drawing1.xml",
+ data: wpsPresentationTestDrawing(style, paragraph, `<a:sp/>`),
+ }},
+ },
+ {
+ name: "extension drawing only",
+ entries: []wpsPresentationTestArchiveEntry{{name: "clipboard/drawings/drawingEx.xml", data: drawing}},
+ },
+ {
+ name: "namespace spoofing",
+ entries: []wpsPresentationTestArchiveEntry{{
+ name: "clipboard/drawings/drawing1.xml",
+ data: `<txBody><lstStyle><lvl1pPr><buChar char="•"/></lvl1pPr></lstStyle><p><pPr lvl="0"/><r><t>A</t></r></p></txBody>`,
+ }},
+ },
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ encoded := buildWPSPresentationTestArchive(t, test.entries...)
+ if _, converted := wpsPresentationHTML(encoded, "", "objects"); converted {
+ t.Fatal("complex or untrusted object must fall back to its preview image")
+ }
+ })
+ }
+
+ for _, name := range []string{
+ "clipboard/drawings/drawing.xml",
+ "clipboard/drawings/drawingEx.xml",
+ "clipboard/drawings/drawing1.xml/extra",
+ "clipboard/drawing1.xml",
+ } {
+ if _, ok := wpsPresentationDrawingIndex(name); ok {
+ t.Errorf("unexpected drawing path match: %q", name)
+ }
+ }
+ if index, ok := wpsPresentationDrawingIndex("clipboard/drawings/drawing12.xml"); !ok || index != 12 {
+ t.Fatalf("expected numeric drawing path, got index=%d ok=%v", index, ok)
+ }
+}
+
+func TestWPSPresentationSafetyLimits(t *testing.T) {
+ if _, converted := wpsPresentationHTML("not-base64", "", "objects"); converted {
+ t.Fatal("invalid base64 must not be converted")
+ }
+
+ entries := make([]wpsPresentationTestArchiveEntry, maxWPSPresentationArchiveEntries+1)
+ for index := range entries {
+ entries[index] = wpsPresentationTestArchiveEntry{name: "entry" + strconv.Itoa(index), data: "x"}
+ }
+ entries[0] = wpsPresentationTestArchiveEntry{
+ name: "clipboard/drawings/drawing1.xml",
+ data: wpsPresentationTestDrawing(`<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr>`,
+ wpsPresentationTestParagraph(0, "", "A"), ""),
+ }
+ if _, converted := wpsPresentationHTML(buildWPSPresentationTestArchive(t, entries...), "", "objects"); converted {
+ t.Fatal("archive entry limit must reject the payload")
+ }
+
+ oversized := strings.Repeat("x", maxWPSPresentationEntryBytes+1)
+ if _, converted := wpsPresentationHTML(buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "large.bin", data: oversized},
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: "<invalid/>"}), "", "objects"); converted {
+ t.Fatal("single-entry size limit must reject the payload")
+ }
+
+ deep := `<a:x xmlns:a="` + drawingMLNamespace + `">` + strings.Repeat(`<a:x>`, maxWPSPresentationXMLDepth) +
+ strings.Repeat(`</a:x>`, maxWPSPresentationXMLDepth) + `</a:x>`
+ if _, converted := wpsPresentationHTML(buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: deep}), "", "objects"); converted {
+ t.Fatal("XML depth limit must reject the payload")
+ }
+
+ largeText := strings.Repeat("&", maxWPSPresentationOutputBytes/5+1)
+ largeDrawing := wpsPresentationTestDrawing(`<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr>`,
+ wpsPresentationTestParagraph(0, "", largeText), "")
+ if _, converted := wpsPresentationHTML(buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: largeDrawing}), "", "objects"); converted {
+ t.Fatal("generated HTML size limit must reject the payload")
+ }
+}
+
+func TestWPSPresentationRequestBodyLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.POST("/api/lute/wpsPresentation2BlockDOM", wpsPresentation2BlockDOM)
+ recorder := httptest.NewRecorder()
+ body := strings.NewReader(`{"data":"` + strings.Repeat("A", maxWPSPresentationRequestBytes) + `","type":"objects"}`)
+ request := httptest.NewRequest(http.MethodPost, "/api/lute/wpsPresentation2BlockDOM", body)
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ var response struct {
+ Code int `json:"code"`
+ Data struct {
+ Converted bool `json:"converted"`
+ } `json:"data"`
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code == 0 || response.Data.Converted {
+ t.Fatalf("oversized request body was not rejected: %s", recorder.Body.String())
+ }
+}
+
+func TestWPSPresentationHandler(t *testing.T) {
+ style := `<a:lvl1pPr><a:buChar char="•"/></a:lvl1pPr>`
+ drawing := wpsPresentationTestDrawing(style, wpsPresentationTestParagraph(0, "", "A"), "")
+ encoded := buildWPSPresentationTestArchive(t,
+ wpsPresentationTestArchiveEntry{name: "clipboard/drawings/drawing1.xml", data: drawing})
+ body, err := json.Marshal(map[string]string{"data": encoded, "text": "", "type": "objects"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.POST("/api/lute/wpsPresentation2BlockDOM", wpsPresentation2BlockDOM)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "/api/lute/wpsPresentation2BlockDOM", bytes.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+
+ var response struct {
+ Code int `json:"code"`
+ Data struct {
+ Converted bool `json:"converted"`
+ DOM string `json:"dom"`
+ } `json:"data"`
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code != 0 || !response.Data.Converted || !strings.Contains(response.Data.DOM, `data-subtype="u"`) {
+ t.Fatalf("unexpected handler response: %s", recorder.Body.String())
+ }
+}
+
+func wpsPresentationTestDrawing(style, paragraphs, extra string) string {
+ return `<a:graphic xmlns:a="` + drawingMLNamespace + `"><a:sp/>` + extra + `<a:txSp>` +
+ wpsPresentationTestTextBody(style, paragraphs) + `</a:txSp></a:graphic>`
+}
+
+func wpsPresentationTestTextBody(style, paragraphs string) string {
+ return `<a:txBody><a:bodyPr/><a:lstStyle>` + style + `</a:lstStyle>` + paragraphs + `</a:txBody>`
+}
+
+func wpsPresentationTestParagraph(level int, bullet, text string) string {
+ return `<a:p><a:pPr lvl="` + strconv.Itoa(level) + `">` + bullet + `</a:pPr><a:r><a:t>` +
+ stdhtml.EscapeString(text) + `</a:t></a:r></a:p>`
+}
+
+func buildWPSPresentationTestArchive(t *testing.T, entries ...wpsPresentationTestArchiveEntry) string {
+ t.Helper()
+ var buffer bytes.Buffer
+ writer := archivezip.NewWriter(&buffer)
+ for _, entry := range entries {
+ file, err := writer.Create(entry.name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = file.Write([]byte(entry.data)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return base64.StdEncoding.EncodeToString(buffer.Bytes())
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 762c45915f..00a28af599 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -217,6 +217,7 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/lute/spinBlockDOM", model.CheckAuth, model.CheckAdminRole, spinBlockDOM)
ginServer.Handle("POST", "/api/lute/html2BlockDOM", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, html2BlockDOM)
+ ginServer.Handle("POST", "/api/lute/wpsPresentation2BlockDOM", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, wpsPresentation2BlockDOM)
ginServer.Handle("POST", "/api/lute/copyStdMarkdown", model.CheckAuth, copyStdMarkdown)
ginServer.Handle("POST", "/api/lute/md2html", model.CheckAuth, md2HTML)