ampless 1.0.0-alpha.46 → 1.0.0-alpha.48
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/dist/index.d.ts +67 -1
- package/docs/plugin-author-guide.ja.md +153 -0
- package/docs/plugin-author-guide.md +226 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1014,6 +1014,30 @@ interface TiptapRenderNode {
|
|
|
1014
1014
|
*/
|
|
1015
1015
|
type TiptapNodeToMarkdown = (node: TiptapRenderNode) => string | null;
|
|
1016
1016
|
type TiptapNodeMarkdownAdapters = Readonly<Record<string, TiptapNodeToMarkdown>>;
|
|
1017
|
+
/**
|
|
1018
|
+
* Adapter that converts a single tiptap node to its canonical HTML placeholder
|
|
1019
|
+
* div form. Plugins that ship an embed node (e.g. amplessYoutube →
|
|
1020
|
+
* `<div data-ampless-youtube data-video-id="...">…</div>`) export a map from
|
|
1021
|
+
* nodeType to adapter from their `./editor` module (named export
|
|
1022
|
+
* `tiptapNodeToHtml`); `update-ampless` wires the map into
|
|
1023
|
+
* `installAdminTiptapNodeHtml` so the admin's `tiptap → html` format switch
|
|
1024
|
+
* can losslessly serialise the embed to the canonical placeholder div form.
|
|
1025
|
+
*
|
|
1026
|
+
* The canonical div is what tiptap's `Node.renderHTML` emits and what the
|
|
1027
|
+
* `Node.parseHTML` `tag: 'div[data-ampless-*]'` rule restores from. It is an
|
|
1028
|
+
* admin format-switch interchange form; public rendering expands embeds from
|
|
1029
|
+
* the `tiptap` / `markdown` walkers, while `format: 'html'` preserves the div
|
|
1030
|
+
* literally.
|
|
1031
|
+
*
|
|
1032
|
+
* The `markdown → html` direction is a 2-hop via `generateJSON(...)` so
|
|
1033
|
+
* plugins only need to export the `tiptap → html` adapter; the markdown side
|
|
1034
|
+
* reuses it via tiptap's parseHTML rules (no duplicate logic).
|
|
1035
|
+
*
|
|
1036
|
+
* Return `null` (or simply omit the nodeType from the map) to fall through to
|
|
1037
|
+
* the runtime's default HTML switch.
|
|
1038
|
+
*/
|
|
1039
|
+
type TiptapNodeToHtml = (node: TiptapRenderNode) => string | null;
|
|
1040
|
+
type TiptapNodeHtmlAdapters = Readonly<Record<string, TiptapNodeToHtml>>;
|
|
1017
1041
|
/**
|
|
1018
1042
|
* Match object passed to a `contentFields` `markdown-url` renderer. The
|
|
1019
1043
|
* runtime walks the markdown body via `marked.lexer`, tests the trimmed
|
|
@@ -1048,6 +1072,48 @@ type ContentFieldRenderer = {
|
|
|
1048
1072
|
kind: 'tiptap';
|
|
1049
1073
|
nodeType: string;
|
|
1050
1074
|
render(node: TiptapRenderNode, ctx: PluginPublicRenderContext): ReactNode;
|
|
1075
|
+
/**
|
|
1076
|
+
* Opt-in: expand this node's canonical placeholder div when it
|
|
1077
|
+
* appears in a `format: 'html'` post body on public render.
|
|
1078
|
+
*
|
|
1079
|
+
* The admin's `tiptap → html` format switch serialises an embed
|
|
1080
|
+
* node (e.g. `amplessYoutube`) to its canonical placeholder div
|
|
1081
|
+
* (`<div data-ampless-youtube data-video-id="…"><a href="…">…</a></div>`,
|
|
1082
|
+
* via the `tiptapNodeToHtml` adapter). Without `htmlPlaceholder`,
|
|
1083
|
+
* the public renderer of a `format: 'html'` post emits that div
|
|
1084
|
+
* literally — the placeholder shows as a bare div + link instead
|
|
1085
|
+
* of the live embed. (This was the documented limitation from the
|
|
1086
|
+
* canonical-html-embed work; declaring `htmlPlaceholder` resolves
|
|
1087
|
+
* it.)
|
|
1088
|
+
*
|
|
1089
|
+
* When declared, the runtime's public html walker finds each
|
|
1090
|
+
* **top-level** element carrying `flagAttr`, builds a
|
|
1091
|
+
* `TiptapRenderNode { type: nodeType, attrs: attrsFromElement(attribs) }`,
|
|
1092
|
+
* and calls this same `render` — so the `tiptap`, `markdown`, and
|
|
1093
|
+
* `html` formats all reach one renderer (no per-format divergence).
|
|
1094
|
+
*
|
|
1095
|
+
* - `flagAttr` is the marker attribute (e.g.
|
|
1096
|
+
* `'data-ampless-youtube'`). It is **matched case-insensitively**:
|
|
1097
|
+
* the runtime lowercases it at registration because htmlparser2
|
|
1098
|
+
* lowercases HTML attribute names while parsing, so declaring
|
|
1099
|
+
* `'data-My-Embed'` still matches `<div data-my-embed>` /
|
|
1100
|
+
* `<div DATA-MY-EMBED>`.
|
|
1101
|
+
* - `attrsFromElement` converts the div's HTML attributes (already
|
|
1102
|
+
* lowercased by the parser) into the tiptap node `attrs` that
|
|
1103
|
+
* `render` expects, with the correct types — e.g. a
|
|
1104
|
+
* `data-start="30"` string must become the `number 30` that
|
|
1105
|
+
* `render` reads.
|
|
1106
|
+
*
|
|
1107
|
+
* Only top-level placeholders expand; divs nested inside
|
|
1108
|
+
* `<blockquote>` / `<li>` / etc. stay literal. If `attrsFromElement`
|
|
1109
|
+
* or `render` throws, the runtime warns and falls back to the raw
|
|
1110
|
+
* placeholder slice (the embedded link stays clickable) rather than
|
|
1111
|
+
* dropping the engineer-authored content.
|
|
1112
|
+
*/
|
|
1113
|
+
htmlPlaceholder?: {
|
|
1114
|
+
flagAttr: string;
|
|
1115
|
+
attrsFromElement(attribs: Readonly<Record<string, string>>): Record<string, unknown>;
|
|
1116
|
+
};
|
|
1051
1117
|
} | {
|
|
1052
1118
|
kind: 'markdown-url';
|
|
1053
1119
|
pattern: RegExp;
|
|
@@ -1901,4 +1967,4 @@ declare function pickDefaultEntrypoint(files: readonly {
|
|
|
1901
1967
|
|
|
1902
1968
|
declare const VERSION = "0.0.1";
|
|
1903
1969
|
|
|
1904
|
-
export { type AmplessEvent, type AmplessPlugin, type AuthContext, type BundleExtractResult, type CacheConfig, type CacheStrategy, type Config, type ContentEventPayload, type ContentEventType, type ContentFieldRenderer, type ContentFormat, type ContentTypeDefinition, type CreatePostInput, DEFAULT_ENTRYPOINT, type DateFormat, type EventPayloadOf, type EventType, type ExtractedFile, type FieldDefinition, type FieldType, type HistoryConfig, type ImageDisplay, type KvItem, type KvStore, type LinkListItem, type ListOptions, type ListPostHistoryOptions, type LocalizedString, MAX_BUNDLE_BYTES, type MarkdownEmbedMatch, type Media, type MediaEventPayload, type MediaEventType, type MediaMetadata, type MediaProcessingDefaults, type OgImageConfig, type OgImageFont, type OgImageRenderContext, PLUGIN_KEY_PATTERN, type Page, type PluginBooleanField, type PluginCapability, type PluginCodeField, type PluginEventHandler, type PluginHookResult, type PluginJsonField, type PluginMetadata, type PluginNumberField, type PluginPackageManifest, type PluginPublicRenderContext, type PluginRepeatableField, type PluginRepeatableSubField, type PluginRuntimeContext, type PluginSecretField, type PluginSelectField, type PluginSettingField, type PluginSettingsManifest, type PluginTextField, type PluginTextareaField, type PluginUninstallContext, type PluginUrlField, type Post, type PostIndexEventPayload, type PostIndexEventType, type PostMetadata, type PostRevision, type PostRevisionConnection, type PostStatus, type PostsProvider, type PublicBodyDescriptor, type PublicHeadDescriptor, type PublicPostBodyDescriptor, type PublicPostHtmlDescriptor, type PublicPostHtmlPosition, type PublicPostScriptDescriptor, type Role, SITE_CONFIG_PK, type ScriptStrategy, type SiteSettingsEventPayload, type SiteSettingsEventType, type StaticPostBody, type StaticPostFileMeta, type StreamEventName, TEXT_EXTENSIONS, type ThemeColorField, type ThemeField, type ThemeFieldType, type ThemeFontFamilyField, type ThemeImageField, type ThemeLengthField, type ThemeLinkListField, type ThemeManifest, type ThemeModule, type ThemeRouteContext, type ThemeSelectField, type ThemeTextField, type TiptapNodeMarkdownAdapters, type TiptapNodeToMarkdown, type TiptapRenderNode, type TrustLevel, type TrustedPluginRuntimeContext, VERSION, type ValidationIssue, bundlePrefix, createPost, decodeAwsJson, defineConfig, definePlugin, defineSchema, defineTheme, defineThemeModule, deletePost, deleteSiteSetting, detectContentEvents, encodeAwsJson, escapeXml, extractFirstImageUrl, findAbsolutePathRefs, flattenSettings, formatColorPair, formatDate, formatPublicAssetUrl, getKvStore, getPost, getPostById, getSiteSetting, hasKvStore, hasPostsProvider, isTagListUrl, isValidPluginKey, listPostHistory, listPosts, listSiteSettings, mimeTypeFor, parseColorPair, parseLinkList, pickDefaultEntrypoint, resolveLocalized, resolvePluginSettings, resolveThemeValues, setKvStore, setPostsProvider, setSiteSetting, stringifyLinkList, stripCommonPrefix, themeSettingKey, unflattenSettings, updatePost, validateBundle, validateBundlePath, validatePluginSettingValue, validatePublicAssetKey, validateThemeValue };
|
|
1970
|
+
export { type AmplessEvent, type AmplessPlugin, type AuthContext, type BundleExtractResult, type CacheConfig, type CacheStrategy, type Config, type ContentEventPayload, type ContentEventType, type ContentFieldRenderer, type ContentFormat, type ContentTypeDefinition, type CreatePostInput, DEFAULT_ENTRYPOINT, type DateFormat, type EventPayloadOf, type EventType, type ExtractedFile, type FieldDefinition, type FieldType, type HistoryConfig, type ImageDisplay, type KvItem, type KvStore, type LinkListItem, type ListOptions, type ListPostHistoryOptions, type LocalizedString, MAX_BUNDLE_BYTES, type MarkdownEmbedMatch, type Media, type MediaEventPayload, type MediaEventType, type MediaMetadata, type MediaProcessingDefaults, type OgImageConfig, type OgImageFont, type OgImageRenderContext, PLUGIN_KEY_PATTERN, type Page, type PluginBooleanField, type PluginCapability, type PluginCodeField, type PluginEventHandler, type PluginHookResult, type PluginJsonField, type PluginMetadata, type PluginNumberField, type PluginPackageManifest, type PluginPublicRenderContext, type PluginRepeatableField, type PluginRepeatableSubField, type PluginRuntimeContext, type PluginSecretField, type PluginSelectField, type PluginSettingField, type PluginSettingsManifest, type PluginTextField, type PluginTextareaField, type PluginUninstallContext, type PluginUrlField, type Post, type PostIndexEventPayload, type PostIndexEventType, type PostMetadata, type PostRevision, type PostRevisionConnection, type PostStatus, type PostsProvider, type PublicBodyDescriptor, type PublicHeadDescriptor, type PublicPostBodyDescriptor, type PublicPostHtmlDescriptor, type PublicPostHtmlPosition, type PublicPostScriptDescriptor, type Role, SITE_CONFIG_PK, type ScriptStrategy, type SiteSettingsEventPayload, type SiteSettingsEventType, type StaticPostBody, type StaticPostFileMeta, type StreamEventName, TEXT_EXTENSIONS, type ThemeColorField, type ThemeField, type ThemeFieldType, type ThemeFontFamilyField, type ThemeImageField, type ThemeLengthField, type ThemeLinkListField, type ThemeManifest, type ThemeModule, type ThemeRouteContext, type ThemeSelectField, type ThemeTextField, type TiptapNodeHtmlAdapters, type TiptapNodeMarkdownAdapters, type TiptapNodeToHtml, type TiptapNodeToMarkdown, type TiptapRenderNode, type TrustLevel, type TrustedPluginRuntimeContext, VERSION, type ValidationIssue, bundlePrefix, createPost, decodeAwsJson, defineConfig, definePlugin, defineSchema, defineTheme, defineThemeModule, deletePost, deleteSiteSetting, detectContentEvents, encodeAwsJson, escapeXml, extractFirstImageUrl, findAbsolutePathRefs, flattenSettings, formatColorPair, formatDate, formatPublicAssetUrl, getKvStore, getPost, getPostById, getSiteSetting, hasKvStore, hasPostsProvider, isTagListUrl, isValidPluginKey, listPostHistory, listPosts, listSiteSettings, mimeTypeFor, parseColorPair, parseLinkList, pickDefaultEntrypoint, resolveLocalized, resolvePluginSettings, resolveThemeValues, setKvStore, setPostsProvider, setSiteSetting, stringifyLinkList, stripCommonPrefix, themeSettingKey, unflattenSettings, updatePost, validateBundle, validateBundlePath, validatePluginSettingValue, validatePublicAssetKey, validateThemeValue };
|
|
@@ -848,6 +848,159 @@ export default createAdminLayout(admin, { editorBootstrap: EditorBootstrap })
|
|
|
848
848
|
|
|
849
849
|
`installAdminEditorExtensions` は idempotent で、render 時に client component 内で呼ばれる。admin の `<TiptapEditor>` は毎回 render 時に登録済みリストを built-in extensions の末尾に spread する。
|
|
850
850
|
|
|
851
|
+
`update-ampless` が生成する `_editor-bootstrap.tsx` は extensions、markdown アダプター、html アダプターの3つの install 呼び出しを含む:
|
|
852
|
+
|
|
853
|
+
```tsx
|
|
854
|
+
// app/(admin)/admin/_editor-bootstrap.tsx (AUTO-GENERATED — 編集不可)
|
|
855
|
+
'use client'
|
|
856
|
+
// AUTO-GENERATED by `npm run update-ampless`. Do not edit ...
|
|
857
|
+
import { installAdminEditorExtensions, installAdminTiptapNodeMarkdown, installAdminTiptapNodeHtml } from '@ampless/admin/editor'
|
|
858
|
+
import * as __ampless_plugin_x_embed_editor from '@ampless/plugin-x-embed/editor'
|
|
859
|
+
import * as __ampless_plugin_youtube_editor from '@ampless/plugin-youtube/editor'
|
|
860
|
+
|
|
861
|
+
export function EditorBootstrap({ children }: { children: React.ReactNode }) {
|
|
862
|
+
installAdminEditorExtensions([
|
|
863
|
+
__ampless_plugin_x_embed_editor.editorExtension,
|
|
864
|
+
__ampless_plugin_youtube_editor.editorExtension,
|
|
865
|
+
])
|
|
866
|
+
installAdminTiptapNodeMarkdown([
|
|
867
|
+
__ampless_plugin_x_embed_editor.tiptapNodeToMarkdown ?? {},
|
|
868
|
+
__ampless_plugin_youtube_editor.tiptapNodeToMarkdown ?? {},
|
|
869
|
+
])
|
|
870
|
+
installAdminTiptapNodeHtml([
|
|
871
|
+
__ampless_plugin_x_embed_editor.tiptapNodeToHtml ?? {},
|
|
872
|
+
__ampless_plugin_youtube_editor.tiptapNodeToHtml ?? {},
|
|
873
|
+
])
|
|
874
|
+
return <>{children}</>
|
|
875
|
+
}
|
|
876
|
+
```
|
|
877
|
+
|
|
878
|
+
### フォーマット切り替えの可逆アダプター(`tiptapNodeToMarkdown` + `tiptapNodeToHtml`)
|
|
879
|
+
|
|
880
|
+
operator が admin UI でポストのフォーマットを切り替える場合(例: `tiptap → markdown`、`tiptap → html`)、admin はボディコンテンツを変換する必要がある。通常の prose node は tiptap の built-in レンダラーで処理されるが、**atom node**(`amplessYoutube` のような embed ブロック)は子要素を持たず、children が空のまま fallthrough し、embed が無音で消えてしまう。
|
|
881
|
+
|
|
882
|
+
2 つのアダプターで両方向を修正する:
|
|
883
|
+
|
|
884
|
+
| アダプター | 方向 | 出力 |
|
|
885
|
+
| --------------------- | --------------------------------- | ---- |
|
|
886
|
+
| `tiptapNodeToMarkdown`| `tiptap → markdown` | bare URL 行(例: `https://youtu.be/<id>`) |
|
|
887
|
+
| `tiptapNodeToHtml` | `tiptap → html`、`markdown → html`| 正規プレースホルダー div |
|
|
888
|
+
|
|
889
|
+
フォーマット切替で扱う 3 種類の正規 body 表現:
|
|
890
|
+
|
|
891
|
+
| フォーマット | 正規形 |
|
|
892
|
+
| ------------ | ------ |
|
|
893
|
+
| tiptap | `{ type: 'amplessYoutube', attrs: { videoId, start } }` Node |
|
|
894
|
+
| markdown | bare `https://youtu.be/<id>` URL 行 |
|
|
895
|
+
| html | `<div data-ampless-youtube data-video-id="<id>" …>…</div>` |
|
|
896
|
+
|
|
897
|
+
プレースホルダー div は **admin format-switch 相互運用専用**の正規 HTML 形式: `Node.renderHTML` が emit し、`Node.parseHTML` の `tag: 'div[data-ampless-*]'` rule が復元することで、admin での `tiptap ↔ markdown ↔ html` 切替が embed を保ったまま round-trip できる。
|
|
898
|
+
|
|
899
|
+
**`format: 'html'` の公開描画は、plugin が `htmlPlaceholder` を宣言していればプレースホルダーを展開する。** 公開描画の 3 経路すべてが同じ `contentFields.tiptap` renderer に到達する: tiptap 投稿は React walker が `contentFields.tiptap` registry を参照(= `amplessYoutube` Node を実際の iframe に変換)、markdown 投稿は markdown walker が `contentFields.markdownUrl` を参照(= bare URL paragraph を実際の iframe に変換)、html 投稿は **public html walker** が `contentFields.htmlPlaceholder` を参照(= top-level の `<div data-ampless-youtube …>` プレースホルダーを実際の iframe に変換)。上の `tiptapNodeToHtml` アダプターは **admin format-switch** の交換形式のみを司り、その形式を公開描画時に展開させるのは `htmlPlaceholder` の宣言である(契約は下記の `htmlPlaceholder` セクションを参照)。`publicHtmlForPost` は従来どおり `beforeContent` / `afterContent` slot のみ提供する capability であり、body を変換しない。
|
|
900
|
+
|
|
901
|
+
embed node を持つが `htmlPlaceholder` を**宣言しない** plugin は従来挙動を維持する: `format: 'html'` 投稿の公開描画ではプレースホルダー div がリテラルにそのまま出力される(内側の正規 URL link は clickable なので graceful に degrade する)。その場合に iframe を得るには `tiptap` または `markdown` 形式で保存する。
|
|
902
|
+
|
|
903
|
+
#### アダプターの契約
|
|
904
|
+
|
|
905
|
+
両アダプターは同じシグネチャを持つ:
|
|
906
|
+
|
|
907
|
+
```ts
|
|
908
|
+
(node: TiptapRenderNode) => string | null
|
|
909
|
+
```
|
|
910
|
+
|
|
911
|
+
**文字列**(空文字 `''` も含む)を返すと、その出力を使う。**`null`** を返すとデフォルトの switch へ fallthrough する(対応しない node や video id が欠損している場合などに使う)。
|
|
912
|
+
|
|
913
|
+
```ts
|
|
914
|
+
// packages/plugin-youtube/src/editor.tsx
|
|
915
|
+
import type { TiptapNodeMarkdownAdapters, TiptapNodeHtmlAdapters } from 'ampless'
|
|
916
|
+
|
|
917
|
+
export const tiptapNodeToMarkdown: TiptapNodeMarkdownAdapters = {
|
|
918
|
+
amplessYoutube: (node) => {
|
|
919
|
+
const videoId = String(node.attrs?.videoId ?? '').trim()
|
|
920
|
+
if (!videoId) return null // fallthrough
|
|
921
|
+
return `https://youtu.be/${videoId}`
|
|
922
|
+
},
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
export const tiptapNodeToHtml: TiptapNodeHtmlAdapters = {
|
|
926
|
+
amplessYoutube: (node) => {
|
|
927
|
+
const videoId = String(node.attrs?.videoId ?? '').trim()
|
|
928
|
+
if (!videoId) return null // fallthrough
|
|
929
|
+
const attrs = placeholderAttrs(node.attrs ?? {})
|
|
930
|
+
// 内側のコンテンツは editor 用視覚 label (`<span>YouTube: id</span>`、
|
|
931
|
+
// Node.renderHTML 専用) ではなく URL link にする。`format: 'html'` の
|
|
932
|
+
// 公開描画ではこの body をリテラル表示するため editor 用 label が漏れる
|
|
933
|
+
// のを防ぐ。viewer 側で iframe 展開されない場合でもクリック可能な link が
|
|
934
|
+
// 残り graceful degradation する。markdown 正規形 (bare URL line) と
|
|
935
|
+
// 対応する形式。parseHTML は `data-video-id` 属性を読むため内側コンテンツは
|
|
936
|
+
// round-trip と無関係。
|
|
937
|
+
const url = `https://youtu.be/${videoId}`
|
|
938
|
+
return `<div ${attrsToHtmlString(attrs)}><a href="${escapeAttr(url)}">${escapeAttr(url)}</a></div>`
|
|
939
|
+
},
|
|
940
|
+
}
|
|
941
|
+
```
|
|
942
|
+
|
|
943
|
+
#### 配線
|
|
944
|
+
|
|
945
|
+
`update-ampless` が各プラグインの `./editor` モジュールから `tiptapNodeToMarkdown` と `tiptapNodeToHtml` の named export を読み取り(namespace import `* as` 経由)、両方の install に自動で配線する。**手動での配線は不要。** プラグインがいずれかのマップを export しない場合、生成ファイルの `?? {}` fallback が no-op になる。
|
|
946
|
+
|
|
947
|
+
#### `markdown → html` 2-hop
|
|
948
|
+
|
|
949
|
+
`markdown → html` の方向は `tiptapNodeToHtml` アダプターを 2-hop 経由で再利用する:
|
|
950
|
+
|
|
951
|
+
1. `markdownToHtml(body)` — marked が markdown を HTML に変換。bare URL 行は `<p><a href="URL">URL</a></p>` になる。
|
|
952
|
+
2. `generateJSON(html, extensions)` — tiptap が HTML を parse。プラグインの `Node.parseHTML` `tag: 'p'` rule が bare URL の paragraph を embed Node に昇格する。
|
|
953
|
+
3. `tiptapToHtml(doc, { nodeAdapters })` — html アダプターが embed Node をプレースホルダー div に serialize する。
|
|
954
|
+
|
|
955
|
+
つまりプラグインは `tiptap → html` アダプターを 1 つ export するだけでよく、`markdown → html` の方向は tiptap の parse rule を通して自動的に再利用される。**重複ロジックは不要。**
|
|
956
|
+
|
|
957
|
+
#### Public html walker: `htmlPlaceholder`
|
|
958
|
+
|
|
959
|
+
`format: 'html'` 投稿のプレースホルダー div を公開ページで実 embed として描画するには、既存の `contentFields` の `tiptap` entry に **`htmlPlaceholder`** 宣言を追加する。**新しい renderer は書かない** — walker は tiptap entry が既に使う `render(node, ctx)` をそのまま呼ぶので、3 形式(tiptap / markdown / html)すべてが 1 個の renderer に到達し、描画が divergence しない。
|
|
960
|
+
|
|
961
|
+
```ts
|
|
962
|
+
// packages/plugin-youtube/src/index.tsx
|
|
963
|
+
contentFields: [
|
|
964
|
+
{
|
|
965
|
+
kind: 'tiptap',
|
|
966
|
+
nodeType: 'amplessYoutube',
|
|
967
|
+
render: (node) => {
|
|
968
|
+
const videoId = String(node.attrs?.videoId ?? '')
|
|
969
|
+
const startRaw = node.attrs?.start
|
|
970
|
+
const start =
|
|
971
|
+
typeof startRaw === 'number' && Number.isFinite(startRaw) ? startRaw : undefined
|
|
972
|
+
return <YouTubeEmbed videoId={videoId} start={start} />
|
|
973
|
+
},
|
|
974
|
+
htmlPlaceholder: {
|
|
975
|
+
// top-level プレースホルダー div を識別する marker attribute。
|
|
976
|
+
flagAttr: 'data-ampless-youtube',
|
|
977
|
+
// div の HTML 属性を render が期待する tiptap node attrs に変換する
|
|
978
|
+
// — 型も正しく。walker は型を知らないのでここで変換する
|
|
979
|
+
// (例: data-start string → number)。
|
|
980
|
+
attrsFromElement: (attribs) => {
|
|
981
|
+
const start = Number(attribs['data-start'])
|
|
982
|
+
return {
|
|
983
|
+
videoId: attribs['data-video-id'] ?? '',
|
|
984
|
+
start: Number.isFinite(start) ? start : undefined,
|
|
985
|
+
}
|
|
986
|
+
},
|
|
987
|
+
},
|
|
988
|
+
},
|
|
989
|
+
// …markdown-url entry は変更なし…
|
|
990
|
+
]
|
|
991
|
+
```
|
|
992
|
+
|
|
993
|
+
`format: 'html'` 投稿の公開描画時、runtime は body を server-side で parse し(`htmlparser2`)、`flagAttr` を持つ **top-level** element ごとに `{ type: nodeType, attrs: attrsFromElement(attribs) }` node を組んで `render(node, ctx)` を呼ぶ。それ以外はすべて **元文字列の slice**(byte 単位で完全保存、DOM の再シリアライズなし)として passthrough する。
|
|
994
|
+
|
|
995
|
+
把握すべき制約:
|
|
996
|
+
|
|
997
|
+
- **top-level のみ。** `<blockquote>` / `<li>` 等の内側に nest したプレースホルダー div はリテラルのまま — editor の body-level-only な `parseHTML` fallback と整合。展開されるのは depth-0 の element のみ。
|
|
998
|
+
- **`flagAttr` は case-insensitive で照合される。** htmlparser2 は parse 時に HTML 属性名を小文字化し、runtime は登録時に `flagAttr` を小文字化するため、`<div DATA-AMPLESS-YOUTUBE …>` も `<div data-ampless-youtube …>` も展開される。`flagAttr` は任意の属性名でよい — site-local plugin は `data-my-embed` を使える。固定の `data-ampless` prefix 要件はない。
|
|
999
|
+
- **graceful degradation。** `attrsFromElement` または `render` が throw した場合、runtime は `console.warn` を出力し **元のプレースホルダー slice**(内側の正規 URL link は clickable のまま)に fallback する。engineer が書いた本文を消さない。
|
|
1000
|
+
- **page-level script。** embed が third-party script を要する場合(例: x.com の `widgets.js`)、`publicPostScript` / 検知ヘルパーもプレースホルダー形式を認識する必要がある。`plugin-x-embed` の `hasTweetIn` は `format: 'html'` body 内で `twitter-tweet` と `data-ampless-tweet` の両方を match させ、展開された blockquote を hydrate するため widgets.js を注入する。
|
|
1001
|
+
|
|
1002
|
+
**wrapper 境界の変化。** プレースホルダーを含まない `format: 'html'` 投稿は単一の wrapper `<div>` として出力される(fast path — 従来の raw passthrough と markup 完全一致)。プレースホルダーを**含む**投稿は **複数の wrapper div と React embed の兄弟列が交互に並ぶ**構造になる: 各 raw chunk 内の bytes は正確に保存されるが、wrapper 境界は移動する。body 全体を 1 個の wrapper で囲む前提の direct-child / adjacent-sibling CSS selector は従来と同じには効かない。これは embed を in-place 展開するための許容トレードオフ。
|
|
1003
|
+
|
|
851
1004
|
### markdown → tiptap の復元
|
|
852
1005
|
|
|
853
1006
|
editor Node が markdown へ bare URL line として serialise される場合、逆方向の復元は paste rule ではなく `Node.parseHTML()` で扱う必要がある。admin の `markdown → tiptap` format switch は、まず markdown を HTML に変換する。GFM autolink により bare URL line は `<p><a href="https://...">https://...</a></p>` になり、その HTML を tiptap が document として parse する。paste rule は user paste / typing event 用なので、この HTML parse 経路では発火しない。
|
|
@@ -1104,6 +1104,232 @@ export default createAdminLayout(admin, { editorBootstrap: EditorBootstrap })
|
|
|
1104
1104
|
inside a client component. The admin's `<TiptapEditor>` spreads the
|
|
1105
1105
|
registered list onto its built-in extensions on every render.
|
|
1106
1106
|
|
|
1107
|
+
The `_editor-bootstrap.tsx` generated by `update-ampless` wires three
|
|
1108
|
+
install calls — extensions, markdown adapters, and html adapters:
|
|
1109
|
+
|
|
1110
|
+
```tsx
|
|
1111
|
+
// app/(admin)/admin/_editor-bootstrap.tsx (AUTO-GENERATED — do not edit)
|
|
1112
|
+
'use client'
|
|
1113
|
+
// AUTO-GENERATED by `npm run update-ampless`. Do not edit ...
|
|
1114
|
+
import { installAdminEditorExtensions, installAdminTiptapNodeMarkdown, installAdminTiptapNodeHtml } from '@ampless/admin/editor'
|
|
1115
|
+
import * as __ampless_plugin_x_embed_editor from '@ampless/plugin-x-embed/editor'
|
|
1116
|
+
import * as __ampless_plugin_youtube_editor from '@ampless/plugin-youtube/editor'
|
|
1117
|
+
|
|
1118
|
+
export function EditorBootstrap({ children }: { children: React.ReactNode }) {
|
|
1119
|
+
installAdminEditorExtensions([
|
|
1120
|
+
__ampless_plugin_x_embed_editor.editorExtension,
|
|
1121
|
+
__ampless_plugin_youtube_editor.editorExtension,
|
|
1122
|
+
])
|
|
1123
|
+
installAdminTiptapNodeMarkdown([
|
|
1124
|
+
__ampless_plugin_x_embed_editor.tiptapNodeToMarkdown ?? {},
|
|
1125
|
+
__ampless_plugin_youtube_editor.tiptapNodeToMarkdown ?? {},
|
|
1126
|
+
])
|
|
1127
|
+
installAdminTiptapNodeHtml([
|
|
1128
|
+
__ampless_plugin_x_embed_editor.tiptapNodeToHtml ?? {},
|
|
1129
|
+
__ampless_plugin_youtube_editor.tiptapNodeToHtml ?? {},
|
|
1130
|
+
])
|
|
1131
|
+
return <>{children}</>
|
|
1132
|
+
}
|
|
1133
|
+
```
|
|
1134
|
+
|
|
1135
|
+
### Lossless format-switch adapters (`tiptapNodeToMarkdown` + `tiptapNodeToHtml`)
|
|
1136
|
+
|
|
1137
|
+
When the operator switches the post format in the admin UI (e.g. `tiptap →
|
|
1138
|
+
markdown` or `tiptap → html`), the admin must convert the body content. For
|
|
1139
|
+
standard prose nodes tiptap's built-in renderers handle this, but **atom
|
|
1140
|
+
nodes** (embed blocks like `amplessYoutube`) have no children — they fall
|
|
1141
|
+
through with empty output, silently dropping the embed.
|
|
1142
|
+
|
|
1143
|
+
Two adapters fix both directions:
|
|
1144
|
+
|
|
1145
|
+
| Adapter | Direction | Output |
|
|
1146
|
+
| --------------------- | --------------------------------- | ------ |
|
|
1147
|
+
| `tiptapNodeToMarkdown`| `tiptap → markdown` | bare URL line (e.g. `https://youtu.be/<id>`) |
|
|
1148
|
+
| `tiptapNodeToHtml` | `tiptap → html`, `markdown → html`| canonical placeholder div |
|
|
1149
|
+
|
|
1150
|
+
The three canonical body representations across format-switch are:
|
|
1151
|
+
|
|
1152
|
+
| Format | Canonical form |
|
|
1153
|
+
| -------- | -------------- |
|
|
1154
|
+
| tiptap | `{ type: 'amplessYoutube', attrs: { videoId, start } }` Node |
|
|
1155
|
+
| markdown | bare `https://youtu.be/<id>` URL line |
|
|
1156
|
+
| html | `<div data-ampless-youtube data-video-id="<id>" …>…</div>` |
|
|
1157
|
+
|
|
1158
|
+
The placeholder div is the canonical HTML form for **admin format-switch
|
|
1159
|
+
interop only**: it is what `Node.renderHTML` emits, and what
|
|
1160
|
+
`Node.parseHTML`'s `tag: 'div[data-ampless-*]'` rule restores from, so
|
|
1161
|
+
that switching `tiptap ↔ markdown ↔ html` in the admin preserves embeds
|
|
1162
|
+
losslessly.
|
|
1163
|
+
|
|
1164
|
+
**Public render of `format: 'html'` posts expands the placeholder when
|
|
1165
|
+
the plugin declares `htmlPlaceholder`.** All three public render paths
|
|
1166
|
+
reach the same `contentFields.tiptap` renderer: tiptap posts go through
|
|
1167
|
+
the React walker that consults the `contentFields.tiptap` registry
|
|
1168
|
+
(= real iframe for `amplessYoutube` Nodes); markdown posts go through the
|
|
1169
|
+
markdown walker that consults `contentFields.markdownUrl` (= real iframe
|
|
1170
|
+
for bare URL paragraphs); html posts go through the **public html walker**
|
|
1171
|
+
that consults `contentFields.htmlPlaceholder` (= real iframe for
|
|
1172
|
+
top-level `<div data-ampless-youtube …>` placeholders). The
|
|
1173
|
+
`tiptapNodeToHtml` adapter above only governs the **admin format-switch**
|
|
1174
|
+
interchange form — declaring `htmlPlaceholder` is what makes the public
|
|
1175
|
+
html walker expand that form on render. (See the dedicated
|
|
1176
|
+
`htmlPlaceholder` section below for the contract.) `publicHtmlForPost`
|
|
1177
|
+
still only emits `beforeContent` / `afterContent` slots and does not
|
|
1178
|
+
transform the body.
|
|
1179
|
+
|
|
1180
|
+
A plugin that ships an embed node but does **not** declare
|
|
1181
|
+
`htmlPlaceholder` keeps the old behaviour: the placeholder div is shipped
|
|
1182
|
+
literally on public render of `format: 'html'` posts (the inner canonical
|
|
1183
|
+
URL link is still clickable, so it degrades gracefully). Save as `tiptap`
|
|
1184
|
+
or `markdown` to get the iframe in that case.
|
|
1185
|
+
|
|
1186
|
+
#### Adapter contract
|
|
1187
|
+
|
|
1188
|
+
Both adapters have the same signature:
|
|
1189
|
+
|
|
1190
|
+
```ts
|
|
1191
|
+
(node: TiptapRenderNode) => string | null
|
|
1192
|
+
```
|
|
1193
|
+
|
|
1194
|
+
Return a **string** (including empty string `''`) to use your output.
|
|
1195
|
+
Return **`null`** to fall through to the default switch (useful for nodes
|
|
1196
|
+
you don't handle or for degenerate inputs like a missing video id).
|
|
1197
|
+
|
|
1198
|
+
```ts
|
|
1199
|
+
// packages/plugin-youtube/src/editor.tsx
|
|
1200
|
+
import type { TiptapNodeMarkdownAdapters, TiptapNodeHtmlAdapters } from 'ampless'
|
|
1201
|
+
|
|
1202
|
+
export const tiptapNodeToMarkdown: TiptapNodeMarkdownAdapters = {
|
|
1203
|
+
amplessYoutube: (node) => {
|
|
1204
|
+
const videoId = String(node.attrs?.videoId ?? '').trim()
|
|
1205
|
+
if (!videoId) return null // fall through
|
|
1206
|
+
return `https://youtu.be/${videoId}`
|
|
1207
|
+
},
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
export const tiptapNodeToHtml: TiptapNodeHtmlAdapters = {
|
|
1211
|
+
amplessYoutube: (node) => {
|
|
1212
|
+
const videoId = String(node.attrs?.videoId ?? '').trim()
|
|
1213
|
+
if (!videoId) return null // fall through
|
|
1214
|
+
// placeholderAttrs() is a plugin-local helper that returns the same
|
|
1215
|
+
// attribute dict used by Node.renderHTML — single source of truth.
|
|
1216
|
+
const attrs = placeholderAttrs(node.attrs ?? {})
|
|
1217
|
+
// Inner content is the canonical URL as a clickable link, not the
|
|
1218
|
+
// editor's visual label `<span>YouTube: id</span>`. Public render of
|
|
1219
|
+
// `format: 'html'` posts shows this content literally; an editor
|
|
1220
|
+
// label would leak. The URL link gracefully degrades — viewers
|
|
1221
|
+
// without iframe expansion still get a clickable link, and it
|
|
1222
|
+
// mirrors the markdown canonical form. parseHTML reads the
|
|
1223
|
+
// `data-video-id` attribute, so the inner content is irrelevant
|
|
1224
|
+
// for round-trip.
|
|
1225
|
+
const url = `https://youtu.be/${videoId}`
|
|
1226
|
+
return `<div ${attrsToHtmlString(attrs)}><a href="${escapeAttr(url)}">${escapeAttr(url)}</a></div>`
|
|
1227
|
+
},
|
|
1228
|
+
}
|
|
1229
|
+
```
|
|
1230
|
+
|
|
1231
|
+
#### Wiring
|
|
1232
|
+
|
|
1233
|
+
`update-ampless` reads the `tiptapNodeToMarkdown` and `tiptapNodeToHtml`
|
|
1234
|
+
named exports from each plugin's `./editor` module (via namespace import `*
|
|
1235
|
+
as`) and wires them into both installs automatically — **no hand-wiring
|
|
1236
|
+
required**. If your plugin does not export one of the maps, the `?? {}`
|
|
1237
|
+
fallback in the generated file is a no-op.
|
|
1238
|
+
|
|
1239
|
+
#### `markdown → html` 2-hop
|
|
1240
|
+
|
|
1241
|
+
The `markdown → html` direction reuses the `tiptapNodeToHtml` adapter via
|
|
1242
|
+
a 2-hop:
|
|
1243
|
+
|
|
1244
|
+
1. `markdownToHtml(body)` — marked converts the markdown body to HTML. Bare
|
|
1245
|
+
URL lines become `<p><a href="URL">URL</a></p>`.
|
|
1246
|
+
2. `generateJSON(html, extensions)` — tiptap parses the HTML. Your plugin's
|
|
1247
|
+
`Node.parseHTML` `tag: 'p'` rule promotes the bare-URL paragraph to the
|
|
1248
|
+
embed Node.
|
|
1249
|
+
3. `tiptapToHtml(doc, { nodeAdapters })` — the html adapter serialises the
|
|
1250
|
+
embed Node to the placeholder div.
|
|
1251
|
+
|
|
1252
|
+
This means your plugin only needs to export the `tiptap → html` adapter once;
|
|
1253
|
+
the `markdown → html` direction reuses it automatically through tiptap's parse
|
|
1254
|
+
rules. **No duplicate logic is needed.**
|
|
1255
|
+
|
|
1256
|
+
#### Public html walker: `htmlPlaceholder`
|
|
1257
|
+
|
|
1258
|
+
To make `format: 'html'` posts render placeholder divs as real embeds on
|
|
1259
|
+
the public page, add an **`htmlPlaceholder`** declaration to your existing
|
|
1260
|
+
`contentFields` `tiptap` entry. You write **no new renderer** — the walker
|
|
1261
|
+
calls the same `render(node, ctx)` your tiptap entry already uses, so all
|
|
1262
|
+
three formats (tiptap / markdown / html) reach one renderer with no
|
|
1263
|
+
divergence.
|
|
1264
|
+
|
|
1265
|
+
```ts
|
|
1266
|
+
// packages/plugin-youtube/src/index.tsx
|
|
1267
|
+
contentFields: [
|
|
1268
|
+
{
|
|
1269
|
+
kind: 'tiptap',
|
|
1270
|
+
nodeType: 'amplessYoutube',
|
|
1271
|
+
render: (node) => {
|
|
1272
|
+
const videoId = String(node.attrs?.videoId ?? '')
|
|
1273
|
+
const startRaw = node.attrs?.start
|
|
1274
|
+
const start =
|
|
1275
|
+
typeof startRaw === 'number' && Number.isFinite(startRaw) ? startRaw : undefined
|
|
1276
|
+
return <YouTubeEmbed videoId={videoId} start={start} />
|
|
1277
|
+
},
|
|
1278
|
+
htmlPlaceholder: {
|
|
1279
|
+
// The marker attribute that flags a top-level placeholder div.
|
|
1280
|
+
flagAttr: 'data-ampless-youtube',
|
|
1281
|
+
// Convert the div's HTML attributes into the tiptap node `attrs`
|
|
1282
|
+
// your `render` expects — WITH the right types. The walker is
|
|
1283
|
+
// type-agnostic, so coerce here (e.g. data-start string → number).
|
|
1284
|
+
attrsFromElement: (attribs) => {
|
|
1285
|
+
const start = Number(attribs['data-start'])
|
|
1286
|
+
return {
|
|
1287
|
+
videoId: attribs['data-video-id'] ?? '',
|
|
1288
|
+
start: Number.isFinite(start) ? start : undefined,
|
|
1289
|
+
}
|
|
1290
|
+
},
|
|
1291
|
+
},
|
|
1292
|
+
},
|
|
1293
|
+
// …markdown-url entry unchanged…
|
|
1294
|
+
]
|
|
1295
|
+
```
|
|
1296
|
+
|
|
1297
|
+
On public render of a `format: 'html'` post, the runtime parses the body
|
|
1298
|
+
server-side (`htmlparser2`), finds each **top-level** element carrying
|
|
1299
|
+
`flagAttr`, builds a `{ type: nodeType, attrs: attrsFromElement(attribs) }`
|
|
1300
|
+
node, and calls `render(node, ctx)`. Everything else passes through as the
|
|
1301
|
+
**original-string slices** (byte-for-byte; no DOM re-serialisation).
|
|
1302
|
+
|
|
1303
|
+
Constraints worth knowing:
|
|
1304
|
+
|
|
1305
|
+
- **Top-level only.** Placeholder divs nested inside `<blockquote>`,
|
|
1306
|
+
`<li>`, etc. stay literal — consistent with the editor's body-level-only
|
|
1307
|
+
`parseHTML` fallback. Only depth-0 elements expand.
|
|
1308
|
+
- **`flagAttr` is matched case-insensitively.** htmlparser2 lowercases
|
|
1309
|
+
HTML attribute names while parsing, and the runtime lowercases your
|
|
1310
|
+
`flagAttr` at registration, so `<div DATA-AMPLESS-YOUTUBE …>` and
|
|
1311
|
+
`<div data-ampless-youtube …>` both expand. `flagAttr` can be any
|
|
1312
|
+
attribute name — a site-local plugin may use `data-my-embed`; there is
|
|
1313
|
+
no fixed `data-ampless` prefix requirement.
|
|
1314
|
+
- **Graceful degradation.** If `attrsFromElement` or `render` throws, the
|
|
1315
|
+
runtime logs a `console.warn` and falls back to the **raw placeholder
|
|
1316
|
+
slice** (the inner canonical URL link stays clickable) rather than
|
|
1317
|
+
dropping the engineer-authored content.
|
|
1318
|
+
- **Page-level scripts.** If your embed needs a third-party script (e.g.
|
|
1319
|
+
x.com's `widgets.js`), your `publicPostScript` / detection helper must
|
|
1320
|
+
also recognise the placeholder form. `plugin-x-embed`'s `hasTweetIn`
|
|
1321
|
+
matches both `twitter-tweet` and `data-ampless-tweet` in `format: 'html'`
|
|
1322
|
+
bodies so widgets.js is injected for the expanded blockquote to hydrate.
|
|
1323
|
+
|
|
1324
|
+
**Wrapper-boundary change.** A placeholder-free `format: 'html'` post is
|
|
1325
|
+
emitted as a single wrapper `<div>` (the fast path — markup-identical to
|
|
1326
|
+
the previous raw passthrough). A post **with** placeholders becomes
|
|
1327
|
+
**multiple wrapper divs interleaved with the React embed siblings**: the
|
|
1328
|
+
bytes inside each raw chunk are preserved exactly, but the wrapper
|
|
1329
|
+
boundaries shift. Direct-child / adjacent-sibling CSS selectors that
|
|
1330
|
+
assumed one wrapper around the whole body will not match the same way.
|
|
1331
|
+
This is the accepted trade-off for expanding embeds in-place.
|
|
1332
|
+
|
|
1107
1333
|
### Markdown to tiptap restoration
|
|
1108
1334
|
|
|
1109
1335
|
If an editor Node serializes to markdown as a bare URL line, the reverse
|