Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/custom.css
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,11 @@ samp {
border-radius: 0;
border-color: var(--hf-ui-border) !important;
color: var(--hf-heading) !important;
/* The whole command stays on screen. A page's link can add values to it, and
a reader should see everything they are about to paste, not the start of a
line that scrolls. */
white-space: pre-wrap;
overflow-wrap: anywhere;
}

/*
Expand Down
161 changes: 142 additions & 19 deletions docs/snippets/catalog-detail.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,21 @@ export const CatalogDetail = ({
font-variant-numeric: tabular-nums;
color: var(--ve-muted);
}
.hf-ve-link-notice {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px 16px;
margin: 0 0 12px;
padding: 10px 14px;
border: 1px solid var(--ve-line);
border-radius: 14px;
background: var(--ve-surface);
font-size: 13px;
line-height: 1.45;
color: var(--ve-fg);
}
.hf-ve-desc {
margin: 6px 0 0;
font-size: 12px;
Expand Down Expand Up @@ -1718,19 +1733,77 @@ export const CatalogDetail = ({
});
}

/** The entries of a parsed query object that name a declared id and hold a primitive value. */
function declaredValues(parsed, ids) {
/**
* Whether a value from a link fits the variable it names.
*
* A link is written by whoever shares it, and the value goes into a
* composition that may put it straight into markup. So each value has to look
* like what its control could have produced: a number for a slider, one of the
* listed options for a choice, a colour for a swatch, an address for an image,
* and text with no markup for a string. The declared default always passes.
*/
function fitsVariable(variable, value) {
if (JSON.stringify(value) === JSON.stringify(variable.default)) return true;
switch (variable.type) {
case "number":
return typeof value === "number" && Number.isFinite(value);
case "boolean":
return typeof value === "boolean";
case "enum":
return (variable.options ?? []).some((option) => option.value === value);
case "color":
return (
typeof value === "string" &&
/^(?:#[0-9a-f]{3,8}|[a-z]{3,24}|(?:rgb|hsl)a?\([\d\s.,%/+-]{1,48}\))$/i.test(value)
);
case "image":
return (
typeof value === "string" &&
value.length <= 2048 &&
/^(?:https?:\/\/|[\w./-])[^\s<>"'`()\\]*$/i.test(value)
);
default:
return typeof value === "string" && value.length <= 10000 && !/[<>]/.test(value);
}
}

/** The entries of a parsed query object that name a declared variable and fit its type. */
function declaredValues(parsed, variables) {
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const byId = new Map(variables.map((variable) => [variable.id, variable]));
return Object.fromEntries(
Object.entries(parsed).filter(([id, value]) => {
if (!ids.has(id)) return false;
if (typeof value === "number") return Number.isFinite(value);
return typeof value === "string" || typeof value === "boolean";
}),
Object.entries(parsed).filter(([id, value]) => byId.has(id) && fitsVariable(byId.get(id), value)),
);
}
// <<< preview values

// >>> copied values
/**
* Whether a value a link arrived with can go into a copied command as it is.
*
* The command is pasted into whatever shell the reader has: bash, zsh, fish,
* PowerShell or cmd.exe. They agree on almost nothing about quoting, so
* rather than escape for each, a link's text is carried only when it is
* short and made of letters, digits, spaces and punctuation that none of them
* reads as syntax inside the argument. Numbers and booleans always qualify.
*/
function plainLinkValue(value) {
if (typeof value === "number") return Number.isFinite(value);
if (typeof value === "boolean") return true;
return typeof value === "string" && value.length <= 200 && /^[A-Za-z0-9 .,:_#+\-/@()?]*$/.test(value);
}

/**
* The changed values copied text may carry: every value the reader set on
* this page, and a value a link arrived with only when `keepFromLink` allows.
*/
function copiedValues(changed, edited, keepFromLink) {
return Object.fromEntries(
Object.entries(changed).filter(([id, value]) => edited.includes(id) || keepFromLink(id, value)),
);
}
// <<< copied values

const readFromUrl = () => {
if (typeof window === "undefined") return {};
try {
Expand All @@ -1739,15 +1812,28 @@ export const CatalogDetail = ({
// `URLSearchParams` has already decoded this once. Decoding again turned
// a path full of percent-escapes into something that no longer parsed,
// and doubled the length of every link.
// Only ids this item declares; a stale link must not inject stray keys.
return declaredValues(JSON.parse(raw), new Set(variables.map((v) => v.id)));
// Only ids this item declares, each holding what its control could have
// set; a stale or hand-made link must not inject stray keys or markup.
return declaredValues(JSON.parse(raw), variables);
} catch {
return {};
}
};

const [values, setValues] = useState(() => ({ ...defaults, ...readFromUrl() }));

/**
* Ids the reader set on this page, and ids the link opened the page with.
*
* A link is written by whoever shared it. Its values still drive the
* preview, but the copy buttons only treat a value as the reader's own once
* they have set it here: until then a link's free text stays out of the
* agent request and the commands. The install command is a separate
* component, so the list is also published on `window` for it.
*/
const [edited, setEdited] = useState([]);
const [fromLink, setFromLink] = useState([]);

/**
* Read the URL again once the component is actually in a browser.
*
Expand All @@ -1763,11 +1849,15 @@ export const CatalogDetail = ({
useEffect(() => {
const fromUrl = readFromUrl();
if (Object.keys(fromUrl).length > 0) setValues((current) => ({ ...current, ...fromUrl }));
setFromLink(
Object.keys(fromUrl).filter((id) => JSON.stringify(fromUrl[id]) !== JSON.stringify(defaults[id])),
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// `replaceState` rather than `pushState`: dragging a slider should not stack
// up history entries the back button has to walk through.
const publishedEdited = useRef("");
useEffect(() => {
if (typeof window === "undefined") return;
const changed = Object.fromEntries(
Expand All @@ -1781,13 +1871,16 @@ export const CatalogDetail = ({
// Comparing first keeps it to an actual change rather than touching the
// history API on each one.
const next = url.toString();
if (next !== window.location.href) {
window.history.replaceState(null, "", next);
const editedNow = JSON.stringify(edited);
if (next !== window.location.href || editedNow !== publishedEdited.current) {
if (next !== window.location.href) window.history.replaceState(null, "", next);
publishedEdited.current = editedNow;
window.__hfEditedVars = { ...window.__hfEditedVars, [compositionId]: edited };
// `replaceState` fires no event, and the install command on the same page
// needs to follow these values.
window.dispatchEvent(new CustomEvent("hf-vars-changed"));
}
}, [values, defaults, urlKey]);
}, [values, defaults, urlKey, edited, compositionId]);
// What the SVG import last had to say, per variable. Held here because
// `control` is a function rather than a component and cannot hold it itself.
const [notes, setNotes] = useState({});
Expand Down Expand Up @@ -1880,6 +1973,10 @@ export const CatalogDetail = ({
" arm(resumeAt || 0);",
" }",
" player = document.createElement('hyperframes-player');",
// The composition runs with values a shared link chose, so it gets an
// origin of its own rather than this page's: whatever it does stays inside
// the preview. This script only ever talks to it through the player's API.
" player.setAttribute('sandbox-origin', 'opaque');",
" player.setAttribute('controls', ''); player.setAttribute('muted', '');",
" document.body.appendChild(player);",
" player.addEventListener('ended', function () { player.seek(0); player.play(); });",
Expand Down Expand Up @@ -1939,6 +2036,16 @@ export const CatalogDetail = ({
snippetLines.push([[SHIKI.punct, "></"], [SHIKI.tag, "div"], [SHIKI.punct, ">"]]);

const dirty = variables.some((v) => values[v.id] !== defaults[v.id]);
const resetValues = () => {
setValues(defaults);
setNotes({});
setEdited([]);
setFromLink([]);
};
// Values the link set that the reader has not touched since.
const heldFromLink = fromLink.filter(
(id) => !edited.includes(id) && JSON.stringify(values[id]) !== JSON.stringify(defaults[id]),
);

const hasTune = variables.length > 0;
const [tab, setTab] = useState("preview");
Expand All @@ -1958,12 +2065,16 @@ export const CatalogDetail = ({
return changed;
};
const renderCommand = (() => {
const changed = changedValues();
const changed = copiedValues(changedValues(), edited, (id, value) => plainLinkValue(value));
const vars = Object.keys(changed).length ? ` --variables '${JSON.stringify(changed).replace(/'/g, "'\\''")}'` : "";
return `# Run from the installed project's root.\nnpx hyperframes render --composition '${compositionSrc}'${vars}`;
})();
const agentRequest = (() => {
const changed = changedValues();
// The reader pastes this to an agent as their own words, so a link's text
// never goes in: only numbers, switches and the author's own options do.
const changed = copiedValues(changedValues(), edited, (id, value) =>
typeof value !== "string" || variables.some((v) => v.id === id && v.type === "enum"),
);
const base = `Install the HyperFrames catalog item "${compositionId}" (${title || compositionId}) into my project with \`npx hyperframes add ${compositionId}\`, mount it at the point of my composition where it should play, and verify with \`npx hyperframes check\`.`;
const set = Object.entries(changed).map(([id, value]) => `${id} = ${JSON.stringify(value)}`);
return set.length ? `${base} Set ${set.join(", ")}; keep the other variables at their defaults.` : `${base} Keep the default variables unless I say otherwise.`;
Expand Down Expand Up @@ -2109,6 +2220,18 @@ export const CatalogDetail = ({

<div className="not-prose">

{heldFromLink.length > 0 && (
<div className="hf-ve-link-notice" role="status">
<span>
This page opened with settings from its link: {heldFromLink.join(", ")}. Text from a link
stays out of copied commands and the agent request until you set it here.
</span>
<button type="button" className="hf-ve-action" onClick={resetValues}>
Reset to defaults
</button>
</div>
)}

<div className="hf-ve-bar">
<div className="hf-ve-meta">
{seconds && (
Expand Down Expand Up @@ -2162,7 +2285,10 @@ export const CatalogDetail = ({
{control(
v,
values[v.id],
(next) => setValues((prev) => ({ ...prev, [v.id]: next })),
(next) => {
setEdited((prev) => (prev.includes(v.id) ? prev : [...prev, v.id]));
setValues((prev) => ({ ...prev, [v.id]: next }));
},
notes[v.id],
(note) => setNotes((prev) => ({ ...prev, [v.id]: note })),
setTyping,
Expand All @@ -2174,10 +2300,7 @@ export const CatalogDetail = ({
<div className="hf-ve-tune-foot">
<button
type="button"
onClick={() => {
setValues(defaults);
setNotes({});
}}
onClick={resetValues}
disabled={!dirty}
className="hf-ve-action"
>
Expand Down
23 changes: 18 additions & 5 deletions docs/snippets/install-command.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,23 @@ export const InstallCommand = ({ command, item }) => {
* The ` --vars '<json>'` suffix for a query value, or "" when nothing usable is in it.
*
* Keeps variable-id keys with string, finite number or boolean values, and
* escapes `'` so the JSON stays one shell argument.
* escapes `'` so the JSON stays one shell argument in bash and zsh.
*
* `edited` lists the ids the reader set on this page. Any other string came
* with the link, from whoever shared it, and the command may be pasted into
* fish, PowerShell or cmd.exe, which quote differently. So such a string is
* kept only when it is short and holds nothing those shells read as syntax.
*/
function varsArgument(raw) {
function varsArgument(raw, edited = []) {
if (!raw) return "";
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return "";
const kept = Object.entries(parsed).filter(([id, value]) => {
if (!/^[A-Za-z_][\w-]*$/.test(id)) return false;
if (typeof value === "number") return Number.isFinite(value);
return typeof value === "string" || typeof value === "boolean";
if (typeof value === "boolean") return true;
if (typeof value !== "string") return false;
return edited.includes(id) || (value.length <= 200 && /^[A-Za-z0-9 .,:_#+\-/@()?]*$/.test(value));
});
if (kept.length === 0) return "";
return ` --vars '${JSON.stringify(Object.fromEntries(kept)).replace(/'/g, "'\\''")}'`;
Expand All @@ -65,7 +72,13 @@ export const InstallCommand = ({ command, item }) => {

const read = () => {
try {
setTuned(varsArgument(new URLSearchParams(window.location.search).get(`vars-${item}`)));
const edited = window.__hfEditedVars?.[item];
setTuned(
varsArgument(
new URLSearchParams(window.location.search).get(`vars-${item}`),
Array.isArray(edited) ? edited : [],
),
);
} catch {
// A hand-edited link should leave the plain command, not break it.
setTuned("");
Expand Down Expand Up @@ -115,7 +128,7 @@ export const InstallCommand = ({ command, item }) => {

return (
<div className="hf-install-command not-prose my-4 flex items-stretch overflow-hidden rounded-xl border border-zinc-200 bg-zinc-50 dark:border-zinc-800 dark:bg-zinc-900">
<code className="flex-1 overflow-x-auto whitespace-nowrap border-r border-zinc-200 px-4 py-3 font-mono text-sm text-zinc-800 dark:border-zinc-800 dark:text-zinc-100">
<code className="flex-1 border-r border-zinc-200 px-4 py-3 font-mono text-sm text-zinc-800 dark:border-zinc-800 dark:text-zinc-100">
{fullCommand}
</code>
<button
Expand Down
Loading
Loading