@uniweb/scene 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # @uniweb/scene
2
+
3
+ A React renderer for the **Scene Composition Format** — declarative, layered
4
+ visual scenes composited with CSS blend modes.
5
+
6
+ > **Status:** initial setup. The renderer implementation is being brought in from
7
+ > its reference implementation; the API below is the shape it lands with.
8
+
9
+ ## What is a scene?
10
+
11
+ A *scene* is a portable JSON description of a layered visual. Each layer is one of
12
+ a handful of kinds — **text**, **subject** (image), **shape**, **spray**,
13
+ **accent**, **svg**, **separator** — positioned in a shared z-index space and
14
+ composited through CSS `mix-blend-mode`. There's no canvas-2D or WebGL: every
15
+ layer is a positioned DOM element, so scenes are light, themeable, and
16
+ server-renderable.
17
+
18
+ ```json
19
+ {
20
+ "name": "Hero",
21
+ "composition": {
22
+ "aspectRatio": "16 / 9",
23
+ "background": "#0b0b12",
24
+ "texts": [{ "id": "title", "content": "Into the\nUnknown", "vAlign": "center" }],
25
+ "shapes": [{ "type": "circle", "background": "radial-gradient(circle, #ff0066, transparent)",
26
+ "width": "240px", "height": "240px", "top": "20%", "left": "60%",
27
+ "mixBlendMode": "screen", "filter": "blur(10px)" }]
28
+ }
29
+ }
30
+ ```
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ npm install @uniweb/scene react
36
+ ```
37
+
38
+ `react` (>= 18) is a peer dependency. The package has no other runtime
39
+ dependencies.
40
+
41
+ ## Usage
42
+
43
+ ```jsx
44
+ import { Scene } from '@uniweb/scene'
45
+ import doc from './hero.scene.json'
46
+
47
+ // Contained — fills its parent.
48
+ <div style={{ width: 800 }}>
49
+ <Scene composition={doc} />
50
+ </div>
51
+ ```
52
+
53
+ `composition` accepts either the full envelope (`{ name, composition }`) or a bare
54
+ composition object.
55
+
56
+ ### Templating
57
+
58
+ `composeScene` is a pure, SSR-safe helper that applies named-slot **overrides**
59
+ and an ordered **content** stream to a template scene, then hands the result to
60
+ `<Scene>`:
61
+
62
+ ```jsx
63
+ import { Scene, composeScene } from '@uniweb/scene'
64
+
65
+ const final = composeScene(template, {
66
+ overrides: { title: { content: 'Article Title' } },
67
+ content: [{ kind: 'text', content: 'By Jane Doe' }]
68
+ })
69
+
70
+ <Scene composition={final} />
71
+ ```
72
+
73
+ ### Theming with CSS variables
74
+
75
+ Every default colour and font reads a `--vc-*` custom property, with a sensible
76
+ literal as the fallback. An explicit value in the scene JSON always wins — only
77
+ the *default* is themeable. Set the variables once on a wrapper and an otherwise
78
+ unstyled scene adopts your tokens:
79
+
80
+ | Variable | Themes the default… | Fallback |
81
+ | --- | --- | --- |
82
+ | `--vc-text` | text colour | `currentColor` |
83
+ | `--vc-font` | text `font-family` | `inherit` |
84
+ | `--vc-shape` | shape background + ring stroke | `#ffffff` |
85
+ | `--vc-accent` | spray fill + accent fill | `#ff3300` |
86
+ | `--vc-separator` | separator rule/label colour | `currentColor` |
87
+
88
+ Because text colour falls back to `currentColor` and font to `inherit`, an
89
+ unstyled scene simply adopts the surrounding element's colour and font.
90
+
91
+ ### Server-side rendering
92
+
93
+ `<Scene>` renders to static HTML and hydrates cleanly — no `useLayoutEffect`, no
94
+ DOM access at module scope. Responsive behaviour is **container-queried** via
95
+ `ResizeObserver` at runtime. For pre-rendering at a known width, pass
96
+ `initialWidth` (a number of CSS pixels) so the first paint matches the
97
+ post-hydration layout:
98
+
99
+ ```jsx
100
+ <Scene composition={doc} initialWidth={360} />
101
+ ```
102
+
103
+ ### Untrusted SVG
104
+
105
+ `svg` layers render inline markup. If a scene can come from an untrusted source,
106
+ pass a sanitizer — the host owns the policy:
107
+
108
+ ```jsx
109
+ <Scene composition={doc} sanitizeSvg={(html) => mySanitizer(html)} />
110
+ ```
111
+
112
+ ## Exports
113
+
114
+ | Export | Description |
115
+ | --- | --- |
116
+ | `Scene` | The renderer component (also the default export). |
117
+ | `composeScene` | Pure templating helper (overrides + content binding). |
118
+ | scene/layer helpers | Pure scene-normalisation and per-layer style utilities. |
119
+
120
+ `<Scene>` also accepts optional pointer hooks (`onLayerPointerDown`,
121
+ `selectedId`, `draggedId`, `tempPos`) for building an interactive editor on top
122
+ of the renderer; without them it is fully inert (`pointer-events: none`).
123
+
124
+ ## License
125
+
126
+ Apache-2.0. Derived from a reference renderer for the Scene Composition Format.
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@uniweb/scene",
3
+ "version": "0.1.1",
4
+ "description": "React renderer for the Scene Composition Format — layered visual scenes composited with CSS blend modes",
5
+ "type": "module",
6
+ "main": "src/index.js",
7
+ "exports": {
8
+ ".": "./src/index.js"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "peerDependencies": {
14
+ "react": ">=18.0.0"
15
+ },
16
+ "keywords": [
17
+ "uniweb",
18
+ "scene",
19
+ "composition",
20
+ "renderer",
21
+ "blend-mode",
22
+ "react",
23
+ "visual"
24
+ ],
25
+ "author": "Uniweb",
26
+ "license": "Apache-2.0",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/uniweb/scene.git"
30
+ },
31
+ "bugs": {
32
+ "url": "https://github.com/uniweb/scene/issues"
33
+ },
34
+ "homepage": "https://github.com/uniweb/scene#readme"
35
+ }
package/src/Scene.jsx ADDED
@@ -0,0 +1,313 @@
1
+ import { useRef, useState, useEffect, useMemo } from 'react'
2
+ import {
3
+ VC_KEYFRAMES,
4
+ DEFAULT_MOBILE_BREAKPOINT,
5
+ flattenLayers,
6
+ isLayerHidden,
7
+ commonStyle,
8
+ shapeStyle,
9
+ subjectStyle,
10
+ sprayStyle,
11
+ accentContainerStyle,
12
+ svgStyle,
13
+ textStyle,
14
+ separatorStyle,
15
+ buildSvgHtml
16
+ } from './layers.js'
17
+
18
+ const SELECTION_OUTLINE = '2px dashed #818cf8'
19
+
20
+ /**
21
+ * Renders a Scene. Presentational by default — pass a composition
22
+ * (either the full `.scene.json` envelope or a bare composition object)
23
+ * and it draws the layered, blend-mode-composited scene with zero host setup.
24
+ *
25
+ * To drive an editor, pass the optional editing hooks: `onLayerPointerDown`
26
+ * turns layers into pointer targets, `selectedId` draws a selection outline,
27
+ * and `draggedId` + `tempPos` apply a live drag position. When `onLayerPointerDown`
28
+ * is omitted the renderer is fully inert (`pointer-events: none`).
29
+ *
30
+ * Responsive visibility is container-queried via `ResizeObserver`. For SSR /
31
+ * pre-rendering, pass `initialWidth` (the known container width) so the first
32
+ * paint matches the post-hydration layout and avoids a desktop→mobile flash.
33
+ *
34
+ * `sanitizeSvg(html) => html` runs author-supplied SVG markup through the
35
+ * host's sanitizer before injection (default: identity). `injectKeyframes`
36
+ * (default `true`) can be set false when the host ships `VC_KEYFRAMES` in its
37
+ * own bundled CSS. Default colors/fonts read `--vc-*` custom properties (see
38
+ * README) so a wrapper can theme an otherwise-unstyled composition.
39
+ */
40
+ export function Scene({
41
+ composition,
42
+ mobileBreakpoint = DEFAULT_MOBILE_BREAKPOINT,
43
+ initialWidth = 1000,
44
+ className,
45
+ style,
46
+ sanitizeSvg = null,
47
+ injectKeyframes = true,
48
+ selectedId = null,
49
+ onLayerPointerDown = null,
50
+ draggedId = null,
51
+ tempPos = null
52
+ }) {
53
+ const comp = composition?.composition || composition || {}
54
+ const interactive = typeof onLayerPointerDown === 'function'
55
+
56
+ const containerRef = useRef(null)
57
+ // `initialWidth` seeds the first render (server + client hydration) before the
58
+ // ResizeObserver measures the real width. Server HTML and the client's first
59
+ // render use the same value, so hydration matches; the real width is applied
60
+ // afterwards. Pass the known width when pre-rendering to avoid a layout flash.
61
+ const [containerWidth, setContainerWidth] = useState(initialWidth)
62
+
63
+ // Container-query the width so responsive behavior tracks the element, not
64
+ // the viewport.
65
+ useEffect(() => {
66
+ if (!containerRef.current) return
67
+ const obs = new ResizeObserver((entries) => {
68
+ setContainerWidth(entries[0].contentRect.width)
69
+ })
70
+ obs.observe(containerRef.current)
71
+ return () => obs.disconnect()
72
+ }, [])
73
+
74
+ const layers = useMemo(() => flattenLayers(comp), [comp])
75
+
76
+ // Interaction-only style overlay (selection outline, grab cursor, live drag
77
+ // position). Empty in presentational mode.
78
+ const editStyle = (layer) => {
79
+ if (!interactive) return { pointerEvents: 'none' }
80
+ const s = { pointerEvents: 'auto' }
81
+ if (selectedId === layer.id) {
82
+ s.outline = SELECTION_OUTLINE
83
+ s.outlineOffset = '2px'
84
+ s.cursor = draggedId === layer.id ? 'grabbing' : 'grab'
85
+ }
86
+ if (draggedId === layer.id && tempPos) {
87
+ s.left = tempPos.left
88
+ s.top = tempPos.top
89
+ }
90
+ return s
91
+ }
92
+
93
+ const handlers = (layer) =>
94
+ interactive ? { onMouseDown: (e) => onLayerPointerDown(e, layer) } : {}
95
+
96
+ const renderAccent = (accent) => {
97
+ const filterId = `vc-accent-${accent.id}`
98
+ const intensity = accent.intensity || 0.015
99
+ const numOctaves = accent.numOctaves || 2
100
+ const spread = accent.spread || 40
101
+ const blobs = accent.blobs || []
102
+ const blurStd =
103
+ accent.variant === 'mist' ? 5 : accent.variant === 'cloud' ? 8 : 1
104
+
105
+ const containerStyle = accentContainerStyle(accent)
106
+ if (interactive && selectedId === accent.id) {
107
+ containerStyle.outline = SELECTION_OUTLINE
108
+ containerStyle.outlineOffset = '-2px'
109
+ }
110
+
111
+ return (
112
+ <div key={accent.id} style={containerStyle}>
113
+ <svg
114
+ width="100%"
115
+ height="100%"
116
+ viewBox="0 0 160 90"
117
+ preserveAspectRatio="xMidYMid slice"
118
+ >
119
+ <defs>
120
+ <filter id={filterId} colorInterpolationFilters="sRGB">
121
+ <feTurbulence
122
+ type="fractalNoise"
123
+ baseFrequency={intensity}
124
+ numOctaves={numOctaves}
125
+ seed={accent.seed || 1}
126
+ result="noise"
127
+ />
128
+ <feDisplacementMap
129
+ in="SourceGraphic"
130
+ in2="noise"
131
+ scale={spread}
132
+ xChannelSelector="R"
133
+ yChannelSelector="G"
134
+ />
135
+ <feGaussianBlur stdDeviation={blurStd} />
136
+ </filter>
137
+ </defs>
138
+ <g filter={`url(#${filterId})`}>
139
+ {blobs.map((blob, i) => {
140
+ const b = Array.isArray(blob)
141
+ ? {
142
+ cx: blob[0],
143
+ cy: blob[1],
144
+ rx: blob[2],
145
+ ry: blob[3],
146
+ color: blob[4],
147
+ opacity: blob[5]
148
+ }
149
+ : blob
150
+ return (
151
+ <ellipse
152
+ key={i}
153
+ cx={b.cx}
154
+ cy={b.cy}
155
+ rx={b.rx}
156
+ ry={b.ry}
157
+ fill={b.color || accent.color || 'var(--vc-accent, #ff3300)'}
158
+ opacity={b.opacity ?? 1}
159
+ />
160
+ )
161
+ })}
162
+ </g>
163
+ </svg>
164
+ </div>
165
+ )
166
+ }
167
+
168
+ // Presentational: a themed horizontal rule with an optional centered label
169
+ // (spec §10). Interactive/editor mode keeps a labeled, selectable box so
170
+ // authors can see and grab an otherwise-invisible separator.
171
+ const renderSeparator = (sep) => {
172
+ const base = {
173
+ ...separatorStyle(sep),
174
+ ...commonStyle(sep),
175
+ ...editStyle(sep)
176
+ }
177
+ if (interactive) {
178
+ return (
179
+ <div
180
+ key={sep.id}
181
+ style={{
182
+ ...base,
183
+ border: '1px dashed rgba(99, 102, 241, 0.4)',
184
+ background: 'rgba(99, 102, 241, 0.1)'
185
+ }}
186
+ {...handlers(sep)}
187
+ >
188
+ <span
189
+ style={{
190
+ fontSize: '10px',
191
+ color: '#818cf8',
192
+ fontWeight: 500,
193
+ letterSpacing: '0.1em',
194
+ textTransform: 'uppercase',
195
+ opacity: 0.7
196
+ }}
197
+ >
198
+ Separator ({sep.gap || 'normal'})
199
+ </span>
200
+ </div>
201
+ )
202
+ }
203
+ const rule = {
204
+ flex: 1,
205
+ borderTop: '1px solid var(--vc-separator, currentColor)',
206
+ opacity: 0.4
207
+ }
208
+ return (
209
+ <div key={sep.id} style={base}>
210
+ <div style={rule} />
211
+ {sep.label && (
212
+ <>
213
+ <span
214
+ style={{
215
+ padding: '0 0.75rem',
216
+ fontSize: '0.75rem',
217
+ color: 'var(--vc-separator, currentColor)',
218
+ opacity: 0.7,
219
+ whiteSpace: 'nowrap'
220
+ }}
221
+ >
222
+ {sep.label}
223
+ </span>
224
+ <div style={rule} />
225
+ </>
226
+ )}
227
+ </div>
228
+ )
229
+ }
230
+
231
+ const renderLayer = (layer) => {
232
+ if (isLayerHidden(layer, containerWidth, mobileBreakpoint)) return null
233
+ const common = commonStyle(layer)
234
+
235
+ switch (layer._kind) {
236
+ case 'shape':
237
+ return (
238
+ <div
239
+ key={layer.id}
240
+ style={{ ...shapeStyle(layer), ...common, ...editStyle(layer) }}
241
+ {...handlers(layer)}
242
+ />
243
+ )
244
+ case 'subject':
245
+ return (
246
+ <img
247
+ key={layer.id}
248
+ src={layer.src}
249
+ alt={layer.alt || ''}
250
+ style={{ ...subjectStyle(layer), ...common, ...editStyle(layer) }}
251
+ {...handlers(layer)}
252
+ />
253
+ )
254
+ case 'spray':
255
+ return (
256
+ <div
257
+ key={layer.id}
258
+ style={{ ...sprayStyle(layer), ...common, ...editStyle(layer) }}
259
+ {...handlers(layer)}
260
+ />
261
+ )
262
+ case 'accent':
263
+ return renderAccent(layer)
264
+ case 'svg':
265
+ return (
266
+ <div
267
+ key={layer.id}
268
+ style={{ ...svgStyle(layer), ...common, ...editStyle(layer) }}
269
+ {...handlers(layer)}
270
+ dangerouslySetInnerHTML={{
271
+ __html: buildSvgHtml(layer, sanitizeSvg)
272
+ }}
273
+ />
274
+ )
275
+ case 'text':
276
+ return (
277
+ <div
278
+ key={layer.id}
279
+ style={{ ...textStyle(layer), ...common, ...editStyle(layer) }}
280
+ {...handlers(layer)}
281
+ >
282
+ {layer.content || layer.title || 'Text Layer'}
283
+ </div>
284
+ )
285
+ case 'separator':
286
+ return renderSeparator(layer)
287
+ default:
288
+ return null
289
+ }
290
+ }
291
+
292
+ return (
293
+ <div
294
+ ref={containerRef}
295
+ className={className}
296
+ style={{
297
+ position: 'relative',
298
+ overflow: 'hidden',
299
+ width: '100%',
300
+ height: '100%',
301
+ background: comp.background || 'transparent',
302
+ aspectRatio: comp.aspectRatio || 'auto',
303
+ borderRadius: comp.borderRadius || '0',
304
+ ...style
305
+ }}
306
+ >
307
+ {injectKeyframes && <style>{VC_KEYFRAMES}</style>}
308
+ {layers.map(renderLayer)}
309
+ </div>
310
+ )
311
+ }
312
+
313
+ export default Scene
package/src/compose.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Pure, SSR-safe templating for content-driven hosts. No React, no DOM, no
3
+ * randomness — safe to call at build time, in SSR, and on the client (ids are
4
+ * deterministic, so server/client output matches).
5
+ *
6
+ * `composeScene(template, { overrides, content })` returns a NEW composition
7
+ * with two transforms applied, then handed straight to <Scene>:
8
+ *
9
+ * - overrides (spec §11.3): named-slot templating. `{ [layerId]: partial }`
10
+ * shallow-merges onto the layer with that id. An explicit field wins.
11
+ * - content (spec §12): ordered, variable-length content stream. Each item
12
+ * `{ kind, ...fields }` becomes a layer, merged under the template's
13
+ * `content.defaults[kind]` (so the template enforces brand styling), with
14
+ * zIndex auto-assigned from `content.{zStart,zStep}` unless the item sets
15
+ * its own.
16
+ *
17
+ * Input may be an envelope (`{ $schema, composition }`) or a bare composition;
18
+ * the return value matches the input shape.
19
+ */
20
+
21
+ const KIND_TO_GROUP = {
22
+ subject: 'subjects',
23
+ shape: 'shapes',
24
+ spray: 'sprays',
25
+ accent: 'accents',
26
+ svg: 'svgs',
27
+ text: 'texts',
28
+ separator: 'separators'
29
+ }
30
+
31
+ const GROUPS = Object.values(KIND_TO_GROUP)
32
+
33
+ export function composeScene(template, { overrides, content } = {}) {
34
+ const isEnvelope = !!(template && typeof template.composition === 'object')
35
+ const comp = isEnvelope ? template.composition : template || {}
36
+
37
+ // Shallow-clone the composition and each layer array/object so we never
38
+ // mutate the caller's template.
39
+ const next = { ...comp }
40
+ for (const group of GROUPS) {
41
+ if (Array.isArray(comp[group]))
42
+ next[group] = comp[group].map((l) => ({ ...l }))
43
+ }
44
+
45
+ // 1) Overrides — shallow-merge by id across every layer kind.
46
+ if (overrides) {
47
+ for (const group of GROUPS) {
48
+ if (!Array.isArray(next[group])) continue
49
+ next[group] = next[group].map((l) =>
50
+ overrides[l.id] ? { ...l, ...overrides[l.id] } : l
51
+ )
52
+ }
53
+ }
54
+
55
+ // 2) Content binding — expand the ordered content stream into layers.
56
+ const items = Array.isArray(content) ? content : []
57
+ if (items.length) {
58
+ const cfg = comp.content || {}
59
+ const zStart = cfg.zStart ?? 100
60
+ const zStep = cfg.zStep ?? 100
61
+ const kindDefaults = cfg.defaults || {}
62
+
63
+ items.forEach((item, i) => {
64
+ if (!item || !item.kind) return
65
+ const group = KIND_TO_GROUP[item.kind]
66
+ if (!group) return
67
+ const layer = {
68
+ ...(kindDefaults[item.kind] || {}),
69
+ ...item,
70
+ // Deterministic id (index-based) so SSR and client hydration agree.
71
+ id: item.id || `content-${item.kind}-${i}`,
72
+ zIndex: item.zIndex ?? zStart + i * zStep
73
+ }
74
+ if (!Array.isArray(next[group])) next[group] = []
75
+ next[group] = [...next[group], layer]
76
+ })
77
+ }
78
+
79
+ return isEnvelope ? { ...template, composition: next } : next
80
+ }
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ // @uniweb/scene — public surface for the Scene Composition Format renderer.
2
+ export { Scene, default } from './Scene.jsx'
3
+ // `Composition` is a back-compat alias (the renderer's pre-rename name upstream).
4
+ export { Scene as Composition } from './Scene.jsx'
5
+ export * from './layers.js'
6
+ export * from './compose.js'
package/src/layers.js ADDED
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Plain-JS core for the scene renderer.
3
+ *
4
+ * Pure data + style computation — no React, no DOM access. Every function
5
+ * takes plain objects and returns plain objects, so this layer can be reused
6
+ * for server-side rendering, static export, or non-React hosts. The JSX
7
+ * components in ./Scene.jsx are a thin view on top of these helpers.
8
+ */
9
+
10
+ // Injected once by <Scene> so animations work with zero host setup.
11
+ export const VC_KEYFRAMES = `
12
+ @media (prefers-reduced-motion: no-preference) {
13
+ @keyframes vc-float {
14
+ 0%, 100% { translate: 0 0; }
15
+ 50% { translate: 0 -6px; }
16
+ }
17
+ @keyframes vc-drift {
18
+ 0%, 100% { translate: 0 0; }
19
+ 50% { translate: 3px -3px; }
20
+ }
21
+ @keyframes vc-pulse {
22
+ 0%, 100% { opacity: 1; }
23
+ 50% { opacity: 0.4; }
24
+ }
25
+ @keyframes vc-rotate-slow {
26
+ to { rotate: 360deg; }
27
+ }
28
+ }
29
+ `
30
+
31
+ // Width (px) below which a container is treated as "mobile". Container-queried
32
+ // via ResizeObserver, not viewport-queried — so a scene behaves the same
33
+ // whether it fills the screen or sits in a small card.
34
+ export const DEFAULT_MOBILE_BREAKPOINT = 768
35
+
36
+ // [compositionArrayKey, layer._kind] — render/flatten order within a z tie.
37
+ const GROUPS = [
38
+ ['subjects', 'subject'],
39
+ ['shapes', 'shape'],
40
+ ['sprays', 'spray'],
41
+ ['accents', 'accent'],
42
+ ['svgs', 'svg'],
43
+ ['texts', 'text'],
44
+ ['separators', 'separator']
45
+ ]
46
+
47
+ /**
48
+ * Merge every layer array of a composition into one list sorted by zIndex
49
+ * (ascending = back-to-front paint order). Each layer is tagged with `_kind`
50
+ * (singular type) and `_group` (its source array name).
51
+ */
52
+ export function flattenLayers(comp) {
53
+ let all = []
54
+ for (const [group, kind] of GROUPS) {
55
+ if (Array.isArray(comp?.[group])) {
56
+ all = all.concat(
57
+ comp[group].map((l) => ({ ...l, _kind: kind, _group: group }))
58
+ )
59
+ }
60
+ }
61
+ return all.sort((a, b) => (a.zIndex || 0) - (b.zIndex || 0))
62
+ }
63
+
64
+ // Parse a `hideBelow` length ("640px", "40rem") to raw pixels for comparison.
65
+ export function getHideBelowPx(val) {
66
+ if (!val) return 0
67
+ const match = String(val).match(/([\d.]+)(px|rem|em)?/)
68
+ if (!match) return 0
69
+ const num = parseFloat(match[1])
70
+ const unit = match[2] || 'px'
71
+ if (unit === 'rem' || unit === 'em') return num * 16
72
+ return num
73
+ }
74
+
75
+ /**
76
+ * Container-width-queried visibility. Replaces the editor's Tailwind
77
+ * `max-md:hidden` / `md:hidden` classes so the renderer needs no CSS framework
78
+ * and follows the spec's container-query intent.
79
+ * - `hidden` → never rendered
80
+ * - `hideBelow` → hidden when the container is narrower than the threshold
81
+ * - `decorative` → desktop-only (hidden below the mobile breakpoint)
82
+ * - separators → mobile-only (hidden at/above the mobile breakpoint)
83
+ */
84
+ export function isLayerHidden(
85
+ layer,
86
+ containerWidth,
87
+ breakpoint = DEFAULT_MOBILE_BREAKPOINT
88
+ ) {
89
+ if (layer.hidden) return true
90
+ if (layer.hideBelow && containerWidth < getHideBelowPx(layer.hideBelow))
91
+ return true
92
+ if (layer.decorative && containerWidth < breakpoint) return true
93
+ if (layer._kind === 'separator' && containerWidth >= breakpoint) return true
94
+ return false
95
+ }
96
+
97
+ // Common, non-interactive props shared by every non-accent layer.
98
+ export function commonStyle(layer) {
99
+ return {
100
+ animation: layer.animation || 'none',
101
+ backdropFilter: layer.backdropFilter || 'none',
102
+ WebkitBackdropFilter: layer.backdropFilter || 'none'
103
+ }
104
+ }
105
+
106
+ export function shapeStyle(shape) {
107
+ const style = {
108
+ position: 'absolute',
109
+ top: shape.top || '50%',
110
+ bottom: shape.bottom,
111
+ left: shape.left || '50%',
112
+ right: shape.right,
113
+ width: shape.width || '80px',
114
+ height: shape.height || '80px',
115
+ background: shape.background || 'var(--vc-shape, #ffffff)',
116
+ mixBlendMode: shape.mixBlendMode || 'normal',
117
+ filter: shape.filter || 'none',
118
+ transform: shape.transform || 'translate(-50%, -50%)',
119
+ opacity: shape.opacity ?? 1,
120
+ zIndex: shape.zIndex || 0
121
+ }
122
+ if (shape.type === 'circle' || shape.type === 'blob')
123
+ style.borderRadius = '50%'
124
+ else if (shape.type === 'pill') style.borderRadius = '9999px'
125
+ else if (shape.type === 'rect')
126
+ style.borderRadius = shape.borderRadius || '0px'
127
+ else if (shape.type === 'ring') {
128
+ style.borderRadius = '50%'
129
+ style.border = `${shape.strokeWidth || '3px'} solid ${shape.color || 'var(--vc-shape, #fff)'}`
130
+ style.background = 'transparent'
131
+ } else if (shape.type === 'diamond') {
132
+ style.transform = `${style.transform !== 'none' ? style.transform : ''} rotate(45deg)`
133
+ }
134
+ return style
135
+ }
136
+
137
+ export function subjectStyle(subject) {
138
+ return {
139
+ position: 'absolute',
140
+ top: subject.top || '50%',
141
+ left: subject.left || '50%',
142
+ transform: `translate(-50%, -50%) ${subject.transform || ''}`,
143
+ width: subject.maxWidth || '70%',
144
+ height: subject.maxHeight || '80%',
145
+ objectFit: subject.objectFit || 'contain',
146
+ objectPosition: subject.objectPosition || 'center',
147
+ mixBlendMode: subject.mixBlendMode || 'normal',
148
+ filter: subject.filter || 'none',
149
+ opacity: subject.opacity ?? 1,
150
+ zIndex: subject.zIndex || 2
151
+ }
152
+ }
153
+
154
+ export function sprayStyle(spray) {
155
+ const style = {
156
+ position: 'absolute',
157
+ top: spray.top || '50%',
158
+ bottom: spray.bottom,
159
+ left: spray.left || '50%',
160
+ right: spray.right,
161
+ width: spray.width || '300px',
162
+ height: spray.height || '300px',
163
+ background: spray.fill || 'var(--vc-accent, #ff3300)',
164
+ mixBlendMode: spray.mixBlendMode || 'normal',
165
+ zIndex: spray.zIndex || 0,
166
+ opacity: spray.opacity ?? 1,
167
+ transform: spray.transform || 'translate(-50%, -50%)',
168
+ filter: spray.filter || 'none'
169
+ }
170
+ const spread = spray.spread !== undefined ? spray.spread : 60
171
+ const radius = spray.radius !== undefined ? spray.radius : 50
172
+ if (spray.mode === 'airbrush' || !spray.mode) {
173
+ style.maskImage = `radial-gradient(circle, black, transparent ${spread}%)`
174
+ style.WebkitMaskImage = style.maskImage
175
+ style.opacity = style.opacity * (radius / 100)
176
+ } else if (spray.mode === 'splatter') {
177
+ style.background = 'transparent'
178
+ style.border = `${spread / 5}px dotted ${spray.fill || 'var(--vc-accent, #ff3300)'}`
179
+ style.borderRadius = '50%'
180
+ style.filter = `blur(${radius / 20}px) ${style.filter}`
181
+ }
182
+ return style
183
+ }
184
+
185
+ // Accents are always full-bleed and never pointer-interactive.
186
+ export function accentContainerStyle(accent) {
187
+ return {
188
+ position: 'absolute',
189
+ inset: 0,
190
+ width: '100%',
191
+ height: '100%',
192
+ mixBlendMode: accent.mixBlendMode || 'normal',
193
+ opacity: accent.opacity ?? 1,
194
+ zIndex: accent.zIndex || 0,
195
+ pointerEvents: 'none',
196
+ animation: accent.animation || 'none',
197
+ backdropFilter: accent.backdropFilter || 'none',
198
+ WebkitBackdropFilter: accent.backdropFilter || 'none'
199
+ }
200
+ }
201
+
202
+ export function svgStyle(svg) {
203
+ return {
204
+ position: 'absolute',
205
+ top: svg.top || '50%',
206
+ bottom: svg.bottom,
207
+ left: svg.left || '50%',
208
+ right: svg.right,
209
+ width: svg.width || '120px',
210
+ height: svg.height || '120px',
211
+ mixBlendMode: svg.mixBlendMode || 'normal',
212
+ opacity: svg.opacity ?? 1,
213
+ zIndex: svg.zIndex || 0,
214
+ transform: svg.transform || 'translate(-50%, -50%)',
215
+ filter: svg.filter || 'none',
216
+ color: svg.color || 'inherit' // drives currentColor in the inline markup
217
+ }
218
+ }
219
+
220
+ export function textStyle(text) {
221
+ return {
222
+ position: 'absolute',
223
+ top: text.top || '50%',
224
+ left: text.left || '50%',
225
+ transform: text.transform || 'translate(-50%, -50%)',
226
+ // Default color/font route through --vc-* so a host can theme unstyled text
227
+ // from its surface tokens; an explicit value in the JSON still wins.
228
+ // `currentColor` lets text inherit the surrounding surface color by default.
229
+ color: text.color || 'var(--vc-text, currentColor)',
230
+ fontFamily: text.fontFamily || 'var(--vc-font, inherit)',
231
+ fontSize: text.fontSize || '4rem',
232
+ fontWeight: text.fontWeight || 800,
233
+ letterSpacing: text.letterSpacing || 'normal',
234
+ lineHeight: text.lineHeight ?? 1.1,
235
+ textShadow: text.textShadow || 'none',
236
+ maxWidth: text.maxWidth || 'none',
237
+ textAlign: text.align || 'center',
238
+ mixBlendMode: text.mixBlendMode || 'normal',
239
+ filter: text.filter || 'none',
240
+ opacity: text.opacity ?? 1,
241
+ zIndex: text.zIndex || 10,
242
+ // pre-wrap (not pre-line) preserves runs of whitespace, not just newlines.
243
+ whiteSpace: 'pre-wrap'
244
+ }
245
+ }
246
+
247
+ // Positioning + centering only. The decoration differs by mode and is applied
248
+ // by the component: a clean rule (presentational) or a labeled debug box
249
+ // (interactive/editor) — see Scene.jsx.
250
+ export function separatorStyle(separator) {
251
+ return {
252
+ position: 'absolute',
253
+ top: separator.top || '50%',
254
+ left: separator.left || '0',
255
+ width: separator.width || '100%',
256
+ height: separator.gap === 'large' ? '40px' : '20px',
257
+ zIndex: separator.zIndex || 0,
258
+ display: 'flex',
259
+ alignItems: 'center',
260
+ justifyContent: 'center'
261
+ }
262
+ }
263
+
264
+ // Spec 1.3: an svg layer's `content` may be a bare fragment (a <path>, a <g>,
265
+ // …). Wrap it in a default <svg> using the layer's viewBox; a complete <svg>
266
+ // passes through untouched.
267
+ //
268
+ // `content` reaches `dangerouslySetInnerHTML`, so when it can be author-supplied
269
+ // or imported, pass a `sanitize` function — the host owns the sanitizer; we only
270
+ // provide the injection point. Defaults to identity (unchanged behavior).
271
+ export function buildSvgHtml(svg, sanitize) {
272
+ const isFragment = !/^\s*<svg/i.test(svg.content || '')
273
+ const html = isFragment
274
+ ? `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${svg.viewBox || '0 0 100 100'}" width="100%" height="100%" preserveAspectRatio="xMidYMid meet">${svg.content}</svg>`
275
+ : svg.content
276
+ return typeof sanitize === 'function' ? sanitize(html) : html
277
+ }