merong-docs 0.1.11 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/OVERVIEW.md +19 -19
  2. package/OVERVIEW.zh-CN.md +19 -22
  3. package/README.md +77 -77
  4. package/README.zh-CN.md +81 -81
  5. package/client/android-file-share.ts +25 -25
  6. package/client/controls.tsx +163 -163
  7. package/client/document-panel.tsx +166 -166
  8. package/client/external-file.tsx +78 -78
  9. package/client/file-reader.tsx +43 -43
  10. package/client/markdown-panel.tsx +737 -737
  11. package/client/markdown-scroll.ts +122 -122
  12. package/client/messages.ts +224 -224
  13. package/client/native-contacts.ts +145 -145
  14. package/client/page-render-queue.ts +12 -12
  15. package/client/page-selection.tsx +227 -227
  16. package/client/page-tools.tsx +72 -72
  17. package/client/pdf-geometry.ts +96 -96
  18. package/client/pdf-panel.tsx +477 -477
  19. package/client/reader-find.tsx +190 -190
  20. package/client/reader-notice.tsx +46 -46
  21. package/client/settings.tsx +143 -143
  22. package/client/syntax.tsx +55 -55
  23. package/client/viewport-geometry.ts +61 -61
  24. package/client/web.ts +462 -462
  25. package/client/worksheet-panel.tsx +631 -631
  26. package/client/zoom-controls.tsx +140 -140
  27. package/index.client.tsx +36 -36
  28. package/index.server.ts +73 -73
  29. package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
  30. package/node_modules/yaml/bin.mjs +0 -0
  31. package/npm-shrinkwrap.json +2 -2
  32. package/package.json +1 -1
  33. package/scripts/prepare-office.mjs +20 -20
  34. package/server/engine.ts +89 -89
  35. package/server/external-file.ts +42 -42
  36. package/server/generated/document-worker.ts +1 -1
  37. package/server/generated/rust-reader_bg.wasm +0 -0
  38. package/server/markdown-index.ts +305 -305
  39. package/server/markdown-links.ts +51 -51
  40. package/server/markdown-page.ts +120 -120
  41. package/server/office-fonts.cjs +824 -824
  42. package/server/office-location.ts +41 -41
  43. package/server/office-preview.ts +186 -186
  44. package/server/office-worker.cjs +49 -49
  45. package/server/office-xml.ts +79 -79
  46. package/server/pdf-engine.ts +168 -168
  47. package/server/pdf-text-geometry.ts +60 -60
  48. package/server/rust-reader.ts +40 -40
  49. package/server/structured-document.ts +69 -69
  50. package/server/text-search.ts +15 -15
  51. package/server/worker-entry.ts +42 -42
  52. package/server/worker-protocol.ts +38 -38
  53. package/server/worksheet.ts +67 -67
  54. package/server/workspace-file.ts +63 -63
  55. package/shared/contracts.ts +187 -187
  56. package/shared/file-limits.ts +5 -5
  57. package/shared/markdown-constants.ts +4 -4
  58. package/shared/markdown-math.ts +198 -198
  59. package/shared/markdown-references.ts +83 -83
  60. package/shared/markdown-source-location.ts +8 -8
  61. package/shared/reader-settings.ts +15 -15
  62. package/shared/reader-shortcuts.ts +132 -132
  63. package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
