@riebeckite/plugin-vega-lite 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,128 @@
1
+ # @riebeckite/plugin-vega-lite
2
+
3
+ Renders ` ```vega-lite ` code blocks as Vega-Lite charts. Charts are drawn in the
4
+ browser, and the Vega runtime is imported dynamically only when it is needed.
5
+
6
+ [Japanese](./README_ja.md)
7
+
8
+ ## Configure
9
+
10
+ ```ts
11
+ import { defineConfig } from "@riebeckite/core";
12
+ import { vegaLite } from "@riebeckite/plugin-vega-lite";
13
+
14
+ export default defineConfig({
15
+ // ...
16
+ plugins: [
17
+ vegaLite({
18
+ caption: true,
19
+ theme: "light",
20
+ renderer: "canvas",
21
+ }),
22
+ ],
23
+ });
24
+ ```
25
+
26
+ The plugin runs with `order: -10`.
27
+
28
+ ## Syntax
29
+
30
+ Put a Vega-Lite specification as JSON in the body of the code block. Both
31
+ `vega-lite` and `vega` are accepted.
32
+
33
+ ````markdown
34
+ ```vega-lite
35
+ {
36
+ "title": "Revenue",
37
+ "data": {
38
+ "values": [
39
+ { "category": "A", "value": 28 },
40
+ { "category": "B", "value": 55 }
41
+ ]
42
+ },
43
+ "mark": "bar",
44
+ "encoding": {
45
+ "x": { "field": "category", "type": "nominal" },
46
+ "y": { "field": "value", "type": "quantitative" }
47
+ }
48
+ }
49
+ ```
50
+ ````
51
+
52
+ The caption comes from the code-block `title`, or from the specification's
53
+ `title`.
54
+
55
+ ## How it renders
56
+
57
+ A ` ```vega-lite ` block becomes a `figure.rb-vega-lite`:
58
+
59
+ - `figure.rb-vega-lite`: carries `data-vega-lite="pending"` and
60
+ `data-vega-lite-spec` (the escaped JSON)
61
+ - `div.rb-vega-lite__canvas`: the element the chart is rendered into
62
+ (`role="img"`)
63
+ - `figcaption.rb-vega-lite__caption`: the caption (enabled by default)
64
+ - `details.rb-vega-lite__fallback`: the original spec, folded away
65
+
66
+ `initVegaLite` finds `[data-vega-lite]`, `JSON.parse`s `data-vega-lite-spec`,
67
+ then dynamically imports `vega`, `vega-lite`, and `vega-embed` and renders with
68
+ `vega-embed`. On success the figure becomes `data-vega-lite="rendered"`.
69
+
70
+ If loading `vega-embed`, parsing the spec, or embedding fails, the initializer
71
+ does not throw: it opens that figure's `details` and marks it
72
+ `data-vega-lite="error"`.
73
+
74
+ A block whose body is not valid JSON is left as a normal code block, and a
75
+ diagnostic with `source: "@riebeckite/plugin-vega-lite"` is emitted.
76
+
77
+ ## Options
78
+
79
+ | Option | Default | Description |
80
+ | --- | --- | --- |
81
+ | `caption` | `true` | Show the `title` as a caption |
82
+ | `actions` | `null` | Show the `vega-embed` actions menu (`true` / `false` / `null`) |
83
+ | `theme` | `"light"` | Colour scheme (`"light"`, `"dark"`, `"none"`) |
84
+ | `renderer` | `"canvas"` | Vega renderer (`"canvas"` or `"svg"`) |
85
+ | `className` | `"rb-vega-lite"` | Base class applied to the figure |
86
+
87
+ When `actions` is `null`, the `vega-embed` default (actions shown) applies. With
88
+ `theme` set to `"light"` or `"none"`, Vega's default light styling is used; only
89
+ `"dark"` applies the built-in `dark` theme.
90
+
91
+ ## Client rendering
92
+
93
+ The client initializer is static and receives no plugin options. `actions`,
94
+ `theme`, and `renderer` are embedded into the figure's `data-vega-lite-*`
95
+ attributes, and `initVegaLite` reads them from there.
96
+
97
+ The Vega runtime is loaded with `import()`, so the page still renders when
98
+ JavaScript is disabled and the spec stays readable in the fallback `details`.
99
+
100
+ ## Output hooks
101
+
102
+ - `figure[data-vega-lite]`: state (`pending` / `rendered` / `error`)
103
+ - `figure[data-vega-lite-spec]`: the escaped spec JSON
104
+ - `figure[data-vega-lite-theme]`, `figure[data-vega-lite-renderer]`,
105
+ `figure[data-vega-lite-actions]`
106
+ - `[data-vega-lite-canvas]`: the render target
107
+ - `details.rb-vega-lite__fallback`: the original spec
108
+
109
+ ## Main exports
110
+
111
+ - `vegaLite(options?)`: create the plugin (`vegaLitePlugin` is an alias)
112
+ - `initVegaLite`: initialize client-side rendering
113
+ - Types: `VegaLiteOptions`, `VegaLiteSpec`, `VegaLiteTheme`,
114
+ `VegaLiteRenderer`
115
+
116
+ ## Limitations
117
+
118
+ - Rendering is client-only. Nothing is rendered at build time, so charts are not
119
+ visible without JavaScript (the spec remains in the fallback `details`)
120
+ - Each chart loads `vega`, `vega-lite`, and `vega-embed`, so pages with many
121
+ charts pay for the transfer and render cost repeatedly
122
+ - Not every Vega-Lite feature is validated; complex specs surface as browser
123
+ errors and reveal the fallback
124
+ - `vega`, `vega-lite`, and `vega-embed` are BSD-3-Clause licensed
125
+
126
+ ## See also
127
+
128
+ - [Plugin system](../../../docs/en/plugin-system.md)
package/README_ja.md ADDED
@@ -0,0 +1,108 @@
1
+ # @riebeckite/plugin-vega-lite
2
+
3
+ ` ```vega-lite ` コードブロックを Vega-Lite のチャートとして表示するプラグインです。チャートはブラウザ側で描画し、Vega ランタイムは必要になったときだけ動的に読み込みます。
4
+
5
+ [English](./README.md)
6
+
7
+ ## 設定する
8
+
9
+ ```ts
10
+ import { defineConfig } from "@riebeckite/core";
11
+ import { vegaLite } from "@riebeckite/plugin-vega-lite";
12
+
13
+ export default defineConfig({
14
+ // ...
15
+ plugins: [
16
+ vegaLite({
17
+ caption: true,
18
+ theme: "light",
19
+ renderer: "canvas",
20
+ }),
21
+ ],
22
+ });
23
+ ```
24
+
25
+ このプラグインは `order: -10` で実行されます。
26
+
27
+ ## 記法
28
+
29
+ コードブロックの本文に Vega-Lite の仕様を JSON で書きます。`vega-lite` に加えて `vega` も受け付けます。
30
+
31
+ ````markdown
32
+ ```vega-lite
33
+ {
34
+ "title": "売上高",
35
+ "data": {
36
+ "values": [
37
+ { "category": "A", "value": 28 },
38
+ { "category": "B", "value": 55 }
39
+ ]
40
+ },
41
+ "mark": "bar",
42
+ "encoding": {
43
+ "x": { "field": "category", "type": "nominal" },
44
+ "y": { "field": "value", "type": "quantitative" }
45
+ }
46
+ }
47
+ ```
48
+ ````
49
+
50
+ キャプションにはコードブロックの `title`、なければ仕様の `title` を使います。
51
+
52
+ ## どのように描画されるか
53
+
54
+ ` ```vega-lite ` のコードブロックは `figure.rb-vega-lite` に置き換わります。
55
+
56
+ - `figure.rb-vega-lite`: `data-vega-lite="pending"` と `data-vega-lite-spec`(JSON をエスケープしたもの)を持ちます
57
+ - `div.rb-vega-lite__canvas`: チャートを描画する領域(`role="img"`)
58
+ - `figcaption.rb-vega-lite__caption`: キャプション(既定で有効)
59
+ - `details.rb-vega-lite__fallback`: 元の仕様を折りたたんで表示
60
+
61
+ `initVegaLite` は `[data-vega-lite]` を探し、`data-vega-lite-spec` を `JSON.parse` してから `vega`、`vega-lite`、`vega-embed` を動的インポートして `vega-embed` で描画します。描画に成功すると `data-vega-lite="rendered"` になります。
62
+
63
+ `vega-embed` の読み込み、仕様の `JSON.parse`、描画のいずれかが失敗した場合は例外を投げず、その figure の `details` を開いて元の仕様を見せます(`data-vega-lite="error"`)。
64
+
65
+ JSON を解析できないコードブロックは置き換えず、通常のコードブロックのまま残し、`@riebeckite/plugin-vega-lite` を `source` に持つ診断を出します。
66
+
67
+ ## オプション
68
+
69
+ | 項目 | 既定値 | 説明 |
70
+ | --- | --- | --- |
71
+ | `caption` | `true` | `title` をキャプションとして表示する |
72
+ | `actions` | `null` | `vega-embed` の操作メニューを表示する(`true` / `false` / `null`) |
73
+ | `theme` | `"light"` | 配色(`"light"`、`"dark"`、`"none"`) |
74
+ | `renderer` | `"canvas"` | Vega のレンダラー(`"canvas"` または `"svg"`) |
75
+ | `className` | `"rb-vega-lite"` | figure に付ける基準クラス |
76
+
77
+ `actions` が `null` のときは `vega-embed` の既定(操作メニューあり)に従います。`theme` が `"light"` または `"none"` のときは Vega 既定の明るい配色を使い、`"dark"` のときだけ `vega-embed` の `dark` テーマを適用します。
78
+
79
+ ## クライアント側の描画
80
+
81
+ クライアントの初期化コードは静的なので、プラグインのオプションは受け取りません。`actions`、`theme`、`renderer` は figure の `data-vega-lite-*` 属性に埋め込まれ、`initVegaLite` がそこから読み取ります。
82
+
83
+ Vega ランタイムは `import()` で動的に読み込むため、JavaScript を無効にしていてもページは表示され、仕様はフォールバックの `details` から読めます。
84
+
85
+ ## 出力のフック
86
+
87
+ - `figure[data-vega-lite]`: 状態(`pending` / `rendered` / `error`)
88
+ - `figure[data-vega-lite-spec]`: エスケープ済みの仕様 JSON
89
+ - `figure[data-vega-lite-theme]`、`figure[data-vega-lite-renderer]`、`figure[data-vega-lite-actions]`
90
+ - `[data-vega-lite-canvas]`: 描画先の要素
91
+ - `details.rb-vega-lite__fallback`: 元の仕様
92
+
93
+ ## 主なエクスポート
94
+
95
+ - `vegaLite(options?)`: プラグインを作成する(`vegaLitePlugin` は別名)
96
+ - `initVegaLite`: クライアント側の描画を初期化する
97
+ - 型: `VegaLiteOptions`、`VegaLiteSpec`、`VegaLiteTheme`、`VegaLiteRenderer`
98
+
99
+ ## 制限
100
+
101
+ - 描画はクライアント側のみです。ビルド時に SVG などは生成しないため、JavaScript が無効な環境ではチャートは表示されません(仕様の `details` は残ります)
102
+ - チャートごとに `vega`、`vega-lite`、`vega-embed` を読み込むため、多数のチャートを含むページでは転送量と描画コストが増えます
103
+ - Vega-Lite のすべての機能を検証しているわけではありません。複雑な仕様はブラウザ側のエラーとして扱われ、フォールバックが開きます
104
+ - `vega`、`vega-lite`、`vega-embed` は BSD-3-Clause ライセンスです
105
+
106
+ ## 関連資料
107
+
108
+ - [プラグインシステム](../../../docs/ja/plugin-system.md)
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Renders every server-emitted `[data-vega-lite]` figure in the browser.
3
+ *
4
+ * The spec travels in a `data-vega-lite-spec` attribute, so the heavy Vega
5
+ * runtime is imported dynamically and the page still renders (as a fallback
6
+ * `<details>`) when JavaScript is disabled. A broken payload or a Vega error
7
+ * reveals the fallback for that figure without affecting the rest of the page.
8
+ */
9
+ export declare function initVegaLite(): Promise<void>;
package/dist/client.js ADDED
@@ -0,0 +1,67 @@
1
+ // client.ts
2
+ var FIGURE_SELECTOR = "[data-vega-lite]";
3
+ var CANVAS_SELECTOR = "[data-vega-lite-canvas]";
4
+ async function initVegaLite() {
5
+ const figures = Array.from(
6
+ document.querySelectorAll(FIGURE_SELECTOR)
7
+ );
8
+ if (figures.length === 0) return;
9
+ let embed;
10
+ try {
11
+ const [, , vegaEmbed] = await Promise.all([
12
+ import("vega"),
13
+ import("vega-lite"),
14
+ import("vega-embed")
15
+ ]);
16
+ embed = vegaEmbed.default;
17
+ } catch {
18
+ for (const figure of figures) revealFallback(figure);
19
+ return;
20
+ }
21
+ for (const figure of figures) {
22
+ await renderFigure(embed, figure);
23
+ }
24
+ }
25
+ async function renderFigure(embed, figure) {
26
+ const canvas = figure.querySelector(CANVAS_SELECTOR);
27
+ const serialized = figure.dataset.vegaLiteSpec;
28
+ if (!canvas || !serialized) {
29
+ revealFallback(figure);
30
+ return;
31
+ }
32
+ let spec;
33
+ try {
34
+ spec = JSON.parse(serialized);
35
+ } catch {
36
+ revealFallback(figure);
37
+ return;
38
+ }
39
+ try {
40
+ await embed(
41
+ canvas,
42
+ spec,
43
+ buildEmbedOptions(figure)
44
+ );
45
+ figure.dataset.vegaLite = "rendered";
46
+ } catch {
47
+ revealFallback(figure);
48
+ }
49
+ }
50
+ function buildEmbedOptions(figure) {
51
+ const options = {};
52
+ const actions = figure.dataset.vegaLiteActions;
53
+ if (actions === "true") options.actions = true;
54
+ else if (actions === "false") options.actions = false;
55
+ if (figure.dataset.vegaLiteTheme === "dark") options.theme = "dark";
56
+ const renderer = figure.dataset.vegaLiteRenderer;
57
+ if (renderer === "canvas" || renderer === "svg") options.renderer = renderer;
58
+ return options;
59
+ }
60
+ function revealFallback(figure) {
61
+ figure.dataset.vegaLite = "error";
62
+ const fallback = figure.querySelector("details");
63
+ if (fallback) fallback.open = true;
64
+ }
65
+ export {
66
+ initVegaLite
67
+ };
@@ -0,0 +1,11 @@
1
+ import type { VegaLiteOptions } from "./src/types.js";
2
+ export { rehypeVegaLite } from "./src/rehype.js";
3
+ export type { VegaLiteOptions, VegaLiteRenderer, VegaLiteSpec, VegaLiteTheme, } from "./src/types.js";
4
+ /**
5
+ * Renders fenced `vega-lite` (and `vega`) code blocks as charts. The block body
6
+ * is a Vega-Lite JSON specification; the chart is drawn in the browser by
7
+ * `initVegaLite`, which imports the Vega runtime dynamically.
8
+ */
9
+ export declare function vegaLite(options?: VegaLiteOptions): import("@riebeckite/core").RiebeckitePlugin<VegaLiteOptions>;
10
+ /** Alias kept for symmetry with the other plugin factories. */
11
+ export declare const vegaLitePlugin: typeof vegaLite;
package/dist/index.js ADDED
@@ -0,0 +1,238 @@
1
+ // index.ts
2
+ import {
3
+ createClientEntry,
4
+ createStyleAsset,
5
+ definePlugin
6
+ } from "@riebeckite/core";
7
+
8
+ // src/hast.ts
9
+ function visitElements(node, visitor, parent, index) {
10
+ if (isElementNode(node)) visitor(node, parent, index);
11
+ for (const [childIndex, child] of [...getChildren(node)].entries()) {
12
+ visitElements(child, visitor, hasChildren(node) ? node : parent, childIndex);
13
+ }
14
+ }
15
+ function element(tagName, properties = {}, children = []) {
16
+ return { type: "element", tagName, properties, children };
17
+ }
18
+ function text(value) {
19
+ return { type: "text", value };
20
+ }
21
+ function getTextContent(node) {
22
+ if (node.type === "text" && "value" in node && typeof node.value === "string") {
23
+ return node.value;
24
+ }
25
+ return getChildren(node).map(getTextContent).join("");
26
+ }
27
+ function getStringProperty(node, key) {
28
+ const value = node.properties?.[key];
29
+ if (typeof value === "string") return value;
30
+ if (Array.isArray(value)) return value.join(" ");
31
+ return null;
32
+ }
33
+ function hasClass(node, className) {
34
+ const value = node.properties?.className;
35
+ const classes = Array.isArray(value) ? value.map(String) : typeof value === "string" ? value.split(/\s+/) : [];
36
+ return classes.includes(className);
37
+ }
38
+ function isElementNode(node) {
39
+ return node.type === "element";
40
+ }
41
+ function hasChildren(node) {
42
+ return Array.isArray(node.children);
43
+ }
44
+ function getChildren(node) {
45
+ const children = node.children;
46
+ return Array.isArray(children) ? children : [];
47
+ }
48
+
49
+ // src/rehype.ts
50
+ var DEFAULT_CLASS_NAME = "rb-vega-lite";
51
+ var DEFAULT_THEME = "light";
52
+ var DEFAULT_RENDERER = "canvas";
53
+ var VEGA_LITE_LANGUAGE_CLASS = "language-vega-lite";
54
+ var VEGA_LANGUAGE_CLASS = "language-vega";
55
+ var DIAGNOSTIC_SOURCE = "@riebeckite/plugin-vega-lite";
56
+ function rehypeVegaLite(options = {}) {
57
+ const resolved = {
58
+ className: options.className?.trim() || DEFAULT_CLASS_NAME,
59
+ caption: options.caption !== false,
60
+ theme: options.theme ?? DEFAULT_THEME,
61
+ renderer: options.renderer ?? DEFAULT_RENDERER,
62
+ actions: options.actions ?? null
63
+ };
64
+ return (tree, file) => {
65
+ visitElements(tree, (node, parent, index) => {
66
+ if (!parent || index === void 0 || !isVegaLiteCodeBlock(node)) return;
67
+ replaceVegaLiteBlock(parent, index, node, file, resolved);
68
+ });
69
+ };
70
+ }
71
+ function replaceVegaLiteBlock(parent, index, pre, file, options) {
72
+ const code = findDirectChild(pre, "code");
73
+ const source = code ? getTextContent(code).trim() : getTextContent(pre).trim();
74
+ const parsed = parseSpec(source);
75
+ if (parsed.ok === false) {
76
+ reportDiagnostic(file, parsed.message);
77
+ return;
78
+ }
79
+ const captionText = options.caption ? extractCaption(pre, code, parsed.spec) : null;
80
+ const label = captionText ?? "Vega-Lite chart";
81
+ parent.children = parent.children ?? [];
82
+ parent.children[index] = buildFigure({
83
+ className: options.className,
84
+ spec: parsed.spec,
85
+ source,
86
+ caption: captionText,
87
+ label,
88
+ theme: options.theme,
89
+ renderer: options.renderer,
90
+ actions: options.actions
91
+ });
92
+ }
93
+ function buildFigure(input) {
94
+ const base = input.className;
95
+ const children = [
96
+ element(
97
+ "div",
98
+ {
99
+ className: `${base}__canvas`,
100
+ dataVegaLiteCanvas: "true",
101
+ role: "img",
102
+ ariaLabel: input.label
103
+ },
104
+ []
105
+ )
106
+ ];
107
+ if (input.caption) {
108
+ children.push(
109
+ element("figcaption", { className: `${base}__caption` }, [
110
+ text(input.caption)
111
+ ])
112
+ );
113
+ }
114
+ children.push(
115
+ element("details", { className: `${base}__fallback` }, [
116
+ element("summary", {}, [text("Vega-Lite spec")]),
117
+ element("pre", {}, [element("code", {}, [text(input.source)])])
118
+ ])
119
+ );
120
+ return element(
121
+ "figure",
122
+ {
123
+ className: base,
124
+ dataVegaLite: "pending",
125
+ dataVegaLiteSpec: JSON.stringify(input.spec),
126
+ dataVegaLiteTheme: input.theme,
127
+ dataVegaLiteRenderer: input.renderer,
128
+ dataVegaLiteActions: input.actions === null ? void 0 : String(input.actions)
129
+ },
130
+ children
131
+ );
132
+ }
133
+ function parseSpec(source) {
134
+ let parsed;
135
+ try {
136
+ parsed = JSON.parse(source);
137
+ } catch (error) {
138
+ return { ok: false, message: `Invalid JSON: ${formatError(error)}` };
139
+ }
140
+ if (!isRecord(parsed)) {
141
+ return { ok: false, message: "Expected a JSON object." };
142
+ }
143
+ return { ok: true, spec: parsed };
144
+ }
145
+ function extractCaption(pre, code, spec) {
146
+ const title = getStringProperty(pre, "title") ?? (code ? getStringProperty(code, "title") : null);
147
+ const value = title ?? readSpecTitle(spec.title);
148
+ return value?.trim() || null;
149
+ }
150
+ function readSpecTitle(value) {
151
+ if (typeof value === "string") return value;
152
+ if (isRecord(value) && typeof value.text === "string") return value.text;
153
+ return null;
154
+ }
155
+ function isVegaLiteCodeBlock(node) {
156
+ if (node.tagName !== "pre") return false;
157
+ const code = findDirectChild(node, "code");
158
+ return Boolean(
159
+ code && (hasClass(code, VEGA_LITE_LANGUAGE_CLASS) || hasClass(code, VEGA_LANGUAGE_CLASS))
160
+ );
161
+ }
162
+ function findDirectChild(node, tagName) {
163
+ return node.children?.find(
164
+ (child) => child.type === "element" && child.tagName === tagName
165
+ ) ?? null;
166
+ }
167
+ function reportDiagnostic(file, message) {
168
+ const reporter = file?.message;
169
+ if (typeof reporter !== "function") return;
170
+ const diagnostic = reporter.call(file, `Invalid Vega-Lite spec: ${message}`);
171
+ if (diagnostic && typeof diagnostic === "object") {
172
+ Object.assign(diagnostic, {
173
+ source: DIAGNOSTIC_SOURCE,
174
+ ruleId: "invalid-spec"
175
+ });
176
+ }
177
+ }
178
+ function isRecord(value) {
179
+ return typeof value === "object" && value !== null && !Array.isArray(value);
180
+ }
181
+ function formatError(error) {
182
+ return error instanceof Error ? error.message : String(error);
183
+ }
184
+
185
+ // index.ts
186
+ var THEMES = ["light", "dark", "none"];
187
+ var RENDERERS = ["canvas", "svg"];
188
+ function vegaLite(options = {}) {
189
+ return definePlugin({
190
+ name: "vega-lite",
191
+ order: -10,
192
+ options,
193
+ validateOptions: validateVegaLiteOptions,
194
+ extendHtmlPipeline: (pipeline) => {
195
+ pipeline.use(rehypeVegaLite, options);
196
+ },
197
+ assets: [createStyleAsset("vega-lite")],
198
+ clientEntries: [createClientEntry("vega-lite", "initVegaLite")]
199
+ });
200
+ }
201
+ var vegaLitePlugin = vegaLite;
202
+ function validateVegaLiteOptions(options) {
203
+ if (!options) return [];
204
+ const issues = [];
205
+ if (options.caption !== void 0 && typeof options.caption !== "boolean") {
206
+ issues.push({ path: "caption", message: "Expected a boolean." });
207
+ }
208
+ if (options.actions !== void 0 && options.actions !== null && typeof options.actions !== "boolean") {
209
+ issues.push({ path: "actions", message: "Expected a boolean or null." });
210
+ }
211
+ if (options.theme !== void 0 && !isTheme(options.theme)) {
212
+ issues.push({
213
+ path: "theme",
214
+ message: 'Expected "light", "dark", or "none".'
215
+ });
216
+ }
217
+ if (options.renderer !== void 0 && !isRenderer(options.renderer)) {
218
+ issues.push({
219
+ path: "renderer",
220
+ message: 'Expected "canvas" or "svg".'
221
+ });
222
+ }
223
+ if (options.className !== void 0 && (typeof options.className !== "string" || options.className.trim() === "")) {
224
+ issues.push({ path: "className", message: "Expected a non-empty string." });
225
+ }
226
+ return issues;
227
+ }
228
+ function isTheme(value) {
229
+ return THEMES.includes(value);
230
+ }
231
+ function isRenderer(value) {
232
+ return RENDERERS.includes(value);
233
+ }
234
+ export {
235
+ rehypeVegaLite,
236
+ vegaLite,
237
+ vegaLitePlugin
238
+ };
@@ -0,0 +1,7 @@
1
+ import type { ElementNode, HastNode, ParentNode, TextNode } from "./types.js";
2
+ export declare function visitElements(node: HastNode, visitor: (node: ElementNode, parent?: ParentNode, index?: number) => void, parent?: ParentNode, index?: number): void;
3
+ export declare function element(tagName: string, properties?: Record<string, unknown>, children?: HastNode[]): ElementNode;
4
+ export declare function text(value: string): TextNode;
5
+ export declare function getTextContent(node: HastNode): string;
6
+ export declare function getStringProperty(node: ElementNode, key: string): string | null;
7
+ export declare function hasClass(node: ElementNode, className: string): boolean;
@@ -0,0 +1,6 @@
1
+ import type { HastNode, VegaLiteOptions } from "./types.js";
2
+ /**
3
+ * Replaces fenced `vega-lite` (and `vega`) code blocks with a figure carrying
4
+ * the parsed specification. The chart is drawn in the browser by `initVegaLite`.
5
+ */
6
+ export declare function rehypeVegaLite(options?: VegaLiteOptions): (tree: HastNode, file: unknown) => void;
@@ -0,0 +1,42 @@
1
+ /** A Vega-Lite specification parsed from a fenced code block. */
2
+ export type VegaLiteSpec = Record<string, unknown>;
3
+ /** Colour scheme applied by `vega-embed`. */
4
+ export type VegaLiteTheme = "light" | "dark" | "none";
5
+ /** Renderer handed to `vega-embed`. */
6
+ export type VegaLiteRenderer = "canvas" | "svg";
7
+ export type VegaLiteOptions = {
8
+ /** Render the spec title (or code-block title) as a `figcaption`. Defaults to `true`. */
9
+ caption?: boolean;
10
+ /**
11
+ * Show the `vega-embed` actions menu. `true`/`false` force it, `null` (the
12
+ * default) keeps the `vega-embed` default.
13
+ */
14
+ actions?: boolean | null;
15
+ /** Colour scheme for the rendered chart. Defaults to `"light"`. */
16
+ theme?: VegaLiteTheme;
17
+ /** Base class applied to the figure. Defaults to `"rb-vega-lite"`. */
18
+ className?: string;
19
+ /** Renderer used by the Vega runtime. Defaults to `"canvas"`. */
20
+ renderer?: VegaLiteRenderer;
21
+ };
22
+ export type ElementNode = {
23
+ type: string;
24
+ tagName?: string;
25
+ properties?: Record<string, unknown>;
26
+ children?: HastNode[];
27
+ };
28
+ export type ParentNode = HastNode & {
29
+ children?: HastNode[];
30
+ };
31
+ export type TextNode = {
32
+ type: "text";
33
+ value: string;
34
+ };
35
+ export type RawNode = {
36
+ type: "raw";
37
+ value: string;
38
+ };
39
+ export type HastNode = ElementNode | TextNode | RawNode | {
40
+ type: string;
41
+ [key: string]: unknown;
42
+ };
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@riebeckite/plugin-vega-lite",
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
+ "vega": "^6.4.0",
25
+ "vega-embed": "^7.3.0",
26
+ "vega-lite": "^6.4.3",
27
+ "@riebeckite/core": "0.0.1"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "files": [
33
+ "LICENSE",
34
+ "README.md",
35
+ "README_ja.md",
36
+ "dist",
37
+ "style.css"
38
+ ],
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "https://github.com/Rerurate514/riebeckite.git",
42
+ "directory": "packages/plugins/vega-lite"
43
+ },
44
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
45
+ "bugs": {
46
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
47
+ },
48
+ "description": "Vega-Lite chart rendering for Riebeckite code blocks.",
49
+ "keywords": [
50
+ "riebeckite",
51
+ "plugin",
52
+ "vega-lite",
53
+ "charts"
54
+ ],
55
+ "engines": {
56
+ "node": "^20.19.0 || >=22.12.0"
57
+ },
58
+ "sideEffects": [
59
+ "./style.css"
60
+ ],
61
+ "scripts": {
62
+ "build": "node ../../../scripts/build_package.mjs"
63
+ }
64
+ }
package/style.css ADDED
@@ -0,0 +1,73 @@
1
+ .rb-vega-lite {
2
+ --rb-vega-lite-paper: var(--rb-color-paper, #ffffff);
3
+ --rb-vega-lite-ink: var(--rb-color-ink, #000000);
4
+ --rb-vega-lite-muted: var(--rb-color-muted, #69645c);
5
+ --rb-vega-lite-rule: var(
6
+ --rb-color-border,
7
+ color-mix(in srgb, var(--rb-vega-lite-ink) 18%, transparent)
8
+ );
9
+ --rb-vega-lite-accent: var(--rb-color-accent, #686868);
10
+ margin: 2rem 0;
11
+ border: 1px solid var(--rb-vega-lite-rule);
12
+ background: color-mix(
13
+ in srgb,
14
+ var(--rb-vega-lite-paper) 96%,
15
+ var(--rb-vega-lite-ink)
16
+ );
17
+ color: var(--rb-vega-lite-ink);
18
+ }
19
+
20
+ .rb-vega-lite__caption {
21
+ padding: 0.625rem 0.75rem;
22
+ border-bottom: 1px solid var(--rb-vega-lite-rule);
23
+ color: var(--rb-vega-lite-muted);
24
+ font-size: 0.875rem;
25
+ }
26
+
27
+ .rb-vega-lite__canvas {
28
+ overflow: auto;
29
+ padding: 1rem;
30
+ }
31
+
32
+ .rb-vega-lite__canvas .vega-embed {
33
+ display: block;
34
+ }
35
+
36
+ .rb-vega-lite__canvas .vega-embed canvas,
37
+ .rb-vega-lite__canvas .vega-embed svg {
38
+ display: block;
39
+ max-width: 100%;
40
+ height: auto;
41
+ }
42
+
43
+ .rb-vega-lite__fallback {
44
+ border-top: 1px solid var(--rb-vega-lite-rule);
45
+ color: var(--rb-vega-lite-muted);
46
+ font-size: 0.8125rem;
47
+ }
48
+
49
+ .rb-vega-lite__fallback summary {
50
+ cursor: pointer;
51
+ padding: 0.5rem 0.75rem;
52
+ }
53
+
54
+ .rb-vega-lite__fallback pre {
55
+ overflow: auto;
56
+ margin: 0 1rem;
57
+ padding: 0.75rem;
58
+ border-top: 1px solid var(--rb-vega-lite-rule);
59
+ color: var(--rb-vega-lite-ink);
60
+ background: color-mix(in srgb, var(--rb-vega-lite-ink) 6%, transparent);
61
+ }
62
+
63
+ .rb-vega-lite[data-vega-lite="error"] .rb-vega-lite__canvas::before,
64
+ .rb-vega-lite[data-vega-lite="pending"] .rb-vega-lite__canvas:empty::before {
65
+ content: "Chart could not be rendered.";
66
+ color: var(--rb-vega-lite-muted);
67
+ }
68
+
69
+ html[data-theme="dark"] .rb-vega-lite,
70
+ html.dark .rb-vega-lite {
71
+ --rb-vega-lite-paper: var(--rb-color-ink, #000000);
72
+ --rb-vega-lite-ink: var(--rb-color-paper, #ffffff);
73
+ }