@astl/editor 0.0.0 → 0.1.1

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 (161) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/LICENSE +202 -0
  3. package/README.md +43 -0
  4. package/dist/authoring.d.ts +284 -0
  5. package/dist/authoring.d.ts.map +1 -0
  6. package/dist/authoring.js +566 -0
  7. package/dist/authoring.js.map +1 -0
  8. package/dist/define.d.ts +8 -0
  9. package/dist/define.d.ts.map +1 -0
  10. package/dist/define.js +35 -0
  11. package/dist/define.js.map +1 -0
  12. package/dist/edit.d.ts +45 -0
  13. package/dist/edit.d.ts.map +1 -0
  14. package/dist/edit.js +150 -0
  15. package/dist/edit.js.map +1 -0
  16. package/dist/elements/base.d.ts +31 -0
  17. package/dist/elements/base.d.ts.map +1 -0
  18. package/dist/elements/base.js +75 -0
  19. package/dist/elements/base.js.map +1 -0
  20. package/dist/elements/color-control.d.ts +25 -0
  21. package/dist/elements/color-control.d.ts.map +1 -0
  22. package/dist/elements/color-control.js +139 -0
  23. package/dist/elements/color-control.js.map +1 -0
  24. package/dist/elements/help-form.d.ts +31 -0
  25. package/dist/elements/help-form.d.ts.map +1 -0
  26. package/dist/elements/help-form.js +371 -0
  27. package/dist/elements/help-form.js.map +1 -0
  28. package/dist/elements/insert-menu.d.ts +79 -0
  29. package/dist/elements/insert-menu.d.ts.map +1 -0
  30. package/dist/elements/insert-menu.js +362 -0
  31. package/dist/elements/insert-menu.js.map +1 -0
  32. package/dist/elements/inspector.d.ts +24 -0
  33. package/dist/elements/inspector.d.ts.map +1 -0
  34. package/dist/elements/inspector.js +846 -0
  35. package/dist/elements/inspector.js.map +1 -0
  36. package/dist/elements/issue-list.d.ts +18 -0
  37. package/dist/elements/issue-list.d.ts.map +1 -0
  38. package/dist/elements/issue-list.js +85 -0
  39. package/dist/elements/issue-list.js.map +1 -0
  40. package/dist/elements/issues.d.ts +24 -0
  41. package/dist/elements/issues.d.ts.map +1 -0
  42. package/dist/elements/issues.js +81 -0
  43. package/dist/elements/issues.js.map +1 -0
  44. package/dist/elements/picture-dialog.d.ts +40 -0
  45. package/dist/elements/picture-dialog.d.ts.map +1 -0
  46. package/dist/elements/picture-dialog.js +433 -0
  47. package/dist/elements/picture-dialog.js.map +1 -0
  48. package/dist/elements/picture-field.d.ts +33 -0
  49. package/dist/elements/picture-field.d.ts.map +1 -0
  50. package/dist/elements/picture-field.js +692 -0
  51. package/dist/elements/picture-field.js.map +1 -0
  52. package/dist/elements/preview.d.ts +34 -0
  53. package/dist/elements/preview.d.ts.map +1 -0
  54. package/dist/elements/preview.js +165 -0
  55. package/dist/elements/preview.js.map +1 -0
  56. package/dist/elements/style-form.d.ts +30 -0
  57. package/dist/elements/style-form.d.ts.map +1 -0
  58. package/dist/elements/style-form.js +640 -0
  59. package/dist/elements/style-form.js.map +1 -0
  60. package/dist/elements/style-load.d.ts +26 -0
  61. package/dist/elements/style-load.d.ts.map +1 -0
  62. package/dist/elements/style-load.js +50 -0
  63. package/dist/elements/style-load.js.map +1 -0
  64. package/dist/elements/style-popups.d.ts +39 -0
  65. package/dist/elements/style-popups.d.ts.map +1 -0
  66. package/dist/elements/style-popups.js +173 -0
  67. package/dist/elements/style-popups.js.map +1 -0
  68. package/dist/elements/style-rules.d.ts +21 -0
  69. package/dist/elements/style-rules.d.ts.map +1 -0
  70. package/dist/elements/style-rules.js +274 -0
  71. package/dist/elements/style-rules.js.map +1 -0
  72. package/dist/elements/styles.d.ts +9 -0
  73. package/dist/elements/styles.d.ts.map +1 -0
  74. package/dist/elements/styles.js +161 -0
  75. package/dist/elements/styles.js.map +1 -0
  76. package/dist/elements/toolbar.d.ts +65 -0
  77. package/dist/elements/toolbar.d.ts.map +1 -0
  78. package/dist/elements/toolbar.js +1270 -0
  79. package/dist/elements/toolbar.js.map +1 -0
  80. package/dist/help.d.ts +33 -0
  81. package/dist/help.d.ts.map +1 -0
  82. package/dist/help.js +111 -0
  83. package/dist/help.js.map +1 -0
  84. package/dist/index.d.ts +32 -0
  85. package/dist/index.d.ts.map +1 -0
  86. package/dist/index.js +17 -0
  87. package/dist/index.js.map +1 -0
  88. package/dist/inspect.d.ts +251 -0
  89. package/dist/inspect.d.ts.map +1 -0
  90. package/dist/inspect.js +428 -0
  91. package/dist/inspect.js.map +1 -0
  92. package/dist/messages/en.json +252 -0
  93. package/dist/messages/help/en.json +18 -0
  94. package/dist/messages/help/pl.json +18 -0
  95. package/dist/messages/pl.json +252 -0
  96. package/dist/messages/style/en.json +67 -0
  97. package/dist/messages/style/pl.json +67 -0
  98. package/dist/messages.d.ts +5 -0
  99. package/dist/messages.d.ts.map +1 -0
  100. package/dist/messages.js +9 -0
  101. package/dist/messages.js.map +1 -0
  102. package/dist/pages.d.ts +28 -0
  103. package/dist/pages.d.ts.map +1 -0
  104. package/dist/pages.js +147 -0
  105. package/dist/pages.js.map +1 -0
  106. package/dist/scan.d.ts +82 -0
  107. package/dist/scan.d.ts.map +1 -0
  108. package/dist/scan.js +329 -0
  109. package/dist/scan.js.map +1 -0
  110. package/dist/style-messages.d.ts +7 -0
  111. package/dist/style-messages.d.ts.map +1 -0
  112. package/dist/style-messages.js +12 -0
  113. package/dist/style-messages.js.map +1 -0
  114. package/dist/style-model.d.ts +50 -0
  115. package/dist/style-model.d.ts.map +1 -0
  116. package/dist/style-model.js +76 -0
  117. package/dist/style-model.js.map +1 -0
  118. package/dist/style-placing.d.ts +38 -0
  119. package/dist/style-placing.d.ts.map +1 -0
  120. package/dist/style-placing.js +98 -0
  121. package/dist/style-placing.js.map +1 -0
  122. package/dist/textarea.d.ts +17 -0
  123. package/dist/textarea.d.ts.map +1 -0
  124. package/dist/textarea.js +175 -0
  125. package/dist/textarea.js.map +1 -0
  126. package/package.json +54 -4
  127. package/src/authoring.ts +896 -0
  128. package/src/define.ts +34 -0
  129. package/src/edit.ts +195 -0
  130. package/src/elements/base.ts +93 -0
  131. package/src/elements/color-control.ts +159 -0
  132. package/src/elements/help-form.ts +404 -0
  133. package/src/elements/insert-menu.ts +481 -0
  134. package/src/elements/inspector.ts +941 -0
  135. package/src/elements/issue-list.ts +103 -0
  136. package/src/elements/issues.ts +89 -0
  137. package/src/elements/picture-dialog.ts +461 -0
  138. package/src/elements/picture-field.ts +770 -0
  139. package/src/elements/preview.ts +186 -0
  140. package/src/elements/style-form.ts +751 -0
  141. package/src/elements/style-load.ts +64 -0
  142. package/src/elements/style-popups.ts +257 -0
  143. package/src/elements/style-rules.ts +294 -0
  144. package/src/elements/styles.ts +162 -0
  145. package/src/elements/toolbar.ts +1386 -0
  146. package/src/help.ts +156 -0
  147. package/src/index.ts +81 -0
  148. package/src/inspect.ts +774 -0
  149. package/src/messages/en.json +252 -0
  150. package/src/messages/help/en.json +18 -0
  151. package/src/messages/help/pl.json +18 -0
  152. package/src/messages/pl.json +252 -0
  153. package/src/messages/style/en.json +67 -0
  154. package/src/messages/style/pl.json +67 -0
  155. package/src/messages.ts +11 -0
  156. package/src/pages.ts +158 -0
  157. package/src/scan.ts +382 -0
  158. package/src/style-messages.ts +13 -0
  159. package/src/style-model.ts +125 -0
  160. package/src/style-placing.ts +117 -0
  161. package/src/textarea.ts +182 -0
