@melt-js/libs-core 2026.11.15 → 2026.11.16

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.
Files changed (76) hide show
  1. package/README.md +35 -2
  2. package/dist/browser.d.mts +3 -0
  3. package/dist/browser.mjs +1 -50
  4. package/dist/browser.mjs.gz +0 -0
  5. package/dist/cdn/browser.umd.cjs +2 -0
  6. package/dist/cdn/browser.umd.cjs.gz +0 -0
  7. package/dist/cdn/demo-browser.umd.cjs +2 -0
  8. package/dist/cdn/demo-browser.umd.cjs.gz +0 -0
  9. package/dist/cdn/demo.umd.cjs +2 -0
  10. package/dist/cdn/demo.umd.cjs.gz +0 -0
  11. package/dist/cdn/example-esm.html +1 -0
  12. package/dist/cdn/example-umd.html +1 -0
  13. package/dist/cdn/index.umd.cjs +2 -0
  14. package/dist/cdn/index.umd.cjs.gz +0 -0
  15. package/dist/cdn/manifest.json +129 -0
  16. package/dist/cdn/vendor.umd.cjs +50 -0
  17. package/dist/cdn/vendor.umd.cjs.gz +0 -0
  18. package/dist/cdn.d.mts +3 -0
  19. package/dist/cdn.mjs +1 -0
  20. package/dist/demo/browser.mjs +1 -0
  21. package/dist/demo/browser.mjs.gz +0 -0
  22. package/dist/demo/clipboard.d.mts +6 -0
  23. package/dist/demo/clipboard.mjs +1 -0
  24. package/{src → dist}/demo/docs.d.mts +3 -0
  25. package/dist/demo/docs.mjs +1 -0
  26. package/dist/demo/docs.mjs.gz +0 -0
  27. package/{src → dist}/demo/download.d.mts +38 -33
  28. package/dist/demo/download.mjs +1 -0
  29. package/dist/demo/download.mjs.gz +0 -0
  30. package/dist/demo/fullscreen.mjs +1 -0
  31. package/dist/demo/index.d.mts +9 -0
  32. package/dist/demo/index.mjs +1 -0
  33. package/dist/demo/model.mjs +1 -0
  34. package/dist/demo/remote-debug.d.mts +11 -0
  35. package/dist/demo/remote-debug.mjs +1 -0
  36. package/{src → dist}/demo/runtime.mjs +92 -104
  37. package/dist/demo/split-pane.d.mts +8 -0
  38. package/dist/demo/split-pane.mjs +1 -0
  39. package/dist/demo/standalone.d.mts +9 -0
  40. package/dist/demo/standalone.mjs +1 -0
  41. package/dist/demo/tabs.d.mts +15 -0
  42. package/dist/demo/tabs.mjs +1 -0
  43. package/{src/index.ts → dist/index.d.ts} +1 -1
  44. package/dist/loading.mjs +1 -0
  45. package/dist/remote-address.cjs +2 -0
  46. package/{src → dist}/remote.d.mts +16 -2
  47. package/dist/remote.mjs +1 -0
  48. package/dist/remote.mjs.gz +0 -0
  49. package/dist/vendor/hel-runtime.mjs +50 -0
  50. package/dist/vendor/hel-runtime.mjs.gz +0 -0
  51. package/package.json +41 -25
  52. package/scripts/browser-formats.mjs +355 -0
  53. package/scripts/build-browser.mjs +59 -13
  54. package/scripts/build-protected-esm.mjs +51 -0
  55. package/scripts/cdn-runtime.cjs +30 -0
  56. package/scripts/check-tdz.mjs +327 -324
  57. package/scripts/comps-bundle-obfuscation.cjs +2 -1
  58. package/scripts/package-artifacts.mjs +199 -0
  59. package/scripts/package-env.cjs +193 -193
  60. package/scripts/publish-stage.mjs +50 -42
  61. package/scripts/webpack-bundle-obfuscation.cjs +13 -0
  62. package/demo/index.js +0 -1
  63. package/dist/hel-deployment.json +0 -8
  64. package/src/browser.d.mts +0 -2
  65. package/src/browser.mjs +0 -3
  66. package/src/demo/docs.mjs +0 -75
  67. package/src/demo/download.mjs +0 -118
  68. package/src/demo/fullscreen.mjs +0 -80
  69. package/src/demo/index.d.mts +0 -4
  70. package/src/demo/index.mjs +0 -4
  71. package/src/demo/model.mjs +0 -203
  72. package/src/remote.mjs +0 -286
  73. package/tsconfig.json +0 -13
  74. /package/{src → dist}/demo/fullscreen.d.mts +0 -0
  75. /package/{src → dist}/demo/model.d.mts +0 -0
  76. /package/{src → scripts}/remote-address.cjs +0 -0
