@crombolo/render 0.36.2 → 0.38.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/package.json +5 -2
- package/src/bundle-script.ts +4 -7
- package/src/component-stack.ts +53 -0
- package/src/context.ts +68 -7
- package/src/headers.ts +86 -0
- package/src/index.ts +5 -0
- package/src/islands-loader.ts +152 -0
- package/src/islands.ts +220 -0
- package/src/jsx-runtime.ts +40 -2
- package/src/live-reload.ts +78 -0
- package/src/media.ts +101 -22
- package/src/model.ts +39 -3
- package/src/navigation.ts +70 -0
- package/src/published-cache.ts +41 -3
- package/src/renderer.ts +225 -41
- package/src/seo.ts +63 -1
- package/src/site.ts +106 -0
- package/src/snapshots.ts +32 -1
- package/src/values.ts +49 -5
package/src/islands.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Interactive islands (story 209). A view module whose first statement is
|
|
3
|
+
* `'use client'` runs in the browser: while views are copied into a snapshot it
|
|
4
|
+
* is written as a stub, whose exports render a `<crombolo-island>` placeholder
|
|
5
|
+
* carrying the props as JSON. The browser code is built per snapshot
|
|
6
|
+
* generation, and `/crombolo/islands.js` mounts each island when it is needed.
|
|
7
|
+
* docs/rendering.md, "Islands".
|
|
8
|
+
*/
|
|
9
|
+
import { markIslands } from './context.ts'
|
|
10
|
+
import { escapeHtml, RawHtml } from './html.ts'
|
|
11
|
+
import { type Child, renderToString } from './jsx-runtime.ts'
|
|
12
|
+
|
|
13
|
+
/** The loader every page with an island links to; a file, so no inline script is written. */
|
|
14
|
+
export const ISLAND_LOADER_PATH = '/crombolo/islands.js'
|
|
15
|
+
/** Where a generation's built browser code is served from. */
|
|
16
|
+
export const ISLANDS_PATH = '/crombolo/islands'
|
|
17
|
+
|
|
18
|
+
/** When an island loads: as it scrolls into view, when the browser is idle, or at once. */
|
|
19
|
+
export type IslandLoad = 'visible' | 'idle' | 'load'
|
|
20
|
+
const LOADS: readonly IslandLoad[] = ['visible', 'idle', 'load']
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether a module's first statement is `'use client'`. Comments may come
|
|
24
|
+
* before it; the words anywhere else, in a string or later on, do not count.
|
|
25
|
+
*/
|
|
26
|
+
export function isClientModule(source: string): boolean {
|
|
27
|
+
let rest = source.replace(/^/, '')
|
|
28
|
+
for (;;) {
|
|
29
|
+
rest = rest.replace(/^\s+/, '')
|
|
30
|
+
if (rest.startsWith('//')) {
|
|
31
|
+
const end = rest.indexOf('\n')
|
|
32
|
+
rest = end < 0 ? '' : rest.slice(end + 1)
|
|
33
|
+
} else if (rest.startsWith('/*')) {
|
|
34
|
+
const end = rest.indexOf('*/')
|
|
35
|
+
if (end < 0) return false
|
|
36
|
+
rest = rest.slice(end + 2)
|
|
37
|
+
} else break
|
|
38
|
+
}
|
|
39
|
+
return /^(['"])use client\1\s*(;|\n|$)/.test(rest)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A prop an island cannot carry to the browser, named by where it is. */
|
|
43
|
+
export class IslandPropsError extends Error {}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The props as JSON a `<script type="application/json">` can hold: refused
|
|
47
|
+
* when anything would not survive the trip, escaped so nothing in it can close
|
|
48
|
+
* the script or read as markup.
|
|
49
|
+
*/
|
|
50
|
+
export function serializeProps(props: Record<string, unknown>, island: string): string {
|
|
51
|
+
const seen = new Set<object>()
|
|
52
|
+
const check = (value: unknown, path: string): void => {
|
|
53
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return
|
|
54
|
+
if (typeof value === 'number') {
|
|
55
|
+
if (!Number.isFinite(value))
|
|
56
|
+
throw new IslandPropsError(`${island}: ${path} is ${value}, which JSON cannot carry.`)
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
if (typeof value !== 'object') {
|
|
60
|
+
const what = value === undefined ? 'undefined' : `a ${typeof value}`
|
|
61
|
+
throw new IslandPropsError(
|
|
62
|
+
`${island}: ${path} is ${what}; an island's props travel to the browser as JSON, so only data can be passed.`,
|
|
63
|
+
)
|
|
64
|
+
}
|
|
65
|
+
if (seen.has(value))
|
|
66
|
+
throw new IslandPropsError(
|
|
67
|
+
`${island}: ${path} refers back to itself, which JSON cannot carry.`,
|
|
68
|
+
)
|
|
69
|
+
const proto = Object.getPrototypeOf(value)
|
|
70
|
+
if (!Array.isArray(value) && proto !== Object.prototype && proto !== null)
|
|
71
|
+
throw new IslandPropsError(
|
|
72
|
+
`${island}: ${path} is ${value instanceof Date ? 'a Date' : `a ${proto?.constructor?.name ?? 'class'} instance`}; pass plain data, such as a string or a number.`,
|
|
73
|
+
)
|
|
74
|
+
seen.add(value)
|
|
75
|
+
if (Array.isArray(value))
|
|
76
|
+
for (const [index, item] of value.entries()) check(item, `${path}[${index}]`)
|
|
77
|
+
else
|
|
78
|
+
for (const [key, item] of Object.entries(value))
|
|
79
|
+
if (item !== undefined) check(item, `${path}.${key}`)
|
|
80
|
+
seen.delete(value)
|
|
81
|
+
}
|
|
82
|
+
check(props, 'props')
|
|
83
|
+
return JSON.stringify(props)
|
|
84
|
+
.replaceAll('<', '\\u003c')
|
|
85
|
+
.replaceAll('>', '\\u003e')
|
|
86
|
+
.replaceAll('&', '\\u0026')
|
|
87
|
+
.replaceAll('
', '\\u2028')
|
|
88
|
+
.replaceAll('
', '\\u2029')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const transpiler = new Bun.Transpiler({ loader: 'tsx' })
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* What a client module is written as in a snapshot: each of its exports a
|
|
95
|
+
* server component rendering the island. It imports nothing; the island
|
|
96
|
+
* renderer is reached through a global this module sets, so the stub works
|
|
97
|
+
* wherever the snapshot sits.
|
|
98
|
+
*/
|
|
99
|
+
export function islandStub(module: string, source: string): string {
|
|
100
|
+
const { exports } = transpiler.scan(source)
|
|
101
|
+
const island = 'globalThis[Symbol.for("crombolo.island")]'
|
|
102
|
+
const lines = [`// The browser half of ${module} ('use client', story 209).`]
|
|
103
|
+
for (const name of exports) {
|
|
104
|
+
const call = `(props) => ${island}(${JSON.stringify(module)}, ${JSON.stringify(name)}, props)`
|
|
105
|
+
lines.push(name === 'default' ? `export default ${call}` : `export const ${name} = ${call}`)
|
|
106
|
+
}
|
|
107
|
+
return `${lines.join('\n')}\n`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const encoder = new TextEncoder()
|
|
111
|
+
const decoder = new TextDecoder()
|
|
112
|
+
|
|
113
|
+
/** The snapshot transform: a client module's stub, or undefined to copy the file as it is. */
|
|
114
|
+
export function islandTransform(key: string, bytes: Uint8Array): Uint8Array | undefined {
|
|
115
|
+
if (!/\.[jt]sx?$/.test(key)) return undefined
|
|
116
|
+
const source = decoder.decode(bytes)
|
|
117
|
+
return isClientModule(source) ? encoder.encode(islandStub(key, source)) : undefined
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const htmlOf = async (child: unknown): Promise<string> =>
|
|
121
|
+
child === undefined || child === null ? '' : renderToString(child as Child)
|
|
122
|
+
|
|
123
|
+
interface IslandOptions {
|
|
124
|
+
kind: 'react' | 'mount'
|
|
125
|
+
module: string
|
|
126
|
+
exportName: string
|
|
127
|
+
props: Record<string, unknown>
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function renderIsland(options: IslandOptions): Promise<RawHtml> {
|
|
131
|
+
const { load = 'visible', fallback, children, ...rest } = options.props
|
|
132
|
+
const where =
|
|
133
|
+
options.kind === 'mount'
|
|
134
|
+
? `<Island name="${options.module.slice('client/'.length)}">`
|
|
135
|
+
: options.module
|
|
136
|
+
if (!LOADS.includes(load as IslandLoad))
|
|
137
|
+
throw new IslandPropsError(
|
|
138
|
+
`${where}: load must be visible, idle or load, not ${JSON.stringify(load)}.`,
|
|
139
|
+
)
|
|
140
|
+
const json = serializeProps(rest, where)
|
|
141
|
+
const [fallbackHtml, childrenHtml] = await Promise.all([htmlOf(fallback), htmlOf(children)])
|
|
142
|
+
markIslands()
|
|
143
|
+
let shown = fallbackHtml
|
|
144
|
+
let carried = ''
|
|
145
|
+
let childrenMode = 'none'
|
|
146
|
+
if (options.kind === 'react') {
|
|
147
|
+
if (fallback === undefined || fallback === null) {
|
|
148
|
+
shown = childrenHtml
|
|
149
|
+
if (childrenHtml) childrenMode = 'inline'
|
|
150
|
+
} else if (childrenHtml) {
|
|
151
|
+
carried = `<template data-children>${childrenHtml}</template>`
|
|
152
|
+
childrenMode = 'template'
|
|
153
|
+
}
|
|
154
|
+
} else if (fallback === undefined || fallback === null) shown = childrenHtml
|
|
155
|
+
const attributes = [
|
|
156
|
+
`data-kind="${options.kind}"`,
|
|
157
|
+
`data-module="${escapeHtml(options.module)}"`,
|
|
158
|
+
`data-export="${escapeHtml(options.exportName)}"`,
|
|
159
|
+
`data-load="${load}"`,
|
|
160
|
+
`data-children="${childrenMode}"`,
|
|
161
|
+
].join(' ')
|
|
162
|
+
return new RawHtml(
|
|
163
|
+
`<crombolo-island ${attributes}><script type="application/json">${json}</script>${shown}${carried}</crombolo-island>`,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** What a client component's stub calls. */
|
|
168
|
+
function clientIsland(module: string, exportName: string, props: Record<string, unknown> = {}) {
|
|
169
|
+
return renderIsland({ kind: 'react', module, exportName, props })
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Kept on `globalThis`, so a stub reaches it whichever copy of this module loaded first. */
|
|
173
|
+
const KEY = Symbol.for('crombolo.island')
|
|
174
|
+
;(globalThis as Record<symbol, unknown>)[KEY] ??= clientIsland
|
|
175
|
+
|
|
176
|
+
export interface IslandProps {
|
|
177
|
+
/** `components/client/<name>`, whose default export is `mount(element, props)`. */
|
|
178
|
+
name: string
|
|
179
|
+
props?: Record<string, unknown>
|
|
180
|
+
load?: IslandLoad
|
|
181
|
+
/** Shown until it mounts; the children when there is none. */
|
|
182
|
+
fallback?: Child
|
|
183
|
+
children?: Child
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* An island in another framework — Vue, Lit or plain TypeScript: the module
|
|
188
|
+
* `components/client/<name>` exports `mount(element, props)`, returning an
|
|
189
|
+
* optional unmount.
|
|
190
|
+
*/
|
|
191
|
+
export function Island({
|
|
192
|
+
name,
|
|
193
|
+
props = {},
|
|
194
|
+
load,
|
|
195
|
+
fallback,
|
|
196
|
+
children,
|
|
197
|
+
}: IslandProps): Promise<RawHtml> {
|
|
198
|
+
if (!/^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+)*$/.test(name))
|
|
199
|
+
throw new IslandPropsError(
|
|
200
|
+
`<Island name="${name}">: the name is a path under components/client/.`,
|
|
201
|
+
)
|
|
202
|
+
return renderIsland({
|
|
203
|
+
kind: 'mount',
|
|
204
|
+
module: `client/${name}`,
|
|
205
|
+
exportName: 'default',
|
|
206
|
+
props: { ...props, load, fallback, children },
|
|
207
|
+
})
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The tags a page with islands ends with: where its browser code is, and the loader. */
|
|
211
|
+
export function islandTags(manifestUrl: string): string {
|
|
212
|
+
return `<meta name="crombolo-islands" content="${escapeHtml(manifestUrl)}"><script type="module" src="${ISLAND_LOADER_PATH}"></script>`
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** A page's HTML with the island tags before `</body>`, or at the end when it has none. */
|
|
216
|
+
export function withIslandTags(html: string, manifestUrl: string): string {
|
|
217
|
+
const tags = islandTags(manifestUrl)
|
|
218
|
+
const at = html.toLowerCase().lastIndexOf('</body>')
|
|
219
|
+
return at < 0 ? `${html}${tags}` : `${html.slice(0, at)}${tags}${html.slice(at)}`
|
|
220
|
+
}
|
package/src/jsx-runtime.ts
CHANGED
|
@@ -51,6 +51,19 @@ export type Component = (props: ElementProps) => Child
|
|
|
51
51
|
|
|
52
52
|
export const Fragment = Symbol.for('crombolo.fragment')
|
|
53
53
|
|
|
54
|
+
/**
|
|
55
|
+
* Where a development server installs its component tracker (story 214), on the
|
|
56
|
+
* global object so a view generation imported from another path finds it too.
|
|
57
|
+
*/
|
|
58
|
+
export const COMPONENT_TRACKER = Symbol.for('crombolo.componentTracker')
|
|
59
|
+
|
|
60
|
+
type ComponentTracker = (name: string, call: () => Child) => Child
|
|
61
|
+
|
|
62
|
+
function callComponent(type: Component, props: ElementProps): Child {
|
|
63
|
+
const track = (globalThis as { [COMPONENT_TRACKER]?: ComponentTracker })[COMPONENT_TRACKER]
|
|
64
|
+
return track ? track(type.name || 'Anonymous', () => type(props)) : type(props)
|
|
65
|
+
}
|
|
66
|
+
|
|
54
67
|
export function isPromise(value: unknown): value is Promise<unknown> {
|
|
55
68
|
return typeof (value as { then?: unknown } | null | undefined)?.then === 'function'
|
|
56
69
|
}
|
|
@@ -252,7 +265,7 @@ export function jsx(type: string | Component | typeof Fragment, props: ElementPr
|
|
|
252
265
|
|
|
253
266
|
if (type === Fragment) return toHtml(renderChild(actual.children))
|
|
254
267
|
|
|
255
|
-
if (typeof type === 'function') return toHtml(renderChild(type
|
|
268
|
+
if (typeof type === 'function') return toHtml(renderChild(callComponent(type, actual)))
|
|
256
269
|
|
|
257
270
|
if (type === 'select' && (actual.value != null || actual.defaultValue != null))
|
|
258
271
|
return select(actual)
|
|
@@ -285,6 +298,23 @@ export const jsxDEV = jsx
|
|
|
285
298
|
* `jsx-attributes.ts`), and markup out. `@crombolo/crombolo/loose` is the same runtime
|
|
286
299
|
* with any attribute on any tag, for a site not ready to be checked.
|
|
287
300
|
*/
|
|
301
|
+
/** What a React component returns, which is how a `'use client'` component is recognised. */
|
|
302
|
+
interface ClientElement {
|
|
303
|
+
type: unknown
|
|
304
|
+
props: unknown
|
|
305
|
+
key: unknown
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** What a template may give a `'use client'` component besides its own props. */
|
|
309
|
+
interface IslandAttributes {
|
|
310
|
+
/** Content it wraps, rendered here; shown until it mounts. */
|
|
311
|
+
children?: Child
|
|
312
|
+
/** When it loads: as it scrolls into view (the default), when the browser is idle, or at once. */
|
|
313
|
+
load?: 'visible' | 'idle' | 'load'
|
|
314
|
+
/** Shown until it mounts, instead of its children; never passed to it. */
|
|
315
|
+
fallback?: Child
|
|
316
|
+
}
|
|
317
|
+
|
|
288
318
|
export declare namespace JSX {
|
|
289
319
|
/** What a JSX expression is: markup, or a promise of it once anything in it is async. */
|
|
290
320
|
type Element = Html
|
|
@@ -300,7 +330,15 @@ export declare namespace JSX {
|
|
|
300
330
|
* against the component's own signature regardless; this constrains only what
|
|
301
331
|
* may stand in the tag position.
|
|
302
332
|
*/
|
|
303
|
-
type ElementType = string | ((props: never) => Child)
|
|
333
|
+
type ElementType = string | ((props: never) => Child) | ((props: never) => ClientElement)
|
|
334
|
+
/**
|
|
335
|
+
* A `'use client'` component (story 209) is typed with React's JSX but renders
|
|
336
|
+
* here as an island: it takes server-rendered children, and `load` and
|
|
337
|
+
* `fallback`, which never reach it.
|
|
338
|
+
*/
|
|
339
|
+
type LibraryManagedAttributes<C, P> = C extends (props: never) => ClientElement
|
|
340
|
+
? Omit<P, 'children'> & IslandAttributes
|
|
341
|
+
: P
|
|
304
342
|
interface IntrinsicElements extends KnownElements {
|
|
305
343
|
[custom: `${string}-${string}`]: CustomElementAttributes
|
|
306
344
|
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live reload in development (story 214): the script a page carries, and where
|
|
3
|
+
* it listens. The server streams a `hello` with its boot id on each connection,
|
|
4
|
+
* `reload` when the views, the schema or the content change, and `types` with
|
|
5
|
+
* the background type check's findings. docs/writing-components.md, "The
|
|
6
|
+
* development loop".
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const LIVE_RELOAD_SCRIPT_PATH = '/crombolo/dev/live.js'
|
|
10
|
+
export const LIVE_EVENTS_PATH = '/crombolo/dev/events'
|
|
11
|
+
|
|
12
|
+
/** What changed; a `reload` event carries each in its burst as `reasons`. */
|
|
13
|
+
export type LiveChange = 'views' | 'schema' | 'content'
|
|
14
|
+
|
|
15
|
+
/** The background type check's findings, in a `types` event; no errors clears the banner. */
|
|
16
|
+
export interface LiveTypes {
|
|
17
|
+
count: number
|
|
18
|
+
first?: { file: string; line: number; message: string }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Reloads the page on a `reload`, or on a `hello` from a server that restarted,
|
|
23
|
+
* and keeps a dismissible banner of type errors. Plain DOM, styled through the
|
|
24
|
+
* CSSOM, so a strict content security policy allows it.
|
|
25
|
+
*/
|
|
26
|
+
export const LIVE_RELOAD_SCRIPT = `/* crombolo: live reload in development */
|
|
27
|
+
(function () {
|
|
28
|
+
if (window.__cromboloLive) return
|
|
29
|
+
window.__cromboloLive = true
|
|
30
|
+
var boot = null
|
|
31
|
+
var banner = null
|
|
32
|
+
var events = new EventSource('${LIVE_EVENTS_PATH}')
|
|
33
|
+
events.addEventListener('hello', function (event) {
|
|
34
|
+
var id = JSON.parse(event.data).boot
|
|
35
|
+
if (boot !== null && boot !== id) location.reload()
|
|
36
|
+
boot = id
|
|
37
|
+
})
|
|
38
|
+
events.addEventListener('reload', function () {
|
|
39
|
+
location.reload()
|
|
40
|
+
})
|
|
41
|
+
events.addEventListener('types', function (event) {
|
|
42
|
+
var types = JSON.parse(event.data)
|
|
43
|
+
if (banner) banner.remove()
|
|
44
|
+
banner = null
|
|
45
|
+
if (!types.count) return
|
|
46
|
+
banner = document.createElement('div')
|
|
47
|
+
banner.setAttribute('role', 'status')
|
|
48
|
+
banner.style.cssText = 'position:fixed;left:1rem;right:1rem;bottom:1rem;z-index:2147483647;display:flex;gap:1rem;align-items:flex-start;padding:.75rem 1rem;border-radius:.5rem;background:#3b1219;color:#fff;font:14px/1.4 ui-monospace,monospace;box-shadow:0 4px 16px rgba(0,0,0,.3)'
|
|
49
|
+
var text = document.createElement('div')
|
|
50
|
+
text.style.cssText = 'flex:1;white-space:pre-wrap'
|
|
51
|
+
var first = types.first
|
|
52
|
+
text.textContent = types.count + (types.count === 1 ? ' type error' : ' type errors') +
|
|
53
|
+
(first ? '\\n' + first.file + ':' + first.line + ' ' + first.message : '')
|
|
54
|
+
var close = document.createElement('button')
|
|
55
|
+
close.type = 'button'
|
|
56
|
+
close.textContent = '\\u00d7'
|
|
57
|
+
close.setAttribute('aria-label', 'Dismiss')
|
|
58
|
+
close.style.cssText = 'background:none;border:0;color:inherit;font-size:1.25rem;line-height:1;cursor:pointer'
|
|
59
|
+
close.addEventListener('click', function () {
|
|
60
|
+
if (banner) banner.remove()
|
|
61
|
+
banner = null
|
|
62
|
+
})
|
|
63
|
+
banner.append(text, close)
|
|
64
|
+
document.body.append(banner)
|
|
65
|
+
})
|
|
66
|
+
})()
|
|
67
|
+
`
|
|
68
|
+
|
|
69
|
+
/** The tag that loads the script. */
|
|
70
|
+
export const LIVE_RELOAD_TAG = `<script src="${LIVE_RELOAD_SCRIPT_PATH}" defer></script>`
|
|
71
|
+
|
|
72
|
+
/** A page's HTML with the live-reload script before `</body>`, or at the end when it has none. */
|
|
73
|
+
export function withLiveReload(html: string): string {
|
|
74
|
+
const at = html.toLowerCase().lastIndexOf('</body>')
|
|
75
|
+
return at < 0
|
|
76
|
+
? `${html}${LIVE_RELOAD_TAG}`
|
|
77
|
+
: `${html.slice(0, at)}${LIVE_RELOAD_TAG}${html.slice(at)}`
|
|
78
|
+
}
|
package/src/media.ts
CHANGED
|
@@ -19,41 +19,114 @@ export interface FocalPoint {
|
|
|
19
19
|
top: number
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
/**
|
|
23
|
-
export type
|
|
24
|
-
|
|
|
25
|
-
|
|
|
22
|
+
/** Where a crop is cut from when there is no focal point (ImageSharp's `ranchor`). */
|
|
23
|
+
export type CropAnchor =
|
|
24
|
+
| 'center'
|
|
25
|
+
| 'top'
|
|
26
|
+
| 'bottom'
|
|
27
|
+
| 'left'
|
|
28
|
+
| 'right'
|
|
29
|
+
| 'topleft'
|
|
30
|
+
| 'topright'
|
|
31
|
+
| 'bottomleft'
|
|
32
|
+
| 'bottomright'
|
|
26
33
|
|
|
27
|
-
/**
|
|
34
|
+
/** The options of Umbraco's `GetCropUrl` (story 199), as one object. */
|
|
35
|
+
export interface CropOptions {
|
|
36
|
+
/** A named crop: its area, at its own size unless a size is given. */
|
|
37
|
+
crop?: string
|
|
38
|
+
width?: number
|
|
39
|
+
height?: number
|
|
40
|
+
/** Width ÷ height: the missing side from the given one. */
|
|
41
|
+
ratio?: number
|
|
42
|
+
/** `crop`, `max`, `stretch`, `pad`, `boxpad` or `min`. */
|
|
43
|
+
mode?: string
|
|
44
|
+
/** `jpg`, `png`, `webp`, or `avif` where the server can encode it (WebP where not). */
|
|
45
|
+
format?: string
|
|
46
|
+
/** 1–100. */
|
|
47
|
+
quality?: number
|
|
48
|
+
/** Where to cut from when there is no focal point. */
|
|
49
|
+
anchor?: CropAnchor
|
|
50
|
+
/** With `crop`: ignore its coordinates and cut around the focal point. */
|
|
51
|
+
preferFocalPoint?: boolean
|
|
52
|
+
/** With `crop`: its own size, whatever size is given. Default: only when none is. */
|
|
53
|
+
useCropDimensions?: boolean
|
|
54
|
+
/**
|
|
55
|
+
* A value that changes when the image does, so browsers and CDNs fetch it
|
|
56
|
+
* afresh: the item's update date by default; `false` for none.
|
|
57
|
+
*/
|
|
58
|
+
cacheBuster?: boolean | string
|
|
59
|
+
/** More query, appended as it is: `bgcolor=fff`. */
|
|
60
|
+
furtherOptions?: string
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A crop URL: a named crop (shorthand for `{ crop }`), or the options. */
|
|
64
|
+
export type CropRequest = string | CropOptions
|
|
65
|
+
|
|
66
|
+
/** The cache buster an update date gives. */
|
|
67
|
+
export const cacheBusterOf = (updated: Date): string => updated.getTime().toString(36)
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* `url` with the query that yields `request`, given the crops and focal point
|
|
71
|
+
* in force; null for a named crop that is not there. `updated` is when the
|
|
72
|
+
* image last changed, for the cache buster.
|
|
73
|
+
*/
|
|
28
74
|
export function cropUrl(
|
|
29
75
|
url: string,
|
|
30
76
|
crops: readonly Crop[],
|
|
31
77
|
focalPoint: FocalPoint | null,
|
|
32
78
|
request: CropRequest,
|
|
79
|
+
updated?: Date,
|
|
33
80
|
): string | null {
|
|
81
|
+
const options: CropOptions = typeof request === 'string' ? { crop: request } : request
|
|
34
82
|
const params = new URLSearchParams()
|
|
35
|
-
|
|
36
|
-
|
|
83
|
+
const focal = () => {
|
|
84
|
+
if (focalPoint) params.set('rxy', `${focalPoint.left},${focalPoint.top}`)
|
|
85
|
+
}
|
|
86
|
+
let width = options.width
|
|
87
|
+
let height = options.height
|
|
88
|
+
if (options.crop !== undefined) {
|
|
89
|
+
const crop = crops.find((c) => c.alias === options.crop)
|
|
37
90
|
if (!crop) return null
|
|
38
|
-
if (crop.coordinates)
|
|
91
|
+
if (crop.coordinates && !options.preferFocalPoint)
|
|
39
92
|
params.set(
|
|
40
93
|
'cc',
|
|
41
94
|
[crop.coordinates.x1, crop.coordinates.y1, crop.coordinates.x2, crop.coordinates.y2].join(
|
|
42
95
|
',',
|
|
43
96
|
),
|
|
44
97
|
)
|
|
45
|
-
else
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
98
|
+
else focal()
|
|
99
|
+
const sized = width !== undefined || height !== undefined
|
|
100
|
+
if (options.useCropDimensions || !sized) {
|
|
101
|
+
width = crop.width
|
|
102
|
+
height = crop.height
|
|
103
|
+
} else if (crop.width > 0 && crop.height > 0 && options.ratio === undefined) {
|
|
104
|
+
// A named crop at another size keeps its shape.
|
|
105
|
+
if (height === undefined && width) height = Math.round((width * crop.height) / crop.width)
|
|
106
|
+
if (width === undefined && height) width = Math.round((height * crop.width) / crop.height)
|
|
107
|
+
}
|
|
108
|
+
} else if (width && height) focal()
|
|
109
|
+
if (options.ratio && options.ratio > 0) {
|
|
110
|
+
if (width && !height) height = Math.round(width / options.ratio)
|
|
111
|
+
else if (height && !width) width = Math.round(height * options.ratio)
|
|
112
|
+
if (options.crop === undefined && width && height && !params.has('rxy')) focal()
|
|
55
113
|
}
|
|
56
|
-
|
|
114
|
+
if (width) params.set('width', String(width))
|
|
115
|
+
if (height) params.set('height', String(height))
|
|
116
|
+
if (options.mode) params.set('rmode', options.mode.toLowerCase())
|
|
117
|
+
if (options.anchor && !params.has('rxy')) params.set('ranchor', options.anchor.toLowerCase())
|
|
118
|
+
if (options.format) params.set('format', options.format.toLowerCase())
|
|
119
|
+
if (options.quality) params.set('quality', String(Math.round(options.quality)))
|
|
120
|
+
const buster =
|
|
121
|
+
typeof options.cacheBuster === 'string'
|
|
122
|
+
? options.cacheBuster
|
|
123
|
+
: options.cacheBuster !== false && updated && updated.getTime() > 0
|
|
124
|
+
? cacheBusterOf(updated)
|
|
125
|
+
: undefined
|
|
126
|
+
if (buster) params.set('rnd', buster)
|
|
127
|
+
let query = params.toString()
|
|
128
|
+
const further = options.furtherOptions?.replace(/^[?&]+/, '')
|
|
129
|
+
if (further) query = query ? `${query}&${further}` : further
|
|
57
130
|
return query ? `${url}?${query}` : url
|
|
58
131
|
}
|
|
59
132
|
|
|
@@ -98,11 +171,14 @@ export class ImageCropperValue {
|
|
|
98
171
|
readonly src: string
|
|
99
172
|
readonly crops: Crop[]
|
|
100
173
|
readonly focalPoint: FocalPoint | null
|
|
174
|
+
/** When it last changed: the page's, or the media item's, update date. */
|
|
175
|
+
readonly updated: Date | undefined
|
|
101
176
|
|
|
102
|
-
constructor(value: { src?: unknown; crops?: unknown; focalPoint?: unknown }) {
|
|
177
|
+
constructor(value: { src?: unknown; crops?: unknown; focalPoint?: unknown }, updated?: Date) {
|
|
103
178
|
this.src = typeof value.src === 'string' ? value.src : ''
|
|
104
179
|
this.crops = readCrops(value.crops)
|
|
105
180
|
this.focalPoint = readFocalPoint(value.focalPoint)
|
|
181
|
+
this.updated = updated
|
|
106
182
|
}
|
|
107
183
|
|
|
108
184
|
get url(): string {
|
|
@@ -110,7 +186,7 @@ export class ImageCropperValue {
|
|
|
110
186
|
}
|
|
111
187
|
|
|
112
188
|
cropUrl(request: CropRequest): string | null {
|
|
113
|
-
return this.src ? cropUrl(this.src, this.crops, this.focalPoint, request) : null
|
|
189
|
+
return this.src ? cropUrl(this.src, this.crops, this.focalPoint, request, this.updated) : null
|
|
114
190
|
}
|
|
115
191
|
|
|
116
192
|
toString(): string {
|
|
@@ -173,6 +249,7 @@ export class PublishedMedia {
|
|
|
173
249
|
const file = this.properties.find((p) => p.alias === 'umbracoFile')?.value
|
|
174
250
|
return new ImageCropperValue(
|
|
175
251
|
typeof file === 'string' ? { src: file } : ((file as object | null | undefined) ?? {}),
|
|
252
|
+
this.updateDate,
|
|
176
253
|
)
|
|
177
254
|
}
|
|
178
255
|
|
|
@@ -221,6 +298,8 @@ export class MediaWithCrops {
|
|
|
221
298
|
}
|
|
222
299
|
|
|
223
300
|
cropUrl(request: CropRequest): string | null {
|
|
224
|
-
return this.url
|
|
301
|
+
return this.url
|
|
302
|
+
? cropUrl(this.url, this.crops, this.focalPoint, request, this.media.updateDate)
|
|
303
|
+
: null
|
|
225
304
|
}
|
|
226
305
|
}
|
package/src/model.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* ambient, so `model.value('title')` returns the current request's culture.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import type { FormSubmissionState } from '@crombolo/core'
|
|
10
|
+
import type { FieldError, FormSubmissionState } from '@crombolo/core'
|
|
11
11
|
import type { RawHtml } from './html.ts'
|
|
12
12
|
import type { MediaWithCrops } from './media.ts'
|
|
13
13
|
import type { MenuItem } from './menus.ts'
|
|
@@ -133,7 +133,8 @@ export class PublishedContent<Properties = any> {
|
|
|
133
133
|
|
|
134
134
|
/** How pickers, links and blocks resolve what they point at; the cache supplies it. */
|
|
135
135
|
withValueContext(context: ValueContext<PublishedContent> | undefined): this {
|
|
136
|
-
|
|
136
|
+
// Its own update date, for what its values say about when they changed.
|
|
137
|
+
this.#context = context && { ...context, updated: this.updateDate }
|
|
137
138
|
return this
|
|
138
139
|
}
|
|
139
140
|
|
|
@@ -263,7 +264,35 @@ export interface RequestMember {
|
|
|
263
264
|
roles: string[]
|
|
264
265
|
}
|
|
265
266
|
|
|
266
|
-
/**
|
|
267
|
+
/** The query string, as Next.js hands it to a page: repeated names become arrays. */
|
|
268
|
+
export type SearchParams = Record<string, string | string[] | undefined>
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* What a status page is told about the outcome it is answering (story 206):
|
|
272
|
+
* the status, the words the code gave, any field errors, and for a server
|
|
273
|
+
* error its reference, with the details only where they may be shown.
|
|
274
|
+
*/
|
|
275
|
+
export interface PageOutcome {
|
|
276
|
+
status: number
|
|
277
|
+
/** The helper's name, `notFound`; `serverError` for a 500. */
|
|
278
|
+
name: string
|
|
279
|
+
message?: string
|
|
280
|
+
errors: readonly FieldError[]
|
|
281
|
+
/** A 500's reference, which the log line carries too. */
|
|
282
|
+
reference?: string
|
|
283
|
+
/**
|
|
284
|
+
* A 500's message, source and stack, when `errors.showDetails` allows; for a
|
|
285
|
+
* template error also the code around the line and the component stack.
|
|
286
|
+
*/
|
|
287
|
+
details?: {
|
|
288
|
+
message: string
|
|
289
|
+
location?: string
|
|
290
|
+
stack?: string
|
|
291
|
+
code?: { line: number; lines: ReadonlyArray<{ number: number; text: string }> }
|
|
292
|
+
components?: readonly string[]
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
267
296
|
/**
|
|
268
297
|
* What a template receives. Name the page's interface from `crombolo generate`
|
|
269
298
|
* to have its properties checked: `PageProps<HomePage>`.
|
|
@@ -292,6 +321,13 @@ export interface PageProps<Properties = any> {
|
|
|
292
321
|
submission: FormSubmissionState | undefined
|
|
293
322
|
/** The address requested, and the scheme and host it came in on. */
|
|
294
323
|
request: { origin: string; url: string }
|
|
324
|
+
/**
|
|
325
|
+
* The query string, as a promise as in Next.js 15. Awaiting it makes the page
|
|
326
|
+
* personal; empty on a page that exports `dynamic = 'force-static'`.
|
|
327
|
+
*/
|
|
328
|
+
searchParams: Promise<SearchParams>
|
|
329
|
+
/** On a status page, what it is answering; undefined on any other page. */
|
|
330
|
+
outcome?: PageOutcome
|
|
295
331
|
urls: {
|
|
296
332
|
/** A page's address with scheme and host; undefined for one with no address here. */
|
|
297
333
|
absolute(content: PublishedContent): string | undefined
|