@lynx-js/web-mainthread-apis 0.15.7 → 0.16.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/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # @lynx-js/web-mainthread-apis
2
2
 
3
+ ## 0.16.0
4
+
5
+ ### Minor Changes
6
+
7
+ - refactor: provide the mts a real globalThis ([#1589](https://github.com/lynx-family/lynx-stack/pull/1589))
8
+
9
+ Before this change, We create a function wrapper and a fake globalThis for Javascript code.
10
+
11
+ This caused some issues.
12
+
13
+ After this change, we will create an iframe for createing an isolated Javascript context.
14
+
15
+ This means the globalThis will be the real one.
16
+
17
+ ### Patch Changes
18
+
19
+ - refactor: add `:not([l-e-name])` at the end of selector for lazy component ([#1622](https://github.com/lynx-family/lynx-stack/pull/1622))
20
+
21
+ - fix: the SystemInfo in bts should be assigned to the globalThis ([#1599](https://github.com/lynx-family/lynx-stack/pull/1599))
22
+
23
+ - 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)]:
24
+ - @lynx-js/web-constants@0.16.0
25
+ - @lynx-js/web-style-transformer@0.16.0
26
+
3
27
  ## 0.15.7
4
28
 
5
29
  ### 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 } 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,21 @@ 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
12
  }
13
13
  export interface MainThreadRuntimeConfig {
14
14
  pageConfig: PageConfig;
15
15
  globalProps: unknown;
16
16
  callbacks: MainThreadRuntimeCallbacks;
17
- styleInfo: StyleInfo;
18
- customSections: LynxTemplate['customSections'];
19
- elementTemplate: LynxTemplate['elementTemplate'];
20
- lepusCode: Record<string, LynxJSModule>;
17
+ lynxTemplate: LynxTemplate;
21
18
  browserConfig: BrowserConfig;
22
19
  tagMap: Record<string, string>;
23
20
  rootDom: Pick<Element, 'append' | 'addEventListener'> & Partial<Pick<ShadowRoot, 'querySelectorAll' | 'cloneNode'>>;
24
21
  jsContext: LynxContextEventTarget;
25
22
  ssrHydrateInfo?: SSRHydrateInfo;
26
23
  ssrHooks?: SSRDehydrateHooks;
24
+ mtsRealm: JSRealm;
25
+ document: Document;
27
26
  }
28
27
  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);
@@ -513,53 +475,22 @@ export function createMainThreadGlobalThis(config) {
513
475
  _SetSourceMapRelease: (errInfo) => release = errInfo?.release,
514
476
  __OnLifecycleEvent: callbacks.__OnLifecycleEvent,
515
477
  __FlushElementTree,
516
- __lynxGlobalBindingValues: lynxGlobalBindingValues,
517
478
  _I18nResourceTranslation: callbacks._I18nResourceTranslation,
518
479
  _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
- },
480
+ renderPage: undefined,
529
481
  };
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;
482
+ Object.assign(mtsRealm.globalWindow, mtsGlobalThis);
483
+ Object.defineProperty(mtsRealm.globalWindow, 'renderPage', {
484
+ get() {
485
+ return mtsGlobalThis.renderPage;
545
486
  },
546
- ownKeys(target) {
547
- return Reflect.ownKeys(target).filter((key) => key !== 'globalThis');
487
+ set(v) {
488
+ mtsGlobalThis.renderPage = v;
489
+ queueMicrotask(callbacks.mainChunkReady);
548
490
  },
491
+ configurable: true,
492
+ enumerable: true,
549
493
  });
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;
494
+ return mtsRealm.globalWindow;
564
495
  }
565
496
  //# 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
@@ -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 } 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, ssrHooks?: SSRDehydrateHooks): {
3
+ startMainThread: (config: StartMainThreadContextConfig, ssrHydrateInfo?: SSRHydrateInfo) => Promise<void>;
4
4
  };
@@ -7,9 +7,9 @@ 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';
10
11
  const initWasmPromise = initWasm();
