clay.js
  1. ClayJS
  2. Reference
  3. API
  4. window.clay

window.clay

Everything on window.clay: saving, reading and writing data, edit mode, and what each plugin adds.

Everything on window.clay: saving, reading and writing data, edit mode, and what each plugin adds.

Members#

MemberWhat it does
clay.readyA Promise that resolves once clayjs has booted (core loaded, plugins attached). In inline scripts, await clay.ready before touching anything else. clay:ready fires on document at the same moment.
clay.start([name], fn)Runs app code once per page, after clay.ready. A repeat call with the same name, such as a live-sync merge re-inserting the script, does nothing. Unnamed calls share one slot, so a page with several app scripts names each one.
clay.effect(fn)Runs fn on the next microtask and again after every observed change to the document, including merges, undo and redo. Its own writes never re-trigger it. fn must be synchronous. Returns a function that stops it. See below for its edit-mode warnings.
clay.style(name, css), clay.style(href)Creates or refreshes a named <style>, or a stylesheet <link>, in place. Links match by URL origin and path, so a new ?v= updates the existing link. Marks the tag clay="no-dirty": it stays in saved HTML for the next load, and refreshing it does not add an undo step, start an autosave, or raise the close warning. The next real save carries the current CSS or URL. Available in both modes after clay.ready. Returns the element immediately, without waiting for a stylesheet to load. Use editor-ui for styles that must stay in this tab. See Styles a script writes.
clay.theme(options)Themes the UI ClayJS draws: dialogs and the people name prompt. See below.
clay.assets.load(name)Resolves a library the page asks for by name from the release that served clay.js: overtype, marked, highlight, and the grammars highlight/bash, highlight/css, highlight/javascript, highlight/json, highlight/python, highlight/xml, and uimotion. No library URL and nothing fetched from anywhere else. clay.assets.names() lists every name. See below.
clay.save()Snapshot the page and save it. Skips when nothing changed. Returns Promise<{ok, msg, msgType, code, etag}>; check ok. Never rejects. See below for msgType.
clay.save.force()Save even when nothing appears to have changed.
clay.save.soon()One save 250 ms after the last call and at most 1 s after the first, for a discrete change such as a drop or a toggle, so a peer sees it in well under a second. Every caller gets that save’s result, the same shape as clay.save(). If an incoming merge cancels that save while it is being prepared, it is captured again once after the merge settles. Typing keeps autosave’s timing.
clay.save.flush({keepalive, timeoutMs})Save now and resolve only when the host has accepted the bytes the page holds at that moment: Promise<{state, etag}>. See below.
clay.save.limits({fresh})The host’s save ceiling: Promise<{maxBytes}>, where maxBytes is the most bytes this host stores or null when it announced none. fresh: true asks the host again instead of reusing the answer discovery already gave. See below.
clay.save.inspect(html)Measure bytes that are not this page, such as a file you are about to import: Promise<{bytes, maxBytes, state}>. It captures nothing, sends nothing and moves no baseline. See below.
clay.hasUnsavedChanges()Is there work here that no save has written? Synchronous, and the same question the close warning asks: an edit in the DOM, or work a check registered through clay.registerUnsavedState reports as pending. Answers false in view mode.
clay.extractData(rules?)Read structured JSON from the live page. Supplied by the clay-data.js satellite. Omitted rules use the page’s api rules tag.
clay.applyData(values, {rules})Apply structured JSON to the live page atomically. Supplied by the clay-data.js satellite. It changes content only and refuses executable content, unsafe attributes, unknown keys, and HTML replacement without changing the page.
clay.readData(rules?)Read the saved file as {data, etag}. Always present in core. Omitted rules use the page’s api rules tag. Rejects when the host does not announce data-read, and in draft mode, where the saved file is not this visitor’s to read, with code: "DataUnavailableInDraft".
clay.writeData(values, {rules, ifMatch})Conditionally write JSON into the saved file and return {data, etag}. Requires an editable clean page, a connected sync plugin, a trustworthy ETag, and host support. Always present in core, and rejects when the host does not announce data-write, and in draft mode with code: "DataUnavailableInDraft".
clay.getHTML({transform, flushUndo})The exact HTML string a save would send, after all cleanup. transform(root) edits the detached clone and must be synchronous; flushUndo defaults to true. See below.
clay.addDocumentTransform(fn)Register a callback that receives the cloned document before serialization. The live page is never touched. Runs on every change check too, so keep it pure and repeatable (no timestamps, counters, or network).
clay.onSnapshot(fn)Like addDocumentTransform, but runs for every snapshot, including live-sync broadcasts.
clay.markDirty()Tell live sync the person just edited something it cannot see: an editor whose own UI is editor-ui and which writes its data itself. Call it on each user edit. Without it, an edit made while an incoming update waits on a script or stylesheet load can be recorded as already saved. Present on every edit-mode page, and in view mode when sync is loaded.
clay.isEditModeWhether this page is in edit mode right now (see edit mode).
clay.canEditWhether this person may edit this document (an owner cookie, a save token, or an edit receipt). A document opens in view mode even when this is true.
clay.modeThe current mode: "view", "edit" or "draft".
clay.setMode(mode)Switch to "edit" or "view". It takes one argument, and anything else throws a TypeError. Three answers: { ok: true, mode, changed } when the switch committed, with changed false when the tab was already in that mode; { ok: true, mode, changed: true, reloading: true } when a reload is on its way; and { ok: false, mode, code, pending } when it refused, with mode still the committed one and pending the ids of the sources that held the exit, when any did. Saving and reloading is the undeclared fallback: a document with <html clay-mode-switch="live"> switches live instead, and a workspace frame hands the change to its shell. The codes are listed in switching modes.
clay.modeLifecycleThe edit-mode participants and the live mode facts: register(participant) returns an unregister function, canWrite() says whether a write is admitted now, and state is a frozen snapshot. See below.
clay.derivedThe derived-paint policy: what a sapjs paint owns (isDerivedAttr(el, name), stripDerived(root)) and the hook an engine registers to repaint after a merge. ClayJS uses it to leave painted values out of comparisons, undo and merges. Apps rarely call it. See sap.js: records, views and totals in markup.
clay.isDraftModeWhether this visitor’s work is being kept in their own browser instead of saved to the host. It needs a page that opted in with visitor-drafts (a slot on <html>, the plugin in plugins=, an http(s) page and an api rules tag carrying data-rules-version="1" JSON that parses), so it is false everywhere else, including a normal edit of a file. Draft mode also sets draftmode="true" on <html>, and that is removed from every save. See Free documents for visitors.
clay.visitorDraftsThe draft store: active, slot, key, hasDraft(), saveNow(), reset(), onRestore(fn), editOriginal(), backToDraft(), downloadUrl() and source (visitor-drafts plugin). It is inert outside draft mode. See below for restored() and the events.
clay.isOwnerWhether the platform’s owner cookie is set. Unlike isEditMode, the URL and global overrides don’t affect it.
clay.siteVisibilityHow the host serves this site: "private", "public", or null when the host says nothing (hyperclay.com tells the owner’s tab). Read once, at boot.
clay.hostHost metadata asked for on use, so a page that never reads it never downloads the discovery client: clay.host.versions, a promise for whether this host keeps a version history a person can go back to. See below.
clay.toggleEditMode()Switch to the other mode through clay.setMode. In draft mode it opens ?editmode=true instead.
clay.cacheBust(el)Re-download one resource by stamping ?v= onto its href or src. Details.
clay.MutationThe shared mutation hub (one MutationObserver for the whole page, region rules applied). clay.Mutation.onAnyChange(opts, cb) respects clay="no-watch" regions. See Advanced.
clay.morph(oldEl, newEl)The DOM morphing engine: morphs oldEl in place to match newEl, preserving focus, inputs, and animations. Present in every mode. The engine downloads on the first call, so it returns a Promise: await clay.morph(oldEl, newEl). Its signature is unchanged on hyper-morph 1.0.
clay.conflictsEdits of yours that live sync replaced and you have not decided on: list(), acknowledge(ids, {reason}), claim(ids, {owner}), recoveryOf(id) (sync plugin). The lost edit notice draws from it. registerContext(resolver) registers the page’s own name for any subject the notice or a kept copy asks about, and returns a function that unregisters it; contextFor(subject, apply) asks the newest resolver first and answers {kind, id, label, field, open?} or null. A resolver receives a lost edit’s record (read the node it holds as subject.node), or, for a refused undo step, {source: "undo", id, element}, where id is the nearest [data-id] and element is what that id finds today.
clay.registerUnsavedState({id, isPending})For an editor whose work can be ahead of the page (its model not yet written into the DOM): isPending() is called fresh whenever the close warning checks, and the warning fires while it returns true. Returns {changed(), dispose()}; call changed() when the answer may have changed.
clay.undoThe page’s undo history (undo plugin): undo() and redo() return a receipt, command(label, fn) records one labelled step, setRecording() chooses automatic or commands recording, discard(entryId) drops a refused step, and history, future and the clay:undo-change event describe what the next press would replay. A refused step is kept for a later session, and the page can keep its own material: keep({key, label, context, payload}), kept(), dismissKept(id, {revision}), reviewActions(fn) for the buttons the review panel offers on a kept copy, and reviewActionsFor(record) to ask every provider yourself. See undo.
clay.storageBrowser storage for this document only: clay.storage.local and clay.storage.session. See below.
clay.recoveryThe local recovery copy of unsaved writing: one store per document and mode, for the channels a page registers. Edit mode only, draft mode included. register({channel, version, readSaved, describe}) returns a channel whose stage, flush, list, dismiss, subscribe and dispose work at once. See below and recovery.
clay.trashSoft delete: clay.trash(el) stamps the record with data-deleted-at, clay.trash.is(el), clay.trash.restore(el) and clay.trash.purge(el). A delete is an attribute change, so a peer’s edit merges with it and Undo restores the attribute. Fires clay:trashed and clay:restored. See below.
clay.ephemeralPer-tab state on saved elements: add(el, word), remove, toggle(el, word, force), has. Never saved, synced, undone or counted as a change. See attributes.
clay.unsentThe kept unsent text (unsent plugin): size, list() (one {record, name, base, text} per entry, where base is the value the person started from), clear(el) (drop the draft for that control’s record and name) and drop(record, name). Typing the text back to its base, or emptying it, drops the draft too. See unsent.
clay.cmsThe content panel: clay.cms.open() (cms plugin).
clay.RichClayThe rich-text editor class behind editable (richclay plugin, default on).
clay.quickcrop(file, opts)The crop modal: resolves {blob, dataURL, width, height}, or null if cancelled (quickcrop plugin). See Plugins.
clay.upload(file, {onProgress, signal, requiredAccess})Post a file you supply to the host (upload plugin). See below.
clay.upload.start(file, opts)The same upload as a task: progress, cancel and an explicit retry (upload plugin). See below.
clay.upload.mount(task, container)Draw the shared upload row for a task and resolve {unmount} (upload plugin). See below.
clay.meWho is editing: {id, name, initials, color} or null (people plugin). See below.
clay.peopleNames in this page: get, list, available, add (people plugin). See below.
clay.presenceWho else has this document open and what this tab is working on: getSnapshot(), subscribe(listener), setTarget(target) (sync plugin, and the page plugin’s reader). It is installed after boot, when the presence store loads, and clay:presence-ready fires on document then. See below.
clay.author(el, attr = "data-by")Stamp an element with your id and record you in the registry. With no host it asks your name once, remembered in this browser. Resolves your record, null if you cancel, and rejects with code: "people-unavailable" when the host failed to answer (offer a retry). On a host that names people it asks the host again first, so a sign-out or rename in the app is never stamped with the old name. Edit mode only (people plugin).
clay.wireA per-file control channel to a process on your own machine: send, cancel, get, list, isBusy, on, helpers (wire plugin). See Plugins.
clay.live(name)The page’s <script type="application/json" merge="name" clay="live"> tag as a live object: data, set, delete, add, update, on("change"), toJSON (live plugin). See Plugins.
clay.pageThe page editor’s ready, flush({timeoutMs}), install() and dispose() lifecycle, plus status (the session’s result) and view (the editor view, or null) (page plugin). flush resolves with {ok:true} after a checkpoint, or a failure result that keeps the close warning active. See Plugins.
clay.aiEditThe AI comment box: clay.aiEdit.init() and clay.aiEdit.open(element, { prompt }) (ai-edit plugin; booted by the plugin itself, and a no-op unless the host lists a ready ai-edit wire helper). See Plugins.
clay.sortable.move(item, target, beforeItem)The reorder a drag makes, without a drag: put item into target before beforeItem, or at the end of target when it is null. Returns {ok: true, moved, item, from, to, oldIndex, newIndex}, or {ok: false, code} for not-editable, detached, group, anchor and item. A real move fires clay:sorted and runs onsorted exactly as a drop does; a move to the position already held returns {ok: true, moved: false} and fires nothing. Edit mode only, and the plugin arrives late: wait for clay:plugin-ready (sortable plugin). See sortable.
clay.regionRegion policy helpers and strip selectors (see clay.internals.region; the same object, also published as STRIP_FROM_SAVE-style constants).
clay.menuThe menu plugin’s claygoo menu: addItem({id, label, run, badge}), open() and close(). A duplicate id replaces the earlier item, and badge puts a dot on claygoo. The plugin loads late, so wait for clay:plugin-ready (menu plugin). See menu.
clay.pluginsThe frozen list of plugin names the loader resolved for this page, late plugins included. It says what the page asked for, not what has finished loading.
clay.editPluginsThe frozen list of plugin names an edit session on this page would load, even while the page is in view. Chrome such as the menu reads it to offer an edit-only feature before the switch.
clay.save.overwrite()Ask the host for its current ETag, then force a save over it. The conflict notice’s Keep mine calls it; nothing else overwrites a conflict.
clay.save.replace(html, {etag})One conditional write of a whole document this page did not build, the write an upgrade makes (upgrade plugin). See conditional saves.
clay.bindText(textarea, options)Bind an editor textarea outside the records to one record’s text (bind-text plugin). See bind-text.

