@motionscript/code 0.1.0-alpha.8 → 0.1.0-alpha.9

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/README.md CHANGED
@@ -1,176 +1,175 @@
1
- # @motionscript/code
2
-
3
- Animated, syntax-highlighted code listings for [Motion Script](https://motionscript.dev).
4
- The `Code` node highlights source with [Lezer](https://lezer.codemirror.net)
5
- grammars and animates edits at the token level: each edit is diffed against the
6
- listing it becomes, so tokens that survive travel to their new columns, removed
7
- ones fade out and new ones fade in, rather than the listing snapping.
8
-
9
- Hand `Code` to the engine through your project entry's `nodes`, and any
10
- document that engine opens can name it as `code`:
11
-
12
- ```ts
13
- // src/project.ts
14
- import { Code } from '@motionscript/code';
15
-
16
- export const nodes = [Code];
17
- ```
18
-
19
- ```ts
20
- import type { CompositionDocument } from '@motionscript/sdk';
21
- import { lines } from '@motionscript/code';
22
-
23
- export default {
24
- kind: 'composition',
25
- nodes: [
26
- { id: 'listing', type: 'code', parentId: null, layerOrder: 0,
27
- props: { code: 'function greet(name) {\n return "hi";\n}', language: 'typescript',
28
- theme: 'github-dark', fontSize: 28 } },
29
- ],
30
- commands: [
31
- { id: 'call', type: 'append', targetId: 'listing', at: 0, duration: 0.6,
32
- args: { code: '\ngreet("world");' } },
33
- { id: 'focus', type: 'highlight', targetId: 'listing', at: 0.8, duration: 0.4,
34
- args: { target: lines(2) } },
35
- ],
36
- } satisfies CompositionDocument;
37
- ```
38
-
39
- ## What's in here
40
-
41
- - **`Code`**, a hugging block of highlighted source, written with
42
- `component2d`: call it (`Code({ ... })`) or construct it (`new Code({ ... })`).
43
- Set `code`, `language` and `theme` to choose what is shown; tune `fontSize`,
44
- `fontFamily`, `lineHeight`, `letterSpacing`, `showLineNumbers`,
45
- `lineNumberGap` and `padding` for layout.
46
- - **Token-level commands**: `append`/`prepend` (lines at the end or start),
47
- `insert` (at a `[line, col]` position), `remove`, `replace`,
48
- `highlight`/`resetHighlight` (dim everything outside a range, then restore
49
- it), and `highlightRows`/`resetRowHighlight` (a coloured band behind whole
50
- lines, which slides onto the next rows it is given and follows its lines
51
- through an edit). A `to` command on `code` diffs the whole listing the same way;
52
- while it runs, `code` holds a `CodeBlend` (`{ from, to, t }`) rather than a
53
- string, and a source again at either end.
54
- - **Range helpers**: `word(line, col, length)`, `lines(from, to)` and the
55
- chainable `CodeRanges` build the ranges those commands take.
56
- - **Themes**: `github-dark`, `github-light`, `vscode-dark`, `vscode-light`
57
- and a default, plus `registerCodeTheme` for your own.
58
- `initSyntaxHighlighter(themes, langs)` preloads grammars so the first frame
59
- renders fully highlighted.
60
-
61
- Every token keeps a stable identity across edits, so concurrent animations at
62
- different positions do not clobber each other while one is mid-flight.
63
-
64
- This package is written against [`@motionscript/sdk`](https://github.com/motionscript-dev/motionscript/tree/main/packages/sdk), which it
65
- takes as a peer dependency, and renders through whatever backend draws the
66
- scene, such as [`@motionscript/browser`](https://github.com/motionscript-dev/motionscript/tree/main/packages/browser).
67
-
68
- ## Languages, themes and line endings
69
-
70
- - **Languages**: `typescript` (`ts`), `tsx`, `javascript` (`js`), `jsx`, `python`
71
- (`py`), `json`, `html`, `css`, `rust`, `go`, `java`, `cpp` (`c++`), `php`,
72
- `markdown` (`md`), `xml` and `yaml` (`yml`). `shell` is an alias of
73
- `javascript`, because no shell grammar is bundled. Names are case-insensitive.
74
- - **An unknown language, a grammar whose import is rejected and an unknown theme
75
- name** each fall back (plain text, plain text and the default theme) and log one
76
- `[Code]` warning per name for the life of the process. `''`, `text` and
77
- `plaintext` mean plain text on purpose and say nothing.
78
- - **`language` and `theme` can be tweened or bound.** The listing is re-coloured
79
- from the props on the next frame, keeping the token identities a highlight
80
- already names.
81
- - **`\r\n` and a lone `\r` are line breaks**, in `code` and in the text a command
82
- brings in; the node's `code` reads back with `\n` after its first command.
83
- - **Edits are diffed within a budget.** Lines are paired by the same text at the
84
- ends of the listing and by lines that occur once on both sides, so an edit
85
- to a long listing costs in proportion to what changed. Only a run of changed
86
- lines between two such anchors is compared pairwise, up to
87
- `LINE_ALIGN_CELLS` (40,000) line pairs per run and 160,000 per edit; beyond
88
- that its lines leave and enter as whole rows instead of morphing into each
89
- other.
90
- - **A command on a node that is not in a tree** runs its duration and writes
91
- nothing. A document cannot reach this, because the validator rejects a command
92
- that starts before its target is present.
93
-
94
- ## Ranges, queries and what a copy holds
95
-
96
- - **Ranges are 1-indexed** in lines and columns. `endLine`/`endCol` may be
97
- `Infinity` (to the end of the line or document); a range that went through
98
- JSON holds `null` there and reads the same. Positions clamp, so no command
99
- throws for a bad range, and a `CodeRanges` chain serialises as its array of
100
- ranges.
101
- - **`findAllRanges(source, text)`, `findRangeAt(source, text, index)` and
102
- `findFirstRange(source, text)`** return the literal matches in a source as
103
- ranges: pass a listing's `code`. `listingOf(node)` is what a listing shows now:
104
- its source, its token rows and the edit in flight.
105
- - **`remove` is the command's key, and a node has no method of that name for it**:
106
- `Node.remove` already takes a child out of the tree, so the command is
107
- dispatched by key (a document, a host's registry) and reaches the node's
108
- `_command_remove`.
109
- - **A `Code` takes no children and has no `fill`, `stroke` or `shadow`**; a panel
110
- behind it is a parent `Rect`. It also refuses the ambient text style
111
- (`<DefaultTextStyle>`): its columns are measured against its own face, so an
112
- inherited family or weight would shape glyphs the geometry never measured.
113
- - **`diffStrategy` and `phaseStrategy`** (`CodeStrategies`) replace how an edit is
114
- paired and how its out/move/in windows are timed. They are arguments of
115
- `defineCode({ diffStrategy, phaseStrategy })`, which returns a `code` component
116
- using them: hand that to the engine in place of `Code`. A strategy is a
117
- function, which a prop would read as a binding, so a document cannot set one.
118
- - **Each listing command writes the listing it acted on**, so the token ids a
119
- highlight or a band captured are the ones drawn. Two commands of one kind
120
- that overlap (two edits, two highlights) hand over from the later one's first
121
- frame: the later command's state replaces the earlier's while both run.
122
- - **A `Code` is drawn from what its last measure laid out**, which its parent
123
- asks for before every frame; one that was never measured draws nothing.
124
- - **Highlighter state is per process.** Loaded grammars, registered themes and
125
- token ids are shared by every `Code` in it.
126
- - **`ms add code` copies only `node.ts`** (`registry.json`). The highlighter,
127
- diff, layout and drawing stay in this package behind `src/engine.ts`, which the
128
- copy imports from `@motionscript/code`; the grammars are dynamic imports, so a
129
- host's bundler must resolve `@lezer/*` from where the package is installed.
130
-
131
- ## The monospaced face is yours to supply
132
-
133
- `Code` measures and draws every token in its `fontFamily`, `Fira Mono` by
134
- default, and lines its columns up on that face's advances. The package ships no
135
- font file and names no URL: list a monospaced face under that family in the
136
- engine's asset manifest, alongside the node itself.
137
-
138
- ```ts
139
- const engine = await createBrowserEngine({
140
- wasmUrl,
141
- nodes: [Code],
142
- manifest: {
143
- image: {}, video: {}, audio: {},
144
- font: {
145
- 'Fira Mono@400': {
146
- fontFamily: 'Fira Mono', fontWeight: 400,
147
- src: '/fonts/FiraMono-Regular.ttf', sizeBytes: 0,
148
- },
149
- },
150
- },
151
- });
152
- ```
153
-
154
- A family the manifest does not list is never loaded. The loader warns once, and
155
- the listing draws no text, or shapes in whichever other face is registered. To
156
- use another face, set `fontFamily` on the node and list that family instead.
157
-
158
- ## Usage
159
-
160
- ```bash
161
- npm install @motionscript/code @motionscript/sdk
162
- ```
163
-
164
- Or copy the node's source into your project with `ms add code`
165
- (see [`@motionscript/cli`](https://github.com/motionscript-dev/motionscript/tree/main/packages/cli)). See the
166
- [docs](https://motionscript.dev/docs) for the full feature set and API
167
- reference.
168
-
169
- ## Development
170
-
171
- From the monorepo root:
172
-
173
- ```bash
174
- pnpm --filter @motionscript/code build
175
- pnpm --filter @motionscript/code test
176
- ```
1
+ # @motionscript/code
2
+
3
+ Animated, syntax-highlighted code listings for [Motion Script](https://motionscript.dev).
4
+ The `Code` node highlights source with [Lezer](https://lezer.codemirror.net)
5
+ grammars and animates edits at the token level: each edit is diffed against the
6
+ listing it becomes, so tokens that survive travel to their new columns, removed
7
+ ones fade out and new ones fade in, rather than the listing snapping.
8
+
9
+ Hand `Code` to the engine through your project entry's `nodes`, and any
10
+ document that engine opens can name it as `code`:
11
+
12
+ ```ts
13
+ // src/project.ts
14
+ import { Code } from '@motionscript/code';
15
+
16
+ export const nodes = [Code];
17
+ ```
18
+
19
+ ```ts
20
+ import type { CompositionDocument } from '@motionscript/sdk';
21
+ import { lines } from '@motionscript/code';
22
+
23
+ export default {
24
+ kind: 'composition',
25
+ nodes: [
26
+ { id: 'listing', type: 'code', parentId: null, layerOrder: 0,
27
+ props: { code: 'function greet(name) {\n return "hi";\n}', language: 'typescript',
28
+ theme: 'github-dark', fontSize: 28 } },
29
+ ],
30
+ commands: [
31
+ { id: 'call', type: 'append', targetId: 'listing', at: 0, duration: 0.6,
32
+ args: { code: '\ngreet("world");' } },
33
+ { id: 'focus', type: 'highlight', targetId: 'listing', at: 0.8, duration: 0.4,
34
+ args: { target: lines(2) } },
35
+ ],
36
+ } satisfies CompositionDocument;
37
+ ```
38
+
39
+ ## What's in here
40
+
41
+ - **`Code`**, a hugging block of highlighted source, written with
42
+ `component2d`: call it (`Code({ ... })`) or construct it (`new Code({ ... })`).
43
+ Set `code`, `language` and `theme` to choose what is shown; tune `fontSize`,
44
+ `fontFamily`, `lineHeight`, `letterSpacing`, `showLineNumbers`,
45
+ `lineNumberGap` and `padding` for layout.
46
+ - **Token-level commands**: `append`/`prepend` (lines at the end or start),
47
+ `insert` (at a `[line, col]` position), `remove`, `replace`,
48
+ `highlight`/`resetHighlight` (dim everything outside a range, then restore
49
+ it), and `highlightRows`/`resetRowHighlight` (a coloured band behind whole
50
+ lines, which slides onto the next rows it is given and follows its lines
51
+ through an edit). A `to` command on `code` diffs the whole listing the same way;
52
+ while it runs, `code` holds a `CodeBlend` (`{ from, to, t }`) rather than a
53
+ string, and a source again at either end.
54
+ - **Range helpers**: `word(line, col, length)`, `lines(from, to)` and the
55
+ chainable `CodeRanges` build the ranges those commands take.
56
+ - **Themes**: `github-dark`, `github-light`, `vscode-dark`, `vscode-light`
57
+ and a default, plus `registerCodeTheme` for your own.
58
+ `initSyntaxHighlighter(themes, langs)` preloads grammars so the first frame
59
+ renders fully highlighted.
60
+
61
+ Every token keeps a stable identity across edits, so concurrent animations at
62
+ different positions do not clobber each other while one is mid-flight.
63
+
64
+ This package is written against [`@motionscript/sdk`](https://github.com/motionscript-dev/motionscript/tree/main/packages/sdk), which it
65
+ takes as a peer dependency, and renders through whatever backend draws the
66
+ scene, such as [`@motionscript/browser`](https://github.com/motionscript-dev/motionscript/tree/main/packages/browser).
67
+
68
+ ## Languages, themes and line endings
69
+
70
+ - **Languages**: `typescript` (`ts`), `tsx`, `javascript` (`js`), `jsx`, `python`
71
+ (`py`), `json`, `html`, `css`, `rust`, `go`, `java`, `cpp` (`c++`), `php`,
72
+ `markdown` (`md`), `xml` and `yaml` (`yml`). `shell` is an alias of
73
+ `javascript`, because no shell grammar is bundled. Names are case-insensitive.
74
+ - **An unknown language, a grammar whose import is rejected and an unknown theme
75
+ name** each fall back (plain text, plain text and the default theme) and log one
76
+ `[Code]` warning per name for the life of the process. `''`, `text` and
77
+ `plaintext` mean plain text on purpose and say nothing.
78
+ - **`language` and `theme` can be tweened or bound.** The listing is re-coloured
79
+ from the props on the next frame, keeping the token identities a highlight
80
+ already names.
81
+ - **`\r\n` and a lone `\r` are line breaks**, in `code` and in the text a command
82
+ brings in; the node's `code` reads back with `\n` after its first command.
83
+ - **Edits are diffed within a budget.** Lines are paired by the same text at the
84
+ ends of the listing and by lines that occur once on both sides, so an edit
85
+ to a long listing costs in proportion to what changed. Only a run of changed
86
+ lines between two such anchors is compared pairwise, up to
87
+ `LINE_ALIGN_CELLS` (40,000) line pairs per run and 160,000 per edit; beyond
88
+ that its lines leave and enter as whole rows instead of morphing into each
89
+ other.
90
+ - **A command on a node that is not in a tree** runs its duration and writes
91
+ nothing. A document cannot reach this, because the validator rejects a command
92
+ that starts before its target is present.
93
+
94
+ ## Ranges, queries and what a copy holds
95
+
96
+ - **Ranges are 1-indexed** in lines and columns. `endLine`/`endCol` may be
97
+ `Infinity` (to the end of the line or document); a range that went through
98
+ JSON holds `null` there and reads the same. Positions clamp, so no command
99
+ throws for a bad range, and a `CodeRanges` chain serialises as its array of
100
+ ranges.
101
+ - **`findAllRanges(source, text)`, `findRangeAt(source, text, index)` and
102
+ `findFirstRange(source, text)`** return the literal matches in a source as
103
+ ranges: pass a listing's `code`. `listingOf(node)` is what a listing shows now:
104
+ its source, its token rows and the edit in flight.
105
+ - **`remove` is the command's key, and a node has no method of that name for it**:
106
+ `Node.remove` already takes a child out of the tree, so the command is
107
+ dispatched by key (a document, a host's registry) and reaches the node's
108
+ `_command_remove`.
109
+ - **A `Code` takes no children and has no `fill`, `stroke` or `shadow`**; a panel
110
+ behind it is a parent `Rect`. It also refuses the ambient text style
111
+ (`<DefaultTextStyle>`): its columns are measured against its own face, so an
112
+ inherited family or weight would shape glyphs the geometry never measured.
113
+ - **`diffStrategy` and `phaseStrategy`** (`CodeStrategies`) replace how an edit is
114
+ paired and how its out/move/in windows are timed. They are arguments of
115
+ `defineCode({ diffStrategy, phaseStrategy })`, which returns a `code` component
116
+ using them: hand that to the engine in place of `Code`. A strategy is a
117
+ function, which a prop would read as a binding, so a document cannot set one.
118
+ - **Each listing command writes the listing it acted on**, so the token ids a
119
+ highlight or a band captured are the ones drawn. Two commands of one kind
120
+ that overlap (two edits, two highlights) hand over from the later one's first
121
+ frame: the later command's state replaces the earlier's while both run.
122
+ - **A `Code` is drawn from what its last measure laid out**, which its parent
123
+ asks for before every frame; one that was never measured draws nothing.
124
+ - **Highlighter state is per process.** Loaded grammars, registered themes and
125
+ token ids are shared by every `Code` in it.
126
+ - **A copy of `code` takes only `node.ts`** (`registry.json`). The highlighter,
127
+ diff, layout and drawing stay in this package behind `src/engine.ts`, which the
128
+ copy imports from `@motionscript/code`; the grammars are dynamic imports, so a
129
+ host's bundler must resolve `@lezer/*` from where the package is installed.
130
+
131
+ ## The monospaced face is yours to supply
132
+
133
+ `Code` measures and draws every token in its `fontFamily`, `Fira Mono` by
134
+ default, and lines its columns up on that face's advances. The package ships no
135
+ font file and names no URL: list a monospaced face under that family in the
136
+ engine's asset manifest, alongside the node itself.
137
+
138
+ ```ts
139
+ const engine = await createBrowserEngine({
140
+ wasmUrl,
141
+ nodes: [Code],
142
+ manifest: {
143
+ image: {}, video: {}, audio: {},
144
+ font: {
145
+ 'Fira Mono@400': {
146
+ fontFamily: 'Fira Mono', fontWeight: 400,
147
+ src: '/fonts/FiraMono-Regular.ttf', sizeBytes: 0,
148
+ },
149
+ },
150
+ },
151
+ });
152
+ ```
153
+
154
+ A family the manifest does not list is never loaded. The loader warns once, and
155
+ the listing draws no text, or shapes in whichever other face is registered. To
156
+ use another face, set `fontFamily` on the node and list that family instead.
157
+
158
+ ## Usage
159
+
160
+ ```bash
161
+ npm install @motionscript/code @motionscript/sdk
162
+ ```
163
+
164
+ See the
165
+ [docs](https://motionscript.dev/docs) for the full feature set and API
166
+ reference.
167
+
168
+ ## Development
169
+
170
+ From the monorepo root:
171
+
172
+ ```bash
173
+ pnpm --filter @motionscript/code build
174
+ pnpm --filter @motionscript/code test
175
+ ```