Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
27 changes: 26 additions & 1 deletion .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@
something matches; six-hour in-memory cache for the free plan's 1,000 requests a day. Every
result credits One Page Love and the authors with the entry's link (their terms). Tests:
`inspiration.test.ts`.
- Where frame CSS goes (`FRAME_STYLES` in `server/guide.ts`): agents are asked to style an element
in its own `style` attribute, which is what the editor reads and writes, and to keep a `<style>`
block for what an attribute cannot say (keyframes, font faces, `:root` custom properties, states,
pseudo-elements, media and container queries, a component's variant rules, the reset). A property
a state, variant or query changes sits in the stylesheet with its resting value too, since an
inline value outranks every rule. Guidance
only: nothing rejects or rewrites a stylesheet, and a frame already styled by classes keeps them.
The MCP guide, `create_frame`'s description and the resident agent's system prompt carry the same
text. Tests: `frameStyleGuidance.test.ts`.
- Agent feedback (`server/agentFeedback.ts`, `shared/agentFeedback.ts`): agents talk to the Doop
team through two MCP tools, which the resident agent has under the same names. `report_issue`
(kind `issue`: `bug`, `tool_error`, `confusing`, `missing_capability`, `other`) is for where Doop
Expand Down Expand Up @@ -552,7 +561,9 @@ data-doop-webfonts>` for the roster families the frame names and does not load i
its axes with the far corner held still (`keepAnchorTurned`) and do not snap while turned. MCP `update_frame`
takes `rotation` through `server/pageTools.ts` (normalisation and page validation), and
`get_canvas` lists it when set; copy, paste and duplicate
(`frameClipboard.ts`) carry it. Not yet turned: marquee selection,
(`frameClipboard.ts`) carry it. A drawing dragged in, out of or between turned frames lands
through `turnedDropRect` (its centre carried through each frame's turn), and a turn whose frame,
page or canvas goes mid-drag ends unsaved. Not yet turned: marquee selection,
snapping and exports read the unrotated box. Tests: `frameRotation.test.ts`,
`frameRotationHttp.test.ts`, `frameRotateBrowser.test.ts`.
- Element rotation (`src/lib/elementRotate.ts`): an element inside a frame wears the same rotate
Expand Down Expand Up @@ -691,6 +702,20 @@ data-doop-webfonts>` for the roster families the frame names and does not load i
re-anchors the root and its replies together and broadcasts each; a drop on the same anchor
sends nothing, Esc mid-drag puts the pin back. Tests: `commentMove.test.ts`,
`canvasCommentsRoute.test.ts`, `elementIds.test.ts`, the drag case in `drawingGeometryBrowser.test.ts`.
- Components (`.context/specs/components.md`): a main is an element marked `data-doop-component`; an
instance is full markup marked `data-doop-instance`, so frame consumers need no changes. Every
frame write passes `prepareFrameHtml` (`server/components.ts`): `<doop-use>` expands, a changed main
becomes a revision, instances reconcile against the revision they were rendered from
(`server/componentEngine.ts`) and upgrade. `actions.propagateComponents` carries a change across the
canvas. The components pass runs first on every write, then `withLibraryFaces`, so an expanded
`<doop-use>` naming a library family gets its face. Agents read and write the short form
(`get_frame`, `edit_frame_html`); tools live once in `server/componentTools.ts` for MCP and the
resident agent. `src/lib/components.ts` and `ComponentsPanel.tsx` (the Layers panel's Components
tab, beside Tokens) / `ComponentSection.tsx` are the editor's side. A component is renamed from its card's menu
or a double-click on its name in that tab, or from its main's Layers row (`renameComponent`; instances are
linked by id, so they follow); an instance's row is not renamed on its own. Stored in `components`
(migration `0052_components`). Tests: `components.test.ts`, `componentsEdgeCases.test.ts`,
`componentTools.test.ts`, `componentsRoutes.test.ts`, `componentsBrowser.test.ts`.
- Prototypes (`.context/specs/prototyping.md`): interactions are `data-doop-on` /
`data-doop-action` (or the JSON `data-doop-interactions`) attributes in frame HTML, parsed by
`shared/prototype.ts`, whose parser the frame runtime inlines by source. `PrototypePlayer.tsx`
Expand Down
3 changes: 3 additions & 0 deletions .context/specs/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ lists every file in this folder.
- [image-descriptions.md](image-descriptions.md) - Model-written descriptions of uploaded images,
stored once per asset, billed to the uploader, eligible owner or server behind an
Agents setting, and surfaced to MCP and resident agents as `images` per frame.
- [components.md](components.md) - Reusable components: mains, materialized instances, `<doop-use>`,
props, enum variants, slots, overrides and three-way merge, propagation and sign-off, libraries,
the MCP and resident tools, and the editor UI.
- [design-tokens.md](design-tokens.md) - Design tokens and themes: Paper's eleven token types as
CSS custom properties per canvas, the managed `<style data-doop-tokens>` block every frame
carries, propagation as annotation writes, modes via `data-doop-mode`, REST + MCP + the
Expand Down
94 changes: 94 additions & 0 deletions .context/specs/components.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Components