clay.modeLifecycle#

clay.mode, clay.isEditMode and clay.canEdit are read-only getters over the live mode facts, so they follow a committed mode change. Assigning to one of them throws in strict code and is dropped in sloppy code.

register(participant) adds a participant and returns a function that unregisters it. A participant is {id, order, prepare(context)}: id is a required, unique string; order (default 0) decides prepare order; and prepare returns a lease, or nothing to sit this transition out. prepare may fetch and build inert UI. The lease is {ready, enable, quiesce, resume, dispose}: an optional ready promise resolves once the participant can be enabled, enable is synchronous once every participant has prepared, quiesce stops new writes without losing buffers, resume brings the same lease back after a refused exit, and dispose runs only after a committed exit. context is {generation, destination, signal, represented, reader, initial, isCurrent()}: represented is the saved file the view session represents, with its etag and bytes, reader is that view session, and initial is true for the session this tab booted into. Check isCurrent() after each await and give up when it is false, because a stale preparation is thrown away. An id that starts with clay: belongs to ClayJS’s own modules, and registering one throws a TypeError.

Registering throws TypeError for a missing id or prepare, for an id already registered, and whenever the page is not idle in view: a participant registers in view mode, before the mode it joins. Registering never loads the controller. A script that has to register before ClayJS boots pushes the participants onto window.clay.modeParticipants (creating that array), and the queue is drained when an explicit edit starts.

