@lvl99dotcom/edaha-plugin-codehighlight 0.0.0-stage → 0.3.0

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Matt Scheurich]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,48 @@
1
- # Temporary Holding Version
1
+ # @lvl99dotcom/edaha-plugin-codehighlight
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An [edaha.md](https://github.com/lvl99/edaha.md#readme) embed plugin for code blocks with line numbers, syntax highlighting and a copy button. Several code blocks in one block become tabs. Pages with code load [Shiki](https://shiki.style) from jsDelivr to highlight it, in light or dark colours to match the page.
4
+
5
+ ```sh
6
+ npm add @lvl99dotcom/edaha-plugin-codehighlight --save-dev
7
+ yarn add @lvl99dotcom/edaha-plugin-codehighlight -D
8
+ pnpm add @lvl99dotcom/edaha-plugin-codehighlight -D
9
+ ```
10
+
11
+ ```yaml
12
+ # edahaconfig.yml
13
+ plugins:
14
+ - "@lvl99dotcom/edaha-plugin-codehighlight"
15
+ ```
16
+
17
+ <!-- prettier-ignore-start -->
18
+ ````md
19
+ <!-- embed:codehighlight -->
20
+ <!--yaml
21
+ lineNumbers: true
22
+ -->
23
+ ## ts-node
24
+
25
+ ```ts
26
+ const example = { treatPeople: "With kindness!" };
27
+ ```
28
+
29
+ ```js
30
+ const example = { treatPeople: "With kindness!" };
31
+ ```
32
+ <!-- /embed:codehighlight -->
33
+ ````
34
+ <!-- prettier-ignore-end -->
35
+
36
+ Each tab is labelled by the heading before its code block, else its language's name (e.g. `ts` is "TypeScript"), else "Code". Tabs work with a mouse, touch, and the keyboard (arrow keys, Home and End). Other Markdown in the block is left out.
37
+
38
+ | Option | What it does | Default |
39
+ | ----------------- | -------------------------------- | ------- |
40
+ | `lineNumbers` | Shows line numbers | `true` |
41
+ | `syntaxHighlight` | Highlights the code with Shiki | `true` |
42
+ | `copyButton` | Shows a copy to clipboard button | `true` |
43
+
44
+ Without JavaScript, the code blocks are shown one under another with their labels, without highlighting or copy buttons. Code in a language Shiki doesn't know is shown as it is.
45
+
46
+ Your layout template needs `{% embedHead %}` before `</head>` and `{% embedFoot %}` before `</body>` (the default theme has them). See [Embeds](https://lvl99.github.io/edaha.md/docs/07-embeds/) in the docs.
47
+
48
+ Licensed under the [Apache License 2.0](LICENSE).
@@ -0,0 +1,137 @@
1
+ /** The Shiki version pages load, from jsDelivr */
2
+ export declare const SHIKI_VERSION = "4.6.0";
3
+ /** Shiki's browser module, with its languages and themes loaded as they are needed */
4
+ export declare const SHIKI_URL = "https://cdn.jsdelivr.net/npm/shiki@4.6.0/+esm";
5
+ /** Shiki's themes for light and dark pages */
6
+ export declare const SHIKI_THEMES: {
7
+ light: string;
8
+ dark: string;
9
+ };
10
+ /** Languages' display names, by the names code blocks are marked with; others are shown as they are written */
11
+ export declare const LANGUAGE_NAMES: Readonly<Record<string, string>>;
12
+ /** The copy button's icons (markup): before copying, once copied, and when it couldn't copy */
13
+ export declare const COPY_ICONS: {
14
+ copy: string;
15
+ copied: string;
16
+ failed: string;
17
+ };
18
+ /** A code block in an embed block */
19
+ export interface CodeBlock {
20
+ /** Its language, as it is marked, e.g. "ts" (empty without one) */
21
+ language: string;
22
+ /** Its tab label: the heading before it, else its language's display name, else "Code" */
23
+ label: string;
24
+ /** Whether its label is from a heading */
25
+ headed: boolean;
26
+ /** Its code, without the last line break */
27
+ code: string;
28
+ }
29
+ /**
30
+ * The fenced code blocks in Markdown, each labelled by the heading before it (if it has one and no code block took
31
+ * it), else its language's display name (see LANGUAGE_NAMES), else "Code". Other Markdown is left out.
32
+ *
33
+ * @example
34
+ * codeBlocks("## Node\n\n```js\n1;\n```\n\n```ts\n2;\n```");
35
+ * // [{ language: "js", label: "Node", headed: true, code: "1;" }, { language: "ts", label: "TypeScript", headed: false, code: "2;" }]
36
+ */
37
+ export declare const codeBlocks: (content: string) => CodeBlock[];
38
+ /**
39
+ * A code block's HTML: its label (when it is in tabs or has a heading), and its lines (for line numbers), in a
40
+ * `<pre>` that can be scrolled with the keyboard, in a box the copy button floats in.
41
+ *
42
+ * @param id - its ID on the page
43
+ * @param labelled - whether to show its label
44
+ * @example
45
+ * codeBlockHtml({ language: "js", label: "JavaScript", headed: false, code: "1;" }, "codehighlight-1-1", false);
46
+ * // '<div class="codehighlight-block" id="codehighlight-1-1" data-language="js"><div class="codehighlight-code"><pre tabindex="0"><code class="language-js"><span class="line">1;</span></code></pre></div></div>'
47
+ */
48
+ export declare const codeBlockHtml: ({ language, label, code }: CodeBlock, id: string, labelled: boolean) => string;
49
+ /** What the page script uses from Shiki */
50
+ export interface Shiki {
51
+ codeToHtml(code: string, options: {
52
+ lang: string;
53
+ themes: typeof SHIKI_THEMES;
54
+ defaultColor: false;
55
+ }): Promise<string>;
56
+ }
57
+ /**
58
+ * Enhance a page's code blocks in the browser (run once per page by the page script, as its own source, so it uses
59
+ * nothing outside itself): blocks in a group with several become tabs (the WCAG tabs pattern: arrow keys, Home and
60
+ * End move between them), blocks get copy buttons (when the option is on), and their code is highlighted with Shiki
61
+ * (when the option is on), which is only loaded when a block needs it. Code Shiki can't highlight (e.g. an unknown
62
+ * language, or when it can't be loaded) is left as it is.
63
+ *
64
+ * @param doc - the page
65
+ * @param loadShiki - imports Shiki
66
+ * @param themes - Shiki's themes for light and dark pages
67
+ * @param icons - the copy button's icons
68
+ * @example
69
+ * await enhanceCodeBlocks(document, () => import(SHIKI_URL), SHIKI_THEMES, COPY_ICONS);
70
+ */
71
+ export declare const enhanceCodeBlocks: (doc: Document, loadShiki: () => Promise<Shiki>, themes: typeof SHIKI_THEMES, icons: typeof COPY_ICONS) => Promise<void>;
72
+ /**
73
+ * Shows code blocks with line numbers, syntax highlighting (Shiki, https://shiki.style, loaded in the visitor's
74
+ * browser) and a copy button. Several code blocks become tabs, labelled by the heading before each one, else its
75
+ * language, else "Code":
76
+ *
77
+ * ````
78
+ * <!-- embed:codehighlight -->
79
+ * ## ts-node
80
+ * ```ts
81
+ * const answer = 42;
82
+ * ```
83
+ * <!-- /embed:codehighlight -->
84
+ * ````
85
+ *
86
+ * Options: `lineNumbers`, `syntaxHighlight` and `copyButton` (all on by default). Without JavaScript, the code blocks
87
+ * are shown one under another with their labels, without highlighting or copy buttons.
88
+ *
89
+ * @example
90
+ * await codehighlight.build.render("```js\n1;\n```", context);
91
+ * // '<div class="codehighlight codehighlight-line-numbers" data-syntax-highlight data-copy-button><div class="codehighlight-block" ...'
92
+ */
93
+ export declare const codehighlight: {
94
+ key: string;
95
+ name: string;
96
+ description: string;
97
+ info: string;
98
+ sources: {
99
+ script: string[];
100
+ };
101
+ options: {
102
+ lineNumbers: {
103
+ title: string;
104
+ type: string;
105
+ $edahaField: {
106
+ checkbox: boolean;
107
+ defaultValue: boolean;
108
+ };
109
+ };
110
+ syntaxHighlight: {
111
+ title: string;
112
+ type: string;
113
+ $edahaField: {
114
+ checkbox: boolean;
115
+ defaultValue: boolean;
116
+ };
117
+ };
118
+ copyButton: {
119
+ title: string;
120
+ type: string;
121
+ $edahaField: {
122
+ checkbox: boolean;
123
+ defaultValue: boolean;
124
+ };
125
+ };
126
+ };
127
+ validate: (content: string) => true;
128
+ build: {
129
+ render: (content: string, { state, options }: import("@lvl99dotcom/edaha.md/embeds").EmbedRenderContext) => Promise<string>;
130
+ renderHead: () => Promise<string>;
131
+ renderFoot: () => Promise<string>;
132
+ };
133
+ editor: {
134
+ icon: string;
135
+ };
136
+ };
137
+ export default codehighlight;
package/dist/index.js ADDED
@@ -0,0 +1,367 @@
1
+ import { escapeHtml } from "@lvl99dotcom/edaha.md/generator/format";
2
+ import { createMarkdown } from "@lvl99dotcom/edaha.md/generator/markdown";
3
+ /** The Shiki version pages load, from jsDelivr */
4
+ export const SHIKI_VERSION = "4.6.0";
5
+ /** Shiki's browser module, with its languages and themes loaded as they are needed */
6
+ export const SHIKI_URL = `https://cdn.jsdelivr.net/npm/shiki@${SHIKI_VERSION}/+esm`;
7
+ /** Shiki's themes for light and dark pages */
8
+ export const SHIKI_THEMES = { light: "github-light", dark: "github-dark" };
9
+ /** Languages' display names, by the names code blocks are marked with; others are shown as they are written */
10
+ export const LANGUAGE_NAMES = {
11
+ bash: "Bash",
12
+ c: "C",
13
+ cpp: "C++",
14
+ cs: "C#",
15
+ csharp: "C#",
16
+ css: "CSS",
17
+ diff: "Diff",
18
+ go: "Go",
19
+ html: "HTML",
20
+ java: "Java",
21
+ javascript: "JavaScript",
22
+ js: "JavaScript",
23
+ json: "JSON",
24
+ jsx: "JSX",
25
+ kotlin: "Kotlin",
26
+ md: "Markdown",
27
+ markdown: "Markdown",
28
+ njk: "Nunjucks",
29
+ nunjucks: "Nunjucks",
30
+ php: "PHP",
31
+ py: "Python",
32
+ python: "Python",
33
+ rb: "Ruby",
34
+ ruby: "Ruby",
35
+ rs: "Rust",
36
+ rust: "Rust",
37
+ sass: "Sass",
38
+ scss: "SCSS",
39
+ sh: "Shell",
40
+ shell: "Shell",
41
+ sql: "SQL",
42
+ swift: "Swift",
43
+ text: "Text",
44
+ ts: "TypeScript",
45
+ tsx: "TSX",
46
+ typescript: "TypeScript",
47
+ xml: "XML",
48
+ yaml: "YAML",
49
+ yml: "YAML",
50
+ zsh: "Zsh",
51
+ };
52
+ /** The copy button's icons (markup): before copying, once copied, and when it couldn't copy */
53
+ export const COPY_ICONS = {
54
+ copy: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M360-240q-33 0-56.5-23.5T280-320v-480q0-33 23.5-56.5T360-880h360q33 0 56.5 23.5T800-800v480q0 33-23.5 56.5T720-240H360Zm0-80h360v-480H360v480ZM200-80q-33 0-56.5-23.5T120-160v-560h80v560h440v80H200Zm160-240v-480 480Z"/></svg>',
55
+ copied: '<span class="codehighlight-emoji" aria-hidden="true">✅</span>',
56
+ failed: '<span class="codehighlight-emoji" aria-hidden="true">🙅</span>',
57
+ };
58
+ /** Parses embed blocks' Markdown */
59
+ const markdown = createMarkdown();
60
+ /**
61
+ * The fenced code blocks in Markdown, each labelled by the heading before it (if it has one and no code block took
62
+ * it), else its language's display name (see LANGUAGE_NAMES), else "Code". Other Markdown is left out.
63
+ *
64
+ * @example
65
+ * codeBlocks("## Node\n\n```js\n1;\n```\n\n```ts\n2;\n```");
66
+ * // [{ language: "js", label: "Node", headed: true, code: "1;" }, { language: "ts", label: "TypeScript", headed: false, code: "2;" }]
67
+ */
68
+ export const codeBlocks = (content) => {
69
+ const tokens = markdown.parse(content, { baseUrl: "", siteBaseUrl: "" });
70
+ const blocks = [];
71
+ let heading;
72
+ tokens.forEach((token, i) => {
73
+ if (token.type === "heading_open")
74
+ heading = tokens[i + 1].content.trim() || undefined;
75
+ if (token.type !== "fence")
76
+ return;
77
+ const language = token.info.trim().split(/\s+/)[0];
78
+ blocks.push({
79
+ language,
80
+ label: heading ??
81
+ LANGUAGE_NAMES[language.toLowerCase()] ??
82
+ (language || "Code"),
83
+ headed: heading !== undefined,
84
+ code: token.content.replace(/\r?\n$/, ""),
85
+ });
86
+ heading = undefined;
87
+ });
88
+ return blocks;
89
+ };
90
+ /**
91
+ * A code block's HTML: its label (when it is in tabs or has a heading), and its lines (for line numbers), in a
92
+ * `<pre>` that can be scrolled with the keyboard, in a box the copy button floats in.
93
+ *
94
+ * @param id - its ID on the page
95
+ * @param labelled - whether to show its label
96
+ * @example
97
+ * codeBlockHtml({ language: "js", label: "JavaScript", headed: false, code: "1;" }, "codehighlight-1-1", false);
98
+ * // '<div class="codehighlight-block" id="codehighlight-1-1" data-language="js"><div class="codehighlight-code"><pre tabindex="0"><code class="language-js"><span class="line">1;</span></code></pre></div></div>'
99
+ */
100
+ export const codeBlockHtml = ({ language, label, code }, id, labelled) => {
101
+ const lines = code
102
+ .split(/\r?\n/)
103
+ .map((line) => `<span class="line">${escapeHtml(line)}</span>`)
104
+ .join("\n");
105
+ return [
106
+ `<div class="codehighlight-block" id="${id}"${language ? ` data-language="${escapeHtml(language)}"` : ""}>`,
107
+ labelled
108
+ ? `<p class="codehighlight-label" id="${id}-label">${escapeHtml(label)}</p>`
109
+ : "",
110
+ `<div class="codehighlight-code"><pre tabindex="0"${labelled ? ` aria-labelledby="${id}-label"` : ""}>`,
111
+ `<code${language ? ` class="language-${escapeHtml(language)}"` : ""}>${lines}</code></pre></div></div>`,
112
+ ].join("");
113
+ };
114
+ /**
115
+ * Enhance a page's code blocks in the browser (run once per page by the page script, as its own source, so it uses
116
+ * nothing outside itself): blocks in a group with several become tabs (the WCAG tabs pattern: arrow keys, Home and
117
+ * End move between them), blocks get copy buttons (when the option is on), and their code is highlighted with Shiki
118
+ * (when the option is on), which is only loaded when a block needs it. Code Shiki can't highlight (e.g. an unknown
119
+ * language, or when it can't be loaded) is left as it is.
120
+ *
121
+ * @param doc - the page
122
+ * @param loadShiki - imports Shiki
123
+ * @param themes - Shiki's themes for light and dark pages
124
+ * @param icons - the copy button's icons
125
+ * @example
126
+ * await enhanceCodeBlocks(document, () => import(SHIKI_URL), SHIKI_THEMES, COPY_ICONS);
127
+ */
128
+ export const enhanceCodeBlocks = async (doc, loadShiki, themes, icons) => {
129
+ for (const group of doc.querySelectorAll(".codehighlight[data-tabs]")) {
130
+ const blocks = [
131
+ ...group.querySelectorAll(":scope > .codehighlight-block"),
132
+ ];
133
+ const tabList = doc.createElement("div");
134
+ tabList.className = "codehighlight-tabs";
135
+ tabList.setAttribute("role", "tablist");
136
+ tabList.setAttribute("aria-label", "Code examples");
137
+ const tabs = blocks.map((block) => {
138
+ // Blocks in tabs always have labels
139
+ const label = block.querySelector(".codehighlight-label");
140
+ const tab = doc.createElement("button");
141
+ tab.type = "button";
142
+ tab.id = `${block.id}-tab`;
143
+ tab.className = "codehighlight-tab";
144
+ tab.textContent = label.textContent;
145
+ tab.setAttribute("role", "tab");
146
+ tab.setAttribute("aria-controls", block.id);
147
+ block.setAttribute("role", "tabpanel");
148
+ block.setAttribute("aria-labelledby", tab.id);
149
+ label.hidden = true;
150
+ tabList.append(tab);
151
+ return tab;
152
+ });
153
+ const select = (index, focus) => tabs.forEach((tab, i) => {
154
+ const selected = i === index;
155
+ tab.setAttribute("aria-selected", String(selected));
156
+ tab.tabIndex = selected ? 0 : -1;
157
+ blocks[i].hidden = !selected;
158
+ if (selected && focus)
159
+ tab.focus();
160
+ });
161
+ tabList.addEventListener("click", (event) => {
162
+ const index = tabs.indexOf(event.target.closest("button"));
163
+ if (index >= 0)
164
+ select(index, false);
165
+ });
166
+ tabList.addEventListener("keydown", (event) => {
167
+ const index = tabs.indexOf(doc.activeElement);
168
+ const keys = {
169
+ ArrowRight: index + 1,
170
+ ArrowLeft: index - 1,
171
+ Home: 0,
172
+ End: tabs.length - 1,
173
+ };
174
+ const next = keys[event.key];
175
+ if (next === undefined)
176
+ return;
177
+ event.preventDefault();
178
+ select((next + tabs.length) % tabs.length, true);
179
+ });
180
+ group.prepend(tabList);
181
+ select(0, false);
182
+ }
183
+ for (const block of doc.querySelectorAll(".codehighlight[data-copy-button] .codehighlight-block")) {
184
+ const button = doc.createElement("button");
185
+ button.type = "button";
186
+ button.className = "codehighlight-copy";
187
+ // An icon button, named for screen readers and by its tooltip
188
+ const show = (label, icon) => {
189
+ button.title = label;
190
+ button.innerHTML = `${icon}<span class="codehighlight-hidden">${label}</span>`;
191
+ };
192
+ show("Copy code", icons.copy);
193
+ const status = doc.createElement("span");
194
+ status.className = "codehighlight-hidden";
195
+ status.setAttribute("role", "status");
196
+ const view = doc.defaultView;
197
+ let reset;
198
+ button.addEventListener("click", async () => {
199
+ try {
200
+ await view.navigator.clipboard.writeText(String(block.querySelector("code").textContent));
201
+ show((status.textContent = "Copied"), icons.copied);
202
+ }
203
+ catch {
204
+ show((status.textContent = "Couldn't copy"), icons.failed);
205
+ }
206
+ // Ready to copy again after a moment
207
+ view.clearTimeout(reset);
208
+ reset = view.setTimeout(() => {
209
+ show("Copy code", icons.copy);
210
+ status.textContent = "";
211
+ }, 2000);
212
+ });
213
+ block.querySelector("pre").before(button, status);
214
+ }
215
+ const highlighted = [
216
+ ...doc.querySelectorAll(".codehighlight[data-syntax-highlight] .codehighlight-block[data-language]"),
217
+ ];
218
+ if (!highlighted.length)
219
+ return;
220
+ let shiki;
221
+ try {
222
+ shiki = await loadShiki();
223
+ }
224
+ catch {
225
+ return;
226
+ }
227
+ for (const block of highlighted) {
228
+ const pre = block.querySelector("pre");
229
+ try {
230
+ const template = doc.createElement("template");
231
+ template.innerHTML = await shiki.codeToHtml(String(pre.textContent), {
232
+ lang: block.dataset.language,
233
+ themes,
234
+ defaultColor: false,
235
+ });
236
+ const code = template.content.querySelector("code");
237
+ pre.classList.add("shiki");
238
+ pre.replaceChildren(code);
239
+ }
240
+ catch {
241
+ // Left as it is
242
+ }
243
+ }
244
+ };
245
+ /** Enhances the page's code blocks once it has loaded (see enhanceCodeBlocks) */
246
+ const START_SCRIPT = `<script type="module">
247
+ await (${enhanceCodeBlocks.toString()})(document, () => import("${SHIKI_URL}"), ${JSON.stringify(SHIKI_THEMES)}, ${JSON.stringify(COPY_ICONS)});
248
+ </script>`;
249
+ /**
250
+ * Line numbers (not copied with the code), tabs and copy buttons big enough to tap (the copy button floats in the
251
+ * code's top corner, and the code leaves room for it at the end of its lines), and Shiki's colours for the page's theme: its `data-theme` ("light" or "dark", as the default theme's switcher
252
+ * sets it), or else the visitor's setting.
253
+ */
254
+ const STYLE = `<style>
255
+ .embed-codehighlight { --codehighlight-copy-size: 2.25rem; --codehighlight-copy-inset: 0.5rem; }
256
+ .embed-codehighlight .codehighlight-block { margin: 0 0 1rem; }
257
+ .embed-codehighlight .codehighlight-label { margin: 0 0 0.25rem; font-weight: bold; }
258
+ .embed-codehighlight .codehighlight-code { position: relative; }
259
+ .embed-codehighlight pre { margin: 0; }
260
+ .embed-codehighlight .codehighlight-code:has(.codehighlight-copy) pre {
261
+ padding-inline-end: calc(var(--codehighlight-copy-size) + 2 * var(--codehighlight-copy-inset));
262
+ }
263
+ .embed-codehighlight pre code { display: block; padding: 0; background: none; color: inherit; font-size: inherit; }
264
+ .embed-codehighlight .codehighlight-line-numbers code { counter-reset: line; }
265
+ .embed-codehighlight .codehighlight-line-numbers .line::before {
266
+ counter-increment: line; content: counter(line); display: inline-block; width: 2.5em; margin-right: 1em;
267
+ text-align: right; color: var(--colour-muted, #5a5a60); user-select: none;
268
+ }
269
+ .embed-codehighlight .codehighlight-tabs { display: flex; flex-wrap: wrap; gap: 0.25rem; margin-bottom: 0.5rem; }
270
+ .embed-codehighlight button {
271
+ min-height: 2.75rem; min-width: 2.75rem; padding: 0.5rem 0.75rem; border: 1px solid var(--colour-border, #d8d8de);
272
+ background: var(--colour-background, #fff); color: inherit; font: inherit; cursor: pointer;
273
+ }
274
+ .embed-codehighlight button:focus-visible { outline: 2px solid var(--colour-focus, #db5a10); outline-offset: 2px; }
275
+ .embed-codehighlight .codehighlight-tab[aria-selected="true"] { border-color: currentColor; font-weight: bold; }
276
+ .embed-codehighlight .codehighlight-copy {
277
+ position: absolute; inset-block-start: var(--codehighlight-copy-inset); inset-inline-end: var(--codehighlight-copy-inset);
278
+ display: inline-flex; align-items: center; justify-content: center; box-sizing: border-box;
279
+ width: var(--codehighlight-copy-size); height: var(--codehighlight-copy-size); min-width: 0; min-height: 0;
280
+ padding: 0.25rem; background: var(--colour-surface, #f4f4f6);
281
+ border: 1px solid var(--colour-border, #d8d8de); border-radius: 5px; color: var(--colour-text, #1d1d1f);
282
+ }
283
+ .embed-codehighlight .codehighlight-copy:hover { border-color: var(--colour-muted, #5a5a60); }
284
+ .embed-codehighlight .codehighlight-copy svg { width: 1.5rem; height: 1.5rem; fill: currentColor; }
285
+ .embed-codehighlight .codehighlight-emoji { width: 1.5rem; font-size: 1.25rem; line-height: 1.5rem; text-align: center; }
286
+ .embed-codehighlight .codehighlight-hidden {
287
+ position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap;
288
+ }
289
+ .embed-codehighlight .shiki span { color: var(--shiki-light); }
290
+ @media (prefers-color-scheme: dark) {
291
+ :root:not([data-theme="light"]) .embed-codehighlight .shiki span { color: var(--shiki-dark); }
292
+ }
293
+ :root[data-theme="dark"] .embed-codehighlight .shiki span { color: var(--shiki-dark); }
294
+ </style>`;
295
+ /** Angle brackets, as the editor's icon */
296
+ const ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" aria-hidden="true"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>';
297
+ /**
298
+ * Shows code blocks with line numbers, syntax highlighting (Shiki, https://shiki.style, loaded in the visitor's
299
+ * browser) and a copy button. Several code blocks become tabs, labelled by the heading before each one, else its
300
+ * language, else "Code":
301
+ *
302
+ * ````
303
+ * <!-- embed:codehighlight -->
304
+ * ## ts-node
305
+ * ```ts
306
+ * const answer = 42;
307
+ * ```
308
+ * <!-- /embed:codehighlight -->
309
+ * ````
310
+ *
311
+ * Options: `lineNumbers`, `syntaxHighlight` and `copyButton` (all on by default). Without JavaScript, the code blocks
312
+ * are shown one under another with their labels, without highlighting or copy buttons.
313
+ *
314
+ * @example
315
+ * await codehighlight.build.render("```js\n1;\n```", context);
316
+ * // '<div class="codehighlight codehighlight-line-numbers" data-syntax-highlight data-copy-button><div class="codehighlight-block" ...'
317
+ */
318
+ export const codehighlight = {
319
+ key: "codehighlight",
320
+ name: "Code",
321
+ description: "Code blocks with line numbers, syntax highlighting and a copy button; several become tabs. Pages with code load Shiki from jsDelivr.",
322
+ info: "Fenced code blocks (```ts ... ```), each with an optional heading before it as its tab label",
323
+ sources: { script: ["https://cdn.jsdelivr.net"] },
324
+ options: {
325
+ lineNumbers: {
326
+ title: "Show line numbers",
327
+ type: "boolean",
328
+ $edahaField: { checkbox: true, defaultValue: true },
329
+ },
330
+ syntaxHighlight: {
331
+ title: "Highlight syntax",
332
+ type: "boolean",
333
+ $edahaField: { checkbox: true, defaultValue: true },
334
+ },
335
+ copyButton: {
336
+ title: "Show copy button",
337
+ type: "boolean",
338
+ $edahaField: { checkbox: true, defaultValue: true },
339
+ },
340
+ },
341
+ validate: (content) => {
342
+ if (!codeBlocks(content).length)
343
+ throw new Error("There are no fenced code blocks, e.g. ```ts ... ```");
344
+ return true;
345
+ },
346
+ build: {
347
+ render: async (content, { state, options }) => {
348
+ const group = (state.count ?? 0) + 1;
349
+ state.count = group;
350
+ const blocks = codeBlocks(content);
351
+ const tabbed = blocks.length > 1;
352
+ const attributes = [
353
+ options.lineNumbers === false ? "" : " codehighlight-line-numbers",
354
+ tabbed ? " data-tabs" : "",
355
+ options.syntaxHighlight === false ? "" : " data-syntax-highlight",
356
+ options.copyButton === false ? "" : " data-copy-button",
357
+ ];
358
+ return `<div class="codehighlight${attributes[0]}"${attributes.slice(1).join("")}>${blocks
359
+ .map((block, i) => codeBlockHtml(block, `codehighlight-${group}-${i + 1}`, tabbed || block.headed))
360
+ .join("")}</div>`;
361
+ },
362
+ renderHead: async () => STYLE,
363
+ renderFoot: async () => START_SCRIPT,
364
+ },
365
+ editor: { icon: ICON },
366
+ };
367
+ export default codehighlight;
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@lvl99dotcom/edaha-plugin-codehighlight",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Code blocks with line numbers, syntax highlighting, copy buttons and tabs in edaha.md sites.",
5
+ "keywords": [
6
+ "edaha.md",
7
+ "edaha-plugin",
8
+ "embed",
9
+ "syntax highlighting",
10
+ "shiki"
11
+ ],
12
+ "author": "Matt Scheurich <matt@lvl99.com>",
13
+ "license": "Apache-2.0",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/lvl99/edaha.md.git",
17
+ "directory": "packages/edaha-plugin-codehighlight"
18
+ },
19
+ "homepage": "https://github.com/lvl99/edaha.md#readme",
20
+ "bugs": "https://github.com/lvl99/edaha.md/issues",
21
+ "type": "module",
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "LICENSE"
36
+ ],
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "peerDependencies": {
41
+ "@lvl99dotcom/edaha.md": "^0.3.0"
42
+ },
43
+ "devDependencies": {
44
+ "@lvl99dotcom/edaha.md": "^0.3.0"
45
+ },
46
+ "scripts": {
47
+ "build": "node ../edaha/scripts/build-plugin.ts"
48
+ }
6
49
  }