11
- const moduleCache = {};
12
- export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElement, commitDocument, markTimingInternal, flushMarkTimingInternal, reportError, triggerI18nResourceFallback, initialI18nResources, ssrHooks) {
12
+ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, document, mtsRealm, commitDocument, markTimingInternal, flushMarkTimingInternal, reportError, triggerI18nResourceFallback, initialI18nResources, ssrHooks) {
13
13
  const postTimingFlags = backgroundThreadRpc.createCall(postTimingFlagsEndpoint);
14
14
  const backgroundStart = backgroundThreadRpc.createCall(BackgroundThreadStartEndpoint);
15
15
  const publishEvent = backgroundThreadRpc.createCall(publishEventEndpoint);
@@ -20,46 +20,30 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
20
20
  async function startMainThread(config, ssrHydrateInfo) {
21
21
  let isFp = true;
22
22
  const { globalProps, template, browserConfig, nativeModulesMap, napiModulesMap, tagMap, initI18nResources, } = config;
23
- const { styleInfo, pageConfig, customSections, cardType, lepusCode, elementTemplate, } = template;
23
+ const { styleInfo, pageConfig, customSections, cardType, } = template;
24
24
  markTimingInternal('decode_start');
25
25
  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
26
  const jsContext = new LynxCrossThreadContext({
44
27
  rpc: backgroundThreadRpc,
45
28
  receiveEventEndpoint: dispatchJSContextOnMainThreadEndpoint,
46
29
  sendEventEndpoint: dispatchCoreContextOnBackgroundEndpoint,
47
30
  });
48
31
  const i18nResources = initialI18nResources(initI18nResources);
32
+ const { updateCssOGStyle } = appendStyleElement(styleInfo, pageConfig, rootDom, document, undefined, ssrHydrateInfo);
49
33
  const mtsGlobalThis = createMainThreadGlobalThis({
34
+ lynxTemplate: template,
35
+ mtsRealm,
50
36
  jsContext,
51
37
  tagMap,
52
38
  browserConfig,
53
- customSections,
54
- elementTemplate,
55
39
  globalProps,
56
40
  pageConfig,
57
- styleInfo,
58
- lepusCode: lepusCodeLoaded,
59
41
  rootDom,
60
42
  ssrHydrateInfo,
61
43
  ssrHooks,
44
+ document,
62
45
  callbacks: {
46
+ updateCssOGStyle,
63
47
  mainChunkReady: () => {
64
48
  markTimingInternal('data_processor_start');
65
49
  let initData = config.initData;
@@ -80,7 +64,6 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
80
64
  customSections: Object.fromEntries(Object.entries(customSections).filter(([, value]) => value.type !== 'lazy').map(([k, v]) => [k, v.content])),
81
65
  nativeModulesMap,
82
66
  napiModulesMap,
83
- browserConfig,
84
67
  });
85
68
  if (!ssrHydrateInfo) {
86
69
  mtsGlobalThis.renderPage(initData);
@@ -135,7 +118,6 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
135
118
  markTiming: (a, b) => markTimingInternal(b, a),
136
119
  publishEvent,
137
120
  publicComponentEvent,
138
- createElement,
139
121
  _I18nResourceTranslation: (options) => {
140
122
  const matchedInitI18nResources = i18nResources.data?.find(i => getCacheI18nResourcesKey(i.options)
141
123
  === getCacheI18nResourcesKey(options));
@@ -148,9 +130,8 @@ export function prepareMainThreadAPIs(backgroundThreadRpc, rootDom, createElemen
148
130
  },
149
131
  });
150
132
  markTimingInternal('decode_end');
151
- entry(mtsGlobalThis);
133
+ await mtsRealm.loadScript(template.lepusCode.root);
152
134
  jsContext.__start(); // start the jsContext after the runtime is created
153
- return mtsGlobalThis;
154
135
  }
155
136
  return { startMainThread };
156
137
  }
@@ -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,11 @@ 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
+ };
@@ -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}="${entryName}"]`;
72
+ }
73
+ else {
74
+ suffix = `${suffix}:not([${lynxEntryNameAttribute}])`;
68
75
  }
69
76
  return suffix;
70
77
  }
@@ -116,4 +123,43 @@ 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
+ return { updateCssOGStyle };
164
+ }
119
165
  //# 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.0",
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.0",
29
+ "@lynx-js/web-style-transformer": "0.16.0"
30
30
  }
31
31
  }