canWrite() is whether a write is admitted right now: no transition is running and this tab is in edit mode (draft mode included). state is frozen and holds {mode, phase, destination, generation, reason}: phase is "idle" between transitions, "entering" or "leaving" during one, and "blocked" when entering edit failed; destination is where edits land, "draft" in draft mode, "demo" when the demo plugin saves to localStorage, and "host" otherwise; generation counts committed transitions; and reason is the code of the last refusal, or null. clay:modechange fires on document after a committed change. A declared document, <html clay-mode-switch="live">, switches live, so clay.setMode commits with no reload there; an undeclared document saves, writes the receipt and reloads. See switching modes.

clay.host.versions#

A promise for whether this host keeps a version history a person can go back to. It reads document.versions from the /_/meta discovery answer (see host compatibility) and resolves true only when that field is true; a host that says nothing, has no discovery, fails to answer or times out all answer false, so it never rejects. The answer is asked for on use and memoized with the rest of discovery, so a page that never calls it costs no request.

clay.effect(fn)#

In edit mode it warns once per effect: a write to saved content outside no-dirty or editor-ui, clay.undo.commit inside fn, an effect created inside fn, or more than 50 runs in a second.

clay.assets.load(name)#

Each name is a module in the same release as clay.js, so whichever host serves ClayJS serves them too, on demand and offline included. A document that asks for nothing downloads nothing extra.

