@wix/origami-site 1.0.61 → 1.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/origami-site",
3
- "version": "1.0.61",
3
+ "version": "1.1.0",
4
4
  "description": "Runs an exported Wix origami site: file-based routing, Wix dynamic pages, popups and build checks. Use with @wix/origami-site-astro or @wix/origami-site-express.",
5
5
  "type": "module",
6
6
  "files": [
@@ -46,13 +46,13 @@
46
46
  }
47
47
  },
48
48
  "dependencies": {
49
- "@wix/origami-types": "1.4.6",
49
+ "@wix/origami-types": "^1.5.0",
50
50
  "@wix/builder-error-pages": "^1.1.6",
51
- "@wix/origami-transforms": "0.1.64",
51
+ "@wix/origami-transforms": "^0.1.66",
52
52
  "@babel/parser": "^7.25.0",
53
- "@wix/origami-services": "1.2.9",
53
+ "@wix/origami-services": "^1.3.0",
54
54
  "@wix/services-manager-react": "^1.0.8",
55
- "@wix/origami-bi": "0.24.0"
55
+ "@wix/origami-bi": "^0.24.1"
56
56
  },
57
57
  "exports": {
58
58
  "./server": {
@@ -93,5 +93,5 @@
93
93
  "optional": true
94
94
  }
95
95
  },
96
- "falconPackageHash": "553539db931022bfa26d3b9a4439e16c8707ce7b73db2af9f8f0aac8"
96
+ "falconPackageHash": "853798bbb8b1cb95d8f867ecc4487657e8e848d9eb0c44b0598415a3"
97
97
  }
@@ -1,32 +1,39 @@
1
- import { createElement, useEffect, useRef, useSyncExternalStore } from 'react'
2
- import { closePopup, getOpenPopup, subscribe } from '../popups/runtime.js'
3
- import './popup.css'
1
+ import { createElement, useLayoutEffect, useRef, useSyncExternalStore } from 'react'
2
+ import { closePopup, currentPopup, popup, subscribe } from '../popups/controller.js'
3
+ import './popups.css'
4
4
 
5
- /** The open popup, in a modal `<dialog>`: the popup's own PopupContainer draws the overlay and locks the scroll. ESC
6
- * and a native close go through `closePopup`, so the URL follows. */
5
+ /** Renders the open popup in a modal `<dialog>`, and nothing while none is open. It sits inside #main_MF, so the
6
+ * popup shares the page's services and container-query root. The popup's PopupContainer draws the overlay. */
7
7
  export function PopupHost() {
8
- const open = useSyncExternalStore(subscribe, getOpenPopup)
9
- const dialog = useRef(/** @type {HTMLDialogElement | null} */ (null))
10
- useEffect(() => {
11
- const element = dialog.current
12
- if (open && !element?.open) element?.showModal()
13
- if (!open && element?.open) element.close()
14
- }, [open])
15
- return createElement(
16
- 'dialog',
17
- {
18
- ref: dialog,
19
- className: 'origami-popup',
20
- /** @param {Event} event */
21
- onCancel: event => {
22
- event.preventDefault()
23
- closePopup()
24
- },
25
- // A popup can also close the dialog itself, with `<form method="dialog">` or `dialog.close()`.
26
- onClose: () => {
27
- if (getOpenPopup()) closePopup()
28
- },
29
- },
30
- open ? createElement(open.Component, { key: open.seoUri }) : null
31
- )
8
+ const open = useSyncExternalStore(subscribe, currentPopup)
9
+ const loaded = open && popup(open.seoUri)
10
+ if (!open || !loaded) return null
11
+ // Keyed by popup, so a popup that replaces another gets a fresh dialog and fresh state.
12
+ return createElement(PopupDialog, { key: open.seoUri, title: loaded.title }, createElement(loaded.Popup))
13
+ }
14
+
15
+ /** @param {{ title: string, children: import('react').ReactNode }} props */
16
+ function PopupDialog({ title, children }) {
17
+ const ref = useRef(/** @type {HTMLDialogElement | null} */ (null))
18
+ useLayoutEffect(() => {
19
+ const dialog = ref.current
20
+ if (!dialog) return
21
+ // The popup's content can also close the dialog itself (`form method="dialog"`, `dialog.close()`): the controller
22
+ // follows. The browser fires close in a later task, so a close() of our own reaches a listener only if the dialog
23
+ // is still mounted: StrictMode's remount, which has reopened it by then. A replaced dialog's listener is gone.
24
+ const onClose = () => { if (!dialog.open) closePopup() }
25
+ dialog.addEventListener('close', onClose)
26
+ dialog.showModal()
27
+ return () => {
28
+ dialog.removeEventListener('close', onClose)
29
+ if (dialog.open) dialog.close()
30
+ }
31
+ }, [])
32
+ // ESC fires cancel: the controller closes the popup, not the browser.
33
+ /** @param {Event} event */
34
+ const onCancel = event => {
35
+ event.preventDefault()
36
+ closePopup()
37
+ }
38
+ return createElement('dialog', { ref, className: 'origami-popup', 'aria-label': title, onCancel }, children)
32
39
  }
