@lincyaw/viewer 0.0.0-stage → 1.0.0-rc.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.
- package/LICENSE +202 -0
- package/README.md +31 -2
- package/package.json +65 -3
- package/src/client/block.ts +70 -0
- package/src/client/code/code-block.ts +54 -0
- package/src/client/code/code-editor.ts +73 -0
- package/src/client/code/code-view.ts +22 -0
- package/src/client/code/highlight.ts +73 -0
- package/src/client/code/outputs.ts +84 -0
- package/src/client/content-marks.ts +15 -0
- package/src/client/element.ts +27 -0
- package/src/client/env.d.ts +3 -0
- package/src/client/index.ts +40 -0
- package/src/client/layout.ts +22 -0
- package/src/client/markdown/handlers.ts +161 -0
- package/src/client/markdown/hast.ts +20 -0
- package/src/client/markdown/layout-handlers.ts +57 -0
- package/src/client/markdown/math.ts +10 -0
- package/src/client/markdown/mermaid.ts +75 -0
- package/src/client/markdown/render.ts +79 -0
- package/src/client/markdown/role-mark.ts +9 -0
- package/src/client/markdown/tables.ts +49 -0
- package/src/client/markdown/tabs.ts +52 -0
- package/src/client/markdown/tree-cache.ts +77 -0
- package/src/client/operations.ts +9 -0
- package/src/client/registry.ts +21 -0
- package/src/client/section-context.ts +5 -0
- package/src/client/section.ts +30 -0
- package/src/client/slidev-compat/click-directives.ts +16 -0
- package/src/client/slidev-compat/slide-globals.ts +3 -0
- package/src/client/style.css +1058 -0
- package/src/client/viewer-messages.ts +7 -0
- package/src/client/viewer-plugins.ts +35 -0
- package/src/client/viewer-state.ts +47 -0
- package/src/client/views/actions.ts +52 -0
- package/src/client/views/controls.css +44 -0
- package/src/client/views/document.ts +12 -0
- package/src/client/views/outlets.ts +37 -0
- package/src/client/views/overlay.ts +16 -0
- package/src/client/views/present.ts +132 -0
- package/src/client/views/presenter.ts +76 -0
- package/src/client/views/scrolly.ts +4 -0
- package/src/client/views/slide.css +8 -0
- package/src/client/views/slide.ts +57 -0
- package/src/domain/clicks.ts +38 -0
- package/src/domain/code-width.ts +11 -0
- package/src/domain/document-content.ts +6 -0
- package/src/domain/footnotes.ts +15 -0
- package/src/domain/index.ts +22 -0
- package/src/domain/live.ts +44 -0
- package/src/domain/messages.ts +139 -0
- package/src/domain/origin.ts +78 -0
- package/src/domain/outputs.ts +27 -0
- package/src/domain/steps.ts +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lincyaw/viewer
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Presmium's IR runtime: renders compiled documents in the browser with React, in pluggable runtime views (the document, scrollytelling, the present view, the presenter view), and applies live updates without reloading. The web form and the slides are both this runtime: a slide is a section on a canvas of a fixed size, scaled as a whole. Runnable code blocks can be edited in place before they run (CodeMirror 6, loaded the first time a block is edited).
|
|
4
|
+
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical lecture.json teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
The web renderer `@lincyaw/web` brings it. Plugins that extend it declare it as a peer dependency (`"@lincyaw/viewer": "^1.0.0"`).
|
|
10
|
+
|
|
11
|
+
## Viewer plugins
|
|
12
|
+
|
|
13
|
+
A plugin's `src/client/viewer.ts` exports a `ViewerPlugin`, which registers views, node renderers, components, actions and layers. A layer's `scope` puts it over the window (`viewport`, the default), over the view (`view`), on each slide (`slide`, in the canvas's coordinates, its props also giving the slide's `section` and `step`) or in the presentation bar (`bar`):
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import type { ViewerPlugin } from '@lincyaw/viewer'
|
|
17
|
+
|
|
18
|
+
const plugin: ViewerPlugin = (ctx) => {
|
|
19
|
+
ctx.registerAction({ id: 'my.next', keys: ['n'], run: viewer => viewer.next() })
|
|
20
|
+
}
|
|
21
|
+
export default plugin
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Author editing lives in one native BlockNote document editor in the workbench. It saves normalized `lecture.json` through document-version transactions. The viewer remains a runtime snapshot consumer; independent readers and presentations do not load the authoring editor. React extensions subscribe to public viewer stores with `useStore(viewer.position)` or `useStore(viewer.doc)`.
|
|
25
|
+
|
|
26
|
+
## Documentation
|
|
27
|
+
|
|
28
|
+
- [Plugin guide](https://github.com/Lincyaw/presmium/blob/main/site/plugins/locales/en/lecture.json)
|
|
29
|
+
|
|
30
|
+
## License
|
|
31
|
+
|
|
32
|
+
Apache-2.0
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/viewer",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0-rc.1",
|
|
4
|
+
"description": "Presmium's IR runtime: renders the IR in the browser, with runtime views and live updates",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Lincyaw/presmium.git",
|
|
9
|
+
"directory": "packages/viewer"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/viewer#readme",
|
|
12
|
+
"bugs": "https://github.com/Lincyaw/presmium/issues",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"presmium",
|
|
15
|
+
"ir",
|
|
16
|
+
"react"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22.19"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": "./src/client/index.ts",
|
|
27
|
+
"./domain": "./src/domain/index.ts",
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"src"
|
|
32
|
+
],
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@codemirror/commands": "6.11.1",
|
|
35
|
+
"@codemirror/lang-javascript": "6.2.5",
|
|
36
|
+
"@codemirror/lang-python": "6.2.1",
|
|
37
|
+
"@codemirror/language": "6.13.1",
|
|
38
|
+
"@codemirror/state": "6.7.6",
|
|
39
|
+
"@codemirror/view": "6.43.14",
|
|
40
|
+
"@lezer/highlight": "1.2.5",
|
|
41
|
+
"@radix-ui/react-focus-scope": "^1.1.8",
|
|
42
|
+
"@radix-ui/react-tabs": "^1.1.13",
|
|
43
|
+
"@shikijs/magic-move": "4.5.0",
|
|
44
|
+
"ansi_up": "6.0.6",
|
|
45
|
+
"dompurify": "3.4.17",
|
|
46
|
+
"hast-util-raw": "9.1.0",
|
|
47
|
+
"hast-util-to-html": "9.0.5",
|
|
48
|
+
"katex": "0.18.10",
|
|
49
|
+
"mdast-util-from-markdown": "2.1.0",
|
|
50
|
+
"mdast-util-gfm": "3.1.0",
|
|
51
|
+
"mdast-util-to-hast": "13.2.1",
|
|
52
|
+
"mermaid": "12.2.0",
|
|
53
|
+
"micromark-extension-gfm": "3.0.0",
|
|
54
|
+
"property-information": "7.2.0",
|
|
55
|
+
"react": "18.3.1",
|
|
56
|
+
"react-dom": "18.3.1",
|
|
57
|
+
"shiki": "4.5.0",
|
|
58
|
+
"style-to-js": "2.0.2",
|
|
59
|
+
"@lincyaw/host": "1.0.0-rc.1",
|
|
60
|
+
"@lincyaw/kernel": "1.0.0-rc.1"
|
|
61
|
+
},
|
|
62
|
+
"devDependencies": {
|
|
63
|
+
"@types/hast": "3.0.5",
|
|
64
|
+
"@types/mdast": "4.0.4",
|
|
65
|
+
"@types/react": "18.3.28",
|
|
66
|
+
"@types/react-dom": "18.3.7"
|
|
67
|
+
}
|
|
6
68
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createContext, memo, useContext, useEffect, useRef, useState } from 'react'
|
|
2
|
+
import type { ReactNode } from 'react'
|
|
3
|
+
import { PmBoundary, StepScope, useStaticRender, useStore } from '@lincyaw/host'
|
|
4
|
+
import { blockStepState, blockVisible, componentProps, fnv1a64 } from '@lincyaw/kernel'
|
|
5
|
+
import type { ComponentNode, IRBlock, IRSection } from '@lincyaw/kernel'
|
|
6
|
+
import { FINAL_STEP } from '../domain/index.ts'
|
|
7
|
+
import { CODE_OWNED, CodeBlockView } from './code/code-block.ts'
|
|
8
|
+
import { contentMarks } from './content-marks.ts'
|
|
9
|
+
import { markdownToHast } from './markdown/handlers.ts'
|
|
10
|
+
import { PmMermaid } from './markdown/mermaid.ts'
|
|
11
|
+
import { hastToVNodes, MarkdownView } from './markdown/render.ts'
|
|
12
|
+
import { findComponent, findNodeRenderer, registryRevision } from './registry.ts'
|
|
13
|
+
import { BLOCK_CLASS, trackClicks } from './slidev-compat/click-directives.ts'
|
|
14
|
+
import { viewerMessages } from './viewer-messages.ts'
|
|
15
|
+
import { VIEWER } from './viewer-state.ts'
|
|
16
|
+
import { h } from './element.ts'
|
|
17
|
+
import { SECTION_CONTEXT } from './section-context.ts'
|
|
18
|
+
export interface BlockProps { block: IRBlock, section: IRSection, step: number, expanded?: boolean, localPreview?: boolean }
|
|
19
|
+
const COMPONENT_NODE = createContext<{ node: ComponentNode, section: string } | undefined>(undefined)
|
|
20
|
+
function fallbackOf(node: ComponentNode, section: string) { return node.fallback ? hastToVNodes(markdownToHast(node.fallback, section).children, {}) : [] }
|
|
21
|
+
export function PmComponentFallback() { const current = useContext(COMPONENT_NODE); return current ? h('div', { className: 'pm-component-fallback' }, fallbackOf(current.node, current.section)) : null }
|
|
22
|
+
function ComponentView(props: BlockProps) {
|
|
23
|
+
const node = props.block.node as ComponentNode
|
|
24
|
+
const printed = useStaticRender()
|
|
25
|
+
useStore(registryRevision)
|
|
26
|
+
const component = findComponent(node.name)
|
|
27
|
+
if (printed && node.fallback) return h('div', { className: 'pm-static-fallback', 'data-component': node.name }, fallbackOf(node, props.section.id))
|
|
28
|
+
if (!component) { const fallback = fallbackOf(node, props.section.id); return h('div', { className: 'pm-component-missing', 'data-component': node.name }, fallback.length ? fallback : viewerMessages().missingComponent(node.name)) }
|
|
29
|
+
const state = blockStepState(props.block, props.step)
|
|
30
|
+
const children = node.children?.map(child => h(BlockView, { key: child.id, block: child, section: props.section, step: props.step, expanded: props.expanded }))
|
|
31
|
+
const key = fnv1a64(JSON.stringify([node.props, node.children ?? []]))
|
|
32
|
+
return h(CODE_OWNED.Provider, { value: node.ownsCode !== false }, h(COMPONENT_NODE.Provider, { value: { node, section: props.section.id } }, h(PmBoundary, { name: node.name, resetKey: props.expanded ? key : `${key}@${props.step}` }, h(component, { ...componentProps(node), ...state?.parameters }, children))))
|
|
33
|
+
}
|
|
34
|
+
function content(props: BlockProps): ReactNode {
|
|
35
|
+
const node = props.block.node
|
|
36
|
+
const custom = (node.type === 'component' && findNodeRenderer(node.name)) || (node.type === 'code' && findNodeRenderer(`code:${node.lang}`)) || findNodeRenderer(node.type)
|
|
37
|
+
if (custom) return h(custom, props)
|
|
38
|
+
switch (node.type) {
|
|
39
|
+
case 'markdown': return h(MarkdownView, { ...props, prefix: props.section.id })
|
|
40
|
+
case 'code': return node.lang === 'mermaid' ? h(PmMermaid, { code: node.value }) : h(CodeBlockView, props)
|
|
41
|
+
case 'component': return h(ComponentView, props)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function BlockViewContent(props: BlockProps) {
|
|
45
|
+
const viewer = useContext(VIEWER); const el = useRef<HTMLDivElement>(null)
|
|
46
|
+
useStore(registryRevision)
|
|
47
|
+
useEffect(() => el.current ? trackClicks(el.current, props.expanded ? FINAL_STEP : props.step) : undefined, [props.step, props.expanded, props.block])
|
|
48
|
+
const { block } = props
|
|
49
|
+
const visible = props.expanded || blockVisible(block, props.step)
|
|
50
|
+
const role = block.role === 'narration' && block.only && !block.only.includes('lecture') ? 'reading' : block.role
|
|
51
|
+
return h(StepScope, { at: block.at, until: block.until, states: block.stepStates, step: props.step, localPreview: props.localPreview }, h('div', {
|
|
52
|
+
ref: el, className: [BLOCK_CLASS, `pm-block--${block.role}`, `pm-block--${block.node.type}`, block.until !== undefined ? 'pm-step-range' : '', block.node.type === 'component' && block.node.layer === 'overlay' ? 'pm-block--overlay' : '', !visible ? 'pm-hidden' : ''].filter(Boolean).join(' '),
|
|
53
|
+
'data-block': block.id, 'data-content-role': role, 'data-content-label': viewerMessages().contentRoles[role], 'data-at': block.at, 'data-component': block.node.type === 'component' ? block.node.name : undefined, 'aria-hidden': visible ? undefined : true,
|
|
54
|
+
onClick: viewer?.options.openSource ? (event: MouseEvent) => { if (event.altKey) { event.preventDefault(); event.stopPropagation(); viewer.options.openSource!(block.source) } } : undefined,
|
|
55
|
+
}, [contentMarks(props.section, role, block.at, block.span ?? 0), content(props)]))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const BlockView = memo(BlockViewContent)
|
|
59
|
+
|
|
60
|
+
/** A compiled block's standalone read-only surface, using the same host scope as the full viewer. */
|
|
61
|
+
export function BlockPreview({ block, section }: { block: IRBlock, section: IRSection }) {
|
|
62
|
+
const viewer = useContext(VIEWER)
|
|
63
|
+
const [selected, setSelected] = useState<{ section: string, step: number }>()
|
|
64
|
+
useEffect(() => viewer?.position.subscribe(() => {
|
|
65
|
+
const position = viewer.position.getSnapshot()
|
|
66
|
+
if (position.section === section.id && section.stepIds?.[position.step]) setSelected(position)
|
|
67
|
+
}), [viewer, section.id])
|
|
68
|
+
const step = selected?.section === section.id ? selected.step : FINAL_STEP
|
|
69
|
+
return h(SECTION_CONTEXT.Provider, { value: { section, step, view: 'document' } }, h('div', { className: 'pm-document pm-block-preview', 'data-section': section.id }, h(BlockView, { block, section, step, expanded: true, localPreview: true })))
|
|
70
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { createContext, useContext, useEffect, useRef, useState } from 'react'
|
|
2
|
+
import { currentLocale, OPERATIONS, PmIconButton, useService, useStartReport, useStaticRender } from '@lincyaw/host'
|
|
3
|
+
import type { Operations } from '@lincyaw/host'
|
|
4
|
+
import { blockState, EXECUTOR, errorMessage, failedRun } from '@lincyaw/kernel'
|
|
5
|
+
import type { CodeNode, IRBlock, RecordedRun, RunRequest, RunResult } from '@lincyaw/kernel'
|
|
6
|
+
import { originBar } from '../../domain/index.ts'
|
|
7
|
+
import { useSectionContext } from '../section-context.ts'
|
|
8
|
+
import { viewerMessages } from '../viewer-messages.ts'
|
|
9
|
+
import { h } from '../element.ts'
|
|
10
|
+
import { CodeEditor } from './code-editor.ts'
|
|
11
|
+
import { CodeView, VariantView } from './code-view.ts'
|
|
12
|
+
import { isProseOutput, runOutput } from './outputs.ts'
|
|
13
|
+
export const CODE_OWNED = createContext(false)
|
|
14
|
+
const replays = new Set<(data: Record<string, unknown>) => void>()
|
|
15
|
+
const listening = new WeakSet<Operations>()
|
|
16
|
+
function listenRunReplays(operations: Operations) { if (listening.has(operations)) return; listening.add(operations); operations.onReplay('run', { apply: data => replays.forEach(replay => replay(data)) }) }
|
|
17
|
+
export function CodeBlockView(props: { block: IRBlock, step: number, expanded?: boolean }) {
|
|
18
|
+
const owned = useContext(CODE_OWNED); const executor = useService(EXECUTOR); const operations = useService(OPERATIONS); const section = useSectionContext(); const report = useStartReport(); const printed = useStaticRender()
|
|
19
|
+
const [live, setLive] = useState<RunResult>(); const [fallback, setFallback] = useState<string>(); const [running, setRunning] = useState(false); const [edited, setEdited] = useState<string>(); const [editing, setEditing] = useState(false); const [mounted, setMounted] = useState(false); const current = useRef<AbortController>()
|
|
20
|
+
const node = props.block.node as CodeNode
|
|
21
|
+
const stop = () => { current.current?.abort(); current.current = undefined; setRunning(false) }
|
|
22
|
+
const show = (result: RunResult | undefined) => { const recorded = result && !result.ok && result.exitCode === null && node.outputs?.length; setFallback(recorded ? result.stderr.trim() || viewerMessages().code.unavailable : undefined); setLive(recorded ? undefined : result) }
|
|
23
|
+
useEffect(() => { setMounted(true); return () => current.current?.abort() }, [])
|
|
24
|
+
useEffect(() => { stop(); setLive(undefined); setFallback(undefined); setEdited(undefined); setEditing(false) }, [node.value])
|
|
25
|
+
useEffect(() => { if (operations) listenRunReplays(operations); const replay = (data: Record<string, unknown>) => { if (data.block === props.block.id && (data.section === undefined || data.section === section?.section.id)) { stop(); show(undefined) } }; replays.add(replay); return () => { replays.delete(replay) } }, [operations, props.block.id, section?.section.id])
|
|
26
|
+
const run = async () => {
|
|
27
|
+
if (!node.run || !executor || running) return
|
|
28
|
+
stop(); const controller = new AbortController(); current.current = controller; setRunning(true)
|
|
29
|
+
const { lang, args, stdin, timeoutMs, executor: named, session } = node.run
|
|
30
|
+
const request: RunRequest = { lang, code: edited ?? node.value, args, stdin, timeoutMs, executor: named, session, ...section ? { place: { section: section.section.id, block: props.block.id } } : {} }
|
|
31
|
+
const started = Date.now(); let result: RunResult
|
|
32
|
+
try { result = await executor.run(request, controller.signal) } catch (error) { result = failedRun(executor.id, viewerMessages().code.executorFailed(executor.id, errorMessage(error)), Date.now() - started) }
|
|
33
|
+
if (controller.signal.aborted) return
|
|
34
|
+
show(result); current.current = undefined; setRunning(false)
|
|
35
|
+
const recording = node.outputs?.[0] as RecordedRun | undefined
|
|
36
|
+
operations?.report({ type: 'run', data: { section: section?.section.id, block: props.block.id, result: !result.ok && recording ? `freeze:${recording.cacheKey}` : 'live' } })
|
|
37
|
+
}
|
|
38
|
+
const state = blockState(props.block, props.step); const variants = node.variants ?? []; const shown = variants.length && !props.expanded ? Math.min(state, variants.length - 1) : undefined
|
|
39
|
+
const listings = !variants.length ? [h(CodeView, { lang: node.lang, value: node.value, highlight: props.expanded ? undefined : node.highlight?.[state] })] : shown === undefined ? variants.map(v => h('div', { key: v.label, className: 'pm-code-block__variant' }, [h('p', { className: 'pm-code-block__label' }, v.label), h(CodeView, { lang: node.lang, value: v.value })])) : [h(VariantView, { lang: node.lang, value: variants[shown]!.value })]
|
|
40
|
+
const echo = node.echo !== false; const runnable = !owned && echo && node.run && node.run.when !== 'compile'; const editable = runnable && !variants.length && !node.highlight?.length && !printed; const t = viewerMessages().code; const available = mounted && executor
|
|
41
|
+
if (editable && (editing || edited !== undefined)) listings.splice(0, listings.length, editing ? h(CodeEditor, { lang: node.lang, value: edited ?? node.value, onChange: setEdited, onRun: run }) : h(CodeView, { lang: node.lang, value: edited! }))
|
|
42
|
+
const controls = runnable ? h('div', { className: 'pm-code-block__run', role: 'group', 'aria-label': t.actions }, [
|
|
43
|
+
h(PmIconButton, { icon: 'play', label: live ? t.rerun : t.run, hint: running ? t.running : live ? t.rerun : t.run, small: true, loading: running, disabled: !available, onClick: run }),
|
|
44
|
+
editable ? h(PmIconButton, { icon: editing ? 'check' : 'edit', label: editing ? t.doneEditing : t.edit, small: true, 'aria-pressed': editing, onClick: () => setEditing(!editing) }) : null,
|
|
45
|
+
edited !== undefined && edited !== node.value ? h(PmIconButton, { icon: 'undo', label: t.revert, small: true, onClick: () => { setEdited(undefined); setEditing(false) } }) : null,
|
|
46
|
+
node.run?.session ? h(PmIconButton, { icon: 'refresh', label: t.resetRunSession, small: true, disabled: !available, 'data-session': node.run.session, onClick: async () => { stop(); await executor?.endSession?.(node.run!.session!); show(undefined) } }) : null,
|
|
47
|
+
mounted && !executor && report ? h('span', { className: 'pm-code-block__hint' }, t.unavailable) : null,
|
|
48
|
+
]) : null
|
|
49
|
+
const runs = owned ? [] : live ? [live] : node.outputs ?? []; const prose = !echo && !live && runs.length > 0 && runs.every(isProseOutput); const prefix = section?.section.id ?? props.block.id
|
|
50
|
+
const outputs = runs.length ? h('div', { className: `pm-outputs${prose ? ' pm-outputs--prose' : ''}`, 'data-source': live ? 'live' : 'recorded' }, runs.map((r, i) => runOutput(r, (r as RecordedRun).cacheKey || i, prefix, { prose, note: fallback }))) : null
|
|
51
|
+
const bar = originBar(node, shown, currentLocale())
|
|
52
|
+
const origin = bar ? h('div', { className: 'pm-code-origin', 'data-anchor': bar.anchor }, bar.parts.map((part, key) => h(part.href ? 'a' : 'span', { key, className: `pm-code-origin__${part.kind}`, href: part.href, title: part.title, 'data-active': part.active ? '' : undefined, 'data-status': part.status, 'data-drift': part.drift }, part.text))) : null
|
|
53
|
+
return h('div', { className: `pm-code-block${!echo ? ' pm-code-block--output-only' : ''}`, 'data-state': props.expanded ? undefined : state, 'data-run': runnable ? node.run!.when : undefined, 'data-session': node.run?.session }, echo ? [origin, ...listings, controls, outputs] : [outputs])
|
|
54
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { languageId } from '@lincyaw/kernel'
|
|
2
|
+
import type { Extension } from '@codemirror/state'
|
|
3
|
+
import type { EditorView } from '@codemirror/view'
|
|
4
|
+
import { useEffect, useRef } from 'react'
|
|
5
|
+
import { h } from '../element.ts'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A runnable code block's code, edited in place (CodeMirror 6) before it is run: loaded the first time a block is
|
|
9
|
+
* edited, so that pages which are only read never load it. Mod-Enter runs the code; Escape then Tab leaves the editor.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const LANGUAGES: Record<string, () => Promise<Extension>> = {
|
|
13
|
+
python: () => import('@codemirror/lang-python').then(m => m.python()),
|
|
14
|
+
javascript: () => import('@codemirror/lang-javascript').then(m => m.javascript()),
|
|
15
|
+
typescript: () => import('@codemirror/lang-javascript').then(m => m.javascript({ typescript: true })),
|
|
16
|
+
jsx: () => import('@codemirror/lang-javascript').then(m => m.javascript({ jsx: true })),
|
|
17
|
+
tsx: () => import('@codemirror/lang-javascript').then(m => m.javascript({ jsx: true, typescript: true })),
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const ALIASES: Record<string, string> = { py: 'python', js: 'javascript', mjs: 'javascript', ts: 'typescript', mts: 'typescript' }
|
|
21
|
+
|
|
22
|
+
async function editorModules(lang: string) {
|
|
23
|
+
const id = languageId(lang)
|
|
24
|
+
const grammar = LANGUAGES[ALIASES[id] ?? id]
|
|
25
|
+
const [view, state, commands, language, highlight, extension] = await Promise.all([
|
|
26
|
+
import('@codemirror/view'),
|
|
27
|
+
import('@codemirror/state'),
|
|
28
|
+
import('@codemirror/commands'),
|
|
29
|
+
import('@codemirror/language'),
|
|
30
|
+
import('@lezer/highlight'),
|
|
31
|
+
grammar ? grammar() : Promise.resolve([]),
|
|
32
|
+
])
|
|
33
|
+
const { tags } = highlight
|
|
34
|
+
// The colours of the page's highlighted code, from the design tokens: light and dark alike.
|
|
35
|
+
const style = language.HighlightStyle.define([
|
|
36
|
+
{ tag: [tags.keyword, tags.controlKeyword, tags.operatorKeyword, tags.modifier], color: 'var(--pm-color-syntax-keyword)' },
|
|
37
|
+
{ tag: [tags.string, tags.special(tags.string), tags.regexp], color: 'var(--pm-color-syntax-string)' },
|
|
38
|
+
{ tag: [tags.function(tags.variableName), tags.function(tags.propertyName), tags.definition(tags.variableName), tags.className, tags.typeName], color: 'var(--pm-color-syntax-key)' },
|
|
39
|
+
{ tag: [tags.number, tags.bool, tags.null, tags.atom], color: 'var(--pm-color-accent)' },
|
|
40
|
+
{ tag: [tags.comment, tags.lineComment, tags.blockComment], color: 'var(--pm-color-gutter)', fontStyle: 'italic' },
|
|
41
|
+
])
|
|
42
|
+
return { view, state, commands, language, style, extension, python: (ALIASES[id] ?? id) === 'python' }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function CodeEditor({ lang = '', label, value, onChange, onRun, onSave, onError, shouldFocus }: { lang?: string, label?: string, value: string, onChange?(value: string): void, onRun?(): void, onSave?(): void, onError?(error: unknown): void, shouldFocus?(): boolean }) {
|
|
46
|
+
const host = useRef<HTMLDivElement>(null)
|
|
47
|
+
const active = useRef<EditorView>()
|
|
48
|
+
const replacing = useRef(false)
|
|
49
|
+
const currentValue = useRef(value); currentValue.current = value
|
|
50
|
+
const callbacks = useRef({ onChange, onRun, onSave, onError, shouldFocus }); callbacks.current = { onChange, onRun, onSave, onError, shouldFocus }
|
|
51
|
+
useEffect(() => {
|
|
52
|
+
let editor: EditorView | undefined; let disposed = false
|
|
53
|
+
void editorModules(lang).then(({ view, state, commands, language, style, extension, python }) => {
|
|
54
|
+
if (disposed || !host.current) return
|
|
55
|
+
editor = new view.EditorView({ parent: host.current, state: state.EditorState.create({ doc: currentValue.current, extensions: [commands.history(), view.EditorView.contentAttributes.of(label ? { 'aria-label': label, 'aria-multiline': 'true', role: 'textbox' } : {}), view.keymap.of([{ key: 'Mod-Enter', run: () => { if (!callbacks.current.onRun) return false; callbacks.current.onRun(); return true } }, { key: 'Mod-s', run: () => { if (!callbacks.current.onSave) return false; callbacks.current.onSave(); return true } }, ...commands.defaultKeymap, ...commands.historyKeymap, commands.indentWithTab]), language.indentUnit.of(python ? ' ' : ' '), language.syntaxHighlighting(style), extension, view.EditorView.updateListener.of(update => { if (update.docChanged && !replacing.current) callbacks.current.onChange?.(update.state.doc.toString()) })] }) })
|
|
56
|
+
active.current = editor
|
|
57
|
+
if (callbacks.current.shouldFocus?.() !== false) editor.focus()
|
|
58
|
+
}).catch(error => {
|
|
59
|
+
if (disposed) return
|
|
60
|
+
console.error('[presmium] the code editor failed to initialize', error)
|
|
61
|
+
callbacks.current.onError?.(error)
|
|
62
|
+
})
|
|
63
|
+
return () => { disposed = true; if (active.current === editor) active.current = undefined; editor?.destroy() }
|
|
64
|
+
}, [lang, label])
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
const editor = active.current
|
|
67
|
+
if (!editor || editor.state.doc.toString() === value) return
|
|
68
|
+
replacing.current = true
|
|
69
|
+
try { editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: value } }) }
|
|
70
|
+
finally { replacing.current = false }
|
|
71
|
+
}, [value])
|
|
72
|
+
return h('div', { ref: host, className: 'pm-code-editor' })
|
|
73
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { useAppearance, usePrefersReducedMotion } from '@lincyaw/host'
|
|
2
|
+
import { ShikiMagicMove } from '@shikijs/magic-move/react'
|
|
3
|
+
import '@shikijs/magic-move/style.css'
|
|
4
|
+
import { useEffect, useState } from 'react'
|
|
5
|
+
import type { Element, ElementContent, Root } from 'hast'
|
|
6
|
+
import { toHtml } from 'hast-util-to-html'
|
|
7
|
+
import { codeColumns } from '../../domain/index.ts'
|
|
8
|
+
import { highlighterFor, SHIKI_THEMES } from './highlight.ts'
|
|
9
|
+
import { h } from '../element.ts'
|
|
10
|
+
type Loaded = Awaited<ReturnType<typeof highlighterFor>>
|
|
11
|
+
function useHighlighter(lang: string) { const [loaded, setLoaded] = useState<Loaded>(); useEffect(() => { let active = true; void highlighterFor(lang).then(value => { if (active) setLoaded(value) }).catch(() => {}); return () => { active = false } }, [lang]); return loaded }
|
|
12
|
+
function lineElements(tree: Root): Element[] { const pre = tree.children.find((node): node is Element => node.type === 'element'); const code = pre?.children.find((node): node is Element => node.type === 'element' && node.tagName === 'code'); return (code?.children ?? []).filter((node: ElementContent): node is Element => node.type === 'element') }
|
|
13
|
+
export function CodeView({ lang = '', value, highlight }: { lang?: string, value: string, highlight?: number[] }) {
|
|
14
|
+
const shiki = useHighlighter(lang); const code = value.replace(/\n$/, ''); const lines = new Set(highlight ?? [])
|
|
15
|
+
let html: string | undefined
|
|
16
|
+
if (shiki) { const tree = shiki.highlighter.codeToHast(code, { lang: shiki.lang, themes: SHIKI_THEMES, defaultColor: false }); lineElements(tree).forEach((line, i) => line.properties.class = lines.has(i + 1) ? 'line highlighted' : 'line'); html = toHtml(tree) }
|
|
17
|
+
const attrs = { className: `pm-code${lines.size ? ' pm-code--highlight' : ''}`, style: { '--pm-code-columns': codeColumns(code) }, 'data-lang': lang || undefined }
|
|
18
|
+
if (html) return h('div', { ...attrs, innerHTML: html })
|
|
19
|
+
const rows = code.split('\n').flatMap((text, i) => [h('span', { key: i, className: `line${lines.has(i + 1) ? ' highlighted' : ''}` }, text), '\n'])
|
|
20
|
+
return h('div', attrs, h('pre', { className: 'shiki' }, h('code', {}, rows.slice(0, -1))))
|
|
21
|
+
}
|
|
22
|
+
export function VariantView({ lang = '', value }: { lang?: string, value: string }) { const loaded = useHighlighter(lang); const reduced = usePrefersReducedMotion(); const { dark } = useAppearance(); if (!loaded || reduced) return h(CodeView, { lang, value }); const code = value.replace(/\n$/, ''); return h('div', { className: 'pm-code pm-code--magic-move', style: { '--pm-code-columns': codeColumns(code) }, 'data-lang': lang || undefined }, h(ShikiMagicMove, { highlighter: loaded.highlighter, lang: loaded.lang, theme: dark ? SHIKI_THEMES.dark : SHIKI_THEMES.light, code })) }
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { languageId } from '@lincyaw/kernel'
|
|
2
|
+
import type { HighlighterCore } from 'shiki/core'
|
|
3
|
+
|
|
4
|
+
type Loader = () => Promise<unknown>
|
|
5
|
+
|
|
6
|
+
const GRAMMARS: Record<string, Loader> = import.meta.env.SSR ? {} : {
|
|
7
|
+
python: () => import('shiki/langs/python.mjs'),
|
|
8
|
+
javascript: () => import('shiki/langs/javascript.mjs'),
|
|
9
|
+
typescript: () => import('shiki/langs/typescript.mjs'),
|
|
10
|
+
jsx: () => import('shiki/langs/jsx.mjs'),
|
|
11
|
+
tsx: () => import('shiki/langs/tsx.mjs'),
|
|
12
|
+
json: () => import('shiki/langs/json.mjs'),
|
|
13
|
+
shellscript: () => import('shiki/langs/shellscript.mjs'),
|
|
14
|
+
yaml: () => import('shiki/langs/yaml.mjs'),
|
|
15
|
+
toml: () => import('shiki/langs/toml.mjs'),
|
|
16
|
+
html: () => import('shiki/langs/html.mjs'),
|
|
17
|
+
css: () => import('shiki/langs/css.mjs'),
|
|
18
|
+
vue: () => import('shiki/langs/vue.mjs'),
|
|
19
|
+
markdown: () => import('shiki/langs/markdown.mjs'),
|
|
20
|
+
sql: () => import('shiki/langs/sql.mjs'),
|
|
21
|
+
diff: () => import('shiki/langs/diff.mjs'),
|
|
22
|
+
c: () => import('shiki/langs/c.mjs'),
|
|
23
|
+
cpp: () => import('shiki/langs/cpp.mjs'),
|
|
24
|
+
rust: () => import('shiki/langs/rust.mjs'),
|
|
25
|
+
go: () => import('shiki/langs/go.mjs'),
|
|
26
|
+
java: () => import('shiki/langs/java.mjs'),
|
|
27
|
+
wgsl: () => import('shiki/langs/wgsl.mjs'),
|
|
28
|
+
ruby: () => import('shiki/langs/ruby.mjs'),
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const ALIASES: Record<string, string> = {
|
|
32
|
+
mts: 'typescript',
|
|
33
|
+
sh: 'shellscript',
|
|
34
|
+
bash: 'shellscript',
|
|
35
|
+
shell: 'shellscript',
|
|
36
|
+
zsh: 'shellscript',
|
|
37
|
+
yml: 'yaml',
|
|
38
|
+
md: 'markdown',
|
|
39
|
+
'c++': 'cpp',
|
|
40
|
+
rs: 'rust',
|
|
41
|
+
rb: 'ruby',
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const SHIKI_THEMES = { light: 'github-light', dark: 'github-dark' } as const
|
|
45
|
+
|
|
46
|
+
let highlighter: Promise<HighlighterCore> | undefined
|
|
47
|
+
const loading = new Map<string, Promise<void>>()
|
|
48
|
+
|
|
49
|
+
function load(): Promise<HighlighterCore> {
|
|
50
|
+
if (import.meta.env.SSR) return new Promise(() => {})
|
|
51
|
+
highlighter ??= Promise.all([import('shiki/core'), import('shiki/engine/javascript')]).then(([core, engine]) =>
|
|
52
|
+
core.createHighlighterCore({
|
|
53
|
+
themes: [import('shiki/themes/github-light.mjs'), import('shiki/themes/github-dark.mjs')],
|
|
54
|
+
langs: [],
|
|
55
|
+
engine: engine.createJavaScriptRegexEngine({ forgiving: true }),
|
|
56
|
+
}))
|
|
57
|
+
return highlighter
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function grammarOf(lang: string): string | undefined {
|
|
61
|
+
const id = languageId(lang)
|
|
62
|
+
const name = ALIASES[id] ?? id
|
|
63
|
+
return name in GRAMMARS ? name : undefined
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function highlighterFor(lang: string): Promise<{ highlighter: HighlighterCore, lang: string } | undefined> {
|
|
67
|
+
const name = grammarOf(lang)
|
|
68
|
+
if (!name) return undefined
|
|
69
|
+
const core = await load()
|
|
70
|
+
if (!loading.has(name)) loading.set(name, core.loadLanguage(GRAMMARS[name]!() as never))
|
|
71
|
+
await loading.get(name)
|
|
72
|
+
return { highlighter: core, lang: name }
|
|
73
|
+
}
|