@xharness/satori-element 0.0.0-stage → 4.0.1-alpha.2

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/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@xharness/satori-element",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Element Manipulation",
4
+ "version": "4.0.1-alpha.2",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./lib/types/index.d.ts",
9
+ "default": "./lib/index.js"
10
+ },
11
+ "./src/*": "./src/*",
12
+ "./package.json": "./package.json",
13
+ "./jsx-runtime": {
14
+ "types": "./lib/types/index.d.ts",
15
+ "default": "./lib/index.js"
16
+ },
17
+ "./jsx-dev-runtime": {
18
+ "types": "./lib/types/index.d.ts",
19
+ "default": "./lib/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "lib/index.js",
24
+ "lib/types/**/*.d.ts",
25
+ "lib/types/**/*.d.ts.map",
26
+ "src"
27
+ ],
28
+ "author": "Shigma <shigma10826@gmail.com>",
29
+ "license": "MIT",
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/Kuner/XHarness.git",
33
+ "directory": "vendor/im/element"
34
+ },
35
+ "bugs": {
36
+ "url": "https://github.com/satorijs/satori/issues"
37
+ },
38
+ "homepage": "https://satori.chat/",
39
+ "keywords": [
40
+ "satori",
41
+ "element",
42
+ "segment",
43
+ "component",
44
+ "message",
45
+ "utilities"
46
+ ],
47
+ "dependencies": {
48
+ "@xharness/cordis-element": "~0.3.1-alpha.2",
49
+ "@xharness/cosmokit": "~1.10.0-alpha.2"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public"
53
+ },
54
+ "main": "lib/index.js",
55
+ "types": "lib/types/index.d.ts"
6
56
  }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Block/inline category table of the element vocabulary and the content model `normalize` enforces.
