uncial 0.0.1 → 0.0.3

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/README.md CHANGED
@@ -1,9 +1,13 @@
1
1
  # Uncial
2
2
 
3
- Uncial is a backend-agnostic Svelte block editor built on Tiptap. Library consumers define a block once as a Svelte component, register it with `defineBlock(...)`, and reuse that same block definition in both the WYSIWYG editor and the renderer.
3
+ [Demo](https://d-flood.github.io/uncial/) | [Docs](https://d-flood.github.io/uncial/docs/) | [GitHub](https://github.com/d-flood/uncial)
4
+
5
+ Uncial is a backend-agnostic block editor built on Tiptap. It turns a normal frontend framework component into an editable block in a richtext editor. It supports any frontend framework though Svelte is supported out of the box today. Library consumers define a block once as a component, register it with `defineSvelteBlock(...)`, and reuse that same block definition in both the WYSIWYG editor and the SSR-capable renderer.
4
6
 
5
7
  Custom blocks can stay atomic or declare one default child content region for nested document flow.
6
8
 
9
+ ![screenshot of the Uncial richtext and block editorwith a callout component selected](.github/images/image.png)
10
+
7
11
  ## What ships today
8
12
 
9
13
  - Shared block definitions for editor and renderer
@@ -13,10 +17,13 @@ Custom blocks can stay atomic or declare one default child content region for ne
13
17
  - Document normalization with version stamping
14
18
  - Validation hooks for editor and renderer boundaries
15
19
  - SSR-safe renderer imports separated from browser-only editor behavior
20
+ - A public runtime plugin contract for third-party React, Vue, Web Component, or vanilla runtimes
16
21
 
17
22
  ## Install
18
23
 
19
24
  ```sh
25
+ npm install uncial
26
+ pnpm add uncial
20
27
  bun add uncial
21
28
  ```
22
29
 
@@ -26,6 +33,27 @@ Peer dependency:
26
33
 
27
34
  ## Quick start
28
35
 
36
+ Define a standard Svelte component first:
37
+
38
+ ```svelte
39
+ <!-- PromoCard.svelte -->
40
+ <script lang="ts">
41
+ interface Props {
42
+ title?: string;
43
+ body?: string;
44
+ }
45
+
46
+ let { title = 'Spring launch', body = 'Save 20% on featured plans.' }: Props = $props();
47
+ </script>
48
+
49
+ <article class="promo-card">
50
+ <h3>{title}</h3>
51
+ <p>{body}</p>
52
+ </article>
53
+ ```
54
+
55
+ Then register and use that component as an Uncial block:
56
+
29
57
  ```svelte
30
58
  <script lang="ts">
31
59
  import {
@@ -34,11 +62,11 @@ Peer dependency:
34
62
  createBlockAttributesController,
35
63
  createBlockRegistry,
36
64
  createSchema,
37
- defineBlock
65
+ defineSvelteBlock
38
66
  } from 'uncial';
39
67
  import PromoCard from './PromoCard.svelte';
40
68
 
41
- const promoCard = defineBlock({
69
+ const promoCard = defineSvelteBlock({
42
70
  id: 'promoCard',
43
71
  label: 'Promo Card',
44
72
  attributes: {
@@ -64,6 +92,60 @@ Peer dependency:
64
92
  <Renderer content={document} {blocks} {schema} />
65
93
  ```
66
94
 
95
+ ## Web components
96
+
97
+ React, Vue, and vanilla browser apps can register browser-native elements with a client-side import:
98
+
99
+ ```ts
100
+ import 'uncial/web-components';
101
+ ```
102
+
103
+ Use DOM properties for complex values such as registries, schemas, documents, extensions, and controllers:
104
+
105
+ ```ts
106
+ const renderer = document.querySelector('uncial-renderer');
107
+ Object.assign(renderer, { blocks, schema, content: document });
108
+
109
+ const editor = document.querySelector('uncial-editor');
110
+ Object.assign(editor, { blocks, schema, json: document, attributesController });
111
+ ```
112
+
113
+ ```html
114
+ <uncial-editor></uncial-editor>
115
+ <uncial-renderer></uncial-renderer>
116
+ ```
117
+
118
+ Validation callbacks are emitted as bubbling, composed DOM events. Editor document updates are emitted as `uncial-change` because non-Svelte hosts cannot use `bind:json`:
119
+
120
+ ```ts
121
+ editor.addEventListener('uncial-change', (event) => {
122
+ document = event.detail;
123
+ });
124
+
125
+ renderer.addEventListener('uncial-issue', (event) => {
126
+ console.warn(event.detail.code, event.detail.path);
127
+ });
128
+ ```
129
+
130
+ For SSR frameworks, import `uncial/web-components` on the client only. Svelte blocks still render through the Svelte renderer for SSR; non-Svelte block runtimes should provide their own full-document renderer rather than relying on mixed component islands.
131
+
132
+ ## Runtime plugins
133
+
134
+ Uncial's core block model is runtime-neutral. `defineSvelteBlock(...)` is the first-party helper for the bundled Svelte runtime, and `defineRuntimeBlock(runtimePlugin, config)` is the public escape hatch for third-party runtimes.
135
+
136
+ Registries currently allow a single runtime per document. Empty registries and one-runtime registries are valid; mixed-runtime registries fail fast so future non-Svelte SSR can be implemented as full-document runtime renderers.
137
+
138
+ Runtime plugins normalize native components and may provide editor node-view mounting with `destroy()` and optional `update()` lifecycle hooks. Container block children are exposed as a runtime-specific child outlet; plugins must leave ProseMirror-owned child DOM under editor control. SSR-capable runtimes should provide a renderer that can render the whole document for that runtime.
139
+
140
+ ```ts
141
+ import { defineRuntimeBlock } from 'uncial/core';
142
+ import { reactRuntime } from 'uncial-react-runtime';
143
+
144
+ export function defineReactBlock(config) {
145
+ return defineRuntimeBlock(reactRuntime, config);
146
+ }
147
+ ```
148
+
67
149
  ## Styling and customization
68
150
 
69
151
  The root `Editor` and `Renderer` exports ship with Uncial's starter shell and default component-scoped styling.
@@ -103,7 +185,7 @@ If you want to own the editor layout yourself, use `bindEditor(...)` on an eleme
103
185
  Use `component` when the same Svelte component should render in both the editor and the frontend output.
104
186
 
105
187
  ```ts
106
- const hero = defineBlock({
188
+ const hero = defineSvelteBlock({
107
189
  id: 'hero',
108
190
  label: 'Hero',
109
191
  attributes: {
@@ -130,7 +212,7 @@ Attribute specs support:
130
212
  Blocks can also opt into child content:
131
213
 
132
214
  ```ts
133
- const collapsible = defineBlock({
215
+ const collapsible = defineSvelteBlock({
134
216
  id: 'collapsible',
135
217
  label: 'Collapsible',
136
218
  attributes: {
@@ -199,6 +281,7 @@ Use `validateDocument(...)` directly or pass `onIssue` into `Editor` or `Rendere
199
281
  - Renderer output is driven by the same block registry used by the editor
200
282
  - Built-in rich text rendering supports headings, lists, blockquotes, code blocks, inline code, strike, bold, italic, and links
201
283
  - Links are sanitized to allow only `http`, `https`, `mailto`, `tel`, relative paths, and hash links
284
+ - Custom block components and `html.render` hooks are trusted application code; sanitize any raw HTML or navigation attributes they emit
202
285
 
203
286
  ## Development
204
287
 
@@ -1,2 +1,3 @@
1
- import type { BlockAttributes, BlockConfig, BlockDefinition } from './types.js';
2
- export declare function defineBlock<Attrs extends BlockAttributes>(config: BlockConfig<Attrs>): BlockDefinition<Attrs>;
1
+ import type { BlockAttributes, BlockDefinition, RuntimeBlockConfig } from './types.js';
2
+ import type { BlockRuntimePlugin } from './runtime.js';
3
+ export declare function defineRuntimeBlock<Attrs extends BlockAttributes, Component>(runtime: BlockRuntimePlugin<Component>, config: RuntimeBlockConfig<Attrs, Component>): BlockDefinition<Attrs>;
@@ -40,14 +40,14 @@ function validateConfig(config) {
40
40
  throw new Error(`Block "${config.id}" cannot be inline when content.kind is "${config.content.kind}"`);
41
41
  }
42
42
  }
43
- function normalizeComponents(config) {
43
+ function normalizeComponents(runtime, config) {
44
44
  const shared = config.component;
45
45
  const editor = config.components?.editor ?? shared ?? config.components?.render;
46
46
  const render = config.components?.render ?? shared ?? config.components?.editor;
47
47
  if (!editor || !render) {
48
48
  throw new Error(`Block "${config.id}" must provide either "component" or both "components.editor" and "components.render"`);
49
49
  }
50
- return { editor, render };
50
+ return { editor: runtime.defineComponent(editor), render: runtime.defineComponent(render) };
51
51
  }
52
52
  function normalizeContent(content) {
53
53
  if (!content) {
@@ -57,15 +57,16 @@ function normalizeContent(content) {
57
57
  kind: content.kind
58
58
  };
59
59
  }
60
- export function defineBlock(config) {
60
+ export function defineRuntimeBlock(runtime, config) {
61
61
  validateConfig(config);
62
62
  return Object.freeze({
63
63
  id: config.id,
64
+ runtime: runtime.id,
64
65
  label: config.label,
65
66
  description: config.description,
66
67
  icon: config.icon,
67
68
  attributes: normalizeAttributes(config.attributes),
68
- components: normalizeComponents(config),
69
+ components: normalizeComponents(runtime, config),
69
70
  behaviors: {
70
71
  inline: config.behaviors?.inline ?? false,
71
72
  draggable: config.behaviors?.draggable ?? true,
@@ -1,7 +1,8 @@
1
- export { defineBlock } from './defineBlock.js';
1
+ export { defineRuntimeBlock } from './defineBlock.js';
2
2
  export { coerceAttributeValue, inferAttributeInputKind, normalizeAttributeOptions, normalizeBlockAttributes, parseBlockDraftAttributes, serializeBlockAttributes, toAttributeDraftValues } from './attributes.js';
3
3
  export { createBlockRegistry, createSchema, resolveRegistry } from './registry.js';
4
4
  export { CURRENT_DOCUMENT_VERSION, normalizeDocument } from './normalize.js';
5
5
  export { validateDocument } from './validate.js';
6
+ export type { BlockEditorMountHandle, BlockEditorMountOptions, BlockRuntimePlugin, NormalizedBlockComponentDefinition } from './runtime.js';
6
7
  export { coerceRichTextDocument, emptyRichTextDocument, hasRichTextContent, isRichTextDocument, richTextDocument, resolveRichTextFeatures } from '../shared/richText.js';
7
- export type { AttributeConfig, AttributeInputKind, AttributeOption, AttrParser, AttrSerializer, AttributeSpec, BlockAttributes, BlockBehavior, BlockComponentProps, BlockConfig, BlockContentDefinition, BlockContentKind, BlockDefinition, BlockMetadata, BlockRegistry, ContentDocument, ContentSchema, CreateSchemaOptions, RichTextFeature, RichTextFeatureSelection, ValidateDocumentOptions, ValidationCode, ValidationIssue, ValidationResult } from './types.js';
8
+ export type { AttributeConfig, AttributeInputKind, AttributeOption, AttrParser, AttrSerializer, AttributeSpec, BlockAttributes, BlockBehavior, BlockComponentProps, BlockConfig, BlockContentDefinition, BlockContentKind, BlockDefinition, BlockIcon, BlockMetadata, BlockRegistry, ContentDocument, ContentSchema, CreateSchemaOptions, RichTextFeature, RichTextFeatureSelection, RuntimeBlockConfig, ValidateDocumentOptions, ValidationCode, ValidationIssue, ValidationResult } from './types.js';
@@ -1,4 +1,4 @@
1
- export { defineBlock } from './defineBlock.js';
1
+ export { defineRuntimeBlock } from './defineBlock.js';
2
2
  export { coerceAttributeValue, inferAttributeInputKind, normalizeAttributeOptions, normalizeBlockAttributes, parseBlockDraftAttributes, serializeBlockAttributes, toAttributeDraftValues } from './attributes.js';
3
3
  export { createBlockRegistry, createSchema, resolveRegistry } from './registry.js';
4
4
  export { CURRENT_DOCUMENT_VERSION, normalizeDocument } from './normalize.js';
@@ -2,10 +2,15 @@ const DEFAULT_MARKS = ['bold', 'italic', 'strike', 'code', 'link'];
2
2
  export function createBlockRegistry(blocks) {
3
3
  const byId = new Map();
4
4
  const metadata = [];
5
+ const runtimes = new Set();
5
6
  for (const block of blocks) {
6
7
  if (byId.has(block.id)) {
7
8
  throw new Error(`Duplicate block id "${block.id}"`);
8
9
  }
10
+ runtimes.add(block.runtime);
11
+ if (runtimes.size > 1) {
12
+ throw new Error('Block registries cannot mix runtimes in this release');
13
+ }
9
14
  byId.set(block.id, block);
10
15
  metadata.push({
11
16
  id: block.id,
@@ -0,0 +1,25 @@
1
+ export interface BlockEditorMountOptions {
2
+ target: HTMLElement;
3
+ inline: boolean;
4
+ component: NormalizedBlockComponentDefinition;
5
+ props: Record<string, unknown>;
6
+ }
7
+ export interface BlockEditorMountHandle {
8
+ destroy(): void;
9
+ update?(props: Record<string, unknown>): void;
10
+ }
11
+ export interface NormalizedBlockComponentDefinition {
12
+ runtime: string;
13
+ component: unknown;
14
+ plugin: BlockRuntimePlugin;
15
+ }
16
+ export interface BlockRuntimePlugin<Component = unknown> {
17
+ /** Stable runtime id. Documents may only use blocks from one runtime in this release. */
18
+ id: string;
19
+ /** Normalize a native runtime component into a framework-neutral component definition. */
20
+ defineComponent(component: Component): NormalizedBlockComponentDefinition;
21
+ /** Mount, update, and destroy an editor node-view body for this runtime. */
22
+ createEditorMount?(options: BlockEditorMountOptions): BlockEditorMountHandle;
23
+ /** Reserved for future full-document single-runtime renderers with SSR support. */
24
+ createRenderer?: unknown;
25
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,5 @@
1
- import type { Component, Snippet } from 'svelte';
2
1
  import type { PMDoc, PMPath } from '../shared/document.js';
2
+ import type { NormalizedBlockComponentDefinition } from './runtime.js';
3
3
  export type AttrValidator<T> = (value: unknown) => value is T;
4
4
  export type AttrParser<T> = (value: unknown) => T | undefined;
5
5
  export type AttrSerializer = (value: unknown) => unknown;
@@ -27,6 +27,7 @@ export interface AttributeSpec<T> {
27
27
  }
28
28
  export type AttributeConfig<T> = AttributeSpec<T> | T;
29
29
  export type BlockAttributes = Record<string, unknown>;
30
+ export type BlockIcon = string | unknown;
30
31
  export type HtmlSpecValue = string | number | boolean | null | undefined;
31
32
  export type HtmlSpec = [string, Record<string, unknown>?, ...(HtmlSpec | HtmlSpecValue)[]];
32
33
  export type BlockHtmlRenderer = (attrs: BlockAttributes) => HtmlSpec;
@@ -36,32 +37,28 @@ export interface BlockContentDefinition {
36
37
  }
37
38
  export interface BlockComponentProps {
38
39
  content?: import('../shared/document.js').PMNode[];
39
- children?: Snippet;
40
40
  [name: string]: unknown;
41
41
  }
42
42
  export type NormalizedAttributes<Attrs extends BlockAttributes> = {
43
43
  [K in keyof Attrs]: AttributeSpec<Attrs[K]>;
44
44
  };
45
45
  export interface BlockComponents {
46
- editor: Component<Record<string, unknown>>;
47
- render: Component<Record<string, unknown>>;
46
+ editor: NormalizedBlockComponentDefinition;
47
+ render: NormalizedBlockComponentDefinition;
48
48
  }
49
- export type BlockComponent = Component<Record<string, unknown>>;
50
49
  export interface BlockBehavior {
51
50
  inline?: boolean;
52
51
  draggable?: boolean;
53
52
  selectable?: boolean;
54
53
  }
55
- export interface BlockConfig<Attrs extends BlockAttributes> {
54
+ export interface BaseBlockConfig<Attrs extends BlockAttributes> {
56
55
  id: string;
57
56
  label: string;
58
57
  description?: string;
59
- icon?: string | Component<Record<string, never>>;
58
+ icon?: BlockIcon;
60
59
  attributes: {
61
60
  [K in keyof Attrs]: AttributeConfig<Attrs[K]>;
62
61
  };
63
- component?: BlockComponent;
64
- components?: Partial<BlockComponents>;
65
62
  behaviors?: BlockBehavior;
66
63
  content?: false | BlockContentDefinition;
67
64
  html?: {
@@ -69,11 +66,20 @@ export interface BlockConfig<Attrs extends BlockAttributes> {
69
66
  render?: BlockHtmlRenderer;
70
67
  };
71
68
  }
69
+ export interface RuntimeBlockConfig<Attrs extends BlockAttributes, Component> extends BaseBlockConfig<Attrs> {
70
+ component?: Component;
71
+ components?: {
72
+ editor?: Component;
73
+ render?: Component;
74
+ };
75
+ }
76
+ export type BlockConfig<Attrs extends BlockAttributes> = RuntimeBlockConfig<Attrs, unknown>;
72
77
  export interface BlockDefinition<Attrs extends BlockAttributes = BlockAttributes> {
73
78
  id: string;
79
+ runtime: string;
74
80
  label: string;
75
81
  description?: string;
76
- icon?: string | Component<Record<string, never>>;
82
+ icon?: BlockIcon;
77
83
  attributes: NormalizedAttributes<Attrs>;
78
84
  components: BlockComponents;
79
85
  behaviors: BlockBehavior;
@@ -87,7 +93,7 @@ export interface BlockMetadata {
87
93
  id: string;
88
94
  label: string;
89
95
  description?: string;
90
- icon?: string | Component<Record<string, never>>;
96
+ icon?: BlockIcon;
91
97
  }
92
98
  export interface BlockRegistry {
93
99
  blocks: BlockDefinition[];
@@ -3,6 +3,7 @@ import { NodeSelection } from '@tiptap/pm/state';
3
3
  import { getBlockDefaultAttrs } from '../shared/tiptap.js';
4
4
  import { parseBlockDraftAttributes, toAttributeDraftValues } from '../core/attributes.js';
5
5
  import { CODE_BLOCK_ID, codeBlockAttributeTarget } from '../shared/codeBlockAttributes.js';
6
+ import { sanitizeHref } from '../render/sanitize.js';
6
7
  const INITIAL_STATE = {
7
8
  open: false,
8
9
  mode: null,
@@ -315,7 +316,7 @@ export function createBlockAttributesController() {
315
316
  if (!editor)
316
317
  return false;
317
318
  const attrs = get(state).link.attrs;
318
- const href = attrs.href?.trim();
319
+ const href = sanitizeHref(attrs.href);
319
320
  if (!href)
320
321
  return false;
321
322
  return editor
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './core/index.js';
2
+ export * from './runtime/svelte.js';
2
3
  export * from './editor/index.js';
3
4
  export * from './render/index.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './core/index.js';
2
+ export * from './runtime/svelte.js';
2
3
  export * from './editor/index.js';
3
4
  export * from './render/index.js';
@@ -11,6 +11,7 @@
11
11
  import type { PMDoc, PMNode } from '../shared/document.js';
12
12
  import { resolveRegistry } from '../core/registry.js';
13
13
  import { emptyDocument } from '../shared/content.js';
14
+ import { SVELTE_RUNTIME_ID } from '../runtime/svelte.js';
14
15
  import RichContent from './RichContent.svelte';
15
16
 
16
17
  interface Props {
@@ -22,7 +23,14 @@
22
23
 
23
24
  let { content = emptyDocument(), blocks = [], schema = undefined, onIssue }: Props = $props();
24
25
 
25
- const registry = $derived(resolveRegistry(blocks));
26
+ const registry = $derived.by(() => {
27
+ const resolved = resolveRegistry(blocks);
28
+ const runtime = resolved.blocks[0]?.runtime;
29
+ if (runtime && runtime !== SVELTE_RUNTIME_ID) {
30
+ throw new Error(`The Svelte renderer cannot render "${runtime}" runtime blocks`);
31
+ }
32
+ return resolved;
33
+ });
26
34
  const normalizedContent = $derived(
27
35
  normalizeDocument(content as Partial<PMDoc>, registry, schema)
28
36
  );
@@ -34,7 +42,7 @@
34
42
  </script>
35
43
 
36
44
  <div class="uncial-renderer rounded-box border border-base-300 bg-base-100 shadow-sm">
37
- <div class="uncial-content uncial-rich-content min-h-[28rem] p-5 leading-7 sm:p-8">
45
+ <div class="uncial-content uncial-rich-content min-h-112 p-5 leading-7 sm:p-8">
38
46
  <RichContent nodes={(normalizedContent.content ?? []) as PMNode[]} {registry} {schema} />
39
47
  </div>
40
48
  </div>
@@ -1,8 +1,11 @@
1
1
  <script lang="ts">
2
+ import { resolve } from '$app/paths';
3
+ import type { Component } from 'svelte';
2
4
  import type { BlockRegistry, ContentSchema } from '../core/types.js';
3
5
  import type { PMMark, PMNode } from '../shared/document.js';
4
6
  import { getCodeLanguageClass, highlightCodeToHtml } from '../shared/syntaxHighlight.js';
5
7
  import RichContent from './RichContent.svelte';
8
+ import { sanitizeHref } from './sanitize.js';
6
9
 
7
10
  interface Props {
8
11
  node: PMNode;
@@ -27,6 +30,10 @@
27
30
  function getActiveMarks(marks: PMMark[] = []): PMMark[] {
28
31
  return schema ? marks.filter((mark) => schema.allowedMarks.has(mark.type)) : marks;
29
32
  }
33
+
34
+ function getSvelteRenderComponent(component: unknown): Component<Record<string, unknown>> {
35
+ return component as Component<Record<string, unknown>>;
36
+ }
30
37
  </script>
31
38
 
32
39
  {#snippet blockChildren()}
@@ -46,6 +53,18 @@
46
53
  <s>{@render renderMarkedText(text, rest)}</s>
47
54
  {:else if mark.type === 'code'}
48
55
  <code>{@render renderMarkedText(text, rest)}</code>
56
+ {:else if mark.type === 'link'}
57
+ {@const href = sanitizeHref(mark.attrs?.href)}
58
+ {#if href}
59
+ {#if href.startsWith('/')}
60
+ <a href={resolve(href as '/')}>{@render renderMarkedText(text, rest)}</a>
61
+ {:else}
62
+ <!-- eslint-disable-next-line svelte/no-navigation-without-resolve -- sanitized rich-text links may be external, mailto, tel, or hash URLs -->
63
+ <a {href}>{@render renderMarkedText(text, rest)}</a>
64
+ {/if}
65
+ {:else}
66
+ {@render renderMarkedText(text, rest)}
67
+ {/if}
49
68
  {:else}
50
69
  {@render renderMarkedText(text, rest)}
51
70
  {/if}
@@ -59,8 +78,12 @@
59
78
  ></pre>
60
79
  <!-- eslint-enable svelte/no-at-html-tags -->
61
80
  {:else if block && (!schema || schema.allowedBlocks.has(block.id))}
62
- {@const RenderComponent = block.components.render}
63
- <RenderComponent {...blockAttrs} content={blockContent} children={block.content ? blockChildren : undefined} />
81
+ {@const RenderComponent = getSvelteRenderComponent(block.components.render.component)}
82
+ <RenderComponent
83
+ {...blockAttrs}
84
+ content={blockContent}
85
+ children={block.content ? blockChildren : undefined}
86
+ />
64
87
  {:else if node.type === 'paragraph'}
65
88
  <p>
66
89
  <RichContent nodes={node.content ?? []} {registry} {schema} />
@@ -1,3 +1,4 @@
1
+ import type { Component } from 'svelte';
1
2
  import type { BlockRegistry, ContentSchema } from '../core/types.js';
2
3
  import type { PMNode } from '../shared/document.js';
3
4
  interface Props {
@@ -5,6 +6,6 @@ interface Props {
5
6
  registry: BlockRegistry;
6
7
  schema?: ContentSchema;
7
8
  }
8
- declare const RichNode: import("svelte").Component<Props, {}, "">;
9
+ declare const RichNode: Component<Props, {}, "">;
9
10
  type RichNode = ReturnType<typeof RichNode>;
10
11
  export default RichNode;
@@ -0,0 +1,12 @@
1
+ import type { Component, Snippet } from 'svelte';
2
+ import type { BlockRuntimePlugin } from '../core/runtime.js';
3
+ import type { BlockAttributes, RuntimeBlockConfig } from '../core/types.js';
4
+ export declare const SVELTE_RUNTIME_ID = "svelte";
5
+ export interface SvelteBlockComponentProps {
6
+ content?: unknown[];
7
+ children?: Snippet;
8
+ [name: string]: unknown;
9
+ }
10
+ export type SvelteBlockComponent = Component<Record<string, unknown>>;
11
+ export declare const svelteRuntime: BlockRuntimePlugin<SvelteBlockComponent>;
12
+ export declare function defineSvelteBlock<Attrs extends BlockAttributes>(config: RuntimeBlockConfig<Attrs, SvelteBlockComponent>): import("../core/types.js").BlockDefinition<Attrs>;
@@ -0,0 +1,51 @@
1
+ import { createRawSnippet, mount, unmount } from 'svelte';
2
+ import { defineRuntimeBlock } from '../core/defineBlock.js';
3
+ import BlockNodeView from '../editor/BlockNodeView.svelte';
4
+ export const SVELTE_RUNTIME_ID = 'svelte';
5
+ function isSvelteComponentDefinition(definition) {
6
+ return definition.runtime === SVELTE_RUNTIME_ID;
7
+ }
8
+ function createContentSnippet(contentDOM) {
9
+ return contentDOM
10
+ ? createRawSnippet(() => ({
11
+ render: () => '<div class="uncial-nodeview-content"></div>',
12
+ setup: (element) => {
13
+ element.replaceChildren(contentDOM);
14
+ }
15
+ }))
16
+ : undefined;
17
+ }
18
+ export const svelteRuntime = {
19
+ id: SVELTE_RUNTIME_ID,
20
+ defineComponent(component) {
21
+ return { runtime: SVELTE_RUNTIME_ID, component, plugin: svelteRuntime };
22
+ },
23
+ createEditorMount(options) {
24
+ if (!isSvelteComponentDefinition(options.component)) {
25
+ throw new Error('Svelte runtime can only mount Svelte block components');
26
+ }
27
+ const host = document.createElement(options.inline ? 'span' : 'div');
28
+ host.className = 'uncial-nodeview-host';
29
+ options.target.replaceChildren(host);
30
+ const props = {
31
+ ...options.props,
32
+ component: options.component.component,
33
+ children: createContentSnippet(options.props.contentDOM ?? null)
34
+ };
35
+ let mounted = mount(BlockNodeView, {
36
+ target: host,
37
+ props: props
38
+ });
39
+ return {
40
+ destroy() {
41
+ if (mounted) {
42
+ void unmount(mounted);
43
+ mounted = null;
44
+ }
45
+ }
46
+ };
47
+ }
48
+ };
49
+ export function defineSvelteBlock(config) {
50
+ return defineRuntimeBlock(svelteRuntime, config);
51
+ }
@@ -1,11 +1,10 @@
1
1
  import StarterKit from '@tiptap/starter-kit';
2
2
  import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight';
3
3
  import { Mark, mergeAttributes, Node } from '@tiptap/core';
4
- import { createRawSnippet, mount, unmount } from 'svelte';
5
4
  import { resolveRegistry } from '../core/registry.js';
6
5
  import { coerceAttributeValue, normalizeBlockAttributes, serializeBlockAttributes } from '../core/attributes.js';
7
- import BlockNodeView from '../editor/BlockNodeView.svelte';
8
6
  import { lowlight } from './syntaxHighlight.js';
7
+ import { sanitizeHref } from '../render/sanitize.js';
9
8
  function safeParseJSON(raw) {
10
9
  if (!raw)
11
10
  return {};
@@ -21,30 +20,23 @@ export function getBlockDefaultAttrs(block) {
21
20
  return normalizeBlockAttributes(block, {});
22
21
  }
23
22
  function mountBlockEditorComponent(block, node, container, contentDOM, mounted, onActivate, getPos) {
24
- if (mounted) {
25
- void unmount(mounted);
23
+ mounted?.destroy();
24
+ const createEditorMount = block.components.editor.plugin.createEditorMount;
25
+ if (!createEditorMount) {
26
+ throw new Error(`Runtime "${block.runtime}" does not support editor node views`);
26
27
  }
27
- const host = document.createElement(block.behaviors.inline ? 'span' : 'div');
28
- host.className = 'uncial-nodeview-host';
29
- container.replaceChildren(host);
30
- return mount(BlockNodeView, {
31
- target: host,
28
+ return createEditorMount({
29
+ target: container,
30
+ inline: block.behaviors.inline ?? false,
31
+ component: block.components.editor,
32
32
  props: {
33
- component: block.components.editor,
34
33
  attrs: node.attrs ?? {},
35
34
  content: (node.content?.toJSON() ?? []),
35
+ contentDOM,
36
36
  blockId: block.id,
37
37
  label: block.label,
38
38
  draggable: block.behaviors.draggable ?? true,
39
- onActivate: getPos && onActivate ? () => onActivate(getPos()) : undefined,
40
- children: contentDOM
41
- ? createRawSnippet(() => ({
42
- render: () => '<div class="uncial-nodeview-content"></div>',
43
- setup: (element) => {
44
- element.replaceChildren(contentDOM);
45
- }
46
- }))
47
- : undefined
39
+ onActivate: getPos && onActivate ? () => onActivate(getPos()) : undefined
48
40
  }
49
41
  });
50
42
  }
@@ -112,9 +104,7 @@ function createBlockNodeView(block, node, getPos, onActivate) {
112
104
  dom.classList.remove('ProseMirror-selectednode');
113
105
  },
114
106
  destroy() {
115
- if (mounted) {
116
- void unmount(mounted);
117
- }
107
+ mounted?.destroy();
118
108
  }
119
109
  };
120
110
  }
@@ -179,7 +169,10 @@ const LinkMark = Mark.create({
179
169
  inclusive: false,
180
170
  addAttributes() {
181
171
  return {
182
- href: { default: null },
172
+ href: {
173
+ default: null,
174
+ parseHTML: (element) => sanitizeHref(element.getAttribute('href'))
175
+ },
183
176
  target: { default: null },
184
177
  rel: { default: null }
185
178
  };
@@ -188,12 +181,15 @@ const LinkMark = Mark.create({
188
181
  return [{ tag: 'a[href]' }];
189
182
  },
190
183
  renderHTML({ HTMLAttributes }) {
191
- return ['a', mergeAttributes(HTMLAttributes), 0];
184
+ const href = sanitizeHref(HTMLAttributes.href);
185
+ const rest = { ...HTMLAttributes };
186
+ delete rest.href;
187
+ return ['a', mergeAttributes(rest, href ? { href } : {}), 0];
192
188
  },
193
189
  addCommands() {
194
190
  return {
195
- toggleLink: (attributes) => ({ commands }) => Boolean(attributes?.href) &&
196
- commands.toggleMark(this.name, attributes, { extendEmptyMarkRange: true }),
191
+ toggleLink: (attributes) => ({ commands }) => Boolean(sanitizeHref(attributes?.href)) &&
192
+ commands.toggleMark(this.name, { ...attributes, href: sanitizeHref(attributes?.href) }, { extendEmptyMarkRange: true }),
197
193
  unsetLink: () => ({ commands }) => commands.unsetMark(this.name, { extendEmptyMarkRange: true })
198
194
  };
199
195
  }
@@ -0,0 +1,60 @@
1
+ <script lang="ts">
2
+ import type { AnyExtension, JSONContent } from '@tiptap/core';
3
+ import Editor from '../editor/Editor.svelte';
4
+ import type {
5
+ BlockAttributesController,
6
+ ToolbarFeature,
7
+ ToolbarFeatureSelection
8
+ } from '../editor/index.js';
9
+ import type {
10
+ BlockDefinition,
11
+ BlockRegistry,
12
+ ContentSchema,
13
+ ValidationIssue
14
+ } from '../core/types.js';
15
+ import { emptyDocument } from '../shared/content.js';
16
+
17
+ interface Props {
18
+ blocks?: BlockRegistry | BlockDefinition[];
19
+ schema?: ContentSchema;
20
+ json?: JSONContent;
21
+ extensions?: AnyExtension[];
22
+ toolbarFeatures?: ToolbarFeatureSelection;
23
+ toolbarExtensions?: ToolbarFeature[];
24
+ attributesController?: BlockAttributesController | null;
25
+ onIssue?: (issue: ValidationIssue) => void;
26
+ onChange?: (document: JSONContent) => void;
27
+ }
28
+
29
+ let {
30
+ blocks = [],
31
+ schema = undefined,
32
+ json = $bindable(emptyDocument()),
33
+ extensions = [],
34
+ toolbarFeatures = undefined,
35
+ toolbarExtensions = [],
36
+ attributesController = null,
37
+ onIssue,
38
+ onChange
39
+ }: Props = $props();
40
+
41
+ function dispatchIssue(issue: ValidationIssue): void {
42
+ onIssue?.(issue);
43
+ }
44
+
45
+ function setJson(nextDocument: JSONContent): void {
46
+ json = nextDocument;
47
+ onChange?.(nextDocument);
48
+ }
49
+ </script>
50
+
51
+ <Editor
52
+ {blocks}
53
+ {schema}
54
+ bind:json={() => json, setJson}
55
+ {extensions}
56
+ {toolbarFeatures}
57
+ {toolbarExtensions}
58
+ {attributesController}
59
+ onIssue={dispatchIssue}
60
+ />
@@ -0,0 +1,17 @@
1
+ import type { AnyExtension, JSONContent } from '@tiptap/core';
2
+ import type { BlockAttributesController, ToolbarFeature, ToolbarFeatureSelection } from '../editor/index.js';
3
+ import type { BlockDefinition, BlockRegistry, ContentSchema, ValidationIssue } from '../core/types.js';
4
+ interface Props {
5
+ blocks?: BlockRegistry | BlockDefinition[];
6
+ schema?: ContentSchema;
7
+ json?: JSONContent;
8
+ extensions?: AnyExtension[];
9
+ toolbarFeatures?: ToolbarFeatureSelection;
10
+ toolbarExtensions?: ToolbarFeature[];
11
+ attributesController?: BlockAttributesController | null;
12
+ onIssue?: (issue: ValidationIssue) => void;
13
+ onChange?: (document: JSONContent) => void;
14
+ }
15
+ declare const UncialEditor: import("svelte").Component<Props, {}, "json">;
16
+ type UncialEditor = ReturnType<typeof UncialEditor>;
17
+ export default UncialEditor;
@@ -0,0 +1,26 @@
1
+ <script lang="ts">
2
+ import type { JSONContent } from '@tiptap/core';
3
+ import Renderer from '../render/Renderer.svelte';
4
+ import type {
5
+ BlockDefinition,
6
+ BlockRegistry,
7
+ ContentSchema,
8
+ ValidationIssue
9
+ } from '../core/types.js';
10
+ import { emptyDocument } from '../shared/content.js';
11
+
12
+ interface Props {
13
+ content?: JSONContent;
14
+ blocks?: BlockRegistry | BlockDefinition[];
15
+ schema?: ContentSchema;
16
+ onIssue?: (issue: ValidationIssue) => void;
17
+ }
18
+
19
+ let { content = emptyDocument(), blocks = [], schema = undefined, onIssue }: Props = $props();
20
+
21
+ function dispatchIssue(issue: ValidationIssue): void {
22
+ onIssue?.(issue);
23
+ }
24
+ </script>
25
+
26
+ <Renderer {content} {blocks} {schema} onIssue={dispatchIssue} />
@@ -0,0 +1,11 @@
1
+ import type { JSONContent } from '@tiptap/core';
2
+ import type { BlockDefinition, BlockRegistry, ContentSchema, ValidationIssue } from '../core/types.js';
3
+ interface Props {
4
+ content?: JSONContent;
5
+ blocks?: BlockRegistry | BlockDefinition[];
6
+ schema?: ContentSchema;
7
+ onIssue?: (issue: ValidationIssue) => void;
8
+ }
9
+ declare const UncialRenderer: import("svelte").Component<Props, {}, "">;
10
+ type UncialRenderer = ReturnType<typeof UncialRenderer>;
11
+ export default UncialRenderer;
@@ -0,0 +1,62 @@
1
+ import UncialEditor from './UncialEditor.svelte';
2
+ import UncialRenderer from './UncialRenderer.svelte';
3
+ import type { AnyExtension, JSONContent } from '@tiptap/core';
4
+ import type { BlockAttributesController, ToolbarFeature, ToolbarFeatureSelection } from '../editor/index.js';
5
+ import type { BlockDefinition, BlockRegistry, ContentSchema } from '../core/types.js';
6
+ type EditorProps = {
7
+ blocks?: BlockRegistry | BlockDefinition[];
8
+ schema?: ContentSchema;
9
+ json?: JSONContent;
10
+ extensions?: AnyExtension[];
11
+ toolbarFeatures?: ToolbarFeatureSelection;
12
+ toolbarExtensions?: ToolbarFeature[];
13
+ attributesController?: BlockAttributesController | null;
14
+ };
15
+ type RendererProps = {
16
+ content?: JSONContent;
17
+ blocks?: BlockRegistry | BlockDefinition[];
18
+ schema?: ContentSchema;
19
+ };
20
+ declare const BrowserHTMLElement: {
21
+ new (): HTMLElement;
22
+ prototype: HTMLElement;
23
+ };
24
+ declare abstract class UncialElement<Props extends Record<string, unknown>> extends BrowserHTMLElement {
25
+ protected props: Props;
26
+ private mounted;
27
+ private readonly root;
28
+ connectedCallback(): void;
29
+ disconnectedCallback(): void;
30
+ protected setProp<Key extends keyof Props>(key: Key, value: Props[Key]): void;
31
+ protected emit(type: string, detail: unknown): void;
32
+ protected abstract mount(): Record<string, unknown>;
33
+ private render;
34
+ private destroy;
35
+ }
36
+ declare class UncialEditorElement extends UncialElement<EditorProps> {
37
+ get blocks(): EditorProps['blocks'];
38
+ set blocks(value: EditorProps['blocks']);
39
+ get schema(): EditorProps['schema'];
40
+ set schema(value: EditorProps['schema']);
41
+ get json(): EditorProps['json'];
42
+ set json(value: EditorProps['json']);
43
+ get extensions(): EditorProps['extensions'];
44
+ set extensions(value: EditorProps['extensions']);
45
+ get toolbarFeatures(): EditorProps['toolbarFeatures'];
46
+ set toolbarFeatures(value: EditorProps['toolbarFeatures']);
47
+ get toolbarExtensions(): EditorProps['toolbarExtensions'];
48
+ set toolbarExtensions(value: EditorProps['toolbarExtensions']);
49
+ get attributesController(): EditorProps['attributesController'];
50
+ set attributesController(value: EditorProps['attributesController']);
51
+ protected mount(): Record<string, unknown>;
52
+ }
53
+ declare class UncialRendererElement extends UncialElement<RendererProps> {
54
+ get content(): RendererProps['content'];
55
+ set content(value: RendererProps['content']);
56
+ get blocks(): RendererProps['blocks'];
57
+ set blocks(value: RendererProps['blocks']);
58
+ get schema(): RendererProps['schema'];
59
+ set schema(value: RendererProps['schema']);
60
+ protected mount(): Record<string, unknown>;
61
+ }
62
+ export { UncialEditor, UncialEditorElement, UncialRenderer, UncialRendererElement };
@@ -0,0 +1,129 @@
1
+ import UncialEditor from './UncialEditor.svelte';
2
+ import UncialRenderer from './UncialRenderer.svelte';
3
+ import { mount, unmount } from 'svelte';
4
+ const BrowserHTMLElement = globalThis.HTMLElement ?? class {
5
+ };
6
+ class UncialElement extends BrowserHTMLElement {
7
+ props = {};
8
+ mounted = null;
9
+ root = this.attachShadow({ mode: 'open' });
10
+ connectedCallback() {
11
+ this.render();
12
+ }
13
+ disconnectedCallback() {
14
+ this.destroy();
15
+ }
16
+ setProp(key, value) {
17
+ this.props = { ...this.props, [key]: value };
18
+ if (this.isConnected)
19
+ this.render();
20
+ }
21
+ emit(type, detail) {
22
+ this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));
23
+ }
24
+ render() {
25
+ this.destroy();
26
+ this.mounted = this.mount();
27
+ }
28
+ destroy() {
29
+ if (!this.mounted)
30
+ return;
31
+ void unmount(this.mounted);
32
+ this.mounted = null;
33
+ }
34
+ }
35
+ class UncialEditorElement extends UncialElement {
36
+ get blocks() {
37
+ return this.props.blocks;
38
+ }
39
+ set blocks(value) {
40
+ this.setProp('blocks', value);
41
+ }
42
+ get schema() {
43
+ return this.props.schema;
44
+ }
45
+ set schema(value) {
46
+ this.setProp('schema', value);
47
+ }
48
+ get json() {
49
+ return this.props.json;
50
+ }
51
+ set json(value) {
52
+ this.setProp('json', value);
53
+ }
54
+ get extensions() {
55
+ return this.props.extensions;
56
+ }
57
+ set extensions(value) {
58
+ this.setProp('extensions', value);
59
+ }
60
+ get toolbarFeatures() {
61
+ return this.props.toolbarFeatures;
62
+ }
63
+ set toolbarFeatures(value) {
64
+ this.setProp('toolbarFeatures', value);
65
+ }
66
+ get toolbarExtensions() {
67
+ return this.props.toolbarExtensions;
68
+ }
69
+ set toolbarExtensions(value) {
70
+ this.setProp('toolbarExtensions', value);
71
+ }
72
+ get attributesController() {
73
+ return this.props.attributesController;
74
+ }
75
+ set attributesController(value) {
76
+ this.setProp('attributesController', value);
77
+ }
78
+ mount() {
79
+ return mount(UncialEditor, {
80
+ target: this.shadowRoot ?? this,
81
+ props: {
82
+ ...this.props,
83
+ onIssue: (issue) => this.emit('uncial-issue', issue),
84
+ onChange: (document) => {
85
+ this.props = { ...this.props, json: document };
86
+ this.emit('uncial-change', document);
87
+ }
88
+ }
89
+ });
90
+ }
91
+ }
92
+ class UncialRendererElement extends UncialElement {
93
+ get content() {
94
+ return this.props.content;
95
+ }
96
+ set content(value) {
97
+ this.setProp('content', value);
98
+ }
99
+ get blocks() {
100
+ return this.props.blocks;
101
+ }
102
+ set blocks(value) {
103
+ this.setProp('blocks', value);
104
+ }
105
+ get schema() {
106
+ return this.props.schema;
107
+ }
108
+ set schema(value) {
109
+ this.setProp('schema', value);
110
+ }
111
+ mount() {
112
+ return mount(UncialRenderer, {
113
+ target: this.shadowRoot ?? this,
114
+ props: {
115
+ ...this.props,
116
+ onIssue: (issue) => this.emit('uncial-issue', issue)
117
+ }
118
+ });
119
+ }
120
+ }
121
+ if (typeof customElements !== 'undefined') {
122
+ if (!customElements.get('uncial-editor')) {
123
+ customElements.define('uncial-editor', UncialEditorElement);
124
+ }
125
+ if (!customElements.get('uncial-renderer')) {
126
+ customElements.define('uncial-renderer', UncialRendererElement);
127
+ }
128
+ }
129
+ export { UncialEditor, UncialEditorElement, UncialRenderer, UncialRendererElement };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "uncial",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "packageManager": "bun@1.3.10",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -40,7 +40,8 @@
40
40
  "!dist/**/*.spec.*"
41
41
  ],
42
42
  "sideEffects": [
43
- "**/*.css"
43
+ "**/*.css",
44
+ "./dist/web-components/index.js"
44
45
  ],
45
46
  "svelte": "./dist/index.js",
46
47
  "types": "./dist/index.d.ts",
@@ -65,6 +66,16 @@
65
66
  "types": "./dist/render/index.d.ts",
66
67
  "svelte": "./dist/render/index.js",
67
68
  "default": "./dist/render/index.js"
69
+ },
70
+ "./runtime/svelte": {
71
+ "types": "./dist/runtime/svelte.d.ts",
72
+ "svelte": "./dist/runtime/svelte.js",
73
+ "default": "./dist/runtime/svelte.js"
74
+ },
75
+ "./web-components": {
76
+ "types": "./dist/web-components/index.d.ts",
77
+ "svelte": "./dist/web-components/index.js",
78
+ "default": "./dist/web-components/index.js"
68
79
  }
69
80
  },
70
81
  "peerDependencies": {
@@ -87,6 +98,7 @@
87
98
  "eslint-config-prettier": "^10.1.8",
88
99
  "eslint-plugin-svelte": "^3.14.0",
89
100
  "globals": "^17.3.0",
101
+ "mdsvex": "^0.12.7",
90
102
  "playwright": "^1.58.2",
91
103
  "prettier": "^3.8.1",
92
104
  "prettier-plugin-svelte": "^3.4.1",