Skip to content

Commit 8cc7e84

Browse files
committed
Each code block in a section uses its own fold key and rerender entry
1 parent 7d60aeb commit 8cc7e84

5 files changed

Lines changed: 136 additions & 67 deletions

File tree

‎main.js‎

Lines changed: 41 additions & 41 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/ReadingView/CodeBlockRenderer.ts‎

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import CodeBlockCustomizerPlugin from "../main";
55
import { CodeblockCustomizerSettings, FoldingScope } from "../Settings";
66
import { DEFAULT_COLLAPSE_TEXT, fadeOutLineCount } from "../Const";
77
import { FoldCommand, FoldingState } from "../EditorView/EditorEffects";
8-
import { createButtons, toggleFold, extractLinesFromHTML, attachEventListeners, renderCodeBlockLines, CodeBlockData, extractCodeBlocksFromSection, extractCodeBlocksFromAdmonition, reassignFadeOutClasses, getHtmlCodeBlockData, prepareHtmlCodeElement } from "./ReadingViewUtils";
8+
import { createButtons, toggleFold, extractLinesFromHTML, attachEventListeners, renderCodeBlockLines, CodeBlockData, extractCodeBlocksFromSection, extractCodeBlocksFromAdmonition, reassignFadeOutClasses, getHtmlCodeBlockData, prepareHtmlCodeElement, getBlockLine } from "./ReadingViewUtils";
99
import { CBCParameters, getAllParameters } from "../Parsing";
1010
import { countHtmlCodeElements, findHtmlCodeBlocks, isHtmlCodeBlockStart } from "../HtmlCodeBlocks";
1111

@@ -64,12 +64,12 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
6464

6565
this.allPreElements = [preElement];
6666

67-
const charPos = this.getCharPos(allFileLines);
67+
const charPos = this.getCharPos(allFileLines, sectionInfo.lineStart);
6868
const blockData: CodeBlockData = {
6969
firstLine: firstLine,
7070
contentLines: contentLines,
71-
startLine: sectionInfo.lineStart,
72-
endLine: sectionInfo.lineEnd
71+
startLine: 0,
72+
endLine: sectionInfo.lineEnd - sectionInfo.lineStart
7373
};
7474
await this.processSingleCodeBlock(preElement, blockData, { charPos, isPrinting: false });
7575
}// renderExternal
@@ -196,9 +196,7 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
196196
return;
197197
}
198198

199-
const charPos = this.getCharPos(fileContentLines);
200-
201-
await this.processCodeBlockFirstLines(allBlocks, charPos);
199+
await this.processCodeBlockFirstLines(allBlocks, fileContentLines);
202200
}// processCodeBlockSection
203201

204202
private isHtmlCodeBlockSection(firstLine: string | undefined) {
@@ -232,13 +230,9 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
232230
}
233231
}// getFileContentLines
234232