One design used in many places. People make them from any element; agents make, use and change them
through tools, and read them back in a short form.

## Problems and decisions

| Problem | Decision |
| --------------------------------------------------- | ----------------------------------------------------------------------------------- |
| Agents redraw components | Catalog in `get_canvas` and the resident prompt; a note when a write has lookalikes |
| Component payloads are expensive to read | `get_frame` returns `<doop-use>`; the full form is opt-in |
| Override ID paths are intricate | Attributes are props; part-keyed overrides are there when needed |
| Agents read pre-override values | Instances read back with their real props and overridden parts |
| Errors found only in a screenshot | Unknown names and values come back in the write's result, with what is valid |
| Edits break the link, or get thrown away | Any edit becomes the narrowest override that holds it; no detach needed |
| Sweeping edits have unknown blast radius | `update_component` reports impact, with `dry_run` |
| Variant explosion | An enum prop is `data-<name>` on the root, and variants are CSS |
| Canvases that grew without components | `find_component_candidates` + `replace_matching` retrofit them |
| Components disconnected from code | Optional `code` mapping; compact form reads like JSX |
| Libraries silently change consumers, or are one-way | Linked copies; updates shown, pulled on request |

## Model

Instances are **materialized**: the frame's HTML holds the full markup. Everything that reads frame HTML
(iframes, thumbnails, PDF and image export, comments, Layers) works unchanged, and a deleted
component loses nothing visually.

- **Main**: an element with `data-doop-component="<id>"`. Editing it with any tool edits the component.
A copy of a main elsewhere becomes an instance. If it disappears the component lives on with no main;
a marker coming back (undo, restore) reclaims the role, and an update writes a new main.
- **Definition** (`components` table, mirrored on `canvas.components`, keyed per canvas so a copied
canvas's markers stay valid): `template`, scoped `css`, `rawCss`, `head`, `props`, `slots`, `rev`,
`mainFrameId`, `code`, `source`, and the last 20 revisions inline.
- **Instance**: root attributes `data-doop-instance`, `data-doop-rev`, `data-doop-id`, and when needed
`data-doop-props` / `data-doop-overrides` as JSON. Every element keeps its `data-doop-part` key.
Slot content and nested instances are read from the DOM, not repeated in the marker.
A nested instance's id is derived from its owner's id and part key, so it stays the same across
renders and through the short form without being stored. Detaching leaves `data-doop-detached-from`
on the root and a frozen copy of the component's CSS scoped to it, one per revision per frame.
- **Template markup**: `data-doop-prop` binds text, attributes, styles and custom properties;
`data-doop-if` makes elements conditional; `data-doop-slot` / `data-doop-slot-suggest` declare slots.
Enum props exist only in the definition and set `data-<name>` on the root. Nested components are
`<doop-use>` by id, so a rename cannot break them.
- **CSS**: the server has no CSSOM, so rules are matched on what their selectors name, over-keeping
occasionally. Rules are scoped with `:where([data-doop-instance="<id>"])`, which adds no specificity.
Inherited declarations and used custom properties from `html` / `body` / `:root` land on the instance
root. Stylesheet links and the Tailwind CDN script are carried as `head`.

## The write pipeline

`prepareFrameHtml` runs synchronously inside every `actions.ts` write:

1. Expand `<doop-use>` at string level (a parser would foster-parent one out of a `<table>`).
2. Fold a changed main into its definition: a new revision, reported as `changed`.
3. Reconcile each outermost instance: render its own `rev` with its marker's state, diff against the
incoming markup, record differences as overrides, render at the current revision. Unchanged input
stays byte-identical. This three-way step is what stops a stale client's save being taken for edits.
4. Put exactly the needed stylesheets in the head.

Edits map to the narrowest thing that holds them: a bound element to its prop; attributes and individual
style properties to a part override; a deleted element to `hidden`; moved or added children to an `html`
override on that one element, which stays linked above and beside. Setting something back to the
template's value removes the override.

`propagateComponents` then rewrites each referencing frame as an ordinary write: history is filed, sign-off
on an approved frame moves to `needs_review`, the room sees `frame:updated` and a `component` message, and
one activity line names the frames. A frame mid-stream catches up when its stream ends, including one whose agent went silent.

## Agent surface

`server/componentTools.ts` holds each tool's schema and handler once, for MCP and the resident agent:
`list_components`, `get_component`, `create_component`, `update_component`, `insert_instance`,
`update_instances`, `find_component_candidates`, `delete_component`, `restore_component_version`,
`import_component`, `sync_component`. Previews are `get_component_preview` (MCP) and
`screenshot_component` (resident). `get_canvas` carries the catalog; `get_frame` and `edit_frame_html` speak
the compact form. Instructions are `COMPONENTS` in `server/guide.ts`.

## Editor

Layers / Components switch in the left rail (`ComponentsPanel.tsx`): search, previews, click to place, repeated
design scan, library import. `ComponentSection.tsx` heads the Design tab: props, go to main, reset, detach on an
instance; description and make-a-prop / make-a-slot on a main. Right-click and ⌘⌥K create one.

## Limits

- Variants are styled in CSS, through agents or the HTML tab. There is no visual per-variant editing yet.
- Placing is by click; no drag from the panel onto the canvas.
- Selection outlines do not yet distinguish mains and instances; the Layers glyph and Design tab do.
- The Components page frame for a main made from markup uses a default size until resized.
- Figma import does not map Figma components to these.
- A restored revision older than the 20 kept cannot be used for merging: its instance keeps its marker
state and upgrades.
- `@scope` is not used, so a host frame's own rules for the same class still apply to an instance.
- Resident agents cannot import libraries: their run is scoped to one canvas.
3 changes: 2 additions & 1 deletion .context/specs/workspaces-billing.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ A new workspace starts `inactive`; the client opens the plan picker immediately
`checkout.session.completed` and `customer.subscription.{created,updated,deleted}`, finds the
workspace by `metadata.workspaceId`, applies the same `subscriptionPatch`.
4. Seat changes: `addMember`/`removeMember` call `billing.syncSeats` in the background (updates
the subscription item quantity; Stripe prorates). Never blocks the invite.
the subscription item quantity; an added seat is invoiced at once with `always_invoice`, a
removed one is a credit on the next invoice). Never blocks the invite.
5. Portal: `POST …/billing/portal` opens Stripe's hosted portal for cards, invoices, cancel,
interval switches.