NameResolves to
overtypeThe vendored OverType editor as default (with default.setTheme), plus its toolbarButtons.
marked{ Marked }, the Markdown parser class: new Marked().parse(markdown).
highlight{ default: hljs }, highlight.js core with no grammar registered (hljs.getLanguage("javascript") is undefined).
highlight/bash, /css, /javascript, /json, /python, /xml{ default: language }, one grammar to hand to hljs.registerLanguage(name, language).
uimotionThe engine the free apps’ intros animate with: scene(stage, options), mount(stage, build, options), rewind(scene, keep) and ease, the curves.

One load per name: a second call before the first settles gets the same promise, and a failed load is forgotten so the next call tries again. An unknown name rejects with clay.assets: no asset named "<name>", which includes names such as constructor and __proto__. clay.assets.names() returns the list in that order.

clay.theme(options)#

options is { auto, colorScheme, tokens, parts }, the same shape as window.clayTheme set before the loader. clay.theme(false) keeps the exact Bevel look, clay.theme(null) restores the default (the page’s font and solid colours over Bevel), clay.theme() returns the current configuration. Invalid options throw a TypeError and keep the previous theme. Applies to the next surface drawn. See docs/injected-ui.md, “Page themes”.

clay.save()#

msgType is success, error, skipped (nothing was sent), conflict (HTTP 412, see clay:save-conflict; the result also carries changedBy, afterTimeout and conflictEtag), or unknown (the request timed out, so the write may or may not have landed). forbidden means the host has already answered that this page may not be written, so nothing was sent: the result carries code: "forbidden", status: 403 and sent: false, the same answer a host’s own 403 gets. A host may answer with its own severity, such as warning, and that rides through untouched. skipped covers both “No changes to save” and “Save already in progress” (the bytes are queued and sent after the in-flight save), so branch on msgType, not ok.

