piral-lazy 1.0.0-pre.2085 → 1.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2019 - 2021 smapiot
3
+ Copyright (c) 2019 - 2023 smapiot
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- [![Piral Logo](https://github.com/smapiot/piral/raw/master/docs/assets/logo.png)](https://piral.io)
1
+ [![Piral Logo](https://github.com/smapiot/piral/raw/main/docs/assets/logo.png)](https://piral.io)
2
2
 
3
- # [Piral Lazy](https://piral.io) · [![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/smapiot/piral/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/piral-lazy.svg?style=flat)](https://www.npmjs.com/package/piral-lazy) [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://jestjs.io) [![Gitter Chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/piral-io/community)
3
+ # [Piral Lazy](https://piral.io) · [![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/smapiot/piral/blob/main/LICENSE) [![npm version](https://img.shields.io/npm/v/piral-lazy.svg?style=flat)](https://www.npmjs.com/package/piral-lazy) [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://jestjs.io) [![Gitter Chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/piral-io/community)
4
4
 
5
5
  This is a plugin that only has a peer dependency to `piral-core`. What `piral-lazy` brings to the table is a set of Pilet API extensions that can be used with `piral` or `piral-core`.
6
6
 
@@ -8,6 +8,19 @@ The set includes a `fromLazy` shortcut.
8
8
 
9
9
  By default, these API extensions are not integrated in `piral`, so you'd need to add them to your Piral instance. We recommend integrating `piral-lazy` when you think about an opt-in for *any* third-party framework (e.g., `piral-vue`, `piral-ng`, ...).
10
10
 
11
+ ## Why and When
12
+
13
+ Lazy loading of data or other dependencies can be crucial in more complex scenarios. It should not be necessary to include everything in one load to bring a pilet or components of it to live.
14
+
15
+ `piral-lazy` allows defining generic dependencies that will be loaded *before* loading/using a component. The provided helpers which are exposed via the pilet API give you the power to
16
+
17
+ 1. define new dependencies (given by a unique name and a loader function) and
18
+ 2. rely on defined dependencies before actually loading/trying to render a component.
19
+
20
+ If your pilets use lazy loading in some way then `piral-lazy` may be the right choice. Also, if your pilets are too large and could benefit from further resource sharing and lazy loading then this plugin could be helpful. `piral-lazy` remains framework agnostic and thus works beyond React.
21
+
22
+ Alternative: Just define/use what is there out of the box. By using `React.lazy` together with bundle splitting most of the things may be already properly transported. Remember that you could also lazy load context that provide your dependencies - thus making `React.lazy` a single solution (if your framework is "React").
23
+
11
24
  ## Documentation
12
25
 
13
26
  The following functions are brought to the Pilet API.
@@ -0,0 +1,3 @@
1
+ import { PiralPlugin } from 'piral-core';
2
+ import { PiletLazyApi } from './types';
3
+ export declare function createLazyApi(): PiralPlugin<PiletLazyApi>;
package/esm/create.js ADDED
@@ -0,0 +1,39 @@
1
+ import { lazy, createElement } from 'react';
2
+ import { withApi } from 'piral-core';
3
+ export function createLazyApi() {
4
+ return (context) => {
5
+ return (api) => {
6
+ const cache = {};
7
+ const getDependency = (name) => {
8
+ var _a;
9
+ const dep = cache[name];
10
+ if (!dep) {
11
+ throw new Error(`The given dependency "${name}" cannot be found. Please add it first using "defineDependency"`);
12
+ }
13
+ return (_a = dep.result) !== null && _a !== void 0 ? _a : (dep.result = dep.loader());
14
+ };
15
+ return {
16
+ defineDependency(name, loader) {
17
+ cache[name] = {
18
+ loader,
19
+ result: undefined,
20
+ };
21
+ },
22
+ fromLazy(load, deps = []) {
23
+ return lazy(() => Promise.all(deps.map(getDependency)).then((values) => {
24
+ const depMap = deps.reduce((obj, name, index) => {
25
+ obj[name] = values[index];
26
+ return obj;
27
+ }, {});
28
+ return load()
29
+ .then((comp) => withApi(context, comp, api, 'unknown'))
30
+ .then((compWithApi) => ({
31
+ default: (props) => createElement(compWithApi, Object.assign({ deps: depMap }, props)),
32
+ }));
33
+ }));
34
+ },
35
+ };
36
+ };
37
+ };
38
+ }
39
+ //# sourceMappingURL=create.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,aAAa,EAAiB,MAAM,OAAO,CAAC;AAC3D,OAAO,EAAe,OAAO,EAAE,MAAM,YAAY,CAAC;AAUlD,MAAM,UAAU,aAAa;IAC3B,OAAO,CAAC,OAAO,EAAE,EAAE;QACjB,OAAO,CAAC,GAAG,EAAE,EAAE;YACb,MAAM,KAAK,GAAoB,EAAE,CAAC;YAElC,MAAM,aAAa,GAAG,CAAC,IAAY,EAAE,EAAE;;gBACrC,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;gBAExB,IAAI,CAAC,GAAG,EAAE;oBACR,MAAM,IAAI,KAAK,CACb,yBAAyB,IAAI,iEAAiE,CAC/F,CAAC;iBACH;gBAED,OAAO,MAAA,GAAG,CAAC,MAAM,mCAAI,CAAC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACnD,CAAC,CAAC;YAEF,OAAO;gBACL,gBAAgB,CAAC,IAAI,EAAE,MAAM;oBAC3B,KAAK,CAAC,IAAI,CAAC,GAAG;wBACZ,MAAM;wBACN,MAAM,EAAE,SAAS;qBAClB,CAAC;gBACJ,CAAC;gBACD,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,EAAE;oBACtB,OAAO,IAAI,CAAC,GAAG,EAAE,CACf,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;wBACnD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;4BAC9C,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;4BAC1B,OAAO,GAAG,CAAC;wBACb,CAAC,EAAE,EAAE,CAAC,CAAC;wBACP,OAAO,IAAI,EAAE;6BACV,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,CAAC;6BACtD,IAAI,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;4BACtB,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,aAAa,CAAC,WAA4B,kBAAI,IAAI,EAAE,MAAM,IAAK,KAAK,EAAG;yBAC5F,CAAC,CAAC,CAAC;oBACR,CAAC,CAAC,CACH,CAAC;gBACJ,CAAC;aACF,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
package/esm/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './create';
2
+ export * from './types';
package/esm/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './create';
2
+ export * from './types';
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC"}
package/esm/types.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { ComponentType } from 'react';
2
+ import type { AnyComponent, BaseComponentProps } from 'piral-core';
3
+ declare module 'piral-core/lib/types/custom' {
4
+ interface PiletCustomApi extends PiletLazyApi {
5
+ }
6
+ }
7
+ export interface LazyComponentLoader<TProps> {
8
+ (): Promise<AnyComponent<TProps>>;
9
+ }
10
+ export interface LazyDependencyLoader {
11
+ (): Promise<any>;
12
+ }
13
+ /**
14
+ * Defines the provided set of lazy loading Pilet API extensions.
15
+ */
16
+ export interface PiletLazyApi {
17
+ /**
18
+ * Defines a dependency for lazy loading.
19
+ * @param name The name of the dependency.
20
+ * @param loader The associated dependency loader.
21
+ */
22
+ defineDependency(name: string, loader: LazyDependencyLoader): void;
23
+ /**
24
+ * Properly introduces a lazy loaded foreign component.
25
+ * @param cb The callback to trigger when the component should be loaded.
26
+ * @param deps The optional names of the dependencies to load beforehand.
27
+ * @returns The lazy loading component.
28
+ */
29
+ fromLazy<T extends BaseComponentProps>(cb: LazyComponentLoader<T>, deps?: Array<string>): ComponentType<T & {
30
+ deps?: Record<string, any>;
31
+ }>;
32
+ }
package/esm/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/lib/create.js CHANGED
@@ -1,33 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createLazyApi = void 0;
4
- var react_1 = require("react");
5
- var piral_core_1 = require("piral-core");
4
+ const react_1 = require("react");
5
+ const piral_core_1 = require("piral-core");
6
6
  function createLazyApi() {
7
- return function (context) {
8
- return function (api) {
9
- var cache = {};
10
- var getDependency = function (name) {
7
+ return (context) => {
8
+ return (api) => {
9
+ const cache = {};
10
+ const getDependency = (name) => {
11
11
  var _a;
12
- var dep = cache[name];
12
+ const dep = cache[name];
13
13
  if (!dep) {
14
- throw new Error("The given dependency \"" + name + "\" cannot be found. Please add it first using \"defineDependency\"");
14
+ throw new Error(`The given dependency "${name}" cannot be found. Please add it first using "defineDependency"`);
15
15
  }
16
16
  return (_a = dep.result) !== null && _a !== void 0 ? _a : (dep.result = dep.loader());
17
17
  };
18
- var wrapComponent = function (comp) { return ({
19
- default: piral_core_1.withApi(context, comp, api, 'unknown'),
20
- }); };
21
18
  return {
22
- defineDependency: function (name, loader) {
19
+ defineDependency(name, loader) {
23
20
  cache[name] = {
24
- loader: loader,
21
+ loader,
25
22
  result: undefined,
26
23
  };
27
24
  },
28
- fromLazy: function (load, deps) {
29
- if (deps === void 0) { deps = []; }
30
- return react_1.lazy(function () { return Promise.all(deps.map(getDependency)).then(load).then(wrapComponent); });
25
+ fromLazy(load, deps = []) {
26
+ return (0, react_1.lazy)(() => Promise.all(deps.map(getDependency)).then((values) => {
27
+ const depMap = deps.reduce((obj, name, index) => {
28
+ obj[name] = values[index];
29
+ return obj;
30
+ }, {});
31
+ return load()
32
+ .then((comp) => (0, piral_core_1.withApi)(context, comp, api, 'unknown'))
33
+ .then((compWithApi) => ({
34
+ default: (props) => (0, react_1.createElement)(compWithApi, Object.assign({ deps: depMap }, props)),
35
+ }));
36
+ }));
31
37
  },
32
38
  };
33
39
  };
package/lib/create.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"create.js","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":";;;AAAA,+BAA6B;AAC7B,yCAAiE;AAUjE,SAAgB,aAAa;IAC3B,OAAO,UAAC,OAAO;QACb,OAAO,UAAC,GAAG;YACT,IAAM,KAAK,GAAoB,EAAE,CAAC;YAElC,IAAM,aAAa,GAAG,UAAC,IAAY;;gBACjC,IAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;gBAExB,IAAI,CAAC,GAAG,EAAE;oBACR,MAAM,IAAI,KAAK,CACb,4BAAyB,IAAI,uEAAiE,CAC/F,CAAC;iBACH;gBAED,aAAO,GAAG,CAAC,MAAM,mCAAI,CAAC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACnD,CAAC,CAAC;YACF,IAAM,aAAa,GAAG,UAAI,IAAsB,IAAK,OAAA,CAAC;gBACpD,OAAO,EAAE,oBAAO,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC;aAChD,CAAC,EAFmD,CAEnD,CAAC;YAEH,OAAO;gBACL,gBAAgB,YAAC,IAAI,EAAE,MAAM;oBAC3B,KAAK,CAAC,IAAI,CAAC,GAAG;wBACZ,MAAM,QAAA;wBACN,MAAM,EAAE,SAAS;qBAClB,CAAC;gBACJ,CAAC;gBACD,QAAQ,YAAC,IAAI,EAAE,IAAS;oBAAT,qBAAA,EAAA,SAAS;oBACtB,OAAO,YAAI,CAAC,cAAM,OAAA,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,EAAnE,CAAmE,CAAC,CAAC;gBACzF,CAAC;aACF,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAjCD,sCAiCC"}
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":";;;AAAA,iCAA2D;AAC3D,2CAAkD;AAUlD,SAAgB,aAAa;IAC3B,OAAO,CAAC,OAAO,EAAE,EAAE;QACjB,OAAO,CAAC,GAAG,EAAE,EAAE;YACb,MAAM,KAAK,GAAoB,EAAE,CAAC;YAElC,MAAM,aAAa,GAAG,CAAC,IAAY,EAAE,EAAE;;gBACrC,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;gBAExB,IAAI,CAAC,GAAG,EAAE;oBACR,MAAM,IAAI,KAAK,CACb,yBAAyB,IAAI,iEAAiE,CAC/F,CAAC;iBACH;gBAED,OAAO,MAAA,GAAG,CAAC,MAAM,mCAAI,CAAC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;YACnD,CAAC,CAAC;YAEF,OAAO;gBACL,gBAAgB,CAAC,IAAI,EAAE,MAAM;oBAC3B,KAAK,CAAC,IAAI,CAAC,GAAG;wBACZ,MAAM;wBACN,MAAM,EAAE,SAAS;qBAClB,CAAC;gBACJ,CAAC;gBACD,QAAQ,CAAC,IAAI,EAAE,IAAI,GAAG,EAAE;oBACtB,OAAO,IAAA,YAAI,EAAC,GAAG,EAAE,CACf,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;wBACnD,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE;4BAC9C,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;4BAC1B,OAAO,GAAG,CAAC;wBACb,CAAC,EAAE,EAAE,CAAC,CAAC;wBACP,OAAO,IAAI,EAAE;6BACV,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAA,oBAAO,EAAC,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,CAAC,CAAC;6BACtD,IAAI,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;4BACtB,OAAO,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAA,qBAAa,EAAC,WAA4B,kBAAI,IAAI,EAAE,MAAM,IAAK,KAAK,EAAG;yBAC5F,CAAC,CAAC,CAAC;oBACR,CAAC,CAAC,CACH,CAAC;gBACJ,CAAC;aACF,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AA1CD,sCA0CC"}
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var tslib_1 = require("tslib");
3
+ const tslib_1 = require("tslib");
4
4
  tslib_1.__exportStar(require("./create"), exports);
5
5
  tslib_1.__exportStar(require("./types"), exports);
6
6
  //# sourceMappingURL=index.js.map
package/lib/types.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { ComponentType, LazyExoticComponent } from 'react';
2
- import { FirstParametersOf, ComponentConverters } from 'piral-core';
1
+ import type { ComponentType } from 'react';
2
+ import type { AnyComponent, BaseComponentProps } from 'piral-core';
3
3
  declare module 'piral-core/lib/types/custom' {
4
4
  interface PiletCustomApi extends PiletLazyApi {
5
5
  }
6
6
  }
7
7
  export interface LazyComponentLoader<TProps> {
8
- (): Promise<FirstParametersOf<ComponentConverters<TProps>>>;
8
+ (): Promise<AnyComponent<TProps>>;
9
9
  }
10
10
  export interface LazyDependencyLoader {
11
11
  (): Promise<any>;
@@ -26,5 +26,7 @@ export interface PiletLazyApi {
26
26
  * @param deps The optional names of the dependencies to load beforehand.
27
27
  * @returns The lazy loading component.
28
28
  */
29
- fromLazy<T>(cb: LazyComponentLoader<T>, deps?: Array<string>): LazyExoticComponent<ComponentType<T>>;
29
+ fromLazy<T extends BaseComponentProps>(cb: LazyComponentLoader<T>, deps?: Array<string>): ComponentType<T & {
30
+ deps?: Record<string, any>;
31
+ }>;
30
32
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "piral-lazy",
3
- "version": "1.0.0-pre.2085",
3
+ "version": "1.0.0",
4
4
  "description": "Plugin for lazy loading third-party framework components in Piral.",
5
5
  "keywords": [
6
6
  "piral",
@@ -16,12 +16,32 @@
16
16
  "author": "smapiot",
17
17
  "homepage": "https://piral.io",
18
18
  "license": "MIT",
19
+ "module": "esm/index.js",
19
20
  "main": "lib/index.js",
20
21
  "typings": "lib/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "import": "./esm/index.js",
25
+ "require": "./lib/index.js"
26
+ },
27
+ "./esm/*": {
28
+ "import": "./esm/*"
29
+ },
30
+ "./lib/*": {
31
+ "require": "./lib/*"
32
+ },
33
+ "./_/*": {
34
+ "import": "./esm/*.js",
35
+ "require": "./lib/*.js"
36
+ },
37
+ "./package.json": "./package.json"
38
+ },
21
39
  "sideEffects": false,
22
40
  "files": [
41
+ "esm",
23
42
  "lib",
24
- "src"
43
+ "src",
44
+ "piral-lazy.min.js"
25
45
  ],
26
46
  "repository": {
27
47
  "type": "git",
@@ -31,15 +51,22 @@
31
51
  "url": "https://github.com/smapiot/piral/issues"
32
52
  },
33
53
  "scripts": {
34
- "build": "tsc",
54
+ "cleanup": "rimraf esm lib piral-lazy.min.js",
55
+ "build": "yarn build:bundle && yarn build:commonjs && yarn build:esnext",
56
+ "build:bundle": "esbuild src/index.ts --outfile=piral-lazy.min.js --bundle --external:piral-core --external:react --minify --global-name=piralLazy",
57
+ "build:commonjs": "tsc --project tsconfig.json --outDir lib --module commonjs",
58
+ "build:esnext": "tsc --project tsconfig.json --outDir esm --module esnext",
35
59
  "typedoc": "typedoc --json ../../../docs/types/piral-lazy.json src --exclude \"src/**/*.test.*\"",
36
60
  "test": "echo \"Error: run tests from root\" && exit 1"
37
61
  },
38
62
  "devDependencies": {
39
- "piral-core": "^1.0.0-pre.2085"
63
+ "@types/react": "^18.0.0",
64
+ "piral-core": "^1.0.0",
65
+ "react": "^18.0.0"
40
66
  },
41
67
  "peerDependencies": {
42
- "piral-core": "1.x"
68
+ "piral-core": "0.14.x || 0.15.x",
69
+ "react": ">=16.8.0"
43
70
  },
44
- "gitHead": "140092491c51e02c298804e87070f56c8f6ce0fc"
71
+ "gitHead": "67d9a2920bd5231baf10bc87ae8985666b18fa3a"
45
72
  }
@@ -0,0 +1 @@
1
+ var piralLazy=(()=>{var D=Object.create;var p=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames,y=Object.getOwnPropertySymbols,C=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,x=Object.prototype.propertyIsEnumerable;var s=(e,n,r)=>n in e?p(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r,f=(e,n)=>{for(var r in n||(n={}))l.call(n,r)&&s(e,r,n[r]);if(y)for(var r of y(n))x.call(n,r)&&s(e,r,n[r]);return e};var m=e=>p(e,"__esModule",{value:!0});var h=(e=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(e,{get:(n,r)=>(typeof require!="undefined"?require:n)[r]}):e)(function(e){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var T=(e,n)=>{m(e);for(var r in n)p(e,r,{get:n[r],enumerable:!0})},E=(e,n,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of A(n))!l.call(e,o)&&o!=="default"&&p(e,o,{get:()=>n[o],enumerable:!(r=w(n,o))||r.enumerable});return e},P=e=>E(m(p(e!=null?D(C(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var v={};T(v,{createLazyApi:()=>k});var d=P(h("react")),L=P(h("piral-core"));function k(){return e=>n=>{let r={},o=a=>{var c;let t=r[a];if(!t)throw new Error(`The given dependency "${a}" cannot be found. Please add it first using "defineDependency"`);return(c=t.result)!=null?c:t.result=t.loader()};return{defineDependency(a,t){r[a]={loader:t,result:void 0}},fromLazy(a,t=[]){return(0,d.lazy)(()=>Promise.all(t.map(o)).then(c=>{let g=t.reduce((i,u,z)=>(i[u]=c[z],i),{});return a().then(i=>(0,L.withApi)(e,i,n,"unknown")).then(i=>({default:u=>(0,d.createElement)(i,f({deps:g},u))}))}))}}}}return v;})();
@@ -0,0 +1,68 @@
1
+ import * as React from 'react';
2
+ import create from 'zustand';
3
+ import { render, act } from '@testing-library/react';
4
+ import { StateContext } from 'piral-core';
5
+ import { createLazyApi } from './create';
6
+
7
+ function createMockContainer() {
8
+ const state = create(() => ({
9
+ app: {
10
+ publicPath: '/',
11
+ },
12
+ components: {},
13
+ errorComponents: {},
14
+ portals: {},
15
+ registry: {
16
+ wrappers: {},
17
+ },
18
+ }));
19
+ return {
20
+ context: {
21
+ on: jest.fn(),
22
+ off: jest.fn(),
23
+ emit: jest.fn(),
24
+ defineActions() {},
25
+ state,
26
+ converters: {
27
+ html: ({ component }) => component,
28
+ },
29
+ navigation: {
30
+ router: undefined,
31
+ },
32
+ readState(read) {
33
+ return read(state.getState());
34
+ },
35
+ destroyPortal() {},
36
+ dispatch(update) {
37
+ state.setState(update(state.getState()));
38
+ },
39
+ } as any,
40
+ api: {
41
+ meta: {
42
+ name: 'sample-pilet',
43
+ },
44
+ } as any,
45
+ };
46
+ }
47
+
48
+ describe('Piral-Lazy create module', () => {
49
+ it('appends lazy loading for a DOM component', async () => {
50
+ const mount = jest.fn();
51
+ const MyComponent = { component: { mount }, type: 'html' };
52
+ const load = async () => await Promise.resolve(MyComponent);
53
+ const { context, api } = createMockContainer();
54
+ const apiCreator: any = createLazyApi()(context);
55
+ const { fromLazy, defineDependency } = apiCreator(api);
56
+ defineDependency('testName', () => {});
57
+ const LazyComponent = fromLazy(load, ['testName']);
58
+ render(
59
+ <StateContext.Provider value={context}>
60
+ <React.Suspense fallback="anything">
61
+ <LazyComponent />
62
+ </React.Suspense>
63
+ </StateContext.Provider>,
64
+ );
65
+ await act(() => Promise.resolve());
66
+ expect(LazyComponent).not.toBeUndefined();
67
+ });
68
+ });
package/src/create.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { lazy } from 'react';
2
- import { PiralPlugin, withApi, HtmlComponent } from 'piral-core';
1
+ import { lazy, createElement, ComponentType } from 'react';
2
+ import { PiralPlugin, withApi } from 'piral-core';
3
3
  import { PiletLazyApi, LazyDependencyLoader } from './types';
4
4
 
5
5
  interface DependencyCache {
@@ -25,9 +25,6 @@ export function createLazyApi(): PiralPlugin<PiletLazyApi> {
25
25
 
26
26
  return dep.result ?? (dep.result = dep.loader());
27
27
  };
28
- const wrapComponent = <T>(comp: HtmlComponent<T>) => ({
29
- default: withApi(context, comp, api, 'unknown'),
30
- });
31
28
 
32
29
  return {
33
30
  defineDependency(name, loader) {
@@ -37,7 +34,19 @@ export function createLazyApi(): PiralPlugin<PiletLazyApi> {
37
34
  };
38
35
  },
39
36
  fromLazy(load, deps = []) {
40
- return lazy(() => Promise.all(deps.map(getDependency)).then(load).then(wrapComponent));
37
+ return lazy(() =>
38
+ Promise.all(deps.map(getDependency)).then((values) => {
39
+ const depMap = deps.reduce((obj, name, index) => {
40
+ obj[name] = values[index];
41
+ return obj;
42
+ }, {});
43
+ return load()
44
+ .then((comp) => withApi(context, comp, api, 'unknown'))
45
+ .then((compWithApi) => ({
46
+ default: (props) => createElement(compWithApi as ComponentType, { deps: depMap, ...props }),
47
+ }));
48
+ }),
49
+ );
41
50
  },
42
51
  };
43
52
  };
package/src/types.ts CHANGED
@@ -1,12 +1,12 @@
1
- import { ComponentType, LazyExoticComponent } from 'react';
2
- import { FirstParametersOf, ComponentConverters } from 'piral-core';
1
+ import type { ComponentType } from 'react';
2
+ import type { AnyComponent, BaseComponentProps } from 'piral-core';
3
3
 
4
4
  declare module 'piral-core/lib/types/custom' {
5
5
  interface PiletCustomApi extends PiletLazyApi {}
6
6
  }
7
7
 
8
8
  export interface LazyComponentLoader<TProps> {
9
- (): Promise<FirstParametersOf<ComponentConverters<TProps>>>;
9
+ (): Promise<AnyComponent<TProps>>;
10
10
  }
11
11
 
12
12
  export interface LazyDependencyLoader {
@@ -29,5 +29,8 @@ export interface PiletLazyApi {
29
29
  * @param deps The optional names of the dependencies to load beforehand.
30
30
  * @returns The lazy loading component.
31
31
  */
32
- fromLazy<T>(cb: LazyComponentLoader<T>, deps?: Array<string>): LazyExoticComponent<ComponentType<T>>;
32
+ fromLazy<T extends BaseComponentProps>(
33
+ cb: LazyComponentLoader<T>,
34
+ deps?: Array<string>,
35
+ ): ComponentType<T & { deps?: Record<string, any> }>;
33
36
  }
@@ -1,34 +0,0 @@
1
- import { Atom, swap } from '@dbeining/react-atom';
2
- import { createLazyApi } from './create';
3
-
4
- function createMockContainer() {
5
- const state = Atom.of({});
6
- return {
7
- context: {
8
- converters: {},
9
- on: jest.fn(),
10
- off: jest.fn(),
11
- emit: jest.fn(),
12
- defineActions() {},
13
- state,
14
- readState(read) {
15
- return read(state);
16
- },
17
- dispatch(update) {
18
- swap(state, update);
19
- },
20
- } as any,
21
- api: {} as any,
22
- };
23
- }
24
-
25
- describe('Piral-Lazy create module', () => {
26
- it('appends lazy loading for a DOM component', () => {
27
- const { context } = createMockContainer();
28
- const load = () => Promise.resolve({});
29
- const apiCreator: any = createLazyApi()(context);
30
- const { fromLazy } = apiCreator();
31
- const lazyComponent = fromLazy(load);
32
- expect(lazyComponent).not.toBeUndefined();
33
- });
34
- });