@wix/origami-site 1.0.59 → 1.0.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/origami-site",
3
- "version": "1.0.59",
3
+ "version": "1.0.61",
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,9 +46,9 @@
46
46
  }
47
47
  },
48
48
  "dependencies": {
49
- "@wix/origami-types": "1.4.5",
49
+ "@wix/origami-types": "1.4.6",
50
50
  "@wix/builder-error-pages": "^1.1.6",
51
- "@wix/origami-transforms": "0.1.62",
51
+ "@wix/origami-transforms": "0.1.64",
52
52
  "@babel/parser": "^7.25.0",
53
53
  "@wix/origami-services": "1.2.9",
54
54
  "@wix/services-manager-react": "^1.0.8",
@@ -93,5 +93,5 @@
93
93
  "optional": true
94
94
  }
95
95
  },
96
- "falconPackageHash": "5eb4888fb584dfc9ea7859f4954a0d69efbe6783ed782be5ce9e6b37"
96
+ "falconPackageHash": "553539db931022bfa26d3b9a4439e16c8707ce7b73db2af9f8f0aac8"
97
97
  }
@@ -0,0 +1,32 @@
1
+ import { createElement, useEffect, useRef, useSyncExternalStore } from 'react'
2
+ import { closePopup, getOpenPopup, subscribe } from '../popups/runtime.js'
3
+ import './popup.css'
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. */
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
+ )
32
+ }
@@ -1,11 +1,14 @@
1
1
  import type { PageData } from '../server/index.js'
2
2
  import type { ComponentType } from 'react'
3
+ import type { ServicesConfigs } from '@wix/origami-services'
3
4
 
4
5
  export type PageModule = { default: ComponentType }
5
6
  export type MountPageOptions = {
6
7
  pages: Record<string, () => Promise<PageModule>>
7
8
  popups: Record<string, () => Promise<unknown>>
8
9
  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 }>>
9
12
  beforeMount: () => Promise<unknown>
10
13
  /** The site's meta site id, from `VITE_WIX_METASITE_ID`. Services get no site identity without it. */
11
14
  siteId?: string
@@ -3,6 +3,8 @@ 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'
7
+ import { PopupHost } from './PopupHost.js'
6
8
 
7
9
  let hasReadPageData = false
8
10
  /** @type {import('../server/index.js').PageData | undefined} */
@@ -35,7 +37,7 @@ export function readPageData() {
35
37
  * @param {import('./index.js').MountPageOptions} options
36
38
  * @returns {Promise<() => void>}
37
39
  */
38
- export async function mountPage(element, { pages, beforeMount, siteId }) {
40
+ export async function mountPage(element, { pages, popups = {}, seoUriByPageId = {}, popupServicesConfigs = {}, beforeMount, siteId }) {
39
41
  if (!element) throw new Error('Cannot mount page: root element is missing')
40
42
  const data = readPageData()
41
43
  const pageKey = data?.page
@@ -51,17 +53,47 @@ export async function mountPage(element, { pages, beforeMount, siteId }) {
51
53
  } catch (error) {
52
54
  console.error(error)
53
55
  }
54
- // Loading the page registers its globals and own DM configs before services are created.
55
- const { default: Page } = await loadPage()
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
+ ])
63
+ const hasPopups = Object.keys(popups).length > 0
64
+ setSitePopups(popups, seoUriByPageId)
65
+ const requestConfigs = { ...data?.services, ...(hasPopups ? { '@wix/site-service-lightbox': lightboxConfig } : {}) }
56
66
  const map = servicesMap({
57
- servicesConfigs: registeredServicesConfigs(), requestConfigs: data?.services ?? {}, url: location.href, siteId,
67
+ servicesConfigs: [...popupConfigs, ...registeredServicesConfigs()], requestConfigs, url: location.href, siteId,
58
68
  userAgent: navigator.userAgent, reducedMotion: globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
59
69
  })
60
70
  sealServicesConfigs()
61
71
  const root = createRoot(element)
62
72
  // #main_MF is the container-query root: editor-components' `--one-unit: 1cqw` resolves against it.
63
- const main = createElement('div', { id: 'main_MF', style: { containerType: 'inline-size' } }, createElement(Page))
64
- // Stage 3: PopupHost belongs inside WixServices so popups share page services.
65
- root.render(createElement(StrictMode, null, createElement(WixServices, { servicesMap: map, children: main })))
66
- return () => root.unmount()
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 })))
77
+ if (!hasPopups) return () => root.unmount()
78
+ syncWithUrl()
79
+ document.addEventListener('click', onPopupLinkClick)
80
+ window.addEventListener('popstate', syncWithUrl)
81
+ return () => {
82
+ document.removeEventListener('click', onPopupLinkClick)
83
+ window.removeEventListener('popstate', syncWithUrl)
84
+ root.unmount()
85
+ }
86
+ }
87
+
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 */
90
+ function onPopupLinkClick(event) {
91
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
92
+ const link = event.target instanceof Element ? event.target.closest('a[href]') : null
93
+ if (!(link instanceof HTMLAnchorElement) || (link.target && link.target !== '_self')) return
94
+ const url = new URL(link.href)
95
+ const seoUri = popupOfUrl(link.href)
96
+ if (!seoUri || url.origin !== location.origin || url.pathname !== location.pathname) return
97
+ event.preventDefault()
98
+ void openPopup(seoUri, { history: 'push' })
67
99
  }
@@ -0,0 +1,17 @@
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
+ }
@@ -13,7 +13,13 @@ function moduleSource(table) {
13
13
  })
14
14
  const popups = table.popups.map(popup =>
15
15
  ` [${JSON.stringify(popup.seoUri)}]: () => import(${JSON.stringify(`/src/${popup.itemPath}/_generated/index.jsx`)})`)
16
- return `export const pages = {\n${entries.join(',\n')}\n};\nexport const popups = {\n${popups.join(',\n')}\n};\nexport const seoUriByPageId = {};\n`
16
+ // lightbox.open({ pageId }) names a popup by its Wix page id, as a Wix Forms form stores it.
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`
17
23
  }
18
24
 
19
25
  /** @param {import('./index.js').OrigamiVitePluginsOptions['siteTree']} siteTree
@@ -1,3 +1,10 @@
1
- // PLAN-QUESTION: Popup option/result types are unspecified here; leave options opaque until milestone 3.2.
2
- export function openPopup(seoUri: string, options?: Record<string, unknown>): void
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. */
3
10
  export function closePopup(): void
@@ -1 +1 @@
1
- export {}
1
+ export { openPopup, closePopup } from './runtime.js'
@@ -0,0 +1,110 @@
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
+ }
@@ -206,6 +206,8 @@ function readPopups(src) {
206
206
  if (nested.length) throw new SiteTreeError('POPUP_NOT_TOP_LEVEL', nested.map(itemPath => `src/${itemPath}`), 'A popup must sit directly in src/popups.')
207
207
  return items.map(itemPath => {
208
208
  const seoUri = basename(itemPath)
209
- return { key: itemPath, seoUri, itemPath, title: pageMetadata(resolve(src, itemPath)).title ?? seoUri }
209
+ 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 } : {}) }
210
212
  })
211
213
  }
package/src/styles.d.ts CHANGED
@@ -1,2 +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.
4
+ declare module '*.css'