clay.save.flush({keepalive, timeoutMs})#

Save now, and answer only when the host has accepted the bytes the page holds at that moment. Resolves {state, etag}, where state is view (this page cannot save), clean (the file already holds these bytes, so nothing was sent) or saved (this call wrote them, and etag is the stamp the host accepted). Rejects with an Error whose state is failed, conflict or blocked: blocked means the bytes are on the host but the page holds work a save cannot write, reported by a check registered through clay.registerUnsavedState, so only a person can resolve it. A save already on the wire is waited out; an edit made while a request is in flight forces another save. A refusal is reported, never resolved by overwriting: keeping this tab’s version stays a person’s decision (clay.save.overwrite()). In the first seconds after load it waits for the page to settle, so load-time rendering is not written as an edit. keepalive asks the transport to see the request through a page unload and is honoured under a 60 KB UTF-8 body only; timeoutMs (default 15000) bounds the whole call.

clay.save.limits({fresh}) and clay.save.inspect(html)#

clay.save.limits() resolves {maxBytes} from the document.maxBytes field in the host’s /_/meta answer. A limit counts only when it is a positive safe integer. A missing, zero, negative, fractional or non-numeric value means the limit is unknown, and so does every answer in draft mode, where ClayJS asks no host at all: both resolve {maxBytes: null} without a request. fresh: true asks the host again rather than reusing the answer discovery already gave. Neither call sends a save.

