@dou-ui/code 0.1.0-alpha.23 → 0.1.0-alpha.25

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 (41) hide show
  1. package/dist/assets/default-BWWFJmzn.js.map +1 -0
  2. package/dist/code-diff.js.map +1 -1
  3. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js +196 -18
  4. package/dist/code-diff.vue_vue_type_script_setup_true_lang.js.map +1 -1
  5. package/dist/code-editor.js.map +1 -1
  6. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js +636 -461
  7. package/dist/code-editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
  8. package/dist/extension.js.map +1 -1
  9. package/dist/index.js +3 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/language/highlighter.js +1 -1
  12. package/dist/language/highlighter.js.map +1 -1
  13. package/dist/language/language.js +24 -2
  14. package/dist/language/language.js.map +1 -1
  15. package/dist/language/remote-tokens.js +131 -0
  16. package/dist/language/remote-tokens.js.map +1 -0
  17. package/dist/language/worker-client.js +308 -33
  18. package/dist/language/worker-client.js.map +1 -1
  19. package/dist/language/worker-protocol.js.map +1 -1
  20. package/dist/shiki/index.js +54 -3
  21. package/dist/shiki/index.js.map +1 -1
  22. package/dist/style.css +1 -1
  23. package/dist/types/code-diff.vue.d.ts +4 -1
  24. package/dist/types/code-editor.vue.d.ts +2 -1
  25. package/dist/types/extension.d.ts +13 -1
  26. package/dist/types/index.d.ts +18 -6
  27. package/dist/types/language/language.d.ts +27 -0
  28. package/dist/types/language/remote-tokens.d.ts +38 -0
  29. package/dist/types/language/worker-client.d.ts +85 -15
  30. package/dist/types/language/worker-protocol.d.ts +53 -2
  31. package/dist/types/shiki/index.d.ts +36 -1
  32. package/dist/types/types.d.ts +43 -8
  33. package/dist/types/view/measure.d.ts +6 -0
  34. package/dist/types/worker/index.d.ts +27 -12
  35. package/dist/view/measure.js +23 -5
  36. package/dist/view/measure.js.map +1 -1
  37. package/dist/worker/default.js +1 -1
  38. package/dist/worker/index.js +280 -53
  39. package/dist/worker/index.js.map +1 -1
  40. package/package.json +3 -3
  41. package/dist/assets/default-BZBMZKf_.js.map +0 -1
@@ -1,6 +1,9 @@
1
- import type { CodeLanguage } from './language';
1
+ import type { CodeDiffHunk, CodeDiffOptions } from '../core/diff';
2
+ import type { CodeLanguage, CodeLineTokens } from './language';
2
3
  /** A change as sent: `[from, to, insert]`. */
3
4
  export type WireChange = [from: number, to: number, insert: string];
5
+ /** How a worker transfers syntax results back to the page for a document. */
6
+ export type WorkerSyntaxMode = 'auto' | 'states' | 'tokens';
4
7
  export type ToWorker =
5
8
  /** `nested`: the names of the languages it may hold, which the worker's language must hold too. */
6
9
  {
@@ -9,6 +12,7 @@ export type ToWorker =
9
12
  language: string;
10
13
  nested: string[];
11
14
  tabSize: number;
15
+ mode?: WorkerSyntaxMode;
12
16
  }
13
17
  /** The text, in pieces of whole lines; `done` on the last. */
14
18
  | {
@@ -26,21 +30,68 @@ export type ToWorker =
26
30
  id: number;
27
31
  from: number;
28
32
  until: number;
33
+ /** 1-based inclusive line range whose flat tokens should be returned in `tokens` mode. */
34
+ tokensFrom?: number;
35
+ tokensTo?: number;
36
+ /**
37
+ * Specific 1-based inclusive line ranges whose flat tokens should be
38
+ * returned in `tokens` mode, skipping folded or collapsed hidden lines.
39
+ */
40
+ tokenRanges?: Array<[from: number, to: number]>;
41
+ /** Monotonic request sequence so newer viewport requests preempt older ones. */
42
+ seq?: number;
43
+ }
44
+ /** Cancels any pending highlighting work for this document without closing it. */
45
+ | {
46
+ t: 'cancel';
47
+ id: number;
29
48
  } | {
30
49
  t: 'close';
31
50
  id: number;
51
+ }
52
+ /** Requests an asynchronous text diff inside the worker. */
53
+ | {
54
+ t: 'diff';
55
+ id: number;
56
+ original: string;
57
+ modified: string;
58
+ options?: CodeDiffOptions;
59
+ }
60
+ /** Cancels a queued diff request before it runs. */
61
+ | {
62
+ t: 'cancelDiff';
63
+ id: number;
32
64
  };
