@lynx-js/web-mainthread-apis 0.15.7 → 0.16.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @lynx-js/web-mainthread-apis
2
2
 
3
+ ## 0.16.1
4
+
5
+ ### Patch Changes
6
+
7
+ - feat: supports lazy bundle. (This feature requires `@lynx-js/lynx-core >= 0.1.3`) ([#1235](https://github.com/lynx-family/lynx-stack/pull/1235))
8
+
9
+ - Updated dependencies [[`608f375`](https://github.com/lynx-family/lynx-stack/commit/608f375e20732cc4c9f141bfbf9800ba6896100b)]:
10
+ - @lynx-js/web-constants@0.16.1
11
+ - @lynx-js/web-style-transformer@0.16.1
12
+
13
+ ## 0.16.0
14
+
15
+ ### Minor Changes
16
+
17
+ - refactor: provide the mts a real globalThis ([#1589](https://github.com/lynx-family/lynx-stack/pull/1589))
18
+
19
+ Before this change, We create a function wrapper and a fake globalThis for Javascript code.
20
+
21
+ This caused some issues.
22
+
23
+ After this change, we will create an iframe for createing an isolated Javascript context.
24
+
25
+ This means the globalThis will be the real one.
26
+
27
+ ### Patch Changes
28
+
29
+ - refactor: add `:not([l-e-name])` at the end of selector for lazy component ([#1622](https://github.com/lynx-family/lynx-stack/pull/1622))
30
+
31
+ - fix: the SystemInfo in bts should be assigned to the globalThis ([#1599](https://github.com/lynx-family/lynx-stack/pull/1599))
32
+
33
+ - Updated dependencies [[`1a32dd8`](https://github.com/lynx-family/lynx-stack/commit/1a32dd886fe736c95639f67028cf7685377d9769), [`bb53d9a`](https://github.com/lynx-family/lynx-stack/commit/bb53d9a035f607e7c89952098d4ed77877a2e3c1), [`c1f8715`](https://github.com/lynx-family/lynx-stack/commit/c1f8715a81b2e69ff46fc363013626db4468c209)]:
34
+ - @lynx-js/web-constants@0.16.0
35
+ - @lynx-js/web-style-transformer@0.16.0
36
+
3
37
  ## 0.15.7
4
38
 
5
39
  ### Patch Changes
@@ -1,4 +1,4 @@
1
- import { type LynxTemplate, type PageConfig, type StyleInfo, type FlushElementTreeOptions, type Cloneable, type BrowserConfig, type publishEventEndpoint, type publicComponentEventEndpoint, type reportErrorEndpoint, type RpcCallType, type LynxContextEventTarget, type LynxJSModule, type MainThreadGlobalThis, type WebFiberElementImpl, type I18nResourceTranslationOptions, type SSRHydrateInfo, type SSRDehydrateHooks } from '@lynx-js/web-constants';
1
+ import { type LynxTemplate, type PageConfig, type FlushElementTreeOptions, type Cloneable, type BrowserConfig, type publishEventEndpoint, type publicComponentEventEndpoint, type reportErrorEndpoint, type RpcCallType, type LynxContextEventTarget, type MainThreadGlobalThis, type WebFiberElementImpl, type I18nResourceTranslationOptions, type SSRHydrateInfo, type SSRDehydrateHooks, type JSRealm, type QueryComponentPAPI } from '@lynx-js/web-constants';
2
2
  export interface MainThreadRuntimeCallbacks {
3
3
  mainChunkReady: () => void;
4
4
  flushElementTree: (options: FlushElementTreeOptions, timingFlags: string[], exposureChangedElements: WebFiberElementImpl[]) => void;
@@ -7,22 +7,22 @@ export interface MainThreadRuntimeCallbacks {
7
7
  markTiming: (pipelineId: string, timingKey: string) => void;
8
8
  publishEvent: RpcCallType<typeof publishEventEndpoint>;
9
9
  publicComponentEvent: RpcCallType<typeof publicComponentEventEndpoint>;
10
- createElement: (tag: string) => WebFiberElementImpl;
11
10
  _I18nResourceTranslation: (options: I18nResourceTranslationOptions) => unknown | undefined;
11
+ updateCssOGStyle: (uniqueId: number, newClassName: string, cssID: string | null) => void;
12
+ __QueryComponent: QueryComponentPAPI;
12
13
  }
13
14
  export interface MainThreadRuntimeConfig {
14
15
  pageConfig: PageConfig;
15
16
  globalProps: unknown;
16
17
  callbacks: MainThreadRuntimeCallbacks;
17
- styleInfo: StyleInfo;
18
- customSections: LynxTemplate['customSections'];
19
- elementTemplate: LynxTemplate['elementTemplate'];
20
- lepusCode: Record<string, LynxJSModule>;
18
+ lynxTemplate: LynxTemplate;
21
19
  browserConfig: BrowserConfig;
22
20
  tagMap: Record<string, string>;
23
21
  rootDom: Pick<Element, 'append' | 'addEventListener'> & Partial<Pick<ShadowRoot, 'querySelectorAll' | 'cloneNode'>>;
24
22
  jsContext: LynxContextEventTarget;
25
23
  ssrHydrateInfo?: SSRHydrateInfo;
26
24
  ssrHooks?: SSRDehydrateHooks;
25
+ mtsRealm: JSRealm;
26
+ document: Document;
27
27
  }
28
28
  export declare function createMainThreadGlobalThis(config: MainThreadRuntimeConfig): MainThreadGlobalThis;
@@ -1,13 +1,10 @@
1
1
  // Copyright 2023 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
- import { lynxUniqueIdAttribute, systemInfo, parentComponentUniqueIdAttribute, componentIdAttribute, LynxEventNameToW3cByTagName, LynxEventNameToW3cCommon, lynxTagAttribute, W3cEventNameToLynx, cssIdAttribute, lynxDefaultDisplayLinearAttribute, __lynx_timing_flag, lynxDisposedAttribute, globalDisallowedVars, } from '@lynx-js/web-constants';
5
- import { globalMuteableVars } from '@lynx-js/web-constants';
4
+ import { lynxUniqueIdAttribute, systemInfo, parentComponentUniqueIdAttribute, componentIdAttribute, LynxEventNameToW3cByTagName, LynxEventNameToW3cCommon, lynxTagAttribute, W3cEventNameToLynx, cssIdAttribute, lynxDefaultDisplayLinearAttribute, __lynx_timing_flag, lynxDisposedAttribute, } from '@lynx-js/web-constants';
6
5
  import { createMainThreadLynx } from './createMainThreadLynx.js';
7
- import { flattenStyleInfo, genCssContent, genCssOGInfo, transformToWebCss, } from './utils/processStyleInfo.js';
8
6
  import { __AddClass, __AddConfig, __AddDataset, __AddInlineStyle, __AppendElement, __ElementIsEqual, __FirstElement, __GetAttributes, __GetChildren, __GetClasses, __GetComponentID, __GetDataByKey, __GetDataset, __GetElementConfig, __GetElementUniqueID, __GetID, __GetParent, __GetTag, __GetTemplateParts, __InsertElementBefore, __LastElement, __MarkPartElement, __MarkTemplateElement, __NextElement, __RemoveElement, __ReplaceElement, __ReplaceElements, __SetClasses, __SetConfig, __SetCSSId, __SetDataset, __SetID, __SetInlineStyles, __UpdateComponentID, __UpdateComponentInfo, __GetAttributeByName, } from './pureElementPAPIs.js';
9
7
  import { createCrossThreadEvent } from './utils/createCrossThreadEvent.js';
10
- import { decodeCssOG } from './utils/decodeCssOG.js';
11
8
  const exposureRelatedAttributes = new Set([
12
9
  'exposure-id',
13
10
  'exposure-area',
@@ -22,54 +19,14 @@ const exposureRelatedAttributes = new Set([
22
19
  ]);
23
20
  export function createMainThreadGlobalThis(config) {
24
21
  let timingFlags = [];
25
- let renderPage;
26
- const { callbacks, tagMap, pageConfig, lepusCode, rootDom, globalProps, styleInfo, ssrHydrateInfo, ssrHooks, } = config;
22
+ const { callbacks, tagMap, pageConfig, lynxTemplate, rootDom, globalProps, ssrHydrateInfo, ssrHooks, mtsRealm, document, } = config;
23
+ const { elementTemplate, lepusCode } = lynxTemplate;
27
24
  const lynxUniqueIdToElement = ssrHydrateInfo?.lynxUniqueIdToElement ?? [];
28
- const lynxUniqueIdToStyleRulesIndex = ssrHydrateInfo?.lynxUniqueIdToStyleRulesIndex ?? [];
29
25
  const elementToRuntimeInfoMap = new WeakMap();
30
26
  let pageElement = lynxUniqueIdToElement[1]
31
27
  ?.deref();
32
28
  let uniqueIdInc = lynxUniqueIdToElement.length || 1;
33
- /**
34
- * for "update" the globalThis.val in the main thread
35
- */
36
- const varsUpdateHandlers = [];
37
- const lynxGlobalBindingValues = {};
38
29
  const exposureChangedElements = new Set();
39
- /**
40
- * now create the style content
41
- * 1. flatten the styleInfo
42
- * 2. transform the styleInfo to web css
43
- * 3. generate the css in js info
44
- * 4. create the style element
45
- * 5. append the style element to the root dom
46
- */
47
- flattenStyleInfo(styleInfo, pageConfig.enableCSSSelector);
48
- transformToWebCss(styleInfo);
49
- const cssOGInfo = pageConfig.enableCSSSelector
50
- ? {}
51
- : genCssOGInfo(styleInfo);
52
- let cardStyleElement;
53
- if (ssrHydrateInfo?.cardStyleElement) {
54
- cardStyleElement = ssrHydrateInfo.cardStyleElement;
55
- }
56
- else {
57
- cardStyleElement = callbacks.createElement('style');
58
- cardStyleElement.innerHTML = genCssContent(styleInfo, pageConfig);
59
- rootDom.append(cardStyleElement);
60
- }
61
- const cardStyleElementSheet = cardStyleElement.sheet;
62
- const updateCssOGStyle = (uniqueId, newStyles) => {
63
- if (lynxUniqueIdToStyleRulesIndex[uniqueId] !== undefined) {
64
- const rule = cardStyleElementSheet
65
- .cssRules[lynxUniqueIdToStyleRulesIndex[uniqueId]];
66
- rule.style.cssText = newStyles;
67
- }
68
- else {
69
- const index = cardStyleElementSheet.insertRule(`[${lynxUniqueIdAttribute}="${uniqueId}"]{${newStyles}}`, cardStyleElementSheet.cssRules.length);
70
- lynxUniqueIdToStyleRulesIndex[uniqueId] = index;
71
- }
72
- };
73
30
  const commonHandler = (event) => {
74
31
  if (!event.currentTarget) {
75
32
  return;
@@ -107,7 +64,8 @@ export function createMainThreadGlobalThis(config) {
107
64
  crossThreadEvent.currentTarget
108
65
  .elementRefptr = event.currentTarget;
109
66
  }
110
- mtsGlobalThis.runWorklet?.(hname.value, [crossThreadEvent]);
67
+ mtsRealm.globalWindow
68
+ .runWorklet?.(hname.value, [crossThreadEvent]);
111
69
  }
112
70
  }
113
71
  return false;
@@ -227,7 +185,7 @@ export function createMainThreadGlobalThis(config) {
227
185
  const __CreateElement = (tag, parentComponentUniqueId) => {
228
186
  const uniqueId = uniqueIdInc++;
229
187
  const htmlTag = tagMap[tag] ?? tag;
230
- const element = callbacks.createElement(htmlTag);
188
+ const element = document.createElement(htmlTag);
231
189
  lynxUniqueIdToElement[uniqueId] = new WeakRef(element);
232
190
  const parentComponentCssID = lynxUniqueIdToElement[parentComponentUniqueId]
233
191
  ?.deref()?.getAttribute(cssIdAttribute);
@@ -326,9 +284,11 @@ export function createMainThreadGlobalThis(config) {
326
284
  elementToRuntimeInfoMap.set(element, runtimeInfo);
327
285
  };
328
286
  const __SwapElement = (childA, childB) => {
329
- const temp = callbacks.createElement('div');
287
+ const temp = document.createElement('div');
288
+ // @ts-expect-error fixme
330
289
  childA.replaceWith(temp);
331
290
  childB.replaceWith(childA);
291
+ // @ts-expect-error fixme
332
292
  temp.replaceWith(childB);
333
293
  };
334
294
  const __SetCSSIdForCSSOG = (elements, cssId) => {
@@ -342,22 +302,24 @@ export function createMainThreadGlobalThis(config) {
342
302
  const newClassName = ((element.getAttribute('class') ?? '') + ' ' + className)
343
303
  .trim();
344
304
  element.setAttribute('class', newClassName);
345
- const newStyleStr = decodeCssOG(newClassName, cssOGInfo, element.getAttribute(cssIdAttribute));
346
- updateCssOGStyle(Number(element.getAttribute(lynxUniqueIdAttribute)), newStyleStr);
305
+ const cssId = element.getAttribute(cssIdAttribute);
306
+ const uniqueId = Number(element.getAttribute(lynxUniqueIdAttribute));
307
+ callbacks.updateCssOGStyle(uniqueId, newClassName, cssId);
347
308
  };
348
309
  const __SetClassesForCSSOG = (element, classNames) => {
349
310
  __SetClasses(element, classNames);
350
- const newStyleStr = decodeCssOG(classNames ?? '', cssOGInfo, element.getAttribute(cssIdAttribute));
351
- updateCssOGStyle(Number(element.getAttribute(lynxUniqueIdAttribute)), newStyleStr ?? '');
311
+ const cssId = element.getAttribute(cssIdAttribute);
312
+ const uniqueId = Number(element.getAttribute(lynxUniqueIdAttribute));
313
+ callbacks.updateCssOGStyle(uniqueId, classNames ?? '', cssId);
352
314
  };
353
315
  const __LoadLepusChunk = (path) => {
354
- const lepusModule = lepusCode[`${path}`];
355
- if (lepusModule) {
356
- const entry = lepusModule.exports;
357
- entry?.(mtsGlobalThis);
316
+ try {
317
+ path = lepusCode?.[path] ?? path;
318
+ mtsRealm.loadScriptSync(path);
358
319
  return true;
359
320
  }
360
- else {
321
+ catch (e) {
322
+ console.error(`failed to load lepus chunk ${path}`, e);
361
323
  return false;
362
324
  }
363
325
  };
@@ -412,7 +374,7 @@ export function createMainThreadGlobalThis(config) {
412
374
  }
413
375
  };
414
376
  const __ElementFromBinary = (templateId, parentComponentUniId) => {
415
- const elementTemplateData = config.elementTemplate[templateId];
377
+ const elementTemplateData = elementTemplate[templateId];
416
378
  if (elementTemplateData) {
417
379
  let clonedElements;
418
380
  if (templateIdToTemplate[templateId]) {
@@ -421,7 +383,7 @@ export function createMainThreadGlobalThis(config) {
421
383
  else {
422
384
  clonedElements = elementTemplateData.map(data => createElementForElementTemplateData(data, parentComponentUniId));
423
385
  if (rootDom.cloneNode) {
424
- const template = callbacks.createElement('template');
386
+ const template = document.createElement('template');
425
387
  template.content.append(...clonedElements);
426
388
  templateIdToTemplate[templateId] = template;
427
389
  rootDom.append(template);
@@ -507,59 +469,29 @@ export function createMainThreadGlobalThis(config) {
507
469
  __LoadLepusChunk,
508
470
  __GetPageElement,
509
471
  __globalProps: globalProps,
472
+ __QueryComponent: callbacks.__QueryComponent,
510
473
  SystemInfo,
511
474
  lynx: createMainThreadLynx(config, SystemInfo),
512
475
  _ReportError: (err, _) => callbacks._ReportError(err, _, release),
513
476
  _SetSourceMapRelease: (errInfo) => release = errInfo?.release,
514
477
  __OnLifecycleEvent: callbacks.__OnLifecycleEvent,
515
478
  __FlushElementTree,
516
- __lynxGlobalBindingValues: lynxGlobalBindingValues,
517
479
  _I18nResourceTranslation: callbacks._I18nResourceTranslation,
518
480
  _AddEventListener: () => { },
519
- set _updateVars(handler) {
520
- varsUpdateHandlers.push(handler);
521
- },
522
- set renderPage(foo) {
523
- renderPage = foo;
524
- queueMicrotask(callbacks.mainChunkReady);
525
- },
526
- get renderPage() {
527
- return renderPage;
528
- },
481
+ renderPage: undefined,
529
482
  };
530
- mtsGlobalThis.globalThis = new Proxy(mtsGlobalThis, {
531
- get: (target, prop) => {
532
- if (typeof prop === 'string' && globalDisallowedVars.includes(prop)) {
533
- return undefined;
534
- }
535
- if (prop === 'globalThis') {
536
- return target;
537
- }
538
- // @ts-expect-error
539
- return target[prop] ?? globalThis[prop];
540
- },
541
- set: (target, prop, value) => {
542
- // @ts-expect-error
543
- target[prop] = value;
544
- return true;
483
+ Object.assign(mtsRealm.globalWindow, mtsGlobalThis);
484
+ Object.defineProperty(mtsRealm.globalWindow, 'renderPage', {
485
+ get() {
486
+ return mtsGlobalThis.renderPage;
545
487
  },
546
- ownKeys(target) {
547
- return Reflect.ownKeys(target).filter((key) => key !== 'globalThis');
488
+ set(v) {
489
+ mtsGlobalThis.renderPage = v;
490
+ queueMicrotask(callbacks.mainChunkReady);
548
491
  },
492
+ configurable: true,
493
+ enumerable: true,
549
494
  });
550
- for (const nm of globalMuteableVars) {
551
- Object.defineProperty(mtsGlobalThis, nm, {
552
- get: () => {
553
- return lynxGlobalBindingValues[nm];
554
- },
555
- set: (v) => {
556
- lynxGlobalBindingValues[nm] = v;
557
- for (const handler of varsUpdateHandlers) {
558
- handler();
559
- }
560
- },
561
- });
562
- }
563
- return mtsGlobalThis;
495
+ return mtsRealm.globalWindow;
564
496
  }
565
497
  //# sourceMappingURL=createMainThreadGlobalThis.js.map
@@ -1,21 +1,31 @@
1
1
  import {} from './createMainThreadGlobalThis.js';
2
2
  export function createMainThreadLynx(config, SystemInfo) {
3
+ const requestAnimationFrameBrowserImpl = requestAnimationFrame;
4
+ const cancelAnimationFrameBrowserImpl = cancelAnimationFrame;
5
+ const setTimeoutBrowserImpl = setTimeout;
6
+ const clearTimeoutBrowserImpl = clearTimeout;
7
+ const setIntervalBrowserImpl = setInterval;
8
+ const clearIntervalBrowserImpl = clearInterval;
3
9
  return {
4
10
  getJSContext() {
5
11
  return config.jsContext;
6
12
  },
7
13
  requestAnimationFrame(cb) {
8
- return requestAnimationFrame(cb);
14
+ return requestAnimationFrameBrowserImpl(cb);
9
15
  },
10
16
  cancelAnimationFrame(handler) {
11
- return cancelAnimationFrame(handler);
17
+ return cancelAnimationFrameBrowserImpl(handler);
12
18
  },
13
19
  __globalProps: config.globalProps,
14
20
  getCustomSectionSync(key) {
15
- return config.customSections[key]?.content;
21
+ return config.lynxTemplate.customSections[key]?.content;
16
22
  },
17
23
  markPipelineTiming: config.callbacks.markTiming,
18
24
  SystemInfo,
25
+ setTimeout: setTimeoutBrowserImpl,
26
+ clearTimeout: clearTimeoutBrowserImpl,
27
+ setInterval: setIntervalBrowserImpl,
28
+ clearInterval: clearIntervalBrowserImpl,
19
29
  };
20
30
  }
21
31
  //# sourceMappingURL=createMainThreadLynx.js.map
@@ -0,0 +1,4 @@
1
+ import { type JSRealm, type LynxCrossThreadContext, type MainThreadGlobalThis, type QueryComponentPAPI, type Rpc, type StyleInfo, type TemplateLoader } from '@lynx-js/web-constants';
2
+ export declare function createQueryComponent(loadTemplate: TemplateLoader, updateLazyComponentStyle: (styleInfo: StyleInfo, entryName: string) => void, backgroundThreadRpc: Rpc, mtsGlobalThisRef: {
3
+ mtsGlobalThis: MainThreadGlobalThis;
4
+ }, jsContext: LynxCrossThreadContext, mtsRealm: JSRealm): QueryComponentPAPI;
@@ -0,0 +1,48 @@
1
+ import { queryComponentEndpoint, updateBTSTemplateCacheEndpoint, } from '@lynx-js/web-constants';
2
+ export function createQueryComponent(loadTemplate, updateLazyComponentStyle, backgroundThreadRpc, mtsGlobalThisRef, jsContext, mtsRealm) {
3
+ const updateBTSTemplateCache = backgroundThreadRpc.createCall(updateBTSTemplateCacheEndpoint);
4
+ const __QueryComponentImpl = (url, callback) => {
5
+ loadTemplate(url).then(async (template) => {
6
+ const updateBTSCachePromise = updateBTSTemplateCache(url, template);
7
+ let lepusRootChunkExport = await mtsRealm.loadScript(template.lepusCode.root);
8
+ if (mtsGlobalThisRef.mtsGlobalThis.processEvalResult) {
9
+ lepusRootChunkExport = mtsGlobalThisRef.mtsGlobalThis.processEvalResult(lepusRootChunkExport, url);
10
+ }
11
+ updateLazyComponentStyle(template.styleInfo, url);
12
+ await updateBTSCachePromise;
13
+ jsContext.dispatchEvent({
14
+ type: '__OnDynamicJSSourcePrepared',
15
+ data: url,
16
+ });
17
+ callback?.({
18
+ code: 0,
19
+ data: {
20
+ url,
21
+ evalResult: lepusRootChunkExport,
22
+ },
23
+ });
24
+ }).catch((error) => {
25
+ console.error(`lynx web: lazy bundle load failed:`, error);
26
+ callback?.({
27
+ code: -1,
28
+ data: undefined,
29
+ });
30
+ });
31
+ return null;
32
+ };
33
+ backgroundThreadRpc.registerHandler(queryComponentEndpoint, (url) => {
34
+ const ret = new Promise(resolve => {
35
+ __QueryComponentImpl(url, (result) => {
36
+ resolve({
37
+ code: result.code,
38
+ detail: {
39
+ schema: url,
40
+ },
41
+ });
42
+ });
43
+ });
44
+ return ret;
45
+ });
46
+ return __QueryComponentImpl;
47
+ }
48
+ //# sourceMappingURL=createQueryComponent.js.map
@@ -1,4 +1,4 @@
1
- import { type Rpc, type StartMainThreadContextConfig, type RpcCallType, type reportErrorEndpoint, type MainThreadGlobalThis, type I18nResourceTranslationOptions, type InitI18nResources, type I18nResources, type SSRHydrateInfo, type SSRDehydrateHooks } from '@lynx-js/web-constants';
2
- export declare function prepareMainThreadAPIs(backgroundThreadRpc: Rpc, rootDom: Document | ShadowRoot, createElement: Document['createElement'], commitDocument: (exposureChangedElements: HTMLElement[]) => Promise<void> | void, markTimingInternal: (timingKey: string, pipelineId?: string) => void, flushMarkTimingInternal: () => void, reportError: RpcCallType<typeof reportErrorEndpoint>, triggerI18nResourceFallback: (options: I18nResourceTranslationOptions) => void, initialI18nResources: (data: InitI18nResources) => I18nResources, ssrHooks?: SSRDehydrateHooks): {
3
- startMainThread: (config: StartMainThreadContextConfig, ssrHydrateInfo?: SSRHydrateInfo) => Promise<MainThreadGlobalThis>;
1
+ import { type Rpc, type StartMainThreadContextConfig, type RpcCallType, type reportErrorEndpoint, type I18nResourceTranslationOptions, type InitI18nResources, type I18nResources, type SSRHydrateInfo, type SSRDehydrateHooks, type JSRealm, type TemplateLoader } from '@lynx-js/web-constants';
2
+ export declare function prepareMainThreadAPIs(backgroundThreadRpc: Rpc, rootDom: Document | ShadowRoot, document: Document, mtsRealm: JSRealm, commitDocument: (exposureChangedElements: HTMLElement[]) => Promise<void> | void, markTimingInternal: (timingKey: string, pipelineId?: string) => void, flushMarkTimingInternal: () => void, reportError: RpcCallType<typeof reportErrorEndpoint>, triggerI18nResourceFallback: (options: I18nResourceTranslationOptions) => void, initialI18nResources: (data: InitI18nResources) => I18nResources, loadTemplate: TemplateLoader, ssrHooks?: SSRDehydrateHooks): {
3
+ startMainThread: (config: StartMainThreadContextConfig, ssrHydrateInfo?: SSRHydrateInfo) => Promise<void>;
4
4
  };
@@ -7,9 +7,10 @@ import { registerGetCustomSectionHandler } from './crossThreadHandlers/registerG
7
7
  import { createMainThreadGlobalThis } from './createMainThreadGlobalThis.js';
8
8
  import { createExposureService } from './utils/createExposureService.js';
9
9
  import { initWasm } from '@lynx-js/web-style-transformer';
10
+ import { appendStyleElement } from './utils/processStyleInfo.js';
11
+ import { createQueryComponent } from './crossThreadHandlers/createQueryComponent.js';
10
12
  const initWasmPromise = initWasm();
11
- const moduleCache = {};
12
- export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElement, commitDocument, markTimingInternal, flushMarkTimingInternal, reportError, triggerI18nResourceFallback, initialI18nResources, ssrHooks) {
13
+ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, document, mtsRealm, commitDocument, markTimingInternal, flushMarkTimingInternal, reportError, triggerI18nResourceFallback, initialI18nResources, loadTemplate, ssrHooks) {
13
14
  const postTimingFlags = backgroundThreadRpc.createCall(postTimingFlagsEndpoint);
14
15
  const backgroundStart = backgroundThreadRpc.createCall(BackgroundThreadStartEndpoint);
15
16
  const publishEvent = backgroundThreadRpc.createCall(publishEventEndpoint);
@@ -20,46 +21,34 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
20
21
  async function startMainThread(config, ssrHydrateInfo) {
21
22
  let isFp = true;
22
23
  const { globalProps, template, browserConfig, nativeModulesMap, napiModulesMap, tagMap, initI18nResources, } = config;
23
- const { styleInfo, pageConfig, customSections, cardType, lepusCode, elementTemplate, } = template;
24
+ const { styleInfo, pageConfig, customSections, cardType, } = template;
24
25
  markTimingInternal('decode_start');
25
26
  await initWasmPromise;
26
- const lepusCodeEntries = await Promise.all(Object.entries(lepusCode).map(async ([name, url]) => {
27
- const cachedModule = moduleCache[url];
28
- if (cachedModule) {
29
- return [name, cachedModule];
30
- }
31
- else {
32
- const { default: evaluateModule } = await import(
33
- /* webpackIgnore: true */ url);
34
- const module = {
35
- exports: evaluateModule,
36
- };
37
- moduleCache[url] = module;
38
- return [name, module];
39
- }
40
- }));
41
- const lepusCodeLoaded = Object.fromEntries(lepusCodeEntries);
42
- const entry = lepusCodeLoaded['root'].exports;
43
27
  const jsContext = new LynxCrossThreadContext({
44
28
  rpc: backgroundThreadRpc,
45
29
  receiveEventEndpoint: dispatchJSContextOnMainThreadEndpoint,
46
30
  sendEventEndpoint: dispatchCoreContextOnBackgroundEndpoint,
47
31
  });
48
32
  const i18nResources = initialI18nResources(initI18nResources);
33
+ const { updateCssOGStyle, updateLazyComponentStyle } = appendStyleElement(styleInfo, pageConfig, rootDom, document, undefined, ssrHydrateInfo);
34
+ const mtsGlobalThisRef = {
35
+ mtsGlobalThis: undefined,
36
+ };
37
+ const __QueryComponent = createQueryComponent(loadTemplate, updateLazyComponentStyle, backgroundThreadRpc, mtsGlobalThisRef, jsContext, mtsRealm);
49
38
  const mtsGlobalThis = createMainThreadGlobalThis({
39
+ lynxTemplate: template,
40
+ mtsRealm,
50
41
  jsContext,
51
42
  tagMap,
52
43
  browserConfig,
53
- customSections,
54
- elementTemplate,
55
44
  globalProps,
56
45
  pageConfig,
57
- styleInfo,
58
- lepusCode: lepusCodeLoaded,
59
46
  rootDom,
60
47
  ssrHydrateInfo,
61
48
  ssrHooks,
49
+ document,
62
50
  callbacks: {
51
+ updateCssOGStyle,
63
52
  mainChunkReady: () => {
64
53
  markTimingInternal('data_processor_start');
65
54
  let initData = config.initData;
@@ -80,7 +69,6 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
80
69
  customSections: Object.fromEntries(Object.entries(customSections).filter(([, value]) => value.type !== 'lazy').map(([k, v]) => [k, v.content])),
81
70
  nativeModulesMap,
82
71
  napiModulesMap,
83
- browserConfig,
84
72
  });
85
73
  if (!ssrHydrateInfo) {
86
74
  mtsGlobalThis.renderPage(initData);
@@ -135,7 +123,6 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
135
123
  markTiming: (a, b) => markTimingInternal(b, a),
136
124
  publishEvent,
137
125
  publicComponentEvent,
138
- createElement,
139
126
  _I18nResourceTranslation: (options) => {
140
127
  const matchedInitI18nResources = i18nResources.data?.find(i => getCacheI18nResourcesKey(i.options)
141
128
  === getCacheI18nResourcesKey(options));
@@ -145,12 +132,13 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
145
132
  }
146
133
  return triggerI18nResourceFallback(options);
147
134
  },
135
+ __QueryComponent,
148
136
  },
149
137
  });
138
+ mtsGlobalThisRef.mtsGlobalThis = mtsGlobalThis;
150
139
  markTimingInternal('decode_end');
151
- entry(mtsGlobalThis);
140
+ await mtsRealm.loadScript(template.lepusCode.root);
152
141
  jsContext.__start(); // start the jsContext after the runtime is created
153
- return mtsGlobalThis;
154
142
  }
155
143
  return { startMainThread };
156
144
  }
@@ -1,7 +1,7 @@
1
1
  // Copyright 2023 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
- import { componentIdAttribute, cssIdAttribute, lynxComponentConfigAttribute, lynxDatasetAttribute, lynxElementTemplateMarkerAttribute, lynxPartIdAttribute, lynxTagAttribute, lynxUniqueIdAttribute, } from '@lynx-js/web-constants';
4
+ import { componentIdAttribute, cssIdAttribute, lynxComponentConfigAttribute, lynxDatasetAttribute, lynxElementTemplateMarkerAttribute, lynxEntryNameAttribute, lynxPartIdAttribute, lynxTagAttribute, lynxUniqueIdAttribute, } from '@lynx-js/web-constants';
5
5
  import { queryCSSProperty } from './style/cssPropertyMap.js';
6
6
  import { transformInlineStyleString, transformParsedStyles, } from './style/transformInlineStyle.js';
7
7
  import hyphenateStyleName from 'hyphenate-style-name';
@@ -92,9 +92,10 @@ export const __UpdateComponentInfo = /*#__PURE__*/ (element, params) => {
92
92
  && element.setAttribute(cssIdAttribute, params.cssID + '');
93
93
  params.name !== undefined && element.setAttribute('name', params.name);
94
94
  };
95
- export const __SetCSSId = /*#__PURE__*/ (elements, cssId) => {
95
+ export const __SetCSSId = /*#__PURE__*/ (elements, cssId, entryName) => {
96
96
  for (const element of elements) {
97
97
  element.setAttribute(cssIdAttribute, cssId + '');
98
+ entryName && element.setAttribute(lynxEntryNameAttribute, entryName);
98
99
  }
99
100
  };
100
101
  export const __SetClasses = /*#__PURE__*/ (element, classname) => {
@@ -1,4 +1,4 @@
1
- import { type StyleInfo, type CssOGInfo, type PageConfig } from '@lynx-js/web-constants';
1
+ import { type StyleInfo, type CssOGInfo, type PageConfig, type SSRHydrateInfo } from '@lynx-js/web-constants';
2
2
  export declare function flattenStyleInfo(styleInfo: StyleInfo, enableCSSSelector: boolean): void;
3
3
  /**
4
4
  * apply the lynx css -> web css transformation
@@ -7,8 +7,12 @@ export declare function transformToWebCss(styleInfo: StyleInfo): void;
7
7
  /**
8
8
  * generate those styles applied by <style>...</style>
9
9
  */
10
- export declare function genCssContent(styleInfo: StyleInfo, pageConfig: PageConfig): string;
10
+ export declare function genCssContent(styleInfo: StyleInfo, pageConfig: PageConfig, entryName?: string): string;
11
11
  /**
12
12
  * generate the css-in-js data
13
13
  */
14
14
  export declare function genCssOGInfo(styleInfo: StyleInfo): CssOGInfo;
15
+ export declare function appendStyleElement(styleInfo: StyleInfo, pageConfig: PageConfig, rootDom: Node, document: Document, entryName?: string, ssrHydrateInfo?: SSRHydrateInfo): {
16
+ updateCssOGStyle: (uniqueId: number, newClassName: string, cssID: string | null) => void;
17
+ updateLazyComponentStyle: (styleInfo: StyleInfo, entryName: string) => void;
18
+ };
@@ -1,8 +1,9 @@
1
1
  // Copyright 2023 The Lynx Authors. All rights reserved.
2
2
  // Licensed under the Apache License Version 2.0 that can be found in the
3
3
  // LICENSE file in the root directory of this source tree.
4
- import { cssIdAttribute, lynxTagAttribute, } from '@lynx-js/web-constants';
4
+ import { cssIdAttribute, lynxTagAttribute, lynxUniqueIdAttribute, lynxEntryNameAttribute, } from '@lynx-js/web-constants';
5
5
  import { transformParsedStyles } from './tokenizer.js';
6
+ import { decodeCssOG } from './decodeCssOG.js';
6
7
  export function flattenStyleInfo(styleInfo, enableCSSSelector) {
7
8
  function flattenOneStyleInfo(cssId) {
8
9
  const oneInfo = styleInfo[cssId];
@@ -51,20 +52,26 @@ export function transformToWebCss(styleInfo) {
51
52
  /**
52
53
  * generate those styles applied by <style>...</style>
53
54
  */
54
- export function genCssContent(styleInfo, pageConfig) {
55
+ export function genCssContent(styleInfo, pageConfig, entryName) {
55
56
  function getExtraSelectors(cssId) {
56
- let suffix = '';
57
+ let suffix;
57
58
  if (!pageConfig.enableRemoveCSSScope) {
58
59
  if (cssId !== undefined) {
59
- suffix += `[${cssIdAttribute}="${cssId}"]`;
60
+ suffix = `[${cssIdAttribute}="${cssId}"]`;
60
61
  }
61
62
  else {
62
63
  // To make sure the Specificity correct
63
- suffix += `[${lynxTagAttribute}]`;
64
+ suffix = `[${lynxTagAttribute}]`;
64
65
  }
65
66
  }
66
67
  else {
67
- suffix += `[${lynxTagAttribute}]`;
68
+ suffix = `[${lynxTagAttribute}]`;
69
+ }
70
+ if (entryName) {
71
+ suffix = `${suffix}[${lynxEntryNameAttribute}=${JSON.stringify(entryName)}]`;
72
+ }
73
+ else {
74
+ suffix = `${suffix}:not([${lynxEntryNameAttribute}])`;
68
75
  }
69
76
  return suffix;
70
77
  }
@@ -116,4 +123,49 @@ export function genCssOGInfo(styleInfo) {
116
123
  return [cssId, oneCssOGInfo];
117
124
  }));
118
125
  }
126
+ export function appendStyleElement(styleInfo, pageConfig, rootDom, document, entryName, ssrHydrateInfo) {
127
+ const lynxUniqueIdToStyleRulesIndex = ssrHydrateInfo?.lynxUniqueIdToStyleRulesIndex ?? [];
128
+ /**
129
+ * now create the style content
130
+ * 1. flatten the styleInfo
131
+ * 2. transform the styleInfo to web css
132
+ * 3. generate the css in js info
133
+ * 4. create the style element
134
+ * 5. append the style element to the root dom
135
+ */
136
+ flattenStyleInfo(styleInfo, pageConfig.enableCSSSelector);
137
+ transformToWebCss(styleInfo);
138
+ const cssOGInfo = pageConfig.enableCSSSelector
139
+ ? {}
140
+ : genCssOGInfo(styleInfo);
141
+ let cardStyleElement;
142
+ if (ssrHydrateInfo?.cardStyleElement) {
143
+ cardStyleElement = ssrHydrateInfo.cardStyleElement;
144
+ }
145
+ else {
146
+ cardStyleElement = document.createElement('style');
147
+ cardStyleElement.textContent = genCssContent(styleInfo, pageConfig, entryName);
148
+ rootDom.appendChild(cardStyleElement);
149
+ }
150
+ const cardStyleElementSheet = cardStyleElement.sheet;
151
+ const updateCssOGStyle = (uniqueId, newClassName, cssID) => {
152
+ const newStyles = decodeCssOG(newClassName, cssOGInfo, cssID);
153
+ if (lynxUniqueIdToStyleRulesIndex[uniqueId] !== undefined) {
154
+ const rule = cardStyleElementSheet
155
+ .cssRules[lynxUniqueIdToStyleRulesIndex[uniqueId]];
156
+ rule.style.cssText = newStyles;
157
+ }
158
+ else {
159
+ const index = cardStyleElementSheet.insertRule(`[${lynxUniqueIdAttribute}="${uniqueId}"]{${newStyles}}`, cardStyleElementSheet.cssRules.length);
160
+ lynxUniqueIdToStyleRulesIndex[uniqueId] = index;
161
+ }
162
+ };
163
+ const updateLazyComponentStyle = (styleInfo, entryName) => {
164
+ flattenStyleInfo(styleInfo, pageConfig.enableCSSSelector);
165
+ transformToWebCss(styleInfo);
166
+ const newStyleSheet = genCssContent(styleInfo, pageConfig, entryName);
167
+ cardStyleElement.textContent += newStyleSheet;
168
+ };
169
+ return { updateCssOGStyle, updateLazyComponentStyle };
170
+ }
119
171
  //# sourceMappingURL=processStyleInfo.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lynx-js/web-mainthread-apis",
3
- "version": "0.15.7",
3
+ "version": "0.16.1",
4
4
  "private": false,
5
5
  "description": "",
6
6
  "keywords": [],
@@ -25,7 +25,7 @@
25
25
  ],
26
26
  "dependencies": {
27
27
  "hyphenate-style-name": "^1.1.0",
28
- "@lynx-js/web-constants": "0.15.7",
29
- "@lynx-js/web-style-transformer": "0.15.7"
28
+ "@lynx-js/web-constants": "0.16.1",
29
+ "@lynx-js/web-style-transformer": "0.16.1"
30
30
  }
31
31
  }