@panomc/widget-host 0.0.0-stage → 1.0.0-dev.61

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.
Files changed (108) hide show
  1. package/dist/runtime/chunks/chunk-9EZydhXt.js +1 -0
  2. package/dist/runtime/chunks/chunk-BQPllGmY.js +1 -0
  3. package/dist/runtime/chunks/chunk-CTgT5UYL.js +1 -0
  4. package/dist/runtime/chunks/chunk-ChRkfjHR.js +1 -0
  5. package/dist/runtime/chunks/chunk-Cmbb89rp.js +1 -0
  6. package/dist/runtime/chunks/chunk-CqpY4RsZ.js +1 -0
  7. package/dist/runtime/chunks/chunk-D7Jd5Dpn.js +1 -0
  8. package/dist/runtime/chunks/chunk-DNUkGPCL.js +1 -0
  9. package/dist/runtime/chunks/chunk-DebScgYV.js +1 -0
  10. package/dist/runtime/chunks/chunk-DgPYxg7o.js +1 -0
  11. package/dist/runtime/chunks/chunk-DhgH0pN2.js +1 -0
  12. package/dist/runtime/chunks/chunk-FEL6LDrJ.js +1 -0
  13. package/dist/runtime/chunks/chunk-RPo0Hd8r.js +1 -0
  14. package/dist/runtime/chunks/chunk-Xd_2KAhC.js +1 -0
  15. package/dist/runtime/chunks/chunk-akOtSLvV.js +1 -0
  16. package/dist/runtime/chunks/chunk-cUxFvg6m.js +1 -0
  17. package/dist/runtime/css/pano-fallback-icons.css +9 -0
  18. package/dist/runtime/css/pano-tokens.css +225 -0
  19. package/dist/runtime/host/components-panel.js +1 -0
  20. package/dist/runtime/host/components-theme.js +1 -0
  21. package/dist/runtime/host/controllers.js +1 -0
  22. package/dist/runtime/host/index.js +1 -0
  23. package/dist/runtime/host/internal.js +1 -0
  24. package/dist/runtime/host/svelte.js +1 -0
  25. package/dist/runtime/host/toasts.js +1 -0
  26. package/dist/runtime/host/utils-api.js +1 -0
  27. package/dist/runtime/host/utils-auth.js +1 -0
  28. package/dist/runtime/host/utils-component.js +1 -0
  29. package/dist/runtime/host/utils-language.js +1 -0
  30. package/dist/runtime/host/utils-route.js +1 -0
  31. package/dist/runtime/host/utils-text.js +1 -0
  32. package/dist/runtime/host/utils-tooltip.js +1 -0
  33. package/dist/runtime/host/variables.js +1 -0
  34. package/dist/runtime/host/views.js +1 -0
  35. package/dist/runtime/loader.js +1 -0
  36. package/dist/runtime/runtime.json +104 -0
  37. package/dist/runtime/svelte/animate.js +1 -0
  38. package/dist/runtime/svelte/attachments.js +1 -0
  39. package/dist/runtime/svelte/easing.js +1 -0
  40. package/dist/runtime/svelte/events.js +1 -0
  41. package/dist/runtime/svelte/index.js +1 -0
  42. package/dist/runtime/svelte/internal-client.js +1 -0
  43. package/dist/runtime/svelte/internal-disclose-version.js +1 -0
  44. package/dist/runtime/svelte/internal-flags-async.js +1 -0
  45. package/dist/runtime/svelte/internal-flags-legacy.js +1 -0
  46. package/dist/runtime/svelte/internal-flags-tracing.js +1 -0
  47. package/dist/runtime/svelte/internal.js +1 -0
  48. package/dist/runtime/svelte/legacy.js +1 -0
  49. package/dist/runtime/svelte/motion.js +1 -0
  50. package/dist/runtime/svelte/reactivity-window.js +1 -0
  51. package/dist/runtime/svelte/reactivity.js +1 -0
  52. package/dist/runtime/svelte/store.js +1 -0
  53. package/dist/runtime/svelte/transition.js +1 -0
  54. package/dist/runtime/svelte-i18n.js +1 -0
  55. package/dist/runtime/webfonts/fa-brands-400.ttf +0 -0
  56. package/dist/runtime/webfonts/fa-brands-400.woff2 +0 -0
  57. package/dist/runtime/webfonts/fa-regular-400.ttf +0 -0
  58. package/dist/runtime/webfonts/fa-regular-400.woff2 +0 -0
  59. package/dist/runtime/webfonts/fa-solid-900.ttf +0 -0
  60. package/dist/runtime/webfonts/fa-solid-900.woff2 +0 -0
  61. package/dist/runtime/webfonts/fa-v4compatibility.ttf +0 -0
  62. package/dist/runtime/webfonts/fa-v4compatibility.woff2 +0 -0
  63. package/dist/widget-runtime.zip +0 -0
  64. package/package.json +59 -4
  65. package/scripts/build-zip.js +35 -0
  66. package/scripts/install-local.js +57 -0
  67. package/scripts/loader.js +169 -0
  68. package/scripts/runtime-map.js +52 -0
  69. package/scripts/zip.js +128 -0
  70. package/src/__tests__/components.test.js +77 -0
  71. package/src/__tests__/controllers.test.js +188 -0
  72. package/src/__tests__/define.test.js +276 -0
  73. package/src/__tests__/env.js +111 -0
  74. package/src/__tests__/fixtures/Goal.svelte +5 -0
  75. package/src/__tests__/modules.test.js +251 -0
  76. package/src/__tests__/parity.test.js +123 -0
  77. package/src/api.js +144 -0
  78. package/src/auth.js +2 -0
  79. package/src/component.js +4 -0
  80. package/src/components/Date.svelte +38 -0
  81. package/src/components/NoContent.svelte +13 -0
  82. package/src/components/PageActions.svelte +22 -0
  83. package/src/components/PageTitle.svelte +32 -0
  84. package/src/components/Pagination.svelte +49 -0
  85. package/src/components/PlayerHead.svelte +39 -0
  86. package/src/components/Toast.svelte +16 -0
  87. package/src/components/empty.js +3 -0
  88. package/src/components/index.js +14 -0
  89. package/src/components/panel.js +19 -0
  90. package/src/config.js +100 -0
  91. package/src/context.js +47 -0
  92. package/src/controllers.js +313 -0
  93. package/src/define.js +352 -0
  94. package/src/index.js +38 -0
  95. package/src/internal.js +2 -0
  96. package/src/language.js +181 -0
  97. package/src/plugin.js +20 -0
  98. package/src/route.js +4 -0
  99. package/src/runtime.js +49 -0
  100. package/src/session.js +72 -0
  101. package/src/svelte-runtime.js +3 -0
  102. package/src/svelte.js +72 -0
  103. package/src/text.js +2 -0
  104. package/src/toasts.js +75 -0
  105. package/src/tooltip.js +4 -0
  106. package/src/variables.js +29 -0
  107. package/src/views.js +17 -0
  108. package/README.md +0 -3