@@ -1,198 +1,198 @@
1
- import MarkdownIt from "markdown-it";
2
- import { maxFormulaLength } from "./markdown-constants";
3
-
4
- export const markdownParser = new MarkdownIt({ html: true });
5
- export const possibleMath = /[$]|\\[([]|(?:`{3,}|~{3,})[ \t]*math\b/i;
6
-
7
- interface SourceRange {
8
- start: number;
9
- end: number;
10
- }
11
-
12
- interface FormulaSpan extends SourceRange {
13
- tex: string;
14
- block: boolean;
15
- }
16
-
17
- interface OpaqueBlock extends SourceRange {
18
- formula?: FormulaSpan;
19
- }
20
-
21
- interface MarkdownStructure {
22
- opaqueBlocks: OpaqueBlock[];
23
- standaloneParagraphs: Set<string>;
24
- }
25
-
26
- function sourceRangeKey(start: number, end: number) {
27
- return `${start}:${end}`;
28
- }
29
-
30
- export function lineOffsets(source: string): number[] {
31
- const offsets = [0];
32
- for (let index = 0; index < source.length; index++) {
33
- const code = source.charCodeAt(index);
34
- if (code === 10) offsets.push(index + 1);
35
- else if (code === 13) {
36
- if (source.charCodeAt(index + 1) === 10) index++;
37
- offsets.push(index + 1);
38
- }
39
- }
40
- offsets.push(source.length);
41
- return offsets;
42
- }
43
-
44
- function markdownStructure(source: string): MarkdownStructure {
45
- const offsets = lineOffsets(source);
46
- const tokens = markdownParser.parse(source, {});
47
- const opaqueBlocks: OpaqueBlock[] = [];
48
- const standaloneParagraphs = new Set<string>();
49
- for (const [index, token] of tokens.entries()) {
50
- if (token.type === "inline" && token.map && tokens[index - 1]?.type === "paragraph_open") {
51
- const [firstLine, endLine] = token.map;
52
- if (endLine - firstLine <= 1) {
53
- let start = offsets[firstLine];
54
- let end = offsets[endLine];
55
- while (start < end && /\s/.test(source[start])) start++;
56
- while (end > start && /\s/.test(source[end - 1])) end--;
57
- if (start < end) standaloneParagraphs.add(sourceRangeKey(start, end));
58
- }
59
- }
60
- if (!token.map || (token.type !== "fence" && token.type !== "code_block" && token.type !== "html_block")) continue;
61
- const start = offsets[token.map[0]];
62
- const end = offsets[token.map[1]];
63
- if (
64
- token.type === "fence" &&
65
- token.info.trim().toLowerCase() === "math" &&
66
- token.map[1] - token.map[0] >= 3 &&
67
- /^\s*(?:`{3,}|~{3,})\s*math\b/i.test(source.slice(start, offsets[token.map[0] + 1]))
68
- ) {
69
- const closingLine = source.slice(offsets[token.map[1] - 1], end).replace(/(?:\r\n|\r|\n)$/, "");
70
- const marker = /^ {0,3}(`+|~+)[ \t]*$/.exec(closingLine)?.[1];
71
- const tex = token.content.trim();
72
- if (marker?.startsWith(token.markup) && tex.length > 0 && tex.length <= maxFormulaLength) {
73
- opaqueBlocks.push({ start, end, formula: { start, end, tex, block: true } });
74
- continue;
75
- }
76
- }
77
- opaqueBlocks.push({ start, end });
78
- }
79
- return { opaqueBlocks, standaloneParagraphs };
80
- }
81
-
82
- function skipCodeSpan(source: string, start: number, limit: number): number {
83
- let openEnd = start;
84
- while (source[openEnd] === "`") openEnd++;
85
- const runs = /`+/g;
86
- runs.lastIndex = openEnd;
87
- for (let match = runs.exec(source); match && match.index < limit; match = runs.exec(source)) {
88
- if (match[0].length === openEnd - start) return runs.lastIndex;
89
- if (runs.lastIndex - start > maxFormulaLength * 4) break;
90
- }
91
- return openEnd;
92
- }
93
-
94
- function skipLinkDestination(source: string, start: number, limit: number): number {
95
- const close = source[start] === "(" ? ")" : "]";
96
- let depth = 1;
97
- let angle = false;
98
- let title = "";
99
- for (let index = start + 1; index < Math.min(limit, start + 8192); index++) {
100
- const character = source[index];
101
- if (character === "\r" || character === "\n") break;
102
- if (character === "\\") { index++; continue; }
103
- if (close === ")") {
104
- if (title) {
105
- if (character === title) title = "";
106
- continue;
107
- }
108
- if (character === "<" && index === start + 1) angle = true;
109
- if (character === ">" && angle) { angle = false; continue; }
110
- if (angle) continue;
111
- if (depth === 1 && (character === '"' || character === "'") && /\s/.test(source[index - 1])) {
112
- title = character;
113
- continue;
114
- }
115
- if (character === "(") depth++;
116
- }
117
- if (character === close && --depth === 0) return index + 1;
118
- }
119
- return start;
120
- }
121
-
122
- function readFormula(
123
- source: string, start: number, limit: number, standaloneParagraphs: ReadonlySet<string>,
124
- ): FormulaSpan | undefined {
125
- const open = source.startsWith("$$", start) ? "$$" : source.slice(start, start + 2);
126
- const close = open === "\\(" ? "\\)" : open === "\\[" ? "\\]" : open === "$$" ? "$$" : "$";
127
- const display = close === "\\]" || close === "$$";
128
- const from = start + (close === "$" ? 1 : 2);
129
- if (close === "$" && (!source[from] || /\s/.test(source[from]))) return;
130
- const endLimit = Math.min(limit, from + maxFormulaLength + close.length);
131
- for (let index = from; index < endLimit; index++) {
132
- if (!display && (source[index] === "\n" || source[index] === "\r")) return;
133
- if (close === "$" && source[index] === "`") return;
134
- if (source.startsWith(close, index)) {
135
- if (close === "$" && (source[index + 1] === "$" || source[index - 1] === "$")) continue;
136
- if (close === "$" && (/\s/.test(source[index - 1]) || /[0-9]/.test(source[index + 1] ?? ""))) return;
137
- const tex = source.slice(from, index).trim();
138
- if (!tex) return;
139
- const end = index + close.length;
140
- const lineStart = source.lastIndexOf("\n", start - 1) + 1;
141
- const nextLine = source.indexOf("\n", end);
142
- const isolatedLine = /^[ \t]*$/.test(source.slice(lineStart, start)) &&
143
- /^[ \t\r]*$/.test(source.slice(end, nextLine < 0 ? source.length : nextLine));
144
- const block = display ? isolatedLine : standaloneParagraphs.has(sourceRangeKey(start, end));
145
- return { start, end, tex, block };
146
- }
147
- if (source[index] === "\\") index++;
148
- }
149
- }
150
-
151
- export function findFormulas(source: string): FormulaSpan[] {
152
- if (!possibleMath.test(source)) return [];
153
- const { opaqueBlocks, standaloneParagraphs } = markdownStructure(source);
154
- const formulas: FormulaSpan[] = [];
155
- let blockIndex = 0;
156
- for (let index = 0; index < source.length;) {
157
- const block = opaqueBlocks[blockIndex];
158
- if (block && index >= block.start) {
159
- if (block.formula) formulas.push(block.formula);
160
- index = Math.max(index, block.end);
161
- blockIndex++;
162
- continue;
163
- }
164
- const limit = block?.start ?? source.length;
165
- const character = source[index];
166
- if (character === "`") {
167
- index = skipCodeSpan(source, index, limit);
168
- continue;
169
- }
170
- if (character === "]" && (source[index + 1] === "(" || source[index + 1] === "[")) {
171
- index = skipLinkDestination(source, index + 1, limit);
172
- continue;
173
- }
174
- if (character === "<") {
175
- const close = source.indexOf(">", index + 1);
176
- if (close >= 0 && close < limit && /^(?:\/?[a-z][\w-]*(?:\s|$)|[a-z][\w+.-]*:)/i.test(source.slice(index + 1, close))) {
177
- index = close + 1;
178
- continue;
179
- }
180
- }
181
- if (character === "[" && (index === 0 || source[index - 1] === "\n")) {
182
- const newline = source.indexOf("\n", index);
183
- const end = newline < 0 ? source.length : newline;
184
- if (/^\[[^\]]+\]:[ \t]+/.test(source.slice(index, end))) { index = end; continue; }
185
- }
186
- if (character === "$" || (character === "\\" && (source[index + 1] === "(" || source[index + 1] === "["))) {
187
- const formula = readFormula(source, index, limit, standaloneParagraphs);
188
- if (formula) {
189
- formulas.push(formula);
190
- index = formula.end;
191
- continue;
192
- }
193
- if (source.startsWith("$$", index)) { index += 2; continue; }
194
- }
195
- index += character === "\\" ? 2 : 1;
196
- }
197
- return formulas;
198
- }
1
+ import MarkdownIt from "markdown-it";
2
+ import { maxFormulaLength } from "./markdown-constants";
3
+
4
+ export const markdownParser = new MarkdownIt({ html: true });
5
+ export const possibleMath = /[$]|\\[([]|(?:`{3,}|~{3,})[ \t]*math\b/i;
6
+
7
+ interface SourceRange {
8
+ start: number;
9
+ end: number;
10
+ }
11
+
12
+ interface FormulaSpan extends SourceRange {
13
+ tex: string;
14
+ block: boolean;
15
+ }
16
+
17
+ interface OpaqueBlock extends SourceRange {
18
+ formula?: FormulaSpan;
19
+ }
20
+
21
+ interface MarkdownStructure {
22
+ opaqueBlocks: OpaqueBlock[];
23
+ standaloneParagraphs: Set<string>;
24
+ }
25
+
26
+ function sourceRangeKey(start: number, end: number) {
27
+ return `${start}:${end}`;
28
+ }
29
+
30
+ export function lineOffsets(source: string): number[] {
31
+ const offsets = [0];
32
+ for (let index = 0; index < source.length; index++) {
33
+ const code = source.charCodeAt(index);
34
+ if (code === 10) offsets.push(index + 1);
35
+ else if (code === 13) {
36
+ if (source.charCodeAt(index + 1) === 10) index++;
37
+ offsets.push(index + 1);
38
+ }
39
+ }
40
+ offsets.push(source.length);
41
+ return offsets;
42
+ }
43
+
44
+ function markdownStructure(source: string): MarkdownStructure {
45
+ const offsets = lineOffsets(source);
46
+ const tokens = markdownParser.parse(source, {});
47
+ const opaqueBlocks: OpaqueBlock[] = [];
48
+ const standaloneParagraphs = new Set<string>();
49
+ for (const [index, token] of tokens.entries()) {
50
+ if (token.type === "inline" && token.map && tokens[index - 1]?.type === "paragraph_open") {
51
+ const [firstLine, endLine] = token.map;
52
+ if (endLine - firstLine <= 1) {
53
+ let start = offsets[firstLine];
54
+ let end = offsets[endLine];
55
+ while (start < end && /\s/.test(source[start])) start++;
56
+ while (end > start && /\s/.test(source[end - 1])) end--;
57
+ if (start < end) standaloneParagraphs.add(sourceRangeKey(start, end));
58
+ }
59
+ }
60
+ if (!token.map || (token.type !== "fence" && token.type !== "code_block" && token.type !== "html_block")) continue;
61
+ const start = offsets[token.map[0]];
62
+ const end = offsets[token.map[1]];
63
+ if (
64
+ token.type === "fence" &&
65
+ token.info.trim().toLowerCase() === "math" &&
66
+ token.map[1] - token.map[0] >= 3 &&
67
+ /^\s*(?:`{3,}|~{3,})\s*math\b/i.test(source.slice(start, offsets[token.map[0] + 1]))
68
+ ) {
69
+ const closingLine = source.slice(offsets[token.map[1] - 1], end).replace(/(?:\r\n|\r|\n)$/, "");
70
+ const marker = /^ {0,3}(`+|~+)[ \t]*$/.exec(closingLine)?.[1];
71
+ const tex = token.content.trim();
72
+ if (marker?.startsWith(token.markup) && tex.length > 0 && tex.length <= maxFormulaLength) {
73
+ opaqueBlocks.push({ start, end, formula: { start, end, tex, block: true } });
74
+ continue;
75
+ }
76
+ }
77
+ opaqueBlocks.push({ start, end });
78
+ }
79
+ return { opaqueBlocks, standaloneParagraphs };
80
+ }
81
+
82
+ function skipCodeSpan(source: string, start: number, limit: number): number {
83
+ let openEnd = start;
84
+ while (source[openEnd] === "`") openEnd++;
85
+ const runs = /`+/g;
86
+ runs.lastIndex = openEnd;
87
+ for (let match = runs.exec(source); match && match.index < limit; match = runs.exec(source)) {
88
+ if (match[0].length === openEnd - start) return runs.lastIndex;
89
+ if (runs.lastIndex - start > maxFormulaLength * 4) break;
90
+ }
91
+ return openEnd;
92
+ }
93
+
94
+ function skipLinkDestination(source: string, start: number, limit: number): number {
95
+ const close = source[start] === "(" ? ")" : "]";
96
+ let depth = 1;
97
+ let angle = false;
98
+ let title = "";
99
+ for (let index = start + 1; index < Math.min(limit, start + 8192); index++) {
100
+ const character = source[index];
101
+ if (character === "\r" || character === "\n") break;
102
+ if (character === "\\") { index++; continue; }
103
+ if (close === ")") {
104
+ if (title) {
105
+ if (character === title) title = "";
106
+ continue;
107
+ }
108
+ if (character === "<" && index === start + 1) angle = true;
109
+ if (character === ">" && angle) { angle = false; continue; }
110
+ if (angle) continue;
111
+ if (depth === 1 && (character === '"' || character === "'") && /\s/.test(source[index - 1])) {
112
+ title = character;
113
+ continue;
114
+ }
115
+ if (character === "(") depth++;
116
+ }
117
+ if (character === close && --depth === 0) return index + 1;
118
+ }
119
+ return start;
120
+ }
121
+
122
+ function readFormula(
123
+ source: string, start: number, limit: number, standaloneParagraphs: ReadonlySet<string>,
124
+ ): FormulaSpan | undefined {
125
+ const open = source.startsWith("$$", start) ? "$$" : source.slice(start, start + 2);
126
+ const close = open === "\\(" ? "\\)" : open === "\\[" ? "\\]" : open === "$$" ? "$$" : "$";
127
+ const display = close === "\\]" || close === "$$";
128
+ const from = start + (close === "$" ? 1 : 2);
129
+ if (close === "$" && (!source[from] || /\s/.test(source[from]))) return;
130
+ const endLimit = Math.min(limit, from + maxFormulaLength + close.length);
131
+ for (let index = from; index < endLimit; index++) {
132
+ if (!display && (source[index] === "\n" || source[index] === "\r")) return;
133
+ if (close === "$" && source[index] === "`") return;
134
+ if (source.startsWith(close, index)) {
135
+ if (close === "$" && (source[index + 1] === "$" || source[index - 1] === "$")) continue;
136
+ if (close === "$" && (/\s/.test(source[index - 1]) || /[0-9]/.test(source[index + 1] ?? ""))) return;
137
+ const tex = source.slice(from, index).trim();
138
+ if (!tex) return;
139
+ const end = index + close.length;
140
+ const lineStart = source.lastIndexOf("\n", start - 1) + 1;
141
+ const nextLine = source.indexOf("\n", end);
142
+ const isolatedLine = /^[ \t]*$/.test(source.slice(lineStart, start)) &&
143
+ /^[ \t\r]*$/.test(source.slice(end, nextLine < 0 ? source.length : nextLine));
144
+ const block = display ? isolatedLine : standaloneParagraphs.has(sourceRangeKey(start, end));
145
+ return { start, end, tex, block };
146
+ }
147
+ if (source[index] === "\\") index++;
148
+ }
149
+ }
150
+
151
+ export function findFormulas(source: string): FormulaSpan[] {
152
+ if (!possibleMath.test(source)) return [];
153
+ const { opaqueBlocks, standaloneParagraphs } = markdownStructure(source);
154
+ const formulas: FormulaSpan[] = [];
155
+ let blockIndex = 0;
156
+ for (let index = 0; index < source.length;) {
157
+ const block = opaqueBlocks[blockIndex];
158
+ if (block && index >= block.start) {
159
+ if (block.formula) formulas.push(block.formula);
160
+ index = Math.max(index, block.end);
161
+ blockIndex++;
162
+ continue;
163
+ }
164
+ const limit = block?.start ?? source.length;
165
+ const character = source[index];
166
+ if (character === "`") {
167
+ index = skipCodeSpan(source, index, limit);
168
+ continue;
169
+ }
170
+ if (character === "]" && (source[index + 1] === "(" || source[index + 1] === "[")) {
171
+ index = skipLinkDestination(source, index + 1, limit);
172
+ continue;
173
+ }
174
+ if (character === "<") {
175
+ const close = source.indexOf(">", index + 1);
176
+ if (close >= 0 && close < limit && /^(?:\/?[a-z][\w-]*(?:\s|$)|[a-z][\w+.-]*:)/i.test(source.slice(index + 1, close))) {
177
+ index = close + 1;
178
+ continue;
179
+ }
180
+ }
181
+ if (character === "[" && (index === 0 || source[index - 1] === "\n")) {
182
+ const newline = source.indexOf("\n", index);
183
+ const end = newline < 0 ? source.length : newline;
184
+ if (/^\[[^\]]+\]:[ \t]+/.test(source.slice(index, end))) { index = end; continue; }
185
+ }
186
+ if (character === "$" || (character === "\\" && (source[index + 1] === "(" || source[index + 1] === "["))) {
187
+ const formula = readFormula(source, index, limit, standaloneParagraphs);
188
+ if (formula) {
189
+ formulas.push(formula);
190
+ index = formula.end;
191
+ continue;
192
+ }
193
+ if (source.startsWith("$$", index)) { index += 2; continue; }
194
+ }
195
+ index += character === "\\" ? 2 : 1;
196
+ }
197
+ return formulas;
198
+ }
@@ -1,83 +1,83 @@
1
- import { parse, postprocess, preprocess } from "micromark";
2
- import { decodeString } from "micromark-util-decode-string";
3
- import type { MarkdownReference as Reference } from "./contracts";
4
-
5
- export function normalizeMarkdownLabel(value: string) {
6
- return value.replace(/[\t\n\r ]+/g, " ").trim().toLowerCase().toUpperCase();
7
- }
8
-
9
- export function markdownEvents(text: string) {
10
- return postprocess(parse().document().write(preprocess()(text, undefined, true)));
11
- }
12
-
13
- function referencesFromEvents(text: string, events: ReturnType<typeof markdownEvents>): Reference[] {
14
- const references: Reference[] = [];
15
- let entry: Reference | undefined;
16
- for (const [action, token] of events) {
17
- if (action === "enter" && token.type === "definition") entry = { label: "", destination: "" };
18
- if (!entry) continue;
19
- const value = () => text.slice(token.start.offset, token.end.offset);
20
- if (action === "enter" && token.type === "definitionLabelString") entry.label = value();
21
- if (action === "enter" && token.type === "definitionDestinationString") entry.destination = decodeString(value());
22
- if (action === "enter" && token.type === "definitionTitleString") entry.title = decodeString(value());
23
- if (action === "exit" && token.type === "definition") {
24
- if (entry.label) references.push(entry);
25
- entry = undefined;
26
- }
27
- }
28
- return references;
29
- }
30
-
31
- export function markdownReferences(text: string): Reference[] {
32
- return text.includes("]:") ? referencesFromEvents(text, markdownEvents(text)) : [];
33
- }
34
-
35
- function resource({ destination, title }: Reference) {
36
- const href = destination.replace(/[<>\\\r\n]/g, (char) => encodeURIComponent(char)).replaceAll("&", "&amp;");
37
- const caption = !title ? "" : ` "${title.replace(/\r\n?|\n/g, " ").replace(/[\\"]/g, "\\$&").replaceAll("&", "&amp;")}"`;
38
- return `<${href}>${caption}`;
39
- }
40
-
41
- export function inlineReferenceLinks(text: string, definitions?: readonly Reference[]) {
42
- if (!text.includes("[") || (!definitions?.length && !text.includes("]:"))) return text;
43
- const parsedEvents = definitions ? undefined : markdownEvents(text);
44
- const references = new Map<string, Reference>();
45
- for (const entry of definitions ?? referencesFromEvents(text, parsedEvents!)) {
46
- const key = normalizeMarkdownLabel(entry.label);
47
- if (!references.has(key)) references.set(key, entry);
48
- }
49
- if (!references.size) return text;
50
- const prefix = definitions?.length
51
- ? [...references.values()].map((entry) => `[${entry.label.replace(/[\r\n]+/g, " ")}]: ${resource(entry)}`).join("\n") + "\n\n"
52
- : "";
53
- const input = prefix + text;
54
- const events = prefix ? markdownEvents(input) : parsedEvents ?? markdownEvents(input);
55
- const stack: { label?: string; labelEnd?: number; reference?: string; inline?: boolean }[] = [];
56
- const edits: { start: number; end: number; value: string }[] = [];
57
- for (const [action, token] of events) {
58
- if (token.type === "link" || token.type === "image") {
59
- if (action === "enter") stack.push({});
60
- else {
61
- const current = stack.pop();
62
- if (!current?.label || current.labelEnd === undefined || current.inline || current.labelEnd < prefix.length) continue;
63
- const entry = references.get(normalizeMarkdownLabel(current.reference ?? current.label));
64
- if (entry) edits.push({ start: current.labelEnd - prefix.length, end: token.end.offset - prefix.length, value: `(${resource(entry)})` });
65
- }
66
- } else {
67
- const current = stack.at(-1);
68
- if (!current) continue;
69
- if (action === "enter" && token.type === "resource") current.inline = true;
70
- if (action === "exit" && token.type === "label") current.labelEnd = token.end.offset;
71
- if (action === "enter" && token.type === "labelText") current.label = input.slice(token.start.offset, token.end.offset);
72
- if (action === "enter" && token.type === "referenceString") current.reference = input.slice(token.start.offset, token.end.offset);
73
- }
74
- }
75
- if (!edits.length) return text;
76
- let tail = text.length;
77
- const result: string[] = [];
78
- for (const { start, end, value } of edits.reverse()) {
79
- result.push(text.slice(end, tail), value);
80
- tail = start;
81
- }
82
- return text.slice(0, tail) + result.reverse().join("");
83
- }
1
+ import { parse, postprocess, preprocess } from "micromark";
2
+ import { decodeString } from "micromark-util-decode-string";
3
+ import type { MarkdownReference as Reference } from "./contracts";
4
+
5
+ export function normalizeMarkdownLabel(value: string) {
6
+ return value.replace(/[\t\n\r ]+/g, " ").trim().toLowerCase().toUpperCase();
7
+ }
8
+
9
+ export function markdownEvents(text: string) {
10
+ return postprocess(parse().document().write(preprocess()(text, undefined, true)));
11
+ }
12
+
13
+ function referencesFromEvents(text: string, events: ReturnType<typeof markdownEvents>): Reference[] {
14
+ const references: Reference[] = [];
15
+ let entry: Reference | undefined;
16
+ for (const [action, token] of events) {
17
+ if (action === "enter" && token.type === "definition") entry = { label: "", destination: "" };
18
+ if (!entry) continue;
19
+ const value = () => text.slice(token.start.offset, token.end.offset);
20
+ if (action === "enter" && token.type === "definitionLabelString") entry.label = value();
21
+ if (action === "enter" && token.type === "definitionDestinationString") entry.destination = decodeString(value());
22
+ if (action === "enter" && token.type === "definitionTitleString") entry.title = decodeString(value());
23
+ if (action === "exit" && token.type === "definition") {
24
+ if (entry.label) references.push(entry);
25
+ entry = undefined;
26
+ }
27
+ }
28
+ return references;
29
+ }
30
+
31
+ export function markdownReferences(text: string): Reference[] {
32
+ return text.includes("]:") ? referencesFromEvents(text, markdownEvents(text)) : [];
33
+ }
34
+
35
+ function resource({ destination, title }: Reference) {
36
+ const href = destination.replace(/[<>\\\r\n]/g, (char) => encodeURIComponent(char)).replaceAll("&", "&amp;");
37
+ const caption = !title ? "" : ` "${title.replace(/\r\n?|\n/g, " ").replace(/[\\"]/g, "\\$&").replaceAll("&", "&amp;")}"`;
38
+ return `<${href}>${caption}`;
39
+ }
40
+
41
+ export function inlineReferenceLinks(text: string, definitions?: readonly Reference[]) {
42
+ if (!text.includes("[") || (!definitions?.length && !text.includes("]:"))) return text;
43
+ const parsedEvents = definitions ? undefined : markdownEvents(text);
44
+ const references = new Map<string, Reference>();
45
+ for (const entry of definitions ?? referencesFromEvents(text, parsedEvents!)) {
46
+ const key = normalizeMarkdownLabel(entry.label);
47
+ if (!references.has(key)) references.set(key, entry);
48
+ }
49
+ if (!references.size) return text;
50
+ const prefix = definitions?.length
51
+ ? [...references.values()].map((entry) => `[${entry.label.replace(/[\r\n]+/g, " ")}]: ${resource(entry)}`).join("\n") + "\n\n"
52
+ : "";
53
+ const input = prefix + text;
54
+ const events = prefix ? markdownEvents(input) : parsedEvents ?? markdownEvents(input);
55
+ const stack: { label?: string; labelEnd?: number; reference?: string; inline?: boolean }[] = [];
56
+ const edits: { start: number; end: number; value: string }[] = [];
57
+ for (const [action, token] of events) {
58
+ if (token.type === "link" || token.type === "image") {
59
+ if (action === "enter") stack.push({});
60
+ else {
61
+ const current = stack.pop();
62
+ if (!current?.label || current.labelEnd === undefined || current.inline || current.labelEnd < prefix.length) continue;
63
+ const entry = references.get(normalizeMarkdownLabel(current.reference ?? current.label));
64
+ if (entry) edits.push({ start: current.labelEnd - prefix.length, end: token.end.offset - prefix.length, value: `(${resource(entry)})` });
65
+ }
66
+ } else {
67
+ const current = stack.at(-1);
68
+ if (!current) continue;
69
+ if (action === "enter" && token.type === "resource") current.inline = true;
70
+ if (action === "exit" && token.type === "label") current.labelEnd = token.end.offset;
71
+ if (action === "enter" && token.type === "labelText") current.label = input.slice(token.start.offset, token.end.offset);
72
+ if (action === "enter" && token.type === "referenceString") current.reference = input.slice(token.start.offset, token.end.offset);
73
+ }
74
+ }
75
+ if (!edits.length) return text;
76
+ let tail = text.length;
77
+ const result: string[] = [];
78
+ for (const { start, end, value } of edits.reverse()) {
79
+ result.push(text.slice(end, tail), value);
80
+ tail = start;
81
+ }
82
+ return text.slice(0, tail) + result.reverse().join("");
83
+ }
@@ -1,8 +1,8 @@
1
- export function markdownSourceLocation(lineStart?: number, lineEnd?: number, lineCount?: number) {
2
- if (lineStart === undefined || !Number.isInteger(lineStart) || lineStart < 1) return;
3
- const limit = lineCount ?? Number.MAX_SAFE_INTEGER;
4
- const first = Math.min(lineStart, limit);
5
- const last = lineEnd !== undefined && Number.isInteger(lineEnd) && lineEnd >= lineStart
6
- ? Math.min(lineEnd, limit) : first;
7
- return { first, last };
8
- }
1
+ export function markdownSourceLocation(lineStart?: number, lineEnd?: number, lineCount?: number) {
2
+ if (lineStart === undefined || !Number.isInteger(lineStart) || lineStart < 1) return;
3
+ const limit = lineCount ?? Number.MAX_SAFE_INTEGER;
4
+ const first = Math.min(lineStart, limit);
5
+ const last = lineEnd !== undefined && Number.isInteger(lineEnd) && lineEnd >= lineStart
6
+ ? Math.min(lineEnd, limit) : first;
7
+ return { first, last };
8
+ }
@@ -1,15 +1,15 @@
1
- import { defineSettings } from "@getpaseo/plugin";
2
- import { z } from "zod";
3
- import { defaultModifiers, keyboardShortcuts, type KeyboardShortcut, type ModifiedShortcut } from "./reader-shortcuts";
4
-
5
- export const readerSettings = defineSettings({
6
- id: "reader",
7
- scope: "host",
8
- version: 2,
9
- schema: z.object({
10
- shortcuts: z.partialRecord(z.enum([
11
- ...Object.keys(keyboardShortcuts) as KeyboardShortcut[],
12
- ...Object.keys(defaultModifiers) as ModifiedShortcut[],
13
- ]), z.string().max(64)).default({}),
14
- }),
15
- });
1
+ import { defineSettings } from "@getpaseo/plugin";
2
+ import { z } from "zod";
3
+ import { defaultModifiers, keyboardShortcuts, type KeyboardShortcut, type ModifiedShortcut } from "./reader-shortcuts";
4
+
5
+ export const readerSettings = defineSettings({
6
+ id: "reader",
7
+ scope: "host",
8
+ version: 2,
9
+ schema: z.object({
10
+ shortcuts: z.partialRecord(z.enum([
11
+ ...Object.keys(keyboardShortcuts) as KeyboardShortcut[],
12
+ ...Object.keys(defaultModifiers) as ModifiedShortcut[],
13
+ ]), z.string().max(64)).default({}),
14
+ }),
15
+ });