@@ -0,0 +1,125 @@
1
+ /**
2
+ * What the first load of the kit reads: the declarations of a style as a map, the host's fonts, the ready styles and
3
+ * the layouts. A layout's source goes through the format's rules like any other.
4
+ */
5
+ import type { EditorLayoutShape } from '@astl/core';
6
+
7
+ /** The declarations of a `style` value as a map, read as they are written (they come from the allow-list). */
8
+ export const styleMapOf = (style: string): ReadonlyMap<string, string> =>
9
+ new Map(
10
+ style.split(';').flatMap((part): [string, string][] => {
11
+ const at = part.indexOf(':');
12
+ return at < 0
13
+ ? []
14
+ : [
15
+ [
16
+ part.slice(0, at).trim().toLowerCase(),
17
+ part
18
+ .slice(at + 1)
19
+ .trim()
20
+ .toLowerCase(),
21
+ ],
22
+ ];
23
+ }),
24
+ );
25
+
26
+ /** A font a host offers (`defineEditor({ fonts })`): its name in the menus, and its CSS stack. */
27
+ export interface EditorFont {
28
+ readonly name: string;
29
+ readonly stack: string;
30
+ }
31
+
32
+ /** The default list: stacks every system has, nothing to download or license. */
33
+ export const DEFAULT_FONTS: readonly EditorFont[] = [
34
+ { name: 'Arial', stack: 'Arial, Helvetica, sans-serif' },
35
+ { name: 'Verdana', stack: 'Verdana, Geneva, sans-serif' },
36
+ { name: 'Georgia', stack: 'Georgia, serif' },
37
+ { name: 'Times New Roman', stack: '"Times New Roman", Times, serif' },
38
+ { name: 'Courier New', stack: '"Courier New", Courier, monospace' },
39
+ ];
40
+
41
+ /**
42
+ * A ready style a host offers (`defineEditor({ styles })`), as a word processor has its built-in ones. Picked, it is
43
+ * written into the document as a named style (`<astl-style>`), which the exercise then owns like any other.
44
+ */
45
+ export interface EditorStylePreset {
46
+ /** The name it is applied by (`class`): what `isStyleName` takes. */
47
+ readonly name: string;
48
+ /** Its declarations, every one of which the style allow-list must keep. */
49
+ readonly style: string;
50
+ /** Its name in the menus and in the rule. Default: the kit's message `style.preset.<name>`, else the name. */
51
+ readonly label?: string;
52
+ /**
53
+ * A style of words: it goes on the selected text, and with only a cursor on what the cursor is in. Without it, a
54
+ * style of boxes: on what the cursor is in (a block, a component), words selected or not.
55
+ */
56
+ readonly text?: true;
57
+ }
58
+
59
+ /**
60
+ * The default ready styles: boxes for a note, a tip, a warning, a definition, an example and a quote, then two for
61
+ * words. Their text reads at 4.5:1 on what is behind it, in the light theme and as the player paints them in the dark
62
+ * one (`styled.browser.test.ts`). A style of words holds no padding and no margin: on a phone the player gives
63
+ * whatever has a padding its own (`styled.ts`), which would pad a word inside its sentence.
64
+ */
65
+ export const DEFAULT_STYLES: readonly EditorStylePreset[] = [
66
+ {
67
+ name: 'note',
68
+ style:
69
+ 'background-color: #fff4d6; border-inline-start: 4px solid #b7791f; padding: 12px 16px; border-radius: 6px',
70
+ },
71
+ {
72
+ name: 'tip',
73
+ style:
74
+ 'background-color: #e7f6ec; border-inline-start: 4px solid #2f855a; padding: 12px 16px; border-radius: 6px',
75
+ },
76
+ {
77
+ name: 'important',
78
+ style:
79
+ 'background-color: #fdecec; border-inline-start: 4px solid #c53030; padding: 12px 16px; border-radius: 6px',
80
+ },
81
+ {
82
+ name: 'definition',
83
+ style: 'background-color: #eef1fe; border: 1px solid #5a67d8; padding: 12px 16px; border-radius: 6px',
84
+ },
85
+ { name: 'example', style: 'border: 2px dashed #718096; padding: 12px 16px; border-radius: 6px' },
86
+ {
87
+ name: 'quote',
88
+ style:
89
+ 'border-inline-start: 3px solid #a0aec0; padding-inline-start: 16px; font-style: italic; color: #4a5568',
90
+ },
91
+ { name: 'highlight', style: 'background-color: #fff3a3', text: true },
92
+ { name: 'small-print', style: 'font-size: 14px; color: #4a5568', text: true },
93
+ ];
94
+
95
+ /** The theme's colours an author can pick, by number: `var(--astl-palette-<n>)`. */
96
+ export const PALETTE_SIZE = 8;
97
+
98
+ /** The layouts of the insert menu's "Layout" group. */
99
+ export type LayoutName = EditorLayoutShape | 'picture-text';
100
+
101
+ export const LAYOUTS: readonly LayoutName[] = ['two', 'three', 'wide-narrow', 'narrow-wide', 'picture-text'];
102
+
103
+ /** The shapes a layout can be changed to (`EditorStyles.editLayout`), in the menu's order. */
104
+ export const LAYOUT_SHAPES: readonly EditorLayoutShape[] = ['two', 'three', 'wide-narrow', 'narrow-wide'];
105
+
106
+ /** Each shape's columns by their `flex-grow`: null for an equal share. */
107
+ export const LAYOUT_COLUMNS: Readonly<Record<EditorLayoutShape, readonly (number | null)[]>> = {
108
+ two: [null, null],
109
+ three: [null, null, null],
110
+ 'wide-narrow': [2, null],
111
+ 'narrow-wide': [null, 2],
112
+ };
113
+
114
+ const column = (content = '<p></p>', grow: number | null = null) =>
115
+ `<astl-column${grow === null ? '' : ` style="flex-grow: ${grow}"`}>${content}</astl-column>`;
116
+
117
+ /** The source of a layout; `picture-text` takes the source of its picture. */
118
+ export function layoutHtml(name: LayoutName, picture = ''): string {
119
+ const columns =
120
+ name === 'picture-text'
121
+ ? column(picture.startsWith('<figure') ? picture : `<p>${picture}</p>`) + column()
122
+ : LAYOUT_COLUMNS[name].map((grow) => column('<p></p>', grow)).join('');
123
+ const shape = name === 'picture-text' ? ' style="align-items: start"' : '';
124
+ return `<astl-columns${shape}>${columns}</astl-columns>`;
125
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * How a placement of a picture, a figure or a component is written, and a new style's name: what the style form and a surface read, outside the
3
+ * kit's first load. Everything a position writes has its logical form in the allow-list, so a page in any direction
4
+ * reads the same; the player's narrow rule keeps `auto` margins and lets the others go.
5
+ */
6
+ import type { EditorStyleChanges } from '@astl/core';
7
+ import { isStyleName } from '@astl/core/declarations';
8
+ import { styleMapOf } from './style-model.js';
9
+
10
+ /**
11
+ * Where a picture, a figure or a component sits: in the line, floating at either side with text beside it, centred,
12
+ * or filling.
13
+ */
14
+ export type Placement = 'inline' | 'start' | 'end' | 'center' | 'full';
15
+
16
+ export const PLACEMENTS: readonly Placement[] = ['inline', 'start', 'end', 'center', 'full'];
17
+
18
+ /** @deprecated Use `Placement`: components are placed the same way. */
19
+ export type PicturePosition = Placement;
20
+
21
+ /** @deprecated Use `PLACEMENTS`. */
22
+ export const PICTURE_POSITIONS: readonly Placement[] = PLACEMENTS;
23
+
24
+ /** What a position may have written, also by hand: all of it goes before a new position is written. */
25
+ const POSITION_PROPERTIES = [
26
+ 'float',
27
+ 'display',
28
+ 'margin',
29
+ ...['left', 'right', 'bottom'].map((side) => `margin-${side}`),
30
+ 'margin-inline',
31
+ 'margin-inline-start',
32
+ 'margin-inline-end',
33
+ 'margin-block-end',
34
+ ];
35
+
36
+ /** The declarations of each position. */
37
+ const POSITION_STYLES: Readonly<Record<Placement, Readonly<Record<string, string>>>> = {
38
+ inline: {},
39
+ start: { float: 'inline-start', 'margin-inline-end': '16px', 'margin-block-end': '8px' },
40
+ end: { float: 'inline-end', 'margin-inline-start': '16px', 'margin-block-end': '8px' },
41
+ center: { display: 'block', 'margin-inline': 'auto' },
42
+ full: { display: 'block', width: '100%' },
43
+ };
44
+
45
+ /** The position a `style` value says, also written by hand, with physical sides or `margin: 0 auto`. */
46
+ export function positionOf(style: string): Placement {
47
+ const map = styleMapOf(style);
48
+ const float = map.get('float');
49
+ if (float === 'inline-start' || float === 'left') return 'start';
50
+ if (float === 'inline-end' || float === 'right') return 'end';
51
+ if (map.get('width') === '100%' && (map.get('display') === 'block' || !map.has('display'))) return 'full';
52
+ const margin = map.get('margin')?.split(/\s+/);
53
+ const centred =
54
+ map.get('margin-inline') === 'auto' ||
55
+ ['left', 'right'].every((side) => map.get(`margin-${side}`) === 'auto') ||
56
+ (margin !== undefined && margin.length === 2 && margin[1] === 'auto');
57
+ return centred ? 'center' : 'inline';
58
+ }
59
+
60
+ /**
61
+ * The changes that put an element whose style is `style` at `position`; leaving "full width" lets go of its width. A
62
+ * figure fills the line unless it has a width, so "centred" would not show on one without it (`figure`).
63
+ */
64
+ export function positionChanges(position: Placement, style: string, figure = false): EditorStyleChanges {
65
+ const changes: Record<string, string | null> = {};
66
+ for (const name of POSITION_PROPERTIES) changes[name] = null;
67
+ if (positionOf(style) === 'full') changes.width = null;
68
+ if (figure && position === 'center' && (positionOf(style) === 'full' || !styleMapOf(style).has('width')))
69
+ changes.width = '50%';
70
+ return { ...changes, ...POSITION_STYLES[position] };
71
+ }
72
+
73
+ /** The changes that make an element whose style is `style` this wide: a handle and a field write the same. */
74
+ export function widthChanges(style: string, percent: number): EditorStyleChanges {
75
+ return {
76
+ width: `${percent}%`,
77
+ // Narrower than the line, it is no longer "full width": what said so goes with it.
78
+ ...(positionOf(style) === 'full' && percent < 100 ? { display: null } : {}),
79
+ };
80
+ }
81
+
82
+ const PLACING: ReadonlySet<string> = new Set([...POSITION_PROPERTIES, 'width']);
83
+
84
+ /**
85
+ * A `style` value in two: what places the element (its position and width) and the rest. A surface that frames an
86
+ * element draws the first on the frame and the rest inside it.
87
+ */
88
+ export function splitPlacement(style: string): { readonly placed: string; readonly rest: string } {
89
+ const placed: string[] = [];
90
+ const rest: string[] = [];
91
+ for (const [name, value] of styleMapOf(style))
92
+ (PLACING.has(name) ? placed : rest).push(`${name}: ${value}`);
93
+ return { placed: placed.join('; '), rest: rest.join('; ') };
94
+ }
95
+
96
+ /** The width a `style` value gives in percent, or null: none, or another unit. */
97
+ export function widthPercent(style: string): number | null {
98
+ const match = /^(\d+(?:\.\d+)?)%$/.exec(styleMapOf(style).get('width') ?? '');
99
+ return match === null ? null : Number(match[1]);
100
+ }
101
+
102
+ /** A name for a new style from its label: lowercase letters, digits and dashes, the format's grammar, not taken. */
103
+ export function styleNameFrom(label: string, taken: ReadonlySet<string>): string {
104
+ const plain = label
105
+ .normalize('NFD')
106
+ .replace(/\p{M}/gu, '')
107
+ .replace(/[łŁ]/g, 'l')
108
+ .toLowerCase()
109
+ .replace(/[^a-z0-9]+/g, '-')
110
+ .replace(/^[^a-z]+|-+$/g, '')
111
+ .slice(0, 56);
112
+ const base = isStyleName(plain) ? plain : 'style';
113
+ if (base !== 'style' && !taken.has(base)) return base;
114
+ let n = 1;
115
+ while (taken.has(`${base}-${n}`)) n++;
116
+ return `${base}-${n}`;
117
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * The reference EditorAdapter: the source edited as text in a `<textarea>`. Elements are found with `scanElements`,
3
+ * edits are string splices, so the author's formatting outside the edited element is never touched.
4
+ */
5
+ import { DOC_TAG, type EditorAdapter, type EditorSelection, PAGE_TAG } from '@astl/core';
6
+ import { addPageSource, mergePageSource, type PageEdit, splitPageSource } from './pages.js';
7
+ import { type ScannedElement, scanElements, tokenize } from './scan.js';
8
+
9
+ export interface TextareaAdapter extends EditorAdapter {
10
+ /** A page break at the caret, in the source text (`EditorAdapter.splitPage`). */
11
+ splitPage(): string | null;
12
+ /** An empty page after the page `after`, in the source text (`EditorAdapter.addPage`). */
13
+ addPage(after?: string): string;
14
+ /** The page `id` joined to the page before it, in the source text (`EditorAdapter.mergePage`). */
15
+ mergePage(id: string): boolean;
16
+ /** Removes the textarea listeners and every subscription. */
17
+ destroy(): void;
18
+ }
19
+
20
+ const SELECTION_EVENTS = ['select', 'keyup', 'click', 'focus'] as const;
21
+
22
+ function same(a: EditorSelection | null, b: EditorSelection | null): boolean {
23
+ return a?.id === b?.id && a?.tag === b?.tag;
24
+ }
25
+
26
+ const isComponent = (el: ScannedElement) => el.tag !== PAGE_TAG;
27
+
28
+ /**
29
+ * Where an insertion may go without breaking the source: never inside a tag or comment, never inside a component
30
+ * (it goes after it: components do not nest), never outside `<astl-doc>` (it goes to the end of the last page).
31
+ */
32
+ function insertionRange(source: string, start: number, end: number): [number, number] {
33
+ const elements = scanElements(source);
34
+ // A caret right before an element is not in it; a selection that touches an element is.
35
+ const hit = elements.filter(
36
+ (el) => isComponent(el) && (start === end ? el.start < start : el.start < end) && start < el.end,
37
+ );
38
+ const last = hit[hit.length - 1];
39
+ if (last !== undefined) return [last.end, last.end];
40
+ const tags = tokenize(source);
41
+ const inside = (offset: number) => tags.find((tag) => tag.start < offset && offset < tag.end);
42
+ const cut = inside(start);
43
+ if (cut !== undefined) return [cut.end, cut.end];
44
+ if (inside(end) !== undefined) return [start, start];
45
+ const open = tags.find((tag) => tag.type === 'start' && tag.name === DOC_TAG);
46
+ const close = tags.findLast((tag) => tag.type === 'end' && tag.name === DOC_TAG);
47
+ if (open === undefined) return [start, end];
48
+ if (start >= open.end && (close === undefined || end <= close.start)) return [start, end];
49
+ const pages = elements.filter((el) => el.tag === PAGE_TAG);
50
+ const page = pages[pages.length - 1];
51
+ const pageClose =
52
+ page && tags.find((tag) => tag.type === 'end' && tag.name === PAGE_TAG && tag.end === page.end);
53
+ const at = pageClose?.start ?? close?.start ?? source.length;
54
+ return [at, at];
55
+ }
56
+
57
+ /** Puts the caret of a textarea at `offset` and scrolls the line into view (the caret line, approximately). */
58
+ function reveal(textarea: HTMLTextAreaElement, offset: number): void {
59
+ const line = textarea.value.slice(0, offset).split('\n').length - 1;
60
+ const height = Number.parseFloat(getComputedStyle(textarea).lineHeight) || 20;
61
+ textarea.scrollTop = Math.max(0, line * height - textarea.clientHeight / 3);
62
+ textarea.setSelectionRange(offset, offset);
63
+ }
64
+
65
+ export function createTextareaAdapter(textarea: HTMLTextAreaElement): TextareaAdapter {
66
+ const changes = new Set<() => void>();
67
+ const selections = new Set<(selection: EditorSelection | null) => void>();
68
+ let cache: { readonly value: string; readonly elements: ScannedElement[] } | null = null;
69
+ const elements = (): ScannedElement[] => {
70
+ const value = textarea.value;
71
+ if (cache?.value !== value) cache = { value, elements: scanElements(value) };
72
+ return cache.elements;
73
+ };
74
+ const component = (id: string) => elements().find((el) => isComponent(el) && el.id === id) ?? null;
75
+
76
+ const current = (): EditorSelection | null => {
77
+ const caret = textarea.selectionStart;
78
+ const el = elements().find((e) => isComponent(e) && e.start <= caret && caret < e.end);
79
+ return el?.id ? { id: el.id, tag: el.tag } : null;
80
+ };
81
+ let last = current();
82
+ const emitSelection = () => {
83
+ const now = current();
84
+ if (same(now, last)) return;
85
+ last = now;
86
+ for (const listener of [...selections]) listener(now);
87
+ };
88
+ const emitChange = () => {
89
+ for (const listener of [...changes]) listener();
90
+ emitSelection();
91
+ };
92
+
93
+ textarea.addEventListener('input', emitChange);
94
+ for (const type of SELECTION_EVENTS) textarea.addEventListener(type, emitSelection);
95
+
96
+ const setSource = (source: string) => {
97
+ // Only the span that differs is replaced, so a change at one place (the document's start tag, from the
98
+ // inspector) leaves the caret where it was in the text around it.
99
+ const old = textarea.value;
100
+ const shorter = Math.min(old.length, source.length);
101
+ let start = 0;
102
+ while (start < shorter && old[start] === source[start]) start++;
103
+ let end = 0;
104
+ while (end < shorter - start && old[old.length - 1 - end] === source[source.length - 1 - end]) end++;
105
+ textarea.setRangeText(source.slice(start, source.length - end), start, old.length - end, 'preserve');
106
+ emitChange();
107
+ };
108
+ /** A page edit (`pages.ts`): the new source, then the caret where the edit puts it. */
109
+ const apply = (edit: PageEdit) => {
110
+ setSource(edit.source);
111
+ reveal(textarea, edit.caret);
112
+ emitSelection();
113
+ };
114
+
115
+ return {
116
+ getSource: () => textarea.value,
117
+ setSource,
118
+ insert(html) {
119
+ const [start, end] = insertionRange(textarea.value, textarea.selectionStart, textarea.selectionEnd);
120
+ // The inserted element ends up selected: the inspector shows it and the next insert goes after it.
121
+ textarea.setRangeText(html, start, end, 'select');
122
+ emitChange();
123
+ },
124
+ getElement(id) {
125
+ const el = component(id);
126
+ return el === null ? null : textarea.value.slice(el.start, el.end);
127
+ },
128
+ replaceElement(id, html) {
129
+ const el = component(id);
130
+ if (el === null) return;
131
+ const { selectionStart, selectionEnd, selectionDirection } = textarea;
132
+ const delta = html.length - (el.end - el.start);
133
+ // A caret inside the element stays inside it (at most on its last character); later offsets shift.
134
+ const map = (offset: number) =>
135
+ offset < el.start
136
+ ? offset
137
+ : offset >= el.end
138
+ ? offset + delta
139
+ : Math.min(offset, el.start + Math.max(0, html.length - 1));
140
+ textarea.setRangeText(html, el.start, el.end, 'preserve');
141
+ textarea.setSelectionRange(map(selectionStart), map(selectionEnd), selectionDirection);
142
+ emitChange();
143
+ },
144
+ getSelection: current,
145
+ select(id) {
146
+ const el = elements().find((e) => e.id === id);
147
+ if (el === undefined) return;
148
+ reveal(textarea, el.start);
149
+ textarea.focus();
150
+ emitSelection();
151
+ },
152
+ splitPage() {
153
+ const edit = splitPageSource(textarea.value, textarea.selectionStart);
154
+ if (edit !== null) apply(edit);
155
+ return edit?.id ?? null;
156
+ },
157
+ addPage(after) {
158
+ const edit = addPageSource(textarea.value, after);
159
+ apply(edit);
160
+ return edit.id;
161
+ },
162
+ mergePage(id) {
163
+ const edit = mergePageSource(textarea.value, id);
164
+ if (edit !== null) apply(edit);
165
+ return edit !== null;
166
+ },
167
+ onChange(listener) {
168
+ changes.add(listener);
169
+ return () => changes.delete(listener);
170
+ },
171
+ onSelectionChange(listener) {
172
+ selections.add(listener);
173
+ return () => selections.delete(listener);
174
+ },
175
+ destroy() {
176
+ textarea.removeEventListener('input', emitChange);
177
+ for (const type of SELECTION_EVENTS) textarea.removeEventListener(type, emitSelection);
178
+ changes.clear();
179
+ selections.clear();
180
+ },
181
+ };
182
+ }