33
65
  export type FromWorker = {
34
66
  t: 'states';
35
67
  id: number;
36
68
  version: number;
69
+ seq?: number;
37
70
  points: Array<[line: number, state: unknown]>;
38
71
  }
39
- /** The worker hasn't the language named `missing`, or (without it) can't send its states. */
72
+ /** Flat per-line token arrays starting at 1-based line `from` (inclusive), or disjoint `ranges`. */
73
+ | {
74
+ t: 'tokens';
75
+ id: number;
76
+ version: number;
77
+ seq?: number;
78
+ from: number;
79
+ lines: CodeLineTokens[];
80
+ /** Present when the request asked for multiple disjoint visible line ranges. */
81
+ ranges?: Array<[from: number, lines: CodeLineTokens[]]>;
82
+ frontier: number;
83
+ }
84
+ /** The worker hasn't the language named `missing`, or (without it) can't highlight it. */
40
85
  | {
41
86
  t: 'unsupported';
42
87
  id: number;
43
88
  missing?: string;
89
+ }
90
+ /** Result of an asynchronous `diff` request. */
91
+ | {
92
+ t: 'diffResult';
93
+ id: number;
94
+ hunks: CodeDiffHunk[];
44
95
  };
45
96
  /** A state as plain data, its languages replaced by their names. */
46
97
  export declare function encodeState(value: unknown): unknown;
@@ -1,4 +1,6 @@
1
- import { type CodeLanguage, type CodeTokenType } from '../language/language';
1
+ import { type CodeLanguage, type CodeTokenType, type RemoteCodeLanguageOptions, remoteCodeLanguage } from '../language/language';
2
+ export { remoteCodeLanguage };
3
+ export type { RemoteCodeLanguageOptions };
2
4
  /** The part of a TextMate rule stack the editor uses: Shiki's `StateStack`. */
3
5
  export interface ShikiStateStack {
4
6
  equals(other: ShikiStateStack): boolean;
@@ -17,6 +19,8 @@ export interface ShikiHighlighterLike {
17
19
  stoppedEarly?: boolean;
18
20
  };
19
21
  };
22
+ getLoadedLanguages?: () => string[];
23
+ loadLanguage?: (lang: never) => Promise<void>;
20
24
  }