clay.save.inspect(html) resolves {bytes, maxBytes, state} for a string that is not this page: the exact UTF-8 bytes, the limit, and state one of unknown, ok, near or over. near starts at Math.ceil(maxBytes * 0.8). An import preview uses it on candidate bytes. It captures nothing, sends nothing, moves no baseline and fires no event.

clay.getHTML({transform, flushUndo})#

Without options it is the bytes a save would send: your onbeforesnapshot and onbeforesave hooks run, document transforms run, and the open undo batch closes first.

transform(root) receives the detached clone before the hooks and edits only that clone. Its return value is ignored, and it must be synchronous: a promise throws TypeError: getHTML: the transform must be synchronous. flushUndo: false leaves the open undo batch open instead of closing it, so a comparison does not end a step. Nothing here touches the live page, the change-detection baselines, a save receipt or the network.

The save-too-large refusal#

Every save lane measures the exact UTF-8 bytes it is about to send, after hooks and cleanup, and refuses before anything goes on the wire when they are over a known limit. The result is {ok: false, code: "save-too-large", sent: false, size}, with size holding {bytes, maxBytes, state: "over"}. Nothing is written: no accepted listener runs, no baseline moves and no recovery copy is cleared. A host that answers 413 is reported with the same code, so a save refused for size looks the same whether this tab measured it or the host did. See Size limits.

clay.visitorDrafts#

restored() answers {restored, hadDraft, parked}. The events are clay:drafts-restored, clay:drafts-saved and clay:drafts-store-failed.

clay.storage#

clay.storage.local and clay.storage.session each expose { get(key), set(key, value), remove(key) }, storing JSON (values come back as they went in). Keys are clay:doc:<location.pathname>:<key>, so two documents on one subdomain never see each other’s state. Present in every mode. session survives a reload and is copied into a duplicated tab. Storage that throws or is missing (a browser that blocks it, a sandboxed frame) falls back to an in-memory map for the life of the tab, and set returns false when it did — keep the value somewhere that outlives the tab if that return matters. Use it for UI memory, never for the document’s content.

clay.recovery#

A copy of writing the host has not accepted, kept in this browser, so a reload has something to offer. It is not a save: a completed write means this browser kept a copy, and ClayJS never renders a page from it. Absent in view mode, where a reader opens no database. A document is covered only for the channels its adapters register; there is no whole-body observer serializing the page after every edit.

JavaScript
const entries = clay.recovery.register({
  channel: "journal.entries",
  version: 1,
  readSaved(html) {
    const doc = new DOMParser().parseFromString(html, "text/html");
    return new Map([...doc.querySelectorAll("#entries > article.entry")]
      .map((el) => [el.dataset.id, el.querySelector(".entry-body")?.textContent ?? ""]));
  },
  describe(record) {
    return { label: record.key, text: record.payload };
  }
});

const { id, revision } = entries.stage({ key: entryId, baseEtag, base: savedText, payload: textarea.value });
const receipt = await entries.flush();
CallResolves
clay.recovery.register(spec)a channel, synchronously; registering one channel twice throws
stage({ key, kind, baseEtag, base, payload, lineage }){ id, revision }, synchronously, not a durable receipt
flush(){ ok: true, stored: [{ id, revision }] } after the transaction completes, or { ok: false, code }
list(){ ok, records, status }
dismiss(id, { revision }){ ok: true, id, revision }, or code: "stale" when a newer revision landed since
subscribe(fn)an unsubscribe. Detail is { channel, status, count, revisions }, never payloads
dispose()a best-effort flush; listeners released, records kept
clay.recovery.status(){ ok, code, durable, usage, identityMismatch }
clay.recovery.subscribe(fn)an unsubscribe, for the same detail on every channel registered here

