/playhtml:building-playhtml-elementsfrom playhtml
Guides building collaborative, real-time HTML elements using playhtml and Yjs CRDTs. Covers data types (defaultData, presence, events), React vs vanilla HTML, and design philosophy for multiplayer interactions.
Ships in playhtml. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
playhtml makes HTML elements collaborative and real-time via Yjs CRDTs.
playhtml is for people making their own internet playgrounds. The experience is theirs to design; your job is to make their idea work, not to fill in the idea for them.
If the person says to surprise them or to use your judgment, you may make those choices, and say which ones you made.
Along with any open experience decisions above, if the request is ambiguous on ANY of these, stop and ask:
defaultData=yes, presence=no)These determine which API and data type to use. Getting them wrong means a rewrite.
| Type | Persists? | Syncs? | Use for |
|---|---|---|---|
defaultData | Yes | Yes | Positions, counts, messages, toggles |
presence: defaultPresence (element) / playhtml.people.setMyPresence (page) | No | Yes | Per-person typing, ready, hover, or selection state |
dispatchPlayEvent | No | One-shot | Confetti, notifications |
localStorage | Yes | No | Per-user flags ("has reacted") |
People: every person is a Person ({ pid, name, color, isMe, presence }). playhtml.people.everyone is everyone on the page including you (filter !person.isMe for others); playhtml.people.me is you (assign me.name / me.color to save and show them). Key per-person data by pid. Page presence: playhtml.people.setMyPresence(key, value) sets one key (null clears it), playhtml.people.onChange(keys?, cb) fires now and on changes (skips cursor moves unless "cursor" is in keys). Cursors are at person.presence.cursor. playhtml.people is available after playhtml.ready. Rooms: playhtml.createPresenceRoom(name).people, same API. React: usePeople(keys?) → { everyone, me, setMyPresence }, also on usePlayContext().people. Elements use the same names: defaultPresence, and everyone / me / setMyPresence(value | mutator) in callbacks and on handles (handle.onEveryoneChange(keys?, cb)). Deprecated but working: playhtml.users, User, playhtml.presence, useUsers, usePresence, useCursorPresences, usePlayerIdentity, element live/users/setLive.
id attribute — without it, sync silently failsimport { playhtml } from "https://unpkg.com/playhtml@latest" only works inside <script type="module">, never a plain <script>playhtml.register(elementOrId, initializer)<PlayProvider>Put the script at the end of <body>, and give the tag type="module". A plain
<script> throws "Cannot use import statement outside a module" and nothing
syncs.
<div id="myElement"></div>
<script type="module">
import { playhtml } from "https://unpkg.com/playhtml@latest";
const el = document.getElementById("myElement");
playhtml.register(el, {
defaultData: { count: 0 }, // REQUIRED
defaultPresence: { ready: false }, // optional, per-person, not saved
update: ({ element, data, everyone, me }) => { ... }, // REQUIRED
onClick: (e, { data, setData }) => { ... },
onDrag: (e, { data, setData, localData, setLocalData }) => { ... },
onDragStart: (e, { setLocalData }) => { ... },
onMount: ({ getData, setData, getElement }) => { ... },
resetShortcut: "shiftKey", // "shiftKey"|"ctrlKey"|"altKey"|"metaKey"
});
playhtml.init();
</script>
Every other vanilla snippet in this guide that uses playhtml goes inside the
same <script type="module"> block.
Pass an element when you already have the DOM node, or pass its id before it
exists. register works before or after init(). Use
setupPlayElement(element) after inserting a dynamic built-in or defined
capability. Registered custom elements bind automatically.
import { PlayProvider, withSharedState, usePlayContext } from "@playhtml/react";
const Counter = withSharedState(
{ defaultData: { count: 0 } },
({ data, setData, ref }) => (
<button
ref={ref}
onClick={() => {
setData((draft) => {
draft.count += 1;
});
}}
>
{data.count}
</button>
)
);
// Component receives: data, setData, everyone, me, setMyPresence, ref (pass defaultPresence for presence)
// For events: usePlayContext() → { dispatchPlayEvent, registerPlayEventListener }
// For people and cursors: usePeople() or usePlayContext().people → { everyone, me, setMyPresence }
// Mutator form: edit the current shared draft.
// Use this for increments, arrays, nested fields, and keyed collections.
setData((draft) => { draft.count += 1; });
setData((draft) => { draft.items.push(newItem); });
setData((draft) => { draft.settings.theme = "dark"; });
setData((draft) => { draft.byUser[userId] = value; });
// Replacement form: replaces ALL data.
// Use only when intentionally replacing the whole stored value.
setData({ on: true });
setData({ x: e.clientX, y: e.clientY });
Avoid replacement writes that rebuild from rendered data:
// Bad for counters: can overwrite newer synced counts.
setData({ count: data.count + 1 });
// Bad for appends: concurrent appends compete over one replacement.
setData({ messages: [...data.messages, message] });
For bounded lists, push and cap in the same mutator:
setData((draft) => {
draft.messages.push(message);
if (draft.messages.length > 100) {
draft.messages.splice(0, draft.messages.length - 100);
}
});
The most dangerous bug in playhtml. A React effect (or updateElement) that both reads shared data and writes it loops forever: the write changes the data → the dependency re-fires → it writes again. Because the data is a CRDT, concurrent writes from multiple readers append rather than overwrite, so the loop never converges to a value a guard can catch. This passes local testing and only blows up once several readers connect, when the room's data grows without bound until the page stops loading.
// DANGER — infinite write loop
useEffect(() => {
setData({ entries: [...data.entries, me] }); // writes entries…
}, [data.entries]); // …re-runs because entries changed
Strongest fix — model unique collections as a keyed map and upsert in place with the mutator form. A keyed write is idempotent (same id overwrites, never appends) and merge-safe (maps are last-write-wins per key), so even if the effect loops it cannot grow the doc:
// entries is keyed by id, not an array
const ref = useRef(data.entries); ref.current = data.entries;
useEffect(() => {
if (ref.current[me.id]?.name === me.name) return; // already correct
setData((draft) => { draft.entries[me.id] = me; }); // keyed, idempotent, merge-safe
}, [me.id, me.name]); // local identity only — NOT data.entries
Two reinforcing rules: (1) prefer keyed-map + mutator upsert over array + replacement rewrite; (2) read the data through a ref so the effect depends on local identity, not the shared collection. If you truly need an array, you must both read via ref AND dedupe-by-id into a Map before writing — but a keyed map is almost always the right shape.
Rule of thumb: write shared data from explicit user events, not from reactive callbacks. If you must write from a callback, prove it converges. Full explanation: https://playhtml.fun/docs/advanced/data-best-practices/#7-never-write-shared-data-from-code-that-re-runs-when-that-data-changes
defaultData only seeds brand-new elements. A room that already has persisted data loads it as-is — so if you change the data's shape (array→map, rename a field, add a required field) for something already deployed, existing rooms hydrate the OLD shape into your NEW code. That mismatch crashes the page: e.g. a keyed write data.entries[pid] = … against a room whose entries is still a legacy Y.Array throws and blanks the page; reads of a field that doesn't exist yet are undefined and throw.
If you are changing the shape of data that is already live, STOP and flag it to the user, then pick one (in order of preference):
resetShortcut), accepting that saved state is lost.Only applies to already-live / persisted data — brand-new features have no old data. Testing against a fresh room will NOT catch this: verify a shape change by loading the real page against a room that still holds the old shape.
Use instead of can-play when they fit: can-move, can-toggle, can-spin, can-grow, can-duplicate, can-hover, can-mirror. See https://playhtml.fun/docs/capabilities/ for each one.
playhtml.init({ cursors: { enabled: true, room: "page" } }); // "page"|"domain"|"section"
await playhtml.ready;
playhtml.people.everyone.length; // people here (window.cursors still works but is legacy)
playhtml.people.onChange("cursor", (everyone) => { /* person.presence.cursor */ });
See https://playhtml.fun/docs/advanced/cursors/ for full API.
playhtml.register(elementOrId, initializer) so setup does not depend on assigning callbacks to a DOM node before initialization.id: No id = no sync. Silent failure.defaultData for ephemeral user state (it leaves stale data). Refer to the Data Types table.push()/splice() only — shift(), pop(), and items[i] = x don't sync correctly.setData({ x: 5 }) erases y. Use replacement only for whole-value writes, or use mutator form for field-level changes.setData on every mousemove. Debounce, or use setLocalData/presence (rate limited to ~20 writes/s; use cursors for pointer position).
update/render.withSharedState silently fails without it.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub spencerc99/playhtml --plugin playhtml2 skills in this plugin
Other plugins' skills for the same job