@melt-js/libs-core 2026.11.14 → 2026.11.15
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 +19 -2
- package/demo/index.js +1 -0
- package/dist/browser.mjs +50 -0
- package/dist/hel-deployment.json +8 -0
- package/package.json +16 -4
- package/scripts/build-browser.mjs +13 -0
- package/scripts/component-events.mjs +57 -0
- package/scripts/hel-build-paths.cjs +48 -0
- package/scripts/package-env.cjs +15 -2
- package/src/browser.d.mts +2 -0
- package/src/browser.mjs +3 -0
- package/src/demo/docs.d.mts +25 -0
- package/src/demo/docs.mjs +75 -0
- package/src/demo/download.d.mts +33 -0
- package/src/demo/download.mjs +118 -0
- package/src/demo/fullscreen.d.mts +8 -0
- package/src/demo/fullscreen.mjs +80 -0
- package/src/demo/index.d.mts +4 -0
- package/src/demo/index.mjs +4 -0
- package/src/demo/model.d.mts +12 -0
- package/src/demo/model.mjs +203 -0
- package/src/demo/runtime.mjs +104 -0
- package/src/remote.d.mts +1 -0
- package/src/remote.mjs +37 -0
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
const hasOwn = (value, key) => Object.prototype.hasOwnProperty.call(value, key)
|
|
2
|
+
const kebab = name => name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase()
|
|
3
|
+
const handlerName = name => 'on' + name.replace(/(^|[^a-zA-Z0-9])([a-zA-Z0-9])/g, (_, __, letter) => letter.toUpperCase())
|
|
4
|
+
const attr = value => String(value).replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, ' ')
|
|
5
|
+
|
|
6
|
+
function literal(value) {
|
|
7
|
+
if (typeof value === 'function') return '() => {}'
|
|
8
|
+
if (value === undefined) return 'undefined'
|
|
9
|
+
try {
|
|
10
|
+
const result = JSON.stringify(value, (_, item) => typeof item === 'function' ? undefined : typeof item === 'bigint' ? String(item) : item)
|
|
11
|
+
return result === undefined ? 'undefined' : result
|
|
12
|
+
}
|
|
13
|
+
catch { return 'undefined /* 请提供可序列化的值 */' }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Schema defaults describe the API; values describe the current live example. */
|
|
17
|
+
export function buildComponentDocs({ name = 'Component', schema = [], values = {}, framework = 'vue3', events = [], slotHtml = {}, description = '', requirements = [], code, models = [] } = {}) {
|
|
18
|
+
const props = schema.filter(prop => !prop.isEvent).map(prop => ({
|
|
19
|
+
name: prop.name, type: prop.type || 'unknown',
|
|
20
|
+
default: prop.default === undefined || prop.default === '' ? '—' : String(prop.default),
|
|
21
|
+
required: prop.required === true || prop.required === 'true', description: prop.description || '—',
|
|
22
|
+
}))
|
|
23
|
+
const eventMap = new Map()
|
|
24
|
+
for (const event of [...schema.filter(prop => prop.isEvent), ...events]) {
|
|
25
|
+
const item = typeof event === 'string' ? { name: event } : event
|
|
26
|
+
if (item && item.name) eventMap.set(item.name, { ...eventMap.get(item.name), ...item })
|
|
27
|
+
}
|
|
28
|
+
const eventRows = [...eventMap.values()].map(event => ({
|
|
29
|
+
name: event.name, type: event.type || '未声明参数类型', description: event.description || '—',
|
|
30
|
+
}))
|
|
31
|
+
const entries = Object.entries(values).filter(([key]) => !eventMap.has(key))
|
|
32
|
+
let usage
|
|
33
|
+
if (framework === 'react') {
|
|
34
|
+
const attributes = entries.filter(([key]) => key !== 'children').map(([key, value]) =>
|
|
35
|
+
typeof value === 'string' ? ` ${key}="${attr(value)}"` : ` ${key}={${literal(value)}}`)
|
|
36
|
+
for (const event of eventRows) {
|
|
37
|
+
const key = /^on[A-Z]/.test(event.name) ? event.name : handlerName(event.name)
|
|
38
|
+
attributes.push(` ${key}={(...args) => { /* 处理 ${event.name} */ }}`)
|
|
39
|
+
}
|
|
40
|
+
const child = slotHtml.default !== undefined ? `{${literal(slotHtml.default)}}` : hasOwn(values, 'children') ? `{${literal(values.children)}}` : ''
|
|
41
|
+
// Slot HTML is explicit, rather than silently treating an HTML string as JSX.
|
|
42
|
+
const content = slotHtml.default && /<[a-z][\s\S]*>/i.test(slotHtml.default)
|
|
43
|
+
? `<span dangerouslySetInnerHTML={{ __html: ${literal(slotHtml.default)} }} />` : child
|
|
44
|
+
usage = `<${name}${attributes.length ? '\n' + attributes.join('\n') + '\n' : ''}${content ? `>\n ${content}\n</${name}>` : ' />'}`
|
|
45
|
+
} else {
|
|
46
|
+
const attributes = entries.map(([key, value]) => models.some(model => model.prop === key)
|
|
47
|
+
? ` :${kebab(key)}="${attr(key)}"`
|
|
48
|
+
: typeof value === 'string' ? ` ${kebab(key)}="${attr(value)}"` : ` :${kebab(key)}="${attr(literal(value))}"`)
|
|
49
|
+
for (const model of models) {
|
|
50
|
+
if (!eventMap.has(model.event)) eventRows.push({ name: model.event, type: '模型值', description: `同步 ${model.prop}` })
|
|
51
|
+
}
|
|
52
|
+
for (const event of eventRows) {
|
|
53
|
+
const model = models.find(item => item.event === event.name)
|
|
54
|
+
attributes.push(` @${event.name}="${model ? `${model.prop} = $event` : handlerName(event.name)}"`)
|
|
55
|
+
}
|
|
56
|
+
const slots = Object.entries(slotHtml).map(([key, html]) => key === 'default' ? String(html) : `<template #${key}>${html}</template>`).join('\n ')
|
|
57
|
+
usage = `<${kebab(name)}${attributes.length ? '\n' + attributes.join('\n') + '\n' : ''}>${slots ? '\n ' + slots + '\n' : ''}</${kebab(name)}>`
|
|
58
|
+
const handlers = eventRows.filter(event => !models.some(model => model.event === event.name))
|
|
59
|
+
if (models.length || handlers.length) {
|
|
60
|
+
const data = Object.fromEntries(models.map(model => [model.prop, values[model.prop]]))
|
|
61
|
+
const script = framework === 'vue3'
|
|
62
|
+
? [models.length ? "import { ref } from 'vue'" : '', ...models.map(model => `const ${model.prop} = ref(${literal(values[model.prop])})`), ...handlers.map(event => `function ${handlerName(event.name)}(...args) { /* 处理 ${event.name} */ }`)].filter(Boolean).join('\n')
|
|
63
|
+
: `export default {\n data: () => (${literal(data)}),\n methods: {\n${handlers.map(event => ` ${handlerName(event.name)}(...args) { /* 处理 ${event.name} */ },`).join('\n')}\n },\n}`
|
|
64
|
+
usage = `<template>\n${usage}\n</template>\n\n<script${framework === 'vue3' ? ' setup' : ''}>\n${script}\n</script>`
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { name, props, events: eventRows, description, requirements, code: code || usage }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Only declared events and configured listeners are listed, never guessed APIs. */
|
|
71
|
+
export function componentEvents(component, listeners = {}) {
|
|
72
|
+
const options = (component && component.options) || component || {}
|
|
73
|
+
const declared = options.emits || []
|
|
74
|
+
return [...new Set([...(Array.isArray(declared) ? declared : Object.keys(declared)), ...Object.keys(listeners)])]
|
|
75
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export interface VueDownloadExample {
|
|
2
|
+
component: string
|
|
3
|
+
props?: Record<string, unknown>
|
|
4
|
+
slotHtml?: string | Record<string, string>
|
|
5
|
+
background?: string
|
|
6
|
+
stageHeight?: string
|
|
7
|
+
openProp?: string
|
|
8
|
+
libName?: string
|
|
9
|
+
}
|
|
10
|
+
export interface DownloadItem {
|
|
11
|
+
name: string
|
|
12
|
+
label: string
|
|
13
|
+
props: Record<string, unknown>
|
|
14
|
+
slotHtml?: Record<string, string>
|
|
15
|
+
}
|
|
16
|
+
export interface ReactDownloadExample {
|
|
17
|
+
title: string
|
|
18
|
+
libName: string
|
|
19
|
+
items: DownloadItem[]
|
|
20
|
+
panelSchema?: unknown[]
|
|
21
|
+
propsPanel?: boolean
|
|
22
|
+
}
|
|
23
|
+
export interface DownloadFile { fileName: string; html: string }
|
|
24
|
+
export interface DownloadOptions { framework: 'vue2' | 'vue3' | 'react'; libName?: string }
|
|
25
|
+
export interface DownloadState { downloaded: string; error: string }
|
|
26
|
+
export const DOWNLOAD_HINT: string
|
|
27
|
+
export const EXAMPLE_HINT: string
|
|
28
|
+
export function buildDownloadFile(example: VueDownloadExample | ReactDownloadExample, options: DownloadOptions): DownloadFile
|
|
29
|
+
export function createDownloadController(onChange?: (state: DownloadState) => void): {
|
|
30
|
+
reset(): void
|
|
31
|
+
dispose(): void
|
|
32
|
+
download(example: VueDownloadExample | ReactDownloadExample, options: DownloadOptions): DownloadFile | undefined
|
|
33
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { resolveHelDep } from '../remote.mjs'
|
|
2
|
+
import * as runtime from './runtime.mjs'
|
|
3
|
+
|
|
4
|
+
export const DOWNLOAD_HINT = '下载当前示例(HTML + unpkg CDN 单文件,联网后可直接打开)'
|
|
5
|
+
export const EXAMPLE_HINT = '本示例的框架、加载器、适配层和远程组件均从 unpkg 加载。保存为 HTML 后可直接打开,需要联网。'
|
|
6
|
+
|
|
7
|
+
const cdn = (name, file) => 'https://unpkg.com/' + name + '/' + file
|
|
8
|
+
const escapeHtml = value => String(value).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
|
9
|
+
const scriptJson = value => JSON.stringify(value, null, 2).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')
|
|
10
|
+
const moduleData = source => 'data:text/javascript,' + encodeURIComponent(source)
|
|
11
|
+
|
|
12
|
+
function dependencies(framework) {
|
|
13
|
+
const imports = {
|
|
14
|
+
'@melt-js/libs-core': cdn('@melt-js/libs-core', 'dist/browser.mjs'),
|
|
15
|
+
['@melt-js/libs-core-' + framework]: cdn('@melt-js/libs-core-' + framework, 'src/index.mjs'),
|
|
16
|
+
}
|
|
17
|
+
let scripts
|
|
18
|
+
if (framework === 'react') {
|
|
19
|
+
imports.react = moduleData('export default window.React;')
|
|
20
|
+
scripts = [
|
|
21
|
+
cdn('react@18.3.1', 'umd/react.production.min.js'),
|
|
22
|
+
cdn('react-dom@18.3.1', 'umd/react-dom.production.min.js'),
|
|
23
|
+
cdn('react-is@18.3.1', 'umd/react-is.production.min.js'),
|
|
24
|
+
]
|
|
25
|
+
} else if (framework === 'vue2') {
|
|
26
|
+
imports.vue = moduleData('export default window.Vue;')
|
|
27
|
+
scripts = [cdn('vue@2.7.16', 'dist/vue.min.js')]
|
|
28
|
+
} else {
|
|
29
|
+
imports.vue = moduleData('export default window.Vue; export const { defineComponent, h, onBeforeUnmount, onErrorCaptured, onMounted, shallowRef } = window.Vue;')
|
|
30
|
+
scripts = [cdn('vue@3.5.45', 'dist/vue.global.prod.js')]
|
|
31
|
+
}
|
|
32
|
+
return { imports, scripts }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Demo hosts provide data only. Deployment/local-server addresses never enter the HTML. */
|
|
36
|
+
export function buildDownloadFile(input, { framework, libName = input && input.libName } = {}) {
|
|
37
|
+
if (!['vue2', 'vue3', 'react'].includes(framework)) throw new Error('需要指定示例框架:vue2 / vue3 / react')
|
|
38
|
+
if (!input || typeof libName !== 'string' || !libName.trim()) throw new Error('需要指定远程组件包 libName')
|
|
39
|
+
const packageName = libName.startsWith('@') ? libName : '@melt-js/' + libName
|
|
40
|
+
const dep = resolveHelDep(packageName, { type: 'unpkg' })
|
|
41
|
+
const example = framework === 'react'
|
|
42
|
+
? { title: input.title, packageName, items: input.items.map(({ name, label, props, slotHtml }) => ({ name, label, props: props || {}, ...(slotHtml ? { slotHtml } : {}) })),
|
|
43
|
+
...(input.panelSchema ? { panelSchema: input.panelSchema } : {}), propsPanel: !!input.propsPanel }
|
|
44
|
+
: { title: input.component, packageName, component: input.component, props: input.props || {},
|
|
45
|
+
slotHtml: input.slotHtml || '', openProp: input.openProp || '' }
|
|
46
|
+
if (framework === 'react' ? !example.items.length : !example.component) throw new Error('示例缺少组件')
|
|
47
|
+
const { imports, scripts } = dependencies(framework)
|
|
48
|
+
const resources = [...scripts, ...Object.values(imports).filter(url => url.startsWith('https:')), dep.host]
|
|
49
|
+
if (example.panelSchema) resources.push(resolveHelDep('@melt-js/libs-react-leva').host)
|
|
50
|
+
const snippet = [
|
|
51
|
+
`import { defineHelComponent${framework === 'react' ? ', loadHelLib, bindReactRuntime' : example.openProp ? ', loadHelComponent' : ''} } from '@melt-js/libs-core-${framework}'`,
|
|
52
|
+
"const example = JSON.parse(document.getElementById('demo-config').textContent)",
|
|
53
|
+
runtime[framework !== 'react' && example.openProp ? framework + 'Modal' : framework],
|
|
54
|
+
].join('\n')
|
|
55
|
+
const styles = [input.background ? 'background:' + input.background : '', input.stageHeight ? 'height:' + input.stageHeight : ''].filter(Boolean).join(';')
|
|
56
|
+
const bootstrap = [
|
|
57
|
+
...scripts.map(url => `<script src="${escapeHtml(url)}" crossorigin="anonymous"></script>`),
|
|
58
|
+
`<script type="importmap">${scriptJson({ imports })}</script>`,
|
|
59
|
+
`<script type="module">${snippet}</script>`,
|
|
60
|
+
].join('\n')
|
|
61
|
+
const html = [
|
|
62
|
+
'<!doctype html><html lang="zh-CN"><head>',
|
|
63
|
+
'<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">',
|
|
64
|
+
'<base href="https://unpkg.com/">',
|
|
65
|
+
`<title>${escapeHtml(example.title)} · HTML + unpkg</title>`,
|
|
66
|
+
'<style>body{margin:0;padding:28px;color:#1f2937;background:#f5f7fa;font:15px/1.7 system-ui,sans-serif}main{max-width:1100px;margin:auto}#app{box-sizing:border-box;min-height:240px;padding:24px;background:#fff;border-radius:12px;overflow:auto}pre{padding:20px;overflow:auto;background:#0f172a;color:#e2e8f0;border-radius:12px;font:13px/1.7 monospace}.example-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px}.example-item{min-width:0}a{overflow-wrap:anywhere}h1{font-size:26px}</style>',
|
|
67
|
+
`</head><body><main><h1>${escapeHtml(example.title)}</h1><p>${EXAMPLE_HINT}</p>`,
|
|
68
|
+
`<div id="app" style="${escapeHtml(styles)}"><div id="demo-root">正在加载远程组件…</div></div><p id="example-load-error" role="alert" hidden></p>`,
|
|
69
|
+
'<h2>引用的 unpkg CDN</h2><ul>' + resources.map(url => `<li><a href="${escapeHtml(url)}">${escapeHtml(url)}</a></li>`).join('') + '</ul>',
|
|
70
|
+
'<h2>HTML 引用与懒加载示例</h2><pre>' + escapeHtml(bootstrap) + '</pre>',
|
|
71
|
+
'<h2>示例参数</h2><pre>' + escapeHtml(JSON.stringify(example, null, 2)) + '</pre></main>',
|
|
72
|
+
`<script id="demo-config" type="application/json">${scriptJson(example)}</script>`,
|
|
73
|
+
'<script>function showLoadError(message){const target=document.getElementById("example-load-error");if(target){target.hidden=false;target.textContent="加载失败:"+message}}window.addEventListener("error",function(event){if(event.target&&event.target!==window&&!/^(SCRIPT|LINK)$/.test(event.target.tagName))return;showLoadError(event.message||"unpkg 资源加载失败")},true);window.addEventListener("unhandledrejection",function(event){showLoadError(String(event.reason))})</script>',
|
|
74
|
+
bootstrap,
|
|
75
|
+
'</body></html>',
|
|
76
|
+
].join('\n')
|
|
77
|
+
const slug = (input.component || dep.name + '-' + (input.items ? input.items.map(item => item.name).join('-') : 'example'))
|
|
78
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2').replace(/[^a-z0-9_-]/gi, '-').toLowerCase()
|
|
79
|
+
return { fileName: 'hel-micro-' + slug + '.html', html }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Shared status, copy and object-URL lifetime for all three Leva buttons. */
|
|
83
|
+
export function createDownloadController(onChange = () => {}) {
|
|
84
|
+
let timer
|
|
85
|
+
let disposed = false
|
|
86
|
+
const update = state => { if (!disposed) onChange(state) }
|
|
87
|
+
const reset = () => { clearTimeout(timer); update({ downloaded: '', error: '' }) }
|
|
88
|
+
return {
|
|
89
|
+
reset,
|
|
90
|
+
dispose() { disposed = true; clearTimeout(timer) },
|
|
91
|
+
download(example, options) {
|
|
92
|
+
let objectUrl = ''
|
|
93
|
+
let link
|
|
94
|
+
try {
|
|
95
|
+
const file = buildDownloadFile(example, options)
|
|
96
|
+
objectUrl = URL.createObjectURL(new Blob([file.html], { type: 'text/html;charset=utf-8' }))
|
|
97
|
+
link = document.createElement('a')
|
|
98
|
+
link.href = objectUrl
|
|
99
|
+
link.download = file.fileName
|
|
100
|
+
link.rel = 'noopener'
|
|
101
|
+
document.body.appendChild(link)
|
|
102
|
+
link.click()
|
|
103
|
+
// Allow the browser to take over the download before releasing its URL.
|
|
104
|
+
setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)
|
|
105
|
+
clearTimeout(timer)
|
|
106
|
+
update({ downloaded: file.fileName, error: '' })
|
|
107
|
+
timer = setTimeout(reset, 2000)
|
|
108
|
+
return file
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (objectUrl) URL.revokeObjectURL(objectUrl)
|
|
111
|
+
clearTimeout(timer)
|
|
112
|
+
update({ downloaded: '', error: '下载失败:' + String(error) })
|
|
113
|
+
} finally {
|
|
114
|
+
if (link) link.remove()
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type FullscreenTarget = string | Element | null | (() => Element | null)
|
|
2
|
+
export function createDemoFullscreen(options?: { target?: FullscreenTarget; onChange?: (active: boolean) => void }): {
|
|
3
|
+
readonly active: boolean
|
|
4
|
+
enter(trigger?: HTMLElement): void
|
|
5
|
+
exit(): void
|
|
6
|
+
toggle(trigger?: HTMLElement): void
|
|
7
|
+
dispose(): void
|
|
8
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// The registry is shared across separately bundled remote libraries in one document.
|
|
2
|
+
const key = Symbol.for('@melt-js/demo-fullscreen')
|
|
3
|
+
|
|
4
|
+
/** Page fullscreen works in embedded browsers and preserves the live component DOM. */
|
|
5
|
+
export function createDemoFullscreen({ target = '[data-demo-preview]', onChange = () => {} } = {}) {
|
|
6
|
+
let cleanup = null
|
|
7
|
+
let disposed = false
|
|
8
|
+
const resolve = () => {
|
|
9
|
+
const value = typeof target === 'function' ? target() : target
|
|
10
|
+
return typeof value === 'string' ? document.querySelector(value) : value
|
|
11
|
+
}
|
|
12
|
+
const controller = {
|
|
13
|
+
get active() { return !!cleanup },
|
|
14
|
+
enter(trigger) {
|
|
15
|
+
if (disposed || cleanup) return
|
|
16
|
+
const element = resolve()
|
|
17
|
+
if (!element || !element.isConnected || element === document.body || element === document.documentElement) throw new Error('没有找到需要全屏的组件预览区')
|
|
18
|
+
if (document[key]) document[key].exit()
|
|
19
|
+
const marker = document.createComment('demo fullscreen position')
|
|
20
|
+
element.before(marker)
|
|
21
|
+
const attributes = ['role', 'aria-modal', 'aria-label'].map(name => [name, element.getAttribute(name)])
|
|
22
|
+
const overflow = document.body.style.overflow
|
|
23
|
+
const previousFocus = trigger || document.activeElement
|
|
24
|
+
const scroll = [window.scrollX, window.scrollY]
|
|
25
|
+
const hadClass = element.classList.contains('leva-demo-fullscreen')
|
|
26
|
+
const exitButton = document.createElement('button')
|
|
27
|
+
exitButton.type = 'button'
|
|
28
|
+
exitButton.className = 'leva-fullscreen-exit'
|
|
29
|
+
exitButton.textContent = '退出全屏(Esc)'
|
|
30
|
+
exitButton.setAttribute('aria-label', '退出全屏')
|
|
31
|
+
exitButton.addEventListener('click', () => controller.exit())
|
|
32
|
+
document.body.appendChild(element)
|
|
33
|
+
element.classList.add('leva-demo-fullscreen')
|
|
34
|
+
element.setAttribute('role', 'dialog')
|
|
35
|
+
element.setAttribute('aria-modal', 'true')
|
|
36
|
+
element.setAttribute('aria-label', '组件全屏预览')
|
|
37
|
+
element.appendChild(exitButton)
|
|
38
|
+
document.body.style.overflow = 'hidden'
|
|
39
|
+
const siblings = [...document.body.children].filter(item => item !== element && item.tagName !== 'SCRIPT' && item.tagName !== 'STYLE')
|
|
40
|
+
const inert = siblings.map(item => [item, item.inert])
|
|
41
|
+
for (const [item] of inert) item.inert = true
|
|
42
|
+
function keydown(event) {
|
|
43
|
+
if (event.key === 'Escape') { event.preventDefault(); controller.exit(); return }
|
|
44
|
+
if (event.key !== 'Tab') return
|
|
45
|
+
const focusable = [...element.querySelectorAll('a[href],button,input,select,textarea,[tabindex]')]
|
|
46
|
+
.filter(item => item.tabIndex >= 0 && !item.matches(':disabled,[hidden]') && !item.closest('[inert]') && item.getClientRects().length)
|
|
47
|
+
const first = focusable[0] || exitButton
|
|
48
|
+
const last = focusable[focusable.length - 1] || exitButton
|
|
49
|
+
if (event.shiftKey && (document.activeElement === first || !element.contains(document.activeElement))) { event.preventDefault(); last.focus() }
|
|
50
|
+
else if (!event.shiftKey && (document.activeElement === last || !element.contains(document.activeElement))) { event.preventDefault(); first.focus() }
|
|
51
|
+
}
|
|
52
|
+
document.addEventListener('keydown', keydown)
|
|
53
|
+
cleanup = () => {
|
|
54
|
+
document.removeEventListener('keydown', keydown)
|
|
55
|
+
exitButton.remove()
|
|
56
|
+
if (!hadClass) element.classList.remove('leva-demo-fullscreen')
|
|
57
|
+
for (const [name, value] of attributes) value === null ? element.removeAttribute(name) : element.setAttribute(name, value)
|
|
58
|
+
if (marker.parentNode) marker.replaceWith(element)
|
|
59
|
+
document.body.style.overflow = overflow
|
|
60
|
+
for (const [item, value] of inert) item.inert = value
|
|
61
|
+
if (previousFocus && previousFocus.isConnected && previousFocus.focus) previousFocus.focus({ preventScroll: true })
|
|
62
|
+
window.scrollTo(...scroll)
|
|
63
|
+
}
|
|
64
|
+
document[key] = controller
|
|
65
|
+
exitButton.focus({ preventScroll: true })
|
|
66
|
+
onChange(true)
|
|
67
|
+
},
|
|
68
|
+
exit() {
|
|
69
|
+
if (!cleanup) return
|
|
70
|
+
const restore = cleanup
|
|
71
|
+
cleanup = null
|
|
72
|
+
restore()
|
|
73
|
+
if (document[key] === controller) delete document[key]
|
|
74
|
+
onChange(false)
|
|
75
|
+
},
|
|
76
|
+
toggle(trigger) { if (cleanup) controller.exit(); else controller.enter(trigger) },
|
|
77
|
+
dispose() { controller.exit(); disposed = true },
|
|
78
|
+
}
|
|
79
|
+
return controller
|
|
80
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface ModelBinding { prop: string; event: string; getValue?: ((...args: unknown[]) => unknown) | null }
|
|
2
|
+
export function defaultModelEvent(prop: string): string
|
|
3
|
+
export function normalizeModel(input: unknown): ModelBinding | null
|
|
4
|
+
export function normalizeModels(models: unknown): ModelBinding[]
|
|
5
|
+
export function schemaModels(schema?: unknown[]): ModelBinding[]
|
|
6
|
+
export function componentOptions(component: unknown): unknown
|
|
7
|
+
export function componentPropNames(component: unknown): string[]
|
|
8
|
+
export function componentEmitNames(component: unknown): string[]
|
|
9
|
+
export function componentModels(component: unknown, options?: { isVue2?: boolean }): ModelBinding[]
|
|
10
|
+
export function fallbackModels(schema?: unknown[], options?: { isVue2?: boolean }): ModelBinding[]
|
|
11
|
+
export function resolveModels(options?: { component?: unknown; schema?: unknown[]; models?: unknown; isVue2?: boolean }): ModelBinding[]
|
|
12
|
+
export function isSameValue(a: unknown, b: unknown): boolean
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/*
|
|
2
|
+
|--------------------------------------------------------------------------
|
|
3
|
+
|
|
|
4
|
+
| v-model / value 双向绑定的契约解析(与 Vue 版本无关)
|
|
5
|
+
|
|
|
6
|
+
| 面板和预览组件共用同一份 values:
|
|
7
|
+
| - 面板改值 -> v-bind 到组件
|
|
8
|
+
| - 组件内部交互 -> 组件 emit 模型事件 -> 写回 values -> 面板 refresh
|
|
9
|
+
|
|
|
10
|
+
| 模型 prop / event 的来源优先级:
|
|
11
|
+
| 1. PropsPlayground 的 models prop(显式覆盖,最可靠)
|
|
12
|
+
| 2. 组件自身的 model 选项 / Vue 3 emits 里的 update:xxx(运行时最真实)
|
|
13
|
+
| 3. schema 里 prop.model / prop.modelEvent(老组件、拿不到组件定义时)
|
|
14
|
+
| 4. schema 里存在 value / modelValue 时按默认约定兜底
|
|
15
|
+
|
|
|
16
|
+
| 注意:这里只解析“契约”,不碰 Vue 实例;PropsPlayground 负责绑定与回写。
|
|
17
|
+
|
|
|
18
|
+
|--------------------------------------------------------------------------
|
|
19
|
+
*/
|
|
20
|
+
const isBindable = prop => Boolean(prop && prop.bindable);
|
|
21
|
+
|
|
22
|
+
const UPDATE_PREFIX = 'update:';
|
|
23
|
+
|
|
24
|
+
/** 按 prop 名猜默认事件:modelValue -> update:modelValue,其余 -> input */
|
|
25
|
+
export function defaultModelEvent(prop) {
|
|
26
|
+
return prop === 'modelValue' ? `${UPDATE_PREFIX}modelValue` : 'input';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 把各种写法归一成 { prop, event, getValue? }
|
|
31
|
+
*
|
|
32
|
+
* 支持:
|
|
33
|
+
* - 'value'
|
|
34
|
+
* - { prop: 'selectValue', event: 'change' }
|
|
35
|
+
* - { name: 'checked', event: 'change', getValue: (...args) => ... }
|
|
36
|
+
*/
|
|
37
|
+
export function normalizeModel(input) {
|
|
38
|
+
if (!input) return null;
|
|
39
|
+
if (typeof input === 'string') {
|
|
40
|
+
return { prop: input, event: defaultModelEvent(input) };
|
|
41
|
+
}
|
|
42
|
+
const prop = input.prop || input.name;
|
|
43
|
+
if (!prop) return null;
|
|
44
|
+
return {
|
|
45
|
+
prop,
|
|
46
|
+
event: input.event || input.modelEvent || defaultModelEvent(prop),
|
|
47
|
+
getValue: typeof input.getValue === 'function' ? input.getValue : null,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 单个 model 或 model 数组 -> 数组 */
|
|
52
|
+
export function normalizeModels(models) {
|
|
53
|
+
if (!models) return [];
|
|
54
|
+
const list = Array.isArray(models) ? models : [models];
|
|
55
|
+
return list.map(normalizeModel).filter(Boolean);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 从 schema 读取模型标记:
|
|
60
|
+
* { name: 'selectValue', model: true, modelEvent: 'change' }
|
|
61
|
+
* { name: 'value', model: { event: 'change' } }
|
|
62
|
+
*/
|
|
63
|
+
export function schemaModels(schema) {
|
|
64
|
+
return (schema || []).reduce((models, prop) => {
|
|
65
|
+
if (!prop || !prop.model) return models;
|
|
66
|
+
const config = typeof prop.model === 'object' ? prop.model : {};
|
|
67
|
+
const model = normalizeModel({
|
|
68
|
+
prop: config.prop || prop.name,
|
|
69
|
+
event: config.event || prop.modelEvent,
|
|
70
|
+
getValue: config.getValue,
|
|
71
|
+
});
|
|
72
|
+
if (model) models.push(model);
|
|
73
|
+
return models;
|
|
74
|
+
}, []);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 组件定义:Vue 2 的构造函数是 { options },普通对象/Vue 3 直接就是 options */
|
|
78
|
+
export function componentOptions(component) {
|
|
79
|
+
if (!component) return null;
|
|
80
|
+
if (component.options) return component.options;
|
|
81
|
+
if (typeof component === 'function') return component.options || null;
|
|
82
|
+
return component;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 组件显式声明的 props 名;拿不到时返回 [](比如远程代理壳) */
|
|
86
|
+
export function componentPropNames(component) {
|
|
87
|
+
const options = componentOptions(component);
|
|
88
|
+
const props = options && options.props;
|
|
89
|
+
if (!props) return [];
|
|
90
|
+
return Array.isArray(props) ? props.slice() : Object.keys(props);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** 组件显式声明的 emits 名(Vue 3) */
|
|
94
|
+
export function componentEmitNames(component) {
|
|
95
|
+
const options = componentOptions(component);
|
|
96
|
+
const emits = options && options.emits;
|
|
97
|
+
if (!emits) return [];
|
|
98
|
+
return Array.isArray(emits) ? emits.slice() : Object.keys(emits);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 从组件定义里读取“显式”的模型契约。
|
|
103
|
+
*
|
|
104
|
+
* Vue 2:只认 model 选项;没有时交给 schema 标记 / 默认约定兜底,
|
|
105
|
+
* 这样 schema 里的 modelEvent 才能覆盖 value + input 的默认推断。
|
|
106
|
+
* Vue 3:emits 里声明的 update:xxx(对应 v-model:xxx,可以一次同步多个模型)。
|
|
107
|
+
*/
|
|
108
|
+
export function componentModels(component, options = {}) {
|
|
109
|
+
const { isVue2 = true } = options;
|
|
110
|
+
const resolved = componentOptions(component);
|
|
111
|
+
if (!resolved) return [];
|
|
112
|
+
|
|
113
|
+
if (isVue2) {
|
|
114
|
+
const model = normalizeModel(resolved.model);
|
|
115
|
+
return model ? [model] : [];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const props = componentPropNames(component);
|
|
119
|
+
const emits = componentEmitNames(component);
|
|
120
|
+
const models = [];
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
|
|
123
|
+
emits.forEach((event) => {
|
|
124
|
+
if (!event.startsWith(UPDATE_PREFIX)) return;
|
|
125
|
+
const prop = event.slice(UPDATE_PREFIX.length);
|
|
126
|
+
if (!prop || seen.has(prop)) return;
|
|
127
|
+
if (props.length && !props.includes(prop)) return;
|
|
128
|
+
seen.add(prop);
|
|
129
|
+
models.push({ prop, event });
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
return models;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** schema 里有 value / modelValue 时按框架默认约定兜底 */
|
|
136
|
+
export function fallbackModels(schema, options = {}) {
|
|
137
|
+
const { isVue2 = true } = options;
|
|
138
|
+
const names = new Set((schema || []).map((prop) => prop && prop.name).filter(Boolean));
|
|
139
|
+
const models = [];
|
|
140
|
+
|
|
141
|
+
const add = (prop, event) => {
|
|
142
|
+
if (names.has(prop)) models.push({ prop, event });
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
if (isVue2) {
|
|
146
|
+
add('value', 'input');
|
|
147
|
+
add('modelValue', `${UPDATE_PREFIX}modelValue`);
|
|
148
|
+
} else {
|
|
149
|
+
add('modelValue', `${UPDATE_PREFIX}modelValue`);
|
|
150
|
+
add('value', 'input');
|
|
151
|
+
}
|
|
152
|
+
return models;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 解析当前组件要同步的模型列表。
|
|
157
|
+
*
|
|
158
|
+
* @param {object} options
|
|
159
|
+
* @param {object|Function} options.component 预览组件
|
|
160
|
+
* @param {Array} options.schema 组件的 propsSchema
|
|
161
|
+
* @param {object|Array} [options.models] 宿主显式配置,优先级最高
|
|
162
|
+
* @param {boolean} [options.isVue2=true] 当前运行时
|
|
163
|
+
* @returns {Array<{prop:string,event:string,getValue?:Function}>}
|
|
164
|
+
*/
|
|
165
|
+
export function resolveModels(options = {}) {
|
|
166
|
+
const { component, schema, models, isVue2 = true } = options;
|
|
167
|
+
const explicit = normalizeModels(models);
|
|
168
|
+
const candidates = (
|
|
169
|
+
explicit.length
|
|
170
|
+
? explicit
|
|
171
|
+
: [
|
|
172
|
+
...componentModels(component, { isVue2 }),
|
|
173
|
+
...schemaModels(schema),
|
|
174
|
+
...fallbackModels(schema, { isVue2 }),
|
|
175
|
+
]
|
|
176
|
+
)
|
|
177
|
+
.map(normalizeModel)
|
|
178
|
+
.filter(Boolean);
|
|
179
|
+
|
|
180
|
+
// 面板上只有 bindable 的 prop 有控件;没有控件就没必要回写。
|
|
181
|
+
// 显式 models 允许指向非 bindable(宿主可能自己接住 values)。
|
|
182
|
+
const bindable = new Set((schema || []).filter(isBindable).map((prop) => prop.name));
|
|
183
|
+
const seen = new Set();
|
|
184
|
+
|
|
185
|
+
return candidates.filter((model) => {
|
|
186
|
+
if (!model || !model.prop || !model.event) return false;
|
|
187
|
+
// 同一个 prop 只同步一次;候选顺序已经保证了显式 > 组件 > schema > 兜底
|
|
188
|
+
const key = model.prop;
|
|
189
|
+
if (seen.has(key)) return false;
|
|
190
|
+
seen.add(key);
|
|
191
|
+
if (explicit.length) return true;
|
|
192
|
+
return !bindable.size || bindable.has(model.prop);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** 判断两个面板值是否等价(数组按元素比较,对象仍用引用比较) */
|
|
197
|
+
export function isSameValue(a, b) {
|
|
198
|
+
if (Object.is(a, b)) return true;
|
|
199
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
200
|
+
return a.length === b.length && a.every((item, index) => Object.is(item, b[index]));
|
|
201
|
+
}
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Keep executable examples as source strings: production obfuscation must not
|
|
2
|
+
// rewrite function bodies that will later run in a separate HTML document.
|
|
3
|
+
export const vue3 = String.raw`
|
|
4
|
+
const slotMap = typeof example.slotHtml === 'string' ? { default: example.slotHtml } : example.slotHtml || {}
|
|
5
|
+
const RemoteComponent = defineHelComponent({ dep: example.packageName, exportName: example.component })
|
|
6
|
+
const props = Vue.reactive({ ...example.props })
|
|
7
|
+
if (example.openProp) props[example.openProp] = false
|
|
8
|
+
Vue.createApp({
|
|
9
|
+
mounted() { if (example.openProp) props[example.openProp] = true },
|
|
10
|
+
render() {
|
|
11
|
+
return Vue.h(RemoteComponent, props, Object.fromEntries(Object.entries(slotMap).map(([name, html]) => [name, () => Vue.h('div', { innerHTML: html })])))
|
|
12
|
+
},
|
|
13
|
+
}).mount('#demo-root')
|
|
14
|
+
`
|
|
15
|
+
|
|
16
|
+
export const vue2 = String.raw`
|
|
17
|
+
const slotMap = typeof example.slotHtml === 'string' ? { default: example.slotHtml } : example.slotHtml || {}
|
|
18
|
+
const RemoteComponent = defineHelComponent({ dep: example.packageName, exportName: example.component })
|
|
19
|
+
new Vue({
|
|
20
|
+
data: () => ({ values: { ...example.props, ...(example.openProp ? { [example.openProp]: false } : {}) } }),
|
|
21
|
+
mounted() { if (example.openProp) this.$set(this.values, example.openProp, true) },
|
|
22
|
+
render(h) {
|
|
23
|
+
return h(RemoteComponent, { attrs: this.values, scopedSlots: Object.fromEntries(Object.entries(slotMap).map(([name, html]) => [name, () => h('div', { domProps: { innerHTML: html } })])) })
|
|
24
|
+
},
|
|
25
|
+
}).$mount('#demo-root')
|
|
26
|
+
`
|
|
27
|
+
|
|
28
|
+
// Modal components must receive false -> true after the real component mounts,
|
|
29
|
+
// rather than when its still-loading lazy wrapper mounts.
|
|
30
|
+
export const vue2Modal = String.raw`
|
|
31
|
+
const slotMap = typeof example.slotHtml === 'string' ? { default: example.slotHtml } : example.slotHtml || {}
|
|
32
|
+
const RemotePreview = defineHelComponent({
|
|
33
|
+
exportName: 'Preview',
|
|
34
|
+
loader: async () => {
|
|
35
|
+
const Component = await loadHelComponent({ dep: example.packageName, exportName: example.component })
|
|
36
|
+
return { Preview: {
|
|
37
|
+
data: () => ({ values: { ...example.props, [example.openProp]: false } }),
|
|
38
|
+
mounted() { this.$nextTick(() => this.$set(this.values, example.openProp, true)) },
|
|
39
|
+
render(h) {
|
|
40
|
+
return h(Component, { props: this.values, scopedSlots: Object.fromEntries(Object.entries(slotMap).map(([name, html]) => [name, () => h('div', { domProps: { innerHTML: html } })])) })
|
|
41
|
+
},
|
|
42
|
+
} }
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
new Vue({ render: h => h(RemotePreview) }).$mount('#demo-root')
|
|
46
|
+
`
|
|
47
|
+
|
|
48
|
+
export const vue3Modal = String.raw`
|
|
49
|
+
const slotMap = typeof example.slotHtml === 'string' ? { default: example.slotHtml } : example.slotHtml || {}
|
|
50
|
+
const RemotePreview = defineHelComponent({
|
|
51
|
+
exportName: 'Preview',
|
|
52
|
+
loader: async () => {
|
|
53
|
+
const Component = await loadHelComponent({ dep: example.packageName, exportName: example.component })
|
|
54
|
+
return { Preview: {
|
|
55
|
+
setup() {
|
|
56
|
+
const props = Vue.reactive({ ...example.props, [example.openProp]: false })
|
|
57
|
+
Vue.onMounted(() => Vue.nextTick(() => { props[example.openProp] = true }))
|
|
58
|
+
return () => Vue.h(Component, props, Object.fromEntries(Object.entries(slotMap).map(([name, html]) => [name, () => Vue.h('div', { innerHTML: html })])))
|
|
59
|
+
},
|
|
60
|
+
} }
|
|
61
|
+
},
|
|
62
|
+
})
|
|
63
|
+
Vue.createApp({ render: () => Vue.h(RemotePreview) }).mount('#demo-root')
|
|
64
|
+
`
|
|
65
|
+
|
|
66
|
+
export const react = String.raw`
|
|
67
|
+
bindReactRuntime({ React, ReactDOM, ReactIs })
|
|
68
|
+
// 面板包先于组件包准备;加载请求由 core 复用,错误和重试由适配层处理。
|
|
69
|
+
const panelDep = '@melt-js/libs-react-leva'
|
|
70
|
+
const loader = async () => {
|
|
71
|
+
if (example.panelSchema) await loadHelLib(panelDep)
|
|
72
|
+
return loadHelLib(example.packageName)
|
|
73
|
+
}
|
|
74
|
+
const items = example.items.map(item => ({ ...item,
|
|
75
|
+
Component: defineHelComponent({ loader, exportName: item.name }),
|
|
76
|
+
}))
|
|
77
|
+
let content
|
|
78
|
+
if (example.propsPanel) {
|
|
79
|
+
const item = items[0]
|
|
80
|
+
const Panel = defineHelComponent({ dep: panelDep, exportName: 'PropsPanel' })
|
|
81
|
+
function Preview() {
|
|
82
|
+
const [values, setValues] = React.useState(item.props)
|
|
83
|
+
const onChange = React.useCallback(next => setValues({ ...item.props, ...next }), [])
|
|
84
|
+
return React.createElement('div', null,
|
|
85
|
+
React.createElement(item.Component, values),
|
|
86
|
+
React.createElement(Panel, { compName: item.name, schema: example.panelSchema, value: values, onChange }))
|
|
87
|
+
}
|
|
88
|
+
content = React.createElement(Preview)
|
|
89
|
+
} else if (example.panelSchema) {
|
|
90
|
+
const item = items[0]
|
|
91
|
+
const Playground = defineHelComponent({ dep: panelDep, exportName: 'PropsPlayground' })
|
|
92
|
+
content = React.createElement(Playground, {
|
|
93
|
+
components: { [item.name]: item.Component },
|
|
94
|
+
schemas: { [item.name]: example.panelSchema },
|
|
95
|
+
presets: { [item.name]: item.props },
|
|
96
|
+
stageStyles: { [item.name]: { height: '320px', background: '#f6f7f9' } },
|
|
97
|
+
})
|
|
98
|
+
} else {
|
|
99
|
+
content = React.createElement('div', { className: items.length > 1 ? 'example-grid' : '' },
|
|
100
|
+
...items.map(item => React.createElement('section', { key: item.name, className: 'example-item' },
|
|
101
|
+
React.createElement('h2', null, item.label), React.createElement(item.Component, item.props, item.slotHtml?.default ? React.createElement('span', { dangerouslySetInnerHTML: { __html: item.slotHtml.default } }) : item.props.children))))
|
|
102
|
+
}
|
|
103
|
+
ReactDOM.createRoot(document.getElementById('demo-root')).render(content)
|
|
104
|
+
`
|
package/src/remote.d.mts
CHANGED