code is unavailable, blocked, quota, over-budget, unknown-schema, aborted, uncloneable, stale, missing, invalid or error. durable is false until a transaction completes, and a page must never present memory as a durable copy. A save clears a revision only when its own capture’s bytes cover it: a skipped save, a refusal, a conflict, an error and an unknown outcome clear nothing. Recovery covers the store’s scope, its 32 MiB per document and 64 MiB per database limits, privacy, and the difference between journaled, acknowledged and checkpointed.

clay.trash(el, {at})#

A record is in the trash while it carries data-deleted-at (an ISO timestamp, at or now), so a delete is an attribute change: a peer’s edit to the same record made at the same time merges with it, and Undo restores the attribute instead of an old copy. clay.trash.purge(el) removes the record for good. The call returns {undo: () => clay.trash.restore(el)}. Events: clay:trashed, clay:restored, both bubbling from the record. Present in every mode; a write in view mode saves nothing. Leave trashed records out with a rules selector, article.entry:not([data-deleted-at]), or keep them and show a deletedAt field; a <noscript> rule hides them from readers without JavaScript. The undo toast is yours: clay.toastPersistent(message, type, {actions}) takes the button where clay-ui is loaded.

clay.upload(file, {onProgress, signal, requiredAccess})#

Post a File you supply (from an <input type="file">, a drop or a paste) to the host. Resolves {ok, msg, msgType, code, uploads} with uploads[0].url on success and never rejects. It opens no picker and inserts nothing: write the URL into the page yourself. code is unsupported when the host stores no files; other failures include too-large, unsupported-type, payment-required, unauthorized, forbidden, timeout, aborted, network. requiredAccess is "document", "local" or "document-or-local": the access the host must promise before the bytes are sent and report on each returned upload afterwards, or the result is privacy-unsupported. A name outside those three throws. Events: clay:upload-start, clay:upload-progress, clay:upload-done, clay:upload-error (upload plugin). See upload and quickcrop for what each access value means.

clay.upload.start(file, {requiredAccess, onProgress})#

The same upload with an identity of its own, so one editor row can follow it. Returns a task at once and starts the first attempt before returning; it throws for no file or an unknown requiredAccess, and nothing else about it rejects.

task.id is stable for the life of the task, task.attempt increases only on an explicit retry, task.state is uploading, succeeded, failed or cancelled, and task.file is the held file. task.snapshot() returns {id, attempt, state, loaded, total, percent, result}; task.subscribe(fn) calls fn with a snapshot now and on every change, and returns the unsubscribe function. task.result is the promise of the current attempt, with the same shape and codes as clay.upload. task.cancel() ends the attempt and deletes nothing the host may already hold. task.retry() starts a new attempt of the same file from failed or cancelled and returns its promise; from uploading or succeeded it returns the attempt already running. task.dispose() cancels the attempt and releases the file. A percent of 100 means the bytes were sent: the attempt is still uploading until the host answers.

clay.upload.mount(task, container) draws the shared row for that task (name, progress, Cancel, Retry where a retry could answer differently, Dismiss) into an element or a selector, and resolves {unmount}. The row and its stylesheet load on the first call, and everything it draws is clay="editor-ui", so none of it is saved. It throws a TypeError for a task without subscribe or a container that is not an element.

clay.me#

The person editing: {id, name, initials, color} or null (people plugin). The host names you through /_/meta: hyperclay.com from your account, HTML Clay and Hyperclay Local from their Profile setting when you turn it on (Local uses your Hyperclay account while signed in). Otherwise it is the name this browser gave the first time you authored something. color is an index from 0 to 7; the eight colors in order are #6b4fa8, #2f6a9e, #9a6a1c, #a8463d, #2f7a69, #4f6178, #3f7d3a, #a2457a, and the presence stack paints index n with the nth, so an app that uses them shows a person in the same color as the stack. Attribution, never a permission check.

clay.people#

get(id) (always a record, “Unknown person” for an id nobody named), list() (the people this document names), await available() (the host’s team for a picker, refreshed, or null), add(person) (record a person in the document’s <div clay-people hidden> registry and return the record), canRename() and rename(name) (change the name this browser chose, keeping its id; only when the host names nobody, since a host’s name is changed in the host) (people plugin).