Expand Down
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions ios/BlitzKit/include/doopblitz.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ void doopblitz_buffer_free(uint8_t *ptr, size_t len);

/// Node ids are opaque non-zero values; 0 means none.
uint64_t doopblitz_doc_element_from_point(DoopBlitzDoc *doc, float x, float y);
/// The element a tap there selects: its drawing, else the nearest element with a box.
uint64_t doopblitz_doc_pick_from_point(DoopBlitzDoc *doc, float x, float y);
uint64_t doopblitz_doc_query_selector(const DoopBlitzDoc *doc, const char *selector);
uint64_t doopblitz_node_parent(const DoopBlitzDoc *doc, uint64_t node);
/// out receives x, y, width, height in CSS pixels.
Expand Down
67 changes: 67 additions & 0 deletions ios/BlitzKit/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,37 @@ fn base_font_context() -> FontContext {
collection: Collection::new(CollectionOptions { shared: false, system_fonts: true }),
};
ctx.collection.register_fonts(Blob::new(Arc::new(blitz_dom::BULLET_FONT) as _), None);
add_symbol_fallbacks(&mut ctx.collection);
Mutex::new(ctx)
})
.lock()
.unwrap()
.clone()
}

/// System families that carry the symbols pages use as text (★ ✓ → ● ⌘ ✦), first match wins.
/// System Font and Apple Symbols come first, as WebKit's cascade picks them; a family the
/// device lacks is skipped.
const SYMBOL_FAMILIES: &[&str] =
&["System Font", "Apple Symbols", "Hiragino Sans", "Menlo", "Zapf Dingbats", "STIX Two Math"];

/// Fontique finds a fallback per script from one sample letter, and symbols belong to no
/// script of their own: a ★ in a Latin run only gets the Latin fallback (Helvetica), and a
/// run of symbols and digits gets none. On macOS Helvetica happens to carry ★; on iOS it
/// does not, so the glyph came from LastResort. Append the symbol families after the
/// system's own fallback for Latin and for the common, inherited and unknown scripts.
fn add_symbol_fallbacks(collection: &mut parley::fontique::Collection) {
use parley::fontique::{FallbackKey, Script};
let symbols: Vec<_> = SYMBOL_FAMILIES.iter().filter_map(|name| collection.family_id(name)).collect();
for script in [*b"Latn", *b"Zyyy", *b"Zinh", *b"Zzzz"] {
let key = FallbackKey::new(Script::from_bytes(script), None);
// Asking first records the system's own choice, which appending would otherwise replace.
let system: Vec<_> = collection.fallback_families(key).collect();
let extra = symbols.iter().copied().filter(|id| !system.contains(id));
collection.append_fallbacks(key, extra);
}
}

