@soleil-se/app-util 5.5.2 → 5.6.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,10 +1,24 @@
1
- # Changelog
1
+ ---
2
+ title: Changelog
3
+ ---
2
4
 
3
5
  All notable changes to this project will be documented in this file.
4
6
 
5
7
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
8
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
9
 
10
+ ## [5.6.1] - 2023-12-13
11
+
12
+ - Hydrate when children other than HTML Elements exist in target.
13
+ - New argument for client side Svelte rendering for `hydrate`.
14
+
15
+ ## [5.6.0] - 2023-11-23
16
+
17
+ - New constants: `isServer` and `isBrowser`.
18
+ - New function: `generateId`.
19
+ - Throw more clear error when JSON response can't be parsed in `fetchJson`.
20
+ - Webpack support for usage with `@sitevision/sitevision-scripts`.
21
+
8
22
  ## [5.5.2] - 2023-08-28
9
23
 
10
24
  - Respect hash when updating URL parameters with `updateUrlParams` and `setUrlParams`.
@@ -159,7 +173,7 @@ See [MIGRATION](./MIGRATION.md).
159
173
  - App data import in client, `@soleil-api/webapp-util/app-data`.
160
174
  - `getViewUri` to get the URI that also renders the page.
161
175
  - `isOnline` to see if the app is online.
162
- - `vue` is now an optional depedency.
176
+ - `vue` is now an optional depedency.
163
177
 
164
178
  ## [2.0.0] - 2020-02-12
165
179
 
package/README.md CHANGED
@@ -11,7 +11,7 @@ Utility functions for WebApps.
11
11
  ## Requirements
12
12
 
13
13
  * Sitevision 9.1.0 or later.
14
- * `@soleil-se/sv-app-build` 1.0.0 or later.
14
+ * `@soleil-se/sv-app-build@^1.0.0` or `@sitevision/sitevision-scripts@^3.0.0`.
15
15
  * WebApps 2 enabled app.
16
16
 
17
17
  ### Manifest
@@ -86,6 +86,26 @@ import { isOnline } from '@soleil-se/webapp-util';
86
86
  console.log(isOnline); // true or false
87
87
  ```
88
88
 
89
+ ### isServer : `Boolean`
90
+
91
+ If the current code is running on the server.
92
+
93
+ ```js
94
+ import { isServer } from '@soleil-se/webapp-util';
95
+
96
+ console.log(isServer); // true or false
97
+ ```
98
+
99
+ ### isBrowser : `Boolean`
100
+
101
+ If the current code is running in the browser.
102
+
103
+ ```js
104
+ import { isBrowser } from '@soleil-se/webapp-util';
105
+
106
+ console.log(isBrowser); // true or false
107
+ ```
108
+
89
109
  ### getNamespace([prefix]) ⇒ `String`
90
110
 
91
111
  Get a prefixed namespace unique for app.
@@ -110,6 +130,27 @@ console.log(getNamespace('decoration'));
110
130
  // For example: decoration_10_3871c02f1754f3aa8f9d4eb_12_70c3d424173b4900fc550e1c
111
131
  ```
112
132
 
133
+ ### generateId([prefix]) ⇒ `String`
134
+
135
+ Generate a unique identifier with a random UUID without dashes.
136
+
137
+ **Returns**: `String` - Unique identifier.
138
+
139
+ | Param | Type | Default |
140
+ | --- | --- | --- |
141
+ | [prefix] | `string` | `"'id'"` |
142
+
143
+ ```js
144
+ import { generateId } from '@soleil-se/webapp-util';
145
+
146
+ console.log(generateId());
147
+ // For example: id_550e8400e29b41d4a716446655440000
148
+
149
+ console.log(generateId('input'));
150
+ // For example: input_550e8400e29b41d4a716446655440000
151
+
152
+ ```
153
+
113
154
  ### getRouteUri(route, [query]) ⇒ `String`
114
155
 
115
156
  Get URI for a route.
@@ -7,25 +7,32 @@ function getUrl(uri, params) {
7
7
  return getRouteUri(uri, params);
8
8
  }
9
9
 