@@ -0,0 +1,313 @@
1
+ // `@panomc/sdk/controllers` in a widget page (doc 06 section 3.2, doc 02 section 2): the same `plugin` / `useController` / `reactive`
2
+ // over the page's controller registry and one widget `ControllerHost`.
3
+ //
4
+ // The registry file is the SDK's own (state on `globalThis.__PANO_CONTROLLERS__`), so a plugin's `controllers.mjs` registers
5
+ // into the same place whatever bundle it is imported from.
6
+ import { createSubscriber } from 'svelte/reactivity';
7
+ import { onMount } from './svelte-runtime.js';
8
+ import { get } from 'svelte/store';
9
+ import { _, locale } from 'svelte-i18n';
10
+ import { createFetchHost } from '@panomc/plugin-kit/controller';
11
+ import * as registry from '../../sdk/core/js/ControllerRegistry.js';
12
+ import { getConfig, resolveUrl } from './config.js';
13
+ import { hostRequest } from './api.js';
14
+ import { getSession, onSession } from './session.js';
15
+ import { goto } from './svelte.js';
16
+ import { showToast } from './toasts.js';
17
+
18
+ export { registry };
19
+
20
+ // ---------------------------------------------------------------------------------------------
21
+ // Load memo: `load(name, params)` is shared while in flight and for 5 seconds afterwards, so four widgets of one
22
+ // plugin that all read the same controller make one request (doc 06 section 3.1).
23
+ // ---------------------------------------------------------------------------------------------
24
+
25
+ export const LOAD_MEMO_MS = 5000;
26
+
27
+ function stable(value) {
28
+ if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;
29
+ if (value && typeof value === 'object') {
30
+ return `{${Object.keys(value)
31
+ .sort()
32
+ .map((k) => `${JSON.stringify(k)}:${stable(value[k])}`)
33
+ .join(',')}}`;
34
+ }
35
+ return JSON.stringify(value) ?? 'undefined';
36
+ }
37
+
38
+ /**
39
+ * @param {{ ttl?: number, now?: () => number }} [options]
40
+ */
41
+ export function createLoadMemo({ ttl = LOAD_MEMO_MS, now = () => Date.now() } = {}) {
42
+ /** @type {Map<string, { promise: Promise<any>, pending: boolean, settledAt: number }>} */
43
+ const entries = new Map();
44
+
45
+ return {
46
+ /**
47
+ * @param {string} name full controller name
48
+ * @param {object | undefined} params
49
+ * @param {() => Promise<any>} produce called only when nothing fresh is stored
50
+ */
51
+ run(name, params, produce) {
52
+ const key = `${name}\u0000${stable(params ?? {})}`;
53
+ const found = entries.get(key);
54
+
55
+ if (found && (found.pending || now() - found.settledAt < ttl)) return found.promise;
56
+ entries.delete(key);
57
+
58
+ let promise;
59
+ try {
60
+ promise = Promise.resolve(produce());
61
+ } catch (e) {
62
+ promise = Promise.reject(e);
63
+ }
64
+
65
+ const entry = { promise, pending: true, settledAt: 0 };
66
+ entries.set(key, entry);
67
+
68
+ promise.then(
69
+ (value) => {
70
+ // a controller that is not available (null) may be registered a moment later: do not keep that answer
71
+ if (value === null || value === undefined) {
72
+ if (entries.get(key) === entry) entries.delete(key);
73
+ return;
74
+ }
75
+ entry.pending = false;
76
+ entry.settledAt = now();
77
+ },
78
+ () => {
79
+ if (entries.get(key) === entry) entries.delete(key);
80
+ },
81
+ );
82
+
83
+ return promise;
84
+ },
85
+ clear() {
86
+ entries.clear();
87
+ },
88
+ get size() {
89
+ return entries.size;
90
+ },
91
+ };
92
+ }
93
+
94
+ const memo = createLoadMemo();
95
+
96
+ /** Forgets every memoised load (after `invalidate`, and in tests). */
97
+ export function clearLoadMemo() {
98
+ memo.clear();
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------------------------
102
+ // Host
103
+ // ---------------------------------------------------------------------------------------------
104
+
105
+ function storage(kind) {
106
+ try {
107
+ return (kind === 'session' ? globalThis.sessionStorage : globalThis.localStorage) || null;
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+
113
+ function currentLocale() {
114
+ try {
115
+ return get(locale) || getConfig().locale || undefined;
116
+ } catch {
117
+ return getConfig().locale || undefined;
118
+ }
119
+ }
120
+
121
+ function translateKey(key, values) {
122
+ try {
123
+ return get(_)(key, { values });
124
+ } catch {
125
+ return key;
126
+ }
127
+ }
128
+
129
+ /** A key of the URL map when the page configured it, else the default path on the site. */
130
+ function siteUrlFor(key, fallbackPath) {
131
+ return getConfig().urls[key] ? resolveUrl(key) : resolveUrl(fallbackPath);
132
+ }
133
+
134
+ function withReturn(target, returnTo) {
135
+ if (!returnTo) return target;
136
+ return `${target}${target.includes('?') ? '&' : '?'}redirect=${encodeURIComponent(returnTo)}`;
137
+ }
138
+
139
+ /**
140
+ * The `ControllerHost` of a widget page (doc 02 section 1): `request` goes to the page client, `session` / `onSession` to the
141
+ * probe, `locale` / `t` to svelte-i18n, `toast` / `navigate` to the modules of this package, `storage` to the browser.
142
+ * @param {Record<string, any>} [overrides]
143
+ */
144
+ export function createWidgetHost(overrides = {}) {
145
+ const base = createFetchHost({ baseUrl: getConfig().apiBase, browser: true });
146
+
147
+ const host = {
148
+ ...base,
149
+ request: (r) => hostRequest(r),
150
+ session: () => getSession(),
151
+ onSession: (fn) => onSession(fn),
152
+ locale: currentLocale,
153
+ t: translateKey,
154
+ toast: (key, o) => {
155
+ void showToast(key, o?.values ?? {}, undefined, o?.variant ? { variant: o.variant } : undefined);
156
+ },
157
+ navigate: (url, o) => {
158
+ void goto(url, { replaceState: !!o?.replace });
159
+ },
160
+ storage,
161
+ feature: () => false,
162
+ loginUrl: (returnTo) => withReturn(siteUrlFor('auth.login', '/login'), returnTo),
163
+ registerUrl: (returnTo) => withReturn(siteUrlFor('auth.register', '/register'), returnTo),
164
+ ...overrides,
165
+ };
166
+
167
+ Object.defineProperty(host, 'baseUrl', { get: () => getConfig().apiBase, enumerable: true, configurable: true });
168
+ return host;
169
+ }
170
+
171
+ let hostInstalled = false;
172
+
173
+ /** Gives the registry its host factory (once per page). */
174
+ export function ensureControllerHost() {
175
+ if (hostInstalled) return;
176
+ hostInstalled = true;
177
+ const host = createWidgetHost();
178
+ registry.setHostFactory(() => host);
179
+ }
180
+
181
+ /** @type {Map<string, Promise<boolean>>} */
182
+ const pluginLoads = new Map();
183
+
184
+ /**
185
+ * Registers a plugin's controllers before its first widget mounts: imports `controllers/controllers.mjs` (`url`, or an already
186
+ * imported `module`) and registers its definitions. Once per plugin; resolves false when the plugin has none or the import fails.
187
+ * @param {{ pluginId: string, ns: string, url?: string, module?: { controllers?: object } }} plugin
188
+ */
189
+ export function loadPluginControllers({ pluginId, ns, url, module }) {
190
+ if (!pluginLoads.has(pluginId)) {
191
+ pluginLoads.set(
192
+ pluginId,
193
+ (async () => {
194
+ try {
195
+ const mod = module ?? (await import(/* @vite-ignore */ url));
196
+ if (!mod?.controllers) return false;
197
+ ensureControllerHost();
198
+ registry.register(pluginId, ns, mod.controllers);
199
+ return true;
200
+ } catch (e) {
201
+ console.warn(`[pano-widgets] controllers of ${pluginId} could not be loaded`, e);
202
+ return false;
203
+ }
204
+ })(),
205
+ );
206
+ }
207
+ return pluginLoads.get(pluginId);
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------------------------
211
+ // The Svelte wrapper (same surface as packages/sdk/src/controllers.js)
212
+ // ---------------------------------------------------------------------------------------------
213
+
214
+ /**
215
+ * Wraps a controller so `.state` is a tracked getter: reading it inside an effect or a template re-runs on change.
216
+ * @param {{ get: () => any, subscribe: (run: (s:any) => void) => (() => void), actions: any }} controller
217
+ */
218
+ export function reactive(controller) {
219
+ const track = createSubscriber((update) => {
220
+ let ready = false;
221
+ // subscribe() calls back synchronously once with the current state; that is not a change
222
+ const unsubscribe = controller.subscribe(() => {
223
+ if (ready) update();
224
+ });
225
+ ready = true;
226
+ return unsubscribe;
227
+ });
228
+
229
+ return {
230
+ controller,
231
+ actions: controller.actions,
232
+ get state() {
233
+ track();
234
+ return controller.get();
235
+ },
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Registry `use` plus `reactive`; null when the controller is unavailable. An `instance` scoped controller is destroyed when the
241
+ * calling component unmounts.
242
+ * @param {string} name `<namespace>/<controller>`
243
+ * @param {{version?:number, params?:object, initial?:object, event?:any}} [opts]
244
+ */
245
+ export function useController(name, opts) {
246
+ ensureControllerHost();
247
+ const controller = registry.use(name, opts);
248
+ if (!controller) return null;
249
+
250
+ const isInstance = registry.list().find((c) => c.name === name)?.scope === 'instance';
251
+
252
+ if (isInstance && typeof window !== 'undefined') {
253
+ try {
254
+ onMount(() => () => controller.destroy());
255
+ } catch {
256
+ // called outside a component: the caller owns destroy()
257
+ }
258
+ }
259
+
260
+ return reactive(controller);
261
+ }
262
+
263
+ // `values` object (doc 02) or a svelte-i18n options object ({ values, default, ... }) are both accepted
264
+ function toI18nOptions(arg) {
265
+ if (!arg || typeof arg !== 'object') return undefined;
266
+ if ('values' in arg || 'default' in arg || 'locale' in arg || 'format' in arg) return arg;
267
+ return { values: arg };
268
+ }
269
+
270
+ /** @param {string} namespace */
271
+ export function plugin(namespace) {
272
+ const pluginId = () => registry.pluginIdOf(namespace) ?? `pano-plugin-${namespace}`;
273
+ const prefix = () => `plugins.${pluginId()}.`;
274
+ const fullName = (name) => `${namespace}/${name}`;
275
+
276
+ /** readable store of `(key, values) => string` */
277
+ const text = {
278
+ subscribe(run) {
279
+ const p = prefix();
280
+ return _.subscribe(($fn) => {
281
+ run((key, values) => $fn(`${p}${key}`, toI18nOptions(values)));
282
+ });
283
+ },
284
+ };
285
+
286
+ return {
287
+ get id() {
288
+ return pluginId();
289
+ },
290
+ namespace,
291
+ get installed() {
292
+ return registry.pluginIdOf(namespace) !== undefined;
293
+ },
294
+ _: text,
295
+ toast(key, o) {
296
+ return showToast(`${prefix()}${key}`, o?.values ?? {}, undefined, o?.variant ? { variant: o.variant } : undefined);
297
+ },
298
+ use(name, opts) {
299
+ return useController(fullName(name), opts);
300
+ },
301
+ require(name, opts) {
302
+ const c = useController(fullName(name), opts);
303
+ if (!c) throw new Error(`${fullName(name)} is not available`);
304
+ return c;
305
+ },
306
+ /** Memoised per page: shared while in flight and for 5 s (`LOAD_MEMO_MS`). */
307
+ load(name, opts) {
308
+ ensureControllerHost();
309
+ const full = fullName(name);
310
+ return memo.run(full, opts?.params, () => registry.load(full, opts));
311
+ },
312
+ };
313
+ }
package/src/define.js ADDED
@@ -0,0 +1,352 @@
1
+ // `defineWidget(tag, def, meta)` (doc 06 section 3.4): turns the module a plugin build emits for a widget view
2
+ // (`{ component, load, attrs, session }`) into a custom element.
3
+ //
4
+ // connected -> loading state -> controllers / text / session -> `load` -> `mount(component, { target, props })`
5
+ // attribute -> the props of the mounted component change
6
+ // disconnected -> `unmount`
7
+ //
8
+ // Events (bubbling, composed): `pano:ready`, `pano:error` { code }, `pano:toast` (see toasts.js), `pano:navigate` { url } (cancelable).
9
+ // States: load error -> inline message and a retry button; inactive plugin -> empty; `session: 'required'` and anonymous -> sign-in link.
10
+ // Attribute `no-shadow` renders in the light DOM (the sheets are linked in `head`).
11
+ import { mount, unmount } from './svelte-runtime.js';
12
+ import { createSubscriber } from 'svelte/reactivity';
13
+ import { getConfig, pageFetch, resolveUrl } from './config.js';
14
+ import { loadPluginControllers } from './controllers.js';
15
+ import { ensureLanguage, loadPluginTranslations, translate } from './language.js';
16
+ import { emit, registerWidget, unregisterWidget } from './runtime.js';
17
+ import { ensureSession, getSession } from './session.js';
18
+
19
+ const INACTIVE_CODES = new Set(['PLUGIN_INACTIVE', 'PLUGIN_NOT_FOUND']);
20
+
21
+ /**
22
+ * @typedef {Object} WidgetMeta
23
+ * @property {string} [ns] namespace, `data-pano-fb` of the wrapper
24
+ * @property {string} [pluginId] full plugin id (translations, controllers)
25
+ * @property {{ fallback?: string, hash?: string, icons?: string }} [styles] absolute URLs of the plugin's sheets (index.json)
26
+ * @property {string} [controllers] absolute URL of `controllers/controllers.mjs`, when the plugin has controllers
27
+ * @property {'none'|'optional'|'required'} [session] overrides the module's own value
28
+ * @property {boolean} [active] false: the plugin is inactive, the widget stays empty
29
+ */
30
+
31
+ const kebab = (name) => name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
32
+ const camel = (name) => name.replace(/-([a-z0-9])/g, (_m, c) => c.toUpperCase());
33
+
34
+ /** @param {Array<string | { name: string, type?: string }>} [attrs] */
35
+ function normalizeAttrs(attrs) {
36
+ return (attrs ?? []).map((a) => {
37
+ const name = typeof a === 'string' ? a : a.name;
38
+ return { attr: kebab(name), prop: camel(name), type: typeof a === 'string' ? 'string' : (a.type ?? 'string') };
39
+ });
40
+ }
41
+
42
+ function coerce(type, value) {
43
+ if (value === null) return type === 'boolean' ? false : undefined;
44
+ if (type === 'number') {
45
+ const n = Number(value);
46
+ return Number.isNaN(n) ? undefined : n;
47
+ }
48
+ if (type === 'boolean') return value !== 'false';
49
+ return value;
50
+ }
51
+
52
+ function sheetHref(styles) {
53
+ const href = styles?.fallback;
54
+ if (!href) return null;
55
+ return styles.hash && !href.includes('?') ? `${href}?v=${styles.hash}` : href;
56
+ }
57
+
58
+ function link(href) {
59
+ const el = document.createElement('link');
60
+ el.rel = 'stylesheet';
61
+ el.href = href;
62
+ return el;
63
+ }
64
+
65
+ function ensureHeadSheet(href) {
66
+ if (!href) return;
67
+ const exists = [...document.head.querySelectorAll('link[rel="stylesheet"]')].some((l) => l.getAttribute('href') === href);
68
+ if (!exists) document.head.append(link(href));
69
+ }
70
+
71
+ /**
72
+ * Props that Svelte reads through getters; `set` makes the dependent effects of the mounted component re-run.
73
+ * @param {Record<string, any>} initial
74
+ */
75
+ function reactiveProps(initial) {
76
+ let values = { ...initial };
77
+ /** @type {null | (() => void)} */
78
+ let notify = null;
79
+ const track = createSubscriber((update) => {
80
+ notify = update;
81
+ return () => {
82
+ notify = null;
83
+ };
84
+ });
85
+
86
+ const props = new Proxy(
87
+ {},
88
+ {
89
+ get(_t, key) {
90
+ track();
91
+ return values[/** @type {string} */ (key)];
92
+ },
93
+ has(_t, key) {
94
+ track();
95
+ return key in values;
96
+ },
97
+ ownKeys() {
98
+ track();
99
+ return Reflect.ownKeys(values);
100
+ },
101
+ getOwnPropertyDescriptor(_t, key) {
102
+ track();
103
+ return key in values ? { enumerable: true, configurable: true, writable: true, value: values[/** @type {string} */ (key)] } : undefined;
104
+ },
105
+ },
106
+ );
107
+
108
+ return {
109
+ props,
110
+ set(next) {
111
+ values = { ...next };
112
+ notify?.();
113
+ },
114
+ };
115
+ }
116
+
117
+ /**
118
+ * @param {string} tag custom element name, e.g. `pano-market-goal`
119
+ * @param {{ component: any, load?: Function, attrs?: Array<string | { name: string, type?: string }>, session?: 'none'|'optional'|'required' }} def
120
+ * @param {WidgetMeta} [meta]
121
+ * @returns {CustomElementConstructor} the element class (already registered; an existing registration is kept)
122
+ */
123
+ export function defineWidget(tag, def, meta = {}) {
124
+ const existing = customElements.get(tag);
125
+ if (existing) return existing;
126
+
127
+ const attrs = normalizeAttrs(def.attrs);
128
+ const typeOf = new Map(attrs.map((a) => [a.attr, a]));
129
+ const sessionMode = meta.session ?? def.session ?? 'none';
130
+
131
+ class PanoWidget extends HTMLElement {
132
+ static get observedAttributes() {
133
+ return attrs.map((a) => a.attr);
134
+ }
135
+
136
+ constructor() {
137
+ super();
138
+ this._gen = 0;
139
+ this._instance = null;
140
+ this._reactive = null;
141
+ this._loaded = {};
142
+ this._jsProps = {};
143
+ this._root = null;
144
+ this._container = null;
145
+ }
146
+
147
+ connectedCallback() {
148
+ registerWidget(this);
149
+ this._ensureStructure();
150
+ void this._start(false);
151
+ }
152
+
153
+ disconnectedCallback() {
154
+ this._gen += 1;
155
+ this._unmount();
156
+ unregisterWidget(this);
157
+ }
158
+
159
+ attributeChangedCallback() {
160
+ if (this._instance) this._reactive?.set(this._currentProps());
161
+ }
162
+
163
+ /** Re-runs `load` (retry button, `invalidate`); the mounted component stays until the new data is there. */
164
+ reload() {
165
+ return this._start(true);
166
+ }
167
+
168
+ get props() {
169
+ return { ...this._jsProps };
170
+ }
171
+
172
+ set props(value) {
173
+ Object.assign(this._jsProps, value ?? {});
174
+ if (this._instance) this._reactive?.set(this._currentProps());
175
+ }
176
+
177
+ _ensureStructure() {
178
+ if (this._container) return;
179
+
180
+ const shadow = !this.hasAttribute('no-shadow');
181
+ const styles = meta.styles ?? {};
182
+ const fallback = sheetHref(styles);
183
+
184
+ const container = document.createElement('div');
185
+ container.className = 'pano-fb';
186
+ container.dataset.panoFb = meta.ns ?? '';
187
+
188
+ if (shadow) {
189
+ const root = this.shadowRoot ?? this.attachShadow({ mode: 'open' });
190
+ if (fallback) root.append(link(fallback));
191
+ if (styles.icons) root.append(link(styles.icons));
192
+ root.append(container);
193
+ this._root = root;
194
+ } else {
195
+ ensureHeadSheet(fallback);
196
+ ensureHeadSheet(styles.icons);
197
+ this.append(container);
198
+ this._root = this;
199
+ }
200
+
201
+ this._container = container;
202
+ }
203
+
204
+ _attrProps() {
205
+ const out = {};
206
+ for (const { attr, prop, type } of attrs) {
207
+ const value = coerce(type, this.getAttribute(attr));
208
+ if (value !== undefined) out[prop] = value;
209
+ }
210
+ return out;
211
+ }
212
+
213
+ _currentProps() {
214
+ return { ...this._loaded, ...this._attrProps(), ...this._jsProps };
215
+ }
216
+
217
+ _setState(state) {
218
+ this.dataset.panoState = state;
219
+ }
220
+
221
+ _unmount() {
222
+ if (this._instance) {
223
+ try {
224
+ unmount(this._instance);
225
+ } catch (e) {
226
+ console.warn(`[pano-widgets] ${tag} unmount failed`, e);
227
+ }
228
+ }
229
+ this._instance = null;
230
+ this._reactive = null;
231
+ if (this._container) this._container.replaceChildren();
232
+ }
233
+
234
+ _show(state, content) {
235
+ this._unmount();
236
+ this._setState(state);
237
+ if (content) this._container.append(content);
238
+ }
239
+
240
+ _stateNode(state, role) {
241
+ const el = document.createElement('div');
242
+ el.className = 'pano-widget__state';
243
+ el.dataset.panoStateView = state;
244
+ if (role) el.setAttribute('role', role);
245
+ return el;
246
+ }
247
+
248
+ _showError(error) {
249
+ const code = error?.code ?? error?.error?.code ?? 'LOAD_FAILED';
250
+ if (INACTIVE_CODES.has(code)) {
251
+ this._show('inactive');
252
+ return;
253
+ }
254
+
255
+ const node = this._stateNode('error', 'alert');
256
+ const message = document.createElement('span');
257
+ message.textContent = translate('widgets.error', 'This content could not be loaded.');
258
+ const retry = document.createElement('button');
259
+ retry.type = 'button';
260
+ retry.dataset.panoRetry = '';
261
+ retry.textContent = translate('widgets.retry', 'Retry');
262
+ retry.addEventListener('click', () => void this.reload());
263
+ node.append(message, ' ', retry);
264
+
265
+ this._show('error', node);
266
+ emit(this, 'pano:error', { code });
267
+ }
268
+
269
+ _showSignIn() {
270
+ const node = this._stateNode('signin');
271
+ const a = document.createElement('a');
272
+ a.href = resolveUrl(getConfig().urls['auth.login'] ? 'auth.login' : '/login');
273
+ a.textContent = translate('widgets.sign-in', 'Sign in');
274
+ node.append(a);
275
+ this._show('signin', node);
276
+ }
277
+
278
+ async _start(soft) {
279
+ const gen = (this._gen += 1);
280
+ const stale = () => gen !== this._gen;
281
+
282
+ if (meta.active === false) {
283
+ this._show('inactive');
284
+ return;
285
+ }
286
+
287
+ if (!soft || !this._instance) {
288
+ this._show('loading', this._stateNode('loading'));
289
+ this._container.firstChild?.setAttribute('aria-busy', 'true');
290
+ }
291
+
292
+ try {
293
+ if (sessionMode !== 'none') {
294
+ await ensureSession();
295
+ if (stale()) return;
296
+ if (sessionMode === 'required' && !getSession().user) {
297
+ this._showSignIn();
298
+ return;
299
+ }
300
+ }
301
+
302
+ await Promise.all([
303
+ meta.pluginId && meta.controllers
304
+ ? loadPluginControllers({ pluginId: meta.pluginId, ns: meta.ns ?? '', url: meta.controllers })
305
+ : null,
306
+ ensureLanguage().then(() => (meta.pluginId ? loadPluginTranslations(meta.pluginId) : null)),
307
+ ]);
308
+ if (stale()) return;
309
+
310
+ const attrProps = this._attrProps();
311
+ const loaded =
312
+ typeof def.load === 'function'
313
+ ? await def.load({ fetch: (...a) => pageFetch(...a), params: attrProps, url: new URL(globalThis.location.href), widget: true }, attrProps)
314
+ : {};
315
+ if (stale()) return;
316
+
317
+ this._loaded = loaded && typeof loaded === 'object' ? loaded : {};
318
+
319
+ if (this._instance) {
320
+ this._reactive?.set(this._currentProps());
321
+ return;
322
+ }
323
+
324
+ this._unmount();
325
+ this._reactive = reactiveProps(this._currentProps());
326
+ this._instance = mount(def.component, { target: this._container, props: this._reactive.props });
327
+ this._setState('ready');
328
+ emit(this, 'pano:ready', { tag });
329
+ } catch (error) {
330
+ if (stale()) return;
331
+ this._showError(error);
332
+ }
333
+ }
334
+ }
335
+
336
+ // JS properties for the declared attributes (`el.goalId = 3`); other props go through `el.props = { ... }`
337
+ for (const { attr, prop } of attrs) {
338
+ Object.defineProperty(PanoWidget.prototype, prop, {
339
+ configurable: true,
340
+ get() {
341
+ return prop in this._jsProps ? this._jsProps[prop] : coerce(typeOf.get(attr).type, this.getAttribute(attr));
342
+ },
343
+ set(value) {
344
+ this._jsProps[prop] = value;
345
+ if (this._instance) this._reactive?.set(this._currentProps());
346
+ },
347
+ });
348
+ }
349
+
350
+ customElements.define(tag, PanoWidget);
351
+ return PanoWidget;
352
+ }
package/src/index.js ADDED
@@ -0,0 +1,38 @@
1
+ // `@panomc/widget-host` (doc 06 section 3.2): the `@panomc/sdk` facade for a widget page, plus the wrapper and the page API.
2
+ // The module files beside this one stand in for the other SDK specifiers; `SPECIFIER_MODULES` says which is which.
3
+ import { createViewProxy } from './views.js';
4
+
5
+ export { getPanoContext, setPanoContext } from './context.js';
6
+ export { PanoPlugin } from './plugin.js';
7
+ export { viewComponent } from './component.js';
8
+
9
+ export { defineWidget } from './define.js';
10
+ export { configure, getConfig, resolveUrl } from './config.js';
11
+ export { ensureSession, getSession, setSession } from './session.js';
12
+ export { ensureLanguage, loadPluginTranslations } from './language.js';
13
+ export { loadPluginControllers, createWidgetHost, createLoadMemo, clearLoadMemo, LOAD_MEMO_MS } from './controllers.js';
14
+ export { WidgetError } from './runtime.js';
15
+ export { createViewProxy };
16
+
17
+ /**
18
+ * SDK specifier -> file in this package that replaces it in a widget bundle (the aliases of the widget build target).
19
+ * Every key of `@panomc/sdk`'s `exports` that is a facade is listed; `@panomc/sdk/build/*` and `core/*` are not facades.
20
+ */
21
+ export const SPECIFIER_MODULES = Object.freeze({
22
+ '@panomc/sdk': 'index.js',
23
+ '@panomc/sdk/svelte': 'svelte.js',
24
+ '@panomc/sdk/views': 'views.js',
25
+ '@panomc/sdk/controllers': 'controllers.js',
26
+ '@panomc/sdk/toasts': 'toasts.js',
27
+ '@panomc/sdk/internal': 'internal.js',
28
+ '@panomc/sdk/variables': 'variables.js',
29
+ '@panomc/sdk/components/theme': 'components/index.js',
30
+ '@panomc/sdk/components/panel': 'components/panel.js',
31
+ '@panomc/sdk/utils/api': 'api.js',
32
+ '@panomc/sdk/utils/auth': 'auth.js',
33
+ '@panomc/sdk/utils/tooltip': 'tooltip.js',
34
+ '@panomc/sdk/utils/language': 'language.js',
35
+ '@panomc/sdk/utils/component': 'component.js',
36
+ '@panomc/sdk/utils/text': 'text.js',
37
+ '@panomc/sdk/utils/route': 'route.js',
38
+ });
@@ -0,0 +1,2 @@
1
+ // `@panomc/sdk/internal` in a widget.
2
+ export { getPanoContext, setPanoContext } from './context.js';