fn runtime() -> &'static tokio::runtime::Runtime {
RUNTIME.get_or_init(|| {
tokio::runtime::Builder::new_multi_thread()
Expand Down Expand Up @@ -444,6 +468,49 @@ pub extern "C" fn doopblitz_doc_element_from_point(doc: *mut Doc, x: f32, y: f32
raw(doc.base().element_from_point(x, y))
}

/// The element a tap at a CSS point selects, or 0, as the web runtime's
/// `probe` picks it: the drawing (`[data-doop-drawing]`) the hit is part of,
/// so a text layer is selected whole rather than the run of bold inside it.
/// Outside a drawing, a hit without a box of its own (inline formatting, whose
/// glyphs live in the parent's inline layout) resolves to the nearest ancestor
/// that has one, or the selection would be an outline of zero size.
#[unsafe(no_mangle)]
pub extern "C" fn doopblitz_doc_pick_from_point(doc: *mut Doc, x: f32, y: f32) -> u64 {
let doc = unsafe { &mut *doc };
let _guard = runtime().enter();
doc.base_mut().resolve(0.0);
let base = doc.base();
let Some(hit) = base.element_from_point(x, y) else { return 0 };
if let Some(drawing) = self_or_ancestor(base, hit, |id| is_drawing(base, id)) {
return raw(Some(drawing));
}
raw(self_or_ancestor(base, hit, |id| has_box(base, id)).or(Some(hit)))
}

fn self_or_ancestor(base: &BaseDocument, id: NodeId, matches: impl Fn(NodeId) -> bool) -> Option<NodeId> {
let mut current = Some(id);
while let Some(node) = current {
if is_real_element(base, node) && matches(node) {
return Some(node);
}
current = element_parent(base, node);
}
None
}

fn is_drawing(base: &BaseDocument, id: NodeId) -> bool {
base.get_node(id)
.and_then(|n| n.element_data())
.is_some_and(|e| e.attrs().iter().any(|a| &*a.name.local == "data-doop-drawing"))
}

fn has_box(base: &BaseDocument, id: NodeId) -> bool {
base.get_node(id).is_some_and(|n| {
let size = n.final_layout().size;
size.width > 0.0 && size.height > 0.0
})
}

/// First element matching a CSS selector, or 0.
#[unsafe(no_mangle)]
pub extern "C" fn doopblitz_doc_query_selector(doc: *const Doc, selector: *const c_char) -> u64 {
Expand Down
32 changes: 32 additions & 0 deletions ios/BlitzKit/rust/tests/abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,3 +542,35 @@ fn rect_composes_nested_transforms_before_bounding() {
doopblitz_doc_free(doc);
}
}

/// A tap selects the drawing it lands in, the way the web runtime's `probe`
/// does: the whole text layer, not a bold run inside it, which as an inline
/// box has no layout of its own and came back as a zero-size outline.
#[test]
fn pick_selects_the_text_layer_not_its_inline_runs() {
let html = CString::new(concat!(
"<body style=\"margin:0\">",
"<p data-doop-drawing=\"text\" id=\"t\" style=\"position:fixed;left:100px;top:100px;width:200px;height:120px;margin:0;font:24px/1.4 sans-serif\"><b>bold</b> run</p>",
"<div id=\"plain\" style=\"position:fixed;left:100px;top:300px;width:200px;height:60px;font:24px/1.4 sans-serif\"><b>bold</b></div>",
"</body>",
))
.unwrap();
let base = CString::new("https://doop.design/").unwrap();
unsafe {
let doc = doopblitz_doc_new(html.as_ptr(), base.as_ptr(), 400, 400, 1.0);
let (mut w, mut h, mut len) = (0u32, 0u32, 0usize);
doopblitz_buffer_free(doopblitz_doc_render(doc, &mut w, &mut h, &mut len), len);
let layer = doopblitz_doc_query_selector(doc, CString::new("#t").unwrap().as_ptr());
let plain = doopblitz_doc_query_selector(doc, CString::new("#plain").unwrap().as_ptr());
// On the bold glyphs, and in the layer's empty lower half.
assert_eq!(doopblitz_doc_pick_from_point(doc, 120.0, 115.0), layer);
assert_eq!(doopblitz_doc_pick_from_point(doc, 250.0, 200.0), layer);
// Outside a drawing, bold text resolves to the nearest box.
assert_ne!(doopblitz_doc_element_from_point(doc, 120.0, 315.0), plain);
assert_eq!(doopblitz_doc_pick_from_point(doc, 120.0, 315.0), plain);
let mut rect = [0f32; 4];
assert!(doopblitz_node_rect(doc, layer, rect.as_mut_ptr()));
assert!(rect[2] > 199.0 && rect[3] > 119.0, "{rect:?}");
doopblitz_doc_free(doc);
}
}
Loading
Loading