@kanbun-skam/skam-web-component 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-present berlysia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # @kanbun-skam/skam-web-component
2
+
3
+ **`<skam-renderer>`** カスタムエレメント。
4
+
5
+ SKAM-ML/XML を Shadow DOM 内で HTML レンダリングする Web Component。インポートするだけで自動登録。
6
+
7
+ ## インストール
8
+
9
+ ```bash
10
+ npm install @kanbun-skam/skam-web-component
11
+ # or
12
+ pnpm add @kanbun-skam/skam-web-component
13
+ ```
14
+
15
+ ## 使い方
16
+
17
+ ### 基本的な使い方
18
+
19
+ ```html
20
+ <script type="module">
21
+ import '@kanbun-skam/skam-web-component';
22
+ </script>
23
+
24
+ <skam-renderer>
25
+ <script type="application/vnd.berlysia.skam+xml">
26
+ <?xml version="1.0" encoding="UTF-8"?>
27
+ <skam:doc xmlns:skam="urn:skam:1" xml:lang="ja">
28
+ <skam:body>
29
+ <skam:block>
30
+ <skam:kun yomi="まな" okuri="びて">學</skam:kun><skam:okimoji>而</skam:okimoji>時<skam:kaeri kind="re"/><skam:kun soe="を">之</skam:kun><skam:kun okuri="ふ">習</skam:kun>
31
+ </skam:block>
32
+ </skam:body>
33
+ </skam:doc>
34
+ </script>
35
+ </skam-renderer>
36
+ ```
37
+
38
+ ### プログラマティックに XML を設定
39
+
40
+ ```typescript
41
+ import { SkamRendererElement } from '@kanbun-skam/skam-web-component';
42
+
43
+ const el = document.querySelector('skam-renderer') as SkamRendererElement;
44
+ el.xmlContent = xmlString;
45
+ ```
46
+
47
+ ### 属性
48
+
49
+ | 属性 | 値 | デフォルト | 説明 |
50
+ | ----------------------- | --------------------------------------------------- | ---------- | ------------------------- |
51
+ | `writing-mode` | `vertical` \| `horizontal` | `vertical` | 書字方向 |
52
+ | `profile` | `full` \| `learningBasic` \| `learningHint` \| JSON | `full` | 表示プロファイル |
53
+ | `inline` | (boolean) | false | インラインモード |
54
+ | `interactive` | (boolean) | false | インタラクティブ操作 |
55
+ | `include-reading-layer` | `true` \| `false` | `true` | 読み層の表示 |
56
+ | `copyable` | `all` \| スペース区切りの要素名 | (なし) | コピー可能な注記要素 |
57
+ | `class-prefix` | 文字列 | `skam` | CSS クラス名の接頭辞 |
58
+ | `auto-font` | (boolean) | false | Google Fonts 自動読み込み |
59
+
60
+ ### イベント
61
+
62
+ | イベント | detail | 説明 |
63
+ | ------------- | ---------------------------- | ------------------ |
64
+ | `skam-render` | `{ document: SKAMDocument }` | レンダリング成功時 |
65
+ | `skam-error` | `{ error: Error }` | エラー発生時 |
66
+
67
+ ### CSS Variables によるカスタマイズ
68
+
69
+ Shadow DOM 内のスタイルはホスト要素の CSS Variables で制御可能:
70
+
71
+ ```css
72
+ skam-renderer {
73
+ --skam-color-fg: #333;
74
+ --skam-color-kaeriten: #c00;
75
+ --skam-font-family: '游明朝', serif;
76
+ --skam-glyph-size: 1.2em;
77
+ }
78
+ ```
79
+
80
+ ### XML ソースの優先順位
81
+
82
+ 1. `xmlContent` プロパティ(プログラマティック設定)
83
+ 2. `<script type="application/vnd.berlysia.skam+xml">` 子要素
84
+ 3. Light DOM のテキストコンテンツ
85
+
86
+ ## 関連パッケージ
87
+
88
+ - [@kanbun-skam/skam](https://github.com/berlysia/kanbun-annotation/tree/master/packages/skam) - 型定義・バリデーター
89
+ - [@kanbun-skam/skam-xml-parser](https://github.com/berlysia/kanbun-annotation/tree/master/packages/skam-xml-parser) - SKAM-ML/XML パーサー
90
+ - [@kanbun-skam/skam-html-renderer](https://github.com/berlysia/kanbun-annotation/tree/master/packages/skam-html-renderer) - HTML レンダラー
91
+
92
+ ## ライセンス
93
+
94
+ UNLICENSED
package/dist/auto.d.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/auto.js ADDED
@@ -0,0 +1,8 @@
1
+ import {
2
+ SkamRendererElement
3
+ } from "./chunk-NXVDX5VV.js";
4
+
5
+ // src/auto.ts
6
+ if (!customElements.get("skam-renderer")) {
7
+ customElements.define("skam-renderer", SkamRendererElement);
8
+ }
@@ -0,0 +1,303 @@
1
+ // src/xml-extraction.ts
2
+ var SKAM_XML_MEDIA_TYPE = "application/vnd.berlysia.skam+xml";
3
+ function extractXmlFromScriptElement(host) {
4
+ const script = host.querySelector(`script[type="${SKAM_XML_MEDIA_TYPE}"]`);
5
+ if (script) {
6
+ const text = script.textContent?.trim();
7
+ return text || null;
8
+ }
9
+ return null;
10
+ }
11
+ function extractXmlFromLightDOM(host) {
12
+ const text = host.textContent;
13
+ if (text && text.trim()) {
14
+ return text;
15
+ }
16
+ return null;
17
+ }
18
+ function extractXml(xmlContent, host) {
19
+ if (xmlContent !== void 0) {
20
+ return xmlContent || null;
21
+ }
22
+ const fromScript = extractXmlFromScriptElement(host);
23
+ if (fromScript) {
24
+ return fromScript;
25
+ }
26
+ return extractXmlFromLightDOM(host);
27
+ }
28
+
29
+ // src/skam-renderer.ts
30
+ import { parse } from "@kanbun-skam/skam-xml-parser";
31
+ import { render, calibrateGridBaseline } from "@kanbun-skam/skam-html-renderer";
32
+
33
+ // src/attribute-map.ts
34
+ import { PROFILES } from "@kanbun-skam/skam-html-renderer";
35
+ var VALID_WRITING_MODES = ["vertical", "horizontal"];
36
+ var VALID_COPYABLE_ELEMENTS = ["ruby", "okurigana", "soegana", "kaeriten", "okototen"];
37
+ function parseWritingMode(value) {
38
+ if (value != null && VALID_WRITING_MODES.includes(value)) {
39
+ return value;
40
+ }
41
+ return "vertical";
42
+ }
43
+ function parseProfile(value) {
44
+ if (value == null) return void 0;
45
+ const preset = PROFILES[value];
46
+ if (preset) return preset;
47
+ try {
48
+ const parsed = JSON.parse(value);
49
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
50
+ return parsed;
51
+ }
52
+ } catch {
53
+ }
54
+ return void 0;
55
+ }
56
+ function parseBooleanAttr(value) {
57
+ return value !== null;
58
+ }
59
+ function parseCopyable(value) {
60
+ if (value == null) return void 0;
61
+ if (value === "all") return "all";
62
+ const elements = value.split(/\s+/).filter(
63
+ (v) => VALID_COPYABLE_ELEMENTS.includes(v)
64
+ );
65
+ return elements.length > 0 ? elements : void 0;
66
+ }
67
+ function buildRenderOptions(attrs) {
68
+ const options = {
69
+ writingMode: parseWritingMode(attrs["writing-mode"]),
70
+ useLayer: false
71
+ // Shadow DOM doesn't need @layer
72
+ };
73
+ const profile = parseProfile(attrs.profile);
74
+ if (profile) {
75
+ options.profile = profile;
76
+ }
77
+ if (parseBooleanAttr(attrs.inline)) {
78
+ options.inline = true;
79
+ }
80
+ if (attrs["include-reading-layer"] === null) {
81
+ options.includeReadingLayer = true;
82
+ } else {
83
+ options.includeReadingLayer = attrs["include-reading-layer"] !== "false";
84
+ }
85
+ const copyable = parseCopyable(attrs.copyable);
86
+ if (copyable) {
87
+ options.copyable = copyable;
88
+ }
89
+ if (attrs["class-prefix"] != null) {
90
+ options.classPrefix = attrs["class-prefix"];
91
+ }
92
+ return options;
93
+ }
94
+
95
+ // src/font-loader.ts
96
+ var DEFAULT_FONT_FAMILY = "Noto Serif JP";
97
+ var GOOGLE_FONTS_URL = "https://fonts.googleapis.com/css2?family=Noto+Serif+JP:wght@400;700&display=swap";
98
+ var LINK_SELECTOR = 'link[href*="fonts.googleapis.com"][href*="Noto+Serif+JP"]';
99
+ function injectGoogleFontsLink() {
100
+ if (typeof document === "undefined") return;
101
+ if (!document.querySelector(LINK_SELECTOR)) {
102
+ const link = document.createElement("link");
103
+ link.rel = "stylesheet";
104
+ link.href = GOOGLE_FONTS_URL;
105
+ document.head.appendChild(link);
106
+ }
107
+ }
108
+ function buildFontStyle(variablePrefix) {
109
+ const family = `"${DEFAULT_FONT_FAMILY}", serif`;
110
+ return `:host {
111
+ --${variablePrefix}-font-family: ${family};
112
+ --${variablePrefix}-font-family-ruby: ${family};
113
+ }`;
114
+ }
115
+
116
+ // src/skam-renderer.ts
117
+ var ERROR_CSS = `
118
+ [role="alert"] {
119
+ color: #c00;
120
+ padding: 0.5em;
121
+ font-family: monospace;
122
+ white-space: pre-wrap;
123
+ }
124
+ `;
125
+ function generateVarOverrideCss(prefix) {
126
+ const vp = prefix;
127
+ return `
128
+ :host {
129
+ --${vp}-color-fg: currentColor;
130
+ --${vp}-color-kaeriten: currentColor;
131
+ --${vp}-color-ruby: currentColor;
132
+ --${vp}-color-emphasis: currentColor;
133
+ --${vp}-glyph-size: 1em;
134
+ --${vp}-ruby-ratio: 0.5;
135
+ --${vp}-line-height: 2;
136
+ --${vp}-letter-spacing: 0;
137
+ }
138
+ .${vp}-document {
139
+ --${vp}-color-fg: inherit;
140
+ --${vp}-color-kaeriten: inherit;
141
+ --${vp}-color-ruby: inherit;
142
+ --${vp}-color-emphasis: inherit;
143
+ --${vp}-font-family: inherit;
144
+ --${vp}-font-family-ruby: inherit;
145
+ --${vp}-glyph-size: inherit;
146
+ --${vp}-ruby-ratio: inherit;
147
+ --${vp}-line-height: inherit;
148
+ --${vp}-letter-spacing: inherit;
149
+ }`;
150
+ }
151
+ var SkamRendererElement = class extends HTMLElement {
152
+ static observedAttributes = [
153
+ "writing-mode",
154
+ "profile",
155
+ "inline",
156
+ "include-reading-layer",
157
+ "copyable",
158
+ "class-prefix",
159
+ "auto-font"
160
+ ];
161
+ #shadow;
162
+ #mainStyle;
163
+ #errorStyle;
164
+ #fontStyle;
165
+ #contentDiv;
166
+ #xmlContent;
167
+ #observer = null;
168
+ #rafId = null;
169
+ constructor() {
170
+ super();
171
+ this.#shadow = this.attachShadow({ mode: "open" });
172
+ this.#mainStyle = document.createElement("style");
173
+ this.#mainStyle.id = "main-css";
174
+ this.#errorStyle = document.createElement("style");
175
+ this.#errorStyle.id = "error-css";
176
+ this.#errorStyle.textContent = ERROR_CSS;
177
+ this.#fontStyle = document.createElement("style");
178
+ this.#fontStyle.id = "font-css";
179
+ this.#contentDiv = document.createElement("div");
180
+ this.#contentDiv.id = "content";
181
+ this.#shadow.appendChild(this.#fontStyle);
182
+ this.#shadow.appendChild(this.#mainStyle);
183
+ this.#shadow.appendChild(this.#errorStyle);
184
+ this.#shadow.appendChild(this.#contentDiv);
185
+ }
186
+ /**
187
+ * XML コンテンツをプログラマティックに設定する。
188
+ * undefined の場合は <script type="application/vnd.berlysia.skam+xml"> や Light DOM にフォールバック。
189
+ * 空文字列 "" も「設定済み」とみなし、フォールバックしない。
190
+ */
191
+ get xmlContent() {
192
+ return this.#xmlContent;
193
+ }
194
+ set xmlContent(value) {
195
+ this.#xmlContent = value;
196
+ this.#scheduleRender();
197
+ }
198
+ connectedCallback() {
199
+ this.#ensureFont();
200
+ this.#observer = new MutationObserver(() => {
201
+ this.#scheduleRender();
202
+ });
203
+ this.#observer.observe(this, {
204
+ childList: true,
205
+ subtree: true,
206
+ characterData: true
207
+ });
208
+ this.#scheduleRender();
209
+ }
210
+ disconnectedCallback() {
211
+ this.#observer?.disconnect();
212
+ this.#observer = null;
213
+ if (this.#rafId !== null) {
214
+ cancelAnimationFrame(this.#rafId);
215
+ this.#rafId = null;
216
+ }
217
+ }
218
+ attributeChangedCallback(_name, _oldValue, _newValue) {
219
+ this.#scheduleRender();
220
+ }
221
+ #scheduleRender() {
222
+ if (this.#rafId !== null) return;
223
+ this.#rafId = requestAnimationFrame(() => {
224
+ this.#rafId = null;
225
+ this.#performRender();
226
+ });
227
+ }
228
+ #performRender() {
229
+ const xml = extractXml(this.#xmlContent, this);
230
+ if (!xml) {
231
+ this.#contentDiv.innerHTML = "";
232
+ this.#mainStyle.textContent = "";
233
+ return;
234
+ }
235
+ try {
236
+ const doc = parse(xml);
237
+ const attrs = this.#getAttributeValues();
238
+ const options = buildRenderOptions(attrs);
239
+ const { html, css } = render(doc, options);
240
+ const prefix = options.classPrefix ?? "skam";
241
+ this.#mainStyle.textContent = css + generateVarOverrideCss(prefix);
242
+ this.#ensureFont();
243
+ this.#updateFontStyle(prefix);
244
+ this.#contentDiv.innerHTML = html;
245
+ calibrateGridBaseline(this.#contentDiv, {
246
+ variablePrefix: prefix
247
+ });
248
+ this.dispatchEvent(
249
+ new CustomEvent("skam-render", {
250
+ detail: { document: doc },
251
+ bubbles: true,
252
+ composed: true
253
+ })
254
+ );
255
+ } catch (error) {
256
+ this.#handleError(error);
257
+ }
258
+ }
259
+ #handleError(error) {
260
+ const message = error instanceof Error ? error.message : String(error);
261
+ this.#contentDiv.innerHTML = "";
262
+ const alert = document.createElement("div");
263
+ alert.setAttribute("role", "alert");
264
+ alert.textContent = message;
265
+ this.#contentDiv.appendChild(alert);
266
+ this.dispatchEvent(
267
+ new CustomEvent("skam-error", {
268
+ detail: { error },
269
+ bubbles: true,
270
+ composed: true
271
+ })
272
+ );
273
+ }
274
+ /** auto-font 属性があれば Google Fonts <link> を document.head に注入 */
275
+ #ensureFont() {
276
+ if (this.hasAttribute("auto-font")) {
277
+ injectGoogleFontsLink();
278
+ }
279
+ }
280
+ /** Shadow DOM 内のフォント CSS Variable を更新(auto-font 時のみ設定) */
281
+ #updateFontStyle(variablePrefix) {
282
+ if (this.hasAttribute("auto-font")) {
283
+ this.#fontStyle.textContent = buildFontStyle(variablePrefix);
284
+ } else {
285
+ this.#fontStyle.textContent = "";
286
+ }
287
+ }
288
+ #getAttributeValues() {
289
+ return {
290
+ "writing-mode": this.getAttribute("writing-mode"),
291
+ profile: this.getAttribute("profile"),
292
+ inline: this.getAttribute("inline"),
293
+ "include-reading-layer": this.getAttribute("include-reading-layer"),
294
+ copyable: this.getAttribute("copyable"),
295
+ "class-prefix": this.getAttribute("class-prefix")
296
+ };
297
+ }
298
+ };
299
+
300
+ export {
301
+ SKAM_XML_MEDIA_TYPE,
302
+ SkamRendererElement
303
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * <skam-renderer> カスタムエレメント
3
+ *
4
+ * SKAM の HTML レンダリングパイプラインを Web Component として提供する。
5
+ * Shadow DOM でスタイルをカプセル化し、CSS Variables による外部カスタマイズを可能にする。
6
+ */
7
+ declare class SkamRendererElement extends HTMLElement {
8
+ #private;
9
+ static observedAttributes: string[];
10
+ constructor();
11
+ /**
12
+ * XML コンテンツをプログラマティックに設定する。
13
+ * undefined の場合は <script type="application/vnd.berlysia.skam+xml"> や Light DOM にフォールバック。
14
+ * 空文字列 "" も「設定済み」とみなし、フォールバックしない。
15
+ */
16
+ get xmlContent(): string | undefined;
17
+ set xmlContent(value: string | undefined);
18
+ connectedCallback(): void;
19
+ disconnectedCallback(): void;
20
+ attributeChangedCallback(_name: string, _oldValue: string | null, _newValue: string | null): void;
21
+ }
22
+
23
+ declare global {
24
+ interface HTMLElementTagNameMap {
25
+ 'skam-renderer': SkamRendererElement;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * HTML属性 → RenderOptions 変換ユーティリティ
31
+ */
32
+
33
+ interface AttributeValues {
34
+ 'writing-mode': string | null;
35
+ profile: string | null;
36
+ inline: string | null;
37
+ 'include-reading-layer': string | null;
38
+ copyable: string | null;
39
+ 'class-prefix': string | null;
40
+ }
41
+
42
+ /**
43
+ * XML テキスト取得ロジック
44
+ *
45
+ * 優先順位:
46
+ * 1. xmlContent プロパティ(プログラマティック設定値)
47
+ * 2. <script type="application/vnd.berlysia.skam+xml"> 子要素の textContent
48
+ * 3. Light DOM の textContent(フォールバック)
49
+ */
50
+ declare const SKAM_XML_MEDIA_TYPE = "application/vnd.berlysia.skam+xml";
51
+
52
+ export { type AttributeValues, SKAM_XML_MEDIA_TYPE, SkamRendererElement };
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import {
2
+ SKAM_XML_MEDIA_TYPE,
3
+ SkamRendererElement
4
+ } from "./chunk-NXVDX5VV.js";
5
+ export {
6
+ SKAM_XML_MEDIA_TYPE,
7
+ SkamRendererElement
8
+ };
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@kanbun-skam/skam-web-component",
3
+ "version": "0.1.0",
4
+ "description": "SKAM Web Component - <skam-renderer> カスタムエレメント",
5
+ "type": "module",
6
+ "sideEffects": [
7
+ "./dist/auto.js",
8
+ "./src/auto.ts"
9
+ ],
10
+ "exports": {
11
+ ".": {
12
+ "import": "./dist/index.js",
13
+ "types": "./dist/index.d.ts"
14
+ },
15
+ "./auto": {
16
+ "import": "./dist/auto.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "kanbun",
24
+ "漢文",
25
+ "annotation",
26
+ "skam",
27
+ "web-component",
28
+ "custom-element"
29
+ ],
30
+ "author": "berlysia",
31
+ "license": "MIT",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/berlysia/kanbun-annotation.git",
35
+ "directory": "packages/skam-web-component"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/berlysia/kanbun-annotation/issues"
39
+ },
40
+ "homepage": "https://github.com/berlysia/kanbun-annotation/tree/master/packages/skam-web-component#readme",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "node": ">=18.0.0"
46
+ },
47
+ "dependencies": {
48
+ "@kanbun-skam/skam-html-renderer": "0.1.0",
49
+ "@kanbun-skam/skam-xml-parser": "0.1.0"
50
+ },
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "typecheck": "tsgo --noEmit",
54
+ "lint": "oxlint src",
55
+ "test": "vitest",
56
+ "test:run": "vitest run"
57
+ }
58
+ }