@weapp-vite/web 1.6.0 → 2.0.0
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 +22 -0
- package/dist/css/wxss.mjs +2 -1
- package/dist/css/wxss.mjs.map +1 -1
- package/dist/plugin/hostTypes.d.mts +74 -0
- package/dist/plugin/index.d.mts +2 -74
- package/dist/plugin/index.mjs +9 -2
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/sfcHmr.mjs +19 -0
- package/dist/plugin/sfcHmr.mjs.map +1 -0
- package/dist/plugin/vueSfc.mjs +12 -9
- package/dist/plugin/vueSfc.mjs.map +1 -1
- package/dist/runtime/appStyle.mjs +25 -0
- package/dist/runtime/appStyle.mjs.map +1 -0
- package/dist/runtime/component/element.mjs +39 -19
- package/dist/runtime/component/element.mjs.map +1 -1
- package/dist/runtime/component/events.mjs +34 -3
- package/dist/runtime/component/events.mjs.map +1 -1
- package/dist/runtime/component/publicInstance.mjs +7 -3
- package/dist/runtime/component/publicInstance.mjs.map +1 -1
- package/dist/runtime/component/state.mjs +7 -0
- package/dist/runtime/component/state.mjs.map +1 -1
- package/dist/runtime/component/types.d.mts +2 -0
- package/dist/runtime/component/utils.mjs +23 -3
- package/dist/runtime/component/utils.mjs.map +1 -1
- package/dist/runtime/componentEvents.mjs +37 -0
- package/dist/runtime/componentEvents.mjs.map +1 -0
- package/dist/runtime/eventBinding.mjs +5 -2
- package/dist/runtime/eventBinding.mjs.map +1 -1
- package/dist/runtime/legacyTemplate/dom.mjs +2 -7
- package/dist/runtime/legacyTemplate/dom.mjs.map +1 -1
- package/dist/runtime/nativeComponents/canvas/index.mjs +12 -3
- package/dist/runtime/nativeComponents/canvas/index.mjs.map +1 -1
- package/dist/runtime/polyfill/routeRuntime.d.mts +1 -1
- package/dist/runtime/polyfill/routeRuntime.mjs +5 -1
- package/dist/runtime/polyfill/routeRuntime.mjs.map +1 -1
- package/dist/runtime/renderContext.mjs +3 -2
- package/dist/runtime/renderContext.mjs.map +1 -1
- package/dist/runtime/wevu.mjs +2 -0
- package/dist/runtime/wevu.mjs.map +1 -1
- package/dist/shared/wxml.mjs +5 -1
- package/dist/shared/wxml.mjs.map +1 -1
- package/package.json +14 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vueSfc.mjs","names":[],"sources":["../../src/plugin/vueSfc.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { VueTransformResult } from 'wevu/compiler'\nimport type { ModuleMeta, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState, WebStylePreprocessOptions } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { fs } from '@weapp-core/shared/fs'\nimport { transform } from 'esbuild'\nimport MagicString from 'magic-string'\nimport path from 'pathe'\nimport { compileVueFile, isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { resolveScriptFile } from './files'\nimport { appendInlineQuery, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\n\nconst traverse = _babelTraverse\n\nasync function resolveSfcSrc(\n request: string,\n importer: string,\n srcRoot: string,\n resolveId?: ResolveWebModuleId,\n) {\n if (request.startsWith('@/')) {\n return path.resolve(srcRoot, request.slice(2))\n }\n if (request.startsWith('.')) {\n return path.resolve(path.dirname(importer), request)\n }\n if (request.startsWith('/')) {\n return path.resolve(srcRoot, request.slice(1))\n }\n return await resolveId?.(request, importer)\n}\n\nexport async function compileWebVueSfc(options: {\n source: string\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const { filename, meta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions } = options\n const source = uniApp && isUniAppCompatibilityFile(filename, srcRoot, uniApp.include)\n ? transformUniAppSource(options.source, { filename, target: 'h5' }).code\n : options.source\n const result = await compileVueFile(source, filename, {\n isApp: meta.kind === 'app',\n isPage: meta.kind === 'page',\n sourceMap: false,\n style: {\n preprocessOptions: stylePreprocessOptions,\n preserveDeepSelectors: true,\n transformScoped: false,\n },\n json: { kind: meta.kind },\n autoUsingComponents: {\n enabled: true,\n resolveUsingComponentPath: async (request, importer) => {\n const base = request.startsWith('@/')\n ? path.resolve(srcRoot, request.slice(2))\n : request.startsWith('.')\n ? path.resolve(path.dirname(importer), request)\n : request.startsWith('/')\n ? path.resolve(srcRoot, request.slice(1))\n : undefined\n if (!base) {\n return undefined\n }\n const resolvedId = await resolveScriptFile(base)\n if (!resolvedId) {\n return undefined\n }\n return {\n from: request,\n resolvedId,\n sourceType: resolvedId.endsWith('.vue') ? 'wevu-sfc' : 'native',\n }\n },\n },\n autoImportTags: {\n enabled: Boolean(resolveAutoImportTag),\n resolveUsingComponent: async (tag, importer) => resolveAutoImportTag?.(tag, importer),\n },\n sfcSrc: {\n resolveId: async (request, importer) => {\n return resolveSfcSrc(request, importer!, srcRoot, resolveId)\n },\n },\n })\n state.sfcResults.set(filename, result)\n for (const dependency of result.meta?.sfcSrcDeps ?? []) {\n state.templatePathSet.add(dependency)\n }\n return result\n}\n\nexport async function ensureWebVueSfcResult(options: {\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n source?: string\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const cached = options.state.sfcResults.get(options.filename)\n if (cached) {\n return cached\n }\n const source = options.source ?? await fs.readFile(options.filename, 'utf8')\n return await compileWebVueSfc({ ...options, source })\n}\n\nfunction getSfcRegisterName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'registerWebWevuApp' : 'registerWebWevuComponent'\n}\n\nfunction getSfcFactoryName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'createApp' : 'createWevuComponent'\n}\n\nfunction createRegisterMetaCode(meta: ModuleMeta, templateIdent?: string, styleIdent?: string) {\n const parts = [`id: ${JSON.stringify(meta.id)}`, `kind: ${JSON.stringify(meta.kind)}`]\n if (templateIdent) {\n parts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n parts.push(`style: ${styleIdent}`)\n }\n if (meta.navigationBar) {\n parts.push(`navigationBar: ${JSON.stringify(meta.navigationBar)}`)\n }\n return `{ ${parts.join(', ')} }`\n}\n\nexport async function transformWebVueSfcScript(options: {\n code: string\n filename: string\n meta: ModuleMeta\n runtimeModuleId: string\n styleLanguage: string\n enableHmr: boolean\n hmrAcceptCode?: string\n}) {\n const { code, filename, meta, runtimeModuleId, styleLanguage, enableHmr, hmrAcceptCode } = options\n const ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n ranges: true,\n })\n const s = new MagicString(code)\n const templateIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_template__'\n const styleIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_style__'\n const registerName = getSfcRegisterName(meta.kind)\n const factoryName = getSfcFactoryName(meta.kind)\n const registerMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent)\n let transformed = false\n\n traverse(ast, {\n CallExpression(nodePath: NodePath<CallExpression>) {\n const callee = nodePath.node.callee\n if (!t.isIdentifier(callee, { name: factoryName })) {\n return\n }\n s.overwrite(callee.start!, callee.end!, registerName)\n s.appendLeft(nodePath.node.end! - 1, `, ${registerMetaCode}`)\n transformed = true\n },\n })\n\n if (!transformed) {\n throw new Error(`[@weapp-vite/web] Vue SFC 未生成 ${factoryName} 注册调用: ${filename}`)\n }\n\n const imports = [`import { ${registerName} } from '${runtimeModuleId}'`]\n if (templateIdent) {\n imports.push(`import ${templateIdent} from '${toRelativeImport(filename, filename)}?weapp-web-sfc-template'`)\n }\n if (styleIdent) {\n const styleFilename = `${filename}.${styleLanguage}`\n imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`)\n }\n s.prepend(`${imports.join('\\n')}\\n`)\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n const transpiled = await transform(s.toString(), {\n format: 'esm',\n legalComments: 'inline',\n loader: 'ts',\n sourcefile: filename,\n sourcemap: 'external',\n target: 'es2022',\n })\n return {\n code: transpiled.code,\n map: JSON.parse(transpiled.map),\n }\n}\n\nexport function generateWebVueSfcTemplate(\n result: VueTransformResult,\n meta: ModuleMeta,\n filename: string,\n srcRoot: string,\n) {\n const compiled = compileWxml({\n id: filename,\n source: result.template ?? '',\n navigationBar: meta.navigationBar ? { config: meta.navigationBar } : undefined,\n componentTags: meta.componentTags,\n resolveTemplatePath: (request, importer) => resolveTemplatePathSync(request, importer, srcRoot),\n resolveWxsPath: (request, importer) => resolveWxsPathSync(request, importer, srcRoot),\n })\n return compiled\n}\n\nexport function resolveWebVueSfcStyleLanguage(result: VueTransformResult, filename: string) {\n const languages = new Set(\n (result.meta?.styleBlocks ?? []).map(style => style.lang?.trim() || 'css'),\n )\n for (const language of languages) {\n if (!/^[a-z][a-z0-9-]*$/i.test(language)) {\n throw new Error(`[@weapp-vite/web] Vue SFC 样式语言无效: ${filename} -> ${language}`)\n }\n }\n const preprocessLanguages = [...languages].filter(language => language !== 'css')\n if (preprocessLanguages.length > 1) {\n throw new Error(`[@weapp-vite/web] Vue SFC 暂不支持混合样式语言: ${filename}`)\n }\n return preprocessLanguages[0] ?? 'css'\n}\n\nexport function generateWebVueSfcStyle(result: VueTransformResult) {\n return result.style ?? ''\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW;AAEjB,eAAe,cACb,SACA,UACA,SACA,WACA;CACA,IAAI,QAAQ,WAAW,IAAI,GACzB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,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AAO,YAAY;EAC3B,eAAe,KAAK,gBAAgB,EAAE,QAAQ,KAAK,cAAc,IAAI;EACrE,eAAe,KAAK;EACpB,sBAAsB,SAAS,aAAa,wBAAwB,SAAS,UAAU,OAAO;EAC9F,iBAAiB,SAAS,aAAa,mBAAmB,SAAS,UAAU,OAAO;CACtF,CACc;AAChB;AAEA,SAAgB,8BAA8B,QAA4B,UAAkB;CAC1F,MAAM,YAAY,IAAI,KACnB,OAAO,MAAM,eAAe,CAAC,EAAC,CAAE,KAAI,UAAS,MAAM,MAAM,KAAK,KAAK,KAAK,CAC3E;CACA,KAAK,MAAM,YAAY,WACrB,IAAI,CAAC,qBAAqB,KAAK,QAAQ,GACrC,MAAM,IAAI,MAAM,qCAAqC,SAAS,MAAM,UAAU;CAGlF,MAAM,sBAAsB,CAAC,GAAG,SAAS,CAAC,CAAC,QAAO,aAAY,aAAa,KAAK;CAChF,IAAI,oBAAoB,SAAS,GAC/B,MAAM,IAAI,MAAM,yCAAyC,UAAU;CAErE,OAAO,oBAAoB,MAAM;AACnC;AAEA,SAAgB,uBAAuB,QAA4B;CACjE,OAAO,OAAO,SAAS;AACzB"}
|
|
1
|
+
{"version":3,"file":"vueSfc.mjs","names":[],"sources":["../../src/plugin/vueSfc.ts"],"sourcesContent":["import type { NodePath } from '@babel/traverse'\nimport type { CallExpression } from '@babel/types'\nimport type { VueTransformResult } from 'wevu/compiler'\nimport type { ModuleMeta, ResolveWebAutoImportTag, ResolveWebModuleId, ScanState, WebStylePreprocessOptions } from './types'\nimport { parse } from '@babel/parser'\nimport _babelTraverse from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { fs } from '@weapp-core/shared/fs'\nimport { transform } from 'esbuild'\nimport MagicString from 'magic-string'\nimport path from 'pathe'\nimport { compileVueFile, getMiniProgramTemplatePlatform, isUniAppCompatibilityFile, transformUniAppSource } from 'wevu/compiler'\nimport { compileWxml } from '../compiler/wxml'\nimport { resolveScriptFile } from './files'\nimport { appendInlineQuery, normalizePath, resolveTemplatePathSync, resolveWxsPathSync, toRelativeImport } from './path'\n\nconst traverse = _babelTraverse\nconst webTemplatePlatform = { ...getMiniProgramTemplatePlatform('weapp'), nativeSlotContext: false }\n\nasync function resolveSfcSrc(\n request: string,\n importer: string,\n srcRoot: string,\n resolveId?: ResolveWebModuleId,\n) {\n if (request.startsWith('@/')) {\n return path.resolve(srcRoot, request.slice(2))\n }\n if (request.startsWith('.')) {\n return path.resolve(path.dirname(importer), request)\n }\n if (request.startsWith('/')) {\n return path.resolve(srcRoot, request.slice(1))\n }\n return await resolveId?.(request, importer)\n}\n\nexport async function compileWebVueSfc(options: {\n source: string\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const { filename, meta, srcRoot, state, resolveId, resolveAutoImportTag, uniApp, stylePreprocessOptions } = options\n const source = uniApp && isUniAppCompatibilityFile(filename, srcRoot, uniApp.include)\n ? transformUniAppSource(options.source, { filename, target: 'h5' }).code\n : options.source\n const result = await compileVueFile(source, filename, {\n isApp: meta.kind === 'app',\n isPage: meta.kind === 'page',\n sourceMap: false,\n template: { platform: webTemplatePlatform },\n style: {\n preprocessOptions: stylePreprocessOptions,\n preserveDeepSelectors: true,\n transformScoped: false,\n },\n json: { kind: meta.kind },\n autoUsingComponents: {\n enabled: true,\n resolveUsingComponentPath: async (request, importer) => {\n const base = request.startsWith('@/')\n ? path.resolve(srcRoot, request.slice(2))\n : request.startsWith('.')\n ? path.resolve(path.dirname(importer), request)\n : request.startsWith('/')\n ? path.resolve(srcRoot, request.slice(1))\n : undefined\n if (!base) {\n return undefined\n }\n const resolvedId = await resolveScriptFile(base)\n if (!resolvedId) {\n return undefined\n }\n return {\n from: request,\n resolvedId,\n sourceType: resolvedId.endsWith('.vue') ? 'wevu-sfc' : 'native',\n }\n },\n },\n autoImportTags: {\n enabled: Boolean(resolveAutoImportTag),\n resolveUsingComponent: async (tag, importer) => resolveAutoImportTag?.(tag, importer),\n },\n sfcSrc: {\n resolveId: async (request, importer) => {\n return resolveSfcSrc(request, importer!, srcRoot, resolveId)\n },\n },\n })\n state.sfcResults.set(normalizePath(filename), result)\n for (const dependency of result.meta?.sfcSrcDeps ?? []) {\n state.templatePathSet.add(dependency)\n }\n return result\n}\n\nexport async function ensureWebVueSfcResult(options: {\n filename: string\n meta: ModuleMeta\n srcRoot: string\n state: ScanState\n source?: string\n resolveId?: ResolveWebModuleId\n resolveAutoImportTag?: ResolveWebAutoImportTag\n uniApp?: { include: string[] }\n stylePreprocessOptions?: WebStylePreprocessOptions\n}) {\n const cached = options.state.sfcResults.get(normalizePath(options.filename))\n if (cached) {\n return cached\n }\n const source = options.source ?? await fs.readFile(options.filename, 'utf8')\n return await compileWebVueSfc({ ...options, source })\n}\n\nfunction getSfcRegisterName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'registerWebWevuApp' : 'registerWebWevuComponent'\n}\n\nfunction getSfcFactoryName(kind: ModuleMeta['kind']) {\n return kind === 'app' ? 'createApp' : 'createWevuComponent'\n}\n\nfunction createRegisterMetaCode(meta: ModuleMeta, templateIdent?: string, styleIdent?: string) {\n const parts = [`id: ${JSON.stringify(meta.id)}`, `kind: ${JSON.stringify(meta.kind)}`]\n if (templateIdent) {\n parts.push(`template: ${templateIdent}`)\n }\n if (styleIdent) {\n parts.push(`style: ${styleIdent}`)\n }\n if (meta.navigationBar) {\n parts.push(`navigationBar: ${JSON.stringify(meta.navigationBar)}`)\n }\n return `{ ${parts.join(', ')} }`\n}\n\nexport async function transformWebVueSfcScript(options: {\n code: string\n filename: string\n meta: ModuleMeta\n runtimeModuleId: string\n styleLanguage: string\n enableHmr: boolean\n hmrAcceptCode?: string\n}) {\n const { code, filename, meta, runtimeModuleId, styleLanguage, enableHmr, hmrAcceptCode } = options\n const ast = parse(code, {\n sourceType: 'module',\n plugins: ['typescript', 'jsx'],\n ranges: true,\n })\n const s = new MagicString(code)\n const templateIdent = meta.kind === 'app' ? undefined : '__weapp_sfc_template__'\n const styleIdent = '__weapp_sfc_style__'\n const registerName = getSfcRegisterName(meta.kind)\n const factoryName = getSfcFactoryName(meta.kind)\n const registerMetaCode = createRegisterMetaCode(meta, templateIdent, styleIdent)\n let transformed = false\n\n traverse(ast, {\n CallExpression(nodePath: NodePath<CallExpression>) {\n const callee = nodePath.node.callee\n if (!t.isIdentifier(callee, { name: factoryName })) {\n return\n }\n s.overwrite(callee.start!, callee.end!, registerName)\n s.appendLeft(nodePath.node.end! - 1, `, ${registerMetaCode}`)\n transformed = true\n },\n })\n\n if (!transformed) {\n throw new Error(`[@weapp-vite/web] Vue SFC 未生成 ${factoryName} 注册调用: ${filename}`)\n }\n\n const imports = [`import { ${registerName} } from '${runtimeModuleId}'`]\n if (templateIdent) {\n imports.push(`import ${templateIdent} from '${toRelativeImport(filename, filename)}?weapp-web-sfc-template'`)\n }\n const styleFilename = `${filename}.${styleLanguage}`\n imports.push(`import ${styleIdent} from '${appendInlineQuery(`${toRelativeImport(filename, styleFilename)}?weapp-web-sfc-style`)}'`)\n s.prepend(`${imports.join('\\n')}\\n`)\n if (enableHmr && hmrAcceptCode) {\n s.append(`\\n${hmrAcceptCode}\\n`)\n }\n const transpiled = await transform(s.toString(), {\n format: 'esm',\n legalComments: 'inline',\n loader: 'ts',\n sourcefile: filename,\n sourcemap: 'external',\n target: 'es2022',\n })\n return {\n code: transpiled.code,\n map: JSON.parse(transpiled.map),\n }\n}\n\nexport function generateWebVueSfcTemplate(\n result: VueTransformResult,\n meta: ModuleMeta,\n filename: string,\n srcRoot: string,\n) {\n const compiled = compileWxml({\n id: filename,\n source: result.template ?? '',\n navigationBar: meta.navigationBar ? { config: meta.navigationBar } : undefined,\n componentTags: meta.componentTags,\n resolveTemplatePath: (request, importer) => resolveTemplatePathSync(request, importer, srcRoot),\n resolveWxsPath: (request, importer) => resolveWxsPathSync(request, importer, srcRoot),\n })\n return compiled\n}\n\nexport function resolveWebVueSfcStyleLanguage(result: VueTransformResult, filename: string) {\n const languages = new Set(\n (result.meta?.styleBlocks ?? []).map(style => style.lang?.trim() || 'css'),\n )\n for (const language of languages) {\n if (!/^[a-z][a-z0-9-]*$/i.test(language)) {\n throw new Error(`[@weapp-vite/web] Vue SFC 样式语言无效: ${filename} -> ${language}`)\n }\n }\n const preprocessLanguages = [...languages].filter(language => language !== 'css')\n if (preprocessLanguages.length > 1) {\n throw new Error(`[@weapp-vite/web] Vue SFC 暂不支持混合样式语言: ${filename}`)\n }\n return preprocessLanguages[0] ?? 'css'\n}\n\nexport function generateWebVueSfcStyle(result: VueTransformResult) {\n return result.style ?? ''\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,WAAW;AACjB,MAAM,sBAAsB;CAAE,GAAG,+BAA+B,OAAO;CAAG,mBAAmB;AAAM;AAEnG,eAAe,cACb,SACA,UACA,SACA,WACA;CACA,IAAI,QAAQ,WAAW,IAAI,GACzB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,IAAI,QAAQ,WAAW,GAAG,GACxB,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ,GAAG,OAAO;CAErD,IAAI,QAAQ,WAAW,GAAG,GACxB,OAAO,KAAK,QAAQ,SAAS,QAAQ,MAAM,CAAC,CAAC;CAE/C,OAAO,MAAM,YAAY,SAAS,QAAQ;AAC5C;AAEA,eAAsB,iBAAiB,SAUpC;CACD,MAAM,EAAE,UAAU,MAAM,SAAS,OAAO,WAAW,sBAAsB,QAAQ,2BAA2B;CAC5G,MAAM,SAAS,UAAU,0BAA0B,UAAU,SAAS,OAAO,OAAO,IAChF,sBAAsB,QAAQ,QAAQ;EAAE;EAAU,QAAQ;CAAK,CAAC,CAAC,CAAC,OAClE,QAAQ;CACZ,MAAM,SAAS,MAAM,eAAe,QAAQ,UAAU;EACpD,OAAO,KAAK,SAAS;EACrB,QAAQ,KA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AAO,aAAY,aAAa,KAAK;CAChF,IAAI,oBAAoB,SAAS,GAC/B,MAAM,IAAI,MAAM,yCAAyC,UAAU;CAErE,OAAO,oBAAoB,MAAM;AACnC;AAEA,SAAgB,uBAAuB,QAA4B;CACjE,OAAO,OAAO,SAAS;AACzB"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { injectStyle, removeStyle } from "./style.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/runtime/appStyle.ts
|
|
4
|
+
const styleId = "weapp-web-app-style";
|
|
5
|
+
const consumers = /* @__PURE__ */ new Set();
|
|
6
|
+
let appStyle = "";
|
|
7
|
+
function getAppStyle() {
|
|
8
|
+
return appStyle;
|
|
9
|
+
}
|
|
10
|
+
/** 应用样式是页面及非隔离组件的共享输入;主题变量通过 document 自然继承。 */
|
|
11
|
+
function setAppStyle(style) {
|
|
12
|
+
if (style === appStyle) return;
|
|
13
|
+
appStyle = style;
|
|
14
|
+
if (style) injectStyle(style, styleId);
|
|
15
|
+
else removeStyle(styleId);
|
|
16
|
+
for (const consumer of consumers) consumer.requestUpdate();
|
|
17
|
+
}
|
|
18
|
+
function trackAppStyle(consumer, enabled) {
|
|
19
|
+
if (enabled) consumers.add(consumer);
|
|
20
|
+
else consumers.delete(consumer);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
export { getAppStyle, setAppStyle, trackAppStyle };
|
|
25
|
+
//# sourceMappingURL=appStyle.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"appStyle.mjs","names":[],"sources":["../../src/runtime/appStyle.ts"],"sourcesContent":["import { injectStyle, removeStyle } from './style'\n\ninterface AppStyleConsumer {\n requestUpdate: () => unknown\n}\n\nconst styleId = 'weapp-web-app-style'\nconst consumers = new Set<AppStyleConsumer>()\nlet appStyle = ''\n\nexport function getAppStyle() {\n return appStyle\n}\n\n/** 应用样式是页面及非隔离组件的共享输入;主题变量通过 document 自然继承。 */\nexport function setAppStyle(style: string) {\n if (style === appStyle) {\n return\n }\n appStyle = style\n if (style) {\n injectStyle(style, styleId)\n }\n else {\n removeStyle(styleId)\n }\n for (const consumer of consumers) {\n consumer.requestUpdate()\n }\n}\n\nexport function trackAppStyle(consumer: AppStyleConsumer, enabled: boolean) {\n if (enabled) {\n consumers.add(consumer)\n }\n else {\n consumers.delete(consumer)\n }\n}\n"],"mappings":";;;AAMA,MAAM,UAAU;AAChB,MAAM,4BAAY,IAAI,IAAsB;AAC5C,IAAI,WAAW;AAEf,SAAgB,cAAc;CAC5B,OAAO;AACT;;AAGA,SAAgB,YAAY,OAAe;CACzC,IAAI,UAAU,UACZ;CAEF,WAAW;CACX,IAAI,OACF,YAAY,OAAO,OAAO;MAG1B,YAAY,OAAO;CAErB,KAAK,MAAM,YAAY,WACrB,SAAS,cAAc;AAE3B;AAEA,SAAgB,cAAc,UAA4B,SAAkB;CAC1E,IAAI,SACF,UAAU,IAAI,QAAQ;MAGtB,UAAU,OAAO,QAAQ;AAE7B"}
|
|
@@ -1,16 +1,18 @@
|
|
|
1
|
+
import { getAppStyle, trackAppStyle } from "../appStyle.mjs";
|
|
1
2
|
import { supportsLit } from "./constants.mjs";
|
|
3
|
+
import { markComponentEvent, registerComponentEventTarget } from "../componentEvents.mjs";
|
|
4
|
+
import { hasOwn } from "../utils/object.mjs";
|
|
2
5
|
import { createComponentPublicInstance } from "./publicInstance.mjs";
|
|
3
6
|
import { createIntersectionObserverBridge } from "../polyfill/intersectionObserver.mjs";
|
|
4
7
|
import { createRenderContext } from "../renderContext.mjs";
|
|
5
|
-
import { hasOwn } from "../utils/object.mjs";
|
|
6
8
|
import { createScopedSelectorQuery, resolveRenderRoot, selectRuntimeComponent, selectRuntimeComponents } from "./dom.mjs";
|
|
7
9
|
import { bindRuntimeEvents } from "./events.mjs";
|
|
8
10
|
import { runComponentObservers } from "./observers.mjs";
|
|
9
11
|
import { resolveRelationNodes } from "./relations.mjs";
|
|
10
12
|
import { createWebSlotsProxy } from "./slots.mjs";
|
|
11
|
-
import { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from "./utils.mjs";
|
|
13
|
+
import { assignDataPath, cloneCommittedValue, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from "./utils.mjs";
|
|
12
14
|
import { clearVirtualHostClasses, clearVirtualHostParts, syncVirtualHostClasses, syncVirtualHostParts } from "./virtualHost.mjs";
|
|
13
|
-
import { WEVU_HOST_COMMIT_PROMISE_KEY } from "@weapp-core/constants";
|
|
15
|
+
import { WEVU_HOST_COMMIT_PROMISE_KEY, WEVU_HOST_INSTALL_METHOD_KEY } from "@weapp-core/constants";
|
|
14
16
|
import { html } from "lit";
|
|
15
17
|
import { unsafeHTML } from "lit/directives/unsafe-html.js";
|
|
16
18
|
|
|
@@ -35,6 +37,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
35
37
|
#state;
|
|
36
38
|
#properties;
|
|
37
39
|
#methods = {};
|
|
40
|
+
#setupMethods = {};
|
|
38
41
|
#publicInstance;
|
|
39
42
|
#exposedMethodNames = /* @__PURE__ */ new Set();
|
|
40
43
|
#isMounted = false;
|
|
@@ -53,6 +56,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
53
56
|
properties;
|
|
54
57
|
constructor() {
|
|
55
58
|
super();
|
|
59
|
+
registerComponentEventTarget(this);
|
|
56
60
|
const dataOption = runtimeState.componentRef.data ?? {};
|
|
57
61
|
this.#properties = { ...runtimeState.defaultPropertyValues };
|
|
58
62
|
this.#state = {
|
|
@@ -76,7 +80,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
76
80
|
get: () => this.#properties
|
|
77
81
|
}
|
|
78
82
|
});
|
|
79
|
-
this.#publicInstance = createComponentPublicInstance(this, WeappWebComponent.prototype, (key) => typeof key === "string" ? this.#methods[key] : void 0);
|
|
83
|
+
this.#publicInstance = createComponentPublicInstance(this, WeappWebComponent.prototype, (key) => typeof key === "string" ? this.#methods[key] : void 0, this.#properties);
|
|
80
84
|
for (const [propName] of runtimeState.propertyEntries) Object.defineProperty(this, propName, {
|
|
81
85
|
configurable: true,
|
|
82
86
|
enumerable: true,
|
|
@@ -116,11 +120,18 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
116
120
|
callback?.();
|
|
117
121
|
}
|
|
118
122
|
triggerEvent(name, detail, options = {}) {
|
|
119
|
-
this.dispatchEvent(new CustomEvent(name, {
|
|
123
|
+
this.dispatchEvent(markComponentEvent(new CustomEvent(name, {
|
|
120
124
|
detail,
|
|
121
125
|
bubbles: options.bubbles ?? false,
|
|
122
126
|
composed: options.composed ?? false
|
|
123
|
-
}));
|
|
127
|
+
})));
|
|
128
|
+
}
|
|
129
|
+
[WEVU_HOST_INSTALL_METHOD_KEY](methods) {
|
|
130
|
+
const bound = {};
|
|
131
|
+
for (const [name, method] of Object.entries(methods)) bound[name] = method.bind(this.#publicInstance);
|
|
132
|
+
this.#setupMethods = bound;
|
|
133
|
+
this.#syncMethods(runtimeState.componentRef.methods);
|
|
134
|
+
this.requestUpdate();
|
|
124
135
|
}
|
|
125
136
|
createSelectorQuery() {
|
|
126
137
|
return createScopedSelectorQuery(this);
|
|
@@ -146,18 +157,21 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
146
157
|
}
|
|
147
158
|
}
|
|
148
159
|
connectedCallback() {
|
|
160
|
+
instances.add(this);
|
|
149
161
|
const superConnected = BaseElement.prototype.connectedCallback;
|
|
150
162
|
if (supportsLit && typeof superConnected === "function") superConnected.call(this);
|
|
151
163
|
this.#applyAttributes();
|
|
152
164
|
if (runtimeState.observerInitEnabled) this.#runInitialObservers();
|
|
153
165
|
runtimeState.lifetimes.attached?.call(this.#publicInstance);
|
|
154
166
|
this.#isMounted = true;
|
|
155
|
-
|
|
167
|
+
trackAppStyle(this, runtimeState.inheritAppStyle);
|
|
168
|
+
this.requestUpdate();
|
|
156
169
|
}
|
|
157
170
|
disconnectedCallback() {
|
|
158
171
|
const superDisconnected = BaseElement.prototype.disconnectedCallback;
|
|
159
172
|
if (supportsLit && typeof superDisconnected === "function") superDisconnected.call(this);
|
|
160
173
|
this.#isMounted = false;
|
|
174
|
+
trackAppStyle(this, false);
|
|
161
175
|
instances.delete(this);
|
|
162
176
|
runtimeState.lifetimes.detached?.call(this.#publicInstance);
|
|
163
177
|
}
|
|
@@ -179,14 +193,9 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
179
193
|
}
|
|
180
194
|
render() {
|
|
181
195
|
const result = runtimeState.templateRef(this.#state, this.#renderContext);
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
return html`${styleMarkup}${unsafeHTML(result)}`;
|
|
186
|
-
}
|
|
187
|
-
this.#usesLegacyTemplate = false;
|
|
188
|
-
if (styleMarkup) return html`${styleMarkup}${result}`;
|
|
189
|
-
return result;
|
|
196
|
+
const appStyle = runtimeState.inheritAppStyle ? getAppStyle() : "";
|
|
197
|
+
this.#usesLegacyTemplate = typeof result === "string";
|
|
198
|
+
return html`<style>${appStyle}</style><style>${runtimeState.styleRef}</style>${typeof result === "string" ? unsafeHTML(result) : result}`;
|
|
190
199
|
}
|
|
191
200
|
requestUpdate(name, oldValue, options) {
|
|
192
201
|
const superRequestUpdate = BaseElement.prototype.requestUpdate;
|
|
@@ -202,12 +211,17 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
202
211
|
let changed = false;
|
|
203
212
|
const changedKeys = [];
|
|
204
213
|
const previousProperties = {};
|
|
214
|
+
let copiedContainers;
|
|
205
215
|
for (const [path, value] of Object.entries(patch)) {
|
|
206
216
|
const segments = parseDataPath(path);
|
|
207
217
|
const topKey = segments[0];
|
|
208
|
-
if (!topKey || topKey === "$slots"
|
|
218
|
+
if (!topKey || topKey === "$slots") continue;
|
|
219
|
+
let nextValue = value;
|
|
220
|
+
if (value !== null && typeof value === "object") nextValue = cloneCommittedValue(value);
|
|
221
|
+
else if (Object.is(resolveDataPath(this.#state, segments), value)) continue;
|
|
209
222
|
if (hasOwn(this.#properties, topKey) && !hasOwn(previousProperties, topKey)) previousProperties[topKey] = this.#properties[topKey];
|
|
210
|
-
|
|
223
|
+
if (segments.length > 1) copiedContainers ??= /* @__PURE__ */ new WeakSet();
|
|
224
|
+
assignDataPath(this.#state, segments, nextValue, copiedContainers);
|
|
211
225
|
if (hasOwn(this.#properties, topKey)) this.#properties[topKey] = this.#state[topKey];
|
|
212
226
|
changedKeys.push(path);
|
|
213
227
|
changed = true;
|
|
@@ -244,6 +258,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
244
258
|
const resolved = nextMethods ?? {};
|
|
245
259
|
const bound = {};
|
|
246
260
|
for (const [name, fn] of Object.entries(resolved)) if (typeof fn === "function") bound[name] = fn.bind(this.#publicInstance);
|
|
261
|
+
Object.assign(bound, this.#setupMethods);
|
|
247
262
|
for (const name of this.#exposedMethodNames) {
|
|
248
263
|
if (name in bound) continue;
|
|
249
264
|
const descriptor = Object.getOwnPropertyDescriptor(this, name);
|
|
@@ -252,8 +267,12 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
252
267
|
}
|
|
253
268
|
for (const key of Object.keys(this.#methods)) if (!(key in bound)) delete this.#methods[key];
|
|
254
269
|
for (const [key, fn] of Object.entries(bound)) {
|
|
270
|
+
const previous = this.#methods[key];
|
|
255
271
|
this.#methods[key] = fn;
|
|
256
|
-
if (
|
|
272
|
+
if (this.#exposedMethodNames.has(key)) {
|
|
273
|
+
const descriptor = Object.getOwnPropertyDescriptor(this, key);
|
|
274
|
+
if (!descriptor?.configurable || descriptor.value !== previous) continue;
|
|
275
|
+
} else if (key in this) continue;
|
|
257
276
|
Object.defineProperty(this, key, {
|
|
258
277
|
configurable: true,
|
|
259
278
|
enumerable: false,
|
|
@@ -266,6 +285,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
266
285
|
}
|
|
267
286
|
__weappSync(nextMethods) {
|
|
268
287
|
this.#syncMethods(nextMethods);
|
|
288
|
+
trackAppStyle(this, this.#isMounted && runtimeState.inheritAppStyle);
|
|
269
289
|
this.requestUpdate();
|
|
270
290
|
}
|
|
271
291
|
__weappInvokePageLifetime(type) {
|
|
@@ -275,7 +295,7 @@ function createComponentElementClass({ BaseElement, runtimeState, instances }) {
|
|
|
275
295
|
#renderLegacy() {
|
|
276
296
|
const result = runtimeState.templateRef(this.#state, this.#renderContext);
|
|
277
297
|
const root = resolveRenderRoot(this);
|
|
278
|
-
const styleMarkup = runtimeState.
|
|
298
|
+
const styleMarkup = `<style>${runtimeState.inheritAppStyle ? getAppStyle() : ""}</style><style>${runtimeState.styleRef}</style>`;
|
|
279
299
|
if (typeof result === "string") {
|
|
280
300
|
root.innerHTML = `${styleMarkup}${result}`;
|
|
281
301
|
bindRuntimeEvents(root, this.#methods, this);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"element.mjs","names":[],"sources":["../../../src/runtime/component/element.ts"],"sourcesContent":["import type {\n CreateComponentElementClassOptions,\n WeappComponentInstance,\n} from './elementTypes'\nimport type {\n ComponentOptions,\n ComponentPublicInstance,\n DataRecord,\n PageLifeTimeHooks,\n TriggerEventOptions,\n} from './types'\nimport type { ClassAttributeElement } from './virtualHost'\nimport { WEVU_HOST_COMMIT_PROMISE_KEY } from '@weapp-core/constants'\nimport { html } from 'lit'\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js'\nimport { createIntersectionObserverBridge } from '../polyfill/intersectionObserver'\nimport { createRenderContext } from '../renderContext'\nimport { hasOwn } from '../utils/object'\nimport { supportsLit } from './constants'\nimport {\n createScopedSelectorQuery,\n resolveRenderRoot,\n selectRuntimeComponent,\n selectRuntimeComponents,\n} from './dom'\nimport { bindRuntimeEvents } from './events'\nimport { runComponentObservers } from './observers'\nimport { createComponentPublicInstance } from './publicInstance'\nimport { resolveRelationNodes } from './relations'\nimport { createWebSlotsProxy } from './slots'\nimport { assignDataPath, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from './utils'\nimport {\n clearVirtualHostClasses,\n clearVirtualHostParts,\n syncVirtualHostClasses,\n syncVirtualHostParts,\n} from './virtualHost'\n\nexport type { WeappComponentInstance } from './elementTypes'\nexport type WeappComponentElementClass = typeof HTMLElement & {\n new (): WeappComponentInstance\n}\n\nfunction resolveComposedParent(node: Node): Node | undefined {\n const assignedSlot = (node as Element).assignedSlot\n if (assignedSlot) {\n return assignedSlot\n }\n if (node.parentNode) {\n return node.parentNode\n }\n const root = node.getRootNode?.()\n return root instanceof ShadowRoot ? root.host : undefined\n}\n\nfunction isWeappComponentInstance(value: unknown): value is WeappComponentInstance {\n return Boolean(\n value\n && typeof value === 'object'\n && typeof (value as WeappComponentInstance).__weappSync === 'function',\n )\n}\n\nexport function createComponentElementClass({\n BaseElement,\n runtimeState,\n instances,\n}: CreateComponentElementClassOptions): WeappComponentElementClass {\n const RuntimeBaseElement = BaseElement as typeof HTMLElement & {\n readonly observedAttributes?: string[]\n }\n class WeappWebComponent extends RuntimeBaseElement implements WeappComponentInstance {\n static get observedAttributes() {\n const inherited = super.observedAttributes ?? []\n return Array.from(new Set([...inherited, ...runtimeState.observedAttributes]))\n }\n\n #state: DataRecord\n #properties: DataRecord\n #methods: Record<string, (event: any) => any> = {}\n #publicInstance: ComponentPublicInstance\n #exposedMethodNames = new Set<string>()\n #isMounted = false\n #renderContext = createRenderContext(this, {})\n #usesLegacyTemplate = false\n #readyFired = false\n #observerInitDone = false\n #observedKeys = new Set<string>()\n #virtualHostClassTokens = new Set<string>()\n #virtualHostPartTokens = new Set<string>()\n #virtualHostRootElement: ClassAttributeElement | undefined\n #needsSetDataRecovery = false\n #hostCommitPromise: Promise<void> | undefined\n #hostCommitUpdate: Promise<boolean> | undefined\n readonly data!: DataRecord\n readonly properties!: DataRecord\n\n constructor() {\n super()\n const dataOption = runtimeState.componentRef.data ?? {}\n this.#properties = { ...runtimeState.defaultPropertyValues }\n this.#state = { ...cloneValue(this.#properties), ...cloneValue(dataOption) }\n Object.defineProperty(this.#state, '$slots', {\n configurable: true,\n enumerable: true,\n value: createWebSlotsProxy(() => this.#state.vueSlots),\n })\n Object.defineProperties(this, {\n data: {\n configurable: true,\n enumerable: true,\n get: () => this.#state,\n },\n properties: {\n configurable: true,\n enumerable: true,\n get: () => this.#properties,\n },\n })\n this.#publicInstance = createComponentPublicInstance(\n this,\n WeappWebComponent.prototype,\n key => typeof key === 'string' ? this.#methods[key] : undefined,\n )\n for (const [propName] of runtimeState.propertyEntries) {\n Object.defineProperty(this, propName, {\n configurable: true,\n enumerable: true,\n get: () => this.#state[propName],\n set: value => this.#setProperty(propName, value),\n })\n }\n this.#syncMethods(runtimeState.componentRef.methods ?? {})\n if (!supportsLit) {\n const host = this as unknown as HTMLElement\n if (!host.shadowRoot && typeof host.attachShadow === 'function') {\n host.attachShadow({ mode: 'open' })\n }\n ;(this as any).renderRoot = host.shadowRoot ?? host\n }\n instances.add(this)\n runtimeState.lifetimes.created?.call(this.#publicInstance)\n }\n\n get [WEVU_HOST_COMMIT_PROMISE_KEY]() {\n // 回调异常属于当前提交;后续属性更新或 HMR 必须等待自己的 Lit 提交。\n if (!supportsLit) {\n return undefined\n }\n // 动态 Lit 基类不会在静态声明中暴露 updateComplete。\n const litElement = this as unknown as { updateComplete: Promise<boolean> }\n const update = litElement.updateComplete\n return this.#hostCommitUpdate === update ? this.#hostCommitPromise : update\n }\n\n setData(patch: DataRecord, callback?: () => void) {\n const changed = this.#applyDataPatch(patch)\n if (supportsLit && (changed || this.#needsSetDataRecovery)) {\n if (!changed) {\n this.requestUpdate()\n }\n // 动态 Lit 基类不会在静态声明中暴露 updateComplete。\n const litElement = this as unknown as { updateComplete: Promise<boolean> }\n const update = litElement.updateComplete\n const commitPromise = update.then(\n () => {\n this.#needsSetDataRecovery = false\n callback?.()\n },\n (cause) => {\n this.#needsSetDataRecovery = true\n throw cause\n },\n )\n this.#hostCommitPromise = commitPromise\n this.#hostCommitUpdate = update\n return commitPromise\n }\n callback?.()\n }\n\n triggerEvent(name: string, detail?: any, options: TriggerEventOptions = {}) {\n this.dispatchEvent(new CustomEvent(name, {\n detail,\n bubbles: options.bubbles ?? false,\n composed: options.composed ?? false,\n }))\n }\n\n createSelectorQuery() {\n return createScopedSelectorQuery(this)\n }\n\n createIntersectionObserver(options?: {\n initialRatio?: number\n observeAll?: boolean\n thresholds?: number[]\n }) {\n return createIntersectionObserverBridge(this, options)\n }\n\n selectComponent(selector: string) {\n return selectRuntimeComponent(this, selector)\n }\n\n selectAllComponents(selector: string) {\n return selectRuntimeComponents(this, selector)\n }\n\n getRelationNodes(relationPath: string) {\n const relation = runtimeState.componentRef.relations?.[relationPath]\n return relation\n ? resolveRelationNodes(this, runtimeState.id, relationPath, relation.type)\n : []\n }\n\n selectOwnerComponent() {\n let current = resolveComposedParent(this)\n while (current) {\n if (isWeappComponentInstance(current)) {\n return current\n }\n current = resolveComposedParent(current)\n }\n return undefined\n }\n\n connectedCallback() {\n const superConnected = (BaseElement.prototype as { connectedCallback?: () => void }).connectedCallback\n if (supportsLit && typeof superConnected === 'function') {\n superConnected.call(this)\n }\n this.#applyAttributes()\n if (runtimeState.observerInitEnabled) {\n this.#runInitialObservers()\n }\n runtimeState.lifetimes.attached?.call(this.#publicInstance)\n this.#isMounted = true\n if (!supportsLit) {\n this.#renderLegacy()\n }\n }\n\n disconnectedCallback() {\n const superDisconnected = (BaseElement.prototype as { disconnectedCallback?: () => void }).disconnectedCallback\n if (supportsLit && typeof superDisconnected === 'function') {\n superDisconnected.call(this)\n }\n this.#isMounted = false\n instances.delete(this)\n runtimeState.lifetimes.detached?.call(this.#publicInstance)\n }\n\n attributeChangedCallback(attrName: string, oldValue: string | null, newValue: string | null) {\n const superAttributeChanged = (BaseElement.prototype as {\n attributeChangedCallback?: (name: string, oldValue: string | null, newValue: string | null) => void\n }).attributeChangedCallback\n if (supportsLit && typeof superAttributeChanged === 'function') {\n superAttributeChanged.call(this, attrName, oldValue, newValue)\n }\n const propName = toCamelCase(attrName)\n if (!hasOwn(this.#properties, propName)) {\n return\n }\n const propOption = runtimeState.componentRef.properties?.[propName]\n this.#setProperty(propName, coerceValue(newValue, propOption?.type))\n }\n\n firstUpdated() {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n\n updated() {\n this.#syncVirtualHostClasses()\n if (this.#usesLegacyTemplate) {\n bindRuntimeEvents(resolveRenderRoot(this), this.#methods, this)\n }\n }\n\n render() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const styleMarkup = runtimeState.styleRef\n ? html`<style>${runtimeState.styleRef}</style>`\n : null\n if (typeof result === 'string') {\n this.#usesLegacyTemplate = true\n return html`${styleMarkup}${unsafeHTML(result)}`\n }\n this.#usesLegacyTemplate = false\n if (styleMarkup) {\n return html`${styleMarkup}${result as any}`\n }\n return result\n }\n\n requestUpdate(name?: PropertyKey, oldValue?: unknown, options?: unknown) {\n const superRequestUpdate = (BaseElement.prototype as any).requestUpdate\n if (supportsLit && typeof superRequestUpdate === 'function') {\n return superRequestUpdate.call(this, name, oldValue, options)\n }\n if (this.#isMounted) {\n this.#renderLegacy()\n }\n return undefined\n }\n\n #applyAttributes() {\n if (!this.attributes || typeof this.attributes[Symbol.iterator] !== 'function') {\n return\n }\n for (const attr of this.attributes) {\n this.attributeChangedCallback(attr.name, null, attr.value)\n }\n }\n\n #applyDataPatch(patch: DataRecord) {\n if (!patch || typeof patch !== 'object') {\n return false\n }\n let changed = false\n const changedKeys: string[] = []\n const previousProperties: DataRecord = {}\n for (const [path, value] of Object.entries(patch)) {\n const segments = parseDataPath(path)\n const topKey = segments[0]\n if (!topKey || topKey === '$slots' || Object.is(resolveDataPath(this.#state, segments), value)) {\n continue\n }\n if (hasOwn(this.#properties, topKey) && !hasOwn(previousProperties, topKey)) {\n previousProperties[topKey] = this.#properties[topKey]\n }\n assignDataPath(this.#state, segments, value)\n if (hasOwn(this.#properties, topKey)) {\n this.#properties[topKey] = this.#state[topKey]\n }\n changedKeys.push(path)\n changed = true\n }\n if (changed) {\n this.requestUpdate()\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, changedKeys, previousProperties)\n for (const key of changedKeys) {\n if (runtimeState.componentRef.properties?.[key]?.observer) {\n this.#observedKeys.add(key)\n }\n }\n }\n return changed\n }\n\n #setProperty(name: string, value: any) {\n const propOption = runtimeState.componentRef.properties?.[name]\n const coerced = coerceValue(value, propOption?.type)\n const oldValue = this.#properties[name]\n if (oldValue === coerced) {\n return\n }\n this.#properties[name] = coerced\n this.#state[name] = coerced\n if (this.#isMounted) {\n this.requestUpdate()\n }\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, [name], { [name]: oldValue })\n if (propOption?.observer) {\n this.#observedKeys.add(name)\n }\n }\n\n #runInitialObservers() {\n if (this.#observerInitDone) {\n return\n }\n this.#observerInitDone = true\n for (const [propName, propOption] of runtimeState.propertyEntries) {\n if (!propOption.observer || this.#observedKeys.has(propName)) {\n continue\n }\n const value = this.#state[propName]\n propOption.observer.call(this.#publicInstance, value, undefined)\n this.#observedKeys.add(propName)\n }\n }\n\n #syncMethods(nextMethods: ComponentOptions['methods']) {\n const resolved = nextMethods ?? {}\n const bound: Record<string, (event: any) => any> = {}\n for (const [name, fn] of Object.entries(resolved)) {\n if (typeof fn === 'function') {\n bound[name] = fn.bind(this.#publicInstance)\n }\n }\n for (const name of this.#exposedMethodNames) {\n if (name in bound) {\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(this, name)\n if (descriptor?.configurable && descriptor.value === this.#methods[name]) {\n delete (this as unknown as Record<string, unknown>)[name]\n }\n this.#exposedMethodNames.delete(name)\n }\n for (const key of Object.keys(this.#methods)) {\n if (!(key in bound)) {\n delete this.#methods[key]\n }\n }\n for (const [key, fn] of Object.entries(bound)) {\n this.#methods[key] = fn\n if (!this.#exposedMethodNames.has(key) && key in this) {\n continue\n }\n Object.defineProperty(this, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: fn,\n })\n this.#exposedMethodNames.add(key)\n }\n this.#renderContext = createRenderContext(this, this.#methods)\n }\n\n __weappSync(nextMethods: ComponentOptions['methods']) {\n this.#syncMethods(nextMethods)\n this.requestUpdate()\n }\n\n __weappInvokePageLifetime(type: keyof PageLifeTimeHooks) {\n const hook = runtimeState.pageLifetimes[type]\n if (typeof hook === 'function') {\n hook.call(this.#publicInstance)\n }\n }\n\n #renderLegacy() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const root = resolveRenderRoot(this)\n const styleMarkup = runtimeState.styleRef ? `<style>${runtimeState.styleRef}</style>` : ''\n if (typeof result === 'string') {\n root.innerHTML = `${styleMarkup}${result}`\n bindRuntimeEvents(root as ShadowRoot, this.#methods, this)\n }\n else if (result == null) {\n root.innerHTML = styleMarkup\n }\n else {\n root.innerHTML = `${styleMarkup}${String(result)}`\n }\n this.#syncVirtualHostClasses()\n if (!this.#readyFired) {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n }\n\n #syncVirtualHostClasses() {\n const host = this as unknown as ClassAttributeElement\n if (!runtimeState.componentRef.options?.virtualHost) {\n clearVirtualHostClasses(host, this.#virtualHostClassTokens)\n clearVirtualHostParts(this.#virtualHostRootElement, this.#virtualHostPartTokens)\n this.#virtualHostRootElement = undefined\n return\n }\n const root = resolveRenderRoot(this)\n syncVirtualHostClasses(host, root, this.#virtualHostClassTokens)\n this.#virtualHostRootElement = syncVirtualHostParts(\n root,\n this.#virtualHostRootElement,\n this.#virtualHostPartTokens,\n )\n }\n }\n\n return WeappWebComponent as WeappComponentElementClass\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2CA,SAAS,sBAAsB,MAA8B;CAC3D,MAAM,eAAgB,KAAiB;CACvC,IAAI,cACF,OAAO;CAET,IAAI,KAAK,YACP,OAAO,KAAK;CAEd,MAAM,OAAO,KAAK,cAAc;CAChC,OAAO,gBAAgB,aAAa,KAA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KAAK,aAAa;IACrB,aAAa,UAAU,OAAO,KAAK,KAAK,eAAe;IACvD,KAAK,cAAc;GACrB;EACF;EAEA,0BAA0B;GACxB,MAAM,OAAO;GACb,IAAI,CAAC,aAAa,aAAa,SAAS,aAAa;IACnD,wBAAwB,MAAM,KAAK,uBAAuB;IAC1D,sBAAsB,KAAK,yBAAyB,KAAK,sBAAsB;IAC/E,KAAK,0BAA0B;IAC/B;GACF;GACA,MAAM,OAAO,kBAAkB,IAAI;GACnC,uBAAuB,MAAM,MAAM,KAAK,uBAAuB;GAC/D,KAAK,0BAA0B,qBAC7B,MACA,KAAK,yBACL,KAAK,sBACP;EACF;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"element.mjs","names":[],"sources":["../../../src/runtime/component/element.ts"],"sourcesContent":["import type {\n CreateComponentElementClassOptions,\n WeappComponentInstance,\n} from './elementTypes'\nimport type {\n ComponentOptions,\n ComponentPublicInstance,\n DataRecord,\n PageLifeTimeHooks,\n TriggerEventOptions,\n} from './types'\nimport type { ClassAttributeElement } from './virtualHost'\nimport { WEVU_HOST_COMMIT_PROMISE_KEY, WEVU_HOST_INSTALL_METHOD_KEY } from '@weapp-core/constants'\nimport { html } from 'lit'\nimport { unsafeHTML } from 'lit/directives/unsafe-html.js'\nimport { getAppStyle, trackAppStyle } from '../appStyle'\nimport { markComponentEvent, registerComponentEventTarget } from '../componentEvents'\nimport { createIntersectionObserverBridge } from '../polyfill/intersectionObserver'\nimport { createRenderContext } from '../renderContext'\nimport { hasOwn } from '../utils/object'\nimport { supportsLit } from './constants'\nimport {\n createScopedSelectorQuery,\n resolveRenderRoot,\n selectRuntimeComponent,\n selectRuntimeComponents,\n} from './dom'\nimport { bindRuntimeEvents } from './events'\nimport { runComponentObservers } from './observers'\nimport { createComponentPublicInstance } from './publicInstance'\nimport { resolveRelationNodes } from './relations'\nimport { createWebSlotsProxy } from './slots'\nimport { assignDataPath, cloneCommittedValue, cloneValue, coerceValue, parseDataPath, resolveDataPath, toCamelCase } from './utils'\nimport {\n clearVirtualHostClasses,\n clearVirtualHostParts,\n syncVirtualHostClasses,\n syncVirtualHostParts,\n} from './virtualHost'\n\nexport type { WeappComponentInstance } from './elementTypes'\nexport type WeappComponentElementClass = typeof HTMLElement & {\n new (): WeappComponentInstance\n}\n\nfunction resolveComposedParent(node: Node): Node | undefined {\n const assignedSlot = (node as Element).assignedSlot\n if (assignedSlot) {\n return assignedSlot\n }\n if (node.parentNode) {\n return node.parentNode\n }\n const root = node.getRootNode?.()\n return root instanceof ShadowRoot ? root.host : undefined\n}\n\nfunction isWeappComponentInstance(value: unknown): value is WeappComponentInstance {\n return Boolean(\n value\n && typeof value === 'object'\n && typeof (value as WeappComponentInstance).__weappSync === 'function',\n )\n}\n\nexport function createComponentElementClass({\n BaseElement,\n runtimeState,\n instances,\n}: CreateComponentElementClassOptions): WeappComponentElementClass {\n const RuntimeBaseElement = BaseElement as typeof HTMLElement & {\n readonly observedAttributes?: string[]\n }\n class WeappWebComponent extends RuntimeBaseElement implements WeappComponentInstance {\n static get observedAttributes() {\n const inherited = super.observedAttributes ?? []\n return Array.from(new Set([...inherited, ...runtimeState.observedAttributes]))\n }\n\n #state: DataRecord\n #properties: DataRecord\n #methods: Record<string, (event: any) => any> = {}\n #setupMethods: Record<string, (...args: any[]) => any> = {}\n #publicInstance: ComponentPublicInstance\n #exposedMethodNames = new Set<string>()\n #isMounted = false\n #renderContext = createRenderContext(this, {})\n #usesLegacyTemplate = false\n #readyFired = false\n #observerInitDone = false\n #observedKeys = new Set<string>()\n #virtualHostClassTokens = new Set<string>()\n #virtualHostPartTokens = new Set<string>()\n #virtualHostRootElement: ClassAttributeElement | undefined\n #needsSetDataRecovery = false\n #hostCommitPromise: Promise<void> | undefined\n #hostCommitUpdate: Promise<boolean> | undefined\n readonly data!: DataRecord\n readonly properties!: DataRecord\n\n constructor() {\n super()\n registerComponentEventTarget(this)\n const dataOption = runtimeState.componentRef.data ?? {}\n this.#properties = { ...runtimeState.defaultPropertyValues }\n this.#state = { ...cloneValue(this.#properties), ...cloneValue(dataOption) }\n Object.defineProperty(this.#state, '$slots', {\n configurable: true,\n enumerable: true,\n value: createWebSlotsProxy(() => this.#state.vueSlots),\n })\n Object.defineProperties(this, {\n data: {\n configurable: true,\n enumerable: true,\n get: () => this.#state,\n },\n properties: {\n configurable: true,\n enumerable: true,\n get: () => this.#properties,\n },\n })\n this.#publicInstance = createComponentPublicInstance(\n this,\n WeappWebComponent.prototype,\n key => typeof key === 'string' ? this.#methods[key] : undefined,\n this.#properties,\n )\n for (const [propName] of runtimeState.propertyEntries) {\n Object.defineProperty(this, propName, {\n configurable: true,\n enumerable: true,\n get: () => this.#state[propName],\n set: value => this.#setProperty(propName, value),\n })\n }\n this.#syncMethods(runtimeState.componentRef.methods ?? {})\n if (!supportsLit) {\n const host = this as unknown as HTMLElement\n if (!host.shadowRoot && typeof host.attachShadow === 'function') {\n host.attachShadow({ mode: 'open' })\n }\n ;(this as any).renderRoot = host.shadowRoot ?? host\n }\n instances.add(this)\n runtimeState.lifetimes.created?.call(this.#publicInstance)\n }\n\n get [WEVU_HOST_COMMIT_PROMISE_KEY]() {\n // 回调异常属于当前提交;后续属性更新或 HMR 必须等待自己的 Lit 提交。\n if (!supportsLit) {\n return undefined\n }\n // 动态 Lit 基类不会在静态声明中暴露 updateComplete。\n const litElement = this as unknown as { updateComplete: Promise<boolean> }\n const update = litElement.updateComplete\n return this.#hostCommitUpdate === update ? this.#hostCommitPromise : update\n }\n\n setData(patch: DataRecord, callback?: () => void) {\n const changed = this.#applyDataPatch(patch)\n if (supportsLit && (changed || this.#needsSetDataRecovery)) {\n if (!changed) {\n this.requestUpdate()\n }\n // 动态 Lit 基类不会在静态声明中暴露 updateComplete。\n const litElement = this as unknown as { updateComplete: Promise<boolean> }\n const update = litElement.updateComplete\n const commitPromise = update.then(\n () => {\n this.#needsSetDataRecovery = false\n callback?.()\n },\n (cause) => {\n this.#needsSetDataRecovery = true\n throw cause\n },\n )\n this.#hostCommitPromise = commitPromise\n this.#hostCommitUpdate = update\n return commitPromise\n }\n callback?.()\n }\n\n triggerEvent(name: string, detail?: any, options: TriggerEventOptions = {}) {\n this.dispatchEvent(markComponentEvent(new CustomEvent(name, {\n detail,\n bubbles: options.bubbles ?? false,\n composed: options.composed ?? false,\n })))\n }\n\n [WEVU_HOST_INSTALL_METHOD_KEY](methods: Readonly<Record<string, (...args: any[]) => any>>) {\n const bound: Record<string, (...args: any[]) => any> = {}\n for (const [name, method] of Object.entries(methods)) {\n bound[name] = method.bind(this.#publicInstance)\n }\n this.#setupMethods = bound\n this.#syncMethods(runtimeState.componentRef.methods)\n this.requestUpdate()\n }\n\n createSelectorQuery() {\n return createScopedSelectorQuery(this)\n }\n\n createIntersectionObserver(options?: {\n initialRatio?: number\n observeAll?: boolean\n thresholds?: number[]\n }) {\n return createIntersectionObserverBridge(this, options)\n }\n\n selectComponent(selector: string) {\n return selectRuntimeComponent(this, selector)\n }\n\n selectAllComponents(selector: string) {\n return selectRuntimeComponents(this, selector)\n }\n\n getRelationNodes(relationPath: string) {\n const relation = runtimeState.componentRef.relations?.[relationPath]\n return relation\n ? resolveRelationNodes(this, runtimeState.id, relationPath, relation.type)\n : []\n }\n\n selectOwnerComponent() {\n let current = resolveComposedParent(this)\n while (current) {\n if (isWeappComponentInstance(current)) {\n return current\n }\n current = resolveComposedParent(current)\n }\n return undefined\n }\n\n connectedCallback() {\n instances.add(this)\n const superConnected = (BaseElement.prototype as { connectedCallback?: () => void }).connectedCallback\n if (supportsLit && typeof superConnected === 'function') {\n superConnected.call(this)\n }\n this.#applyAttributes()\n if (runtimeState.observerInitEnabled) {\n this.#runInitialObservers()\n }\n runtimeState.lifetimes.attached?.call(this.#publicInstance)\n this.#isMounted = true\n trackAppStyle(this, runtimeState.inheritAppStyle)\n this.requestUpdate()\n }\n\n disconnectedCallback() {\n const superDisconnected = (BaseElement.prototype as { disconnectedCallback?: () => void }).disconnectedCallback\n if (supportsLit && typeof superDisconnected === 'function') {\n superDisconnected.call(this)\n }\n this.#isMounted = false\n trackAppStyle(this, false)\n instances.delete(this)\n runtimeState.lifetimes.detached?.call(this.#publicInstance)\n }\n\n attributeChangedCallback(attrName: string, oldValue: string | null, newValue: string | null) {\n const superAttributeChanged = (BaseElement.prototype as {\n attributeChangedCallback?: (name: string, oldValue: string | null, newValue: string | null) => void\n }).attributeChangedCallback\n if (supportsLit && typeof superAttributeChanged === 'function') {\n superAttributeChanged.call(this, attrName, oldValue, newValue)\n }\n const propName = toCamelCase(attrName)\n if (!hasOwn(this.#properties, propName)) {\n return\n }\n const propOption = runtimeState.componentRef.properties?.[propName]\n this.#setProperty(propName, coerceValue(newValue, propOption?.type))\n }\n\n firstUpdated() {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n\n updated() {\n this.#syncVirtualHostClasses()\n if (this.#usesLegacyTemplate) {\n bindRuntimeEvents(resolveRenderRoot(this), this.#methods, this)\n }\n }\n\n render() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const appStyle = runtimeState.inheritAppStyle ? getAppStyle() : ''\n this.#usesLegacyTemplate = typeof result === 'string'\n return html`<style>${appStyle}</style><style>${runtimeState.styleRef}</style>${typeof result === 'string' ? unsafeHTML(result) : result}`\n }\n\n requestUpdate(name?: PropertyKey, oldValue?: unknown, options?: unknown) {\n const superRequestUpdate = (BaseElement.prototype as any).requestUpdate\n if (supportsLit && typeof superRequestUpdate === 'function') {\n return superRequestUpdate.call(this, name, oldValue, options)\n }\n if (this.#isMounted) {\n this.#renderLegacy()\n }\n return undefined\n }\n\n #applyAttributes() {\n if (!this.attributes || typeof this.attributes[Symbol.iterator] !== 'function') {\n return\n }\n for (const attr of this.attributes) {\n this.attributeChangedCallback(attr.name, null, attr.value)\n }\n }\n\n #applyDataPatch(patch: DataRecord) {\n if (!patch || typeof patch !== 'object') {\n return false\n }\n let changed = false\n const changedKeys: string[] = []\n const previousProperties: DataRecord = {}\n let copiedContainers: WeakSet<object> | undefined\n for (const [path, value] of Object.entries(patch)) {\n const segments = parseDataPath(path)\n const topKey = segments[0]\n if (!topKey || topKey === '$slots') {\n continue\n }\n let nextValue = value\n if (value !== null && typeof value === 'object') {\n // 整体提交需刷新整个子树,新的外层对象也可能复用已原地修改的后代。\n // 快照可保留内部别名,路径更新仍需按分支取得写入所有权。\n nextValue = cloneCommittedValue(value)\n }\n else if (Object.is(resolveDataPath(this.#state, segments), value)) {\n continue\n }\n if (hasOwn(this.#properties, topKey) && !hasOwn(previousProperties, topKey)) {\n previousProperties[topKey] = this.#properties[topKey]\n }\n if (segments.length > 1) {\n copiedContainers ??= new WeakSet<object>()\n }\n assignDataPath(this.#state, segments, nextValue, copiedContainers)\n if (hasOwn(this.#properties, topKey)) {\n this.#properties[topKey] = this.#state[topKey]\n }\n changedKeys.push(path)\n changed = true\n }\n if (changed) {\n this.requestUpdate()\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, changedKeys, previousProperties)\n for (const key of changedKeys) {\n if (runtimeState.componentRef.properties?.[key]?.observer) {\n this.#observedKeys.add(key)\n }\n }\n }\n return changed\n }\n\n #setProperty(name: string, value: any) {\n const propOption = runtimeState.componentRef.properties?.[name]\n const coerced = coerceValue(value, propOption?.type)\n const oldValue = this.#properties[name]\n if (oldValue === coerced) {\n return\n }\n this.#properties[name] = coerced\n this.#state[name] = coerced\n if (this.#isMounted) {\n this.requestUpdate()\n }\n runComponentObservers(runtimeState.componentRef, this.#publicInstance, [name], { [name]: oldValue })\n if (propOption?.observer) {\n this.#observedKeys.add(name)\n }\n }\n\n #runInitialObservers() {\n if (this.#observerInitDone) {\n return\n }\n this.#observerInitDone = true\n for (const [propName, propOption] of runtimeState.propertyEntries) {\n if (!propOption.observer || this.#observedKeys.has(propName)) {\n continue\n }\n const value = this.#state[propName]\n propOption.observer.call(this.#publicInstance, value, undefined)\n this.#observedKeys.add(propName)\n }\n }\n\n #syncMethods(nextMethods: ComponentOptions['methods']) {\n const resolved = nextMethods ?? {}\n const bound: Record<string, (event: any) => any> = {}\n for (const [name, fn] of Object.entries(resolved)) {\n if (typeof fn === 'function') {\n bound[name] = fn.bind(this.#publicInstance)\n }\n }\n Object.assign(bound, this.#setupMethods)\n for (const name of this.#exposedMethodNames) {\n if (name in bound) {\n continue\n }\n const descriptor = Object.getOwnPropertyDescriptor(this, name)\n if (descriptor?.configurable && descriptor.value === this.#methods[name]) {\n delete (this as unknown as Record<string, unknown>)[name]\n }\n this.#exposedMethodNames.delete(name)\n }\n for (const key of Object.keys(this.#methods)) {\n if (!(key in bound)) {\n delete this.#methods[key]\n }\n }\n for (const [key, fn] of Object.entries(bound)) {\n const previous = this.#methods[key]\n this.#methods[key] = fn\n if (this.#exposedMethodNames.has(key)) {\n const descriptor = Object.getOwnPropertyDescriptor(this, key)\n if (!descriptor?.configurable || descriptor.value !== previous) {\n continue\n }\n }\n else if (key in this) {\n continue\n }\n Object.defineProperty(this, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: fn,\n })\n this.#exposedMethodNames.add(key)\n }\n this.#renderContext = createRenderContext(this, this.#methods)\n }\n\n __weappSync(nextMethods: ComponentOptions['methods']) {\n this.#syncMethods(nextMethods)\n trackAppStyle(this, this.#isMounted && runtimeState.inheritAppStyle)\n this.requestUpdate()\n }\n\n __weappInvokePageLifetime(type: keyof PageLifeTimeHooks) {\n const hook = runtimeState.pageLifetimes[type]\n if (typeof hook === 'function') {\n hook.call(this.#publicInstance)\n }\n }\n\n #renderLegacy() {\n const result = runtimeState.templateRef(this.#state, this.#renderContext)\n const root = resolveRenderRoot(this)\n const appStyle = runtimeState.inheritAppStyle ? getAppStyle() : ''\n const styleMarkup = `<style>${appStyle}</style><style>${runtimeState.styleRef}</style>`\n if (typeof result === 'string') {\n root.innerHTML = `${styleMarkup}${result}`\n bindRuntimeEvents(root as ShadowRoot, this.#methods, this)\n }\n else if (result == null) {\n root.innerHTML = styleMarkup\n }\n else {\n root.innerHTML = `${styleMarkup}${String(result)}`\n }\n this.#syncVirtualHostClasses()\n if (!this.#readyFired) {\n runtimeState.lifetimes.ready?.call(this.#publicInstance)\n this.#readyFired = true\n }\n }\n\n #syncVirtualHostClasses() {\n const host = this as unknown as ClassAttributeElement\n if (!runtimeState.componentRef.options?.virtualHost) {\n clearVirtualHostClasses(host, this.#virtualHostClassTokens)\n clearVirtualHostParts(this.#virtualHostRootElement, this.#virtualHostPartTokens)\n this.#virtualHostRootElement = undefined\n return\n }\n const root = resolveRenderRoot(this)\n syncVirtualHostClasses(host, root, this.#virtualHostClassTokens)\n this.#virtualHostRootElement = syncVirtualHostParts(\n root,\n this.#virtualHostRootElement,\n this.#virtualHostPartTokens,\n )\n }\n }\n\n return WeappWebComponent as WeappComponentElementClass\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6CA,SAAS,sBAAsB,MAA8B;CAC3D,MAAM,eAAgB,KAAiB;CACvC,IAAI,cACF,OAAO;CAET,IAAI,KAAK,YACP,OAAO,KAAK;CAEd,MAAM,OAAO,KAAK,cAAc;CAChC,OAAO,gBAAgB,aAAa,KAAK,OAAO;AAClD;AAEA,SAAS,yBAAyB,OAAiD;CACjF,OAAO,QACL,SACG,OAAO,UAAU,YACjB,OAAQ,MAAiC,gBAAgB,UAC9D;AACF;AAEA,SAAgB,4BAA4B,EAC1C,aACA,cACA,aACiE;CACjE,MAAM,qBAAqB;CAG3B,MAAM,0BAA0B,mBAAqD;EACnF,WAAW,qBAAqB;GAC9B,MAAM,YAAY,MAAM,sBAAsB,CAAC;GAC/C,OAAO,MAAM,qBAAK,IAAI,IAAI,CAAC,GAAG,WAAW,GAAG,aAAa,kBAAkB,CAAC,CAAC;EAC/E;EAEA;EACA;EACA,WAAgD,CAAC;EACjD,gBAAyD,CAAC;EAC1D;EACA,sCAAsB,IAAI,IAAY;EACtC,aAAa;EACb,iBAAiB,oBAAoB,MAAM,CAAC,CAAC;EAC7C,sBAAsB;EACtB,cAAc;EACd,oBAAoB;EACpB,gCAAgB,IAAI,I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AAU,IAAI;GAC3D,OACK,IAAI,UAAU,MACjB,KAAK,YAAY;QAGjB,KAAK,YAAY,GAAG,cAAc,OAAO,MAAM;GAEjD,KAAK,wBAAwB;GAC7B,IAAI,CAAC,KAAK,aAAa;IACrB,aAAa,UAAU,OAAO,KAAK,KAAK,eAAe;IACvD,KAAK,cAAc;GACrB;EACF;EAEA,0BAA0B;GACxB,MAAM,OAAO;GACb,IAAI,CAAC,aAAa,aAAa,SAAS,aAAa;IACnD,wBAAwB,MAAM,KAAK,uBAAuB;IAC1D,sBAAsB,KAAK,yBAAyB,KAAK,sBAAsB;IAC/E,KAAK,0BAA0B;IAC/B;GACF;GACA,MAAM,OAAO,kBAAkB,IAAI;GACnC,uBAAuB,MAAM,MAAM,KAAK,uBAAuB;GAC/D,KAAK,0BAA0B,qBAC7B,MACA,KAAK,yBACL,KAAK,sBACP;EACF;CACF;CAEA,OAAO;AACT"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { EVENT_ATTRIBUTE_PREFIXES, EVENT_FLAG_ATTRIBUTE_PREFIXES, decodeEventAttributeName } from "./constants.mjs";
|
|
2
|
+
import { listenRuntimeEvent, nameRuntimeEventHandler } from "../componentEvents.mjs";
|
|
2
3
|
import { invokeMiniProgramEventHandler } from "../inputHandlerResult.mjs";
|
|
3
4
|
|
|
4
5
|
//#region src/runtime/component/events.ts
|
|
@@ -14,12 +15,28 @@ function parseEventFlags(value) {
|
|
|
14
15
|
capture: tokenSet.has("capture")
|
|
15
16
|
};
|
|
16
17
|
}
|
|
18
|
+
const runtimeEventBindings = /* @__PURE__ */ new WeakMap();
|
|
19
|
+
function getEventFlagAttributeValue(element, encodedEventName) {
|
|
20
|
+
for (const prefix of EVENT_FLAG_ATTRIBUTE_PREFIXES) {
|
|
21
|
+
const value = element.getAttribute(`${prefix}${encodedEventName}`);
|
|
22
|
+
if (value !== null) return value;
|
|
23
|
+
}
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
17
26
|
function bindRuntimeEvents(root, methods, instance) {
|
|
18
27
|
if (typeof document === "undefined") return;
|
|
19
28
|
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
|
|
20
29
|
while (walker.nextNode()) {
|
|
21
30
|
const element = walker.currentNode;
|
|
31
|
+
let bindings = runtimeEventBindings.get(element);
|
|
32
|
+
if (bindings) for (const [attribute, binding] of bindings) {
|
|
33
|
+
const handlerName = element.getAttribute(attribute);
|
|
34
|
+
if (handlerName && methods[handlerName] === binding.handler && instance === binding.instance && getEventFlagAttributeValue(element, binding.encodedEventName) === binding.flagAttributeValue) continue;
|
|
35
|
+
binding.dispose();
|
|
36
|
+
bindings.delete(attribute);
|
|
37
|
+
}
|
|
22
38
|
for (const attribute of element.getAttributeNames()) {
|
|
39
|
+
if (bindings?.has(attribute)) continue;
|
|
23
40
|
const matchedPrefix = EVENT_ATTRIBUTE_PREFIXES.find((prefix) => attribute.startsWith(prefix));
|
|
24
41
|
if (!matchedPrefix || EVENT_FLAG_ATTRIBUTE_PREFIXES.some((prefix) => attribute.startsWith(prefix))) continue;
|
|
25
42
|
const handlerName = element.getAttribute(attribute);
|
|
@@ -28,8 +45,9 @@ function bindRuntimeEvents(root, methods, instance) {
|
|
|
28
45
|
if (!handler) continue;
|
|
29
46
|
const encodedEventName = attribute.slice(matchedPrefix.length);
|
|
30
47
|
const eventName = decodeEventAttributeName(encodedEventName);
|
|
31
|
-
const
|
|
32
|
-
|
|
48
|
+
const flagAttributeValue = getEventFlagAttributeValue(element, encodedEventName);
|
|
49
|
+
const flags = parseEventFlags(flagAttributeValue);
|
|
50
|
+
const listener = nameRuntimeEventHandler((nativeEvent) => {
|
|
33
51
|
if (flags.catch) nativeEvent.stopPropagation();
|
|
34
52
|
const dataset = { ...element.dataset };
|
|
35
53
|
const syntheticEvent = {
|
|
@@ -41,8 +59,21 @@ function bindRuntimeEvents(root, methods, instance) {
|
|
|
41
59
|
originalEvent: nativeEvent
|
|
42
60
|
};
|
|
43
61
|
invokeMiniProgramEventHandler(handler, instance, syntheticEvent, nativeEvent);
|
|
44
|
-
},
|
|
62
|
+
}, eventName);
|
|
63
|
+
const dispose = listenRuntimeEvent(element, eventName, listener, flags.capture);
|
|
64
|
+
if (!bindings) {
|
|
65
|
+
bindings = /* @__PURE__ */ new Map();
|
|
66
|
+
runtimeEventBindings.set(element, bindings);
|
|
67
|
+
}
|
|
68
|
+
bindings.set(attribute, {
|
|
69
|
+
encodedEventName,
|
|
70
|
+
flagAttributeValue,
|
|
71
|
+
handler,
|
|
72
|
+
instance,
|
|
73
|
+
dispose
|
|
74
|
+
});
|
|
45
75
|
}
|
|
76
|
+
if (bindings?.size === 0) runtimeEventBindings.delete(element);
|
|
46
77
|
}
|
|
47
78
|
}
|
|
48
79
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.mjs","names":[],"sources":["../../../src/runtime/component/events.ts"],"sourcesContent":["import type { ComponentPublicInstance } from './types'\nimport { invokeMiniProgramEventHandler } from '../inputHandlerResult'\nimport {\n decodeEventAttributeName,\n EVENT_ATTRIBUTE_PREFIXES,\n EVENT_FLAG_ATTRIBUTE_PREFIXES,\n} from './constants'\n\nfunction parseEventFlags(value: string | null) {\n if (!value) {\n return { catch: false, capture: false }\n }\n const tokens = value.split(',').map(token => token.trim()).filter(Boolean)\n const tokenSet = new Set(tokens)\n return {\n catch: tokenSet.has('catch'),\n capture: tokenSet.has('capture'),\n }\n}\n\nexport function bindRuntimeEvents(\n root: HTMLElement | ShadowRoot,\n methods: Record<string, (event: any) => any>,\n instance: ComponentPublicInstance,\n) {\n if (typeof document === 'undefined') {\n return\n }\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT)\n while (walker.nextNode()) {\n const element = walker.currentNode as HTMLElement\n for (const attribute of element.getAttributeNames()) {\n const matchedPrefix = EVENT_ATTRIBUTE_PREFIXES.find(prefix => attribute.startsWith(prefix))\n if (!matchedPrefix || EVENT_FLAG_ATTRIBUTE_PREFIXES.some(prefix => attribute.startsWith(prefix))) {\n continue\n }\n const handlerName = element.getAttribute(attribute)\n if (!handlerName) {\n continue\n }\n const handler = methods[handlerName]\n if (!handler) {\n continue\n }\n const encodedEventName = attribute.slice(matchedPrefix.length)\n const eventName = decodeEventAttributeName(encodedEventName)\n const flagAttributeValue =
|
|
1
|
+
{"version":3,"file":"events.mjs","names":[],"sources":["../../../src/runtime/component/events.ts"],"sourcesContent":["import type { ComponentPublicInstance } from './types'\nimport { listenRuntimeEvent, nameRuntimeEventHandler } from '../componentEvents'\nimport { invokeMiniProgramEventHandler } from '../inputHandlerResult'\nimport {\n decodeEventAttributeName,\n EVENT_ATTRIBUTE_PREFIXES,\n EVENT_FLAG_ATTRIBUTE_PREFIXES,\n} from './constants'\n\ninterface RuntimeEventFlags {\n catch: boolean\n capture: boolean\n}\n\nfunction parseEventFlags(value: string | null): RuntimeEventFlags {\n if (!value) {\n return { catch: false, capture: false }\n }\n const tokens = value.split(',').map(token => token.trim()).filter(Boolean)\n const tokenSet = new Set(tokens)\n return {\n catch: tokenSet.has('catch'),\n capture: tokenSet.has('capture'),\n }\n}\n\ninterface RuntimeEventBinding {\n encodedEventName: string\n flagAttributeValue: string | null\n handler: (event: unknown) => unknown\n instance: ComponentPublicInstance\n dispose: () => void\n}\n\nconst runtimeEventBindings = new WeakMap<HTMLElement, Map<string, RuntimeEventBinding>>()\n\nfunction getEventFlagAttributeValue(element: HTMLElement, encodedEventName: string) {\n for (const prefix of EVENT_FLAG_ATTRIBUTE_PREFIXES) {\n const value = element.getAttribute(`${prefix}${encodedEventName}`)\n if (value !== null) {\n return value\n }\n }\n return null\n}\n\nexport function bindRuntimeEvents(\n root: HTMLElement | ShadowRoot,\n methods: Record<string, (event: any) => any>,\n instance: ComponentPublicInstance,\n) {\n if (typeof document === 'undefined') {\n return\n }\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT)\n while (walker.nextNode()) {\n const element = walker.currentNode as HTMLElement\n let bindings = runtimeEventBindings.get(element)\n if (bindings) {\n for (const [attribute, binding] of bindings) {\n const handlerName = element.getAttribute(attribute)\n if (\n handlerName\n && methods[handlerName] === binding.handler\n && instance === binding.instance\n && getEventFlagAttributeValue(element, binding.encodedEventName) === binding.flagAttributeValue\n ) {\n continue\n }\n binding.dispose()\n bindings.delete(attribute)\n }\n }\n for (const attribute of element.getAttributeNames()) {\n if (bindings?.has(attribute)) {\n continue\n }\n const matchedPrefix = EVENT_ATTRIBUTE_PREFIXES.find(prefix => attribute.startsWith(prefix))\n if (!matchedPrefix || EVENT_FLAG_ATTRIBUTE_PREFIXES.some(prefix => attribute.startsWith(prefix))) {\n continue\n }\n const handlerName = element.getAttribute(attribute)\n if (!handlerName) {\n continue\n }\n const handler = methods[handlerName]\n if (!handler) {\n continue\n }\n const encodedEventName = attribute.slice(matchedPrefix.length)\n const eventName = decodeEventAttributeName(encodedEventName)\n const flagAttributeValue = getEventFlagAttributeValue(element, encodedEventName)\n const flags = parseEventFlags(flagAttributeValue)\n const listener = nameRuntimeEventHandler((nativeEvent) => {\n if (flags.catch) {\n nativeEvent.stopPropagation()\n }\n const dataset = { ...element.dataset }\n const syntheticEvent = {\n type: eventName,\n timeStamp: nativeEvent.timeStamp,\n detail: (nativeEvent as CustomEvent).detail ?? (nativeEvent as InputEvent).data ?? undefined,\n target: {\n dataset,\n },\n currentTarget: {\n dataset,\n },\n originalEvent: nativeEvent,\n }\n invokeMiniProgramEventHandler(handler, instance, syntheticEvent, nativeEvent)\n }, eventName)\n const dispose = listenRuntimeEvent(element, eventName, listener, flags.capture)\n if (!bindings) {\n bindings = new Map()\n runtimeEventBindings.set(element, bindings)\n }\n bindings.set(attribute, { encodedEventName, flagAttributeValue, handler, instance, dispose })\n }\n if (bindings?.size === 0) {\n runtimeEventBindings.delete(element)\n }\n }\n}\n"],"mappings":";;;;;AAcA,SAAS,gBAAgB,OAAyC;CAChE,IAAI,CAAC,OACH,OAAO;EAAE,OAAO;EAAO,SAAS;CAAM;CAExC,MAAM,SAAS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,UAAU,MAAM,cAAc,MAAM;GAC7D,MAAM,YAAY,yBAAyB,gBAAgB;GAC3D,MAAM,qBAAqB,2BAA2B,SAAS,gBAAgB;GAC/E,MAAM,QAAQ,gBAAgB,kBAAkB;GAChD,MAAM,WAAW,yBAAyB,gBAAgB;IACxD,IAAI,MAAM,OACR,YAAY,gBAAgB;IAE9B,MAAM,UAAU,EAAE,GAAG,QAAQ,QAAQ;IACrC,MAAM,iBAAiB;KACrB,MAAM;KACN,WAAW,YAAY;KACvB,QAAS,YAA4B,UAAW,YAA2B,QAAQ;KACnF,QAAQ,EACN,QACF;KACA,eAAe,EACb,QACF;KACA,eAAe;IACjB;IACA,8BAA8B,SAAS,UAAU,gBAAgB,WAAW;GAC9E,GAAG,SAAS;GACZ,MAAM,UAAU,mBAAmB,SAAS,WAAW,UAAU,MAAM,OAAO;GAC9E,IAAI,CAAC,UAAU;IACb,2BAAW,IAAI,IAAI;IACnB,qBAAqB,IAAI,SAAS,QAAQ;GAC5C;GACA,SAAS,IAAI,WAAW;IAAE;IAAkB;IAAoB;IAAS;IAAU;GAAQ,CAAC;EAC9F;EACA,IAAI,UAAU,SAAS,GACrB,qBAAqB,OAAO,OAAO;CAEvC;AACF"}
|
|
@@ -1,15 +1,18 @@
|
|
|
1
|
+
import { hasOwn } from "../utils/object.mjs";
|
|
2
|
+
|
|
1
3
|
//#region src/runtime/component/publicInstance.ts
|
|
2
4
|
const componentPublicInstanceTargets = /* @__PURE__ */ new WeakMap();
|
|
3
5
|
function resolveComponentPublicInstanceTarget(value) {
|
|
4
6
|
if (!value || typeof value !== "object") return;
|
|
5
7
|
return componentPublicInstanceTargets.get(value);
|
|
6
8
|
}
|
|
7
|
-
function createComponentPublicInstance(target, runtimePrototype, resolveComponentMethod) {
|
|
9
|
+
function createComponentPublicInstance(target, runtimePrototype, resolveComponentMethod, componentProperties) {
|
|
8
10
|
const runtimeMethods = /* @__PURE__ */ new Map();
|
|
9
11
|
const publicInstance = new Proxy(target, {
|
|
10
12
|
get(instance, key) {
|
|
11
|
-
|
|
12
|
-
if (
|
|
13
|
+
const ownDescriptor = Reflect.getOwnPropertyDescriptor(instance, key);
|
|
14
|
+
if (ownDescriptor && (!ownDescriptor.configurable || !componentProperties || !hasOwn(componentProperties, key))) return Reflect.get(instance, key, instance);
|
|
15
|
+
if (Reflect.getOwnPropertyDescriptor(runtimePrototype, key) && !ownDescriptor) {
|
|
13
16
|
const value = Reflect.get(instance, key, instance);
|
|
14
17
|
if (typeof value !== "function") return value;
|
|
15
18
|
const cached = runtimeMethods.get(key);
|
|
@@ -23,6 +26,7 @@ function createComponentPublicInstance(target, runtimePrototype, resolveComponen
|
|
|
23
26
|
}
|
|
24
27
|
const componentMethod = resolveComponentMethod?.(key);
|
|
25
28
|
if (typeof componentMethod === "function") return componentMethod;
|
|
29
|
+
if (ownDescriptor) return Reflect.get(instance, key, instance);
|
|
26
30
|
return typeof key === "symbol" ? Reflect.get(instance, key, instance) : void 0;
|
|
27
31
|
},
|
|
28
32
|
set(instance, key, value) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"publicInstance.mjs","names":[],"sources":["../../../src/runtime/component/publicInstance.ts"],"sourcesContent":["import type { ComponentPublicInstance } from './types'\n\nconst componentPublicInstanceTargets = new WeakMap<object, ComponentPublicInstance>()\n\nexport function resolveComponentPublicInstanceTarget(value: unknown) {\n if (!value || typeof value !== 'object') {\n return undefined\n }\n return componentPublicInstanceTargets.get(value)\n}\n\nexport function createComponentPublicInstance(\n target: ComponentPublicInstance,\n runtimePrototype: object,\n resolveComponentMethod?: (key: PropertyKey) => unknown,\n): ComponentPublicInstance {\n type RuntimeMethod = (...args: any[]) => unknown\n const runtimeMethods = new Map<PropertyKey, { source: RuntimeMethod, bound: RuntimeMethod }>()\n\n const publicInstance = new Proxy(target, {\n get(instance, key) {\n const ownDescriptor = Reflect.getOwnPropertyDescriptor(instance, key)\n if (ownDescriptor) {\n return Reflect.get(instance, key, instance)\n }\n const runtimeDescriptor = Reflect.getOwnPropertyDescriptor(runtimePrototype, key)\n if (runtimeDescriptor) {\n const value = Reflect.get(instance, key, instance)\n if (typeof value !== 'function') {\n return value\n }\n const cached = runtimeMethods.get(key)\n if (cached && cached.source === value) {\n return cached.bound\n }\n const bound = value.bind(instance)\n runtimeMethods.set(key, { source: value, bound })\n return bound\n }\n const componentMethod = resolveComponentMethod?.(key)\n if (typeof componentMethod === 'function') {\n return componentMethod\n }\n return typeof key === 'symbol' ? Reflect.get(instance, key, instance) : undefined\n },\n set(instance, key, value) {\n if (Reflect.getOwnPropertyDescriptor(instance, key) || typeof key === 'symbol') {\n return Reflect.set(instance, key, value, instance)\n }\n Reflect.defineProperty(instance, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value,\n })\n return true\n },\n has(instance, key) {\n return Reflect.getOwnPropertyDescriptor(instance, key) !== undefined\n || Reflect.getOwnPropertyDescriptor(runtimePrototype, key) !== undefined\n || typeof resolveComponentMethod?.(key) === 'function'\n || (typeof key === 'symbol' && Reflect.has(instance, key))\n },\n })\n componentPublicInstanceTargets.set(publicInstance, target)\n return publicInstance\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"publicInstance.mjs","names":[],"sources":["../../../src/runtime/component/publicInstance.ts"],"sourcesContent":["import type { ComponentPublicInstance } from './types'\nimport { hasOwn } from '../utils/object'\n\nconst componentPublicInstanceTargets = new WeakMap<object, ComponentPublicInstance>()\n\nexport function resolveComponentPublicInstanceTarget(value: unknown) {\n if (!value || typeof value !== 'object') {\n return undefined\n }\n return componentPublicInstanceTargets.get(value)\n}\n\nexport function createComponentPublicInstance(\n target: ComponentPublicInstance,\n runtimePrototype: object,\n resolveComponentMethod?: (key: PropertyKey) => unknown,\n componentProperties?: Readonly<Record<string, unknown>>,\n): ComponentPublicInstance {\n type RuntimeMethod = (...args: any[]) => unknown\n const runtimeMethods = new Map<PropertyKey, { source: RuntimeMethod, bound: RuntimeMethod }>()\n\n const publicInstance = new Proxy(target, {\n get(instance, key) {\n const ownDescriptor = Reflect.getOwnPropertyDescriptor(instance, key)\n // 只有声明的 prop 冲突才优先方法表;普通自有字段与不可配置属性保持宿主语义。\n if (ownDescriptor && (!ownDescriptor.configurable || !componentProperties || !hasOwn(componentProperties, key))) {\n return Reflect.get(instance, key, instance)\n }\n const runtimeDescriptor = Reflect.getOwnPropertyDescriptor(runtimePrototype, key)\n if (runtimeDescriptor && !ownDescriptor) {\n const value = Reflect.get(instance, key, instance)\n if (typeof value !== 'function') {\n return value\n }\n const cached = runtimeMethods.get(key)\n if (cached && cached.source === value) {\n return cached.bound\n }\n const bound = value.bind(instance)\n runtimeMethods.set(key, { source: value, bound })\n return bound\n }\n // 公共实例解析方法;DOM 同名属性仍由父级输入驱动。\n const componentMethod = resolveComponentMethod?.(key)\n if (typeof componentMethod === 'function') {\n return componentMethod\n }\n if (ownDescriptor) {\n return Reflect.get(instance, key, instance)\n }\n return typeof key === 'symbol' ? Reflect.get(instance, key, instance) : undefined\n },\n set(instance, key, value) {\n if (Reflect.getOwnPropertyDescriptor(instance, key) || typeof key === 'symbol') {\n return Reflect.set(instance, key, value, instance)\n }\n Reflect.defineProperty(instance, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value,\n })\n return true\n },\n has(instance, key) {\n return Reflect.getOwnPropertyDescriptor(instance, key) !== undefined\n || Reflect.getOwnPropertyDescriptor(runtimePrototype, key) !== undefined\n || typeof resolveComponentMethod?.(key) === 'function'\n || (typeof key === 'symbol' && Reflect.has(instance, key))\n },\n })\n componentPublicInstanceTargets.set(publicInstance, target)\n return publicInstance\n}\n"],"mappings":";;;AAGA,MAAM,iDAAiC,IAAI,QAAyC;AAEpF,SAAgB,qCAAqC,OAAgB;CACnE,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B;CAEF,OAAO,+BAA+B,IAAI,KAAK;AACjD;AAEA,SAAgB,8BACd,QACA,kBACA,wBACA,qBACyB;CAEzB,MAAM,iCAAiB,IAAI,IAAkE;CAE7F,MAAM,iBA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,+BAA+B,IAAI,gBAAgB,MAAM;CACzD,OAAO;AACT"}
|
|
@@ -31,6 +31,11 @@ function createPropertyEntries(component) {
|
|
|
31
31
|
function createObservedAttributes(propertyEntries) {
|
|
32
32
|
return propertyEntries.map(([name]) => hyphenate(name));
|
|
33
33
|
}
|
|
34
|
+
function inheritsAppStyle(kind, component) {
|
|
35
|
+
if (kind === "page") return true;
|
|
36
|
+
const { styleIsolation, addGlobalClass } = component.options ?? {};
|
|
37
|
+
return styleIsolation === void 0 ? Boolean(addGlobalClass) : styleIsolation !== "isolated";
|
|
38
|
+
}
|
|
34
39
|
function createComponentRuntimeState(options) {
|
|
35
40
|
const { component, warnings } = resolveNormalizedComponent(options.component ?? {});
|
|
36
41
|
const propertyEntries = createPropertyEntries(component);
|
|
@@ -39,6 +44,7 @@ function createComponentRuntimeState(options) {
|
|
|
39
44
|
id: options.id,
|
|
40
45
|
templateRef: options.template,
|
|
41
46
|
styleRef: options.style ?? "",
|
|
47
|
+
inheritAppStyle: inheritsAppStyle(options.kind, component),
|
|
42
48
|
componentRef: component,
|
|
43
49
|
observerInitEnabled: Boolean(options.observerInit),
|
|
44
50
|
propertyEntries,
|
|
@@ -56,6 +62,7 @@ function updateComponentRuntimeState(state, options) {
|
|
|
56
62
|
state.templateRef = options.template;
|
|
57
63
|
state.id = options.id;
|
|
58
64
|
state.styleRef = options.style ?? "";
|
|
65
|
+
state.inheritAppStyle = inheritsAppStyle(options.kind, component);
|
|
59
66
|
state.componentRef = component;
|
|
60
67
|
state.observerInitEnabled = Boolean(options.observerInit);
|
|
61
68
|
state.lifetimes = component.lifetimes ?? {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.mjs","names":[],"sources":["../../../src/runtime/component/state.ts"],"sourcesContent":["import type {\n ComponentOptions,\n DataRecord,\n DefineComponentOptions,\n LifeTimeHooks,\n NormalizedComponentOptions,\n PageLifeTimeHooks,\n PropertyDeclaration,\n PropertyOption,\n} from './types'\nimport { hasOwn } from '../utils/object'\nimport { normalizeBehaviors } from './behavior'\nimport { cloneValue, hyphenate } from './utils'\n\ntype PropertyEntry = [string, PropertyOption]\n\nexport interface ComponentRuntimeState {\n id?: string\n templateRef: DefineComponentOptions['template']\n styleRef: string\n componentRef: NormalizedComponentOptions\n observerInitEnabled: boolean\n propertyEntries: PropertyEntry[]\n observedAttributes: string[]\n defaultPropertyValues: DataRecord\n lifetimes: LifeTimeHooks\n pageLifetimes: PageLifeTimeHooks\n}\n\nfunction normalizePropertyDeclaration(declaration: PropertyDeclaration): PropertyOption {\n if (declaration === null || typeof declaration === 'function') {\n return { type: declaration }\n }\n return declaration\n}\n\nfunction resolveNormalizedComponent(component: ComponentOptions) {\n const normalized = normalizeBehaviors(component)\n const resolved = normalized.component!\n return {\n warnings: normalized.warnings,\n component: {\n ...resolved,\n properties: Object.fromEntries(\n Object.entries(resolved.properties ?? {}).map(([name, declaration]) => [\n name,\n normalizePropertyDeclaration(declaration),\n ]),\n ),\n } satisfies NormalizedComponentOptions,\n }\n}\n\nfunction createDefaultPropertyValues(propertyEntries: PropertyEntry[]) {\n return propertyEntries.reduce<DataRecord>((acc, [name, prop]) => {\n if (prop !== null && typeof prop === 'object' && hasOwn(prop, 'value')) {\n acc[name] = cloneValue(prop.value)\n }\n else {\n acc[name] = undefined\n }\n return acc\n }, {})\n}\n\nfunction createPropertyEntries(component: NormalizedComponentOptions): PropertyEntry[] {\n return Object.entries(component.properties)\n}\n\nfunction createObservedAttributes(propertyEntries: PropertyEntry[]) {\n return propertyEntries.map(([name]) => hyphenate(name))\n}\n\nexport function createComponentRuntimeState(options: DefineComponentOptions) {\n const { component, warnings } = resolveNormalizedComponent(options.component ?? {})\n const propertyEntries = createPropertyEntries(component)\n const state: ComponentRuntimeState = {\n id: options.id,\n templateRef: options.template,\n styleRef: options.style ?? '',\n componentRef: component,\n observerInitEnabled: Boolean(options.observerInit),\n propertyEntries,\n observedAttributes: createObservedAttributes(propertyEntries),\n defaultPropertyValues: createDefaultPropertyValues(propertyEntries),\n lifetimes: component.lifetimes ?? {},\n pageLifetimes: component.pageLifetimes ?? {},\n }\n return {\n state,\n warnings,\n }\n}\n\nexport function updateComponentRuntimeState(state: ComponentRuntimeState, options: DefineComponentOptions) {\n const { component, warnings } = resolveNormalizedComponent(options.component ?? {})\n const propertyEntries = createPropertyEntries(component)\n state.templateRef = options.template\n state.id = options.id\n state.styleRef = options.style ?? ''\n state.componentRef = component\n state.observerInitEnabled = Boolean(options.observerInit)\n state.lifetimes = component.lifetimes ?? {}\n state.pageLifetimes = component.pageLifetimes ?? {}\n state.propertyEntries = propertyEntries\n state.observedAttributes = createObservedAttributes(propertyEntries)\n state.defaultPropertyValues = createDefaultPropertyValues(propertyEntries)\n return {\n warnings,\n nextMethods: component.methods ?? {},\n }\n}\n"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"state.mjs","names":[],"sources":["../../../src/runtime/component/state.ts"],"sourcesContent":["import type {\n ComponentOptions,\n DataRecord,\n DefineComponentOptions,\n LifeTimeHooks,\n NormalizedComponentOptions,\n PageLifeTimeHooks,\n PropertyDeclaration,\n PropertyOption,\n} from './types'\nimport { hasOwn } from '../utils/object'\nimport { normalizeBehaviors } from './behavior'\nimport { cloneValue, hyphenate } from './utils'\n\ntype PropertyEntry = [string, PropertyOption]\n\nexport interface ComponentRuntimeState {\n id?: string\n templateRef: DefineComponentOptions['template']\n styleRef: string\n inheritAppStyle: boolean\n componentRef: NormalizedComponentOptions\n observerInitEnabled: boolean\n propertyEntries: PropertyEntry[]\n observedAttributes: string[]\n defaultPropertyValues: DataRecord\n lifetimes: LifeTimeHooks\n pageLifetimes: PageLifeTimeHooks\n}\n\nfunction normalizePropertyDeclaration(declaration: PropertyDeclaration): PropertyOption {\n if (declaration === null || typeof declaration === 'function') {\n return { type: declaration }\n }\n return declaration\n}\n\nfunction resolveNormalizedComponent(component: ComponentOptions) {\n const normalized = normalizeBehaviors(component)\n const resolved = normalized.component!\n return {\n warnings: normalized.warnings,\n component: {\n ...resolved,\n properties: Object.fromEntries(\n Object.entries(resolved.properties ?? {}).map(([name, declaration]) => [\n name,\n normalizePropertyDeclaration(declaration),\n ]),\n ),\n } satisfies NormalizedComponentOptions,\n }\n}\n\nfunction createDefaultPropertyValues(propertyEntries: PropertyEntry[]) {\n return propertyEntries.reduce<DataRecord>((acc, [name, prop]) => {\n if (prop !== null && typeof prop === 'object' && hasOwn(prop, 'value')) {\n acc[name] = cloneValue(prop.value)\n }\n else {\n acc[name] = undefined\n }\n return acc\n }, {})\n}\n\nfunction createPropertyEntries(component: NormalizedComponentOptions): PropertyEntry[] {\n return Object.entries(component.properties)\n}\n\nfunction createObservedAttributes(propertyEntries: PropertyEntry[]) {\n return propertyEntries.map(([name]) => hyphenate(name))\n}\n\nfunction inheritsAppStyle(kind: DefineComponentOptions['kind'], component: NormalizedComponentOptions) {\n if (kind === 'page') {\n return true\n }\n const { styleIsolation, addGlobalClass } = component.options ?? {}\n return styleIsolation === undefined ? Boolean(addGlobalClass) : styleIsolation !== 'isolated'\n}\n\nexport function createComponentRuntimeState(options: DefineComponentOptions) {\n const { component, warnings } = resolveNormalizedComponent(options.component ?? {})\n const propertyEntries = createPropertyEntries(component)\n const state: ComponentRuntimeState = {\n id: options.id,\n templateRef: options.template,\n styleRef: options.style ?? '',\n inheritAppStyle: inheritsAppStyle(options.kind, component),\n componentRef: component,\n observerInitEnabled: Boolean(options.observerInit),\n propertyEntries,\n observedAttributes: createObservedAttributes(propertyEntries),\n defaultPropertyValues: createDefaultPropertyValues(propertyEntries),\n lifetimes: component.lifetimes ?? {},\n pageLifetimes: component.pageLifetimes ?? {},\n }\n return {\n state,\n warnings,\n }\n}\n\nexport function updateComponentRuntimeState(state: ComponentRuntimeState, options: DefineComponentOptions) {\n const { component, warnings } = resolveNormalizedComponent(options.component ?? {})\n const propertyEntries = createPropertyEntries(component)\n state.templateRef = options.template\n state.id = options.id\n state.styleRef = options.style ?? ''\n state.inheritAppStyle = inheritsAppStyle(options.kind, component)\n state.componentRef = component\n state.observerInitEnabled = Boolean(options.observerInit)\n state.lifetimes = component.lifetimes ?? {}\n state.pageLifetimes = component.pageLifetimes ?? {}\n state.propertyEntries = propertyEntries\n state.observedAttributes = createObservedAttributes(propertyEntries)\n state.defaultPropertyValues = createDefaultPropertyValues(propertyEntries)\n return {\n warnings,\n nextMethods: component.methods ?? {},\n }\n}\n"],"mappings":";;;;;AA8BA,SAAS,6BAA6B,aAAkD;CACtF,IAAI,gBAAgB,QAAQ,OAAO,gBAAgB,YACjD,OAAO,EAAE,MAAM,YAAY;CAE7B,OAAO;AACT;AAEA,SAAS,2BAA2B,WAA6B;CAC/D,MAAM,aAAa,mBAAmB,SAAS;CAC/C,MAAM,WAAW,WAAW;CAC5B,OAAO;EACL,UAAU,WAAW;EACrB,WAAW;GACT,GAAG;GACH,YAAY,OAAO,YACjB,OAAO,QAAQ,SAAS,cAAc,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,iBAAiB,CACrE,MACA,6BAA6B,WAAW,CAC1C,CAAC,CACH;EACF;CACF;AACF;AAEA,SAAS,4BAA4B,iBAAkC;CACrE,OAAO,gBAAgB,QAAoB,KAAK,CAAC,MAAM,UAAU;EAC/D,IAAI,SAAS,QAAQ,OAAO,SAAS,YAAY,OAAO,MAAM,OAAO,GACnE,IAAI,QAAQ,WAAW,KAAK,KAAK;OAGjC,IAAI,QAAQ;EAEd,OAAO;CACT,GAAG,CAAC,CAAC;AACP;AAEA,SAAS,sBAAsB,WAAwD;CACrF,OAAO,OAAO,QAAQ,UAAU,UAAU;AAC5C;AAEA,SAAS,yBAAyB,iBAAkC;CAClE,OAAO,gBAAgB,KAAK,CAAC,UAAU,UAAU,IAAI,CAAC;AACxD;AAEA,SAAS,iBAAiB,MAAsC,WAAuC;CACrG,IAAI,SAAS,QACX,OAAO;CAET,MAAM,EAAE,gBAAgB,mBAAmB,UAAU,WAAW,CAAC;CACjE,OAAO,mBAAmB,SAAY,QAAQ,cAAc,IAAI,mBAAmB;AACrF;AAEA,SAAgB,4BAA4B,SAAiC;CAC3E,MAAM,EAAE,WAAW,aAAa,2BAA2B,QAAQ,aAAa,CAAC,CAAC;CAClF,MAAM,kBAAkB,sBAAsB,SAAS;CAcvD,OAAO;EACL;GAbA,IAAI,QAAQ;GACZ,aAAa,QAAQ;GACrB,UAAU,QAAQ,SAAS;GAC3B,iBAAiB,iBAAiB,QAAQ,MAAM,SAAS;GACzD,cAAc;GACd,qBAAqB,QAAQ,QAAQ,YAAY;GACjD;GACA,oBAAoB,yBAAyB,eAAe;GAC5D,uBAAuB,4BAA4B,eAAe;GAClE,WAAW,UAAU,aAAa,CAAC;GACnC,eAAe,UAAU,iBAAiB,CAAC;EAGvC;EACJ;CACF;AACF;AAEA,SAAgB,4BAA4B,OAA8B,SAAiC;CACzG,MAAM,EAAE,WAAW,aAAa,2BAA2B,QAAQ,aAAa,CAAC,CAAC;CAClF,MAAM,kBAAkB,sBAAsB,SAAS;CACvD,MAAM,cAAc,QAAQ;CAC5B,MAAM,KAAK,QAAQ;CACnB,MAAM,WAAW,QAAQ,SAAS;CAClC,MAAM,kBAAkB,iBAAiB,QAAQ,MAAM,SAAS;CAChE,MAAM,eAAe;CACrB,MAAM,sBAAsB,QAAQ,QAAQ,YAAY;CACxD,MAAM,YAAY,UAAU,aAAa,CAAC;CAC1C,MAAM,gBAAgB,UAAU,iBAAiB,CAAC;CAClD,MAAM,kBAAkB;CACxB,MAAM,qBAAqB,yBAAyB,eAAe;CACnE,MAAM,wBAAwB,4BAA4B,eAAe;CACzE,OAAO;EACL;EACA,aAAa,UAAU,WAAW,CAAC;CACrC;AACF"}
|
|
@@ -45,6 +45,8 @@ export interface ComponentOptions {
|
|
|
45
45
|
}
|
|
46
46
|
export interface DefineComponentOptions {
|
|
47
47
|
id?: string;
|
|
48
|
+
/** 注册层提供的样式域;组件仍按 styleIsolation 决定是否接收应用样式。 */
|
|
49
|
+
kind?: 'page' | 'component';
|
|
48
50
|
template: TemplateRenderer;
|
|
49
51
|
style?: string;
|
|
50
52
|
component?: ComponentOptions;
|