3
+ */
4
+
5
+ import type { Tag } from './vocabulary.ts'
6
+
7
+ /** Element category. */
8
+ export type Category =
9
+ | 'root' | 'envelope' | 'inline' | 'block' | 'media' | 'interactive' | 'control' | 'alternative' | 'input'
10
+ | 'inbound'
11
+
12
+ /** T1 = core fallback + at least one v1 mode; T2 = vocabulary + core fallback only. T3 tags are `reservedTags`. */
13
+ export type Tier = 1 | 2
14
+
15
+ /**
16
+ * Where an element may stand: `inline` = phrasing content only (a bare run at flow level is wrapped into `<p>`),
17
+ * `block` = flow content only, `any` = both (media, buttons, inbound wrappers: block when standing in a flow
18
+ * container, inline inside phrasing content — see the `img.inline` / `button.inline` variants).
19
+ */
20
+ export type Position = 'inline' | 'block' | 'any'
21
+
22
+ /**
23
+ * What an element may contain:
24
+ * - `flow`: blocks; bare inline runs are wrapped into `<p>` (message, li, td, th, blockquote);
25
+ * - `details`: flow content with an optional leading `<summary>`;
26
+ * - `phrasing`: inline content;
27
+ * - `text`: text only (`br` becomes `\n`);
28
+ * - `list` / `table` / `row` / `buttons` / `options`: only `li` / `tr` / `th|td` / `button` / `option` children;
29
+ * - `cases`: only `case` children, each holding content of the model of the `<fallback>`'s own parent;
30
+ * - `empty`: no children.
31
+ */
32
+ export type ContentModel =
33
+ | 'flow' | 'details' | 'phrasing' | 'text' | 'list' | 'table' | 'row' | 'buttons' | 'options' | 'cases' | 'empty'
34
+
35
+ export interface ElementInfo {
36
+ readonly category: Category
37
+ readonly tier: Tier
38
+ readonly position: Position
39
+ readonly content: ContentModel
40
+ /** When set, the element may only be a direct child of these tags (e.g. `li` of `ul`/`ol`). */
41
+ readonly parents?: readonly Tag[]
42
+ /** Attributes that must be non-empty strings. */
43
+ readonly required?: readonly string[]
44
+ }
45
+
46
+ const inline = (tier: Tier = 1, content: ContentModel = 'phrasing', required?: string[]): ElementInfo => ({
47
+ category: 'inline', tier, position: 'inline', content, ...required && { required },
48
+ })
49
+ const block = (content: ContentModel, parents?: Tag[]): ElementInfo => ({
50
+ category: 'block', tier: 1, position: 'block', content, ...parents && { parents },
51
+ })
52
+ const media: ElementInfo = { category: 'media', tier: 1, position: 'any', content: 'empty', required: ['src'] }
53
+
54
+ export const elementInfo: { readonly [K in Tag]: ElementInfo } = {
55
+ message: { category: 'root', tier: 1, position: 'block', content: 'flow' },
56
+ quote: { category: 'envelope', tier: 1, position: 'block', content: 'empty', parents: ['message'], required: ['id'] },
57
+ title: { category: 'envelope', tier: 1, position: 'block', content: 'phrasing', parents: ['message'] },
58
+ text: inline(1, 'empty'),
59
+ b: inline(),
60
+ i: inline(),
61
+ u: inline(),
62
+ s: inline(),
63
+ spoiler: inline(2),
64
+ code: inline(1, 'text'),
65
+ a: inline(1, 'phrasing', ['href']),
66
+ at: inline(1, 'empty'),
67
+ channel: inline(2, 'empty', ['id']),
68
+ emoji: inline(2, 'empty', ['id']),
69
+ span: inline(2),
70
+ br: inline(1, 'empty'),
71
+ p: block('phrasing'),
72
+ h1: block('phrasing'),
73
+ h2: block('phrasing'),
74
+ h3: block('phrasing'),
75
+ h4: block('phrasing'),
76
+ h5: block('phrasing'),
77
+ h6: block('phrasing'),
78
+ ul: block('list'),
79
+ ol: block('list'),
80
+ li: block('flow', ['ul', 'ol']),
81
+ blockquote: block('flow'),
82
+ pre: block('text'),
83
+ hr: block('empty'),
84
+ table: block('table'),
85
+ tr: block('row', ['table']),
86
+ th: block('flow', ['tr']),
87
+ td: block('flow', ['tr']),
88
+ details: block('details'),
89
+ summary: block('phrasing', ['details']),
90
+ small: block('phrasing'),
91
+ img: media,
92
+ audio: media,
93
+ video: media,
94
+ file: media,
95
+ button: { category: 'interactive', tier: 1, position: 'any', content: 'phrasing' },
96
+ 'button-group': { category: 'interactive', tier: 1, position: 'block', content: 'buttons' },
97
+ form: { category: 'control', tier: 1, position: 'block', content: 'flow', required: ['name'] },
98
+ input: { category: 'control', tier: 1, position: 'block', content: 'empty' },
99
+ select: { category: 'control', tier: 1, position: 'block', content: 'options' },
100
+ option: { category: 'control', tier: 1, position: 'block', content: 'phrasing', parents: ['select'], required: ['value'] },
101
+ fallback: { category: 'alternative', tier: 1, position: 'any', content: 'cases' },
102
+ case: { category: 'alternative', tier: 1, position: 'any', content: 'cases', parents: ['fallback'] },
103
+ markdown: { category: 'input', tier: 1, position: 'any', content: 'text' },
104
+ forward: { category: 'inbound', tier: 1, position: 'any', content: 'phrasing', required: ['id'] },
105
+ raw: { category: 'inbound', tier: 1, position: 'any', content: 'phrasing', required: ['platform', 'type'] },
106
+ }
107
+
108
+ /** T3: names reserved for later versions; `normalize` rejects them in v1. */
109
+ export const reservedTags = [
110
+ 'math', 'time', 'sup', 'sub', 'mark', 'sticker', 'gallery', 'figure', 'columns', 'poll', 'location', 'contact',
111
+ 'progress', 'countdown',
112
+ ] as const
113
+ export type ReservedTag = typeof reservedTags[number]
114
+
115
+ /** Old Satori / HTML spellings and the v4 tag that replaces them (rejected by `normalize` with a hint). */
116
+ export const tagAliases: Readonly<Record<string, Tag>> = {
117
+ strong: 'b',
118
+ em: 'i',
119
+ ins: 'u',
120
+ del: 's',
121
+ spl: 'spoiler',
122
+ sharp: 'channel',
123
+ face: 'emoji',
124
+ strike: 's',
125
+ image: 'img',
126
+ }
127
+
128
+ /** Every tag of the vocabulary. */
129
+ export const tags = Object.keys(elementInfo) as Tag[]
130
+
131
+ export function isTag(type: string): type is Tag {
132
+ return Object.prototype.hasOwnProperty.call(elementInfo, type)
133
+ }
134
+
135
+ export function isReservedTag(type: string): type is ReservedTag {
136
+ return (reservedTags as readonly string[]).includes(type)
137
+ }
138
+
139
+ /** Containers whose children are blocks (bare inline runs are wrapped into `<p>`). */
140
+ export function isFlowContainer(type: string): boolean {
141
+ if (!isTag(type)) return false
142
+ const { content } = elementInfo[type]
143
+ return content === 'flow' || content === 'details'
144
+ }
145
+
146
+ /** Containers whose children are inline (phrasing) content. */
147
+ export function isPhrasingContainer(type: string): boolean {
148
+ if (!isTag(type)) return false
149
+ const { content } = elementInfo[type]
150
+ return content === 'phrasing' || content === 'text'
151
+ }
152
+
153
+ export function isInline(type: string): boolean {
154
+ return isTag(type) && elementInfo[type].position === 'inline'
155
+ }
156
+
157
+ export function isBlock(type: string): boolean {
158
+ return isTag(type) && elementInfo[type].position === 'block'
159
+ }
package/src/factory.ts ADDED
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Typed factories and the JSX runtime (`@xharness/satori-element/jsx-runtime` resolves to this package's index).
3
+ */
4
+
5
+ import { Element as createElement, isElement as isRuntimeElement, parse as parseMarkup } from '@xharness/cordis-element'
6
+ import type { Child, Element, ElementMap, Fragment as FragmentType, Tag } from './vocabulary.ts'
7
+
8
+ type OptionalKeys<A> = { [P in keyof A]-?: {} extends Pick<A, P> ? P : never }[keyof A]
9
+ type Simplify<T> = { [P in keyof T]: T[P] } & {}
10
+
11
+ /**
12
+ * Factory input for a tag's attributes: `ElementMap[K]` where optional attributes also accept `undefined`
13
+ * (dropped at runtime, so callers under `exactOptionalPropertyTypes` can pass `name: user.name`), plus `key`.
14
+ */
15
+ export type Attrs<K extends Tag> = LooseAttrs<ElementMap[K]>
16
+ type LooseAttrs<A> = A extends unknown
17
+ ? Simplify<
18
+ & { [P in Exclude<keyof A, OptionalKeys<A>>]: A[P] }
19
+ & { [P in OptionalKeys<A>]?: A[P] | undefined }
20
+ & { key?: string | undefined }
21
+ >
22
+ : never
23
+
24
+ /** Tags whose attributes are all optional, so `h(tag, ...children)` may omit them. */
25
+ export type BareTag = { [K in Tag]: {} extends ElementMap[K] ? K : never }[Tag]
26
+
27
+ export interface ElementFactory {
28
+ <K extends Tag>(tag: K, attrs: Attrs<K>, ...children: Child[]): Element<K>
29
+ <K extends BareTag>(tag: K, ...children: Child[]): Element<K>
30
+ text(content: string): Element<'text'>
31
+ /** `<markdown content>`: GFM source, expanded into elements by the IM render engine's `markdown` service. */
32
+ markdown(source: string): Element<'markdown'>
33
+ }
34
+
35
+ /** Element-like check: a `cordis-element` runtime element, or a plain `{ type, attrs, children }` object. */
36
+ export function isElement(value: unknown): value is Element {
37
+ if (isRuntimeElement(value)) return true
38
+ if (!value || typeof value !== 'object') return false
39
+ const { type, attrs, children } = value as Record<string, unknown>
40
+ return typeof type === 'string' && !!attrs && typeof attrs === 'object' && Array.isArray(children)
41
+ }
42
+
43
+ /** Runtime tag of a JSX fragment (`<>…</>`); flattened by the factories, `normalize` and `toText`. */
44
+ export const Fragment = ''
45
+ export type Fragment = FragmentType
46
+
47
+ /**
48
+ * Parse the XML-ish `Element.toString()` form back into elements (goldens, logs, tests). Not an input format for
49
+ * user content: plain strings passed to `h` / `normalize` are literal text.
50
+ */
51
+ export function parse(source: string): Element[] {
52
+ return parseMarkup(source) as unknown as Element[]
53
+ }
54
+
55
+ /** @internal Build a runtime element without copying children. */
56
+ export function make(type: string, attrs: Record<string, unknown>, children: Element[], key?: string): Element {
57
+ const el = createElement(type, {}) as unknown as { attrs: Record<string, unknown>; children: Element[]; key?: string }
58
+ for (const [name, value] of Object.entries(attrs)) {
59
+ if (value !== undefined && value !== null) el.attrs[name] = value
60
+ }
61
+ el.children = children
62
+ if (key !== undefined) el.key = key
63
+ return el as unknown as Element
64
+ }
65
+
66
+ /** Flatten children: strings and numbers become `text`, holes are skipped, fragments and arrays are spliced. */
67
+ export function toChildren(child: unknown, out: Element[] = []): Element[] {
68
+ if (child === null || child === undefined || typeof child === 'boolean') return out
69
+ if (typeof child === 'string' || typeof child === 'number') {
70
+ const content = String(child)
71
+ if (content) out.push(make('text', { content }, []))
72
+ } else if (Array.isArray(child)) {
73
+ for (const item of child) toChildren(item, out)
74
+ } else if (isElement(child)) {
75
+ if ((child.type as string) === Fragment) toChildren(child.children, out)
76
+ else out.push(child)
77
+ } else {
78
+ throw new TypeError(`invalid element child: ${Object.prototype.toString.call(child)}`)
79
+ }
80
+ return out
81
+ }
82
+
83
+ function isAttrs(value: unknown): value is Record<string, unknown> {
84
+ return !!value && typeof value === 'object' && !Array.isArray(value) && !isElement(value)
85
+ }
86
+
87
+ /**
88
+ * Children of a `<fallback>`: every item is one candidate, kept apart as a `<case>`. A fragment or an array is one
89
+ * candidate holding all of its nodes; holes are skipped.
90
+ */
91
+ export function toCases(items: readonly unknown[]): Element[] {
92
+ const out: Element[] = []
93
+ for (const item of items) {
94
+ if (item === null || item === undefined || typeof item === 'boolean') continue
95
+ if (isElement(item) && item.type === 'case') out.push(item)
96
+ else out.push(make('case', {}, toChildren(item)))
97
+ }
98
+ return out
99
+ }
100
+
101
+ function create(type: string, args: unknown[]): Element {
102
+ let attrs: Record<string, unknown> = {}
103
+ let key: string | undefined
104
+ if (isAttrs(args[0])) {
105
+ const { key: k, ...rest } = args.shift() as Record<string, unknown>
106
+ attrs = rest
107
+ if (k !== undefined && k !== null) key = String(k)
108
+ }
109
+ return make(type, attrs, type === 'fallback' ? toCases(args) : toChildren(args), key)
110
+ }
111
+
112
+ export const h: ElementFactory = Object.assign(
113
+ (type: Tag, ...args: unknown[]) => create(type, args),
114
+ {
115
+ text: (content: string) => make('text', { content }, []) as Element<'text'>,
116
+ markdown: (source: string) => make('markdown', { content: source }, []) as Element<'markdown'>,
117
+ },
118
+ ) as ElementFactory
119
+
120
+ // ---- JSX ----------------------------------------------------------------------------------------------------------
121
+
122
+ type AnyElement = Element
123
+
124
+ /** Function component: called eagerly while the tree is built (no React semantics, no state). */
125
+ export type Component<P = any> = (props: P) => Child
126
+
127
+ type JsxProps<K extends Tag> = K extends 'markdown'
128
+ ? { content?: string; children?: string | readonly string[] }
129
+ : K extends 'text'
130
+ ? { content: string }
131
+ : Attrs<K> & { children?: Child }
132
+
133
+ /** `<case>` is internal: JSX writes a candidate of `<fallback>` as a fragment. */
134
+ type IntrinsicMap = { [K in Exclude<Tag, 'case'>]: JsxProps<K> }
135
+
136
+ export declare namespace JSX {
137
+ type Element = AnyElement
138
+ type ElementType = Tag | Component
139
+ interface ElementChildrenAttribute { children: {} }
140
+ interface IntrinsicAttributes { key?: string | undefined }
141
+ interface IntrinsicElements extends IntrinsicMap {}
142
+ }
143
+
144
+ /** Automatic JSX runtime entry (`jsx`, `jsxs`, `jsxDEV`). */
145
+ export function jsx(type: Tag | Component | typeof Fragment, props: Record<string, unknown> | null, key?: string): Element {
146
+ const { children, ...attrs } = props ?? {}
147
+ if (typeof type === 'function') {
148
+ const result = type({ ...attrs, ...children !== undefined && { children } })
149
+ const nodes = toChildren(result)
150
+ return nodes.length === 1 && key === undefined ? nodes[0]! : make(Fragment, {}, nodes, key)
151
+ }
152
+ if (type === Fragment) return make(Fragment, {}, toChildren(children), key)
153
+ if (type === 'markdown' && attrs.content === undefined && children !== undefined) {
154
+ attrs.content = ([] as unknown[]).concat(children).join('')
155
+ return make(type, attrs, [], key)
156
+ }
157
+ if (key === undefined && attrs.key !== undefined) key = String(attrs.key)
158
+ delete attrs.key
159
+ if (type === 'fallback') return make(type, attrs, toCases(Array.isArray(children) ? children : [children]), key)
160
+ return make(type, attrs, toChildren(children), key)
161
+ }
162
+
163
+ export { jsx as jsxs, jsx as jsxDEV }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@xharness/satori-element`: the Satori element vocabulary.
3
+ *
4
+ * Also the JSX runtime entry (`jsxImportSource: '@xharness/satori-element'`): `jsx`, `jsxs`, `jsxDEV`,
5
+ * `Fragment` and the `JSX` namespace.
6
+ */
7
+
8
+ export * from './vocabulary.ts'
9
+ export * from './elements.ts'
10
+ export { type Attrs, type BareTag, type Component, type ElementFactory, Fragment, h, isElement, type JSX, jsx, jsxDEV, jsxs, parse } from './factory.ts'
11
+ export * from './normalize.ts'
12
+ export * from './variants.ts'
13
+ export * from './text.ts'
14
+ export { escape, unescape } from '@xharness/cordis-element'
15
+
16
+ export { h as default } from './factory.ts'