@@ -1,14 +1,13 @@
1
1
  import type { PageData } from '../server/index.js'
2
2
  import type { ComponentType } from 'react'
3
- import type { ServicesConfigs } from '@wix/origami-services'
4
3
 
5
4
  export type PageModule = { default: ComponentType }
6
5
  export type MountPageOptions = {
7
6
  pages: Record<string, () => Promise<PageModule>>
8
- popups: Record<string, () => Promise<unknown>>
7
+ /** By seoUri. Every popup loads before the page renders, so its services register in time. */
8
+ popups: Record<string, { title: string; load: () => Promise<PageModule> }>
9
+ /** Popup page id → seoUri, for the lightbox services' `open({ pageId })`. */
9
10
  seoUriByPageId: Record<string, string>
10
- /** Each popup's DM servicesConfigs module, by seoUri. A site exported before it has none. */
11
- popupServicesConfigs?: Record<string, () => Promise<{ default: ServicesConfigs }>>
12
11
  beforeMount: () => Promise<unknown>
13
12
  /** The site's meta site id, from `VITE_WIX_METASITE_ID`. Services get no site identity without it. */
14
13
  siteId?: string
@@ -3,7 +3,7 @@ import { createRoot } from 'react-dom/client'
3
3
  import { registeredServicesConfigs, sealServicesConfigs } from '@wix/origami-services/internal'
4
4
  import { servicesMap } from '@wix/origami-services'
5
5
  import { WixServices } from '@wix/services-manager-react'
6
- import { lightboxConfig, openPopup, popupOfUrl, setSitePopups, syncWithUrl } from '../popups/runtime.js'
6
+ import { lightboxConfig, openPopup, popup, setPopups, startPopups } from '../popups/controller.js'
7
7
  import { PopupHost } from './PopupHost.js'
8
8
 
9
9
  let hasReadPageData = false
@@ -37,7 +37,7 @@ export function readPageData() {
37
37
  * @param {import('./index.js').MountPageOptions} options
38
38
  * @returns {Promise<() => void>}
39
39
  */
40
- export async function mountPage(element, { pages, popups = {}, seoUriByPageId = {}, popupServicesConfigs = {}, beforeMount, siteId }) {
40
+ export async function mountPage(element, { pages, popups = {}, seoUriByPageId = {}, beforeMount, siteId }) {
41
41
  if (!element) throw new Error('Cannot mount page: root element is missing')
42
42
  const data = readPageData()
43
43
  const pageKey = data?.page
@@ -53,47 +53,60 @@ export async function mountPage(element, { pages, popups = {}, seoUriByPageId =
53
53
  } catch (error) {
54
54
  console.error(error)
55
55
  }
56
- // Loading the page registers its globals and own DM configs before services are created. A popup's code loads on
57
- // first open, too late for its configs, so they load now, in folder-name order, and merge first: the page's global
58
- // components and the page itself win over them.
59
- const [{ default: Page }, popupConfigs] = await Promise.all([
60
- loadPage(),
61
- Promise.all(Object.keys(popupServicesConfigs).sort().map(async seoUri => (await popupServicesConfigs[seoUri]()).default)),
62
- ])
56
+ // Loading the popups and then the page registers their globals, services and own DM configs before services are
57
+ // created, so a popup's services work on first open. The page registers last, so its own configs win.
63
58
  const hasPopups = Object.keys(popups).length > 0
64
- setSitePopups(popups, seoUriByPageId)
59
+ setPopups(await loadPopups(popups), seoUriByPageId)
60
+ const { default: Page } = await loadPage()
61
+ // Without popups, the lightbox service keeps its mock and nothing listens for ?popup=.
65
62
  const requestConfigs = { ...data?.services, ...(hasPopups ? { '@wix/site-service-lightbox': lightboxConfig } : {}) }
66
63
  const map = servicesMap({
67
- servicesConfigs: [...popupConfigs, ...registeredServicesConfigs()], requestConfigs, url: location.href, siteId,
64
+ servicesConfigs: registeredServicesConfigs(), requestConfigs, url: location.href, siteId,
68
65
  userAgent: navigator.userAgent, reducedMotion: globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
69
66
  })
70
67
  sealServicesConfigs()
71
68
  const root = createRoot(element)
72
69
  // #main_MF is the container-query root: editor-components' `--one-unit: 1cqw` resolves against it.
73
- const main = createElement('div', { key: 'main', id: 'main_MF', style: { containerType: 'inline-size' } }, createElement(Page))
74
- // PopupHost is inside WixServices, so popups share the page's services.
75
- const children = hasPopups ? [main, createElement(PopupHost, { key: 'popups' })] : main
76
- root.render(createElement(StrictMode, null, createElement(WixServices, { servicesMap: map, children })))
70
+ // PopupHost sits inside it too, so popups share the page's services and container-query root.
71
+ const main = createElement('div', { id: 'main_MF', style: { containerType: 'inline-size' } },
72
+ createElement(Page), hasPopups ? createElement(PopupHost) : null)
73
+ root.render(createElement(StrictMode, null, createElement(WixServices, { servicesMap: map, children: main })))
77
74
  if (!hasPopups) return () => root.unmount()
78
- syncWithUrl()
75
+ startPopups()
79
76
  document.addEventListener('click', onPopupLinkClick)
80
- window.addEventListener('popstate', syncWithUrl)
81
77
  return () => {
82
78
  document.removeEventListener('click', onPopupLinkClick)
83
- window.removeEventListener('popstate', syncWithUrl)
84
79
  root.unmount()
85
80
  }
86
81
  }
87
82
 
88
- /** A plain click on a link to this page with `?popup=` opens the popup in a new history entry instead of loading the
89
- * page again. @param {MouseEvent} event */
83
+ /** A plain click on a link to this page with `?popup=` opens the popup over it instead of loading the page again.
84
+ * The URL doesn't change. @param {MouseEvent} event */
90
85
  function onPopupLinkClick(event) {
91
86
  if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
92
87
  const link = event.target instanceof Element ? event.target.closest('a[href]') : null
93
88
  if (!(link instanceof HTMLAnchorElement) || (link.target && link.target !== '_self')) return
94
89
  const url = new URL(link.href)
95
- const seoUri = popupOfUrl(link.href)
96
- if (!seoUri || url.origin !== location.origin || url.pathname !== location.pathname) return
90
+ const seoUri = url.searchParams.get('popup')
91
+ if (!seoUri || !popup(seoUri) || url.origin !== location.origin || url.pathname !== location.pathname) return
97
92
  event.preventDefault()
98
- void openPopup(seoUri, { history: 'push' })
93
+ void openPopup(seoUri)
94
+ }
95
+
96
+ /** A popup that fails to load is left out, so the page still renders. Popups load one after another: each registers its
97
+ * configs when its module evaluates and later configs win, so loading them together would let the network pick the order.
98
+ * @param {import('./index.js').MountPageOptions['popups']} popups
99
+ * @returns {Promise<Record<string, import('../popups/controller.js').LoadedPopup>>}
100
+ */
101
+ async function loadPopups(popups) {
102
+ /** @type {Record<string, import('../popups/controller.js').LoadedPopup>} */
103
+ const loaded = {}
104
+ for (const [seoUri, { title, load }] of Object.entries(popups)) {
105
+ try {
106
+ loaded[seoUri] = { title, Popup: (await load()).default }
107
+ } catch (error) {
108
+ console.error(`Cannot load popup ${seoUri}:`, error)
109
+ }
110
+ }
111
+ return loaded
99
112
  }
@@ -0,0 +1,25 @@
1
+ /* The popup layer: fixed, full viewport, one grid cell, as Thunderbolt's ResponsivePopupPage lightbox layer.
2
+ PopupContainer centers itself in the cell and draws the overlay, so the dialog and its backdrop draw nothing. */
3
+ dialog.origami-popup {
4
+ position: fixed;
5
+ inset: 0;
6
+ width: 100%;
7
+ height: 100%;
8
+ max-width: none;
9
+ max-height: none;
10
+ margin: 0;
11
+ padding: 0;
12
+ border: 0;
13
+ background: transparent;
14
+ color: inherit;
15
+ overflow: auto;
16
+ /* Exported sites have no Wix ads bar; PopupContainer's overlay offsets by it. */
17
+ --wix-ads-height: 0px;
18
+ }
19
+ dialog.origami-popup[open] {
20
+ display: grid;
21
+ grid-template: 1fr / 1fr;
22
+ }
23
+ dialog.origami-popup::backdrop {
24
+ background: transparent;
25
+ }
@@ -12,14 +12,10 @@ function moduleSource(table) {
12
12
  return ` [${JSON.stringify(page.key)}]: () => import(${JSON.stringify(entry)})`
13
13
  })
14
14
  const popups = table.popups.map(popup =>
15
- ` [${JSON.stringify(popup.seoUri)}]: () => import(${JSON.stringify(`/src/${popup.itemPath}/_generated/index.jsx`)})`)
15
+ ` [${JSON.stringify(popup.seoUri)}]: { title: ${JSON.stringify(popup.title)}, load: () => import(${JSON.stringify(`/src/${popup.itemPath}/_generated/index.jsx`)}) }`)
16
16
  // lightbox.open({ pageId }) names a popup by its Wix page id, as a Wix Forms form stores it.
17
17
  const seoUriByPageId = Object.fromEntries(table.popups.flatMap(popup => (popup.pageId ? [[popup.pageId, popup.seoUri]] : [])))
18
- // A popup's DM configs must be in the services before they are created, so mountPage loads them before its code.
19
- const popupServicesConfigs = table.popups.flatMap(popup => popup.servicesConfigsPath
20
- ? [` [${JSON.stringify(popup.seoUri)}]: () => import(${JSON.stringify(`/src/${popup.servicesConfigsPath}`)})`]
21
- : [])
22
- return `export const pages = {\n${entries.join(',\n')}\n};\nexport const popups = {\n${popups.join(',\n')}\n};\nexport const seoUriByPageId = ${JSON.stringify(seoUriByPageId)};\nexport const popupServicesConfigs = {\n${popupServicesConfigs.join(',\n')}\n};\n`
18
+ return `export const pages = {\n${entries.join(',\n')}\n};\nexport const popups = {\n${popups.join(',\n')}\n};\nexport const seoUriByPageId = ${JSON.stringify(seoUriByPageId)};\n`
23
19
  }
24
20
 
25
21
  /** @param {import('./index.js').OrigamiVitePluginsOptions['siteTree']} siteTree
@@ -0,0 +1,69 @@
1
+ // The one place that knows which popup is open. The lightbox service, `?popup=`, links and user code all open and close
2
+ // popups here, and PopupHost renders what it says. A module singleton, since most callers sit outside React.
3
+
4
+ /** @typedef {{ title: string, Popup: import('react').ComponentType }} LoadedPopup */
5
+ /** @typedef {{ seoUri: string, payload: unknown }} OpenPopup */
6
+
7
+ /** @type {Record<string, LoadedPopup>} */
8
+ let popups = {}
9
+ /** @type {Record<string, string>} */
10
+ let seoUriByPageId = {}
11
+ /** @type {OpenPopup | null} */
12
+ let current = null
13
+ /** @type {Set<() => void>} */
14
+ const listeners = new Set()
15
+
16
+ /** @param {Record<string, LoadedPopup>} loaded @param {Record<string, string>} byPageId */
17
+ export function setPopups(loaded, byPageId) {
18
+ popups = loaded
19
+ seoUriByPageId = byPageId
20
+ }
21
+
22
+ /** @param {string} seoUri */
23
+ export const popup = seoUri => (Object.hasOwn(popups, seoUri) ? popups[seoUri] : undefined)
24
+
25
+ /** One popup at a time: opening another replaces it, and opening the open one only replaces its payload.
26
+ * @param {string} seoUri
27
+ * @param {{ payload?: unknown }} [options]
28
+ */
29
+ export async function openPopup(seoUri, { payload } = {}) {
30
+ if (!popup(seoUri)) throw new Error(`No popup named "${seoUri}"`)
31
+ current = { seoUri, payload }
32
+ notify()
33
+ }
34
+
35
+ export function closePopup() {
36
+ if (!current) return
37
+ current = null
38
+ notify()
39
+ }
40
+
41
+ export const currentPopup = () => current
42
+
43
+ /** @param {() => void} listener */
44
+ export function subscribe(listener) {
45
+ listeners.add(listener)
46
+ return () => { listeners.delete(listener) }
47
+ }
48
+
49
+ function notify() {
50
+ for (const listener of listeners) listener()
51
+ }
52
+
53
+ /** The `@wix/site-service-lightbox` config: it forwards to this controller, by slug or by the deprecated page id. */
54
+ export const lightboxConfig = {
55
+ /** @param {{ slug?: string, pageId?: string, payload?: unknown }} options */
56
+ open: ({ slug, pageId, payload }) => {
57
+ if (slug !== undefined || pageId === undefined) return openPopup(String(slug), { payload })
58
+ if (!Object.hasOwn(seoUriByPageId, pageId)) return Promise.reject(new Error(`No popup with page id "${pageId}"`))
59
+ return openPopup(seoUriByPageId[pageId], { payload })
60
+ },
61
+ close: closePopup,
62
+ getPayload: () => current?.payload,
63
+ }
64
+
65
+ /** Opens the popup a `?popup=<seoUri>` URL names, right away and every time. Opening never changes the URL. */
66
+ export function startPopups() {
67
+ const seoUri = new URL(location.href).searchParams.get('popup')
68
+ if (seoUri) openPopup(seoUri).catch(error => console.warn(`Cannot open ?popup=${seoUri}:`, error))
69
+ }
@@ -1,10 +1,6 @@
1
- export type OpenPopupOptions = {
2
- /** How the URL gets `?popup=`: a new entry (`push`, as a link click), the current one (`replace`), or not at all (`none`). */
3
- history?: 'push' | 'replace' | 'none'
4
- /** What the popup reads with the lightbox service's `getPayload()`. */
5
- payload?: unknown
6
- }
7
- /** Opens the popup in `src/popups/<seoUri>`, replacing an open one. */
8
- export function openPopup(seoUri: string, options?: OpenPopupOptions): Promise<void>
9
- /** Closes the open popup, if any, and cancels one still opening. */
1
+ /** Opens the popup in `src/popups/<seoUri>/` over the current page, replacing any open popup, without changing the
2
+ * URL. Components inside it read `payload` with the lightbox service's `getPayload()`. Rejects when no popup has
3
+ * that name. */
4
+ export function openPopup(seoUri: string, options?: { payload?: unknown }): Promise<void>
5
+ /** Closes the open popup, if any. */
10
6
  export function closePopup(): void
@@ -1 +1 @@
1
- export { openPopup, closePopup } from './runtime.js'
1
+ export { openPopup, closePopup } from './controller.js'
@@ -25,7 +25,8 @@ const readMetadata = structure => {
25
25
  // Walk Babel's AST without a runtime dependency on @babel/types.
26
26
  const visit = node => {
27
27
  if (!node || typeof node !== 'object') return
28
- if (node.type === 'JSXOpeningElement' && node.name.type === 'JSXIdentifier' && node.name.name === 'Page') {
28
+ // A page's root is <Page>, a popup's <PopupRoot>.
29
+ if (node.type === 'JSXOpeningElement' && node.name.type === 'JSXIdentifier' && ['Page', 'PopupRoot'].includes(node.name.name)) {
29
30
  for (const attribute of node.attributes) {
30
31
  if (attribute.type !== 'JSXAttribute') continue
31
32
  if (attribute.name.name === 'id' && attribute.value?.type === 'StringLiteral' && metadata.pageId === undefined)
@@ -207,7 +208,6 @@ function readPopups(src) {
207
208
  return items.map(itemPath => {
208
209
  const seoUri = basename(itemPath)
209
210
  const { title, pageId } = pageMetadata(resolve(src, itemPath))
210
- const servicesConfigsPath = ['index.ts', 'index.js'].map(file => `${itemPath}/servicesConfigs/${file}`).find(path => existsSync(resolve(src, path)))
211
- return { key: itemPath, seoUri, itemPath, title: title ?? seoUri, ...(pageId ? { pageId } : {}), ...(servicesConfigsPath ? { servicesConfigsPath } : {}) }
211
+ return { key: itemPath, seoUri, itemPath, title: title ?? seoUri, ...(pageId ? { pageId } : {}) }
212
212
  })
213
213
  }
package/src/styles.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  // The copied 404 entry imports the package's stylesheet as a bundler side effect.
2
2
  declare module '@wix/builder-error-pages/style.css'
3
- // PopupHost imports the popup dialog's stylesheet the same way.
3
+ // PopupHost imports its own stylesheet the same way.
4
4
  declare module '*.css'
@@ -1,17 +0,0 @@
1
- /* The runtime's popup dialog covers the screen and draws nothing: the popup's PopupContainer has the overlay. */
2
- dialog.origami-popup {
3
- position: fixed;
4
- inset: 0;
5
- width: 100%;
6
- height: 100%;
7
- max-width: none;
8
- max-height: none;
9
- margin: 0;
10
- padding: 0;
11
- border: 0;
12
- background: transparent;
13
- overflow: auto;
14
- }
15
- dialog.origami-popup::backdrop {
16
- background: transparent;
17
- }
@@ -1,110 +0,0 @@
1
- // The open popup, which PopupHost renders, and how its URL got there. One popup at a time: opening one replaces the
2
- // open one. Every open and close takes a new sequence number, so an open still waiting for its import gives up once
3
- // another open or a close came after it.
4
-
5
- /** @typedef {import('./index.js').OpenPopupOptions} OpenPopupOptions */
6
- /** @typedef {{ seoUri: string, Component: import('react').ComponentType, payload: unknown }} OpenPopup */
7
-
8
- const PARAM = 'popup'
9
-
10
- /** @type {Record<string, () => Promise<{ default: import('react').ComponentType }>>} */
11
- let popups = {}
12
- /** @type {Record<string, string>} */
13
- let seoUriByPageId = {}
14
- /** @type {OpenPopup | undefined} */
15
- let open
16
- // Whether opening the popup pushed a history entry, which closing it then goes back from.
17
- let pushed = false
18
- let sequence = 0
19
- // Whether the open still waiting for its import came from the URL (a link or Back), which Back then cancels.
20
- let pendingFromUrl = false
21
- /** @type {Set<() => void>} */
22
- const listeners = new Set()
23
-
24
- /** @param {OpenPopup | undefined} next */
25
- const setOpen = next => {
26
- open = next
27
- for (const listener of listeners) listener()
28
- }
29
-
30
- /** @param {() => void} listener */
31
- export const subscribe = listener => {
32
- listeners.add(listener)
33
- return () => { listeners.delete(listener) }
34
- }
35
-
36
- export const getOpenPopup = () => open
37
-
38
- /** The `?popup=` of a URL, or undefined. @param {string} href */
39
- export const popupOfUrl = href => new URL(href).searchParams.get(PARAM) ?? undefined
40
-
41
- /** @param {string | undefined} seoUri */
42
- const urlWith = seoUri => {
43
- const url = new URL(location.href)
44
- if (seoUri) url.searchParams.set(PARAM, seoUri)
45
- else url.searchParams.delete(PARAM)
46
- return url.href
47
- }
48
-
49
- /** @param {typeof popups} sitePopups @param {typeof seoUriByPageId} siteSeoUriByPageId */
50
- export const setSitePopups = (sitePopups, siteSeoUriByPageId) => {
51
- popups = sitePopups
52
- seoUriByPageId = siteSeoUriByPageId
53
- }
54
-
55
- /** @param {string} seoUri @param {OpenPopupOptions} [options] */
56
- export async function openPopup(seoUri, { history: requested = 'replace', payload } = {}) {
57
- const load = Object.hasOwn(popups, seoUri) ? popups[seoUri] : undefined
58
- if (!load) return console.warn(`No popup "${seoUri}" in src/popups.`)
59
- const id = ++sequence
60
- pendingFromUrl = requested !== 'replace'
61
- const { default: Component } = await load()
62
- if (id !== sequence) return
63
- pendingFromUrl = false
64
- // A link in an open popup replaces it in its entry, so closing goes back past both, and a URL that already names
65
- // the popup stays as it is.
66
- const history = popupOfUrl(location.href) === seoUri ? 'none' : requested === 'push' && open ? 'replace' : requested
67
- if (history === 'push') {
68
- window.history.pushState(window.history.state, '', urlWith(seoUri))
69
- pushed = true
70
- } else if (history === 'replace') window.history.replaceState(window.history.state, '', urlWith(seoUri))
71
- setOpen({ seoUri, Component, payload })
72
- }
73
-
74
- /** Closes the open popup, if any, and cancels one still opening. */
75
- export function closePopup() {
76
- sequence++
77
- if (!open) return
78
- const wasPushed = pushed
79
- pushed = false
80
- setOpen(undefined)
81
- if (wasPushed) window.history.back()
82
- else window.history.replaceState(window.history.state, '', urlWith(undefined))
83
- }
84
-
85
- /** Back or Forward: shows the popup the URL names, without touching history again. */
86
- export const syncWithUrl = () => {
87
- const seoUri = popupOfUrl(location.href)
88
- if (seoUri && seoUri !== open?.seoUri) return void openPopup(seoUri, { history: 'none' })
89
- // Back to the popup already shown, or to no popup: an open the URL started is no longer what it names.
90
- if (pendingFromUrl || (!seoUri && open)) sequence++
91
- pendingFromUrl = false
92
- if (!seoUri && open) {
93
- pushed = false
94
- setOpen(undefined)
95
- }
96
- }
97
-
98
- /** The `@wix/site-service-lightbox` config: every way of opening a popup takes `openPopup`. Its `open` rejects when no
99
- * popup has the slug or page id, as the service's contract says. */
100
- export const lightboxConfig = {
101
- /** @param {{ slug?: string, pageId?: string, payload?: unknown }} options */
102
- open: async ({ slug, pageId, payload }) => {
103
- const seoUri = slug ?? (pageId !== undefined && Object.hasOwn(seoUriByPageId, pageId) ? seoUriByPageId[pageId] : undefined)
104
- if (seoUri === undefined || !Object.hasOwn(popups, seoUri))
105
- throw new Error(slug === undefined ? `No popup with page id "${pageId}" in src/popups.` : `No popup "${slug}" in src/popups.`)
106
- await openPopup(seoUri, { payload })
107
- },
108
- close: closePopup,
109
- getPayload: () => open?.payload,
110
- }