10
- function toJson(response) {
10
+ async function toJson(response) {
11
+ const text = await response.text();
11
12
  try {
12
- return response.json();
13
+ return JSON.parse(text);
13
14
  } catch (e) {
14
- return {};
15
+ return undefined;
15
16
  }
16
17
  }
17
18
 
19
+ async function handleError(response) {
20
+ const json = await toJson(response) || {};
21
+ const error = new Error(json?.message || response?.statusText);
22
+ Object.entries(json).forEach(([key, value]) => {
23
+ error[key] = value;
24
+ });
25
+ error.status = response.status;
26
+ throw error;
27
+ }
28
+
18
29
  async function handleResponse(response) {
30
+ if (!response.ok) handleError(response);
31
+
19
32
  const json = await toJson(response);
20
- if (!response.ok) {
21
- const error = new Error(json?.message || response?.statusText);
22
- Object.entries(json).forEach(([key, value]) => {
23
- error[key] = value;
24
- });
25
- error.status = response.status;
26
- throw error;
33
+ if (!json) {
34
+ throw new Error('Response could not be parsed as JSON.');
27
35
  }
28
-
29
36
  return json;
30
37
  }
31
38
 
@@ -14,11 +14,10 @@ export function render(App, {
14
14
  target,
15
15
  props,
16
16
  intro = false,
17
+ hydrate = target.hasChildNodes(),
17
18
  } = {}) {
18
19
  setAppProps(props);
19
20
 
20
- const hydrate = target.childElementCount > 0;
21
-
22
21
  return new App({
23
22
  hydrate,
24
23
  target,
package/common/index.js CHANGED
@@ -1,21 +1,9 @@
1
- /* eslint-disable global-require */
2
1
  import router from '@sitevision/api/common/router';
3
2
  import app from '@sitevision/api/common/app';
4
3
 
4
+ import { nativeRequire } from '../server';
5
5
  import getLegacyRouteUri from './legacy/getRouteUri';
6
6
 
7
- /**
8
- * Get an ID for the app.
9
- * @return {String} ID
10
- */
11
- const getAppId = () => {
12
- const id = (process.server
13
- ? require('PortletContextUtil')?.getCurrentPortlet()?.getIdentifier()
14
- : app?.portletId) || 'preview';
15
-
16
- return id.replace('.', '_');
17
- };
18
-
19
7
  /**
20
8
  * Regex for selecting leading slashes
21
9
  * @constant {Regex}
@@ -28,18 +16,30 @@ const leadingSlashes = /^(\/)*/g;
28
16
  */
29
17
  const trailingSlashes = /(\/)*$/g;
30
18
 
19
+ /**
20
+ * If the current code is running on the server.
21
+ * @constant {boolean}
22
+ */
23
+ export const isServer = typeof process !== 'undefined' ? process.server : typeof window === 'undefined';
24
+
25
+ /**
26
+ * If the current code is running in the browser.
27
+ * @constant {boolean}
28
+ */
29
+ export const isBrowser = !isServer;
30
+
31
31
  /**
32
32
  * DOM friendly unique identifier for the WebApp.
33
33
  * @constant {string}
34
34
  */
35
- export const appId = getAppId();
35
+ export const appId = (app?.portletId || 'preview').replace('.', '_');
36
36
 
37
37
  /**
38
38
  * If the WebApp is running in offline mode or not.
39
39
  * @constant {boolean}
40
40
  */
41
- export const isOffline = process.server
42
- ? require('VersionUtil').getCurrentVersion() === require('VersionUtil').OFFLINE_VERSION
41
+ export const isOffline = isServer
42
+ ? nativeRequire('VersionUtil').getCurrentVersion() === nativeRequire('VersionUtil').OFFLINE_VERSION
43
43
  : document.documentElement.classList.contains('sv-edit-mode');
44
44
 
45
45
  /**
@@ -51,12 +51,22 @@ export const isOnline = !isOffline;
51
51
  /**
52
52
  * Get a prefixed namespace unique for app.
53
53
  * @param {string} [prefix='app']
54
- * @return {String} - Prefixed namespace.
54
+ * @return {string} - Prefixed namespace.
55
55
  */
56
56
  export function getNamespace(prefix = 'app') {
57
57
  return `${prefix}_${appId}`;
58
58
  }
59
59
 
60
+ /**
61
+ * Generate a unique identifier with a random UUID without dashes.
62
+ * @param {string} prefix Prefix for the identifier.
63
+ * @returns {string} Unique identifier.
64
+ */
65
+ export function generateId(prefix = 'id') {
66
+ const uuid = isServer ? Packages.java.util.UUID.randomUUID() : window.crypto.randomUUID();
67
+ return `${prefix}_${uuid}`.replace(/-/g, '');
68
+ }
69
+
60
70
  /**
61
71
  * Stringify an object to a query string compatible with Sitevision.
62
72
  * @param {Object} params Object with parameters to stringify.
@@ -147,15 +157,7 @@ export function getViewUri(route = '', params = undefined) {
147
157
  * @returns {string} URI for a resource.
148
158
  */
149
159
  export function getResourceUri(resource = '') {
150
- let id;
151
- let version;
152
-
153
- if (process.server) {
154
- ({ appIdentifier: id, appVersion: version } = require('appInfo'));
155
- } else {
156
- ({ webAppId: id, webAppVersion: version } = app);
157
- }
158
-
160
+ const { webAppId: id, webAppVersion: version } = app;
159
161
  const path = resource.replace(leadingSlashes, '');
160
162
  return `/webapp-files/${id}/${version}/${path}`;
161
163
  }
@@ -1,6 +1,7 @@
1
- /* eslint-disable global-require */
1
+ import { nativeRequire } from '../../server';
2
+
2
3
  export default function getRouteUri(route) {
3
- const PortletContextUtil = require('PortletContextUtil');
4
+ const PortletContextUtil = nativeRequire('PortletContextUtil');
4
5
  const currentPage = PortletContextUtil.getCurrentPage();
5
6
  const currentPortlet = PortletContextUtil.getCurrentPortlet();
6
7
  if (currentPage && currentPortlet) {
package/docs/1.svelte.md CHANGED
@@ -1,11 +1,11 @@
1
- # Svelte
1
+ ---
2
+ title: Svelte
3
+ ---
2
4
 
3
5
  Sitevision supports both server and client side rendering with Svelte.
4
6
 
5
7
  ## index.js
6
8
 
7
- For rendering a client side only app use the framework agnostic [client renderer](./1.render.md).
8
-
9
9
  ### `render(App, [props])`
10
10
 
11
11
  `@soleil-api/webapp-util/server/svelte`
@@ -13,20 +13,19 @@ For rendering a client side only app use the framework agnostic [client renderer
13
13
  Get a HTML string for rendering a universal Svelte application.
14
14
  If a client bundle is available the server rendered HTML will be hydrated and not completely re-rendered.
15
15
 
16
- **Returns**: <code>String</code> - HTML for rendering a Svelte application.
16
+ **Returns**: `String` - HTML for rendering a Svelte application.
17
17
 
18
- | Param | Type | Default | Description |
19
- | --- | --- | --- | --- |
20
- | [App] | <code>Svelte</code> | | Svelte app to be rendered. |
21
- | [props] | <code>Object</code> | <code>{}</code> | Props that will be passed to the app. |
18
+ | Param | Type | Default | Description |
19
+ |---------|----------|---------|---------------------------------------|
20
+ | [App] | `Svelte` | | Svelte app to be rendered. |
21
+ | [props] | `Object` | `{}` | Props that will be passed to the app. |
22
22
 
23
23
  ### Universal
24
24
 
25
25
  Render an app with both server and client code.
26
26
 
27
- `index.js`
28
-
29
27
  ```javascript
28
+ // index.js
30
29
  import router from '@sitevision/api/common/router';
31
30
  import { render } from '@soleil-api/webapp-util/server/svelte';
32
31
 
@@ -35,7 +34,7 @@ import App from './App.svelte';
35
34
  router.get('/', (req, res) => {
36
35
  const props = { foo: 'bar' };
37
36
  const html = render(App, props);
38
- res.agnosticRender(html, props);
37
+ res.agnosticRender(html, props);
39
38
  });
40
39
  ```
41
40
 
@@ -43,9 +42,8 @@ router.get('/', (req, res) => {
43
42
 
44
43
  Render an app with only server side code.
45
44
 
46
- `index.js`
47
-
48
- ```javascript
45
+ ```js
46
+ // index.js
49
47
  import router from '@sitevision/api/common/router';
50
48
  import { render } from '@soleil-api/webapp-util/server/svelte';
51
49
 
@@ -54,7 +52,7 @@ import App from './App.svelte';
54
52
  router.get('/', (req, res) => {
55
53
  const props = { foo: 'bar' };
56
54
  const html = render(App, props);
57
- res.send(html);
55
+ res.send(html);
58
56
  });
59
57
  ```
60
58
 
@@ -62,9 +60,8 @@ router.get('/', (req, res) => {
62
60
 
63
61
  Render an app with only client side code.
64
62
 
65
- `index.js`
66
-
67
63
  ```javascript
64
+ // index.js
68
65
  import router from '@sitevision/api/common/router';
69
66
 
70
67
  router.get('/', (req, res) => {
@@ -81,19 +78,19 @@ router.get('/', (req, res) => {
81
78
 
82
79
  Renders a client side Svelte application.
83
80
 
84
- **Returns**: <code>\*</code> - Initialized Svelte component.
85
-
86
- | Param | Type | Default | Description |
87
- | --- | --- | --- | --- |
88
- | App | <code>\*</code> | | Svelte app root component. |
89
- | [settings] | <code>Object</code> | <code>{}</code> | Settings object. |
90
- | [settings.target] | <code>Element</code> | | Target where app should be mounted. |
91
- | [settings.props] | <code>Object</code> | | Root component props. |
92
- | [settings.intro] | <code>String</code> | <code>false</code> | If true, will play transitions on initial render, rather than waiting for subsequent state changes. |
81
+ **Returns**: `SvelteComponent` - Initialized Svelte component.
93
82
 
94
- `main.js`
83
+ | Param | Type | Default | Description |
84
+ |--------------------|-------------------|--------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
85
+ | App | `SvelteComponent` | | Svelte app root component. |
86
+ | [settings] | `Object` | `{}` | Settings object. |
87
+ | [settings.target] | `Element` | | Target where app should be mounted. |
88
+ | [settings.props] | `Object` | | Root component props. |
89
+ | [settings.intro] | `Boolean` | `false` | If true, will play transitions on initial render, rather than waiting for subsequent state changes. |
90
+ | [settings.hydrate] | `Boolean` | `target.hasChildNodes()` | Instructs Svelte to upgrade existing DOM (usually from server-side rendering) rather than creating new elements. By default the app will hydrate when the target has any child nodes. |
95
91
 
96
92
  ```javascript
93
+ // main.js
97
94
  import { render } from '@soleil-api/webapp-util/client/svelte';
98
95
  import App from './App.svelte';
99
96
 
@@ -103,9 +100,9 @@ export default (props, target) => {
103
100
  ```
104
101
 
105
102
  Mount the app in another element:
106
- `main.js`
107
103
 
108
104
  ```javascript
105
+ // main.js
109
106
  import { render } from '@soleil-api/webapp-util/client/svelte';
110
107
  import App from './App.svelte';
111
108
 
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "@soleil-se/app-util",
3
- "version": "5.5.2",
3
+ "version": "5.6.1",
4
4
  "description": "Utility and rendering functions for WebApps.",
5
5
  "main": "./common/index.js",
6
6
  "author": "Soleil AB",
7
7
  "license": "UNLICENSED",
8
8
  "private": false,
9
- "homepage": "https://docs.soleil.se/03.packages/01.@soleil-api&app-util/",
9
+ "homepage": "https://docs.soleil.se/build/sv-app-build/",
10
10
  "devDependencies": {
11
- "@sitevision/api": "^1.0.10",
12
- "svelte": "^3.44.1"
11
+ "@sitevision/api": "^2023.9.2",
12
+ "svelte": "^3.59.2"
13
13
  },
14
14
  "peerDependencies": {
15
15
  "@sitevision/api": "*"
16
16
  },
17
- "gitHead": "e132d21089258c678eab7a8a3387edabe1f6534b",
17
+ "gitHead": "54e37b4e8586cfe3ceccd033b280aba9c4cb2463",
18
18
  "dependencies": {}
19
19
  }
@@ -0,0 +1,7 @@
1
+ /* Make native requires work with @sitevision/sitevision-scripts that uses Webpack */
2
+ /* eslint-disable camelcase, no-undef, import/no-dynamic-require, global-require */
3
+ export function nativeRequire(module) {
4
+ if (typeof __non_webpack_require__ !== 'undefined') return __non_webpack_require__(module);
5
+ return require(module);
6
+ }
7
+ /* eslint-enable camelcase, no-undef, import/no-dynamic-require, global-require */