@k2b/editor 0.9.0 → 0.11.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.
- package/package.json +3 -3
- package/src/BubbleMenu.tsx +11 -4
- package/src/Toolbar.tsx +25 -12
- package/src/chart-locale.ts +1 -1
- package/src/chart-schema.ts +178 -27
- package/src/charts.ts +225 -83
- package/src/collab/remote-cursors.ts +10 -2
- package/src/markdown/_lib/changed-blocks.ts +66 -0
- package/src/markdown/_lib/cursor-zone-field.ts +61 -5
- package/src/markdown/_lib/list-structure.ts +6 -1
- package/src/markdown/_lib/math-syntax.ts +5 -2
- package/src/markdown/block-previews.tsx +16 -9
- package/src/markdown/data-blocks.ts +13 -5
- package/src/markdown/images.ts +2 -1
- package/src/markdown/info-blocks.ts +4 -2
- package/src/markdown/katex.ts +11 -13
- package/src/markdown/lib/chart-blocks.ts +129 -16
- package/src/markdown/lib/query-blocks.ts +1 -0
- package/src/markdown/ligatures.ts +54 -45
- package/src/markdown/links.ts +2 -2
- package/src/markdown/lists.ts +53 -8
- package/src/markdown/markup.ts +110 -340
- package/src/markdown/mermaid.ts +4 -2
- package/src/markdown/named-blocks.ts +4 -2
- package/src/markdown/notebook-charts.tsx +10 -3
- package/src/markdown/tables.ts +15 -7
- package/src/slash-menu.ts +8 -0
- package/src/styles.css +8 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { highlight, text } from "@k2b/stdlib";
|
|
2
2
|
import { prepareChartSnapshot } from "@k2b/ui";
|
|
3
|
-
import { barChartLayout, hbarLayout } from "@k2b/ui/charts";
|
|
4
|
-
import { paretoLayout } from "@k2b/ui/charts/core";
|
|
3
|
+
import { barChartLayout, calendarLayout, calendarViewportHeight, hbarLayout } from "@k2b/ui/charts";
|
|
4
|
+
import { balanceFlowHeight, chartSvgWithUiPalette, paretoLayout, renderBalanceFlowHtml, sankeyFrame } from "@k2b/ui/charts/core";
|
|
5
5
|
import { Lexer, type Tokens } from "marked";
|
|
6
6
|
import type { z } from "zod";
|
|
7
7
|
import {
|
|
@@ -32,11 +32,18 @@ export type MarkdownChartOptions = {
|
|
|
32
32
|
};
|
|
33
33
|
export type ChartBlock = { line: number; input: ChartInput };
|
|
34
34
|
/** `height` is the drawing's own height in CSS pixels when it needs more than the kind's frame (app.css). */
|
|
35
|
-
type Frame = {
|
|
35
|
+
type Frame = {
|
|
36
|
+
kind: ChartInput["kind"];
|
|
37
|
+
area?: boolean;
|
|
38
|
+
title: string;
|
|
39
|
+
subtitle?: string;
|
|
40
|
+
height?: number | string;
|
|
41
|
+
balanceFlow?: Extract<ChartInput, { kind: "balanceFlow" }>;
|
|
42
|
+
};
|
|
36
43
|
type Entry = { value: string; line: number };
|
|
37
44
|
type Cell = { raw: string; result: EvalResult };
|
|
38
45
|
type SourceData = { columns: string[]; rows: Cell[][]; implicit: boolean; entries?: NamedDataEntry[]; invalid?: boolean };
|
|
39
|
-
const TYPES = new Set(["line", "area", "bar", "pie", "donut", "scatter", "stat"]);
|
|
46
|
+
const TYPES = new Set(["line", "area", "bar", "pie", "donut", "scatter", "stat", "balanceFlow"]);
|
|
40
47
|
const escape = highlight.escape;
|
|
41
48
|
const scalarCell = (value: string | number | boolean): Cell => {
|
|
42
49
|
const raw = String(value);
|
|
@@ -134,7 +141,25 @@ const parseChart = (
|
|
|
134
141
|
const key = entry[1]!;
|
|
135
142
|
section = "";
|
|
136
143
|
if (
|
|
137
|
-
![
|
|
144
|
+
![
|
|
145
|
+
"type",
|
|
146
|
+
"title",
|
|
147
|
+
"subtitle",
|
|
148
|
+
"data",
|
|
149
|
+
"columns",
|
|
150
|
+
"rows",
|
|
151
|
+
"x",
|
|
152
|
+
"y",
|
|
153
|
+
"label",
|
|
154
|
+
"value",
|
|
155
|
+
"format",
|
|
156
|
+
"unit",
|
|
157
|
+
"tooltip",
|
|
158
|
+
"periods",
|
|
159
|
+
"currency",
|
|
160
|
+
"locale",
|
|
161
|
+
"period",
|
|
162
|
+
].includes(key)
|
|
138
163
|
) {
|
|
139
164
|
add("unknown-key", key, line);
|
|
140
165
|
continue;
|
|
@@ -181,6 +206,43 @@ const parseChart = (
|
|
|
181
206
|
const title = string("title");
|
|
182
207
|
const subtitle = string("subtitle");
|
|
183
208
|
if (type && !TYPES.has(type)) add("invalid-type", "type");
|
|
209
|
+
if (type === "balanceFlow") {
|
|
210
|
+
let periods: unknown;
|
|
211
|
+
try {
|
|
212
|
+
periods = JSON.parse(top.get("periods")?.value ?? "");
|
|
213
|
+
} catch {
|
|
214
|
+
add("invalid-type", "periods");
|
|
215
|
+
}
|
|
216
|
+
for (const key of top.keys())
|
|
217
|
+
if (!["type", "title", "subtitle", "periods", "currency", "locale", "period"].includes(key)) add("unknown-key", key);
|
|
218
|
+
const parsed = options.schema.safeParse({
|
|
219
|
+
kind: "balanceFlow",
|
|
220
|
+
title,
|
|
221
|
+
subtitle,
|
|
222
|
+
periods,
|
|
223
|
+
currency: string("currency"),
|
|
224
|
+
locale: string("locale"),
|
|
225
|
+
});
|
|
226
|
+
if (!parsed.success)
|
|
227
|
+
for (const issue of parsed.error.issues) {
|
|
228
|
+
const index = issue.path[0] === "periods" && typeof issue.path[1] === "number" ? issue.path[1] : undefined;
|
|
229
|
+
const period: unknown = index !== undefined && Array.isArray(periods) ? periods[index] : undefined;
|
|
230
|
+
if (period && typeof period === "object" && "label" in period && typeof period.label === "string")
|
|
231
|
+
add("chart-balance-period", issue.path.join("."), top.get("periods")?.line, { name: period.label });
|
|
232
|
+
else add("invalid-type", String(issue.path[0] ?? "periods"));
|
|
233
|
+
}
|
|
234
|
+
if (diagnostics.length || !parsed.success) return { diagnostics };
|
|
235
|
+
if (
|
|
236
|
+
parsed.data.kind === "balanceFlow" &&
|
|
237
|
+
parsed.data.periods.reduce((sum, p) => sum + p.inflows.length + p.outflows.length + 3, 0) > options.maxSeries * options.maxValues
|
|
238
|
+
) {
|
|
239
|
+
add("too-many-items", "periods", undefined, { limit: options.maxSeries * options.maxValues });
|
|
240
|
+
return { diagnostics };
|
|
241
|
+
}
|
|
242
|
+
return { diagnostics, block: { line: directive.line, input: parsed.data } };
|
|
243
|
+
}
|
|
244
|
+
for (const key of ["periods", "currency", "locale", "period"]) if (top.has(key)) add("unknown-key", key);
|
|
245
|
+
|
|
184
246
|
let data: SourceData = { columns: [], rows: [], implicit: false };
|
|
185
247
|
if (top.has("data")) {
|
|
186
248
|
if (top.has("columns") || top.has("rows")) add("invalid-type", "data");
|
|
@@ -423,7 +485,7 @@ export const parseNotebookChartBlocks = (
|
|
|
423
485
|
export const chartBlockFrame = (body: string[], options: Pick<MarkdownChartOptions, "schema">): Frame | null => {
|
|
424
486
|
const entries = new Map<string, string>();
|
|
425
487
|
for (const line of body) {
|
|
426
|
-
const pair = /^(type|title|subtitle):\s*(.*)$/.exec(line);
|
|
488
|
+
const pair = /^(type|title|subtitle|periods|currency|locale|period):\s*(.*)$/.exec(line);
|
|
427
489
|
if (!pair) continue;
|
|
428
490
|
if (entries.has(pair[1]!)) return null;
|
|
429
491
|
entries.set(pair[1]!, pair[2]!);
|
|
@@ -439,6 +501,24 @@ export const chartBlockFrame = (body: string[], options: Pick<MarkdownChartOptio
|
|
|
439
501
|
switch (type) {
|
|
440
502
|
case "area":
|
|
441
503
|
return { kind: "line", area: true, title: header.data.title, ...(header.data.subtitle ? { subtitle: header.data.subtitle } : {}) };
|
|
504
|
+
case "balanceFlow": {
|
|
505
|
+
let periods: unknown;
|
|
506
|
+
try {
|
|
507
|
+
periods = JSON.parse(entries.get("periods") ?? "");
|
|
508
|
+
} catch {
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
const parsed = options.schema.safeParse({
|
|
512
|
+
kind: type,
|
|
513
|
+
title,
|
|
514
|
+
subtitle,
|
|
515
|
+
periods,
|
|
516
|
+
currency: parseScalar(entries.get("currency") ?? ""),
|
|
517
|
+
...(entries.has("locale") ? { locale: parseScalar(entries.get("locale")!) } : {}),
|
|
518
|
+
});
|
|
519
|
+
if (!parsed.success || parsed.data.kind !== "balanceFlow") return null;
|
|
520
|
+
return { kind: type, title, subtitle, balanceFlow: parsed.data };
|
|
521
|
+
}
|
|
442
522
|
case "line":
|
|
443
523
|
case "bar":
|
|
444
524
|
case "scatter":
|
|
@@ -456,14 +536,15 @@ export const chartBlockFrame = (body: string[], options: Pick<MarkdownChartOptio
|
|
|
456
536
|
* categories make the drawing taller. The server and an editor placeholder read it from the same parsed block, so
|
|
457
537
|
* both reserve the same box. Undefined for every other drawing, which fits the frame.
|
|
458
538
|
*/
|
|
459
|
-
export const notebookChartHeight = (input: ChartInput, locale: string): number | undefined => {
|
|
539
|
+
export const notebookChartHeight = (input: ChartInput, locale: string): number | string | undefined => {
|
|
460
540
|
const options = chartRenderOptions(input, locale, { legend: "outside" });
|
|
541
|
+
if (options.kind === "balanceFlow") return balanceFlowHeight(options.periods);
|
|
461
542
|
if (options.kind === "treemap") return 280;
|
|
462
543
|
if (options.kind === "pareto") return paretoLayout(options).height;
|
|
463
|
-
|
|
544
|
+
if (options.kind === "sankey") return sankeyFrame(options).height;
|
|
464
545
|
if (options.kind === "bubble" || options.kind === "radar") return 280;
|
|
465
546
|
if (options.kind === "hbar") return hbarLayout(options).height;
|
|
466
|
-
if (options.kind === "heatmap" && options.layout === "calendar") return
|
|
547
|
+
if (options.kind === "heatmap" && options.layout === "calendar") return calendarViewportHeight(calendarLayout(options));
|
|
467
548
|
if (options.kind === "waterfall" || options.kind === "area") return 280;
|
|
468
549
|
if (options.kind !== "bar") return undefined;
|
|
469
550
|
const layout = barChartLayout(options);
|
|
@@ -479,9 +560,18 @@ export const notebookChartHeight = (input: ChartInput, locale: string): number |
|
|
|
479
560
|
export const notebookChartFrameHtml = (
|
|
480
561
|
frame: Frame,
|
|
481
562
|
viewportHtml: string,
|
|
482
|
-
options: { legend?: boolean; input?: ChartInput; print?: boolean } = {},
|
|
563
|
+
options: { legend?: boolean; input?: ChartInput; print?: boolean; locale?: string } = {},
|
|
483
564
|
): string =>
|
|
484
|
-
|
|
565
|
+
frame.balanceFlow
|
|
566
|
+
? renderBalanceFlowHtml(
|
|
567
|
+
{ ...frame.balanceFlow, locale: frame.balanceFlow.locale ?? options.locale },
|
|
568
|
+
"loading",
|
|
569
|
+
undefined,
|
|
570
|
+
"chart",
|
|
571
|
+
false,
|
|
572
|
+
Boolean(options.print),
|
|
573
|
+
)
|
|
574
|
+
: `<figure class="notebook-book-chart"${typeof frame.height === "string" ? ' data-calendar="true" style="container-type:inline-size"' : ""} data-kind="${frame.kind === "line" && frame.area ? "area" : frame.kind}"${options.input ? ` data-chart="${escape(JSON.stringify(options.input))}"` : ""}><figcaption class="notebook-book-chart__header"><span class="notebook-book-chart__title">${escape(frame.title)}</span>${frame.subtitle ? `<span class="notebook-book-chart__subtitle">${escape(frame.subtitle)}</span>` : ""}</figcaption>${options.print ? "" : '<div class="notebook-book-chart__actions"></div>'}<div class="notebook-book-chart__viewport"${options.legend ? ' data-legend="true"' : ""}${frame.height ? ` style="--notebook-chart-height:${typeof frame.height === "number" ? `${frame.height}px` : frame.height}"` : ""}>${viewportHtml}</div></figure>`;
|
|
485
575
|
|
|
486
576
|
/** A chart's data as a note table: the PDF prints it below the figure, and the table view shows it in the frame. */
|
|
487
577
|
export const notebookChartTableHtml = (table: ChartTable, options: { label?: string; className?: string } = {}): string =>
|
|
@@ -490,12 +580,24 @@ export const notebookChartTableHtml = (table: ChartTable, options: { label?: str
|
|
|
490
580
|
/** Only the shared renderer supplies SVG. A failed drawing leaves the caller's source visible. */
|
|
491
581
|
export const renderNotebookChartFigure = (input: ChartInput, locale: string, options: { print?: boolean } = {}): string | null => {
|
|
492
582
|
try {
|
|
583
|
+
if (input.kind === "balanceFlow") {
|
|
584
|
+
const drawing = chartRenderOptions(input, locale);
|
|
585
|
+
if (drawing.kind === "balanceFlow")
|
|
586
|
+
return renderBalanceFlowHtml(
|
|
587
|
+
{ ...drawing, title: input.title, subtitle: input.subtitle },
|
|
588
|
+
"data",
|
|
589
|
+
undefined,
|
|
590
|
+
"chart",
|
|
591
|
+
false,
|
|
592
|
+
Boolean(options.print),
|
|
593
|
+
);
|
|
594
|
+
}
|
|
493
595
|
const rows = chartRows(input, locale);
|
|
494
596
|
const snapshot = prepareChartSnapshot(chartRenderOptions(input, locale, { legend: "outside" }), {
|
|
495
597
|
key: ({ datum }) => chartMarkKey(datum),
|
|
496
598
|
tooltip: ({ datum }) => {
|
|
497
599
|
const row = rows.add(datum);
|
|
498
|
-
return chartTooltip(rows.columns(), row, input
|
|
600
|
+
return chartTooltip(rows.columns(), row, input);
|
|
499
601
|
},
|
|
500
602
|
reference: ({ datum }) => chartReferenceMark(input, datum),
|
|
501
603
|
});
|
|
@@ -505,9 +607,16 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
|
|
|
505
607
|
const valueField = input.kind === "area" ? (input.normalize ? "percent" : "value") : "y";
|
|
506
608
|
let lastX = -Infinity;
|
|
507
609
|
for (const mark of snapshot.marks) lastX = Math.max(lastX, mark.datum.anchor[0]);
|
|
610
|
+
const sourceX = input.kind === "line" ? snapshot.svg.match(/data-line-default-x="([^"]+)"/)?.[1] : undefined;
|
|
508
611
|
const legendValue = (index: number) => {
|
|
509
612
|
const field = snapshot.marks
|
|
510
|
-
.find(
|
|
613
|
+
.find(
|
|
614
|
+
(mark) =>
|
|
615
|
+
mark.datum.seriesIndex === index &&
|
|
616
|
+
(sourceX === undefined
|
|
617
|
+
? mark.datum.anchor[0] === lastX
|
|
618
|
+
: mark.datum.values.some((field) => field.key === "x" && field.value === Number(sourceX))),
|
|
619
|
+
)
|
|
511
620
|
?.datum.values.find((field) => field.key === valueField);
|
|
512
621
|
return field
|
|
513
622
|
? (field.formatted ??
|
|
@@ -517,10 +626,14 @@ export const renderNotebookChartFigure = (input: ChartInput, locale: string, opt
|
|
|
517
626
|
: "—";
|
|
518
627
|
};
|
|
519
628
|
const legendHtml = legend.length
|
|
520
|
-
? `<ul class="k2b-chart-legend" aria-label="${escape(t.chartLegend)}">${legend.map((entry, index) => `<li><span class="k2b-chart-legend__swatch"${entry.style && entry.style !== "solid" ? ` data-style="${entry.style}"` : ""}${entry.reference ? ' data-reference="true"' : ""} style="--k2b-chart-legend-color:var(--stdlib-chart-c${(entry.color % 8) + 1})" aria-hidden="true"></span>${escape(entry.label)}${input.kind === "area" ? `<b data-chart-legend-value data-series-index="${index}" data-field="${valueField}" data-default="${escape(legendValue(index))}">${escape(legendValue(index))}</b>` : ""}</li>`).join("")}</ul>`
|
|
629
|
+
? `<ul class="k2b-chart-legend" aria-label="${escape(t.chartLegend)}">${legend.map((entry, index) => `<li><span class="k2b-chart-legend__swatch"${entry.style && entry.style !== "solid" ? ` data-style="${entry.style}"` : ""}${entry.reference ? ' data-reference="true"' : ""} style="--k2b-chart-legend-color:var(--stdlib-chart-c${(entry.color % 8) + 1})" aria-hidden="true"></span>${escape(entry.label)}${(input.kind === "line" && snapshot.svg.includes("data-line-details")) || input.kind === "area" ? `<b data-chart-legend-value data-series-index="${entry.seriesIndex ?? index}" data-field="${valueField}" data-default="${escape(legendValue(entry.seriesIndex ?? index))}">${escape(legendValue(entry.seriesIndex ?? index))}</b>` : ""}</li>`).join("")}</ul>`
|
|
521
630
|
: "";
|
|
522
|
-
const
|
|
523
|
-
const
|
|
631
|
+
const svg = options.print ? chartSvgWithUiPalette(snapshot.svg) : snapshot.svg;
|
|
632
|
+
const viewport = `<div class="k2b-chart" data-chart-kind="${snapshot.kind}"><div class="k2b-chart__svg"${snapshot.stretch ? ' data-stretch="true"' : ""} style="${snapshot.minWidth ? `min-width:${options.print ? "0" : `${snapshot.minWidth}px`};max-width:${snapshot.maxWidth}px;aspect-ratio:${snapshot.width}/${snapshot.height};` : ""}--k2b-chart-width:${snapshot.width}px;--k2b-chart-height:${snapshot.height}px">${svg}</div></div>${legendHtml}`;
|
|
633
|
+
const height =
|
|
634
|
+
options.print && snapshot.maxWidth
|
|
635
|
+
? `calc(min(100cqw, ${snapshot.maxWidth}px) * ${snapshot.height / snapshot.width})`
|
|
636
|
+
: notebookChartHeight(input, locale);
|
|
524
637
|
const figure = notebookChartFrameHtml(height ? { ...input, height } : input, viewport, {
|
|
525
638
|
legend: legend.length > 0,
|
|
526
639
|
...(options.print ? { print: true } : { input }),
|
|
@@ -13,9 +13,15 @@
|
|
|
13
13
|
import { syntaxTree } from "@codemirror/language";
|
|
14
14
|
import { type Text as DocText, type EditorSelection, type Extension, Prec, type Range } from "@codemirror/state";
|
|
15
15
|
import { Decoration, type DecorationSet, type EditorView, ViewPlugin, type ViewUpdate, WidgetType } from "@codemirror/view";
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
holdsDecorations,
|
|
18
|
+
markdownEditorFocused,
|
|
19
|
+
pointerSelectionHeld,
|
|
20
|
+
refreshesMarkdownDecorations,
|
|
21
|
+
revealedSelection,
|
|
22
|
+
} from "./_lib/cursor-zone-field";
|
|
17
23
|
import type { MarkdownRangeOptions } from "./_lib/list-structure";
|
|
18
|
-
import { blockMathPattern, inlineMathPattern } from "./_lib/math-syntax";
|
|
24
|
+
import { blockMathPattern, hasMathMarker, inlineMathPattern } from "./_lib/math-syntax";
|
|
19
25
|
import { findLigatures, frontMatterLength, type LigatureMatch } from "./lib/ligatures";
|
|
20
26
|
|
|
21
27
|
type Span = { from: number; to: number };
|
|
@@ -57,7 +63,7 @@ const notebookSyntax = (doc: DocText, options: MarkdownRangeOptions, cache: Weak
|
|
|
57
63
|
const spans: Span[] = [];
|
|
58
64
|
const frontMatter = frontMatterLength(markdown);
|
|
59
65
|
if (frontMatter) spans.push({ from: 0, to: frontMatter });
|
|
60
|
-
if (
|
|
66
|
+
if (hasMathMarker(markdown)) {
|
|
61
67
|
for (const pattern of [blockMathPattern(), inlineMathPattern()]) {
|
|
62
68
|
for (const match of markdown.matchAll(pattern)) spans.push({ from: match.index, to: match.index + match[0].length });
|
|
63
69
|
}
|
|
@@ -99,10 +105,10 @@ const findVisibleLigatures = (view: EditorView, options: MarkdownRangeOptions, c
|
|
|
99
105
|
};
|
|
100
106
|
|
|
101
107
|
/** Same rule as hidden Markdown marks: a selection that touches the sequence reveals it. */
|
|
102
|
-
const touched = (selection: EditorSelection, match: LigatureMatch): boolean =>
|
|
103
|
-
selection
|
|
108
|
+
const touched = (selection: EditorSelection | null, match: LigatureMatch): boolean =>
|
|
109
|
+
selection?.ranges.some((range) => range.from <= match.to && range.to >= match.from) ?? false;
|
|
104
110
|
|
|
105
|
-
const touchedKey = (selection: EditorSelection, matches: readonly LigatureMatch[]): string =>
|
|
111
|
+
const touchedKey = (selection: EditorSelection | null, matches: readonly LigatureMatch[]): string =>
|
|
106
112
|
matches.flatMap((match, index) => (touched(selection, match) ? [index] : [])).join(",");
|
|
107
113
|
|
|
108
114
|
class LigatureWidget extends WidgetType {
|
|
@@ -137,7 +143,7 @@ const ligatureDecoration = (symbol: string): Decoration => {
|
|
|
137
143
|
return decoration;
|
|
138
144
|
};
|
|
139
145
|
|
|
140
|
-
const decorate = (selection: EditorSelection, matches: readonly LigatureMatch[]): DecorationSet => {
|
|
146
|
+
const decorate = (selection: EditorSelection | null, matches: readonly LigatureMatch[]): DecorationSet => {
|
|
141
147
|
const ranges: Range<Decoration>[] = [];
|
|
142
148
|
for (const match of matches) {
|
|
143
149
|
if (!touched(selection, match)) ranges.push(ligatureDecoration(match.symbol).range(match.from, match.to));
|
|
@@ -148,46 +154,49 @@ const decorate = (selection: EditorSelection, matches: readonly LigatureMatch[])
|
|
|
148
154
|
/** Highest precedence: only marks of lower precedence, such as syntax highlighting, wrap a replaced widget, so the symbol keeps heading and emphasis styling. */
|
|
149
155
|
export const ligaturesExtension = (options: MarkdownRangeOptions = {}): Extension => {
|
|
150
156
|
const cache = new WeakMap<DocText, Span[]>();
|
|
151
|
-
return
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
update(update: ViewUpdate) {
|
|
167
|
-
const refresh = update.transactions.some((tr) => tr.effects.some((effect) => effect.is(refreshMarkdownDecorationsEffect)));
|
|
168
|
-
// While the button is down only pointer selections wait for the release; scrolling and edits keep the press-time selection.
|
|
169
|
-
const held =
|
|
170
|
-
update.state.field(pointerSelectionHeld, false) === true &&
|
|
171
|
-
!refresh &&
|
|
172
|
-
update.transactions.every((tr) => !tr.selection || holdsDecorations(tr));
|
|
173
|
-
if (held) {
|
|
174
|
-
if (update.docChanged) this.selection = this.selection.map(update.changes);
|
|
175
|
-
} else {
|
|
176
|
-
this.selection = update.state.selection;
|
|
157
|
+
return [
|
|
158
|
+
markdownEditorFocused,
|
|
159
|
+
Prec.highest(
|
|
160
|
+
ViewPlugin.fromClass(
|
|
161
|
+
class {
|
|
162
|
+
matches: LigatureMatch[];
|
|
163
|
+
selection: EditorSelection | null;
|
|
164
|
+
key: string;
|
|
165
|
+
decorations: DecorationSet;
|
|
166
|
+
|
|
167
|
+
constructor(view: EditorView) {
|
|
168
|
+
this.matches = findVisibleLigatures(view, options, cache);
|
|
169
|
+
this.selection = revealedSelection(view.state);
|
|
170
|
+
this.key = touchedKey(this.selection, this.matches);
|
|
171
|
+
this.decorations = decorate(this.selection, this.matches);
|
|
177
172
|
}
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
173
|
+
|
|
174
|
+
update(update: ViewUpdate) {
|
|
175
|
+
const refresh = update.transactions.some(refreshesMarkdownDecorations);
|
|
176
|
+
// While the button is down only pointer selections wait for the release; scrolling and edits keep the press-time selection.
|
|
177
|
+
const held =
|
|
178
|
+
update.state.field(pointerSelectionHeld, false) === true &&
|
|
179
|
+
!refresh &&
|
|
180
|
+
update.transactions.every((tr) => !tr.selection || holdsDecorations(tr));
|
|
181
|
+
if (held) {
|
|
182
|
+
if (update.docChanged) this.selection = this.selection?.map(update.changes) ?? null;
|
|
183
|
+
} else {
|
|
184
|
+
this.selection = revealedSelection(update.state);
|
|
185
|
+
}
|
|
186
|
+
const rescan =
|
|
187
|
+
update.docChanged || update.viewportChanged || syntaxTree(update.startState) !== syntaxTree(update.state) || refresh;
|
|
188
|
+
if (rescan) this.matches = findVisibleLigatures(update.view, options, cache);
|
|
189
|
+
else if (!update.selectionSet || update.transactions.every(holdsDecorations)) return;
|
|
190
|
+
const key = touchedKey(this.selection, this.matches);
|
|
191
|
+
if (!rescan && key === this.key) return;
|
|
192
|
+
this.key = key;
|
|
193
|
+
this.decorations = decorate(this.selection, this.matches);
|
|
194
|
+
}
|
|
195
|
+
},
|
|
196
|
+
{ decorations: (plugin) => plugin.decorations },
|
|
197
|
+
),
|
|
189
198
|
),
|
|
190
|
-
|
|
199
|
+
];
|
|
191
200
|
};
|
|
192
201
|
|
|
193
202
|
const LIGATURE_SKIP = "code, pre, a, time, .katex, .md-formula-ok, .md-formula-error";
|
package/src/markdown/links.ts
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
markdownReferenceType,
|
|
10
10
|
markdownReferenceTypeLabel,
|
|
11
11
|
} from "@k2b/ui";
|
|
12
|
-
import { type CursorZoneState, cursorZoneStateField, selectionIntersectsRange } from "./_lib/cursor-zone-field";
|
|
12
|
+
import { type CursorZoneState, cursorZoneStateField, revealedSelection, selectionIntersectsRange } from "./_lib/cursor-zone-field";
|
|
13
13
|
import { makeOpener } from "./_lib/link-opener";
|
|
14
14
|
import { parseNoteLink } from "./lib/heading-anchors";
|
|
15
15
|
import { extractAttachmentId, isSafeMarkdownUrl, type MarkdownUrlOptions } from "./urls";
|
|
@@ -122,7 +122,7 @@ const parseLinkSyntax = (text: string, options: MarkdownUrlOptions): LinkData |
|
|
|
122
122
|
const findLinks = (state: EditorState, options: MarkdownUrlOptions): CursorZoneState => {
|
|
123
123
|
const decorations: Range<Decoration>[] = [];
|
|
124
124
|
const ranges: { from: number; to: number }[] = [];
|
|
125
|
-
const cursor = state
|
|
125
|
+
const cursor = revealedSelection(state)?.main;
|
|
126
126
|
|
|
127
127
|
syntaxTree(state).iterate({
|
|
128
128
|
enter: ({ type, from, to }) => {
|
package/src/markdown/lists.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { EditorState, Extension, Range, Transaction } from "@codemirror/state";
|
|
2
2
|
import { StateField } from "@codemirror/state";
|
|
3
3
|
import { Decoration, type DecorationSet, EditorView, ViewPlugin, WidgetType } from "@codemirror/view";
|
|
4
|
-
import {
|
|
4
|
+
import { changedMarkdownBlocks, intersectsMarkdownSpans } from "./_lib/changed-blocks";
|
|
5
|
+
import { markdownEditorFocused, revealedSelection, treeOrDocChanged } from "./_lib/cursor-zone-field";
|
|
5
6
|
import {
|
|
6
7
|
type ExcludedSpan,
|
|
7
8
|
excludedSpans,
|
|
@@ -81,7 +82,9 @@ const decorated = (state: EditorState, item: ListItem): boolean =>
|
|
|
81
82
|
: /[ \t]/.test(state.sliceDoc(item.markerTo, item.markerTo + 1));
|
|
82
83
|
|
|
83
84
|
const selectionParent = (state: EditorState, structure: ListStructure): number => {
|
|
84
|
-
const
|
|
85
|
+
const cursor = revealedSelection(state)?.main;
|
|
86
|
+
if (!cursor) return -1;
|
|
87
|
+
const index = listItemAtLine(structure, state.doc.lineAt(cursor.head).number);
|
|
85
88
|
return structure.items[index]?.parent ?? -1;
|
|
86
89
|
};
|
|
87
90
|
|
|
@@ -106,13 +109,44 @@ type ListState = {
|
|
|
106
109
|
parent: number;
|
|
107
110
|
};
|
|
108
111
|
|
|
109
|
-
const build = (state: EditorState, cached?: readonly ExcludedSpan[]): ListState => {
|
|
112
|
+
const build = (state: EditorState, cached?: readonly ExcludedSpan[], incremental?: { value: ListState; tr: Transaction }): ListState => {
|
|
110
113
|
let excluded = cached;
|
|
114
|
+
const spans = incremental ? changedMarkdownBlocks(incremental.tr) : undefined;
|
|
111
115
|
// Notebook blocks are outside Markdown's grammar. Read their source only when lists exist.
|
|
112
|
-
const
|
|
116
|
+
const readExcluded = () => (excluded ??= excludedSpans(state));
|
|
117
|
+
let structure: ListStructure;
|
|
118
|
+
if (incremental && spans) {
|
|
119
|
+
const map = (position: number) => incremental.tr.changes.mapPos(position);
|
|
120
|
+
const items: ListItem[] = incremental.value.structure.items
|
|
121
|
+
.filter((item) => !intersectsMarkdownSpans(spans, map(item.markerFrom), map(item.markerTo)))
|
|
122
|
+
.map((item) => ({
|
|
123
|
+
...item,
|
|
124
|
+
from: map(item.from),
|
|
125
|
+
to: map(item.to),
|
|
126
|
+
line: state.doc.lineAt(map(item.from)).number,
|
|
127
|
+
markerFrom: map(item.markerFrom),
|
|
128
|
+
markerTo: map(item.markerTo),
|
|
129
|
+
contentFrom: map(item.contentFrom),
|
|
130
|
+
taskFrom: item.taskFrom === null ? null : map(item.taskFrom),
|
|
131
|
+
taskTo: item.taskTo === null ? null : map(item.taskTo),
|
|
132
|
+
listFrom: map(item.listFrom),
|
|
133
|
+
}));
|
|
134
|
+
for (const span of spans) items.push(...listStructure(state, readExcluded, span).items);
|
|
135
|
+
items.sort((a, b) => a.from - b.from);
|
|
136
|
+
const parents: number[] = [];
|
|
137
|
+
for (let index = 0; index < items.length; index++) {
|
|
138
|
+
const item = items[index]!;
|
|
139
|
+
while (parents.length > item.depth) items[parents.pop()!]!.subtreeEnd = index;
|
|
140
|
+
item.parent = parents.at(-1) ?? -1;
|
|
141
|
+
parents.push(index);
|
|
142
|
+
}
|
|
143
|
+
for (const index of parents) items[index]!.subtreeEnd = items.length;
|
|
144
|
+
structure = { items };
|
|
145
|
+
} else structure = listStructure(state, readExcluded);
|
|
113
146
|
const ranges: Range<Decoration>[] = [];
|
|
114
147
|
const atomic: Range<Decoration>[] = [];
|
|
115
148
|
for (const item of structure.items) {
|
|
149
|
+
if (spans && !intersectsMarkdownSpans(spans, item.from, item.contentFrom)) continue;
|
|
116
150
|
if (!decorated(state, item)) continue;
|
|
117
151
|
ranges.push(
|
|
118
152
|
Decoration.line({
|
|
@@ -131,11 +165,21 @@ const build = (state: EditorState, cached?: readonly ExcludedSpan[]): ListState
|
|
|
131
165
|
atomic.push(gutter);
|
|
132
166
|
}
|
|
133
167
|
const parent = selectionParent(state, structure);
|
|
168
|
+
const update = (previous: DecorationSet, add: Range<Decoration>[]) => {
|
|
169
|
+
let result = previous.map(incremental!.tr.changes);
|
|
170
|
+
if (spans!.length)
|
|
171
|
+
result = result.update({
|
|
172
|
+
filterFrom: spans![0]!.from,
|
|
173
|
+
filterTo: spans!.at(-1)!.to,
|
|
174
|
+
filter: (from, to) => !intersectsMarkdownSpans(spans!, from, from === to ? from + 1 : to),
|
|
175
|
+
});
|
|
176
|
+
return result.update({ add, sort: true });
|
|
177
|
+
};
|
|
134
178
|
return {
|
|
135
179
|
excluded,
|
|
136
180
|
structure,
|
|
137
|
-
decorations: Decoration.set(ranges, true),
|
|
138
|
-
atomicRanges: Decoration.set(atomic, true),
|
|
181
|
+
decorations: incremental ? update(incremental.value.decorations, ranges) : Decoration.set(ranges, true),
|
|
182
|
+
atomicRanges: incremental ? update(incremental.value.atomicRanges, atomic) : Decoration.set(atomic, true),
|
|
139
183
|
active: activeGuides(state, structure, parent),
|
|
140
184
|
parent,
|
|
141
185
|
};
|
|
@@ -179,10 +223,10 @@ export const listStateField = StateField.define<ListState>({
|
|
|
179
223
|
from: tr.changes.mapPos(span.from, -1),
|
|
180
224
|
to: tr.changes.mapPos(span.to, 1),
|
|
181
225
|
}));
|
|
182
|
-
return build(tr.state
|
|
226
|
+
return exclusionsChanged(tr) ? build(tr.state) : build(tr.state, excluded, { value, tr });
|
|
183
227
|
}
|
|
184
228
|
// Parser progress changes the list tree, but not the source-scanned spans.
|
|
185
|
-
if (treeOrDocChanged(tr)) return build(tr.state, value.excluded);
|
|
229
|
+
if (treeOrDocChanged(tr)) return build(tr.state, value.excluded, { value, tr });
|
|
186
230
|
const parent = selectionParent(tr.state, value.structure);
|
|
187
231
|
return {
|
|
188
232
|
...value,
|
|
@@ -194,6 +238,7 @@ export const listStateField = StateField.define<ListState>({
|
|
|
194
238
|
},
|
|
195
239
|
provide(field) {
|
|
196
240
|
return [
|
|
241
|
+
markdownEditorFocused,
|
|
197
242
|
EditorView.decorations.from(field, (value) => value.decorations),
|
|
198
243
|
EditorView.decorations.from(field, (value) => value.active),
|
|
199
244
|
EditorView.atomicRanges.of((view) => view.state.field(field).atomicRanges),
|