Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions desktop/src/shared/lib/remarkSpoilers.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,24 @@ test("remarkSpoilers: groups block nodes between delimiter paragraphs", () => {
assert.equal(tree.children[1].children[0].children[0].type, "image");
});

test("remarkSpoilers: leaves collapsed GFM table separators as text", () => {
const value =
"| Time | Purpose ||---:|---|| 0:00 | Frame strategy || 3:30 | Orient the board |";
const tree = runPlugin({
type: "root",
children: [{ type: "paragraph", children: [{ type: "text", value }] }],
});

assert.equal(
tree.children[0].children.some((child) => child.type === "spoiler"),
false,
);
assert.equal(
tree.children[0].children.map((child) => child.value ?? "").join(""),
value,
);
});

test("remarkSpoilers: leaves unmatched delimiters as text", () => {
const tree = runPlugin({
type: "root",
Expand Down
25 changes: 22 additions & 3 deletions desktop/src/shared/lib/remarkSpoilers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,29 @@ function transformNode(node: Node) {
transformNode(child);
}

node.children = groupBlockSpoilers(groupSpoilers(node.children));
node.children = groupBlockSpoilers(
groupSpoilers(node.children, node.type === "paragraph"),
);
}

function groupSpoilers(children: Node[]): Node[] {
function groupSpoilers(
children: Node[],
rejectTableDelimiterRow: boolean,
): Node[] {
const output: Node[] = [];
let spoilerBuffer: Node[] | null = null;

for (const part of splitDelimiterParts(children)) {
if (part.type === "delimiter") {
if (spoilerBuffer) {
output.push(buildSpoilerNode(spoilerBuffer));
if (rejectTableDelimiterRow && isTableDelimiterRow(spoilerBuffer)) {
output.push({ type: "text", value: "||" }, ...spoilerBuffer, {
type: "text",
value: "||",
});
} else {
output.push(buildSpoilerNode(spoilerBuffer));
}
spoilerBuffer = null;
} else {
spoilerBuffer = [];
Expand Down Expand Up @@ -100,6 +112,13 @@ function splitDelimiterParts(children: Node[]): Part[] {
return parts;
}

function isTableDelimiterRow(children: Node[]): boolean {
if (children.some((child) => child.type !== "text")) return false;

const value = children.map((child) => String(child.value ?? "")).join("");
return /^\s*:?-{3,}:?(?:\s*\|\s*:?-{3,}:?)+\s*$/.test(value);
}

function buildSpoilerNode(
children: Node[],
options: { block?: boolean } = {},
Expand Down
Loading