@@ -1,45 +1,53 @@
1
1
  #!/usr/bin/env node
2
- import { execSync } from 'node:child_process'
3
- import fs from 'node:fs'
4
- import os from 'node:os'
5
- import path from 'node:path'
6
-
7
- // 统一的 stage 发布入口:先 pnpm pack 再 npm stage publish。
8
- //
9
- // 为什么不能直接 `npx npm stage publish`:
10
- // npm 不认识 workspace: 协议,会把 `workspace:*` 原样写进 tarball 的 package.json,
11
- // 消费方安装时直接报 EUNSUPPORTEDPROTOCOL(例如 2026.11.8-1 的 ele-pure-full)。
12
- // pnpm pack 会把 workspace:* 改写成实际版本,再由 npm 把 tarball 送上 stage。
13
- //
14
- // prepublishOnly 的守卫(版本号 / hel-meta / localhost 资源地址)不会被 tarball 流程触发,
15
- // 这里显式跑一次,避免绕过 comps-* / libs-* 的发布前检查。
16
-
17
- const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'))
18
- if (pkg.private) {
19
- throw new Error('[publish:stage] 当前 package.json 是 private,请在要发布的包目录里执行')
20
- }
21
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hel-stage-'))
22
- const run = (command) => execSync(command, { stdio: 'inherit' })
23
- let npmStage = 'npm'
24
- try {
25
- execSync('npm stage --help', { stdio: 'ignore' })
26
- } catch {
27
- npmStage = 'pnpm --registry=https://registry.npmjs.org --package=npm@11 dlx npm'
2
+ import { execSync } from 'node:child_process'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ // 统一的 stage 发布入口:先 pnpm pack 再 npm stage publish。
8
+ //
9
+ // 为什么不能直接 `npx npm stage publish`:
10
+ // npm 不认识 workspace: 协议,会把 `workspace:*` 原样写进 tarball 的 package.json,
11
+ // 消费方安装时直接报 EUNSUPPORTEDPROTOCOL(例如 2026.11.8-1 的 ele-pure-full)。
12
+ // pnpm pack 会把 workspace:* 改写成实际版本,再由 npm 把 tarball 送上 stage。
13
+ //
14
+ // prepublishOnly 的守卫(版本号 / hel-meta / localhost 资源地址)不会被 tarball 流程触发,
15
+ // 这里显式跑一次,避免绕过 comps-* / libs-* 的发布前检查。
16
+
17
+ const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'))
18
+ const args = process.argv.slice(2)
19
+ if (args.some(arg => arg !== '--dry-run')) throw new Error('用法:hel-publish-stage [--dry-run]')
20
+ const dryRun = args.includes('--dry-run')
21
+ if (pkg.private) {
22
+ throw new Error('[publish:stage] 当前 package.json 是 private,请在要发布的包目录里执行')
28
23
  }
29
-
30
- try {
31
- if (pkg.scripts && pkg.scripts.prepublishOnly) {
32
- run('pnpm run prepublishOnly')
33
- }
34
-
35
- run(`pnpm pack --pack-destination "${tmp}"`)
36
- const tgz = fs.readdirSync(tmp).find((file) => file.endsWith('.tgz'))
37
- if (!tgz) throw new Error('pnpm pack 没有产出 tarball')
38
-
39
- run(
24
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hel-stage-'))
25
+ const run = (command) => execSync(command, { stdio: 'inherit' })
26
+ try {
27
+ if (pkg.scripts && pkg.scripts.prepublishOnly) {
28
+ run('pnpm run prepublishOnly')
29
+ }
30
+
31
+ run(`pnpm pack --pack-destination "${tmp}"`)
32
+ const tgz = fs.readdirSync(tmp).find((file) => file.endsWith('.tgz'))
33
+ if (!tgz) throw new Error('pnpm pack 没有产出 tarball')
34
+
35
+ if (dryRun) {
36
+ console.log(`[publish:stage] dry-run: ${pkg.name}@${pkg.version} packed; 未上传或修改版本。保留产物:${path.join(tmp, tgz)}`)
37
+ process.exitCode = 0
38
+ } else {
39
+ let npmStage = 'npm'
40
+ try {
41
+ execSync('npm stage --help', { stdio: 'ignore' })
42
+ } catch {
43
+ npmStage = 'pnpm --registry=https://registry.npmjs.org --package=npm@11 dlx npm'
44
+ }
45
+
46
+ run(
40
47
  `${npmStage} stage publish "${path.join(tmp, tgz)}" --registry=https://registry.npmjs.org --access public`,
41
- )
42
- console.log(`[publish:stage] ${pkg.name}@${pkg.version} staged`)
43
- } finally {
44
- fs.rmSync(tmp, { recursive: true, force: true })
45
- }
48
+ )
49
+ console.log(`[publish:stage] ${pkg.name}@${pkg.version} staged`)
50
+ }
51
+ } finally {
52
+ if (!dryRun) fs.rmSync(tmp, { recursive: true, force: true })
53
+ }
@@ -111,6 +111,19 @@ function webpackBundlePolicy({ root, Obfuscator, enabled = true }) {
111
111
 
112
112
  function applyWebpackBundlePolicy(config, { root, Obfuscator, enabled = process.env.HEL_OBFUSCATE !== '0' }) {
113
113
  if (process.env.NODE_ENV !== 'production' && config.mode !== 'production') return config
114
+ // Deployment base candidates are build inputs. Only the selected publicPath/remote slots belong in client code.
115
+ // Vue CLI serializes the full process.env object for dependencies using dynamic environment access.
116
+ const deploymentBase = /^(?:VUE_APP_|REACT_APP_|VITE_)(?:SFTP|GITHUB|UNPKG)_PUBLIC_URL$/
117
+ for (const plugin of config.plugins || []) {
118
+ if (plugin?.constructor?.name !== 'DefinePlugin') continue
119
+ const definitions = plugin.definitions || {}
120
+ for (const key of Object.keys(definitions['process.env'] || {})) {
121
+ if (deploymentBase.test(key)) delete definitions['process.env'][key]
122
+ }
123
+ for (const key of Object.keys(definitions)) {
124
+ if (deploymentBase.test(key.replace(/^process\.env\./, ''))) delete definitions[key]
125
+ }
126
+ }
114
127
  const policy = webpackBundlePolicy({ root, Obfuscator, enabled })
115
128
  config.devtool = false
116
129
  config.plugins = (config.plugins || []).filter(plugin => plugin?.constructor?.name !== 'LimitChunkCountPlugin')
package/demo/index.js DELETED
@@ -1 +0,0 @@
1
- export * from '../src/demo/index.mjs'
@@ -1,8 +0,0 @@
1
- {
2
- "target": "unpkg",
3
- "name": "@melt-js/libs-core",
4
- "version": "2026.11.15",
5
- "publicUrl": "https://unpkg.com/@melt-js/libs-core@2026.11.15/dist",
6
- "homePage": "/@melt-js/libs-core@2026.11.15/dist",
7
- "remotes": {}
8
- }
package/src/browser.d.mts DELETED
@@ -1,2 +0,0 @@
1
- export * from './remote.mjs'
2
- export { bindReactRuntime } from 'hel-micro'
package/src/browser.mjs DELETED
@@ -1,3 +0,0 @@
1
- // A bundled, native ESM entry for HTML hosts without a package bundler.
2
- export * from './remote.mjs'
3
- export { bindReactRuntime } from 'hel-micro'
package/src/demo/docs.mjs DELETED
@@ -1,75 +0,0 @@
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, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '&#10;')
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
- }
@@ -1,118 +0,0 @@
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
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
- }
@@ -1,80 +0,0 @@
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
- }
@@ -1,4 +0,0 @@
1
- export * from './download.mjs'
2
- export * from './docs.mjs'
3
- export * from './fullscreen.mjs'
4
- export * from './model.mjs'
@@ -1,4 +0,0 @@
1
- export * from './download.mjs'
2
- export * from './docs.mjs'
3
- export * from './fullscreen.mjs'
4
- export * from './model.mjs'
@@ -1,203 +0,0 @@
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
- }