235-
private getCharPos(fileContentLines: string[]) {
236-
if (!this.codeBlockSectionInfo) {
237-
return -1;
238-
}
239-
233+
private getCharPos(fileContentLines: string[], line: number) {
240234
let charPos = 0;
241-
for (let i = 0; i < this.codeBlockSectionInfo.lineStart; i++) {
235+
for (let i = 0; i < line; i++) {
242236
if (typeof fileContentLines[i] !== 'string') {
243237
console.error(`Inconsistent data for file ${this.context.sourcePath}. Could not calculate character position.`);
244238
charPos = -1;
@@ -250,8 +244,8 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
250244
return charPos !== -1 ? charPos : undefined;
251245
}// getCharPos
252246

253-
private async processCodeBlockFirstLines(allBlocks: CodeBlockData[], charPos?: number) {
254-
if (!this.allPreElements) {
247+
private async processCodeBlockFirstLines(allBlocks: CodeBlockData[], fileContentLines: string[]) {
248+
if (!this.allPreElements || !this.codeBlockSectionInfo) {
255249
return;
256250
}
257251

@@ -261,17 +255,19 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
261255
}
262256

263257
for (const [key, preElement] of this.allPreElements.entries()) {
264-
const isRerenderQueued = this.codeBlockSectionInfo && this.plugin.rerenderQueue.has(this.codeBlockSectionInfo.lineStart + (allBlocks[key]?.firstLineOffset ?? 0));
265-
266-
if (preElement.classList.contains('codeblock-customizer-pre') && !isRerenderQueued) {
258+
const currentBlock = allBlocks[key];
259+
if (!currentBlock) {
267260
continue;
268261
}
269262

270-
const currentBlock = allBlocks[key];
271-
if (!currentBlock) {
263+
const blockLine = getBlockLine(this.codeBlockSectionInfo.lineStart, currentBlock);
264+
const isRerenderQueued = this.plugin.rerenderQueue.has(this.plugin.getRerenderKey(this.context.sourcePath, blockLine));
265+
266+
if (preElement.classList.contains('codeblock-customizer-pre') && !isRerenderQueued) {
272267
continue;
273268
}
274269

270+
const charPos = this.getCharPos(fileContentLines, blockLine);
275271
await this.processSingleCodeBlock(preElement, currentBlock, { charPos, isPrinting: false });
276272
}
277273
}// processCodeBlockFirstLines
@@ -325,7 +321,7 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
325321
let firstLine = codeBlockFirstLine;
326322
let isRerender = isParameterRerender;
327323
// for HTML code blocks the editor uses the line of the opening <code> tag as the first line (it can be after the <pre> line)
328-
const lineStart = this.codeBlockSectionInfo ? this.codeBlockSectionInfo.lineStart + (blockData.firstLineOffset ?? 0) : undefined;
324+
const lineStart = this.codeBlockSectionInfo ? getBlockLine(this.codeBlockSectionInfo.lineStart, blockData) : undefined;
329325

330326
if (!isPrinting && lineStart !== undefined) {
331327
const result = this.handleRerenderOverride(lineStart, codeBlockFirstLine, isParameterRerender);
@@ -384,16 +380,17 @@ export class CodeBlockRenderer extends MarkdownRenderChild {
384380
let firstLine = initialFirstLine;
385381
let isRerender = initialIsRerender;
386382

387-
const override = this.plugin.rerenderQueue.get(lineStart);
383+
const queueKey = this.plugin.getRerenderKey(this.context.sourcePath, lineStart);
384+
const override = this.plugin.rerenderQueue.get(queueKey);
388385
if (override) {
389386
isRerender = true;
390387
firstLine = override.content;
391388
const newCount = override.count - 1;
392389

393390
if (newCount > 0) {
394-
this.plugin.rerenderQueue.set(lineStart, { content: override.content, count: newCount });
391+
this.plugin.rerenderQueue.set(queueKey, { content: override.content, count: newCount });
395392
} else {
396-
this.plugin.rerenderQueue.delete(lineStart);
393+
this.plugin.rerenderQueue.delete(queueKey);
397394
}
398395
}
399396

‎src/ReadingView/ReadingViewUtils.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1798,6 +1798,10 @@ export function extractCodeBlocksFromSection(lines: string[]): CodeBlockData[] {
17981798
return extractCodeBlocks(lines, { stripCalloutMarkers: true, handleIndentedBlocks: true });
17991799
}// extractCodeBlocksFromSection
18001800

1801+
export function getBlockLine(sectionLineStart: number, block: CodeBlockData): number {
1802+
return sectionLineStart + (block.firstLineOffset ?? block.startLine);
1803+
}// getBlockLine
1804+
18011805
// the code lines of an HTML code block are taken from the rendered element, and wrapped in fence lines like the lines of a fenced code block
18021806
// the code is taken from the source, not from the rendered element (which might be already processed, e.g. when rerendering)
18031807
export function getHtmlCodeBlockData(block: HtmlCodeBlock, getLine: (index: number) => string): CodeBlockData {

‎src/main.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ export default class CodeBlockCustomizerPlugin extends Plugin {
7979
tabStoreReading: StateStore<string, number> = new StateStore(false, String);
8080
debounceTimer: number | null = null;
8181
foldCommandTrigger: { command: FoldCommand; path: string } | null = null;
82-
rerenderQueue: Map<number, { content: string; count: number }> = new Map();
82+
rerenderQueue: Map<string, { content: string; count: number }> = new Map();
8383
rerenderDebounceTimers: Map<number, NodeJS.Timeout> = new Map();
8484
modifiedBlocks: Map<string, string> = new Map();
8585
executeCodeObservers: WeakMap<HTMLElement, MutationObserver> = new WeakMap();
@@ -630,6 +630,10 @@ export default class CodeBlockCustomizerPlugin extends Plugin {
630630
}, 100);
631631
}// renderReadingView
632632

633+
getRerenderKey(path: string, line: number): string {
634+
return `${path}|${line}`;
635+
}// getRerenderKey
636+
633637
getFoldCommand(path: string): FoldCommand {
634638
return this.foldCommandTrigger?.path === path ? this.foldCommandTrigger.command : FoldCommand.Default;
635639
}// getFoldCommand
@@ -832,7 +836,7 @@ export default class CodeBlockCustomizerPlugin extends Plugin {
832836

833837
if (targets.length > 0) {
834838
if (newParametersLine !== undefined) {
835-
this.rerenderQueue.set(lineStart, { content: newParametersLine, count: targets.length });
839+
this.rerenderQueue.set(this.getRerenderKey(file.path, lineStart), { content: newParametersLine, count: targets.length });
836840
}
837841

838842
for (const target of targets) {

‎tests/readingViewBlocks.test.cjs‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/* eslint-disable @typescript-eslint/no-require-imports -- Use Node built-in test runner with bundled TypeScript helpers. */
2+
const { test } = require('node:test');
3+
const assert = require('node:assert/strict');
4+
const { load } = require('./helpers/load.cjs');
5+
6+
const { extractCodeBlocksFromSection, getBlockLine, getHtmlCodeBlockData, findHtmlCodeBlocks } = load('src/ReadingView/ReadingViewUtils.ts', 'src/HtmlCodeBlocks.ts');
7+
8+
test('blocks of a list section get their own line, not the section start', () => {
9+
const section = [
10+
'- item one',
11+
' ```python title:"A"',
12+
' a',
13+
' ```',
14+
'- item two',
15+
' ```js',
16+
' b',
17+
' ```',
18+
];
19+
const blocks = extractCodeBlocksFromSection(section);
20+
21+
assert.deepEqual(blocks.map(b => [b.firstLine, b.startLine, b.endLine]), [['```python title:"A"', 1, 3], ['```js', 5, 7]]);
22+
// the section starts on file line 10, the editor queues edits under the fence lines 11 and 15
23+
assert.deepEqual(blocks.map(b => getBlockLine(10, b)), [11, 15]);
24+
});
25+
26+
test('blocks of a callout section get their own line', () => {
27+
const section = [
28+
'> [!note]',
29+
'> text',
30+
'> ```python hl:1',
31+
'> x',
32+
'> ```',
33+
];
34+
const blocks = extractCodeBlocksFromSection(section);
35+
36+
assert.equal(blocks.length, 1);
37+
assert.equal(blocks[0].firstLine, '```python hl:1');
38+
assert.deepEqual(blocks[0].contentLines, ['```python hl:1', 'x', '```']);
39+
assert.equal(getBlockLine(3, blocks[0]), 5);
40+
});
41+
42+
test('a standalone block keeps the section start as its line (remembered folds stay valid)', () => {
43+
const fenced = extractCodeBlocksFromSection(['```cpp fold', 'int a;', '```']);
44+
const indented = extractCodeBlocksFromSection([' int a;', ' int b;']);
45+
46+
assert.equal(getBlockLine(7, fenced[0]), 7);
47+
assert.equal(indented[0].isIndentedBlock, true);
48+
assert.equal(getBlockLine(7, indented[0]), 7);
49+
});
50+
51+
test('HTML blocks use the line of the opening <code> tag, like the editor', () => {
52+
const section = [
53+
'<pre>',
54+
'<code class="language-python">x = 1',
55+
'</code>',
56+
'</pre>',
57+
];
58+
const [block] = findHtmlCodeBlocks(i => section[i], section.length);
59+
const data = getHtmlCodeBlockData(block, i => section[i]);
60+
61+
assert.equal(data.startLine, 0);
62+
assert.equal(data.firstLineOffset, 1);
63+
assert.equal(getBlockLine(20, data), 21);
64+
});

0 commit comments

Comments
 (0)