@mdbase-dev/ui 0.1.5 → 0.1.7

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/css/controls.css CHANGED
@@ -217,10 +217,10 @@ textarea.mdbase-field {
217
217
  max-width: min(420px, calc(100vw - 16px));
218
218
  margin: 0;
219
219
  overflow: auto;
220
- padding: 4px;
220
+ padding: var(--space-1);
221
221
  border: 1px solid var(--color-border-strong);
222
222
  /* Row radius plus the padding, so the corners stay concentric. */
223
- border-radius: calc(var(--control-radius) + 4px);
223
+ border-radius: calc(var(--control-radius) + var(--space-1));
224
224
  outline: 0;
225
225
  color: var(--color-text-soft);
226
226
  background: var(--color-surface);
@@ -289,9 +289,11 @@ textarea.mdbase-field {
289
289
  flex-direction: column;
290
290
  margin: 0;
291
291
  overflow: auto;
292
- padding: 5px;
292
+ --menu-inset: 5px;
293
+ padding: var(--menu-inset);
293
294
  border: 1px solid var(--color-border-strong);
294
- border-radius: calc(var(--control-radius) + 5px);
295
+ /* Row radius plus the padding, so the corners stay concentric. */
296
+ border-radius: calc(var(--control-radius) + var(--menu-inset));
295
297
  outline: 0;
296
298
  color: var(--color-text-soft);
297
299
  background: var(--color-surface-overlay);
@@ -686,14 +688,15 @@ textarea.mdbase-field {
686
688
  across when released. */
687
689
  .mdbase-switch {
688
690
  position: relative;
691
+ --switch-height: 22px;
689
692
  width: 36px;
690
- height: 22px;
693
+ height: var(--switch-height);
691
694
  flex: 0 0 auto;
692
695
  display: inline-flex;
693
696
  align-items: center;
694
697
  padding: 2px;
695
698
  border: 1px solid var(--color-border-strong);
696
- border-radius: 11px;
699
+ border-radius: calc(var(--switch-height) / 2);
697
700
  background: var(--color-surface-subtle);
698
701
  cursor: pointer;
699
702
  transition:
@@ -702,9 +705,11 @@ textarea.mdbase-field {
702
705
  }
703
706
 
704
707
  .mdbase-switch > span {
705
- width: 16px;
706
- height: 16px;
707
- border-radius: 8px;
708
+ --switch-thumb: 16px;
709
+ width: var(--switch-thumb);
710
+ height: var(--switch-thumb);
711
+ /* Half the height, not 50%: the thumb stays round-ended while it stretches. */
712
+ border-radius: calc(var(--switch-thumb) / 2);
708
713
  background: var(--color-text-muted);
709
714
  pointer-events: none;
710
715
  transition:
@@ -769,7 +774,8 @@ textarea.mdbase-field {
769
774
  display: inline-grid;
770
775
  grid-auto-flow: column;
771
776
  grid-auto-columns: minmax(0, 1fr);
772
- padding: 2px;
777
+ --segmented-inset: 2px;
778
+ padding: var(--segmented-inset);
773
779
  border: 1px solid var(--color-border);
774
780
  border-radius: var(--control-radius);
775
781
  background: var(--color-surface-subtle);
@@ -778,13 +784,14 @@ textarea.mdbase-field {
778
784
 
779
785
  .mdbase-segmented-thumb {
780
786
  position: absolute;
781
- top: 2px;
782
- bottom: 2px;
787
+ top: var(--segmented-inset);
788
+ bottom: var(--segmented-inset);
783
789
  border: 1px solid var(--color-border-strong);
784
- border-radius: calc(var(--control-radius) - 2px);
790
+ /* Track radius less its padding, so the corners stay concentric. */
791
+ border-radius: calc(var(--control-radius) - var(--segmented-inset));
785
792
  /* Raised reads as lighter than the track in both themes. */
786
793
  background: light-dark(var(--color-surface), var(--color-border-strong));
787
- box-shadow: 0 1px 2px var(--color-shadow);
794
+ box-shadow: var(--elevation-raised);
788
795
  pointer-events: none;
789
796
  }
790
797
 
@@ -807,7 +814,7 @@ textarea.mdbase-field {
807
814
  align-items: center;
808
815
  justify-content: center;
809
816
  padding: 0 10px;
810
- border-radius: calc(var(--control-radius) - 2px);
817
+ border-radius: calc(var(--control-radius) - var(--segmented-inset));
811
818
  color: var(--color-text-muted);
812
819
  font-weight: var(--font-weight-medium);
813
820
  white-space: nowrap;
@@ -1123,7 +1130,7 @@ textarea.mdbase-field {
1123
1130
  }
1124
1131
 
1125
1132
  .mdbase-switch:active:not(:disabled) > span {
1126
- width: 16px;
1133
+ width: var(--switch-thumb);
1127
1134
  }
1128
1135
 
1129
1136
  .mdbase-switch[aria-checked="true"]:active:not(:disabled) > span {
@@ -380,6 +380,9 @@
380
380
  .cm-lp-code-header button:hover, .cm-lp-callout-header button:hover { background: var(--color-surface); color: var(--color-text); }
381
381
  .cm-lp-code-header button:focus-visible, .cm-lp-callout-header button:focus-visible { outline: 2px solid var(--color-accent); outline-offset: 1px; }
382
382
 
383
+ /* A block widget's box: CodeMirror measures it by its border box, so it contains what is drawn, margins included. */
384
+ .cm-lp-block { display: flow-root; }
385
+
383
386
  .cm-lp-math-source { font-family: var(--mono); font-size: 0.92em; }
384
387
  .cm-lp-math-pending, .cm-lp-math-failed { color: var(--color-text-muted); font-family: var(--mono); font-size: 0.92em; white-space: pre-wrap; }
385
388
  .cm-lp-math-failed { text-decoration: underline dotted var(--color-danger); }
package/css/palette.css CHANGED
@@ -112,6 +112,11 @@
112
112
  font-weight: var(--font-weight-medium);
113
113
  }
114
114
 
115
+ /* The selected fill is deep enough that muted text on it falls below 4.5:1. */
116
+ .mdbase-command-results > button[aria-selected="true"] :is(small, kbd, .mdbase-command-alternate) {
117
+ color: var(--color-text-soft);
118
+ }
119
+
115
120
  .mdbase-command-results mark {
116
121
  color: inherit;
117
122
  background: var(--accent-soft);
package/css/tokens.css CHANGED
@@ -71,6 +71,7 @@
71
71
  --radius-sm: 6px;
72
72
  --radius-md: 8px;
73
73
  --radius-lg: 10px;
74
+ --elevation-raised: 0 1px 2px var(--color-shadow);
74
75
  --elevation-low: 0 4px 12px var(--color-shadow);
75
76
  --elevation-high: 0 12px 32px var(--color-shadow);
76
77
  --space-0: 0;
@@ -5,6 +5,7 @@ import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
5
5
  import { i18n as _i18n } from "@lingui/core";
6
6
  import { DiagramWidget, isDiagramLanguage } from "./diagram.js";
7
7
  import { proseEdit } from "./prose-edit.js";
8
+ import { drawnBlocks, isDrawn, renderedBlockLayer, renderedBlocks } from "./rendered-blocks.js";
8
9
  import { isRevealed, revealField } from "./reveal.js";
9
10
  const toggleFold = StateEffect.define({
10
11
  map: (value, changes) => ({
@@ -386,7 +387,7 @@ const structure = StateField.define({
386
387
  }
387
388
  });
388
389
  export function blockPreview() {
389
- return [folds, structure, EditorView.decorations.compute([structure, revealField, folds], build), keymap.of([{
390
+ return [folds, structure, renderedBlocks.compute([structure, folds], rendered), renderedBlockLayer, EditorView.decorations.compute([structure, revealField, folds, drawnBlocks], build), keymap.of([{
390
391
  key: "Tab",
391
392
  run: view => inCode(view.state) && indentMore(view)
392
393
  }, {
@@ -402,6 +403,30 @@ function inCode(state) {
402
403
  head
403
404
  }) => codes.some(block => head > block.from && head < block.to));
404
405
  }
406
+ function isFolded(callout, foldState) {
407
+ return callout.fold ? foldState.get(callout.from) ?? callout.fold === "-" : false;
408
+ }
409
+ /** Diagrams, and the bodies of folded callouts. */
410
+ function rendered(state) {
411
+ const {
412
+ codes,
413
+ callouts
414
+ } = state.field(structure);
415
+ const foldState = state.field(folds);
416
+ const blocks = [];
417
+ for (const block of codes) if (block.diagram) blocks.push({
418
+ from: block.from,
419
+ to: block.to,
420
+ widget: new DiagramWidget(block.code)
421
+ });
422
+ for (const callout of callouts) {
423
+ if (callout.lines.length > 1 && isFolded(callout, foldState)) blocks.push({
424
+ from: callout.to + 1,
425
+ to: callout.lastTo
426
+ });
427
+ }
428
+ return blocks;
429
+ }
405
430
  function build(state) {
406
431
  const ranges = [];
407
432
  const {
@@ -415,13 +440,8 @@ function build(state) {
415
440
  for (const block of codes) {
416
441
  const first = block.lines[0],
417
442
  last = block.lines[block.lines.length - 1];
418
- if (block.diagram && !isRevealed(state, block.from, block.to)) {
419
- ranges.push(Decoration.replace({
420
- widget: new DiagramWidget(block.code),
421
- block: true
422
- }).range(first.from, last.to));
423
- continue;
424
- }
443
+ // A drawn diagram stands for these lines; see `rendered`.
444
+ if (block.diagram && isDrawn(state, first.from)) continue;
425
445
  block.lines.forEach((line, index) => {
426
446
  const edge = `${index === 0 ? "cm-lp-code-first" : ""} ${index === block.lines.length - 1 ? "cm-lp-code-last" : ""}`;
427
447
  ranges.push(codeLine(edge).range(line.from));
@@ -441,7 +461,7 @@ function build(state) {
441
461
  if (block.closed && !isRevealed(state, last.from, last.to)) ranges.push(hide.range(last.from, last.to));
442
462
  }
443
463
  for (const callout of callouts) {
444
- const folded = callout.fold ? foldState.get(callout.from) ?? callout.fold === "-" : false;
464
+ const folded = isFolded(callout, foldState);
445
465
  callout.lines.forEach((from, index) => {
446
466
  const last = index === callout.lines.length - 1;
447
467
  ranges.push(Decoration.line({
@@ -453,11 +473,6 @@ function build(state) {
453
473
  widget: new CalloutHeader(callout.type, callout.title ?? typeTitle(callout.type), callout.from, !!callout.fold, folded)
454
474
  }).range(callout.from, callout.to));
455
475
  }
456
- if (folded && callout.lines.length > 1 && !isRevealed(state, callout.to + 1, callout.lastTo)) {
457
- ranges.push(Decoration.replace({
458
- block: true
459
- }).range(callout.to + 1, callout.lastTo));
460
- }
461
476
  }
462
477
  for (const from of definitionLines) ranges.push(Decoration.line({
463
478
  class: "cm-lp-footnote-definition"
@@ -1,6 +1,6 @@
1
1
  import type { EditorView } from "@codemirror/view";
2
- import { WidgetType } from "@codemirror/view";
3
2
  import "../i18n.js";
3
+ import { BlockWidget } from "./rendered-blocks.js";
4
4
  /**
5
5
  * A Mermaid diagram, rendered by Pele in place of its fenced source while the
6
6
  * selection is elsewhere. Pele and each diagram type load on first use, so a
@@ -11,12 +11,12 @@ import "../i18n.js";
11
11
  * and links only open in a new tab.
12
12
  */
13
13
  export declare function isDiagramLanguage(language: string): boolean;
14
- export declare class DiagramWidget extends WidgetType {
14
+ export declare class DiagramWidget extends BlockWidget {
15
15
  readonly source: string;
16
+ protected readonly heightKey: string;
16
17
  constructor(source: string);
17
18
  eq(other: DiagramWidget): boolean;
18
- get estimatedHeight(): number;
19
- toDOM(view: EditorView): HTMLDivElement;
20
- destroy(dom: HTMLElement): void;
19
+ protected draw(view: EditorView, hold: () => () => void): HTMLDivElement;
20
+ protected discard(box: HTMLElement): void;
21
21
  ignoreEvent(): boolean;
22
22
  }
@@ -1,7 +1,7 @@
1
- import { WidgetType } from "@codemirror/view";
2
1
  import { i18n as _i18n } from "@lingui/core";
3
2
  import "../i18n.js";
4
3
  import { lazily } from "./lazy.js";
4
+ import { BlockWidget } from "./rendered-blocks.js";
5
5
  /**
6
6
  * A Mermaid diagram, rendered by Pele in place of its fenced source while the
7
7
  * selection is elsewhere. Pele and each diagram type load on first use, so a
@@ -15,16 +15,8 @@ export function isDiagramLanguage(language) {
15
15
  return language.toLowerCase() === "mermaid";
16
16
  }
17
17
  const loadRenderer = lazily(() => import("pele/lazy"));
18
- /** Last rendered height per source, so a re-created widget reserves its space before rendering. */
19
- const heights = new Map();
20
- const HEIGHT_ENTRIES = 256;
21
- function rememberHeight(source, height) {
22
- heights.delete(source);
23
- heights.set(source, height);
24
- if (heights.size > HEIGHT_ENTRIES) heights.delete(heights.keys().next().value);
25
- }
26
18
  const mounts = new WeakMap();
27
- function renderOptions(view, box, source) {
19
+ function renderOptions(onRender) {
28
20
  return {
29
21
  images: false,
30
22
  linkSchemes: ["http", "https", "mailto"],
@@ -51,32 +43,24 @@ function renderOptions(view, box, source) {
51
43
  })
52
44
  }
53
45
  },
54
- onRender: () => view.requestMeasure({
55
- read: () => box.offsetHeight,
56
- write: height => {
57
- if (height > 0) rememberHeight(source, height);
58
- box.style.minHeight = "";
59
- }
60
- })
46
+ onRender
61
47
  };
62
48
  }
63
- export class DiagramWidget extends WidgetType {
49
+ export class DiagramWidget extends BlockWidget {
64
50
  source;
51
+ heightKey;
65
52
  constructor(source) {
66
53
  super();
67
54
  this.source = source;
55
+ this.heightKey = `diagram:${source}`;
68
56
  }
69
57
  eq(other) {
70
58
  return this.source === other.source;
71
59
  }
72
- get estimatedHeight() {
73
- return heights.get(this.source) ?? -1;
74
- }
75
- toDOM(view) {
60
+ draw(view, hold) {
76
61
  const box = document.createElement("div");
77
62
  box.className = "cm-lp-diagram";
78
- const height = heights.get(this.source);
79
- if (height) box.style.minHeight = `${height}px`;
63
+ const drawn = hold();
80
64
  const canvas = document.createElement("div");
81
65
  canvas.className = "cm-lp-diagram-canvas";
82
66
  const edit = document.createElement("button");
@@ -106,12 +90,11 @@ export class DiagramWidget extends WidgetType {
106
90
  mountAsync
107
91
  }) => {
108
92
  if (state.destroyed) return;
109
- return mountAsync(canvas, this.source, renderOptions(view, box, this.source)).then(mounted => {
93
+ return mountAsync(canvas, this.source, renderOptions(drawn)).then(mounted => {
110
94
  if (state.destroyed) mounted.destroy();else state.mounted = mounted;
111
95
  });
112
96
  }).catch(() => {
113
97
  if (state.destroyed) return;
114
- box.style.minHeight = "";
115
98
  canvas.className = "cm-lp-diagram-canvas cm-lp-diagram-failed";
116
99
  canvas.textContent = _i18n._(
117
100
  /** i18n */
@@ -119,11 +102,12 @@ export class DiagramWidget extends WidgetType {
119
102
  id: "MlIz7Y",
120
103
  message: "The diagram could not be shown. Check your connection and reopen the note."
121
104
  });
105
+ drawn();
122
106
  });
123
107
  return box;
124
108
  }
125
- destroy(dom) {
126
- const state = mounts.get(dom);
109
+ discard(box) {
110
+ const state = mounts.get(box);
127
111
  if (!state) return;
128
112
  state.destroyed = true;
129
113
  state.mounted?.destroy();
@@ -2,6 +2,7 @@ import { StateField } from "@codemirror/state";
2
2
  import { EditorView, WidgetType } from "@codemirror/view";
3
3
  import type { MarkdownConfig } from "@lezer/markdown";
4
4
  import "../i18n.js";
5
+ import { BlockWidget } from "./rendered-blocks.js";
5
6
  /**
6
7
  * `$…$` and `$$…$$` math as Markdown syntax: `InlineMath` and `MathBlock`
7
8
  * nodes, each with two `MathMark` children around the TeX. Add it to the
@@ -15,19 +16,25 @@ import "../i18n.js";
15
16
  * container, like an unclosed code fence.
16
17
  */
17
18
  export declare const markdownMath: MarkdownConfig;
18
- /** Where a formula sits: in text, as a display formula in text, as its own block, or under its revealed source. */
19
- type MathKind = "inline" | "display" | "block" | "preview";
20
- /**
21
- * A formula rendered by KaTeX. Formula text is untrusted: `trust` stays off,
22
- * so commands such as `\href` and `\includegraphics` render as errors, and
23
- * sizes are capped. KaTeX loads with the first formula.
24
- */
19
+ /** Where a formula sits in text: within a line, or as a display formula. */
20
+ type MathKind = "inline" | "display";
21
+ /** A formula in a line of text. */
25
22
  export declare class MathWidget extends WidgetType {
26
23
  readonly source: string;
27
24
  readonly kind: MathKind;
28
25
  constructor(source: string, kind: MathKind);
29
26
  eq(other: MathWidget): boolean;
30
- toDOM(view: EditorView): HTMLDivElement | HTMLSpanElement;
27
+ toDOM(view: EditorView): HTMLSpanElement;
28
+ ignoreEvent(): boolean;
29
+ }
30
+ /** A display formula as its own block, or as the preview under its revealed source. */
31
+ export declare class MathBlockWidget extends BlockWidget {
32
+ readonly source: string;
33
+ readonly kind: "block" | "preview";
34
+ protected readonly heightKey: string;
35
+ constructor(source: string, kind: "block" | "preview");
36
+ eq(other: MathBlockWidget): boolean;
37
+ protected draw(_view: EditorView, hold: () => () => void): HTMLDivElement;
31
38
  ignoreEvent(): boolean;
32
39
  }
33
40
  interface Formula {
@@ -5,6 +5,7 @@ import { i18n as _i18n } from "@lingui/core";
5
5
  import "../i18n.js";
6
6
  import { lazily } from "./lazy.js";
7
7
  import { proseEdit } from "./prose-edit.js";
8
+ import { BlockWidget, drawnBlocks, isDrawn, renderedBlockLayer, renderedBlocks } from "./rendered-blocks.js";
8
9
  import { isRevealed, revealField } from "./reveal.js";
9
10
  const DOLLAR = 36,
10
11
  BACKSLASH = 92,
@@ -106,6 +107,29 @@ let katex;
106
107
  * so commands such as `\href` and `\includegraphics` render as errors, and
107
108
  * sizes are capped. KaTeX loads with the first formula.
108
109
  */
110
+ function formula(element, source, display, loading) {
111
+ if (katex) {
112
+ render(katex, element, source, display);
113
+ return;
114
+ }
115
+ const arrived = loading();
116
+ element.classList.add("cm-lp-math-pending");
117
+ element.textContent = source;
118
+ loadKatex().then(loaded => {
119
+ katex = loaded;
120
+ element.classList.remove("cm-lp-math-pending");
121
+ render(loaded, element, source, display);
122
+ }).catch(() => {
123
+ element.classList.replace("cm-lp-math-pending", "cm-lp-math-failed");
124
+ element.title = _i18n._(
125
+ /** i18n */
126
+ {
127
+ id: "2ORwUL",
128
+ message: "Formulas could not be shown. Check your connection and reopen the note."
129
+ });
130
+ }).finally(arrived);
131
+ }
132
+ /** A formula in a line of text. */
109
133
  export class MathWidget extends WidgetType {
110
134
  source;
111
135
  kind;
@@ -118,28 +142,9 @@ export class MathWidget extends WidgetType {
118
142
  return this.source === other.source && this.kind === other.kind;
119
143
  }
120
144
  toDOM(view) {
121
- const element = document.createElement(this.kind === "block" || this.kind === "preview" ? "div" : "span");
145
+ const element = document.createElement("span");
122
146
  element.className = `cm-lp-math cm-lp-math-${this.kind}`;
123
- if (katex) {
124
- render(katex, element, this.source, this.kind !== "inline");
125
- return element;
126
- }
127
- element.classList.add("cm-lp-math-pending");
128
- element.textContent = this.source;
129
- loadKatex().then(loaded => {
130
- katex = loaded;
131
- element.classList.remove("cm-lp-math-pending");
132
- render(loaded, element, this.source, this.kind !== "inline");
133
- view.requestMeasure();
134
- }).catch(() => {
135
- element.classList.replace("cm-lp-math-pending", "cm-lp-math-failed");
136
- element.title = _i18n._(
137
- /** i18n */
138
- {
139
- id: "2ORwUL",
140
- message: "Formulas could not be shown. Check your connection and reopen the note."
141
- });
142
- });
147
+ formula(element, this.source, this.kind !== "inline", () => () => view.requestMeasure());
143
148
  return element;
144
149
  }
145
150
  // A press on a formula places the caret beside it, which reveals its source.
@@ -147,6 +152,30 @@ export class MathWidget extends WidgetType {
147
152
  return false;
148
153
  }
149
154
  }
155
+ /** A display formula as its own block, or as the preview under its revealed source. */
156
+ export class MathBlockWidget extends BlockWidget {
157
+ source;
158
+ kind;
159
+ heightKey;
160
+ constructor(source, kind) {
161
+ super();
162
+ this.source = source;
163
+ this.kind = kind;
164
+ this.heightKey = `math-${kind}:${source}`;
165
+ }
166
+ eq(other) {
167
+ return this.source === other.source && this.kind === other.kind;
168
+ }
169
+ draw(_view, hold) {
170
+ const element = document.createElement("div");
171
+ element.className = `cm-lp-math cm-lp-math-${this.kind}`;
172
+ formula(element, this.source, true, hold);
173
+ return element;
174
+ }
175
+ ignoreEvent() {
176
+ return false;
177
+ }
178
+ }
150
179
  function render(module, element, source, display) {
151
180
  // Invalid TeX renders as its source, coloured, with KaTeX's message as the title.
152
181
  module.render(source, element, {
@@ -207,25 +236,30 @@ const formulaField = StateField.define({
207
236
  });
208
237
  /** Renders `markdownMath` formulas where the selection is not, and shows a rendered preview under a revealed display block. */
209
238
  export function mathPreview() {
210
- return [formulaField, EditorView.decorations.compute([formulaField, revealField], build)];
239
+ return [formulaField, renderedBlocks.compute([formulaField], rendered), renderedBlockLayer, EditorView.decorations.compute([formulaField, revealField, drawnBlocks], build)];
240
+ }
241
+ /** Quote and list markers would be part of a nested display block, so only top-level ones are drawn as blocks. */
242
+ function rendered(state) {
243
+ return state.field(formulaField).flatMap(formula => formula.source && formula.topLevel ? [{
244
+ from: formula.first,
245
+ to: formula.lastTo,
246
+ widget: new MathBlockWidget(formula.source, "block")
247
+ }] : []);
211
248
  }
212
249
  function build(state) {
213
250
  const ranges = [];
214
251
  for (const formula of state.field(formulaField)) {
215
- const revealed = isRevealed(state, formula.from, formula.to);
216
- // Quote and list markers would be part of a nested multi-line formula, so it stays source.
217
- if (!formula.source || revealed || !formula.topLevel && formula.last > 0) {
252
+ if (formula.topLevel) {
253
+ // Drawn as a block, or shown as source with a preview under it.
254
+ if (formula.source && isDrawn(state, formula.first)) continue;
218
255
  ranges.push(sourceMark.range(formula.from, formula.to));
219
- if (formula.source && revealed && formula.topLevel) ranges.push(Decoration.widget({
220
- widget: new MathWidget(formula.source, "preview"),
256
+ if (formula.source) ranges.push(Decoration.widget({
257
+ widget: new MathBlockWidget(formula.source, "preview"),
221
258
  block: true,
222
259
  side: 1
223
260
  }).range(formula.lastTo));
224
- } else if (formula.topLevel) {
225
- ranges.push(Decoration.replace({
226
- widget: new MathWidget(formula.source, "block"),
227
- block: true
228
- }).range(formula.first, formula.lastTo));
261
+ } else if (!formula.source || formula.last > 0 || isRevealed(state, formula.from, formula.to)) {
262
+ ranges.push(sourceMark.range(formula.from, formula.to));
229
263
  } else {
230
264
  ranges.push(Decoration.replace({
231
265
  widget: new MathWidget(formula.source, formula.display ? "display" : "inline")
@@ -0,0 +1,51 @@
1
+ import { Facet, type EditorState, type Extension } from "@codemirror/state";
2
+ import { EditorView, WidgetType } from "@codemirror/view";
3
+ /**
4
+ * Source shown as one drawn block: a diagram, a display formula, an embed, a
5
+ * folded callout body. The block stands for the whole lines that hold
6
+ * [from, to], and its source shows instead while a focused selection touches
7
+ * those lines.
8
+ */
9
+ export interface RenderedBlock {
10
+ from: number;
11
+ to: number;
12
+ /** What is drawn in the lines' place. Without one the lines are only hidden. */
13
+ widget?: BlockWidget;
14
+ }
15
+ /**
16
+ * Every rendered block in the note. Each kind of block provides its own, from
17
+ * its own state; this is the one place they become decorations, so every kind
18
+ * is revealed by the same rule and two kinds never draw over the same lines.
19
+ */
20
+ export declare const renderedBlocks: Facet<readonly RenderedBlock[], readonly (readonly RenderedBlock[])[]>;
21
+ /** The blocks that are drawn: on whole lines, in order, none inside another, none whose source is revealed. */
22
+ export declare const drawnBlocks: import("@codemirror/state").FacetReader<readonly RenderedBlock[]>;
23
+ /** Whether a drawn block stands for the line at `position`. */
24
+ export declare function isDrawn(state: EditorState, position: number): boolean;
25
+ /** Draws `renderedBlocks`. Each provider of blocks includes it; it is installed once. */
26
+ export declare const renderedBlockLayer: Extension;
27
+ /**
28
+ * A widget drawn between lines of text. CodeMirror places every later line by
29
+ * the heights of the blocks before it, so a block's height has to be what
30
+ * CodeMirror thinks it is, before it is drawn, while it loads and after:
31
+ *
32
+ * - The block is measured by its border box. What a kind draws sits inside a
33
+ * box that contains its margins, so they count.
34
+ * - A block not yet drawn is estimated at the height it last had.
35
+ * - A block whose content arrives later holds that height meanwhile, and
36
+ * CodeMirror measures it again whenever its size changes.
37
+ */
38
+ export declare abstract class BlockWidget extends WidgetType {
39
+ /** Names what is drawn, across every kind of block: two blocks with one key are as tall as each other. */
40
+ protected abstract readonly heightKey: string;
41
+ /**
42
+ * Draws the block. A kind whose content arrives later calls `hold` first and
43
+ * the function it returns once the content is in place.
44
+ */
45
+ protected abstract draw(view: EditorView, hold: () => () => void): HTMLElement;
46
+ /** Releases what `draw` made, given the element it returned. */
47
+ protected discard(_drawn: HTMLElement): void;
48
+ get estimatedHeight(): number;
49
+ toDOM(view: EditorView): HTMLDivElement;
50
+ destroy(box: HTMLElement): void;
51
+ }
@@ -0,0 +1,110 @@
1
+ import { Facet } from "@codemirror/state";
2
+ import { Decoration, EditorView, WidgetType } from "@codemirror/view";
3
+ import { isRevealed, revealField } from "./reveal.js";
4
+ /**
5
+ * Every rendered block in the note. Each kind of block provides its own, from
6
+ * its own state; this is the one place they become decorations, so every kind
7
+ * is revealed by the same rule and two kinds never draw over the same lines.
8
+ */
9
+ export const renderedBlocks = Facet.define();
10
+ function resolve(state) {
11
+ const blocks = state.facet(renderedBlocks).flat().map(block => ({
12
+ ...block,
13
+ from: state.doc.lineAt(block.from).from,
14
+ to: state.doc.lineAt(block.to).to
15
+ })).sort((a, b) => a.from - b.from || b.to - a.to);
16
+ const drawn = [];
17
+ let end = -1;
18
+ for (const block of blocks) {
19
+ // A block inside a drawn one, such as an embed in a folded callout, is covered by it.
20
+ if (block.from <= end || isRevealed(state, block.from, block.to)) continue;
21
+ drawn.push(block);
22
+ end = block.to;
23
+ }
24
+ return drawn;
25
+ }
26
+ const drawn = Facet.define({
27
+ combine: values => values[0] ?? []
28
+ });
29
+ /** The blocks that are drawn: on whole lines, in order, none inside another, none whose source is revealed. */
30
+ export const drawnBlocks = drawn.reader;
31
+ /** Whether a drawn block stands for the line at `position`. */
32
+ export function isDrawn(state, position) {
33
+ return state.facet(drawnBlocks).some(block => block.from <= position && position <= block.to);
34
+ }
35
+ /** Draws `renderedBlocks`. Each provider of blocks includes it; it is installed once. */
36
+ export const renderedBlockLayer = [drawn.compute([renderedBlocks, revealField], resolve), EditorView.decorations.compute([drawn], state => Decoration.set(state.facet(drawnBlocks).map(block => Decoration.replace({
37
+ block: true,
38
+ widget: block.widget
39
+ }).range(block.from, block.to))))];
40
+ /** Last drawn height per block, so one drawn again takes its space before its content arrives. */
41
+ const heights = new Map();
42
+ const HEIGHT_ENTRIES = 512;
43
+ function rememberHeight(key, height) {
44
+ heights.delete(key);
45
+ heights.set(key, height);
46
+ if (heights.size > HEIGHT_ENTRIES) heights.delete(heights.keys().next().value);
47
+ }
48
+ const hosts = new WeakMap();
49
+ // CodeMirror measures a block when the editor updates, not when the block's own content arrives.
50
+ const resized = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(entries => {
51
+ for (const {
52
+ target
53
+ } of entries) {
54
+ const host = hosts.get(target);
55
+ if (!host) continue;
56
+ const height = target.offsetHeight;
57
+ if (!host.holds && height > 0) rememberHeight(host.key, height);
58
+ host.view.requestMeasure();
59
+ }
60
+ });
61
+ /**
62
+ * A widget drawn between lines of text. CodeMirror places every later line by
63
+ * the heights of the blocks before it, so a block's height has to be what
64
+ * CodeMirror thinks it is, before it is drawn, while it loads and after:
65
+ *
66
+ * - The block is measured by its border box. What a kind draws sits inside a
67
+ * box that contains its margins, so they count.
68
+ * - A block not yet drawn is estimated at the height it last had.
69
+ * - A block whose content arrives later holds that height meanwhile, and
70
+ * CodeMirror measures it again whenever its size changes.
71
+ */
72
+ export class BlockWidget extends WidgetType {
73
+ /** Releases what `draw` made, given the element it returned. */
74
+ discard(_drawn) {}
75
+ get estimatedHeight() {
76
+ return heights.get(this.heightKey) ?? -1;
77
+ }
78
+ toDOM(view) {
79
+ const box = document.createElement("div");
80
+ box.className = "cm-lp-block";
81
+ const host = {
82
+ view,
83
+ key: this.heightKey,
84
+ holds: 0
85
+ };
86
+ const height = heights.get(this.heightKey);
87
+ box.append(this.draw(view, () => {
88
+ host.holds += 1;
89
+ if (height) box.style.minHeight = `${height}px`;
90
+ let held = true;
91
+ return () => {
92
+ if (!held) return;
93
+ held = false;
94
+ host.holds -= 1;
95
+ if (host.holds) return;
96
+ box.style.minHeight = "";
97
+ if (box.offsetHeight > 0) rememberHeight(host.key, box.offsetHeight);
98
+ view.requestMeasure();
99
+ };
100
+ }));
101
+ hosts.set(box, host);
102
+ resized?.observe(box);
103
+ return box;
104
+ }
105
+ destroy(box) {
106
+ resized?.unobserve(box);
107
+ hosts.delete(box);
108
+ if (box.firstElementChild instanceof HTMLElement) this.discard(box.firstElementChild);
109
+ }
110
+ }
@@ -4,6 +4,7 @@ export type { LivePreviewLink, LivePreviewOptions } from "./live-preview/inline.
4
4
  export { isRevealed, revealField as livePreviewReveal } from "./live-preview/reveal.js";
5
5
  export { indentListItem, outdentListItem } from "./live-preview/keys.js";
6
6
  export { markdownMath } from "./live-preview/math.js";
7
+ export { BlockWidget, renderedBlocks, type RenderedBlock } from "./live-preview/rendered-blocks.js";
7
8
  /**
8
9
  * Live preview for a CodeMirror Markdown editor: the note reads as rendered
9
10
  * text, and each element shows its Markdown only while the selection touches
@@ -13,6 +14,9 @@ export { markdownMath } from "./live-preview/math.js";
13
14
  *
14
15
  * Rendered links carry `data-link-from` (the link's source offset) and
15
16
  * `data-link-format`; opening them is the app's choice. App widgets, such as
16
- * embeds, should follow the same rule through `isRevealed`.
17
+ * embeds, should follow the same rule through `isRevealed`. A widget that
18
+ * stands for whole lines extends `BlockWidget` and is listed in
19
+ * `renderedBlocks`: it is then drawn, revealed and measured like the
20
+ * preview's own blocks.
17
21
  */
18
22
  export declare function livePreview(options?: LivePreviewOptions): Extension;
@@ -8,6 +8,7 @@ import { revealTracking } from "./live-preview/reveal.js";
8
8
  export { isRevealed, revealField as livePreviewReveal } from "./live-preview/reveal.js";
9
9
  export { indentListItem, outdentListItem } from "./live-preview/keys.js";
10
10
  export { markdownMath } from "./live-preview/math.js";
11
+ export { BlockWidget, renderedBlocks } from "./live-preview/rendered-blocks.js";
11
12
  /**
12
13
  * Live preview for a CodeMirror Markdown editor: the note reads as rendered
13
14
  * text, and each element shows its Markdown only while the selection touches
@@ -17,7 +18,10 @@ export { markdownMath } from "./live-preview/math.js";
17
18
  *
18
19
  * Rendered links carry `data-link-from` (the link's source offset) and
19
20
  * `data-link-format`; opening them is the app's choice. App widgets, such as
20
- * embeds, should follow the same rule through `isRevealed`.
21
+ * embeds, should follow the same rule through `isRevealed`. A widget that
22
+ * stands for whole lines extends `BlockWidget` and is listed in
23
+ * `renderedBlocks`: it is then drawn, revealed and measured like the
24
+ * preview's own blocks.
21
25
  */
22
26
  export function livePreview(options = {}) {
23
27
  return [revealTracking(), blockPreview(), mathPreview(), inlinePreview(options), tablePreview(), livePreviewKeys, taskToggle];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mdbase-dev/ui",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -250,6 +250,6 @@
250
250
  "typecheck": "node scripts/compile-catalogues.mjs && tsc -p tsconfig.json --noEmit"
251
251
  },
252
252
  "mdbaseRelease": {
253
- "commit": "e722651e56b311c05f28124b673ef403c1a69898"
253
+ "commit": "e433a42fa6c09dbc44436afe0a01654c1d7d2bce"
254
254
  }
255
255
  }