clay.presence#

The presence facade is not on clay when the page boots. It is installed when the presence store first loads, and at that moment clay:presence-ready fires once on document, with the facade as detail.presence. Wire it whichever way it arrives:

JavaScript
if (window.clay?.presence) wire(window.clay.presence);
else document.addEventListener("clay:presence-ready", (e) => wire(e.detail.presence), { once: true });

The snapshot, the targets and their bounds are in Presence.

View mode#

In view mode the edit-only members are absent. A tab that booted in view has none of them. A tab that left edit on a live-switch document keeps the members that were attached during edit, because nothing detaches them from window.clay, but their sessions are gone: clay keeps undo, sortable, save, upload, page, unsent, bindText, recovery, getHTML, addDocumentTransform, onSnapshot and cacheBust, and a call answers a refusal, such as sortable’s not-editable. In view mode window.clay keeps ready, start, plugins, mode, isEditMode, canEdit, isOwner, isDraftMode, siteVisibility, setMode, toggleEditMode, modeLifecycle, Mutation, region, readData, writeData, assets, storage, ephemeral, host, trash, derived, effect, style, morph, and hasUnsavedChanges (always false, because a page that cannot save has nothing unsaved), plus the members of any plugin that loads in view, such as cms, people or menu. clay.writeData() still refuses without an editable page, a connected sync plugin, and host support. Feature-detect edit mode with clay.isEditMode: on a template copy whose tab can edit, the upgrade plugin loads in view mode too and clay.save holds only replace, so 'save' in clay is true there while clay.save() is absent.

Three tiers#

Three tiers, and only the first two are a promise:

TierWhat it isPromise
clay.* from clay.jsThe everyday surface, aboveStable
clay.* from a satelliteOpt-in, one script tag each: clay-ui, clay-utils, clay-dom, clay-events, clay-options, clay-router, clay-internals, clay-data, sap.jsStable
Anything else under src/Reachable by direct import, because src/ ships to npm and the CDNMay change in any release

The contract starts at 1.0.0: no name in the first two tiers changes without a major version. Everything in the third tier works today and is welcome to be used, but it is not a promise.

Derived values#

Store a value once, as the record, and declare every other place it shows as a sapjs paint. ClayJS loads the sapjs core for any page with a [sap] root and treats what a paint writes as derived.

HTML
<main sap>
  <tbody items="steps">
    <tr item class="step" data-id="s1" attr:data-state="item.state">
      <td><span class="state" bind="state" attr:aria-label="'Status: ' + item.state">accepted</span></td>
    </tr>
  </tbody>
</main>
<script type="application/json" data-rules-name="api" data-rules-version="1">
{"steps": [".step", {"id": "@data-id", "state": ".state"}]}
</script>
  • bind="state" makes the span’s text the record. attr:NAME, class:TOKEN, css:NAME, text, text:fmt and show (plus show-when:, hide-when:, option:, option-not:) paint from it.
  • Painted values are saved with the file but are never an edit: comparisons, the dirty check, autosave, undo and live-sync merges leave out the painted attribute, the one class token, the --NAME property, a text element’s children and hidden under show. The engine repaints right after every merge and at boot, before any baseline. Two tabs that change different records and repaint the same total never conflict.
  • Ownership is read from the element’s attributes, never by running an expression. attr: never owns id, data-id, class, style, value, checked, selected, or a field the same element declares in state=.
  • When a repaint leaves the file’s painted values stale (an agent wrote the record and not the paint), one clean tab with autosave on saves the painted page.
  • Agents and api rules read and write records, never painted output. A painted value on disk can lag the record until a tab repaints and saves it.
  • Never copy a record into a second attribute with a script (a MutationObserver that mirrors text into data-state): the copy goes stale in the file and a merge brings it back. Use a paint.
  • The core covers records and paints only. calc:, each, detail, effect, invalid, the actions (set:, move:, sort:, trigger-*, confirm) and Sap(el) halt with E50 naming full sap.js; add <script src="https://clayjs.com/v1/sap.js"></script> and the markup stays the same.