21
25
  export interface ShikiLanguageOptions {
22
26
  /** The name the editor and code blocks know it by; defaults to the Shiki language's. */
@@ -61,3 +65,34 @@ export declare function tokenTypeOfScopes(scopes: readonly string[]): CodeTokenT
61
65
  * ```
62
66
  */
63
67
  export declare function shikiLanguage(highlighter: ShikiHighlighterLike, language: string, options?: ShikiLanguageOptions): CodeLanguage<ShikiState>;
68
+ export interface ShikiResolverOptions {
69
+ /** Lazily returns (or creates) a Shiki highlighter instance inside the worker. */
70
+ highlighter: () => ShikiHighlighterLike | Promise<ShikiHighlighterLike>;
71
+ /**
72
+ * Loads a language grammar into the highlighter on demand. When omitted, calls
73
+ * `highlighter.loadLanguage(name)` if available and the language is not yet loaded.
74
+ */
75
+ loadLanguage?: (highlighter: ShikiHighlighterLike, name: string) => Promise<void> | void;
76
+ /** Optional `ShikiLanguageOptions` applied to resolved languages. */
77
+ options?: ShikiLanguageOptions | ((name: string) => ShikiLanguageOptions | undefined);
78
+ }
79
+ /**
80
+ * Creates a `resolve` callback for `serveCodeHighlighting` that lazy-loads
81
+ * Shiki grammars inside the worker and wraps them with `shikiLanguage`.
82
+ *
83
+ * ```ts
84
+ * // shiki.worker.ts
85
+ * import { createHighlighter } from 'shiki'
86
+ * import { createShikiLanguageResolver } from '@dou-ui/code/shiki'
87
+ * import { serveCodeHighlighting, typescript } from '@dou-ui/code/worker'
88
+ *
89
+ * let highlighter: ReturnType<typeof createHighlighter> | undefined
90
+ * serveCodeHighlighting({
91
+ * languages: [typescript],
92
+ * resolve: createShikiLanguageResolver(
93
+ * () => (highlighter ??= createHighlighter({ langs: [], themes: [] })),
94
+ * ),
95
+ * })
96
+ * ```
97
+ */
98
+ export declare function createShikiLanguageResolver(highlighterOrOptions: ShikiResolverOptions['highlighter'] | ShikiResolverOptions): (name: string) => Promise<CodeLanguage<ShikiState> | null>;
@@ -7,6 +7,7 @@ import type { CodeSearchQuery } from './core/search';
7
7
  import type { CodeSelection } from './core/selection';
8
8
  import type { CodeMessages } from './locale';
9
9
  import type { CodeLanguage } from './language/language';
10
+ import type { CodeWorkerOption } from './language/worker-client';
10
11
  import type { CodeText } from './core/text';
11
12
  import type { CodeState, CodeTransaction, CodeTransactionMeta, CodeTransactionResult } from './core/transaction';
12
13
  export interface CodeEditorProps {
@@ -57,14 +58,22 @@ export interface CodeEditorProps {
57
58
  /** The language: colors its tokens, and tells how to indent, comment and pair brackets. */
58
59
  language?: CodeLanguage | null;
59
60
  /**
60
- * Reads the code for its colors in a worker, so a long file opened far
61
- * down is colored without the page doing the reading. `true` uses the
62
- * editor's own worker, which knows the built-in languages; a function
63
- * makes your own (`serveCodeHighlighting` from `@dou-ui/code/worker`),
64
- * called in the browser once the editor is mounted. The editor ends the
65
- * worker when it unmounts or no longer uses it.
61
+ * Reads the code for its colors in a worker, so highlighting stays off the
62
+ * main thread. `true` uses the editor's own lazily-spawned worker pool for
63
+ * the built-in languages; a `CodeWorkerPool` (`createCodeWorkerPool`) shares
64
+ * a custom worker pool across instances; a function makes a worker
65
+ * (`serveCodeHighlighting` from `@dou-ui/code/worker`) once the editor is
66
+ * mounted and ends it when unmounted.
66
67
  */
67
- worker?: boolean | (() => Worker);
68
+ worker?: CodeWorkerOption;
69
+ /**
70
+ * Maximum number of unread lines tokenized synchronously on the main thread
71
+ * during rendering. Beyond this threshold, unread lines paint as plain text
72
+ * first and highlight asynchronously in the worker or browser idle slices.
73
+ * Defaults to `2000`. Set to `0` to always paint plain text first and keep
74
+ * tokenization off the render frame (useful in fast-scrolling multi-file lists).
75
+ */
76
+ syncHighlightLines?: number;
68
77
  /** Typing an opening bracket or quote also types its partner. On by default. */
69
78
  closeBrackets?: boolean;
70
79
  /** Outlines the bracket next to the cursor and its partner. On by default. */
@@ -245,6 +254,26 @@ export interface CodeDiffProps {
245
254
  /** The text after, bound with `v-model`; editable beside the original with `editable`. */
246
255
  modelValue?: string;
247
256
  language?: CodeLanguage | null;
257
+ /**
258
+ * Forwards `worker` to the inner `DouCodeEditor` instances and computes
259
+ * large text diffs asynchronously inside the worker. Accepts `true` (built-in
260
+ * lazy worker pool), a `CodeWorkerPool` (`createCodeWorkerPool`), or a worker
261
+ * factory function (`() => Worker`).
262
+ */
263
+ worker?: CodeWorkerOption;
264
+ /**
265
+ * Forwards `syncHighlightLines` to the inner `DouCodeEditor` instances.
266
+ * Defaults to `2000`; set to `0` to paint plain text first and offload
267
+ * syntax highlighting to the worker or idle slices.
268
+ */
269
+ syncHighlightLines?: number;
270
+ /**
271
+ * When `worker` is enabled, runs `diffText` asynchronously in the worker
272
+ * whenever the combined line count of `original` and `modelValue` exceeds
273
+ * this threshold. Defaults to `500`. Set to `0` to always compute diffs in
274
+ * the worker, or `Infinity` to keep diff computation synchronous.
275
+ */
276
+ syncDiffLines?: number;
248
277
  /**
249
278
  * `split` puts the two texts side by side, `inline` puts the changes in
250
279
  * one column. `auto` (the default) is `split` when there is room (560px)
@@ -330,8 +359,14 @@ export interface CodeDiffHoverMarker extends Omit<CodeGutterHoverMarker, 'title'
330
359
  /** A column of `DouCodeDiff`'s gutter, left of the line numbers. */
331
360
  export interface CodeDiffGutter {
332
361
  name: string;
333
- /** In px. Defaults to 16. */
362
+ /** In px. Defaults to 16 (or 18 when rendered as an overlay). */
334
363
  width?: number;
364
+ /**
365
+ * Floats markers over the gutter's right edge without reserving a dedicated
366
+ * column width: `true` always overlays, `'compact'` overlays only in narrow
367
+ * containers (`< 480px`). Defaults to `false`.
368
+ */
369
+ overlay?: boolean | 'compact';
335
370
  markers?: CodeDiffGutterMarker[];
336
371
  /**
337
372
  * A marker on every other line, shown on hover. With `side`, the other
@@ -7,9 +7,15 @@ export declare class Measure {
7
7
  padY: number;
8
8
  /** Space before and after each line (`--dou-code-editor-padding-x`). */
9
9
  padX: number;
10
+ /** Space left of line numbers in the gutter (`--dou-code-editor-gutter-padding-left`). */
11
+ gutterPadLeft: number;
12
+ /** Space right of line numbers in the gutter (`--dou-code-editor-gutter-padding-right`). */
13
+ gutterPadRight: number;
10
14
  tabSize: number;
11
15
  private widths;
12
16
  constructor(probe: () => HTMLElement | null | undefined);
17
+ /** Reads the CSS padding variables; returns `true` when any changed. */
18
+ refreshPadding(): boolean;
13
19
  /** Reads the cell width and line height again, e.g. after the font changed. */
14
20
  refresh(tabSize: number): void;
15
21
  /** Width of one character as drawn. */
@@ -1,8 +1,10 @@
1
1
  import type { CodeLanguage } from '../language/language';
2
2
  export type { CodeLanguage };
3
- export { defineCodeLanguage, copyPlain, samePlain } from '../language/language';
4
- export type { CodeLanguageSpec, CodeTokenType } from '../language/language';
3
+ export { defineCodeLanguage, remoteCodeLanguage, copyPlain, samePlain } from '../language/language';
4
+ export type { CodeLanguageSpec, CodeLineTokens, CodeTokenType, RemoteCodeLanguageOptions, } from '../language/language';
5
5
  export type { CodeStream } from '../language/stream';
6
+ export { diffText } from '../core/diff';
7
+ export type { CodeDiffHunk, CodeDiffOptions, CodeDiffPart } from '../core/diff';
6
8
  export { createJavaScript, javascript, jsx, tsx, typescript } from '../languages/javascript';
7
9
  export { createCss, css, scss } from '../languages/css';
8
10
  export { json } from '../languages/json';
@@ -12,10 +14,26 @@ export { python } from '../languages/python';
12
14
  export { shell } from '../languages/shell';
13
15
  export { sql } from '../languages/sql';
14
16
  export { yaml } from '../languages/yaml';
17
+ export interface WorkerMessageScope {
18
+ postMessage(message: unknown): void;
19
+ addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
20
+ }
21
+ export interface ServeCodeHighlightingOptions {
22
+ /** Languages registered up front. */
23
+ languages?: readonly CodeLanguage[];
24
+ /**
25
+ * Resolves a language by name on demand (for example lazy-loading a Shiki
26
+ * grammar inside the worker). Concurrent requests for the same name share
27
+ * one resolution; returning `null` or `undefined` marks it unsupported.
28
+ */
29
+ resolve?: (name: string) => CodeLanguage | null | undefined | Promise<CodeLanguage | null | undefined>;
30
+ }
15
31
  /**
16
- * Reads code in a worker for `DouCodeEditor`'s `worker`, so a long file is
17
- * colored without the page doing the reading. Call it in the worker's own
18
- * module with the languages the editors use:
32
+ * Reads code and computes diffs in a worker for `DouCodeEditor` and
33
+ * `DouCodeDiff`'s `worker`, so syntax highlighting and large diffs stay off
34
+ * the main thread. Call it in the worker's own module with the languages the
35
+ * editors use, or with a `resolve` callback to lazy-load grammars (such as
36
+ * Shiki) on demand:
19
37
  *
20
38
  * ```ts
21
39
  * // code-worker.ts
@@ -24,11 +42,8 @@ export { yaml } from '../languages/yaml';
24
42
  * serveCodeHighlighting([typescript, css])
25
43
  * ```
26
44
  *
27
- * One worker serves every editor that is given it. A language works here
28
- * when its states are plain data (the built-in ones are); those read by
29
- * the Shiki adapter stay on the page.
45
+ * Languages with plain-data states send state checkpoints; languages with
46
+ * non-serializable states (such as Shiki's `StateStack`) automatically keep
47
+ * their state in the worker and return flat per-line token arrays.
30
48
  */
31
- export declare function serveCodeHighlighting(languages: readonly CodeLanguage[], scope?: {
32
- postMessage(message: unknown): void;
33
- addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
34
- }): void;
49
+ export declare function serveCodeHighlighting(languagesOrOptions: readonly CodeLanguage[] | ServeCodeHighlightingOptions, scope?: WorkerMessageScope): void;
@@ -20,11 +20,33 @@ var Measure = class {
20
20
  padY = 8;
21
21
  /** Space before and after each line (`--dou-code-editor-padding-x`). */
22
22
  padX = 12;
23
+ /** Space left of line numbers in the gutter (`--dou-code-editor-gutter-padding-left`). */
24
+ gutterPadLeft = 16;
25
+ /** Space right of line numbers in the gutter (`--dou-code-editor-gutter-padding-right`). */
26
+ gutterPadRight = 12;
23
27
  tabSize = 2;
24
28
  widths = /* @__PURE__ */ new Map();
25
29
  constructor(probe) {
26
30
  this.probe = probe;
27
31
  }
32
+ /** Reads the CSS padding variables; returns `true` when any changed. */
33
+ refreshPadding() {
34
+ const el = this.probe();
35
+ if (!el) return false;
36
+ el.style.padding = "var(--dou-code-editor-padding-y, 8px) var(--dou-code-editor-padding-x, 12px) var(--dou-code-editor-gutter-padding-left, 16px) var(--dou-code-editor-gutter-padding-right, 12px)";
37
+ const style = getComputedStyle(el);
38
+ const padY = px(style.paddingTop, 8);
39
+ const padX = px(style.paddingRight, 12);
40
+ const gutterPadLeft = px(style.paddingBottom, 16);
41
+ const gutterPadRight = px(style.paddingLeft, 12);
42
+ el.style.padding = "";
43
+ const changed = padY !== this.padY || padX !== this.padX || gutterPadLeft !== this.gutterPadLeft || gutterPadRight !== this.gutterPadRight;
44
+ this.padY = padY;
45
+ this.padX = padX;
46
+ this.gutterPadLeft = gutterPadLeft;
47
+ this.gutterPadRight = gutterPadRight;
48
+ return changed;
49
+ }
28
50
  /** Reads the cell width and line height again, e.g. after the font changed. */
29
51
  refresh(tabSize) {
30
52
  this.tabSize = tabSize;
@@ -36,11 +58,7 @@ var Measure = class {
36
58
  if (rect.width > 0) this.cell = rect.width / 64;
37
59
  if (rect.height > 0) this.lineHeight = Math.round(rect.height);
38
60
  el.textContent = "";
39
- el.style.padding = "var(--dou-code-editor-padding-y, 8px) var(--dou-code-editor-padding-x, 12px)";
40
- const style = getComputedStyle(el);
41
- this.padY = px(style.paddingTop, 8);
42
- this.padX = px(style.paddingLeft, 12);
43
- el.style.padding = "";
61
+ this.refreshPadding();
44
62
  }
45
63
  /** Width of one character as drawn. */
46
64
  width(cluster) {
@@ -1 +1 @@
1
- {"version":3,"file":"measure.js","names":[],"sources":["../../src/view/measure.ts"],"sourcesContent":["import { clusterStarts, isAscii } from '../core/chars'\n\n/**\n * Text metrics without reading layout per line: every plain ASCII\n * character is one monospace cell, and anything else (CJK, emoji, accents)\n * is measured once in the page's own font and remembered. Tabs reach to\n * the next tab stop.\n */\n/** A length read from computed styles, in px. */\nfunction px(value: string, fallback: number) {\n const n = Number.parseFloat(value)\n return Number.isFinite(n) ? Math.max(0, n) : fallback\n}\n\nexport class Measure {\n /** Width of one monospace cell. */\n cell = 8\n lineHeight = 20\n /** Space above the first line and below the last (`--dou-code-editor-padding-y`). */\n padY = 8\n /** Space before and after each line (`--dou-code-editor-padding-x`). */\n padX = 12\n tabSize = 2\n private widths = new Map<string, number>()\n\n constructor(private readonly probe: () => HTMLElement | null | undefined) {}\n\n /** Reads the cell width and line height again, e.g. after the font changed. */\n refresh(tabSize: number) {\n this.tabSize = tabSize\n this.widths.clear()\n const el = this.probe()\n if (!el) return\n el.textContent = 'x'.repeat(64)\n const rect = el.getBoundingClientRect()\n if (rect.width > 0) this.cell = rect.width / 64\n if (rect.height > 0) this.lineHeight = Math.round(rect.height)\n el.textContent = ''\n // Through a padding, so a calc() in the variable comes out in pixels.\n el.style.padding =\n 'var(--dou-code-editor-padding-y, 8px) var(--dou-code-editor-padding-x, 12px)'\n const style = getComputedStyle(el)\n this.padY = px(style.paddingTop, 8)\n this.padX = px(style.paddingLeft, 12)\n el.style.padding = ''\n }\n\n /** Width of one character as drawn. */\n width(cluster: string): number {\n const code = cluster.charCodeAt(0)\n if (cluster.length === 1 && code >= 0x20 && code < 0x7f) return this.cell\n let width = this.widths.get(cluster)\n if (width !== undefined) return width\n const el = this.probe()\n if (el) {\n el.textContent = cluster\n width = el.getBoundingClientRect().width\n el.textContent = ''\n }\n // No layout (tests, a hidden editor): wide scripts take two cells.\n if (!width)\n width = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]|[\\ud83c-\\ud83e]/.test(cluster)\n ? this.cell * 2\n : this.cell\n // Only keep it once the page has fonts, so a fallback guess isn't kept forever.\n if (el?.isConnected) this.widths.set(cluster, width)\n return width\n }\n\n private tab(x: number) {\n const stop = this.cell * this.tabSize\n return (Math.floor(x / stop + 1e-6) + 1) * stop\n }\n\n /** The x of column `col` in `text`, from the line's start. */\n x(text: string, col: number): number {\n col = Math.min(col, text.length)\n if (isAscii(text)) {\n if (!text.includes('\\t')) return col * this.cell\n let x = 0\n for (let i = 0; i < col; i++) x = text.charCodeAt(i) === 9 ? this.tab(x) : x + this.cell\n return x\n }\n let x = 0\n const starts = clusterStarts(text)\n for (let i = 0; i < starts.length - 1 && starts[i]! < col; i++) {\n const cluster = text.slice(starts[i], starts[i + 1])\n x = cluster === '\\t' ? this.tab(x) : x + this.width(cluster)\n }\n return x\n }\n\n /** The column nearest to `x` in `text`, on a character boundary. */\n col(text: string, x: number): number {\n if (x <= 0) return 0\n if (isAscii(text) && !text.includes('\\t'))\n return Math.min(text.length, Math.round(x / this.cell))\n let left = 0\n const ascii = isAscii(text)\n const starts = ascii ? null : clusterStarts(text)\n const count = ascii ? text.length : starts!.length - 1\n for (let i = 0; i < count; i++) {\n const from = ascii ? i : starts![i]!\n const to = ascii ? i + 1 : starts![i + 1]!\n const cluster = text.slice(from, to)\n const right = cluster === '\\t' ? this.tab(left) : left + this.width(cluster)\n if (x < (left + right) / 2) return from\n if (x < right) return to\n left = right\n }\n return text.length\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,GAAG,OAAe,UAAkB;CAC3C,MAAM,IAAI,OAAO,WAAW,KAAK;CACjC,OAAO,OAAO,SAAS,CAAC,IAAI,KAAK,IAAI,GAAG,CAAC,IAAI;AAC/C;AAEA,IAAa,UAAb,MAAqB;CAWU;;CAT7B,OAAO;CACP,aAAa;;CAEb,OAAO;;CAEP,OAAO;CACP,UAAU;CACV,yBAAiB,IAAI,IAAoB;CAEzC,YAAY,OAA8D;EAA7C,KAAA,QAAA;CAA8C;;CAG3E,QAAQ,SAAiB;EACvB,KAAK,UAAU;EACf,KAAK,OAAO,MAAM;EAClB,MAAM,KAAK,KAAK,MAAM;EACtB,IAAI,CAAC,IAAI;EACT,GAAG,cAAc,IAAI,OAAO,EAAE;EAC9B,MAAM,OAAO,GAAG,sBAAsB;EACtC,IAAI,KAAK,QAAQ,GAAG,KAAK,OAAO,KAAK,QAAQ;EAC7C,IAAI,KAAK,SAAS,GAAG,KAAK,aAAa,KAAK,MAAM,KAAK,MAAM;EAC7D,GAAG,cAAc;EAEjB,GAAG,MAAM,UACP;EACF,MAAM,QAAQ,iBAAiB,EAAE;EACjC,KAAK,OAAO,GAAG,MAAM,YAAY,CAAC;EAClC,KAAK,OAAO,GAAG,MAAM,aAAa,EAAE;EACpC,GAAG,MAAM,UAAU;CACrB;;CAGA,MAAM,SAAyB;EAC7B,MAAM,OAAO,QAAQ,WAAW,CAAC;EACjC,IAAI,QAAQ,WAAW,KAAK,QAAQ,MAAQ,OAAO,KA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,QAAQ,KAAK,MAAM,IAAI,KAAK,IAAI,CAAC;EACxD,IAAI,OAAO;EACX,MAAM,QAAQ,QAAQ,IAAI;EAC1B,MAAM,SAAS,QAAQ,OAAO,cAAc,IAAI;EAChD,MAAM,QAAQ,QAAQ,KAAK,SAAS,OAAQ,SAAS;EACrD,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,KAAK;GAC9B,MAAM,OAAO,QAAQ,IAAI,OAAQ;GACjC,MAAM,KAAK,QAAQ,IAAI,IAAI,OAAQ,IAAI;GACvC,MAAM,UAAU,KAAK,MAAM,MAAM,EAAE;GACnC,MAAM,QAAQ,YAAY,MAAO,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,MAAM,OAAO;GAC3E,IAAI,KAAK,OAAO,SAAS,GAAG,OAAO;GACnC,IAAI,IAAI,OAAO,OAAO;GACtB,OAAO;EACT;EACA,OAAO,KAAK;CACd;AACF"}
1
+ {"version":3,"file":"measure.js","names":[],"sources":["../../src/view/measure.ts"],"sourcesContent":["import { clusterStarts, isAscii } from '../core/chars'\n\n/**\n * Text metrics without reading layout per line: every plain ASCII\n * character is one monospace cell, and anything else (CJK, emoji, accents)\n * is measured once in the page's own font and remembered. Tabs reach to\n * the next tab stop.\n */\n/** A length read from computed styles, in px. */\nfunction px(value: string, fallback: number) {\n const n = Number.parseFloat(value)\n return Number.isFinite(n) ? Math.max(0, n) : fallback\n}\n\nexport class Measure {\n /** Width of one monospace cell. */\n cell = 8\n lineHeight = 20\n /** Space above the first line and below the last (`--dou-code-editor-padding-y`). */\n padY = 8\n /** Space before and after each line (`--dou-code-editor-padding-x`). */\n padX = 12\n /** Space left of line numbers in the gutter (`--dou-code-editor-gutter-padding-left`). */\n gutterPadLeft = 16\n /** Space right of line numbers in the gutter (`--dou-code-editor-gutter-padding-right`). */\n gutterPadRight = 12\n tabSize = 2\n private widths = new Map<string, number>()\n\n constructor(private readonly probe: () => HTMLElement | null | undefined) {}\n\n /** Reads the CSS padding variables; returns `true` when any changed. */\n refreshPadding(): boolean {\n const el = this.probe()\n if (!el) return false\n // Through a padding, so a calc() in the variable comes out in pixels.\n el.style.padding =\n 'var(--dou-code-editor-padding-y, 8px) var(--dou-code-editor-padding-x, 12px) var(--dou-code-editor-gutter-padding-left, 16px) var(--dou-code-editor-gutter-padding-right, 12px)'\n const style = getComputedStyle(el)\n const padY = px(style.paddingTop, 8)\n const padX = px(style.paddingRight, 12)\n const gutterPadLeft = px(style.paddingBottom, 16)\n const gutterPadRight = px(style.paddingLeft, 12)\n el.style.padding = ''\n const changed =\n padY !== this.padY ||\n padX !== this.padX ||\n gutterPadLeft !== this.gutterPadLeft ||\n gutterPadRight !== this.gutterPadRight\n this.padY = padY\n this.padX = padX\n this.gutterPadLeft = gutterPadLeft\n this.gutterPadRight = gutterPadRight\n return changed\n }\n\n /** Reads the cell width and line height again, e.g. after the font changed. */\n refresh(tabSize: number) {\n this.tabSize = tabSize\n this.widths.clear()\n const el = this.probe()\n if (!el) return\n el.textContent = 'x'.repeat(64)\n const rect = el.getBoundingClientRect()\n if (rect.width > 0) this.cell = rect.width / 64\n if (rect.height > 0) this.lineHeight = Math.round(rect.height)\n el.textContent = ''\n this.refreshPadding()\n }\n\n /** Width of one character as drawn. */\n width(cluster: string): number {\n const code = cluster.charCodeAt(0)\n if (cluster.length === 1 && code >= 0x20 && code < 0x7f) return this.cell\n let width = this.widths.get(cluster)\n if (width !== undefined) return width\n const el = this.probe()\n if (el) {\n el.textContent = cluster\n width = el.getBoundingClientRect().width\n el.textContent = ''\n }\n // No layout (tests, a hidden editor): wide scripts take two cells.\n if (!width)\n width = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]|[\\ud83c-\\ud83e]/.test(cluster)\n ? this.cell * 2\n : this.cell\n // Only keep it once the page has fonts, so a fallback guess isn't kept forever.\n if (el?.isConnected) this.widths.set(cluster, width)\n return width\n }\n\n private tab(x: number) {\n const stop = this.cell * this.tabSize\n return (Math.floor(x / stop + 1e-6) + 1) * stop\n }\n\n /** The x of column `col` in `text`, from the line's start. */\n x(text: string, col: number): number {\n col = Math.min(col, text.length)\n if (isAscii(text)) {\n if (!text.includes('\\t')) return col * this.cell\n let x = 0\n for (let i = 0; i < col; i++) x = text.charCodeAt(i) === 9 ? this.tab(x) : x + this.cell\n return x\n }\n let x = 0\n const starts = clusterStarts(text)\n for (let i = 0; i < starts.length - 1 && starts[i]! < col; i++) {\n const cluster = text.slice(starts[i], starts[i + 1])\n x = cluster === '\\t' ? this.tab(x) : x + this.width(cluster)\n }\n return x\n }\n\n /** The column nearest to `x` in `text`, on a character boundary. */\n col(text: string, x: number): number {\n if (x <= 0) return 0\n if (isAscii(text) && !text.includes('\\t'))\n return Math.min(text.length, Math.round(x / this.cell))\n let left = 0\n const ascii = isAscii(text)\n const starts = ascii ? null : clusterStarts(text)\n const count = ascii ? text.length : starts!.length - 1\n for (let i = 0; i < count; i++) {\n const from = ascii ? i : starts![i]!\n const to = ascii ? i + 1 : starts![i + 1]!\n const cluster = text.slice(from, to)\n const right = cluster === '\\t' ? this.tab(left) : left + this.width(cluster)\n if (x < (left + right) / 2) return from\n if (x < right) return to\n left = right\n }\n return text.length\n }\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,GAAG,OAAe,UAAkB;CAC3C,MAAM,IAAI,OAAO,WAAW,KAAK;CACjC,OAAO,OAAO,SAAS,CAAC,IAAI,KAAK,IAAI,GAAG,CAAC,IAAI;AAC/C;AAEA,IAAa,UAAb,MAAqB;CAeU;;CAb7B,OAAO;CACP,aAAa;;CAEb,OAAO;;CAEP,OAAO;;CAEP,gBAAgB;;CAEhB,iBAAiB;CACjB,UAAU;CACV,yBAAiB,IAAI,IAAoB;CAEzC,YAAY,OAA8D;EAA7C,KAAA,QAAA;CAA8C;;CAG3E,iBAA0B;EACxB,MAAM,KAAK,KAAK,MAAM;EACtB,IAAI,CAAC,IAAI,OAAO;EAEhB,GAAG,MAAM,UACP;EACF,MAAM,QAAQ,iBAA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