@riebeckite/plugin-code-tabs 0.0.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 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 Rerurate_514
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 ADDED
@@ -0,0 +1,97 @@
1
+ # @riebeckite/plugin-code-tabs
2
+
3
+ Groups adjacent code blocks with `tab="..."` metadata into an accessible tab UI.
4
+
5
+ [日本語](./README_ja.md)
6
+
7
+ ## Installation
8
+
9
+ ```ts
10
+ import { defineConfig } from "@riebeckite/core";
11
+ import { codeTabs } from "@riebeckite/plugin-code-tabs";
12
+
13
+ export default defineConfig({
14
+ // ...
15
+ plugins: [codeTabs()],
16
+ });
17
+ ```
18
+
19
+ The plugin registers its own `style.css` and client entry (`initCodeTabs`).
20
+
21
+ ## Config
22
+
23
+ ```ts
24
+ codeTabs({
25
+ syncTabs: false,
26
+ });
27
+ ```
28
+
29
+ | Option | Type | Default | Description |
30
+ | ------ | ---- | ------- | ----------- |
31
+ | `syncTabs` | `boolean` | `false` | When enabled, selecting a label such as `TypeScript` also selects the same label in other code-tab groups on the page. |
32
+
33
+ ## Syntax
34
+
35
+ ````md
36
+ ```dart tab="Flutter"
37
+ void main() {}
38
+ ```
39
+
40
+ ```ts tab="React"
41
+ console.log("Hello");
42
+ ```
43
+ ````
44
+
45
+ Regular code blocks without `tab="..."` are not changed.
46
+
47
+ ## Grouping rules
48
+
49
+ Adjacent `tab="..."` code blocks become one group. Any other content ends the
50
+ current group.
51
+
52
+ ````md
53
+ ```dart tab="Dart"
54
+ ```
55
+ ```ts tab="TypeScript"
56
+ ```
57
+ ````
58
+
59
+ The two blocks above are one group.
60
+
61
+ ````md
62
+ ```dart tab="Dart"
63
+ ```
64
+
65
+ Text between blocks.
66
+
67
+ ```ts tab="TypeScript"
68
+ ```
69
+ ````
70
+
71
+ The paragraph separates them into different groups.
72
+
73
+ ## Using with code-enhance
74
+
75
+ `@riebeckite/plugin-code-tabs` does not import or depend on
76
+ `@riebeckite/plugin-code-enhance`. It detects both normal `<pre><code>` blocks
77
+ and enhanced `rehype-pretty-code` figures, then wraps the whole rendered code
78
+ block as a panel. Syntax highlighting, filename headers, copy buttons, wrap,
79
+ collapse, line numbers, and diff/highlight markup are preserved as much as
80
+ possible.
81
+
82
+ Place `codeTabs()` after `codeEnhance()` if both plugins are enabled so tabs wrap
83
+ the enhanced code block output.
84
+
85
+ ## Accessibility
86
+
87
+ The generated HTML uses `role="tablist"`, `role="tab"`, and `role="tabpanel"`.
88
+ The client supports click, `ArrowLeft`, `ArrowRight`, `Home`, `End`, `Enter`, and
89
+ `Space`, and keeps `aria-selected` and `tabindex` in sync. Without JavaScript,
90
+ all panels remain visible so every code block can still be read.
91
+
92
+ ## Exports
93
+
94
+ - `codeTabs(options?)` — plugin factory
95
+ - `rehypeCodeTabs(options?)` — rehype transform
96
+ - `initCodeTabs(options?)` — client initializer
97
+ - Types: `CodeTabsOptions`, `CodeTabsClientOptions`
package/README_ja.md ADDED
@@ -0,0 +1,55 @@
1
+ # @riebeckite/plugin-code-tabs
2
+
3
+ 連続するコードブロックを、`tab="..."` の名前ごとにタブへまとめるプラグインです。
4
+
5
+ [English](./README.md)
6
+
7
+ ## 設定
8
+
9
+ ```ts
10
+ import { defineConfig } from "@riebeckite/core";
11
+ import { codeTabs } from "@riebeckite/plugin-code-tabs";
12
+
13
+ export default defineConfig({
14
+ // ...
15
+ plugins: [codeTabs()],
16
+ });
17
+ ```
18
+
19
+ スタイルと `initCodeTabs` はプラグイン自身が登録します。
20
+
21
+ ## コードブロックにタブ名を付ける
22
+
23
+ ````md
24
+ ```dart tab="Flutter"
25
+ void main() {}
26
+ ```
27
+
28
+ ```ts tab="React"
29
+ console.log("Hello");
30
+ ```
31
+ ````
32
+
33
+ `tab` を持つコードブロックが連続している間だけ、一つのタブグループになります。段落、見出し、画像などが間に入ると別のグループです。`tab` のないコードブロックは変更しません。
34
+
35
+ ## オプションとアクセシビリティ
36
+
37
+ | オプション | 既定値 | 内容 |
38
+ | --- | --- | --- |
39
+ | `syncTabs` | `false` | あるタブを選ぶと、同じページの同名タブも切り替えるか |
40
+
41
+ 生成する要素には `tablist`、`tab`、`tabpanel` のロールを設定します。矢印キー、`Home`、`End`、`Enter`、`Space` で操作でき、JavaScript が動かない場合は全パネルをそのまま読めます。
42
+
43
+ `@riebeckite/plugin-code-enhance` と併用する場合は、強調表示後の出力をまとめられるよう `codeEnhance()` の後に `codeTabs()` を置いてください。
44
+
45
+ ## 公開 API
46
+
47
+ - `codeTabs(options?)` — プラグインファクトリ
48
+ - `rehypeCodeTabs(options?)` — Rehype 変換
49
+ - `initCodeTabs(options?)` — ブラウザ初期化関数
50
+ - `CodeTabsOptions`、`CodeTabsClientOptions` — 型
51
+
52
+ ## 関連資料
53
+
54
+ - [プラグインシステム](../../../docs/ja/plugin-system.md)
55
+ - [`@riebeckite/plugin-code-enhance`](../code-enhance/README_ja.md)
@@ -0,0 +1,2 @@
1
+ export { initCodeTabs } from "./src/init.js";
2
+ export type { CodeTabsClientOptions } from "./src/types.js";
package/dist/client.js ADDED
@@ -0,0 +1,84 @@
1
+ // src/init.ts
2
+ var SELECTOR = "[data-code-tabs='true']";
3
+ var TAB_SELECTOR = "[data-code-tabs-tab='true']";
4
+ var PANEL_SELECTOR = "[data-code-tabs-panel='true']";
5
+ function initCodeTabs(options = {}) {
6
+ const groups = getGroups();
7
+ for (const group of groups) initializeGroup(group, options);
8
+ }
9
+ function initializeGroup(group, options) {
10
+ const tabs = getTabs(group);
11
+ const panels = getPanels(group);
12
+ if (tabs.length === 0 || panels.length === 0) return;
13
+ const initialIndex = tabs.findIndex(
14
+ (tab) => tab.getAttribute("aria-selected") === "true"
15
+ );
16
+ activateTab(group, Math.max(initialIndex, 0), { focus: false, sync: false });
17
+ for (const [index, tab] of tabs.entries()) {
18
+ tab.addEventListener("click", () => {
19
+ activateTab(group, index, {
20
+ focus: true,
21
+ sync: options.syncTabs === true
22
+ });
23
+ });
24
+ tab.addEventListener("keydown", (event) => {
25
+ const nextIndex = getKeyboardTargetIndex(event, index, tabs.length);
26
+ if (nextIndex === null) return;
27
+ event.preventDefault();
28
+ activateTab(group, nextIndex, {
29
+ focus: true,
30
+ sync: options.syncTabs === true
31
+ });
32
+ });
33
+ }
34
+ }
35
+ function activateTab(group, index, behavior) {
36
+ const tabs = getTabs(group);
37
+ const panels = getPanels(group);
38
+ const selectedTab = tabs[index];
39
+ if (!selectedTab) return;
40
+ for (const [tabIndex, tab] of tabs.entries()) {
41
+ const selected = tabIndex === index;
42
+ tab.setAttribute("aria-selected", selected ? "true" : "false");
43
+ tab.tabIndex = selected ? 0 : -1;
44
+ }
45
+ for (const [panelIndex, panel] of panels.entries()) {
46
+ const selected = panelIndex === index;
47
+ panel.dataset.active = selected ? "true" : "false";
48
+ panel.hidden = !selected;
49
+ }
50
+ if (behavior.focus) selectedTab.focus();
51
+ if (!behavior.sync || group.dataset.codeTabsSync !== "true") return;
52
+ const label = selectedTab.dataset.codeTabsLabel;
53
+ if (!label) return;
54
+ for (const otherGroup of getGroups()) {
55
+ if (otherGroup === group || otherGroup.dataset.codeTabsSync !== "true")
56
+ continue;
57
+ const otherIndex = getTabs(otherGroup).findIndex(
58
+ (tab) => tab.dataset.codeTabsLabel === label
59
+ );
60
+ if (otherIndex >= 0) {
61
+ activateTab(otherGroup, otherIndex, { focus: false, sync: false });
62
+ }
63
+ }
64
+ }
65
+ function getKeyboardTargetIndex(event, currentIndex, total) {
66
+ if (event.key === "ArrowLeft") return (currentIndex + total - 1) % total;
67
+ if (event.key === "ArrowRight") return (currentIndex + 1) % total;
68
+ if (event.key === "Home") return 0;
69
+ if (event.key === "End") return total - 1;
70
+ if (event.key === "Enter" || event.key === " ") return currentIndex;
71
+ return null;
72
+ }
73
+ function getGroups() {
74
+ return Array.from(document.querySelectorAll(SELECTOR));
75
+ }
76
+ function getTabs(group) {
77
+ return Array.from(group.querySelectorAll(TAB_SELECTOR));
78
+ }
79
+ function getPanels(group) {
80
+ return Array.from(group.querySelectorAll(PANEL_SELECTOR));
81
+ }
82
+ export {
83
+ initCodeTabs
84
+ };
@@ -0,0 +1,6 @@
1
+ import type { CodeTabsOptions } from "./src/types.js";
2
+ export { initCodeTabs } from "./src/init.js";
3
+ export { rehypeCodeTabs } from "./src/rehype.js";
4
+ export { remarkCodeMeta } from "./src/remark.js";
5
+ export type { CodeTabsClientOptions, CodeTabsOptions } from "./src/types.js";
6
+ export declare function codeTabs(options?: CodeTabsOptions): import("@riebeckite/core").RiebeckitePlugin<CodeTabsOptions>;
package/dist/index.js ADDED
@@ -0,0 +1,320 @@
1
+ // index.ts
2
+ import {
3
+ createClientEntry,
4
+ createStyleAsset,
5
+ definePlugin
6
+ } from "@riebeckite/core";
7
+
8
+ // src/hast.ts
9
+ function element(tagName, properties = {}, children = []) {
10
+ return { type: "element", tagName, properties, children };
11
+ }
12
+ function text(value) {
13
+ return { type: "text", value };
14
+ }
15
+ function isElementNode(node) {
16
+ return node.type === "element";
17
+ }
18
+ function getStringProperty(node, key) {
19
+ const value = getProperty(node, key);
20
+ if (typeof value === "string") return value;
21
+ if (Array.isArray(value)) return value.join(" ");
22
+ return null;
23
+ }
24
+ function getBooleanProperty(node, key) {
25
+ const value = getProperty(node, key);
26
+ return value === true || value === "true" || value === "";
27
+ }
28
+ function getProperty(node, key) {
29
+ const value = node.properties?.[key];
30
+ if (value !== void 0) return value;
31
+ const hyphenated = key.replace(
32
+ /[A-Z]/g,
33
+ (match) => `-${match.toLowerCase()}`
34
+ );
35
+ if (hyphenated !== key) return node.properties?.[hyphenated];
36
+ return void 0;
37
+ }
38
+ function mergeClassName(current, next) {
39
+ const currentClass = Array.isArray(current) ? current.join(" ") : typeof current === "string" ? current : "";
40
+ return currentClass ? `${currentClass} ${next}` : next;
41
+ }
42
+
43
+ // src/rehype.ts
44
+ function rehypeCodeTabs(options = {}) {
45
+ let groupIndex = 0;
46
+ return (tree) => {
47
+ transformChildren(tree, options, () => {
48
+ groupIndex += 1;
49
+ return `rr-code-tabs-${groupIndex}`;
50
+ });
51
+ };
52
+ }
53
+ function transformChildren(node, options, nextGroupId) {
54
+ if (!hasChildren(node)) return;
55
+ const nextChildren = [];
56
+ let group = [];
57
+ const flushGroup = () => {
58
+ if (group.length === 0) return;
59
+ nextChildren.push(buildTabGroup(group, options, nextGroupId()));
60
+ group = [];
61
+ };
62
+ for (const child of node.children) {
63
+ if (isElementNode(child)) {
64
+ const tabBlock = getTabBlock(child);
65
+ if (tabBlock) {
66
+ group.push(tabBlock);
67
+ continue;
68
+ }
69
+ transformChildren(child, options, nextGroupId);
70
+ }
71
+ if (isWhitespaceOnlyText(child) && group.length > 0) continue;
72
+ flushGroup();
73
+ nextChildren.push(child);
74
+ }
75
+ flushGroup();
76
+ node.children = nextChildren;
77
+ }
78
+ function isWhitespaceOnlyText(node) {
79
+ return node.type === "text" && typeof node.value === "string" && node.value.trim().length === 0;
80
+ }
81
+ function buildTabGroup(group, options, groupId) {
82
+ return element(
83
+ "div",
84
+ {
85
+ className: "rr-code-tabs",
86
+ dataCodeTabs: "true",
87
+ dataCodeTabsSync: options.syncTabs ? "true" : void 0
88
+ },
89
+ [
90
+ element(
91
+ "div",
92
+ { className: "rr-code-tabs__tablist", role: "tablist" },
93
+ group.map(
94
+ (tab, index) => element(
95
+ "button",
96
+ {
97
+ type: "button",
98
+ className: "rr-code-tabs__tab",
99
+ role: "tab",
100
+ id: `${groupId}-tab-${index}`,
101
+ ariaControls: `${groupId}-panel-${index}`,
102
+ ariaSelected: index === 0 ? "true" : "false",
103
+ tabindex: index === 0 ? "0" : "-1",
104
+ dataCodeTabsTab: "true",
105
+ dataCodeTabsLabel: tab.label
106
+ },
107
+ [text(tab.label)]
108
+ )
109
+ )
110
+ ),
111
+ ...group.map(
112
+ (tab, index) => element(
113
+ "div",
114
+ {
115
+ className: "rr-code-tabs__panel",
116
+ role: "tabpanel",
117
+ id: `${groupId}-panel-${index}`,
118
+ ariaLabelledBy: `${groupId}-tab-${index}`,
119
+ dataCodeTabsPanel: "true",
120
+ dataCodeTabsLabel: tab.label,
121
+ dataActive: index === 0 ? "true" : "false"
122
+ },
123
+ [tab.node]
124
+ )
125
+ )
126
+ ]
127
+ );
128
+ }
129
+ function getTabBlock(node) {
130
+ if (!isCodeBlockRoot(node)) return null;
131
+ const metaOwner = findMetaOwner(node);
132
+ if (!metaOwner) return null;
133
+ const meta = getCodeMeta(metaOwner);
134
+ const label = meta ? parseTabLabel(meta) : null;
135
+ if (!label) return null;
136
+ removeTabMeta(metaOwner, meta);
137
+ node.properties = {
138
+ ...node.properties,
139
+ className: mergeClassName(node.properties?.className, "rr-code-tabs__code")
140
+ };
141
+ return { node, label };
142
+ }
143
+ function isCodeBlockRoot(node) {
144
+ if (node.tagName === "pre") return Boolean(findDirectChild(node, "code"));
145
+ return node.tagName === "figure" && getBooleanProperty(node, "dataRehypePrettyCodeFigure");
146
+ }
147
+ function findMetaOwner(node) {
148
+ if (hasCodeMeta(node)) return node;
149
+ if (node.tagName === "pre") return findDirectChild(node, "code") ?? node;
150
+ const pre = findDescendant(node, (element2) => element2.tagName === "pre");
151
+ if (pre) return findDirectChild(pre, "code") ?? pre;
152
+ return node;
153
+ }
154
+ function hasCodeMeta(node) {
155
+ return getCodeMeta(node) !== null;
156
+ }
157
+ function getCodeMeta(node) {
158
+ const dataMeta = typeof node.data?.meta === "string" ? node.data.meta : null;
159
+ return dataMeta ?? getStringProperty(node, "meta") ?? getStringProperty(node, "dataMeta") ?? getStringProperty(node, "data-meta") ?? getStringProperty(node, "metastring");
160
+ }
161
+ function parseTabLabel(meta) {
162
+ const match = meta.match(/(?:^|\s)tab=("([^"]*)"|'([^']*)'|([^\s]+))/);
163
+ const label = match?.[2] ?? match?.[3] ?? match?.[4] ?? null;
164
+ const trimmed = label?.trim();
165
+ return trimmed ? trimmed : null;
166
+ }
167
+ function removeTabMeta(node, meta) {
168
+ const nextMeta = meta.replace(/(?:^|\s)tab=("[^"]*"|'[^']*'|[^\s]+)/, "").trim();
169
+ node.properties = { ...node.properties };
170
+ for (const key of ["meta", "dataMeta", "data-meta", "metastring"]) {
171
+ if (node.properties[key] === meta) {
172
+ if (nextMeta) node.properties[key] = nextMeta;
173
+ else delete node.properties[key];
174
+ }
175
+ }
176
+ if (node.data && node.data.meta === meta) {
177
+ if (nextMeta) node.data.meta = nextMeta;
178
+ else delete node.data.meta;
179
+ }
180
+ }
181
+ function findDescendant(node, predicate) {
182
+ for (const child of node.children ?? []) {
183
+ if (!isElementNode(child)) continue;
184
+ if (predicate(child)) return child;
185
+ const match = findDescendant(child, predicate);
186
+ if (match) return match;
187
+ }
188
+ return null;
189
+ }
190
+ function findDirectChild(node, tagName) {
191
+ return node.children?.find(
192
+ (child) => child.type === "element" && child.tagName === tagName
193
+ ) ?? null;
194
+ }
195
+ function hasChildren(node) {
196
+ return Array.isArray(node.children);
197
+ }
198
+
199
+ // src/remark.ts
200
+ function remarkCodeMeta() {
201
+ return (tree) => {
202
+ visitMdast(tree, (node) => {
203
+ if (node.type !== "code") return;
204
+ if (typeof node.meta !== "string" || node.meta.trim() === "") return;
205
+ node.data = {
206
+ ...node.data ?? {},
207
+ hProperties: {
208
+ ...node.data?.hProperties,
209
+ "data-meta": node.meta
210
+ }
211
+ };
212
+ });
213
+ };
214
+ }
215
+ function visitMdast(node, visitor) {
216
+ visitor(node);
217
+ for (const child of node.children ?? []) visitMdast(child, visitor);
218
+ }
219
+
220
+ // src/init.ts
221
+ var SELECTOR = "[data-code-tabs='true']";
222
+ var TAB_SELECTOR = "[data-code-tabs-tab='true']";
223
+ var PANEL_SELECTOR = "[data-code-tabs-panel='true']";
224
+ function initCodeTabs(options = {}) {
225
+ const groups = getGroups();
226
+ for (const group of groups) initializeGroup(group, options);
227
+ }
228
+ function initializeGroup(group, options) {
229
+ const tabs = getTabs(group);
230
+ const panels = getPanels(group);
231
+ if (tabs.length === 0 || panels.length === 0) return;
232
+ const initialIndex = tabs.findIndex(
233
+ (tab) => tab.getAttribute("aria-selected") === "true"
234
+ );
235
+ activateTab(group, Math.max(initialIndex, 0), { focus: false, sync: false });
236
+ for (const [index, tab] of tabs.entries()) {
237
+ tab.addEventListener("click", () => {
238
+ activateTab(group, index, {
239
+ focus: true,
240
+ sync: options.syncTabs === true
241
+ });
242
+ });
243
+ tab.addEventListener("keydown", (event) => {
244
+ const nextIndex = getKeyboardTargetIndex(event, index, tabs.length);
245
+ if (nextIndex === null) return;
246
+ event.preventDefault();
247
+ activateTab(group, nextIndex, {
248
+ focus: true,
249
+ sync: options.syncTabs === true
250
+ });
251
+ });
252
+ }
253
+ }
254
+ function activateTab(group, index, behavior) {
255
+ const tabs = getTabs(group);
256
+ const panels = getPanels(group);
257
+ const selectedTab = tabs[index];
258
+ if (!selectedTab) return;
259
+ for (const [tabIndex, tab] of tabs.entries()) {
260
+ const selected = tabIndex === index;
261
+ tab.setAttribute("aria-selected", selected ? "true" : "false");
262
+ tab.tabIndex = selected ? 0 : -1;
263
+ }
264
+ for (const [panelIndex, panel] of panels.entries()) {
265
+ const selected = panelIndex === index;
266
+ panel.dataset.active = selected ? "true" : "false";
267
+ panel.hidden = !selected;
268
+ }
269
+ if (behavior.focus) selectedTab.focus();
270
+ if (!behavior.sync || group.dataset.codeTabsSync !== "true") return;
271
+ const label = selectedTab.dataset.codeTabsLabel;
272
+ if (!label) return;
273
+ for (const otherGroup of getGroups()) {
274
+ if (otherGroup === group || otherGroup.dataset.codeTabsSync !== "true")
275
+ continue;
276
+ const otherIndex = getTabs(otherGroup).findIndex(
277
+ (tab) => tab.dataset.codeTabsLabel === label
278
+ );
279
+ if (otherIndex >= 0) {
280
+ activateTab(otherGroup, otherIndex, { focus: false, sync: false });
281
+ }
282
+ }
283
+ }
284
+ function getKeyboardTargetIndex(event, currentIndex, total) {
285
+ if (event.key === "ArrowLeft") return (currentIndex + total - 1) % total;
286
+ if (event.key === "ArrowRight") return (currentIndex + 1) % total;
287
+ if (event.key === "Home") return 0;
288
+ if (event.key === "End") return total - 1;
289
+ if (event.key === "Enter" || event.key === " ") return currentIndex;
290
+ return null;
291
+ }
292
+ function getGroups() {
293
+ return Array.from(document.querySelectorAll(SELECTOR));
294
+ }
295
+ function getTabs(group) {
296
+ return Array.from(group.querySelectorAll(TAB_SELECTOR));
297
+ }
298
+ function getPanels(group) {
299
+ return Array.from(group.querySelectorAll(PANEL_SELECTOR));
300
+ }
301
+
302
+ // index.ts
303
+ function codeTabs(options = {}) {
304
+ return definePlugin({
305
+ name: "code-tabs",
306
+ options,
307
+ remarkPlugins: [remarkCodeMeta],
308
+ extendHtmlPipeline: (pipeline) => {
309
+ pipeline.use(rehypeCodeTabs, options);
310
+ },
311
+ assets: [createStyleAsset("code-tabs")],
312
+ clientEntries: [createClientEntry("code-tabs", "initCodeTabs")]
313
+ });
314
+ }
315
+ export {
316
+ codeTabs,
317
+ initCodeTabs,
318
+ rehypeCodeTabs,
319
+ remarkCodeMeta
320
+ };
@@ -0,0 +1,7 @@
1
+ import type { ElementNode, HastNode, TextNode } from "./types.js";
2
+ export declare function element(tagName: string, properties?: Record<string, unknown>, children?: HastNode[]): ElementNode;
3
+ export declare function text(value: string): TextNode;
4
+ export declare function isElementNode(node: HastNode): node is ElementNode;
5
+ export declare function getStringProperty(node: ElementNode, key: string): string | null;
6
+ export declare function getBooleanProperty(node: ElementNode, key: string): boolean;
7
+ export declare function mergeClassName(current: unknown, next: string): string;
@@ -0,0 +1,2 @@
1
+ import type { CodeTabsClientOptions } from "./types.js";
2
+ export declare function initCodeTabs(options?: CodeTabsClientOptions): void;
@@ -0,0 +1,2 @@
1
+ import type { CodeTabsOptions, HastNode } from "./types.js";
2
+ export declare function rehypeCodeTabs(options?: CodeTabsOptions): (tree: HastNode) => void;
@@ -0,0 +1 @@
1
+ export declare function remarkCodeMeta(): (tree: unknown) => void;
@@ -0,0 +1,19 @@
1
+ export type CodeTabsOptions = {
2
+ syncTabs?: boolean;
3
+ };
4
+ export type CodeTabsClientOptions = CodeTabsOptions;
5
+ export type ElementNode = {
6
+ type: string;
7
+ tagName?: string;
8
+ properties?: Record<string, unknown>;
9
+ data?: Record<string, unknown>;
10
+ children?: HastNode[];
11
+ };
12
+ export type TextNode = {
13
+ type: "text";
14
+ value: string;
15
+ };
16
+ export type HastNode = ElementNode | TextNode | {
17
+ type: string;
18
+ [key: string]: unknown;
19
+ };
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@riebeckite/plugin-code-tabs",
3
+ "version": "0.0.1",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "./client": {
16
+ "types": "./dist/client.d.ts",
17
+ "import": "./dist/client.js",
18
+ "source": "./client.ts",
19
+ "default": "./dist/client.js"
20
+ },
21
+ "./style.css": "./style.css"
22
+ },
23
+ "dependencies": {
24
+ "@riebeckite/core": "0.0.1"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "LICENSE",
31
+ "README.md",
32
+ "README_ja.md",
33
+ "dist",
34
+ "style.css"
35
+ ],
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/Rerurate514/riebeckite.git",
39
+ "directory": "packages/plugins/code-tabs"
40
+ },
41
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
42
+ "bugs": {
43
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
44
+ },
45
+ "description": "Accessible tabbed code blocks for Riebeckite.",
46
+ "keywords": [
47
+ "riebeckite",
48
+ "plugin",
49
+ "code-blocks",
50
+ "tabs"
51
+ ],
52
+ "engines": {
53
+ "node": "^20.19.0 || >=22.12.0"
54
+ },
55
+ "sideEffects": [
56
+ "./style.css"
57
+ ],
58
+ "scripts": {
59
+ "build": "node ../../../scripts/build_package.mjs"
60
+ }
61
+ }
package/style.css ADDED
@@ -0,0 +1,84 @@
1
+ .rr-code-tabs {
2
+ margin-block: 1.5rem;
3
+ border: 1px solid
4
+ var(--rb-color-border, color-mix(in srgb, currentColor 16%, transparent));
5
+ background: var(--rb-color-surface, transparent);
6
+ }
7
+
8
+ .rr-code-tabs__tablist {
9
+ display: flex;
10
+ gap: 0.25rem;
11
+ overflow-x: auto;
12
+ padding: 0.5rem 0.5rem 0;
13
+ border-bottom: 1px solid
14
+ var(--rb-color-border, color-mix(in srgb, currentColor 16%, transparent));
15
+ scrollbar-width: thin;
16
+ }
17
+
18
+ .rr-code-tabs__tab {
19
+ appearance: none;
20
+ flex: 0 0 auto;
21
+ border: 1px solid transparent;
22
+ border-bottom: 0;
23
+ border-radius: 0.5rem 0.5rem 0 0;
24
+ padding: 0.5rem 0.75rem;
25
+ background: transparent;
26
+ color: var(--rb-color-muted, currentColor);
27
+ font: inherit;
28
+ font-size: 0.875em;
29
+ line-height: 1.3;
30
+ cursor: pointer;
31
+ }
32
+
33
+ .rr-code-tabs__tab:hover {
34
+ color: var(--rb-color-ink, currentColor);
35
+ background: var(
36
+ --rb-color-muted,
37
+ color-mix(in srgb, currentColor 6%, transparent)
38
+ );
39
+ }
40
+
41
+ .rr-code-tabs__tab:focus-visible {
42
+ outline: 2px solid var(--rb-color-accent, currentColor);
43
+ outline-offset: -2px;
44
+ }
45
+
46
+ .rr-code-tabs__tab[aria-selected="true"] {
47
+ border-color: var(
48
+ --rb-color-border,
49
+ color-mix(in srgb, currentColor 16%, transparent)
50
+ );
51
+ background: var(--rb-color-paper, Canvas);
52
+ color: var(--rb-color-ink, currentColor);
53
+ }
54
+
55
+ .rr-code-tabs__panel {
56
+ padding: 0;
57
+ }
58
+
59
+ .rr-code-tabs__panel > :first-child {
60
+ margin-top: 0;
61
+ }
62
+
63
+ .rr-code-tabs__panel > :last-child {
64
+ margin-bottom: 0;
65
+ }
66
+
67
+ .rr-code-tabs__panel[hidden] {
68
+ display: none;
69
+ }
70
+
71
+ .rr-code-tabs__code {
72
+ margin-block: 0;
73
+ }
74
+
75
+ @media (max-width: 640px) {
76
+ .rr-code-tabs {
77
+ margin-inline: calc(var(--rr-content-inline-padding, 0px) * -1);
78
+ border-inline: 0;
79
+ }
80
+
81
+ .rr-code-tabs__tab {
82
+ padding-inline: 0.625rem;
83
+ }
84
+ }