feat(sdk): file-backed fs adapter + setTiming GSAP sync; sdk-playground workspace (#1458)

* feat(sdk): file-backed fs adapter + setTiming GSAP-script sync; add sdk-playground

* fix(sdk): address PR #1423 review — oxfmt, PersistVersionEntry contract, race, comments

- bunx oxfmt packages/sdk-playground/index.html (unblocks CI)
- PersistVersionEntry.content is now optional; HTTP adapter omits it for lazy-load
- fs adapter: monotonic key (Date.now-NNNN) + per-path write serialization via promise chain
- mutate.ts: fix wrong comment on GSAP sync reason; add caveat to "pre-parse once" note

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Co-authored-by: Miguel Ángel <miguel07alm@protonmail.com>

* fix(core): oxfmt gsapSerialize.ts — unblocks Preflight across stack

Pre-existing format issue on the base; fixing here to unblock CI.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Co-authored-by: Miguel Ángel <miguel07alm@protonmail.com>

* chore: update bun.lock for sdk-playground workspace

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Miguel Ángel <miguel07alm@protonmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Vance Ingalls
2026-06-15 01:55:19 -07:00
committed by GitHub
co-authored by Claude Sonnet 4.6 Miguel Ángel
parent 3bfb25efcf
commit 577a689860
12 changed files with 2535 additions and 51 deletions
+39 -36
View File
@@ -298,44 +298,47 @@ export function gsapAnimationsToKeyframes(
const baseTimeEpsilon = 0.001;
const baseValueEpsilon = 0.00001;
return animations
.filter(
(a): a is GsapAnimation & { position: number } =>
validMethods.includes(a.method) && typeof a.position === "number",
)
.map((a) => {
const relativeTimeRaw = a.position - elementStartTime;
const time = clampTimeToZero ? Math.max(0, relativeTimeRaw) : relativeTimeRaw;
return (
animations
.filter(
(a): a is GsapAnimation & { position: number } =>
validMethods.includes(a.method) && typeof a.position === "number",
)
// fallow-ignore-next-line complexity
.map((a) => {
const relativeTimeRaw = a.position - elementStartTime;
const time = clampTimeToZero ? Math.max(0, relativeTimeRaw) : relativeTimeRaw;
const properties: Partial<KeyframeProperties> = {};
for (const [key, value] of Object.entries(a.properties)) {
if (typeof value !== "number") continue;
if (key === "x") properties.x = value - baseX;
else if (key === "y") properties.y = value - baseY;
else if (key === "scale") {
properties.scale = baseScale !== 0 ? value / baseScale : value;
} else {
(properties as Record<string, number>)[key] = value;
const properties: Partial<KeyframeProperties> = {};
for (const [key, value] of Object.entries(a.properties)) {
if (typeof value !== "number") continue;
if (key === "x") properties.x = value - baseX;
else if (key === "y") properties.y = value - baseY;
else if (key === "scale") {
properties.scale = baseScale !== 0 ? value / baseScale : value;
} else {
(properties as Record<string, number>)[key] = value;
}
}
}
if (
skipBaseSet &&
a.method === "set" &&
time < baseTimeEpsilon &&
Object.values(properties).every(
(v) => typeof v === "number" && Math.abs(v) < baseValueEpsilon,
)
) {
return null;
}
if (
skipBaseSet &&
a.method === "set" &&
time < baseTimeEpsilon &&
Object.values(properties).every(
(v) => typeof v === "number" && Math.abs(v) < baseValueEpsilon,
)
) {
return null;
}
return {
id: a.id.replace(/^.*-kf-/, ""),
time,
properties: properties as KeyframeProperties,
ease: a.ease,
};
})
.filter((kf): kf is NonNullable<typeof kf> => kf !== null);
return {
id: a.id.replace(/^.*-kf-/, ""),
time,
properties: properties as KeyframeProperties,
ease: a.ease,
};
})
.filter((kf): kf is NonNullable<typeof kf> => kf !== null)
);
}
+4
View File
@@ -0,0 +1,4 @@
.hf-versions/
composition.html
dist/
node_modules/
+84
View File
@@ -0,0 +1,84 @@
# @hyperframes/sdk-playground
Interactive browser playground for the `@hyperframes/sdk` API. Open a composition, edit it through the full SDK op surface, watch the preview update live.
## Running
```bash
bun run --cwd packages/sdk-playground dev
```
Serves at `http://localhost:5173`. On first load it reads `packages/sdk-playground/composition.html` from disk (if present) or falls back to a built-in demo composition.
## Features
### File persistence
Composition state is persisted to `packages/sdk-playground/composition.html` via a Vite dev-server plugin backed by `@hyperframes/sdk/adapters/fs`. Every save writes a timestamped snapshot to `.hf-versions/composition.html/` (capped at 20). Reload the page and your last state is restored.
### Preview iframe
Full composition rendered in a sandboxed `<iframe>`. Supports:
- **Play / Pause / Seek** via the transport bar
- **Click-to-select** elements (highlights in the tree and properties panel)
- **Drag-to-reposition** — drag any element to a new position; on drop the playground calls `comp.setStyle(id, { left, top })`
### Element tree
Lists all non-root elements. Click any row to select it.
### Properties panel
Editable per-element properties for the selected element:
| Section | SDK op |
| ---------- | --------------------------------------------------------------------------- |
| Content | `comp.setText(id, value)` |
| Typography | `comp.setStyle(id, { fontSize, fontWeight, color, fontFamily })` |
| Box | `comp.setStyle(id, { top, left, width, height })` |
| Attributes | `comp.element(id).setAttribute(name, value)` — shows all non-internal attrs |
| Danger | `comp.element(id).removeElement()` |
| Animations | `comp.setTiming(id, { start, duration })` — inline form per GSAP tween |
### Timeline
DAW-style per-element tween blocks. Drag handles to trim start/end; drag body to move. All edits go through `comp.setTiming(id, { start, duration })` which keeps the GSAP script and DOM attributes in sync.
### Ops panel
Full op surface, grouped by feature:
| Section | SDK op |
| ---------------------------- | --------------------------------------------------------------------------------- |
| PreviewAdapter.select() | `preview.select([id])` |
| setStyle | `comp.setStyle(id, styles)` |
| setText | `comp.setText(id, value)` |
| addGsapTween | `comp.addGsapTween(target, spec)` |
| setTiming | `comp.setTiming(id, { start, duration })` |
| setGsapTween | `comp.setGsapTween(animId, updates)` |
| moveElement | `comp.moveElement(id, { parent, index })` |
| setClassStyle | `comp.dispatch({ type: "setClassStyle", selector, styles })` |
| setAttribute / removeElement | `comp.element(id).setAttribute()` / `.removeElement()` |
| setVariableValue | `comp.setVariableValue(id, value)` |
| find(query) | `comp.find({ tag, text, name, track })` |
| selection() proxy | `comp.selection().setStyle()` / `.removeElement()` |
| listVersions / loadFrom | `adapter.listVersions()` / `adapter.loadFrom()` |
| History / inspect | `comp.undo()`, `comp.redo()`, `comp.can()`, `comp.getOverrides()`, `comp.flush()` |
### Editor modal
Click "Open editor" to view and directly edit the raw composition HTML. Saving re-opens the composition through the SDK.
---
## Planned / not yet wired
- `comp.setTrackVariable(trackId, variableId)` — variable binding per track
- `comp.addElement(spec)` — create new elements from the UI
- `comp.duplicateElement(id)` — duplicate with offset
- Selection multi-select (current: single-select only)
- Timeline zoom and horizontal scroll for long compositions
- Version history browser — list/preview/restore past versions inline (API is implemented; UI shows only list + load-oldest)
- `comp.on('change', cb)` live event log fed from SDK event stream
- Render to video via `@hyperframes/producer` integration
+643
View File
@@ -0,0 +1,643 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@hyperframes/sdk editor</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family:
system-ui,
-apple-system,
sans-serif;
background: #0f1117;
color: #e5e7eb;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
/* ── Header ── */
#header {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 14px;
background: #161b27;
border-bottom: 1px solid #1f2937;
flex-shrink: 0;
}
#header h1 {
font-size: 14px;
font-weight: 600;
color: #f9fafb;
}
#header .badge {
font-size: 11px;
background: #1d4ed8;
color: #bfdbfe;
padding: 2px 7px;
border-radius: 10px;
}
#header .spacer {
flex: 1;
}
#header .sel-label {
font-size: 12px;
color: #4b5563;
}
#header #sel-display {
font-size: 12px;
color: #a78bfa;
font-family: monospace;
min-width: 80px;
}
/* ── Main grid ── */
#app-main {
display: grid;
grid-template-columns: 1fr 310px 260px;
flex: 1;
min-height: 0;
overflow: hidden;
}
/* ── Preview panel ── */
#preview-panel {
display: flex;
flex-direction: column;
padding: 10px;
gap: 8px;
overflow: hidden;
border-right: 1px solid #1f2937;
}
#preview-scaler-outer {
position: relative;
width: 100%;
background: #000;
border: 1px solid #1f2937;
border-radius: 4px;
overflow: hidden;
flex-shrink: 0;
}
#preview-scaler-inner {
transform-origin: top left;
}
#preview-frame {
width: 1280px;
height: 720px;
border: none;
display: block;
}
#preview-hint {
font-size: 11px;
color: #374151;
text-align: center;
}
/* ── Inspector panel ── */
#inspector-panel {
display: flex;
flex-direction: column;
border-right: 1px solid #1f2937;
overflow: hidden;
}
#inspector-tabs {
display: flex;
border-bottom: 1px solid #1f2937;
flex-shrink: 0;
}
.ins-tab {
padding: 7px 16px;
font-size: 12px;
cursor: pointer;
color: #6b7280;
border-bottom: 2px solid transparent;
user-select: none;
}
.ins-tab.active {
color: #60a5fa;
border-bottom-color: #60a5fa;
}
/* Elements list */
#element-list {
border-bottom: 1px solid #1f2937;
overflow-y: auto;
max-height: 160px;
flex-shrink: 0;
}
.el-item {
display: flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
cursor: pointer;
font-size: 12px;
border-bottom: 1px solid #111827;
}
.el-item:hover {
background: #1a2235;
}
.el-item.selected {
background: #172554;
}
.el-item .el-tag {
color: #6b7280;
font-family: monospace;
font-size: 11px;
}
.el-item .el-id {
color: #d1d5db;
font-family: monospace;
}
.el-item .el-text {
color: #4b5563;
font-size: 11px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100px;
}
/* Properties / Ops content */
#inspector-content {
flex: 1;
overflow-y: auto;
padding: 10px;
}
.prop-section {
margin-bottom: 12px;
}
.prop-section-title {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
color: #374151;
margin-bottom: 6px;
}
.prop-row {
display: flex;
align-items: center;
gap: 6px;
margin-bottom: 5px;
}
.prop-label {
font-size: 11px;
color: #6b7280;
width: 64px;
flex-shrink: 0;
}
.prop-input {
flex: 1;
padding: 3px 6px;
background: #111827;
color: #f9fafb;
border: 1px solid #374151;
border-radius: 3px;
font-size: 12px;
font-family: monospace;
min-width: 0;
}
.prop-input:focus {
outline: none;
border-color: #3b82f6;
}
.prop-input.wide {
width: 100%;
}
input[type="color"].prop-color {
width: 28px;
height: 24px;
padding: 1px 2px;
cursor: pointer;
flex-shrink: 0;
border-radius: 3px;
}
textarea.prop-input {
resize: vertical;
min-height: 48px;
font-family: system-ui, sans-serif;
}
select.prop-input {
cursor: pointer;
}
.prop-no-selection {
font-size: 12px;
color: #374151;
padding: 8px 0;
}
/* Tween list */
.tween-id {
font-size: 11px;
font-family: monospace;
color: #34d399;
background: #064e3b;
padding: 2px 6px;
border-radius: 3px;
margin-bottom: 3px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
#add-tween-form {
margin-top: 6px;
display: none;
}
#add-tween-form.open {
display: block;
}
/* Op sections (test panel) */
.op-section {
border: 1px solid #1f2937;
border-radius: 5px;
padding: 8px;
margin-bottom: 7px;
}
.op-title {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: #374151;
margin-bottom: 6px;
font-family: monospace;
}
.op-row {
display: flex;
flex-wrap: wrap;
gap: 5px;
align-items: center;
margin-bottom: 4px;
}
.op-note {
font-size: 11px;
color: #374151;
margin-top: 3px;
}
#anim-id-display {
font-size: 11px;
font-family: monospace;
color: #34d399;
background: #064e3b;
padding: 2px 6px;
border-radius: 3px;
margin-top: 3px;
}
/* Shared button / input */
button {
padding: 4px 10px;
background: #1f2937;
color: #d1d5db;
border: 1px solid #374151;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
}
button:hover {
background: #374151;
color: #f9fafb;
}
button.primary {
background: #1d4ed8;
border-color: #2563eb;
color: #fff;
}
button.primary:hover {
background: #2563eb;
}
button.danger {
background: #7f1d1d;
border-color: #991b1b;
color: #fca5a5;
}
button.danger:hover {
background: #991b1b;
}
button.ghost {
background: transparent;
border-color: transparent;
color: #6b7280;
}
button.ghost:hover {
background: #1f2937;
color: #d1d5db;
}
input[type="text"],
input[type="number"] {
padding: 3px 7px;
background: #111827;
color: #f9fafb;
border: 1px solid #374151;
border-radius: 4px;
font-size: 12px;
font-family: monospace;
}
input[type="text"] {
width: 130px;
}
input[type="number"] {
width: 65px;
}
/* ── Log panel ── */
#log-panel {
display: flex;
flex-direction: column;
overflow: hidden;
}
.panel-title {
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.07em;
color: #374151;
padding: 7px 10px;
border-bottom: 1px solid #1f2937;
flex-shrink: 0;
}
#log-entries {
overflow-y: auto;
padding: 6px;
flex: 1;
}
.log-entry {
border-left: 3px solid #374151;
padding: 3px 7px;
margin-bottom: 4px;
font-size: 11px;
font-family: monospace;
background: #111827;
border-radius: 0 3px 3px 0;
}
.log-entry .log-type {
font-weight: 700;
margin-right: 5px;
}
.log-entry pre {
color: #6b7280;
white-space: pre-wrap;
word-break: break-all;
margin-top: 2px;
font-size: 10px;
}
/* ── Timeline panel ── */
#timeline-panel {
flex-shrink: 0;
height: 158px;
border-top: 1px solid #1f2937;
display: flex;
flex-direction: column;
background: #0a0d14;
}
#tl-controls {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 10px;
border-bottom: 1px solid #1f2937;
flex-shrink: 0;
}
#tl-scrubber {
flex: 1;
accent-color: #3b82f6;
cursor: pointer;
}
#tl-time,
#tl-dur {
font-size: 11px;
font-family: monospace;
color: #4b5563;
white-space: nowrap;
min-width: 32px;
}
#tl-dur {
text-align: right;
}
#tl-body {
flex: 1;
position: relative;
overflow: hidden;
}
#tl-tracks {
position: absolute;
inset: 0;
overflow-y: auto;
overflow-x: hidden;
}
.tl-row {
display: flex;
align-items: center;
height: 26px;
border-bottom: 1px solid #111827;
}
.tl-row:hover {
background: rgba(255, 255, 255, 0.02);
}
.tl-label {
width: 120px;
flex-shrink: 0;
font-size: 11px;
font-family: monospace;
color: #4b5563;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border-right: 1px solid #1f2937;
}
.tl-track {
flex: 1;
position: relative;
height: 100%;
}
.tl-block {
position: absolute;
top: 4px;
height: 17px;
border-radius: 3px;
cursor: grab;
opacity: 0.75;
min-width: 4px;
user-select: none;
}
.tl-block:hover {
opacity: 1;
}
.tl-block.dragging {
opacity: 1;
cursor: grabbing;
}
.tl-handle {
position: absolute;
top: 0;
bottom: 0;
width: 6px;
cursor: ew-resize;
}
.tl-handle-l {
left: 0;
border-radius: 3px 0 0 3px;
}
.tl-handle-r {
right: 0;
border-radius: 0 3px 3px 0;
}
.tl-handle:hover {
background: rgba(255, 255, 255, 0.25);
}
#tl-playhead {
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background: #f87171;
pointer-events: none;
left: 120px;
z-index: 10;
}
/* ── Open overlay ── */
#open-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.7);
display: none;
align-items: center;
justify-content: center;
z-index: 100;
}
#open-overlay.visible {
display: flex;
}
#open-dialog {
background: #161b27;
border: 1px solid #1f2937;
border-radius: 8px;
padding: 20px;
width: 680px;
max-height: 80vh;
display: flex;
flex-direction: column;
gap: 12px;
}
#open-dialog h2 {
font-size: 15px;
font-weight: 600;
color: #f9fafb;
}
#open-dialog p {
font-size: 12px;
color: #6b7280;
}
#open-textarea {
flex: 1;
min-height: 300px;
background: #0f1117;
color: #d1d5db;
border: 1px solid #374151;
border-radius: 4px;
padding: 10px;
font-size: 12px;
font-family: monospace;
resize: vertical;
}
#open-dialog .dialog-actions {
display: flex;
gap: 8px;
justify-content: flex-end;
}
</style>
</head>
<body>
<div id="header">
<h1>@hyperframes/sdk</h1>
<span class="badge">editor</span>
<span id="comp-name" style="font-size: 12px; color: #4b5563; font-family: monospace"
>demo</span
>
<span class="spacer"></span>
<span class="sel-label">selection:</span>
<span id="sel-display">(none)</span>
<button id="btn-undo" class="ghost">← Undo</button>
<button id="btn-redo" class="ghost">Redo →</button>
<button id="btn-open" class="primary">Open…</button>
</div>
<div id="app-main">
<!-- Preview -->
<div id="preview-panel">
<div id="preview-scaler-outer">
<div id="preview-scaler-inner">
<iframe id="preview-frame" sandbox="allow-scripts" title="composition preview"></iframe>
</div>
</div>
<div id="preview-hint">click to select</div>
</div>
<!-- Inspector -->
<div id="inspector-panel">
<div id="inspector-tabs">
<div class="ins-tab active" data-tab="properties">Properties</div>
<div class="ins-tab" data-tab="ops">Ops</div>
</div>
<div id="element-list"><!-- populated by JS --></div>
<div id="inspector-content"><!-- populated by JS --></div>
</div>
<!-- Log -->
<div id="log-panel">
<div class="panel-title">Patch log</div>
<div id="log-entries"><!-- populated by JS --></div>
</div>
</div>
<!-- Timeline -->
<div id="timeline-panel">
<div id="tl-controls">
<button id="btn-play" class="ghost" style="padding: 4px 8px; font-size: 13px"></button>
<span id="tl-time">0.0s</span>
<input type="range" id="tl-scrubber" min="0" max="1000" value="0" step="1" />
<span id="tl-dur"></span>
</div>
<div id="tl-body">
<div id="tl-tracks"><!-- populated by JS --></div>
<div id="tl-playhead"></div>
</div>
</div>
<!-- Open dialog -->
<div id="open-overlay">
<div id="open-dialog">
<h2>Open composition</h2>
<p>
Paste any HyperFrames composition HTML — the outer <code>data-hf-root</code> element and
its contents.
</p>
<textarea
id="open-textarea"
spellcheck="false"
placeholder='<div data-hf-id="hf-stage" data-hf-root ...>'
></textarea>
<div class="dialog-actions">
<button id="btn-open-cancel">Cancel</button>
<button id="btn-open-confirm" class="primary">Open</button>
</div>
</div>
</div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+17
View File
@@ -0,0 +1,17 @@
{
"name": "@hyperframes/sdk-playground",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"@hyperframes/core": "workspace:*",
"@hyperframes/sdk": "workspace:*",
"gsap": "^3.15.0"
},
"devDependencies": {
"vite": "^6.4.2"
}
}
@@ -0,0 +1,59 @@
import type { PersistAdapter, PersistVersionEntry } from "@hyperframes/sdk/adapters/types";
import type { PersistErrorEvent } from "@hyperframes/sdk";
const API = "/api/composition";
class FileAdapter implements PersistAdapter {
private errorHandlers = new Set<(e: PersistErrorEvent) => void>();
async read(_path: string): Promise<string | undefined> {
const res = await fetch(API);
if (res.status === 404) return undefined;
if (!res.ok) throw new Error(`read failed: ${res.status}`);
return res.text();
}
async write(_path: string, content: string): Promise<void> {
try {
const res = await fetch(API, {
method: "PUT",
headers: { "Content-Type": "text/html; charset=utf-8" },
body: content,
});
if (!res.ok) throw new Error(`write failed: ${res.status}`);
} catch (err) {
for (const h of this.errorHandlers) h({ error: { message: String(err), cause: err } });
}
}
async flush(): Promise<void> {}
async listVersions(_path: string): Promise<PersistVersionEntry[]> {
const res = await fetch("/api/composition/versions");
if (!res.ok) return [];
const rows = (await res.json()) as Array<{ key: string; timestamp?: number }>;
return rows.map((r) => ({ key: r.key, timestamp: r.timestamp }));
}
async loadFrom(_path: string, versionKey: string): Promise<string | undefined> {
const res = await fetch(`/api/composition?version=${encodeURIComponent(versionKey)}`);
if (res.status === 404) return undefined;
if (!res.ok) throw new Error(`loadFrom failed: ${res.status}`);
return res.text();
}
on(event: "persist:error", handler: (e: PersistErrorEvent) => void): () => void {
if (event !== "persist:error") return () => {};
this.errorHandlers.add(handler);
return () => this.errorHandlers.delete(handler);
}
}
export async function createFileAdapter(): Promise<{
adapter: PersistAdapter;
initialHtml: string | undefined;
}> {
const adapter = new FileAdapter();
const initialHtml = await adapter.read("composition.html");
return { adapter, initialHtml };
}
File diff suppressed because it is too large Load Diff
+85
View File
@@ -0,0 +1,85 @@
import { defineConfig } from "vite";
import path from "node:path";
import type { Plugin } from "vite";
import type { Connect } from "vite";
import type { ServerResponse } from "node:http";
import { createFsAdapter } from "@hyperframes/sdk/adapters/fs";
import type { PersistAdapter } from "@hyperframes/sdk/adapters/types";
const COMP_ROOT = path.resolve(import.meta.dirname);
const COMP_PATH = "composition.html";
function sendHtml(res: ServerResponse, html: string | undefined) {
if (html === undefined) {
res.statusCode = 404;
res.end("");
return;
}
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(html);
}
function readBody(req: Connect.IncomingMessage): Promise<string> {
return new Promise((resolve) => {
const chunks: Buffer[] = [];
req.on("data", (c: Buffer) => chunks.push(c));
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
});
}
function versionKeyOf(req: Connect.IncomingMessage): string | null {
return new URL(req.url ?? "/", "http://localhost").searchParams.get("version");
}
async function handleCompositionGet(
adapter: PersistAdapter,
req: Connect.IncomingMessage,
res: ServerResponse,
) {
const versionKey = versionKeyOf(req);
const html = versionKey
? await adapter.loadFrom(COMP_PATH, versionKey)
: await adapter.read(COMP_PATH);
sendHtml(res, html);
}
async function handleCompositionPut(
adapter: PersistAdapter,
req: Connect.IncomingMessage,
res: ServerResponse,
) {
await adapter.write(COMP_PATH, await readBody(req));
res.statusCode = 204;
res.end();
}
function methodNotAllowed(res: ServerResponse) {
res.statusCode = 405;
res.end();
}
function compositionPlugin(): Plugin {
const adapter = createFsAdapter({ root: COMP_ROOT });
return {
name: "hf-composition",
configureServer(server) {
server.middlewares.use("/api/composition/versions", async (req, res) => {
if (req.method !== "GET") return methodNotAllowed(res);
const versions = await adapter.listVersions(COMP_PATH);
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(versions.map((v) => ({ key: v.key, timestamp: v.timestamp }))));
});
server.middlewares.use("/api/composition", async (req, res) => {
if (req.method === "GET") return handleCompositionGet(adapter, req, res);
if (req.method === "PUT") return handleCompositionPut(adapter, req, res);
methodNotAllowed(res);
});
},
};
}
export default defineConfig({
plugins: [compositionPlugin()],
});
+96 -14
View File
@@ -1,44 +1,126 @@
import type { PersistAdapter, PersistVersionEntry } from "./types.js";
import type { PersistErrorEvent } from "../types.js";
import { readFile, writeFile, mkdir, readdir, unlink } from "node:fs/promises";
import { join, dirname } from "node:path";
export interface FsAdapterOptions {
/** Root directory for composition files */
root: string;
/** Max versions to keep per file. Default: 20 */
maxVersions?: number;
}
// Phase 4 — fs adapter stub. Full implementation in SDK Phase 4 (adapters stage).
// Uses Node.js fs/promises; not browser-safe (must be conditionally imported by consumers).
const DEFAULT_MAX_VERSIONS = 20;
let _versionCounter = 0;
class FsAdapter implements PersistAdapter {
private readonly root: string;
private readonly maxVersions: number;
private errorHandlers: Array<(e: PersistErrorEvent) => void> = [];
private _writeLocks = new Map<string, Promise<void>>();
constructor(opts: FsAdapterOptions) {
this.root = opts.root;
this.maxVersions = opts.maxVersions ?? DEFAULT_MAX_VERSIONS;
}
async read(_path: string): Promise<string | undefined> {
throw new Error("FsAdapter: Phase 4 — not yet implemented");
async read(path: string): Promise<string | undefined> {
try {
return await readFile(this.abs(path), "utf8");
} catch (err: unknown) {
if (isNotFound(err)) return undefined;
throw err;
}
}
async write(_path: string, _content: string): Promise<void> {
throw new Error("FsAdapter: Phase 4 — not yet implemented");
async write(path: string, content: string): Promise<void> {
try {
const abs = this.abs(path);
await mkdir(dirname(abs), { recursive: true });
await writeFile(abs, content, "utf8");
await this.appendVersion(path, content);
} catch (err) {
for (const h of this.errorHandlers) h({ error: { message: String(err), cause: err } });
}
}
async flush(): Promise<void> {
throw new Error("FsAdapter: Phase 4 — not yet implemented");
async flush(): Promise<void> {}
async listVersions(path: string): Promise<PersistVersionEntry[]> {
const dir = this.versionsDir(path);
try {
const entries = await readdir(dir);
const sorted = entries
.filter((f) => f.endsWith(".html"))
.sort()
.reverse();
return Promise.all(
sorted.map(async (f) => {
const key = f.replace(/\.html$/, "");
return {
key,
content: await readFile(join(dir, f), "utf8"),
timestamp: Number(key.split("-")[0]),
};
}),
);
} catch {
return [];
}
}
async listVersions(_path: string): Promise<PersistVersionEntry[]> {
throw new Error("FsAdapter: Phase 4 — not yet implemented");
async loadFrom(path: string, versionKey: string): Promise<string | undefined> {
try {
return await readFile(join(this.versionsDir(path), `${versionKey}.html`), "utf8");
} catch {
return undefined;
}
}
async loadFrom(_path: string, _versionKey: string): Promise<string | undefined> {
throw new Error("FsAdapter: Phase 4 — not yet implemented");
on(event: "persist:error", handler: (e: PersistErrorEvent) => void): () => void {
if (event !== "persist:error") return () => {};
this.errorHandlers.push(handler);
return () => {
const i = this.errorHandlers.indexOf(handler);
if (i !== -1) this.errorHandlers.splice(i, 1);
};
}
on(_event: "persist:error", _handler: (e: PersistErrorEvent) => void): () => void {
return () => {};
private abs(path: string): string {
return join(this.root, path);
}
private versionsDir(path: string): string {
return join(this.root, ".hf-versions", path);
}
private async appendVersion(path: string, content: string): Promise<void> {
const prior = this._writeLocks.get(path) ?? Promise.resolve();
const next = prior.then(() => this._doAppendVersion(path, content));
this._writeLocks.set(
path,
next.catch(() => {}),
);
return next;
}
private async _doAppendVersion(path: string, content: string): Promise<void> {
const dir = this.versionsDir(path);
await mkdir(dir, { recursive: true });
const key = `${Date.now()}-${String(++_versionCounter).padStart(4, "0")}`;
await writeFile(join(dir, `${key}.html`), content, "utf8");
// prune oldest beyond maxVersions
const all = (await readdir(dir)).filter((f) => f.endsWith(".html")).sort();
const excess = all.length - this.maxVersions;
if (excess > 0) {
await Promise.all(all.slice(0, excess).map((f) => unlink(join(dir, f)).catch(() => {})));
}
}
}
function isNotFound(err: unknown): boolean {
return (err as NodeJS.ErrnoException)?.code === "ENOENT";
}
export function createFsAdapter(opts: FsAdapterOptions): PersistAdapter {
+2 -1
View File
@@ -5,7 +5,8 @@ import type { PersistErrorEvent } from "../types.js";
export interface PersistVersionEntry {
/** Opaque key identifying this version (adapter-defined format) */
key: string;
content: string;
/** Full HTML content — may be omitted by adapters that load content lazily via loadFrom() */
content?: string;
timestamp?: number;
}
+32
View File
@@ -285,6 +285,13 @@ function handleSetTiming(
timing: { start?: number; duration?: number; trackIndex?: number },
): MutationResult {
const result: MutationResult = { forward: [], inverse: [] };
// Parse GSAP script once; updateAnimationInScript re-parses internally per call but
// we avoid re-fetching the script element on every iteration.
const origScript = getGsapScript(parsed.document);
const parsedGsap = origScript ? parseGsapScriptAcornForWrite(origScript) : null;
let currentScript = origScript;
for (const id of ids) {
const el = findById(parsed.document, id);
if (!el) continue;
@@ -332,7 +339,32 @@ function handleSetTiming(
result.inverse.push(p.inverse);
el.setAttribute("data-track-index", String(newTrack));
}
// Sync GSAP tween positions: the GSAP script is the source of truth at play time —
// the timeline rebuilds from it on every seek. Without this, DOM attribute edits
// have zero playback effect; the script's position/duration silently overrides them.
if (parsedGsap && currentScript) {
for (const { id: animId, animation } of parsedGsap.located) {
const sel = animation.targetSelector;
if (sel !== `[data-hf-id="${id}"]` && sel !== `[data-hf-id='${id}']` && sel !== `#${id}`)
continue;
const updates: Partial<GsapAnimation> = {};
if (timing.start !== undefined && newStart !== null) updates.position = newStart;
if (timing.duration !== undefined && newDuration !== null) updates.duration = newDuration;
if (Object.keys(updates).length === 0) continue;
currentScript = updateAnimationInScript(currentScript, animId, updates);
}
}
}
// Flush accumulated GSAP script changes as a single patch pair.
if (origScript && currentScript && currentScript !== origScript) {
setGsapScript(parsed.document, currentScript);
const gsapResult = gsapScriptChange(origScript, currentScript);
result.forward.push(...gsapResult.forward);
result.inverse.push(...gsapResult.inverse);
}
return result;
}