@riebeckite/plugin-excalidraw 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,90 @@
1
+ # @riebeckite/plugin-excalidraw
2
+
3
+ Excalidraw drawing rendering for Obsidian wikilinks.
4
+
5
+ [日本語](./README_ja.md)
6
+
7
+ ## Overview
8
+
9
+ `excalidraw()` provides the `renderAttachment` hook that
10
+ `@riebeckite/plugin-obsidian-markdown` uses when an embedded wikilink
11
+ (`![[drawing.excalidraw]]`) resolves to an Excalidraw file. The plugin emits a
12
+ placeholder figure carrying the drawing payload, and the client entry renders
13
+ it to SVG.
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { defineConfig } from "@riebeckite/core";
19
+ import { excalidraw } from "@riebeckite/plugin-excalidraw";
20
+ import { obsidianMarkdown } from "@riebeckite/plugin-obsidian-markdown";
21
+
22
+ export default defineConfig({
23
+ // ...
24
+ plugins: [obsidianMarkdown(), excalidraw()],
25
+ });
26
+ ```
27
+
28
+ The plugin registers `style.css` and a client entry (`initExcalidraw`) that
29
+ the app calls on page initialization.
30
+
31
+ ## Supported formats
32
+
33
+ ### `*.excalidraw` — plain JSON scene
34
+
35
+ A compact Excalidraw export with `elements`, optional `appState`, and
36
+ `files`.
37
+
38
+ ### `*.excalidraw.md` — Obsidian Excalidraw drawing
39
+
40
+ Obsidian "Excalidraw" plugin stores drawings in Markdown. The `## Drawing`
41
+ fenced code block is extracted and supports both `json` and lz-string
42
+ `compressed-json` variants.
43
+
44
+ ## Behavior
45
+
46
+ ### Build (`renderAttachment`)
47
+
48
+ - Only handles embedded wikilinks (`![[...]]`) to paths ending in
49
+ `.excalidraw` or `.excalidraw.md`; everything else returns `null` and falls
50
+ through to the attachment plugin
51
+ - Reads the file under `config.content.directory` (path-traversal safe)
52
+ - Parses the scene and emits
53
+
54
+ ```html
55
+ <figure class="rr-excalidraw" data-excalidraw="pending" data-excalidraw-lazy="true">
56
+ <div class="rr-excalidraw__canvas" role="img" aria-label="drawing.excalidraw"></div>
57
+ <script type="application/json" class="rr-excalidraw__payload">{"elements":[...],"appState":{...},"files":{...}}</script>
58
+ </figure>
59
+ ```
60
+
61
+ - Wikilink aliases can set a size: `![[drawing.excalidraw|800]]` (width) or
62
+ `![[drawing.excalidraw|800x600]]` (width x height)
63
+ - Missing files, invalid scenes, or out-of-directory paths render an error
64
+ placeholder and log to the console
65
+
66
+ ### Client (`initExcalidraw`)
67
+
68
+ - Renders pending figures to SVG with `exportToSvg` from
69
+ `@excalidraw/excalidraw`
70
+ - Figures marked `data-excalidraw-lazy="false"` render immediately; the rest
71
+ render when they scroll into view (`IntersectionObserver`, 200px margin)
72
+ - Success → `data-excalidraw="ready"` (the SVG replaces the empty canvas)
73
+ - Failure → `data-excalidraw="error"` plus a placeholder message
74
+
75
+ ## Options
76
+
77
+ | Option | Type | Default | Description |
78
+ | ------ | ---- | ------- | ----------- |
79
+ | `lazy` | `boolean` | `true` | Render lazily in the browser (as the figure enters the viewport) instead of immediately |
80
+
81
+ ## Exports
82
+
83
+ - `excalidraw(options?)` / `excalidrawPlugin` — plugin factory
84
+ - Type: `ExcalidrawOptions`
85
+
86
+ ## See also
87
+
88
+ - [Plugin guide](../../docs/plugins_en.md)
89
+ - [`@riebeckite/plugin-obsidian-markdown`](../plugin-obsidian-markdown/README.md)
90
+ - [`@riebeckite/plugin-attachment`](../plugin-attachment/README.md)
package/README_ja.md ADDED
@@ -0,0 +1,48 @@
1
+ # @riebeckite/plugin-excalidraw
2
+
3
+ Obsidian の Excalidraw 埋め込みを SVG として表示するプラグインです。
4
+
5
+ [English](./README.md)
6
+
7
+ ## できること
8
+
9
+ `![[drawing.excalidraw]]` のような埋め込みウィキリンクを検出し、図のデータを含むプレースホルダーを出力します。ブラウザ側の `initExcalidraw` が、そのプレースホルダーを SVG に置き換えます。通常のリンクや対象外のファイルは処理せず、添付ファイル用のレンダラーに任せます。
10
+
11
+ ## 設定
12
+
13
+ ```ts
14
+ import { defineConfig } from "@riebeckite/core";
15
+ import { excalidraw } from "@riebeckite/plugin-excalidraw";
16
+ import { obsidianMarkdown } from "@riebeckite/plugin-obsidian-markdown";
17
+
18
+ export default defineConfig({
19
+ // ...
20
+ plugins: [obsidianMarkdown(), excalidraw()],
21
+ });
22
+ ```
23
+
24
+ ## 読み込めるファイル
25
+
26
+ - `*.excalidraw` — `elements`、任意の `appState` と `files` を持つ JSON シーン
27
+ - `*.excalidraw.md` — Obsidian Excalidraw が保存する Markdown。`## Drawing` 内の `json` と `compressed-json` を読み取ります。
28
+
29
+ `![[drawing.excalidraw|800]]` なら幅を、`![[drawing.excalidraw|800x600]]` なら幅と高さを指定できます。ファイルがない、内容が不正、またはコンテンツディレクトリ外を指す場合は、エラー用プレースホルダーを表示します。
30
+
31
+ ## 描画のタイミング
32
+
33
+ 既定では、図が表示領域の近くに入ってから描画します。`IntersectionObserver` が使えない環境を含め、描画に失敗した要素は `data-excalidraw="error"` になり、エラー表示へ切り替わります。
34
+
35
+ | オプション | 型 | 既定値 | 内容 |
36
+ | --- | --- | --- | --- |
37
+ | `lazy` | `boolean` | `true` | 表示領域に近づいてから SVG を描画するか |
38
+
39
+ ## 公開 API
40
+
41
+ - `excalidraw(options?)` / `excalidrawPlugin` — プラグインファクトリ
42
+ - `ExcalidrawOptions` — オプションの型
43
+
44
+ ## 関連資料
45
+
46
+ - [プラグインシステム](../../../docs/ja/plugin-system.md)
47
+ - [`@riebeckite/plugin-obsidian-markdown`](../obsidian-markdown/README_ja.md)
48
+ - [`@riebeckite/plugin-attachment`](../attachment/README_ja.md)
@@ -0,0 +1 @@
1
+ export { initExcalidraw } from "./src/client_init.js";
package/dist/client.js ADDED
@@ -0,0 +1,64 @@
1
+ // src/client_init.ts
2
+ function initExcalidraw() {
3
+ const figures = Array.from(
4
+ document.querySelectorAll(
5
+ '.rr-excalidraw[data-excalidraw="pending"]'
6
+ )
7
+ );
8
+ if (figures.length === 0) return;
9
+ const immediate = figures.filter(
10
+ (figure) => figure.dataset.excalidrawLazy === "false"
11
+ );
12
+ for (const figure of immediate) void renderFigure(figure);
13
+ const lazy = figures.filter(
14
+ (figure) => figure.dataset.excalidrawLazy !== "false"
15
+ );
16
+ if (lazy.length === 0) return;
17
+ if (!("IntersectionObserver" in window)) {
18
+ for (const figure of lazy) void renderFigure(figure);
19
+ return;
20
+ }
21
+ const observer = new IntersectionObserver(
22
+ (entries) => {
23
+ for (const entry of entries) {
24
+ if (!entry.isIntersecting) continue;
25
+ const figure = entry.target;
26
+ observer.unobserve(figure);
27
+ void renderFigure(figure);
28
+ }
29
+ },
30
+ { rootMargin: "200px" }
31
+ );
32
+ for (const figure of lazy) observer.observe(figure);
33
+ }
34
+ async function renderFigure(figure) {
35
+ const canvas = figure.querySelector(".rr-excalidraw__canvas");
36
+ const payloadScript = figure.querySelector(
37
+ ".rr-excalidraw__payload"
38
+ );
39
+ if (!canvas || !payloadScript?.textContent) return;
40
+ try {
41
+ const payload = JSON.parse(payloadScript.textContent);
42
+ const { exportToSvg } = await import("@excalidraw/excalidraw");
43
+ const svg = await exportToSvg({
44
+ elements: payload.elements,
45
+ appState: {
46
+ ...payload.appState,
47
+ exportBackground: payload.appState.exportBackground ?? false
48
+ },
49
+ files: payload.files
50
+ });
51
+ svg.removeAttribute("width");
52
+ svg.removeAttribute("height");
53
+ svg.setAttribute("role", "img");
54
+ canvas.replaceChildren(svg);
55
+ figure.dataset.excalidraw = "ready";
56
+ } catch (error) {
57
+ console.error("[plugin-excalidraw] SVG export failed", error);
58
+ figure.dataset.excalidraw = "error";
59
+ canvas.textContent = "Drawing could not be rendered.";
60
+ }
61
+ }
62
+ export {
63
+ initExcalidraw
64
+ };
@@ -0,0 +1,4 @@
1
+ import type { ExcalidrawOptions } from "./src/types.js";
2
+ export type { ExcalidrawOptions } from "./src/types.js";
3
+ export declare function excalidraw(options?: ExcalidrawOptions): import("@riebeckite/core").RiebeckitePlugin<ExcalidrawOptions>;
4
+ export declare const excalidrawPlugin: typeof excalidraw;
package/dist/index.js ADDED
@@ -0,0 +1,360 @@
1
+ // index.ts
2
+ import {
3
+ createClientEntry,
4
+ createStyleAsset,
5
+ definePlugin,
6
+ IMAGE_EXTENSIONS,
7
+ readContentSourceEntry
8
+ } from "@riebeckite/core";
9
+ import { visit } from "unist-util-visit";
10
+
11
+ // src/parse.ts
12
+ import { createRequire } from "node:module";
13
+ var require2 = createRequire(import.meta.url);
14
+ var lzString = loadLzString();
15
+ var EXCALIDRAW_FRONTMATTER_RE = /^---\s*\r?\n[\s\S]*?^excalidraw-plugin:\s*parsed\s*$[\s\S]*?^---\s*$/im;
16
+ function parseExcalidrawScene(raw, _filePath) {
17
+ const isObsidianMarkdown = isObsidianExcalidrawMarkdown(raw);
18
+ const source = isObsidianMarkdown ? extractObsidianDrawing(raw) : raw;
19
+ const scene = JSON.parse(source);
20
+ if (!Array.isArray(scene.elements)) {
21
+ throw new Error("Invalid Excalidraw scene: elements is missing.");
22
+ }
23
+ return {
24
+ scene: {
25
+ ...scene,
26
+ elements: scene.elements,
27
+ appState: scene.appState ?? {},
28
+ files: scene.files ?? {}
29
+ },
30
+ embeddedFiles: isObsidianMarkdown ? extractEmbeddedFiles(raw) : []
31
+ };
32
+ }
33
+ function isObsidianExcalidrawMarkdown(raw) {
34
+ return EXCALIDRAW_FRONTMATTER_RE.test(raw);
35
+ }
36
+ function extractObsidianDrawing(markdown) {
37
+ const fence = markdown.match(
38
+ /## Drawing\s*\r?\n```(json|compressed-json)\s*\r?\n([\s\S]*?)\r?\n```/i
39
+ );
40
+ if (!fence?.[1] || !fence[2]) {
41
+ throw new Error("Obsidian Excalidraw drawing block was not found.");
42
+ }
43
+ const kind = fence[1].toLowerCase();
44
+ const body = fence[2].trim();
45
+ if (kind === "json") return body;
46
+ const decompressed = decompressCompressedJson(body);
47
+ if (!decompressed) {
48
+ throw new Error(
49
+ "Obsidian Excalidraw compressed-json could not be decompressed."
50
+ );
51
+ }
52
+ return decompressed;
53
+ }
54
+ function decompressCompressedJson(value) {
55
+ const normalized = value.replace(/\s+/g, "");
56
+ return decompressFromBase64(normalized) ?? decompressFromEncodedURIComponent(normalized) ?? null;
57
+ }
58
+ function decompressFromBase64(value) {
59
+ return lzString.decompressFromBase64(value);
60
+ }
61
+ function decompressFromEncodedURIComponent(value) {
62
+ return lzString.decompressFromEncodedURIComponent(value);
63
+ }
64
+ function loadLzString() {
65
+ const loaded = require2(getLzStringPackageName());
66
+ const candidate = selectLzStringExports(loaded);
67
+ if (!candidate) {
68
+ throw new Error("Invalid lz-string module shape.");
69
+ }
70
+ return candidate;
71
+ }
72
+ function selectLzStringExports(value) {
73
+ if (isLzStringExports(value)) return value;
74
+ if (!value || typeof value !== "object") return null;
75
+ const module = value;
76
+ return isLzStringExports(module.default) ? module.default : null;
77
+ }
78
+ function isLzStringExports(value) {
79
+ if (!value || typeof value !== "object") return false;
80
+ const candidate = value;
81
+ return typeof candidate.decompressFromBase64 === "function" && typeof candidate.decompressFromEncodedURIComponent === "function";
82
+ }
83
+ function getLzStringPackageName() {
84
+ return "lz-string";
85
+ }
86
+ function extractEmbeddedFiles(markdown) {
87
+ const section = markdown.match(
88
+ /## Embedded Files\s*\r?\n([\s\S]*?)(?:\r?\n## |\r?\n%%|$)/i
89
+ )?.[1];
90
+ if (!section) return [];
91
+ return Array.from(
92
+ section.matchAll(
93
+ /^([a-f0-9]{40}):\s*\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?\]\]\s*$/gim
94
+ ),
95
+ (match) => ({
96
+ fileId: match[1] ?? "",
97
+ target: (match[2] ?? "").trim()
98
+ })
99
+ ).filter((file) => file.fileId && file.target);
100
+ }
101
+
102
+ // src/render.ts
103
+ import { escapeHtml, escapeHtmlAttribute } from "@riebeckite/core";
104
+ function renderExcalidrawPlaceholder(input) {
105
+ const style = renderSizeStyle(input.size);
106
+ const error = input.error ? `<p class="rr-excalidraw__error">${escapeHtml(input.error)}</p>` : "";
107
+ const payload = input.scene ? renderPayloadScript(input.scene) : "";
108
+ const state = input.error ? "error" : "pending";
109
+ const lazy = input.lazy === false ? "false" : "true";
110
+ return `<figure class="rr-excalidraw" data-excalidraw="${state}" data-excalidraw-lazy="${lazy}"${style}>
111
+ <div class="rr-excalidraw__canvas" role="img" aria-label="${escapeHtmlAttribute(input.title)}"></div>
112
+ ${error}
113
+ ${payload}
114
+ </figure>`;
115
+ }
116
+ function renderPayloadScript(scene) {
117
+ const payload = {
118
+ elements: scene.elements,
119
+ appState: scene.appState ?? {},
120
+ files: scene.files ?? {}
121
+ };
122
+ return `<script type="application/json" class="rr-excalidraw__payload">${escapeScriptJson(JSON.stringify(payload))}</script>`;
123
+ }
124
+ function renderSizeStyle(size) {
125
+ if (!size?.width && !size?.height) return "";
126
+ const declarations = [
127
+ size.width ? `--rr-excalidraw-width:${size.width}px` : null,
128
+ size.height ? `--rr-excalidraw-height:${size.height}px` : null
129
+ ].filter(Boolean);
130
+ return ` style="${declarations.join(";")}"`;
131
+ }
132
+ function escapeScriptJson(value) {
133
+ return value.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
134
+ }
135
+
136
+ // index.ts
137
+ var PLUGIN_NAME = "excalidraw";
138
+ function excalidraw(options = {}) {
139
+ return definePlugin({
140
+ name: PLUGIN_NAME,
141
+ order: -21,
142
+ options,
143
+ extendMarkdownPipeline: (pipeline, context) => {
144
+ pipeline.use(remarkExcalidrawMarkdownEmbed, {
145
+ contentIndex: context.contentIndex,
146
+ contentSource: context.contentSource,
147
+ options
148
+ });
149
+ },
150
+ renderers: [
151
+ {
152
+ name: "excalidraw-embed",
153
+ render: async (context) => renderAttachment(context, options)
154
+ }
155
+ ],
156
+ assets: [createStyleAsset(PLUGIN_NAME)],
157
+ clientEntries: [createClientEntry(PLUGIN_NAME, "initExcalidraw")]
158
+ });
159
+ }
160
+ var excalidrawPlugin = excalidraw;
161
+ async function renderAttachment(context, options) {
162
+ if (context.kind !== "attachment") return null;
163
+ if (!isExcalidrawPath(context.path)) return null;
164
+ if (!context.embed) return null;
165
+ if (!context.contentSource) {
166
+ return renderExcalidrawPlaceholder({
167
+ title: getFileName(context.path),
168
+ error: "Content source is not available."
169
+ });
170
+ }
171
+ try {
172
+ const raw = await readText(context.contentSource, context.path);
173
+ if (raw === null) return null;
174
+ if (!isExcalidrawDocument(context.path, raw)) return null;
175
+ const parsed = parseExcalidrawScene(raw, context.path);
176
+ const scene = await mergeEmbeddedFiles({
177
+ scene: parsed.scene,
178
+ embeddedFiles: parsed.embeddedFiles,
179
+ contentSource: context.contentSource,
180
+ contentIndex: context.contentIndex
181
+ });
182
+ return renderExcalidrawPlaceholder({
183
+ title: getFileName(context.path),
184
+ scene,
185
+ size: parseSize(context.label),
186
+ lazy: options.lazy !== false
187
+ });
188
+ } catch (error) {
189
+ console.error("[plugin-excalidraw] Failed to render Excalidraw", {
190
+ path: context.path,
191
+ error
192
+ });
193
+ return renderExcalidrawPlaceholder({
194
+ title: getFileName(context.path),
195
+ error: "Excalidraw could not be rendered."
196
+ });
197
+ }
198
+ }
199
+ function isExcalidrawPath(filePath) {
200
+ const lowerPath = filePath.toLowerCase();
201
+ return lowerPath.endsWith(".excalidraw") || lowerPath.endsWith(".excalidraw.md") || lowerPath.endsWith(".md");
202
+ }
203
+ function isExcalidrawDocument(filePath, raw) {
204
+ const lowerPath = filePath.toLowerCase();
205
+ if (lowerPath.endsWith(".excalidraw")) return true;
206
+ if (lowerPath.endsWith(".excalidraw.md")) return true;
207
+ return lowerPath.endsWith(".md") && isObsidianExcalidrawMarkdown(raw);
208
+ }
209
+ function parseSize(label) {
210
+ const value = label.trim();
211
+ if (/^\d{1,5}$/.test(value)) return { width: Number(value) };
212
+ const match = value.match(/^(\d{1,5})x(\d{1,5})$/i);
213
+ if (!match?.[1] || !match[2]) return void 0;
214
+ return { width: Number(match[1]), height: Number(match[2]) };
215
+ }
216
+ function resolveMarkdownTarget(rawTarget, contentIndex) {
217
+ const target = rawTarget.toLowerCase();
218
+ const targetExtension = getPathExtension(target);
219
+ if (targetExtension && targetExtension !== "md") return null;
220
+ const indexKey = target.endsWith(".md") ? target.slice(0, -3) : target;
221
+ const resolved = contentIndex.get(indexKey);
222
+ if (!resolved) return null;
223
+ const resolvedExtension = getPathExtension(resolved);
224
+ if (resolvedExtension && resolvedExtension !== "md") return null;
225
+ return resolved.toLowerCase().endsWith(".md") ? resolved : `${resolved}.md`;
226
+ }
227
+ function remarkExcalidrawMarkdownEmbed(input) {
228
+ return async (tree) => {
229
+ const replacements = [];
230
+ visit(tree, "text", (node, index, parent) => {
231
+ if (!parent || index === void 0) return;
232
+ if (!node.value.includes("![[")) return;
233
+ replacements.push({ node, index, parent });
234
+ });
235
+ for (const replacement of replacements.reverse()) {
236
+ await replaceExcalidrawMarkdownEmbeds(replacement, input);
237
+ }
238
+ };
239
+ }
240
+ async function replaceExcalidrawMarkdownEmbeds(replacement, input) {
241
+ const nodes = [];
242
+ const wikilinkRe = /!\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|([^\]]+))?\]\]/g;
243
+ let lastIndex = 0;
244
+ for (let match = wikilinkRe.exec(replacement.node.value); match !== null; match = wikilinkRe.exec(replacement.node.value)) {
245
+ const full = match[0];
246
+ const rawTarget = match[1]?.trim() ?? "";
247
+ const label = match[2]?.trim() ?? rawTarget;
248
+ const start = match.index;
249
+ const resolved = resolveMarkdownTarget(rawTarget, input.contentIndex);
250
+ const html = resolved ? await renderExcalidrawMarkdownEmbed({
251
+ path: resolved,
252
+ label,
253
+ contentIndex: input.contentIndex,
254
+ contentSource: input.contentSource,
255
+ options: input.options
256
+ }) : null;
257
+ if (!html) continue;
258
+ if (start > lastIndex) {
259
+ nodes.push({
260
+ type: "text",
261
+ value: replacement.node.value.slice(lastIndex, start)
262
+ });
263
+ }
264
+ nodes.push({ type: "html", value: html });
265
+ lastIndex = start + full.length;
266
+ }
267
+ if (lastIndex === 0) return;
268
+ if (lastIndex < replacement.node.value.length) {
269
+ nodes.push({
270
+ type: "text",
271
+ value: replacement.node.value.slice(lastIndex)
272
+ });
273
+ }
274
+ replacement.parent.children.splice(replacement.index, 1, ...nodes);
275
+ }
276
+ async function renderExcalidrawMarkdownEmbed(input) {
277
+ if (!input.contentSource) return null;
278
+ const raw = await readText(input.contentSource, input.path);
279
+ if (raw === null) return null;
280
+ if (!isObsidianExcalidrawMarkdown(raw)) return null;
281
+ const parsed = parseExcalidrawScene(raw, input.path);
282
+ const scene = await mergeEmbeddedFiles({
283
+ scene: parsed.scene,
284
+ embeddedFiles: parsed.embeddedFiles,
285
+ contentSource: input.contentSource,
286
+ contentIndex: input.contentIndex
287
+ });
288
+ return renderExcalidrawPlaceholder({
289
+ title: getFileName(input.path),
290
+ scene,
291
+ size: parseSize(input.label),
292
+ lazy: input.options.lazy !== false
293
+ });
294
+ }
295
+ async function mergeEmbeddedFiles(input) {
296
+ const resolvedFiles = await resolveEmbeddedFiles(input);
297
+ return {
298
+ ...input.scene,
299
+ files: {
300
+ ...input.scene.files ?? {},
301
+ ...resolvedFiles
302
+ }
303
+ };
304
+ }
305
+ async function resolveEmbeddedFiles(input) {
306
+ const files = {};
307
+ for (const embeddedFile of input.embeddedFiles) {
308
+ const assetPath = input.contentIndex.get(embeddedFile.target.toLowerCase());
309
+ if (!assetPath || !isSupportedImagePath(assetPath)) continue;
310
+ try {
311
+ const data = await readContentSourceEntry(input.contentSource, assetPath);
312
+ if (data === null) continue;
313
+ const mimeType = getImageMimeType(assetPath);
314
+ files[embeddedFile.fileId] = {
315
+ id: embeddedFile.fileId,
316
+ dataURL: `data:${mimeType};base64,${toBase64(data)}`,
317
+ mimeType,
318
+ created: Date.now(),
319
+ lastRetrieved: Date.now()
320
+ };
321
+ } catch (error) {
322
+ console.error("[plugin-excalidraw] Failed to resolve embedded file", {
323
+ target: embeddedFile.target,
324
+ error
325
+ });
326
+ }
327
+ }
328
+ return files;
329
+ }
330
+ function isSupportedImagePath(filePath) {
331
+ const extension = getPathExtension(filePath);
332
+ return IMAGE_EXTENSIONS.includes(extension);
333
+ }
334
+ function getImageMimeType(filePath) {
335
+ const extension = getPathExtension(filePath);
336
+ if (extension === "jpg") return "image/jpeg";
337
+ if (extension === "svg") return "image/svg+xml";
338
+ return `image/${extension}`;
339
+ }
340
+ function getPathExtension(filePath) {
341
+ const fileName = getFileName(filePath.toLowerCase());
342
+ const extensionStart = fileName.lastIndexOf(".");
343
+ return extensionStart > 0 ? fileName.slice(extensionStart + 1) : "";
344
+ }
345
+ async function readText(source, logicalPath) {
346
+ const content = await readContentSourceEntry(source, logicalPath);
347
+ if (content === null) return null;
348
+ return typeof content === "string" ? content : new TextDecoder().decode(content);
349
+ }
350
+ function toBase64(content) {
351
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
352
+ return Buffer.from(bytes).toString("base64");
353
+ }
354
+ function getFileName(contentPath) {
355
+ return contentPath.split("/").at(-1) ?? contentPath;
356
+ }
357
+ export {
358
+ excalidraw,
359
+ excalidrawPlugin
360
+ };
@@ -0,0 +1 @@
1
+ export declare function initExcalidraw(): void;
@@ -0,0 +1,3 @@
1
+ import type { ParsedExcalidrawDocument } from "./types.js";
2
+ export declare function parseExcalidrawScene(raw: string, _filePath: string): ParsedExcalidrawDocument;
3
+ export declare function isObsidianExcalidrawMarkdown(raw: string): boolean;
@@ -0,0 +1,11 @@
1
+ import type { ExcalidrawScene } from "./types.js";
2
+ export declare function renderExcalidrawPlaceholder(input: {
3
+ title: string;
4
+ scene?: ExcalidrawScene;
5
+ size?: {
6
+ width?: number;
7
+ height?: number;
8
+ };
9
+ lazy?: boolean;
10
+ error?: string;
11
+ }): string;
@@ -0,0 +1,24 @@
1
+ export type ExcalidrawOptions = {
2
+ lazy?: boolean;
3
+ };
4
+ export type ExcalidrawScene = {
5
+ type?: string;
6
+ version?: number;
7
+ source?: string;
8
+ elements: readonly Record<string, unknown>[];
9
+ appState?: Record<string, unknown>;
10
+ files?: Record<string, Record<string, unknown>>;
11
+ };
12
+ export type ObsidianEmbeddedFile = {
13
+ fileId: string;
14
+ target: string;
15
+ };
16
+ export type ParsedExcalidrawDocument = {
17
+ scene: ExcalidrawScene;
18
+ embeddedFiles: readonly ObsidianEmbeddedFile[];
19
+ };
20
+ export type ExcalidrawPayload = {
21
+ elements: readonly Record<string, unknown>[];
22
+ appState: Record<string, unknown>;
23
+ files: Record<string, Record<string, unknown>>;
24
+ };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@riebeckite/plugin-excalidraw",
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
+ "@excalidraw/excalidraw": "^0.18.0",
25
+ "lz-string": "^1.5.0",
26
+ "unist-util-visit": "^5.0.0",
27
+ "@riebeckite/core": "0.0.1"
28
+ },
29
+ "devDependencies": {
30
+ "@types/mdast": "^4.0.4"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "files": [
36
+ "LICENSE",
37
+ "README.md",
38
+ "README_ja.md",
39
+ "dist",
40
+ "style.css"
41
+ ],
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/Rerurate514/riebeckite.git",
45
+ "directory": "packages/plugins/excalidraw"
46
+ },
47
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
50
+ },
51
+ "description": "Excalidraw attachment rendering for Obsidian wikilinks.",
52
+ "keywords": [
53
+ "riebeckite",
54
+ "plugin",
55
+ "excalidraw",
56
+ "obsidian"
57
+ ],
58
+ "engines": {
59
+ "node": "^20.19.0 || >=22.12.0"
60
+ },
61
+ "sideEffects": [
62
+ "./style.css"
63
+ ],
64
+ "scripts": {
65
+ "build": "node ../../../scripts/build_package.mjs"
66
+ }
67
+ }
package/style.css ADDED
@@ -0,0 +1,50 @@
1
+ .rr-excalidraw {
2
+ --rr-excalidraw-paper: var(--rb-color-paper, #ffffff);
3
+ --rr-excalidraw-ink: var(--rb-color-ink, #000000);
4
+ --rr-excalidraw-muted: var(--rb-color-muted, #69645c);
5
+ --rr-excalidraw-rule: var(
6
+ --rb-color-border,
7
+ color-mix(in srgb, var(--rr-excalidraw-ink) 18%, transparent)
8
+ );
9
+ box-sizing: border-box;
10
+ width: min(100%, var(--rr-excalidraw-width, 100%));
11
+ max-width: 100%;
12
+ margin: 2rem 0;
13
+ border: 1px solid var(--rr-excalidraw-rule);
14
+ background: var(--rr-excalidraw-paper);
15
+ color: var(--rr-excalidraw-ink);
16
+ }
17
+
18
+ .rr-excalidraw__canvas {
19
+ display: grid;
20
+ min-height: min(var(--rr-excalidraw-height, 18rem), 70vh);
21
+ overflow: auto;
22
+ place-items: center;
23
+ padding: 1rem;
24
+ }
25
+
26
+ .rr-excalidraw__canvas > svg {
27
+ display: block;
28
+ width: 100%;
29
+ max-width: 100%;
30
+ height: var(--rr-excalidraw-height, auto);
31
+ }
32
+
33
+ .rr-excalidraw__error {
34
+ margin: 0;
35
+ padding: 0 1rem 1rem;
36
+ color: var(--rr-excalidraw-muted);
37
+ font-size: 0.875rem;
38
+ }
39
+
40
+ .rr-excalidraw[data-excalidraw="pending"] .rr-excalidraw__canvas:empty::before,
41
+ .rr-excalidraw[data-excalidraw="error"] .rr-excalidraw__canvas:empty::before {
42
+ content: "Drawing could not be rendered.";
43
+ color: var(--rr-excalidraw-muted);
44
+ }
45
+
46
+ html[data-theme="dark"] .rr-excalidraw,
47
+ html.dark .rr-excalidraw {
48
+ --rr-excalidraw-paper: var(--rb-color-ink, #000000);
49
+ --rr-excalidraw-ink: var(--rb-color-paper, #ffffff);
50
+ }