From 5c99b4770f1363523393ea5ee16c19eac5e042ca Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:50:27 -0500 Subject: [PATCH 001/279] feat(format): add stoichiometry data to reaction steps and grid tables (0.5.0) A reaction step stores only the amounts the person types (equivalents, mass, volume, density, concentration, purity, molecular weight override, scale, isolated mass); moles, limiting reagent and yields are computed. A table with stoich becomes the grid for one step. The engine model keeps reactions as open dicts, so only FORMAT.md and the window model change. --- docs/FORMAT.md | 11 ++++++++++- frontend/src/engine/model.ts | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 006549fb..50920687 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -296,7 +296,7 @@ A text object (same fields) attached to a structure: `target` (a fragment or gro ### table (built from 0.5.0) -`x`, `y`, `cols` (column widths), `rows` (`[ { "id": "l...", "h": 18, "cells": [ { "runs": [...] }, { "object": "f..." } ] } ]`; a cell holds runs or names a fragment object that it owns), `padding` (default 3), `header` (true styles the first row), `borders` (`"all"`, `"outer"`, `"none"`), `auto_grow`. +`x`, `y`, `cols` (column widths), `rows` (`[ { "id": "l...", "h": 18, "cells": [ { "runs": [...] }, { "object": "f..." } ] } ]`; a cell holds runs or names a fragment object that it owns), `padding` (default 3), `header` (true styles the first row), `borders` (`"all"`, `"outer"`, `"none"`), `auto_grow`. Optional `stoich` (`{ "reaction": "r...", "step": "r..." }`, built from 0.5.0) makes the table a stoichiometry grid for that reaction step: its rows are written from the step's `stoich` data and the derived masses whenever either changes, and editing a cell edits the step's data, not the runs. ### image (built from 0.5.0) @@ -325,6 +325,15 @@ Built from 0.5.0. `page.reactions` lists reactions; each is `{ "id": "r...", "st `arrow` is the arrow object the step is bound to. Roles are object ids on the same page. With `explicit` false the roles were inferred from geometry (left of the tail: reactants; right of the head: products; in the arrow's band above or below: agents, and text there: conditions) and are recomputed when objects move; with `explicit` true the person or an agent set them and they are kept. Plus signs carry no role. Products of one step may be reactants of the next. +A step may carry `stoich` (built from 0.5.0), the person's amounts for a stoichiometry grid: + +```json +{ "scale_mmol": 5.0, "limiting": "f1...", "product": "f2...", "isolated_mg": 812.4, + "components": { "f1...": { "equiv": 1, "mass_mg": 690.6 }, "f3...": { "equiv": 1.2, "volume_ml": 0.57, "density_g_ml": 1.08 } } } +``` + +Keys of `components` are reactant, agent or product object ids of the step. Each component may give `equiv`, `mass_mg`, `volume_ml`, `density_g_ml`, `conc_m` (mol per litre, for solutions), `purity_pct` (default 100), `mw` (overrides the derived molecular weight, for example for a salt or hydrate) and `label`. Only what the person typed is stored; moles, the amounts implied by `equiv` and `scale_mmol`, the limiting reagent when `limiting` is absent (the reactant with the fewest moles divided by its coefficient), the theoretical yield of `product` and the percent yield from `isolated_mg` are computed from these values and the derived molecular weights, and are never stored. + ## The derived cache What the engine computes from a fragment is engine output, never user data. It is not part of document.json and is never written into a `.fchem` package; it is rebuilt after load and broadcast after every transaction, keyed by fragment id and the document revision it was computed at. diff --git a/frontend/src/engine/model.ts b/frontend/src/engine/model.ts index c57c9d37..5e4409ff 100644 --- a/frontend/src/engine/model.ts +++ b/frontend/src/engine/model.ts @@ -61,6 +61,24 @@ export interface ReactionStep { conditions?: Id[]; explicit?: boolean; coefficients?: Record; + stoich?: Stoich; +} +export interface StoichComponent { + equiv?: number; + mass_mg?: number; + volume_ml?: number; + density_g_ml?: number; + conc_m?: number; + purity_pct?: number; + mw?: number; + label?: string; +} +export interface Stoich { + scale_mmol?: number; + limiting?: Id; + product?: Id; + components: Record; + isolated_mg?: number; } export type Radical = 'none' | 'doublet' | 'singlet' | 'triplet'; @@ -257,6 +275,7 @@ export interface TableObject extends ObjectBase { header?: boolean; borders?: 'all' | 'outer' | 'none'; auto_grow?: boolean; + stoich?: { reaction: Id; step: Id }; } export interface ImageObject extends ObjectBase { From 8a4ca18d980250372d67f7ff589ca9f814d69a2f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:57:40 -0500 Subject: [PATCH 002/279] feat(chem): add page geometry for reaction perception (0.5.0) Reaction roles come from where objects sit relative to an arrow, so the engine needs bounds for every object kind and a frame along each arrow's shaft to measure before, after and beside it. --- backend/app/services/chem/geometry.py | 186 ++++++++++++++++++++++++++ 1 file changed, 186 insertions(+) create mode 100644 backend/app/services/chem/geometry.py diff --git a/backend/app/services/chem/geometry.py b/backend/app/services/chem/geometry.py new file mode 100644 index 00000000..69a53cdb --- /dev/null +++ b/backend/app/services/chem/geometry.py @@ -0,0 +1,186 @@ +import math + +Box = tuple[float, float, float, float] + +TEXT_ADVANCE = 0.55 +LINE_HEIGHT = 1.2 +LABEL_PAD = 0.4 +DEFAULT_FONT = 10.0 + + +def _num(v: object) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) + + +def union(boxes: list[Box]) -> Box | None: + found = [b for b in boxes if b is not None] + if not found: + return None + return (min(b[0] for b in found), min(b[1] for b in found), max(b[2] for b in found), max(b[3] for b in found)) + + +def centre(box: Box) -> tuple[float, float]: + return ((box[0] + box[2]) / 2, (box[1] + box[3]) / 2) + + +def _rect(obj: dict) -> Box | None: + x, y, w, h = obj.get("x"), obj.get("y"), obj.get("w"), obj.get("h") + if not all(_num(v) for v in (x, y, w, h)): + return None + rot = obj.get("rot") + if not _num(rot) or not rot: + return (x, y, x + w, y + h) + cx, cy = x + w / 2, y + h / 2 + t = math.radians(rot) + c, s = math.cos(t), math.sin(t) + pts = [(cx + dx * c + dy * s, cy - dx * s + dy * c) for dx in (-w / 2, w / 2) for dy in (-h / 2, h / 2)] + return (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts)) + + +def fragment_box(frag: dict, style: dict) -> Box | None: + atoms = [a for a in (frag.get("atoms") or {}).values() if isinstance(a, dict) and _num(a.get("x")) and _num(a.get("y"))] + if not atoms: + return None + size = float((style.get("label_font") or {}).get("size") or DEFAULT_FONT) + boxes = [] + for a in atoms: + if a.get("element") != "C" or a.get("label") or a.get("show_carbon") == "always" or len(atoms) == 1: + shown = str(a.get("label") or a.get("element") or "") + half = max(1, len(shown)) * size * TEXT_ADVANCE / 2 + LABEL_PAD + boxes.append((a["x"] - half, a["y"] - size * 0.6, a["x"] + half, a["y"] + size * 0.6)) + else: + boxes.append((a["x"], a["y"], a["x"], a["y"])) + return union(boxes) + + +def _run_size(run: dict, style: dict) -> float: + if _num(run.get("size")): + return float(run["size"]) + return float((style.get("caption_font") or {}).get("size") or DEFAULT_FONT) + + +def text_box(obj: dict, style: dict) -> Box | None: + x, y = obj.get("x"), obj.get("y") + if not _num(x) or not _num(y): + return None + lines: list[float] = [0.0] + heights: list[float] = [0.0] + for run in obj.get("runs") or []: + if not isinstance(run, dict): + continue + size = _run_size(run, style) * (0.75 if run.get("sub") or run.get("sup") else 1.0) + parts = str(run.get("t") or "").split("\n") + for n, part in enumerate(parts): + if n: + lines.append(0.0) + heights.append(0.0) + lines[-1] += len(part) * size * TEXT_ADVANCE + heights[-1] = max(heights[-1], size) + base = float((style.get("caption_font") or {}).get("size") or DEFAULT_FONT) + width = float(obj["w"]) if _num(obj.get("w")) and obj["w"] > 0 else max(lines) + height = sum((h or base) * LINE_HEIGHT for h in heights) + align = obj.get("align") or "l" + left = x + if not _num(obj.get("w")): + left = x - width / 2 if align == "c" else x - width if align == "r" else x + return _rect({"x": left, "y": y, "w": width, "h": height, "rot": obj.get("rot")}) + + +def arrow_points(obj: dict) -> tuple[tuple[float, float], tuple[float, float]] | None: + vals = [obj.get(k) for k in ("x1", "y1", "x2", "y2")] + if not all(_num(v) for v in vals): + return None + return (float(vals[0]), float(vals[1])), (float(vals[2]), float(vals[3])) + + +def arrow_box(obj: dict) -> Box | None: + ends = arrow_points(obj) + if ends is None: + return None + (x1, y1), (x2, y2) = ends + pts = [(x1, y1), (x2, y2)] + bend = obj.get("bend") + if _num(bend) and bend: + mx, my = (x1 + x2) / 2, (y1 + y2) / 2 + dx, dy = x2 - x1, y2 - y1 + sag = math.tan(math.radians(bend) / 4) * math.hypot(dx, dy) / 2 + length = math.hypot(dx, dy) or 1.0 + pts.append((mx + dy / length * sag, my - dx / length * sag)) + return (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts)) + + +def plus_box(obj: dict, style: dict) -> Box | None: + x, y = obj.get("x"), obj.get("y") + if not _num(x) or not _num(y): + return None + size = float(obj["size"]) if _num(obj.get("size")) else 0.6 * float(style.get("bond_length") or 14.4) + return (x - size / 2, y - size / 2, x + size / 2, y + size / 2) + + +def table_box(obj: dict) -> Box | None: + x, y = obj.get("x"), obj.get("y") + if not _num(x) or not _num(y): + return None + w = sum(float(c) for c in obj.get("cols") or [] if _num(c)) + h = sum(float(r.get("h") or 0) for r in obj.get("rows") or [] if isinstance(r, dict) and _num(r.get("h") or 0)) + return (x, y, x + w, y + h) + + +def object_box(doc: dict, oid: str, style: dict, depth: int = 0) -> Box | None: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict) or depth > 32: + return None + kind = obj.get("kind") + if kind == "fragment": + return fragment_box(obj, style) + if kind in ("text", "caption"): + return text_box(obj, style) + if kind == "arrow": + return arrow_box(obj) + if kind == "plus": + return plus_box(obj, style) + if kind == "group": + return union([object_box(doc, c, style, depth + 1) for c in obj.get("children") or [] if isinstance(c, str)]) + if kind == "table": + return table_box(obj) + if kind == "line": + pts = [p for p in obj.get("points") or [] if isinstance(p, list) and len(p) == 2 and all(_num(v) for v in p)] + return (min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts)) if pts else None + if kind == "orbital": + x, y, size = obj.get("x"), obj.get("y"), obj.get("size") + if all(_num(v) for v in (x, y, size)): + return (x - size, y - size, x + size, y + size) + return None + return _rect(obj) + + +def has_fragment(doc: dict, oid: str, depth: int = 0) -> bool: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict) or depth > 32: + return False + if obj.get("kind") == "fragment": + return bool(obj.get("atoms")) + if obj.get("kind") == "group": + return any(has_fragment(doc, c, depth + 1) for c in obj.get("children") or [] if isinstance(c, str)) + return False + + +class Frame: + def __init__(self, tail: tuple[float, float], head: tuple[float, float]): + self.tail = tail + dx, dy = head[0] - tail[0], head[1] - tail[1] + self.length = math.hypot(dx, dy) + k = self.length or 1.0 + self.ux, self.uy = dx / k, dy / k + + def along(self, p: tuple[float, float]) -> float: + return (p[0] - self.tail[0]) * self.ux + (p[1] - self.tail[1]) * self.uy + + def across(self, p: tuple[float, float]) -> float: + return (p[0] - self.tail[0]) * self.uy - (p[1] - self.tail[1]) * self.ux + + def project(self, box: Box) -> tuple[float, float, float, float]: + corners = [(box[0], box[1]), (box[2], box[1]), (box[0], box[3]), (box[2], box[3])] + s = [self.along(c) for c in corners] + t = [self.across(c) for c in corners] + return min(s), max(s), min(t), max(t) From 983f43b340f5434ae93c1143b095f33fb0d46f56 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:58:32 -0500 Subject: [PATCH 003/279] feat(chem): infer the roles of one reaction step from an arrow (0.5.0) Structures before the tail are reactants and after the head products, joined across plus signs or when they touch; structures in the arrow's band are agents and text there is conditions. Retrosynthetic arrows swap the sides and decorative arrow kinds are not steps. --- backend/app/services/chem/reactions.py | 168 +++++++++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 backend/app/services/chem/reactions.py diff --git a/backend/app/services/chem/reactions.py b/backend/app/services/chem/reactions.py new file mode 100644 index 00000000..bc191086 --- /dev/null +++ b/backend/app/services/chem/reactions.py @@ -0,0 +1,168 @@ +import copy + +from app.services import model +from app.services.chem import geometry + +REACTION_ARROWS = ("forward", "equilibrium", "equilibrium_unbalanced", "reversible", "retro", "nogo_cross", "nogo_slash", "dashed") +ROLE_KEYS = ("reactants", "products", "agents", "conditions") +BAND_BONDS = 1.5 +ROW_BONDS = 2.5 +JOIN_BONDS = 1.0 +END_BONDS = 0.5 + + +class ReactionError(ValueError): + status = 422 + + +class NotFound(ReactionError): + status = 404 + + +def bond_length(doc: dict) -> float: + return float(model.resolve_style(doc).get("bond_length") or 14.4) + + +def page_of(doc: dict, page_id: str | None = None) -> dict: + pages = [p for p in doc.get("pages") or [] if isinstance(p, dict)] + if not pages: + raise NotFound("The drawing has no pages.") + if page_id is None: + return pages[0] + for p in pages: + if p.get("id") == page_id: + return p + raise NotFound(f"The drawing has no page {page_id}.") + + +def used_ids(doc: dict) -> set[str]: + out: set[str] = set() + stack: list = [doc] + while stack: + node = stack.pop() + if isinstance(node, dict): + if isinstance(node.get("id"), str): + out.add(node["id"]) + stack.extend(node.values()) + elif isinstance(node, list): + stack.extend(node) + return out + + +def fresh_id(used: set[str], prefix: str) -> str: + while True: + found = model.new_id(prefix) + if found not in used: + used.add(found) + return found + + +def is_reaction_arrow(obj: object) -> bool: + return isinstance(obj, dict) and obj.get("kind") == "arrow" and (obj.get("type") or "forward") in REACTION_ARROWS and geometry.arrow_points(obj) is not None + + +def direction(obj: dict) -> tuple[tuple[float, float], tuple[float, float]]: + tail, head = geometry.arrow_points(obj) + if obj.get("head") == "none" and obj.get("tail") not in (None, "none"): + return head, tail + return tail, head + + +def _role_kind(doc: dict, oid: str) -> str | None: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict): + return None + kind = obj.get("kind") + if kind == "fragment" and obj.get("atoms"): + return "structure" + if kind == "group" and geometry.has_fragment(doc, oid): + return "structure" + if kind == "text": + return "formula" if obj.get("formula") else "text" + return None + + +class _Item: + def __init__(self, oid: str, role: str | None, plus: bool, span: tuple[float, float, float, float]): + self.oid = oid + self.role = role + self.plus = plus + self.s0, self.s1, self.t0, self.t1 = span + + @property + def s(self) -> float: + return (self.s0 + self.s1) / 2 + + def gap(self) -> float: + return 0.0 if self.t0 <= 0 <= self.t1 else min(abs(self.t0), abs(self.t1)) + + +def _items(doc: dict, page: dict, arrow_id: str, frame: geometry.Frame, style: dict) -> list[_Item]: + out = [] + for oid in page.get("order") or []: + if oid == arrow_id or not isinstance(oid, str): + continue + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict) or obj.get("hidden"): + continue + box = geometry.object_box(doc, oid, style) + if box is None: + continue + out.append(_Item(oid, _role_kind(doc, oid), obj.get("kind") == "plus", frame.project(box))) + return out + + +def _walk(items: list[_Item], forward: bool, bl: float) -> list[str]: + pluses = [i for i in items if i.plus] + chosen: list[_Item] = [] + candidates = sorted((i for i in items if i.role in ("structure", "formula")), key=lambda i: i.s0 if forward else -i.s1) + for item in candidates: + if not chosen: + chosen.append(item) + continue + last = chosen[-1] + lo, hi = (last.s1, item.s0) if forward else (item.s1, last.s0) + joined = hi - lo <= JOIN_BONDS * bl or any(lo - END_BONDS * bl <= p.s <= hi + END_BONDS * bl for p in pluses) + if not joined: + break + chosen.append(item) + if not forward: + chosen.reverse() + return [i.oid for i in chosen] + + +def infer_step(doc: dict, page: dict, arrow_id: str, used: set[str] | None = None) -> dict | None: + arrow = (doc.get("objects") or {}).get(arrow_id) + if not is_reaction_arrow(arrow): + return None + style = model.resolve_style(doc) + bl = bond_length(doc) + tail, head = direction(arrow) + frame = geometry.Frame(tail, head) + if frame.length <= 0: + return None + items = _items(doc, page, arrow_id, frame, style) + agents, conditions = [], [] + for i in items: + if i.role is None or not 0 <= i.s <= frame.length or i.gap() > BAND_BONDS * bl: + continue + (conditions if i.role == "text" else agents).append(i) + taken = {i.oid for i in agents + conditions} + row = [i for i in items if i.oid not in taken and i.t1 >= -ROW_BONDS * bl and i.t0 <= ROW_BONDS * bl] + tol = END_BONDS * bl + before = _walk([i for i in row if i.s1 <= tol or i.plus], False, bl) + after = _walk([i for i in row if i.s0 >= frame.length - tol or i.plus], True, bl) + if not before and not after: + return None + if arrow.get("type") == "retro": + before, after = after, before + order = lambda i: (i.t0, i.s0) + return { + "id": fresh_id(used if used is not None else used_ids(doc), "r"), + "arrow": arrow_id, + "reactants": before, + "products": after, + "agents": [i.oid for i in sorted(agents, key=order)], + "conditions": [i.oid for i in sorted(conditions, key=order)], + "explicit": False, + } From fa90f83f2fef0142cc8cabe2aa20e5629eaad049 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:59:22 -0500 Subject: [PATCH 004/279] feat(chem): perceive whole reaction schemes as page ops (0.5.0) Steps that share a product and a reactant chain into one reaction in scheme order, explicit steps are kept as they are, and a re-run keeps step and reaction ids, coefficients and stoichiometry, so perception is one undoable set on page.reactions or nothing when the scheme is unchanged. --- backend/app/services/chem/reactions.py | 188 +++++++++++++++++++++++++ 1 file changed, 188 insertions(+) diff --git a/backend/app/services/chem/reactions.py b/backend/app/services/chem/reactions.py index bc191086..4f21a197 100644 --- a/backend/app/services/chem/reactions.py +++ b/backend/app/services/chem/reactions.py @@ -166,3 +166,191 @@ def infer_step(doc: dict, page: dict, arrow_id: str, used: set[str] | None = Non "conditions": [i.oid for i in sorted(conditions, key=order)], "explicit": False, } + + +def role_ids(step: dict) -> set[str]: + return {i for key in ("reactants", "products", "agents") for i in step.get(key) or [] if isinstance(i, str)} + + +def _keep_extras(step: dict, old: dict) -> dict: + roles = role_ids(step) + out = dict(step, id=old["id"]) + for key, value in old.items(): + if key in ("id", "arrow", "explicit") or key in ROLE_KEYS: + continue + if key == "coefficients" and isinstance(value, dict): + kept = {k: v for k, v in value.items() if k in roles} + if kept: + out[key] = kept + elif key == "stoich" and isinstance(value, dict): + st = copy.deepcopy(value) + comps = st.get("components") if isinstance(st.get("components"), dict) else {} + st["components"] = {k: v for k, v in comps.items() if k in roles} + for ref in ("limiting", "product"): + if ref in st and st[ref] not in roles: + st.pop(ref) + out[key] = st + else: + out[key] = copy.deepcopy(value) + return out + + +def _arrow_key(doc: dict, step: dict) -> tuple[float, float]: + arrow = (doc.get("objects") or {}).get(step.get("arrow")) + ends = geometry.arrow_points(arrow) if isinstance(arrow, dict) else None + if ends is None: + return (float("inf"), float("inf")) + (x1, y1), (x2, y2) = ends + return (round(min(y1, y2), 1), min(x1, x2)) + + +def _chains(doc: dict, steps: list[dict]) -> list[list[dict]]: + n = len(steps) + parent = list(range(n)) + + def find(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + feeds = [[j for j in range(n) if j != i and set(steps[i].get("products") or []) & set(steps[j].get("reactants") or [])] for i in range(n)] + for i in range(n): + for j in feeds[i]: + parent[find(i)] = find(j) + depth = [0] * n + for _ in range(n): + moved = False + for i in range(n): + for j in feeds[i]: + if depth[j] < depth[i] + 1 and depth[i] < n: + depth[j] = depth[i] + 1 + moved = True + if not moved: + break + groups: dict[int, list[int]] = {} + for i in range(n): + groups.setdefault(find(i), []).append(i) + ordered = [sorted(g, key=lambda i: (depth[i], _arrow_key(doc, steps[i]))) for g in groups.values()] + ordered.sort(key=lambda g: _arrow_key(doc, steps[g[0]])) + return [[steps[i] for i in g] for g in ordered] + + +def perceive_page(doc: dict, page: dict, used: set[str] | None = None) -> tuple[list[dict], dict]: + used = used if used is not None else used_ids(doc) + objects = doc.get("objects") or {} + old = [r for r in page.get("reactions") or [] if isinstance(r, dict) and isinstance(r.get("id"), str)] + owner: dict[str, dict] = {} + previous: dict[str, dict] = {} + explicit: list[dict] = [] + for r in old: + for s in r.get("steps") or []: + if not isinstance(s, dict) or not isinstance(s.get("id"), str): + continue + owner[s["id"]] = r + if s.get("explicit"): + explicit.append(copy.deepcopy(s)) + elif isinstance(s.get("arrow"), str): + previous.setdefault(s["arrow"], s) + covered = {s.get("arrow") for s in explicit} + steps = list(explicit) + for oid in page.get("order") or []: + if oid in covered: + continue + step = infer_step(doc, page, oid, used) + if step is not None: + steps.append(_keep_extras(step, previous[oid]) if oid in previous else step) + found: list[dict] = [] + claimed: set[str] = set() + for group in _chains(doc, steps): + rec = None + for s in group: + r = owner.get(s["id"]) + if r is not None and r["id"] not in claimed: + rec = {k: copy.deepcopy(v) for k, v in r.items() if k != "steps"} + break + if rec is None: + rec = {"id": fresh_id(used, "r")} + claimed.add(rec["id"]) + rec["steps"] = group + found.append(rec) + summary = { + "page": page.get("id"), + "reactions": len(found), + "steps": sum(len(r["steps"]) for r in found), + "explicit": len(explicit), + "stale": [s["id"] for s in explicit if s.get("arrow") not in objects], + "changed": found != (page.get("reactions") or []), + } + return found, summary + + +def _pages(doc: dict, page_ids: list[str] | None) -> list[dict]: + if page_ids: + return [page_of(doc, p) for p in page_ids] + return [p for p in doc.get("pages") or [] if isinstance(p, dict)] + + +def preview(doc: dict, page_ids: list[str] | None = None) -> list[dict]: + used = used_ids(doc) + out = [] + for page in _pages(doc, page_ids): + found, summary = perceive_page(doc, page, used) + out.append({**summary, "list": found}) + return out + + +def perceive_ops(doc: dict, page_ids: list[str] | None = None) -> tuple[list[dict], list[dict]]: + used = used_ids(doc) + ops: list[dict] = [] + summaries: list[dict] = [] + for page in _pages(doc, page_ids): + found, summary = perceive_page(doc, page, used) + summaries.append(summary) + if not summary["changed"]: + continue + op: dict = {"op": "set", "path": ["pages", {"id": page["id"]}, "reactions"]} + if found: + op["value"] = found + elif "reactions" not in page: + continue + ops.append(op) + return ops, summaries + + +def step_path(page_id: str, reaction_id: str, step_id: str) -> list: + return ["pages", {"id": page_id}, "reactions", {"id": reaction_id}, "steps", {"id": step_id}] + + +def find_step(doc: dict, reaction_id: str | None = None, step_id: str | None = None, page_id: str | None = None) -> tuple[dict, dict, dict]: + pages = [page_of(doc, page_id)] if page_id else [p for p in doc.get("pages") or [] if isinstance(p, dict)] + any_steps = False + for page in pages: + for r in page.get("reactions") or []: + if not isinstance(r, dict): + continue + for s in r.get("steps") or []: + if not isinstance(s, dict): + continue + any_steps = True + if (reaction_id is None or r.get("id") == reaction_id) and (step_id is None or s.get("id") == step_id): + return page, r, s + if not any_steps: + raise NotFound("The drawing has no reaction steps yet: draw an arrow between structures and perceive reactions first.") + if step_id is not None: + raise NotFound(f"No reaction step {step_id}" + (f" in reaction {reaction_id}." if reaction_id else ".")) + raise NotFound(f"No reaction {reaction_id}.") + + +def roles_of(step: dict) -> list[tuple[str, str]]: + out = [] + for key, role in (("reactants", "reactant"), ("agents", "agent"), ("products", "product")): + for oid in step.get(key) or []: + if isinstance(oid, str): + out.append((oid, role)) + return out + + +def coefficient(step: dict, oid: str) -> float: + found = (step.get("coefficients") or {}).get(oid) + return float(found) if isinstance(found, (int, float)) and not isinstance(found, bool) and found > 0 else 1.0 From bf60f8f4e893702e4748983b31b2dcc29db08950 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:59:59 -0500 Subject: [PATCH 005/279] feat(chem): export a reaction step as reaction SMILES and RXN (0.5.0) A step's reactants, agents and products go through the same molfile writer as single structures, so wedges, map numbers and abbreviations match; RXN V2000 and V3000 carry the title and the conditions text in the header and V3000 also carries the reacting-centre marks. --- backend/app/services/chem/rxnio.py | 85 ++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 backend/app/services/chem/rxnio.py diff --git a/backend/app/services/chem/rxnio.py b/backend/app/services/chem/rxnio.py new file mode 100644 index 00000000..f945970b --- /dev/null +++ b/backend/app/services/chem/rxnio.py @@ -0,0 +1,85 @@ +from rdkit import Chem +from rdkit.Chem import rdChemReactions + +from app.services.chem import convert, io, warning +from app.services.chem.reactions import ReactionError, coefficient, roles_of + +FORMATS = ("smiles", "rxn", "rxnv3000") +REACT_STATUS = {"broken": 4, "formed": 4, "order": 8, "unchanged": 2, "centre": 1, "stereo": 1} +LINE = 80 + + +def fragments_in(doc: dict, oid: str, depth: int = 0) -> list[dict]: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict) or depth > 32: + return [] + if obj.get("kind") == "fragment": + return [obj] if obj.get("atoms") else [] + if obj.get("kind") == "group": + return [f for c in obj.get("children") or [] if isinstance(c, str) for f in fragments_in(doc, c, depth + 1)] + return [] + + +def plain_text(obj: dict | None) -> str: + if not isinstance(obj, dict): + return "" + return " ".join("".join(str(r.get("t") or "") for r in obj.get("runs") or [] if isinstance(r, dict)).split()) + + +def molecule(doc: dict, frag: dict) -> tuple[Chem.Mol, list[dict]]: + mol, notes = io._writable(frag, doc.get("expansions")) + bonds = frag.get("bonds") or {} + for b in mol.GetBonds(): + if not b.HasProp(convert.ID_PROP): + continue + status = REACT_STATUS.get((bonds.get(b.GetProp(convert.ID_PROP)) or {}).get("reacting")) + if status: + b.SetIntProp("molReactStatus", status) + b.ClearProp(convert.ID_PROP) + return mol.GetMol(), notes + + +def build(doc: dict, step: dict) -> tuple[rdChemReactions.ChemicalReaction, list[dict]]: + rxn = rdChemReactions.ChemicalReaction() + notes: list[dict] = [] + add = {"reactant": rxn.AddReactantTemplate, "product": rxn.AddProductTemplate, "agent": rxn.AddAgentTemplate} + for oid, role in roles_of(step): + frags = fragments_in(doc, oid) + if not frags: + obj = (doc.get("objects") or {}).get(oid) + what = f"the text {plain_text(obj)!r}" if isinstance(obj, dict) and obj.get("kind") == "text" else oid + notes.append(warning("not_a_structure", f"The {role} {what} is not a structure and is left out.")) + continue + n = coefficient(step, oid) + if n != 1: + notes.append(warning("coefficient_dropped", f"The coefficient {n:g} of {oid} has no place in the format and is not written.")) + for frag in frags: + mol, more = molecule(doc, frag) + notes.extend(more) + add[role](mol) + if not rxn.GetNumReactantTemplates() and not rxn.GetNumProductTemplates(): + raise ReactionError("This step has no reactant or product structures to write.") + return rxn, notes + + +def _header(block: str, title: str, comment: str) -> str: + lines = block.split("\n") + if len(lines) > 3: + lines[1] = title[:LINE] + lines[3] = comment[:LINE] + return "\n".join(lines) + + +def export_step(doc: dict, step: dict, fmt: str, title: str | None = None) -> tuple[str, list[dict]]: + if fmt not in FORMATS: + raise ReactionError(f"format must be one of {', '.join(FORMATS)}") + rxn, notes = build(doc, step) + conditions = "; ".join(t for t in (plain_text((doc.get("objects") or {}).get(c)) for c in step.get("conditions") or []) if t) + if fmt == "smiles": + if conditions: + notes.append(warning("conditions_dropped", "Reaction SMILES has no place for the conditions text.")) + return rdChemReactions.ReactionToSmiles(rxn), notes + block = rdChemReactions.ReactionToRxnBlock(rxn, separateAgents=True, forceV3000=fmt == "rxnv3000") + if conditions: + notes.append(warning("conditions_comment", "The conditions text is written on the comment line, which most readers ignore.")) + return _header(block, title or "", conditions), notes From 50e1a89cd020a21b4241e4b509fbff43435f5126 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:12 -0500 Subject: [PATCH 006/279] feat(chem): lay out imported reactions with an arrow and plus signs (0.5.0) RXN, reaction SMILES and reaction CML now arrive as a drawn scheme: reactants and products on one centre line joined by plus signs, agents above an arrow stretched to fit them, and an explicit step holding the roles the file declared, as ops for one undoable insert. --- backend/app/services/chem/scheme.py | 152 ++++++++++++++++++++++++++++ 1 file changed, 152 insertions(+) create mode 100644 backend/app/services/chem/scheme.py diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py new file mode 100644 index 00000000..6267a58e --- /dev/null +++ b/backend/app/services/chem/scheme.py @@ -0,0 +1,152 @@ +from app.services import model +from app.services.chem import DEFAULT_BOND_LENGTH, geometry, io +from app.services.chem.reactions import ReactionError, fresh_id, used_ids + +GAP_BONDS = 1.0 +END_BONDS = 0.5 +ARROW_BONDS = 4.0 +ROW_GAP_BONDS = 2.0 +PLUS_BONDS = 0.6 +CONDITION_PAD = 7.2 +ALIASES = {"smiles": "rsmiles", "rsmiles": "rsmiles", "rxn": "rxn", "rxnv3000": "rxn", "cml": "cml", "cdxml": "cdxml"} + + +def _claim(frag: dict, used: set[str]) -> dict: + if frag["id"] in used: + frag["id"] = fresh_id(used, "f") + else: + used.add(frag["id"]) + renamed: dict[str, str] = {} + atoms: dict = {} + for aid, atom in frag["atoms"].items(): + new = fresh_id(used, "a") if aid in used else aid + used.add(new) + renamed[aid] = new + atoms[new] = {**atom, "id": new} + bonds: dict = {} + for bid, bond in frag["bonds"].items(): + new = fresh_id(used, "b") if bid in used else bid + used.add(new) + bonds[new] = {**bond, "id": new, "a": renamed[bond["a"]], "b": renamed[bond["b"]]} + frag["atoms"], frag["bonds"] = atoms, bonds + return frag + + +def _move(frag: dict, dx: float, dy: float) -> None: + for a in frag["atoms"].values(): + a["x"] = round(a["x"] + dx, 3) + a["y"] = round(a["y"] + dy, 3) + + +class _Placer: + def __init__(self, bond_length: float): + self.bl = bond_length + self.style = {"bond_length": bond_length, "label_font": {"size": 10}} + + def box(self, frag: dict) -> geometry.Box: + return geometry.fragment_box(frag, self.style) or (0.0, 0.0, 0.0, 0.0) + + def put(self, frag: dict, left: float, cy: float) -> float: + b = self.box(frag) + _move(frag, left - b[0], cy - (b[1] + b[3]) / 2) + return left + b[2] - b[0] + + +def layout(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), + used: set[str] | None = None) -> dict: + used = used if used is not None else set() + roles = parsed.reaction or {} + frags = {f["id"]: f for f in parsed.fragments} + pick = lambda key: [frags[i] for i in roles.get(key) or [] if i in frags] + reactants, products, agents = pick("reactants"), pick("products"), pick("agents") + if not reactants and not products: + raise ReactionError("The text holds no reactants or products.") + placed = {id(f) for f in reactants + products + agents} + others = [f for f in parsed.fragments if id(f) not in placed] + p = _Placer(bond_length) + bl = bond_length + height = max((p.box(f)[3] - p.box(f)[1] for f in reactants + products), default=bl) + agent_h = max((p.box(f)[3] - p.box(f)[1] for f in agents), default=0.0) + x0, y0 = origin + cy = y0 + max(height / 2, agent_h + END_BONDS * bl if agents else 0.0) + plus_size = PLUS_BONDS * bl + objects: list[dict] = [] + x = x0 + + def side(items: list[dict], x: float) -> float: + for n, f in enumerate(items): + if n: + x += GAP_BONDS * bl + objects.append({"id": fresh_id(used, "o"), "kind": "plus", "x": round(x + plus_size / 2, 3), "y": round(cy, 3), "symbol": "plus"}) + x += plus_size + GAP_BONDS * bl + x = p.put(f, x, cy) + objects.append(f) + return x + + x = side(reactants, x) + tail = x + END_BONDS * bl if reactants else x + widths = [p.box(f)[2] - p.box(f)[0] for f in agents] + span = sum(widths) + GAP_BONDS * bl * max(0, len(agents) - 1) + length = max(ARROW_BONDS * bl, span + 2 * CONDITION_PAD) + ax = tail + (length - span) / 2 + for f, w in zip(agents, widths): + b = p.box(f) + _move(f, ax - b[0], cy - END_BONDS * bl - b[3]) + objects.append(f) + ax += w + GAP_BONDS * bl + head = tail + length + arrow = {"id": fresh_id(used, "o"), "kind": "arrow", "type": "forward", "x1": round(tail, 3), "y1": round(cy, 3), + "x2": round(head, 3), "y2": round(cy, 3), "head": "full", "tail": "none"} + objects.append(arrow) + side(products, head + END_BONDS * bl) + bottom = max((p.box(f)[3] for f in reactants + products), default=cy) + ROW_GAP_BONDS * bl + x = x0 + for f in others: + b = p.box(f) + _move(f, x - b[0], bottom - b[1]) + x += b[2] - b[0] + ROW_GAP_BONDS * bl + objects.append(f) + for f in parsed.fragments: + _claim(f, used) + step = {"id": fresh_id(used, "r"), "arrow": arrow["id"], "reactants": [f["id"] for f in reactants], "products": [f["id"] for f in products], + "agents": [f["id"] for f in agents], "conditions": [], "explicit": True} + return {"objects": objects, "reaction": {"id": fresh_id(used, "r"), "steps": [step]}, + "warnings": [w for w in parsed.warnings if w.get("code") != "reaction_arrow"]} + + +def parse(text: str, fmt: str | None = None, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), + used: set[str] | None = None) -> dict: + kind = ALIASES.get(fmt) if fmt else None + if fmt and kind is None: + raise ReactionError(f"format must be one of {', '.join(ALIASES)}") + try: + parsed = io.read_text(text, kind, bond_length, origin) + except ValueError as exc: + raise ReactionError(str(exc)) from exc + if parsed.reaction is None: + raise ReactionError(f"The text reads as {parsed.format}, not as a reaction.") + return {"format": parsed.format, **layout(parsed, bond_length, origin, used)} + + +def free_origin(doc: dict, page: dict) -> tuple[float, float]: + style = model.resolve_style(doc) + margin = float(page.get("margins", 36)) + box = geometry.union([geometry.object_box(doc, oid, style) for oid in page.get("order") or [] if isinstance(oid, str)]) + if box is None: + return (margin, margin) + return (margin, round(box[3] + ROW_GAP_BONDS * float(style.get("bond_length") or DEFAULT_BOND_LENGTH), 3)) + + +def insert_ops(doc: dict, page: dict, text: str, fmt: str | None = None, origin: tuple[float, float] | None = None) -> tuple[list[dict], dict]: + bl = float(model.resolve_style(doc).get("bond_length") or DEFAULT_BOND_LENGTH) + found = parse(text, fmt, bl, origin or free_origin(doc, page), used_ids(doc)) + ops: list[dict] = [] + order = ["pages", {"id": page["id"]}, "order"] + for obj in found["objects"]: + ops.append({"op": "set", "path": ["objects", obj["id"]], "value": obj}) + ops.append({"op": "ins", "path": order, "value": obj["id"]}) + if isinstance(page.get("reactions"), list): + ops.append({"op": "ins", "path": ["pages", {"id": page["id"]}, "reactions"], "value": found["reaction"]}) + else: + ops.append({"op": "set", "path": ["pages", {"id": page["id"]}, "reactions"], "value": [found["reaction"]]}) + return ops, found From b663fb2c3e51f18b2ec4953773dc03358e027717 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:12 -0500 Subject: [PATCH 007/279] feat(import): open reaction files as drawn schemes (0.5.0) File > Open of an RXN file (or a CML or CDXML reaction) used to scatter the structures in rows and drop the roles; it now draws the arrow, the plus signs and the step, and falls back to rows if the layout fails. --- backend/app/services/importers.py | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/backend/app/services/importers.py b/backend/app/services/importers.py index e4613ee4..8a1a49b3 100644 --- a/backend/app/services/importers.py +++ b/backend/app/services/importers.py @@ -170,6 +170,22 @@ def place(frags: list[dict], page: dict, bond_length: float) -> None: top += height + gap +def _reaction(doc: dict, page: dict, result: object, bond_length: float, ids: _Ids, warnings: list[str]) -> bool: + margin = float(page.get("margins", 36)) + try: + from app.services.chem import scheme + found = scheme.layout(result, bond_length, (margin, margin), ids.used) + except Exception as exc: + warnings.append(f"the reaction could not be laid out, so its structures are placed in rows ({exc})") + return False + for obj in found["objects"]: + doc["objects"][obj["id"]] = obj + page["order"].append(obj["id"]) + page["reactions"] = [found["reaction"]] + warnings[:] = [t for t in (_warning_text(w) for w in found["warnings"]) if t] + return True + + def import_file(path: str | Path) -> tuple[dict, list[str]]: p = Path(path).expanduser() if not can_import(p): @@ -189,13 +205,14 @@ def import_file(path: str | Path) -> tuple[dict, list[str]]: page = doc["pages"][0] ids = _Ids({doc["id"], page["id"]}) warnings: list[str] = [t for t in (_warning_text(w) for w in getattr(result, "warnings", None) or []) if t] - frags = [f for f in (normalise_fragment(raw, ids, warnings) for raw in parsed if isinstance(raw, dict)) if f is not None] - if not frags: - raise ImportFailed(f"{p.name} holds no structures FormChem can draw.") - place(frags, page, bond_length) - for f in frags: - doc["objects"][f["id"]] = f - page["order"].append(f["id"]) + if not (getattr(result, "reaction", None) and _reaction(doc, page, result, bond_length, ids, warnings)): + frags = [f for f in (normalise_fragment(raw, ids, warnings) for raw in parsed if isinstance(raw, dict)) if f is not None] + if not frags: + raise ImportFailed(f"{p.name} holds no structures FormChem can draw.") + place(frags, page, bond_length) + for f in frags: + doc["objects"][f["id"]] = f + page["order"].append(f["id"]) doc["meta"]["imported"] = {"name": p.name, "format": FORMATS[p.suffix.lower()]} errors = model.validate(doc) if errors: From 6a3f205257b2d0dbfa96c367ddd9b7128bc9527c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:02:37 -0500 Subject: [PATCH 008/279] feat(chem): map reaction atoms with Indigo and mark reaction centres (0.5.0) Indigo's automap depends on the order it reads molecules in and can leave a whole fragment unmapped, so discard mode tries several orders, keeps the mapping with the fewest unmapped atoms and bond edits, then swaps same-element product atoms while that lowers the score. Map numbers and broken, formed and order-changed bond marks come back as ops; clearing removes both. --- backend/app/services/chem/mapping.py | 239 +++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 backend/app/services/chem/mapping.py diff --git a/backend/app/services/chem/mapping.py b/backend/app/services/chem/mapping.py new file mode 100644 index 00000000..76be40d1 --- /dev/null +++ b/backend/app/services/chem/mapping.py @@ -0,0 +1,239 @@ +import itertools +import time + +from rdkit import Chem + +from app.services.chem import ids as idsmod, perceive, warning +from app.services.chem.reactions import ReactionError +from app.services.chem.rxnio import fragments_in + +MODES = ("discard", "keep", "alter", "clear") +MAX_ORDERS = 24 +BUDGET_SECONDS = 6.0 +TIMEOUT_MS = 3000 +POLISH_ATOMS = 80 +POLISH_ROUNDS = 6 + + +class _Mol: + def __init__(self, frag: dict, role: str, expansions: dict | None, keep: bool): + self.frag = frag + self.role = role + self.conv = perceive.prepare(frag, expansions) + mol = Chem.RWMol(self.conv.mol) + for a in mol.GetAtoms(): + for prop in idsmod.PRIVATE_PROPS: + if a.HasProp(prop): + a.ClearProp(prop) + if not keep: + a.SetAtomMapNum(0) + try: + self.block = Chem.MolToMolBlock(mol, kekulize=True) + except Exception: + self.block = Chem.MolToMolBlock(mol, kekulize=False) + + def hydrogens(self, idx: int) -> int: + return self.conv.mol.GetAtomWithIdx(idx).GetTotalNumHs() + + def bonds(self) -> list[tuple[int, int, float, str | None]]: + return [(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), b.GetBondTypeAsDouble(), self.conv.bond_id(b.GetIdx())) for b in self.conv.mol.GetBonds()] + + +def _indigo(): + from indigo import Indigo + ind = Indigo() + ind.setOption("ignore-stereochemistry-errors", True) + ind.setOption("aam-timeout", TIMEOUT_MS) + return ind + + +def _run(ind, reactants: list[_Mol], products: list[_Mol], mode: str) -> tuple[list[list[int]], list[list[int]]]: + rxn = ind.createReaction() + for m in reactants: + rxn.addReactant(ind.loadMolecule(m.block)) + for m in products: + rxn.addProduct(ind.loadMolecule(m.block)) + rxn.automap(mode) + left = [[rxn.atomMappingNumber(a) for a in mol.iterateAtoms()] for mol in rxn.iterateReactants()] + right = [[rxn.atomMappingNumber(a) for a in mol.iterateAtoms()] for mol in rxn.iterateProducts()] + return left, right + + +def _side_bonds(mols: list[_Mol], maps: list[list[int]]) -> dict[frozenset, float]: + out: dict[frozenset, float] = {} + for m, nums in zip(mols, maps): + for i, j, order, _ in m.bonds(): + if nums[i] and nums[j]: + out[frozenset((nums[i], nums[j]))] = order + return out + + +def _score(reactants: list[_Mol], products: list[_Mol], left: list[list[int]], right: list[list[int]]) -> tuple[int, int, int]: + unmapped = sum(1 for nums in left + right for n in nums if not n) + a, b = _side_bonds(reactants, left), _side_bonds(products, right) + edits = len(a.keys() ^ b.keys()) + sum(1 for k in a.keys() & b.keys() if a[k] != b[k]) + h_left = {n: m.hydrogens(i) for m, nums in zip(reactants, left) for i, n in enumerate(nums) if n} + h_right = {n: m.hydrogens(i) for m, nums in zip(products, right) for i, n in enumerate(nums) if n} + moved = sum(abs(h_left[n] - h_right[n]) for n in h_left.keys() & h_right.keys()) + return unmapped, edits, moved + + +def _orders(n_left: int, n_right: int, search: bool): + if not search: + return [(tuple(range(n_left)), tuple(range(n_right)))] + return list(itertools.islice(itertools.product(itertools.permutations(range(n_left)), itertools.permutations(range(n_right))), MAX_ORDERS)) + + +def _best(reactants: list[_Mol], products: list[_Mol], mode: str) -> tuple[list[list[int]], list[list[int]], int]: + ind = _indigo() + best = None + tried = 0 + started = time.monotonic() + for lo, ro in _orders(len(reactants), len(products), mode == "discard"): + if tried and time.monotonic() - started > BUDGET_SECONDS: + break + tried += 1 + left_p, right_p = _run(ind, [reactants[i] for i in lo], [products[i] for i in ro], mode) + left = [left_p[lo.index(i)] for i in range(len(reactants))] + right = [right_p[ro.index(i)] for i in range(len(products))] + score = _score(reactants, products, left, right) + if best is None or score < best[0]: + best = (score, left, right) + right = _polish(reactants, products, best[1], best[2], best[0]) if mode == "discard" else best[2] + return best[1], right, tried + + +def _polish(reactants: list[_Mol], products: list[_Mol], left: list[list[int]], right: list[list[int]], score: tuple) -> list[list[int]]: + slots = [(mi, ai) for mi, nums in enumerate(right) for ai in range(len(nums))] + if len(slots) > POLISH_ATOMS: + return right + right = [list(nums) for nums in right] + element = {(mi, ai): products[mi].conv.mol.GetAtomWithIdx(ai).GetAtomicNum() for mi, ai in slots} + for _ in range(POLISH_ROUNDS): + better = False + for (m1, a1), (m2, a2) in itertools.combinations(slots, 2): + if element[(m1, a1)] != element[(m2, a2)] or right[m1][a1] == right[m2][a2]: + continue + right[m1][a1], right[m2][a2] = right[m2][a2], right[m1][a1] + found = _score(reactants, products, left, right) + if found < score: + score, better = found, True + else: + right[m1][a1], right[m2][a2] = right[m2][a2], right[m1][a1] + if not better: + break + return right + + +def _compact(left: list[list[int]], right: list[list[int]]) -> tuple[list[list[int]], list[list[int]]]: + renumber: dict[int, int] = {} + for nums in left + right: + for n in nums: + if n and n not in renumber: + renumber[n] = len(renumber) + 1 + return [[renumber.get(n, 0) for n in nums] for nums in left], [[renumber.get(n, 0) for n in nums] for nums in right] + + +def _centres(reactants: list[_Mol], products: list[_Mol], left: list[list[int]], right: list[list[int]]) -> dict[tuple[str, str], str]: + a, b = _side_bonds(reactants, left), _side_bonds(products, right) + marks: dict[tuple[str, str], str] = {} + for mols, maps, mine, other, gone in ((reactants, left, a, b, "broken"), (products, right, b, a, "formed")): + for m, nums in zip(mols, maps): + for i, j, _order, bid in m.bonds(): + if bid is None or not (nums[i] and nums[j]): + continue + key = frozenset((nums[i], nums[j])) + if key not in other: + marks[(m.frag["id"], bid)] = gone + elif other[key] != mine[key]: + marks[(m.frag["id"], bid)] = "order" + return marks + + +def _molecules(doc: dict, step: dict, keep: bool) -> tuple[list[_Mol], list[_Mol]]: + expansions = doc.get("expansions") + seen: set[str] = set() + sides: dict[str, list[_Mol]] = {"reactants": [], "products": []} + for key in sides: + for oid in step.get(key) or []: + for frag in fragments_in(doc, oid): + if frag["id"] not in seen: + seen.add(frag["id"]) + sides[key].append(_Mol(frag, key, expansions, keep)) + return sides["reactants"], sides["products"] + + +def _set(path: list, old: object, new: object) -> dict | None: + if new == old: + return None + op: dict = {"op": "set", "path": path} + if new is not None: + op["value"] = new + return op + + +def map_ops(doc: dict, step: dict, mode: str = "discard", centres: bool = True) -> tuple[list[dict], dict]: + if mode not in MODES: + raise ReactionError(f"mode must be one of {', '.join(MODES)}") + if mode == "clear": + return clear_ops(doc, step, centres) + reactants, products = _molecules(doc, step, mode != "discard") + if not reactants or not products: + raise ReactionError("Mapping needs at least one reactant and one product structure.") + try: + left, right, tried = _best(reactants, products, mode) + except ImportError as exc: + raise ReactionError(f"Indigo is not available, so atoms cannot be mapped ({exc}).") from exc + except Exception as exc: + raise ReactionError(f"The mapper could not map this step: {exc}") from exc + left, right = _compact(left, right) + marks = _centres(reactants, products, left, right) if centres else {} + ops: list[dict] = [] + unmapped = 0 + mapped: set[int] = set() + for m, nums in zip(reactants + products, left + right): + fid, atoms = m.frag["id"], m.frag.get("atoms") or {} + for idx, n in enumerate(nums): + if not m.conv.drawn[idx]: + continue + aid = m.conv.owner[idx] + if n: + mapped.add(n) + else: + unmapped += 1 + op = _set(["objects", fid, "atoms", aid, "map"], atoms[aid].get("map"), n or None) + if op: + ops.append(op) + if centres: + for bid, bond in (m.frag.get("bonds") or {}).items(): + op = _set(["objects", fid, "bonds", bid, "reacting"], bond.get("reacting"), marks.get((fid, bid))) + if op: + ops.append(op) + counts = {k: sum(1 for v in marks.values() if v == k) for k in ("broken", "formed", "order")} + info = {"mode": mode, "mapped": len(mapped), "unmapped": unmapped, "orders_tried": tried, + "quality": "complete" if not unmapped else f"partial: {unmapped} unmapped atom{'s' if unmapped != 1 else ''}", + "centres": counts if centres else None, "warnings": []} + if any(not all(m.conv.drawn) for m in reactants + products): + info["warnings"].append(warning("abbreviations_unmapped", "Atoms inside abbreviations take part in the mapping but carry no map number on the drawing.")) + return ops, info + + +def clear_ops(doc: dict, step: dict, centres: bool = True) -> tuple[list[dict], dict]: + ops: list[dict] = [] + seen: set[str] = set() + cleared = 0 + for key in ("reactants", "agents", "products"): + for oid in step.get(key) or []: + for frag in fragments_in(doc, oid): + if frag["id"] in seen: + continue + seen.add(frag["id"]) + for aid, atom in (frag.get("atoms") or {}).items(): + if "map" in atom: + ops.append({"op": "set", "path": ["objects", frag["id"], "atoms", aid, "map"]}) + cleared += 1 + if centres: + for bid, bond in (frag.get("bonds") or {}).items(): + if "reacting" in bond: + ops.append({"op": "set", "path": ["objects", frag["id"], "bonds", bid, "reacting"]}) + return ops, {"mode": "clear", "cleared": cleared} From d460b29e37a0c6bb738157fbbf6cbfffd466fe08 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:03:52 -0500 Subject: [PATCH 009/279] feat(chem): check reaction balance and suggest coefficients (0.5.0) Element, charge and mass totals per side use the step's coefficients and the same RDKit counts as the formula. When the step does not balance, the smallest positive integer coefficients come from the element and charge conservation system, or, when co-products are missing, from adding up to two common small molecules. --- backend/app/services/chem/balance.py | 195 +++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 backend/app/services/chem/balance.py diff --git a/backend/app/services/chem/balance.py b/backend/app/services/chem/balance.py new file mode 100644 index 00000000..ee805892 --- /dev/null +++ b/backend/app/services/chem/balance.py @@ -0,0 +1,195 @@ +import itertools +import math +from fractions import Fraction + +from rdkit import Chem + +from app.services.chem import ids, mass, perceive, warning +from app.services.chem.reactions import coefficient +from app.services.chem.rxnio import fragments_in, plain_text + +PT = Chem.GetPeriodicTable() +MASS_TOLERANCE = 0.01 +MAX_COEFFICIENT = 50 +CO_PRODUCTS = ( + ("water", "O", {"H": 2, "O": 1}), + ("hydrogen chloride", "Cl", {"H": 1, "Cl": 1}), + ("hydrogen bromide", "Br", {"H": 1, "Br": 1}), + ("carbon dioxide", "O=C=O", {"C": 1, "O": 2}), + ("sulfur dioxide", "O=S=O", {"S": 1, "O": 2}), + ("nitrogen", "N#N", {"N": 2}), + ("hydrogen", "[H][H]", {"H": 2}), + ("sodium chloride", "[Na+].[Cl-]", {"Na": 1, "Cl": 1}), +) + + +def _hill_key(symbols: set[str]): + has_c = "C" in symbols + return lambda s: (0 if has_c and s == "C" else 1 if has_c and s == "H" else 2, s) + + +def species(doc: dict, oid: str) -> dict | None: + frags = fragments_in(doc, oid) + if not frags: + return None + counts: dict[str, int] = {} + charge = 0 + generic: list[str] = [] + mw = 0.0 + formulas = [] + for frag in frags: + conv = perceive.prepare(frag, doc.get("expansions")) + found, labels, q = ids.formula_counts(conv.mol) + for (z, _iso), n in found.items(): + sym = PT.GetElementSymbol(z) + counts[sym] = counts.get(sym, 0) + n + charge += q + generic.extend(labels) + mw += mass.average_mass(conv.mol) + formulas.append(ids.formula(conv.mol)) + return {"counts": counts, "charge": charge, "generic": generic, "mw": round(mw, 4), "formula": ".".join(f for f in formulas if f)} + + +def _nullspace(rows: list[list[Fraction]], n: int) -> list[list[Fraction]]: + m = [list(r) for r in rows] + pivots: list[int] = [] + r = 0 + for c in range(n): + p = next((i for i in range(r, len(m)) if m[i][c] != 0), None) + if p is None: + continue + m[r], m[p] = m[p], m[r] + lead = m[r][c] + m[r] = [v / lead for v in m[r]] + for i in range(len(m)): + if i != r and m[i][c] != 0: + k = m[i][c] + m[i] = [a - k * b for a, b in zip(m[i], m[r])] + pivots.append(c) + r += 1 + if r == len(m): + break + free = [c for c in range(n) if c not in pivots] + basis = [] + for f in free: + v = [Fraction(0)] * n + v[f] = Fraction(1) + for i, c in enumerate(pivots): + v[c] = -m[i][f] + basis.append(v) + return basis + + +def solve(left: list[dict], right: list[dict]) -> list[int] | None: + cols = left + right + if not cols: + return None + symbols = sorted({s for c in cols for s in c["counts"]}) + sign = [1] * len(left) + [-1] * len(right) + rows = [[Fraction(sign[j] * cols[j]["counts"].get(s, 0)) for j in range(len(cols))] for s in symbols] + rows.append([Fraction(sign[j] * cols[j]["charge"]) for j in range(len(cols))]) + basis = _nullspace(rows, len(cols)) + if len(basis) != 1: + return None + v = basis[0] + if all(x <= 0 for x in v): + v = [-x for x in v] + if any(x <= 0 for x in v): + return None + scale = math.lcm(*(x.denominator for x in v)) + ints = [int(x * scale) for x in v] + g = math.gcd(*ints) + ints = [i // g for i in ints] + return ints if max(ints) <= MAX_COEFFICIENT else None + + +def _co_products(left: list[dict], right: list[dict]) -> list[dict]: + extra = [{"counts": counts, "charge": 0, "name": name, "smiles": smiles} for name, smiles, counts in CO_PRODUCTS] + for size in (1, 2): + found = [] + for combo in itertools.combinations(extra, size): + ints = solve(left, right + list(combo)) + if ints is not None: + found.append({"add": [{"name": c["name"], "smiles": c["smiles"], "coefficient": ints[len(left) + len(right) + k]} for k, c in enumerate(combo)], + "coefficients": ints[: len(left) + len(right)]}) + if found: + found.sort(key=lambda o: sum(o["coefficients"]) + sum(a["coefficient"] for a in o["add"])) + return found[:3] + return [] + + +def _n(v: float) -> int | float: + return int(v) if float(v).is_integer() else round(v, 4) + + +def _side_text(diff: dict[str, int], more: bool) -> str: + parts = [f"{abs(n)} {s}" for s, n in diff.items() if (n > 0) == more and n] + return ", ".join(parts) + + +def check(doc: dict, step: dict) -> dict: + objects = doc.get("objects") or {} + rows: list[dict] = [] + notes: list[dict] = [] + left: list[dict] = [] + right: list[dict] = [] + for key, role, side in (("reactants", "reactant", left), ("products", "product", right)): + for oid in step.get(key) or []: + found = species(doc, oid) + if found is None: + notes.append(warning("not_a_structure", f"The {role} {plain_text(objects.get(oid)) or oid} is not a structure, so it is not counted.")) + continue + found.update({"id": oid, "role": role, "coefficient": _n(coefficient(step, oid))}) + side.append(found) + rows.append(found) + if found["generic"]: + notes.append(warning("generic_atoms", f"{', '.join(sorted(set(found['generic'])))} in {oid} cannot be counted, so the balance is approximate.")) + symbols: set[str] = {s for r in rows for s in r["counts"]} + total = lambda side, s: _n(sum(r["coefficient"] * r["counts"].get(s, 0) for r in side)) + elements = [{"element": s, "left": total(left, s), "right": total(right, s), "diff": _n(total(right, s) - total(left, s))} for s in sorted(symbols, key=_hill_key(symbols))] + charge = {"left": _n(sum(r["coefficient"] * r["charge"] for r in left)), "right": _n(sum(r["coefficient"] * r["charge"] for r in right))} + charge["diff"] = _n(charge["right"] - charge["left"]) + mass_left = round(sum(r["coefficient"] * r["mw"] for r in left), 4) + mass_right = round(sum(r["coefficient"] * r["mw"] for r in right), 4) + masses = {"left": mass_left, "right": mass_right, "diff": round(mass_right - mass_left, 4)} + diff = {e["element"]: e["diff"] for e in elements} + balanced = bool(left and right) and not any(diff.values()) and not charge["diff"] + if left and right and not balanced: + lost, gained = _side_text(diff, False), _side_text(diff, True) + text = "Not balanced." + (f" More on the left: {lost}." if lost else "") + (f" More on the right: {gained}." if gained else "") + if charge["diff"]: + text += f" Charge {charge['left']:+g} on the left, {charge['right']:+g} on the right." + notes.append(warning("unbalanced", text)) + if left and right and abs(masses["diff"]) > MASS_TOLERANCE: + notes.append(warning("mass_balance", f"The products weigh {abs(masses['diff']):.2f} g/mol {'more' if masses['diff'] > 0 else 'less'} than the reactants.")) + suggestion = None + if left and right and not balanced: + ints = solve(left, right) + if ints is not None: + suggestion = {"coefficients": {r["id"]: n for r, n in zip(left + right, ints)}} + else: + options = _co_products(left, right) + if options: + suggestion = {"co_products": [{"add": o["add"], "coefficients": {r["id"]: n for r, n in zip(left + right, o["coefficients"])}} for o in options]} + species_rows = [{k: r[k] for k in ("id", "role", "coefficient", "formula", "mw", "charge")} for r in rows] + return {"step": step.get("id"), "balanced": balanced, "species": species_rows, "elements": elements, "charge": charge, + "mass": masses, "suggestion": suggestion, "warnings": notes} + + +def coefficient_ops(path: list, step: dict, wanted: dict[str, int]) -> list[dict]: + roles = set(step.get("reactants") or []) | set(step.get("products") or []) | set(step.get("agents") or []) + merged = {k: v for k, v in (step.get("coefficients") or {}).items() if k in roles} + for oid, n in wanted.items(): + if oid in roles: + if n == 1: + merged.pop(oid, None) + else: + merged[oid] = n + if merged == (step.get("coefficients") or {}): + return [] + op: dict = {"op": "set", "path": [*path, "coefficients"]} + if merged: + op["value"] = merged + elif "coefficients" not in step: + return [] + return [op] From 3b47d09a789e30dfc3237adab5f3e9ee5c8a75f5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:04:06 -0500 Subject: [PATCH 010/279] fix(chem): keep imported reactions valid when a structure gets no layout (0.5.0) The 2D layout returns no coordinates for molecules made only of hydrogens, such as [H][H], and the NaN positions made the whole insert fail validation; such structures are now drawn as a row of atoms with a warning. --- backend/app/services/chem/scheme.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py index 6267a58e..69dcb128 100644 --- a/backend/app/services/chem/scheme.py +++ b/backend/app/services/chem/scheme.py @@ -1,5 +1,7 @@ +import math + from app.services import model -from app.services.chem import DEFAULT_BOND_LENGTH, geometry, io +from app.services.chem import DEFAULT_BOND_LENGTH, geometry, io, warning from app.services.chem.reactions import ReactionError, fresh_id, used_ids GAP_BONDS = 1.0 @@ -32,6 +34,15 @@ def _claim(frag: dict, used: set[str]) -> dict: return frag +def _repair(frag: dict, bond_length: float) -> bool: + atoms = list(frag["atoms"].values()) + if all(math.isfinite(a["x"]) and math.isfinite(a["y"]) for a in atoms): + return False + for n, a in enumerate(atoms): + a["x"], a["y"] = round(n * bond_length, 3), 0.0 + return True + + def _move(frag: dict, dx: float, dy: float) -> None: for a in frag["atoms"].values(): a["x"] = round(a["x"] + dx, 3) @@ -57,6 +68,7 @@ def layout(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGTH, ori used = used if used is not None else set() roles = parsed.reaction or {} frags = {f["id"]: f for f in parsed.fragments} + repaired = [f["id"] for f in parsed.fragments if _repair(f, bond_length)] pick = lambda key: [frags[i] for i in roles.get(key) or [] if i in frags] reactants, products, agents = pick("reactants"), pick("products"), pick("agents") if not reactants and not products: @@ -110,8 +122,10 @@ def side(items: list[dict], x: float) -> float: _claim(f, used) step = {"id": fresh_id(used, "r"), "arrow": arrow["id"], "reactants": [f["id"] for f in reactants], "products": [f["id"] for f in products], "agents": [f["id"] for f in agents], "conditions": [], "explicit": True} - return {"objects": objects, "reaction": {"id": fresh_id(used, "r"), "steps": [step]}, - "warnings": [w for w in parsed.warnings if w.get("code") != "reaction_arrow"]} + notes = [w for w in parsed.warnings if w.get("code") != "reaction_arrow"] + if repaired: + notes.append(warning("no_coordinates", f"{len(repaired)} structure{'s' if len(repaired) != 1 else ''} got no 2D layout and {'were' if len(repaired) != 1 else 'was'} drawn as a row of atoms; clean them up.")) + return {"objects": objects, "reaction": {"id": fresh_id(used, "r"), "steps": [step]}, "warnings": notes} def parse(text: str, fmt: str | None = None, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), From 00c787373159ccff16774f3b2aabc5eb8f0b23af Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:04:57 -0500 Subject: [PATCH 011/279] feat(chem): compute a step's stoichiometry from its typed amounts (0.5.0) Moles, equivalents, the amounts implied by equivalents and the scale, volumes, the limiting reagent, theoretical yields and the percent yield are worked out from step.stoich and the derived molecular weights on every request and never stored, as FORMAT.md asks; a typed amount always wins over typed equivalents, which only raise a warning when they disagree. --- backend/app/services/chem/stoich.py | 140 ++++++++++++++++++++++++++++ 1 file changed, 140 insertions(+) create mode 100644 backend/app/services/chem/stoich.py diff --git a/backend/app/services/chem/stoich.py b/backend/app/services/chem/stoich.py new file mode 100644 index 00000000..9fe66709 --- /dev/null +++ b/backend/app/services/chem/stoich.py @@ -0,0 +1,140 @@ +import math + +from app.services.chem import warning +from app.services.chem.reactions import coefficient, roles_of +from app.services.chem.rxnio import fragments_in, plain_text + +FIELDS = ("equiv", "mass_mg", "volume_ml", "density_g_ml", "conc_m", "purity_pct", "mw") +MISMATCH = 0.01 + + +def _pos(v: object) -> float | None: + if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v > 0: + return float(v) + return None + + +def _r(v: float | None, places: int = 4) -> float | None: + return None if v is None else round(v, places) + + +def derived_mass(doc: dict, oid: str, derived: dict | None) -> tuple[float | None, str]: + found = (derived or {}).get("fragments") or {} + frags = fragments_in(doc, oid) + if not frags: + return None, "" + total, formulas = 0.0, [] + for f in frags: + d = found.get(f["id"]) + mw = _pos((d or {}).get("mw")) + if mw is None: + return None, "" + total += mw + if d.get("formula"): + formulas.append(d["formula"]) + return total, ".".join(formulas) + + +def _label(doc: dict, oid: str, comp: dict, formula: str) -> str: + obj = (doc.get("objects") or {}).get(oid) or {} + if isinstance(comp.get("label"), str) and comp["label"].strip(): + return comp["label"].strip() + if isinstance(obj.get("name"), str) and obj["name"].strip(): + return obj["name"].strip() + return formula or plain_text(obj) or oid + + +def _fixed(comp: dict, mw: float | None, purity: float) -> tuple[float | None, float | None, str | None]: + mass, volume = _pos(comp.get("mass_mg")), _pos(comp.get("volume_ml")) + density, conc = _pos(comp.get("density_g_ml")), _pos(comp.get("conc_m")) + if mass is not None: + return (mass * purity / 100 / mw if mw else None), mass, "mass" + if volume is not None and conc is not None: + mmol = conc * volume + return mmol, (mmol * mw / (purity / 100) if mw else None), "solution" + if volume is not None and density is not None: + mass = volume * density * 1000 + return (mass * purity / 100 / mw if mw else None), mass, "volume" + return None, None, None + + +def compute(doc: dict, reaction: dict, step: dict, derived: dict | None) -> dict: + st = step.get("stoich") if isinstance(step.get("stoich"), dict) else {} + comps = st.get("components") if isinstance(st.get("components"), dict) else {} + notes: list[dict] = [] + rows: list[dict] = [] + for oid, role in roles_of(step): + comp = comps.get(oid) if isinstance(comps.get(oid), dict) else {} + found_mw, formula = derived_mass(doc, oid, derived) + entered = _pos(comp.get("mw")) + mw = entered or found_mw + purity = _pos(comp.get("purity_pct")) or 100.0 + mmol, mass, source = _fixed(comp, mw, purity) + if mw is None: + notes.append(warning("no_mw", f"{_label(doc, oid, comp, formula)} has no molecular weight yet; enter one to compute its amounts.")) + rows.append({"id": oid, "role": role, "label": _label(doc, oid, comp, formula), "formula": formula or None, "mw": _r(mw), + "mw_source": "entered" if entered else "derived" if found_mw else None, "coefficient": coefficient(step, oid), + "purity_pct": purity, "density_g_ml": _pos(comp.get("density_g_ml")), "conc_m": _pos(comp.get("conc_m")), + "equiv_entered": _pos(comp.get("equiv")), "mmol": mmol, "mass_mg": mass, "source": source if role != "product" else None, + "actual_mg": mass if role == "product" else None}) + by_id = {r["id"]: r for r in rows} + users = [r for r in rows if r["role"] != "product"] + reactants = [r for r in rows if r["role"] == "reactant"] + scale = _pos(st.get("scale_mmol")) + limiting_set = st.get("limiting") if (by_id.get(st.get("limiting")) or {}).get("role") == "reactant" else None + if st.get("limiting") and not limiting_set: + notes.append(warning("bad_limiting", "The chosen limiting reagent is not a reactant of this step.")) + reference = None + if scale: + reference = scale + else: + pick = [by_id[limiting_set]] if limiting_set else [] + for r in pick + users: + if r["source"] and r["mmol"]: + reference = r["mmol"] / (r["equiv_entered"] or 1.0) + break + for r in users: + if r["source"] is None and r["equiv_entered"] and reference: + r["mmol"], r["source"] = r["equiv_entered"] * reference, "equiv" + if r["mmol"] and r["mass_mg"] is None and r["mw"]: + r["mass_mg"] = r["mmol"] * r["mw"] / (r["purity_pct"] / 100) + r["equiv"] = r["mmol"] / reference if r["mmol"] and reference else r["equiv_entered"] + if r["source"] in ("mass", "volume", "solution") and r["equiv_entered"] and r["equiv"] and abs(r["equiv"] - r["equiv_entered"]) > MISMATCH * r["equiv_entered"]: + notes.append(warning("equiv_mismatch", f"{r['label']}: the amount entered gives {r['equiv']:.3g} equivalents, not the {r['equiv_entered']:g} entered.")) + if r["mmol"] is None: + notes.append(warning("no_amount", f"{r['label']} has no amount yet.")) + for r in rows: + r["volume_ml"] = None + if r["role"] != "product" and r["mass_mg"]: + if r["conc_m"] and r["mmol"]: + r["volume_ml"] = r["mmol"] / r["conc_m"] + elif r["density_g_ml"]: + r["volume_ml"] = r["mass_mg"] / r["density_g_ml"] / 1000 + limiting = by_id.get(limiting_set) if limiting_set else None + if limiting is None: + ranked = [r for r in reactants if r["mmol"]] + limiting = min(ranked, key=lambda r: r["mmol"] / r["coefficient"]) if ranked else None + for r in rows: + r["limiting"] = limiting is not None and r is limiting + target = st.get("product") if (by_id.get(st.get("product")) or {}).get("role") == "product" else next((r["id"] for r in rows if r["role"] == "product"), None) + summary = None + for r in rows: + if r["role"] != "product": + continue + r["mmol"] = r["mass_mg"] = None + if limiting is not None and limiting["mmol"]: + r["mmol"] = limiting["mmol"] / limiting["coefficient"] * r["coefficient"] + r["mass_mg"] = r["mmol"] * r["mw"] if r["mw"] else None + actual = r["actual_mg"] + if r["id"] == target and _pos(st.get("isolated_mg")): + actual = r["actual_mg"] = _pos(st.get("isolated_mg")) + r["yield_pct"] = round(actual / r["mass_mg"] * 100, 1) if actual and r["mass_mg"] else None + if r["id"] == target: + summary = {"product": r["id"], "theoretical_mmol": _r(r["mmol"]), "theoretical_mg": _r(r["mass_mg"]), "isolated_mg": actual, "percent": r["yield_pct"]} + for r in rows: + for key in ("mmol", "mass_mg", "volume_ml", "equiv"): + r[key] = _r(r.get(key)) + r.setdefault("yield_pct", None) + return {"reaction": reaction.get("id"), "step": step.get("id"), "scale_mmol": scale, "reference_mmol": _r(reference), + "limiting": limiting["id"] if limiting else None, "limiting_source": "entered" if limiting_set else "computed" if limiting else None, + "rows": rows, "yield": summary, "warnings": notes} From e24a6155d8f4855584ffcd1f710a9834c6a5ec79 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:39 -0500 Subject: [PATCH 012/279] feat(chem): build the stoichiometry grid table for a step (0.5.0) The grid is a table object with stoich {reaction, step} whose rows are written from the computed view in engineering units at three significant figures, placed under the scheme; asking again for a step that already has a grid rewrites its rows and columns and keeps the row ids. --- backend/app/services/chem/stoich.py | 109 +++++++++++++++++++++++++++- 1 file changed, 107 insertions(+), 2 deletions(-) diff --git a/backend/app/services/chem/stoich.py b/backend/app/services/chem/stoich.py index 9fe66709..d81f7299 100644 --- a/backend/app/services/chem/stoich.py +++ b/backend/app/services/chem/stoich.py @@ -1,7 +1,8 @@ import math -from app.services.chem import warning -from app.services.chem.reactions import coefficient, roles_of +from app.services import model +from app.services.chem import geometry, warning +from app.services.chem.reactions import bond_length, coefficient, find_step, fresh_id, roles_of from app.services.chem.rxnio import fragments_in, plain_text FIELDS = ("equiv", "mass_mg", "volume_ml", "density_g_ml", "conc_m", "purity_pct", "mw") @@ -138,3 +139,107 @@ def compute(doc: dict, reaction: dict, step: dict, derived: dict | None) -> dict return {"reaction": reaction.get("id"), "step": step.get("id"), "scale_mmol": scale, "reference_mmol": _r(reference), "limiting": limiting["id"] if limiting else None, "limiting_source": "entered" if limiting_set else "computed" if limiting else None, "rows": rows, "yield": summary, "warnings": notes} + + +HEADERS = ("Compound", "Formula", "Role", "MW", "Equiv", "Amount", "Mass", "Volume", "Yield") +ROLE_NAMES = {"reactant": "reactant", "agent": "reagent", "product": "product"} +PADDING = 3.0 +GRID_GAP_BONDS = 1.5 + + +def sig3(v: float) -> str: + if v == 0: + return "0" + places = max(0, 2 - int(math.floor(math.log10(abs(v))))) + return f"{round(v, places):.{places}f}" + + +def _scaled(v: float | None, steps: tuple[tuple[float, str], ...]) -> str: + if v is None: + return "" + for factor, unit in reversed(steps): + if abs(v) * factor >= 0.1 or unit == steps[0][1]: + return f"{sig3(v * factor)} {unit}" + return "" + + +def amount_text(mmol: float | None) -> str: + return _scaled(mmol, ((1000.0, "ยตmol"), (1.0, "mmol"), (0.001, "mol"))) + + +def mass_text(mg: float | None) -> str: + return _scaled(mg, ((1000.0, "ยตg"), (1.0, "mg"), (0.001, "g"), (0.000001, "kg"))) + + +def volume_text(ml: float | None) -> str: + return _scaled(ml, ((1000.0, "ยตL"), (1.0, "mL"), (0.001, "L"))) + + +def _formula_runs(text: str) -> list[dict]: + runs: list[dict] = [] + for ch in text: + sub = ch.isdigit() and bool(runs) and (runs[-1].get("sub") or not runs[-1]["t"][-1:].isspace()) + if runs and bool(runs[-1].get("sub")) == sub: + runs[-1]["t"] += ch + else: + runs.append({"t": ch, "sub": True} if sub else {"t": ch}) + return runs or [{"t": ""}] + + +def _cells(row: dict) -> list[list[dict]]: + texts = [ + row["label"], + None, + ROLE_NAMES.get(row["role"], row["role"]) + (", limiting" if row.get("limiting") else ""), + f"{row['mw']:.2f}" if row["mw"] else "", + sig3(row["equiv"]) if row.get("equiv") else "", + amount_text(row["mmol"]), + mass_text(row["actual_mg"] if row["role"] == "product" and row.get("actual_mg") else row["mass_mg"]), + volume_text(row.get("volume_ml")), + f"{row['yield_pct']:.1f}%" if row.get("yield_pct") is not None else "", + ] + out = [] + for n, t in enumerate(texts): + out.append(_formula_runs(row["formula"] or "") if n == 1 else [{"t": t or ""}]) + return out + + +def _width(runs: list[dict], size: float) -> float: + return sum(len(r["t"]) * size * (0.75 if r.get("sub") else 1.0) for r in runs) * 0.55 + + +def grid(view: dict, size: float = 10.0) -> tuple[list[float], list[list[list[dict]]]]: + body = [[[{"t": h}] for h in HEADERS]] + [_cells(r) for r in view["rows"]] + cols = [round(max(_width(row[c], size) for row in body) + 2 * PADDING + 2, 1) for c in range(len(HEADERS))] + return cols, body + + +def table_ops(doc: dict, page: dict, view: dict, used: set[str], at: tuple[float, float] | None = None) -> tuple[list[dict], dict]: + style = model.resolve_style(doc) + size = float((style.get("caption_font") or {}).get("size") or 10) + cols, body = grid(view, size) + height = round(size * 1.2 + 2 * PADDING, 1) + link = {"reaction": view["reaction"], "step": view["step"]} + objects = doc.get("objects") or {} + existing = next((objects[o] for o in page.get("order") or [] if isinstance(objects.get(o), dict) + and objects[o].get("kind") == "table" and objects[o].get("stoich") == link), None) + old_rows = existing.get("rows") if existing and isinstance(existing.get("rows"), list) else [] + rows = [] + for n, cells in enumerate(body): + rid = old_rows[n].get("id") if n < len(old_rows) and isinstance(old_rows[n], dict) and old_rows[n].get("id") else fresh_id(used, "l") + rows.append({"id": rid, "h": height, "cells": [{"runs": runs} for runs in cells]}) + if existing is not None: + ops = [] + for key, value in (("cols", cols), ("rows", rows)): + if existing.get(key) != value: + ops.append({"op": "set", "path": ["objects", existing["id"], key], "value": value}) + return ops, {**existing, "cols": cols, "rows": rows} + if at is None: + _, _, step = find_step(doc, view["reaction"], view["step"], page.get("id")) + ids = [step.get("arrow")] + [o for k in ("reactants", "products", "agents", "conditions") for o in step.get(k) or []] + box = geometry.union([geometry.object_box(doc, o, style) for o in ids if isinstance(o, str)]) + at = (box[0], box[3] + GRID_GAP_BONDS * bond_length(doc)) if box else (float(page.get("margins", 36)),) * 2 + table = {"id": fresh_id(used, "o"), "kind": "table", "x": round(at[0], 3), "y": round(at[1], 3), "cols": cols, "rows": rows, + "padding": PADDING, "header": True, "borders": "all", "stoich": link} + return [{"op": "set", "path": ["objects", table["id"]], "value": table}, + {"op": "ins", "path": ["pages", {"id": page["id"]}, "order"], "value": table["id"]}], table From 199f6624aa8a0cd4a08635019d9a66d6a2087a2e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:06:44 -0500 Subject: [PATCH 013/279] feat(api): add reaction perception routes (0.5.0) Perceiving reactions is a command: one undoable transaction on page.reactions, or nothing when the scheme is unchanged. The preview route returns what perception would write without changing the drawing, for a derived display while the person draws. --- backend/app/routers/reactions.py | 92 ++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 backend/app/routers/reactions.py diff --git a/backend/app/routers/reactions.py b/backend/app/routers/reactions.py new file mode 100644 index 00000000..5d736be3 --- /dev/null +++ b/backend/app/routers/reactions.py @@ -0,0 +1,92 @@ +import asyncio +import copy + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import window_key +from app.services import ops as opsmod +from app.services.chem import reactions +from app.services.store import STORE + +router = APIRouter() + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +def _snapshot(doc_id: str) -> tuple[object, dict]: + try: + s = STORE.get(doc_id) + except KeyError: + raise HTTPException(404, f"No open drawing has the id {doc_id}.") + with s.lock: + return s, copy.deepcopy(s.doc) + + +def _failed(exc: reactions.ReactionError) -> HTTPException: + return HTTPException(exc.status, str(exc)) + + +def _client(body: dict) -> str | None: + found = body.get("client") + return found if isinstance(found, str) and found else None + + +def _origin(body: dict) -> str: + return body.get("origin") if body.get("origin") in ("user", "system") else "user" + + +def _page_ids(value: object) -> list[str] | None: + if value is None: + return None + if isinstance(value, str) and value: + return [value] + raise HTTPException(422, "page must be a page id") + + +async def _commit(doc_id: str, label: str, ops: list[dict], body: dict, rev: int) -> dict: + if not ops: + return {"changed": False, "tx": None, "rev": rev} + try: + result = await STORE.apply(doc_id, {"label": label, "ops": ops}, _origin(body), client=_client(body)) + except opsmod.OpError as exc: + raise HTTPException(409, {"message": str(exc), "errors": exc.errors}) + except KeyError: + raise HTTPException(404, f"The drawing {doc_id} was closed.") + return {"changed": True, "tx": result["tx"], "rev": result["rev"]} + + +def _listing(doc: dict) -> list[dict]: + return [{"page": p.get("id"), "reactions": p.get("reactions") or []} for p in doc.get("pages") or [] if isinstance(p, dict)] + + +@router.get("/api/documents/{doc_id}/reactions") +def list_reactions(doc_id: str) -> dict: + s, doc = _snapshot(doc_id) + return {"rev": s.rev, "pages": _listing(doc)} + + +@router.get("/api/documents/{doc_id}/reactions/preview") +def preview_reactions(doc_id: str, page: str | None = None) -> dict: + s, doc = _snapshot(doc_id) + try: + found = reactions.preview(doc, _page_ids(page)) + except reactions.ReactionError as exc: + raise _failed(exc) + return {"rev": s.rev, "pages": [{**{k: v for k, v in p.items() if k != "list"}, "reactions": p["list"]} for p in found]} + + +@router.post("/api/documents/{doc_id}/reactions/perceive", dependencies=GUARD) +async def perceive_reactions(doc_id: str, body: dict = Body(default={})) -> dict: + s, doc = _snapshot(doc_id) + try: + ops, summaries = await asyncio.to_thread(reactions.perceive_ops, doc, _page_ids(body.get("page"))) + except reactions.ReactionError as exc: + raise _failed(exc) + out = await _commit(doc_id, "Perceive reactions", ops, body, s.rev) + _, after = _snapshot(doc_id) + return {**out, "summary": summaries, "pages": _listing(after)} From 354277b596117671f9f3b5f3ff095d2237892873 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:08:11 -0500 Subject: [PATCH 014/279] feat(api): add atom mapping, reaction export and import routes (0.5.0) A step is mapped or cleared as one undoable transaction, exported as reaction SMILES, RXN V2000 or V3000 without touching the drawing, and reaction text is either laid out for the window to place (paste) or inserted under the drawing's content as one transaction. --- backend/app/routers/reactions.py | 89 +++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/reactions.py b/backend/app/routers/reactions.py index 5d736be3..218add7d 100644 --- a/backend/app/routers/reactions.py +++ b/backend/app/routers/reactions.py @@ -1,14 +1,16 @@ import asyncio import copy +import math from fastapi import APIRouter, Body, Depends, HTTPException, Request from app.core import window_key from app.services import ops as opsmod -from app.services.chem import reactions +from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, mapping, reactions, rxnio, scheme from app.services.store import STORE router = APIRouter() +MAX_TEXT = 20 * 1024 * 1024 def _guard(request: Request) -> None: @@ -90,3 +92,88 @@ async def perceive_reactions(doc_id: str, body: dict = Body(default={})) -> dict out = await _commit(doc_id, "Perceive reactions", ops, body, s.rev) _, after = _snapshot(doc_id) return {**out, "summary": summaries, "pages": _listing(after)} + + +def _step(doc: dict, reaction_id: str, step_id: str) -> tuple[dict, dict, dict]: + try: + return reactions.find_step(doc, reaction_id, step_id) + except reactions.ReactionError as exc: + raise _failed(exc) + + +STEP = "/api/documents/{doc_id}/reactions/{reaction_id}/steps/{step_id}" + + +@router.post(STEP + "/map", dependencies=GUARD) +async def map_step(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(default={})) -> dict: + s, doc = _snapshot(doc_id) + _, _, step = _step(doc, reaction_id, step_id) + mode = body.get("mode", "discard") + if mode not in ("discard", "keep", "alter"): + raise HTTPException(422, "mode must be discard, keep or alter") + try: + ops, info = await asyncio.to_thread(mapping.map_ops, doc, step, mode, body.get("centres", True) is not False) + except reactions.ReactionError as exc: + raise _failed(exc) + return {**await _commit(doc_id, "Map atoms", ops, body, s.rev), "mapping": info} + + +@router.delete(STEP + "/map", dependencies=GUARD) +async def clear_map(doc_id: str, reaction_id: str, step_id: str, centres: bool = True, client: str | None = None) -> dict: + s, doc = _snapshot(doc_id) + _, _, step = _step(doc, reaction_id, step_id) + ops, info = mapping.clear_ops(doc, step, centres) + return {**await _commit(doc_id, "Clear mapping", ops, {"client": client}, s.rev), "mapping": info} + + +@router.get(STEP + "/export") +def export_step(doc_id: str, reaction_id: str, step_id: str, format: str = "rxn") -> dict: + _, doc = _snapshot(doc_id) + _, reaction, step = _step(doc, reaction_id, step_id) + title = reaction.get("name") or step.get("name") or doc.get("title") or "" + try: + text, warnings = rxnio.export_step(doc, step, format, str(title)) + except reactions.ReactionError as exc: + raise _failed(exc) + return {"format": format, "text": text, "warnings": warnings, "engine": ENGINE} + + +def _text(body: dict) -> str: + text = body.get("text") + if not isinstance(text, str) or not text.strip(): + raise HTTPException(422, "text is required") + if len(text) > MAX_TEXT: + raise HTTPException(413, "text is too large") + return text + + +def _point(value: object) -> tuple[float, float] | None: + if isinstance(value, list) and len(value) == 2 and all(isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) for v in value): + return (float(value[0]), float(value[1])) + return None + + +@router.post("/api/chem/reactions/import") +def import_reaction(body: dict = Body(...)) -> dict: + text = _text(body) + length = body.get("bond_length", DEFAULT_BOND_LENGTH) + if isinstance(length, bool) or not isinstance(length, (int, float)) or not 1 <= length <= 500: + raise HTTPException(422, "bond_length must be a number of points from 1 to 500") + try: + return scheme.parse(text, body.get("format"), float(length), _point(body.get("origin")) or (72.0, 72.0)) + except reactions.ReactionError as exc: + raise _failed(exc) + + +@router.post("/api/documents/{doc_id}/reactions/import", dependencies=GUARD) +async def insert_reaction(doc_id: str, body: dict = Body(...)) -> dict: + text = _text(body) + s, doc = _snapshot(doc_id) + try: + page = reactions.page_of(doc, body.get("page") if isinstance(body.get("page"), str) else None) + ops, found = await asyncio.to_thread(scheme.insert_ops, doc, page, text, body.get("format"), _point(body.get("origin"))) + except reactions.ReactionError as exc: + raise _failed(exc) + out = await _commit(doc_id, "Insert reaction", ops, body, s.rev) + return {**out, "page": page["id"], "format": found["format"], "objects": [o["id"] for o in found["objects"]], + "reaction": found["reaction"], "warnings": found["warnings"]} From f787983d04d3c84f1f94cf4926ad59ef0eb8979e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:08:11 -0500 Subject: [PATCH 015/279] feat(chem): read the conditions line of RXN files back as text (0.5.0) Export writes a step's conditions on the RXN comment line, so import and File > Open now draw that line under the arrow as the step's conditions and a round trip keeps it. --- backend/app/services/chem/scheme.py | 19 +++++++++++++++---- backend/app/services/importers.py | 7 ++++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py index 69dcb128..9b2b400a 100644 --- a/backend/app/services/chem/scheme.py +++ b/backend/app/services/chem/scheme.py @@ -63,8 +63,13 @@ def put(self, frag: dict, left: float, cy: float) -> float: return left + b[2] - b[0] +def rxn_comment(text: str) -> str: + lines = text.replace("\r\n", "\n").lstrip("๏ปฟ").split("\n") + return lines[3].strip() if len(lines) > 3 and lines[0].startswith("$RXN") else "" + + def layout(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), - used: set[str] | None = None) -> dict: + used: set[str] | None = None, conditions: str = "") -> dict: used = used if used is not None else set() roles = parsed.reaction or {} frags = {f["id"]: f for f in parsed.fragments} @@ -99,7 +104,9 @@ def side(items: list[dict], x: float) -> float: tail = x + END_BONDS * bl if reactants else x widths = [p.box(f)[2] - p.box(f)[0] for f in agents] span = sum(widths) + GAP_BONDS * bl * max(0, len(agents) - 1) - length = max(ARROW_BONDS * bl, span + 2 * CONDITION_PAD) + note = {"id": fresh_id(used, "o"), "kind": "text", "x": 0.0, "y": round(cy + END_BONDS * bl, 3), "align": "c", "runs": [{"t": conditions}]} if conditions else None + note_w = geometry.text_box(note, p.style)[2] - geometry.text_box(note, p.style)[0] if note else 0.0 + length = max(ARROW_BONDS * bl, span + 2 * CONDITION_PAD, note_w + 2 * CONDITION_PAD) ax = tail + (length - span) / 2 for f, w in zip(agents, widths): b = p.box(f) @@ -110,6 +117,9 @@ def side(items: list[dict], x: float) -> float: arrow = {"id": fresh_id(used, "o"), "kind": "arrow", "type": "forward", "x1": round(tail, 3), "y1": round(cy, 3), "x2": round(head, 3), "y2": round(cy, 3), "head": "full", "tail": "none"} objects.append(arrow) + if note: + note["x"] = round((tail + head) / 2, 3) + objects.append(note) side(products, head + END_BONDS * bl) bottom = max((p.box(f)[3] for f in reactants + products), default=cy) + ROW_GAP_BONDS * bl x = x0 @@ -121,7 +131,7 @@ def side(items: list[dict], x: float) -> float: for f in parsed.fragments: _claim(f, used) step = {"id": fresh_id(used, "r"), "arrow": arrow["id"], "reactants": [f["id"] for f in reactants], "products": [f["id"] for f in products], - "agents": [f["id"] for f in agents], "conditions": [], "explicit": True} + "agents": [f["id"] for f in agents], "conditions": [note["id"]] if note else [], "explicit": True} notes = [w for w in parsed.warnings if w.get("code") != "reaction_arrow"] if repaired: notes.append(warning("no_coordinates", f"{len(repaired)} structure{'s' if len(repaired) != 1 else ''} got no 2D layout and {'were' if len(repaired) != 1 else 'was'} drawn as a row of atoms; clean them up.")) @@ -139,7 +149,8 @@ def parse(text: str, fmt: str | None = None, bond_length: float = DEFAULT_BOND_L raise ReactionError(str(exc)) from exc if parsed.reaction is None: raise ReactionError(f"The text reads as {parsed.format}, not as a reaction.") - return {"format": parsed.format, **layout(parsed, bond_length, origin, used)} + comment = rxn_comment(text) if parsed.format == "rxn" else "" + return {"format": parsed.format, **layout(parsed, bond_length, origin, used, comment)} def free_origin(doc: dict, page: dict) -> tuple[float, float]: diff --git a/backend/app/services/importers.py b/backend/app/services/importers.py index 8a1a49b3..f40d0335 100644 --- a/backend/app/services/importers.py +++ b/backend/app/services/importers.py @@ -170,11 +170,12 @@ def place(frags: list[dict], page: dict, bond_length: float) -> None: top += height + gap -def _reaction(doc: dict, page: dict, result: object, bond_length: float, ids: _Ids, warnings: list[str]) -> bool: +def _reaction(doc: dict, page: dict, result: object, bond_length: float, ids: _Ids, warnings: list[str], source: Path) -> bool: margin = float(page.get("margins", 36)) try: from app.services.chem import scheme - found = scheme.layout(result, bond_length, (margin, margin), ids.used) + comment = scheme.rxn_comment(source.read_text(encoding="utf-8", errors="replace")) if source.suffix.lower() == ".rxn" else "" + found = scheme.layout(result, bond_length, (margin, margin), ids.used, comment) except Exception as exc: warnings.append(f"the reaction could not be laid out, so its structures are placed in rows ({exc})") return False @@ -205,7 +206,7 @@ def import_file(path: str | Path) -> tuple[dict, list[str]]: page = doc["pages"][0] ids = _Ids({doc["id"], page["id"]}) warnings: list[str] = [t for t in (_warning_text(w) for w in getattr(result, "warnings", None) or []) if t] - if not (getattr(result, "reaction", None) and _reaction(doc, page, result, bond_length, ids, warnings)): + if not (getattr(result, "reaction", None) and _reaction(doc, page, result, bond_length, ids, warnings, p)): frags = [f for f in (normalise_fragment(raw, ids, warnings) for raw in parsed if isinstance(raw, dict)) if f is not None] if not frags: raise ImportFailed(f"{p.name} holds no structures FormChem can draw.") From 754e94739178e22fd54af8e04759f7d176bcf503 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:08:38 -0500 Subject: [PATCH 016/279] feat(chem): warn when a resonance arrow joins structures that are not resonance forms (0.5.0) A resonance arrow is not a reaction step, so the reaction check compares the nearest structure on each side instead: a different formula or charge, or a different heavy-atom skeleton once bond orders, charges and hydrogens are ignored, gives a warning naming the arrow. --- backend/app/services/chem/balance.py | 51 ++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/backend/app/services/chem/balance.py b/backend/app/services/chem/balance.py index ee805892..019a17b8 100644 --- a/backend/app/services/chem/balance.py +++ b/backend/app/services/chem/balance.py @@ -4,8 +4,9 @@ from rdkit import Chem -from app.services.chem import ids, mass, perceive, warning -from app.services.chem.reactions import coefficient +from app.services import model +from app.services.chem import geometry, ids, mass, perceive, warning +from app.services.chem.reactions import ROW_BONDS, END_BONDS, _items, _walk, bond_length, coefficient, direction from app.services.chem.rxnio import fragments_in, plain_text PT = Chem.GetPeriodicTable() @@ -176,6 +177,52 @@ def check(doc: dict, step: dict) -> dict: "mass": masses, "suggestion": suggestion, "warnings": notes} +def _skeleton(doc: dict, oid: str) -> str: + parts = [] + for frag in fragments_in(doc, oid): + mol = Chem.RWMol(perceive.prepare(frag, doc.get("expansions")).mol) + for b in mol.GetBonds(): + b.SetBondType(Chem.BondType.SINGLE) + b.SetIsAromatic(False) + for a in mol.GetAtoms(): + a.SetFormalCharge(0) + a.SetIsAromatic(False) + a.SetNumRadicalElectrons(0) + a.SetNumExplicitHs(0) + a.SetNoImplicit(True) + a.SetAtomMapNum(0) + a.SetIsotope(0) + parts.append(Chem.MolToSmiles(mol, canonical=True)) + return ".".join(sorted(parts)) + + +def resonance(doc: dict, page: dict) -> list[dict]: + style = model.resolve_style(doc) + out = [] + for oid in page.get("order") or []: + arrow = (doc.get("objects") or {}).get(oid) + if not isinstance(arrow, dict) or arrow.get("kind") != "arrow" or arrow.get("type") != "resonance" or geometry.arrow_points(arrow) is None: + continue + tail, head = direction(arrow) + frame = geometry.Frame(tail, head) + bl = bond_length(doc) + row = [i for i in _items(doc, page, oid, frame, style) if i.t1 >= -ROW_BONDS * bl and i.t0 <= ROW_BONDS * bl] + before = _walk([i for i in row if i.s1 <= END_BONDS * bl], False, bl)[-1:] + after = _walk([i for i in row if i.s0 >= frame.length - END_BONDS * bl], True, bl)[:1] + if not before or not after: + continue + a, b = species(doc, before[0]), species(doc, after[0]) + if a is None or b is None: + continue + if a["counts"] != b["counts"] or a["charge"] != b["charge"]: + out.append({**warning("resonance_formula", f"The structures on either side of this resonance arrow differ in formula ({a['formula']} and {b['formula']}), so they are not resonance forms."), + "arrow": oid, "objects": [before[0], after[0]]}) + elif _skeleton(doc, before[0]) != _skeleton(doc, after[0]): + out.append({**warning("resonance_connectivity", "The structures on either side of this resonance arrow are connected differently; resonance forms differ only in where the electrons are."), + "arrow": oid, "objects": [before[0], after[0]]}) + return out + + def coefficient_ops(path: list, step: dict, wanted: dict[str, int]) -> list[dict]: roles = set(step.get("reactants") or []) | set(step.get("products") or []) | set(step.get("agents") or []) merged = {k: v for k, v in (step.get("coefficients") or {}).items() if k in roles} From a5e65321432cd01e8e39e04d94691d3e19cab6c3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:09:45 -0500 Subject: [PATCH 017/279] feat(api): add reaction check, balance and stoichiometry routes (0.5.0) The derived cache has no slot for reactions, so balance and mass-balance warnings and resonance checks are returned by the check routes; balancing writes the suggested or given coefficients as one transaction, the stoichiometry view is computed on request from the current derived masses, and the grid route inserts or refreshes the step's table. --- backend/app/routers/reactions.py | 71 +++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/reactions.py b/backend/app/routers/reactions.py index 218add7d..6e2e1edb 100644 --- a/backend/app/routers/reactions.py +++ b/backend/app/routers/reactions.py @@ -6,7 +6,7 @@ from app.core import window_key from app.services import ops as opsmod -from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, mapping, reactions, rxnio, scheme +from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, balance, mapping, reactions, rxnio, scheme, stoich from app.services.store import STORE router = APIRouter() @@ -177,3 +177,72 @@ async def insert_reaction(doc_id: str, body: dict = Body(...)) -> dict: out = await _commit(doc_id, "Insert reaction", ops, body, s.rev) return {**out, "page": page["id"], "format": found["format"], "objects": [o["id"] for o in found["objects"]], "reaction": found["reaction"], "warnings": found["warnings"]} + + +@router.get("/api/documents/{doc_id}/reactions/check") +def check_reactions(doc_id: str, page: str | None = None) -> dict: + s, doc = _snapshot(doc_id) + try: + pages = [reactions.page_of(doc, page)] if page else [p for p in doc.get("pages") or [] if isinstance(p, dict)] + except reactions.ReactionError as exc: + raise _failed(exc) + out = [] + for p in pages: + steps = [{"reaction": r.get("id"), **balance.check(doc, st)} for r in p.get("reactions") or [] if isinstance(r, dict) + for st in r.get("steps") or [] if isinstance(st, dict)] + out.append({"page": p.get("id"), "steps": steps, "resonance": balance.resonance(doc, p)}) + return {"rev": s.rev, "pages": out} + + +@router.get(STEP + "/check") +def check_step(doc_id: str, reaction_id: str, step_id: str) -> dict: + s, doc = _snapshot(doc_id) + _, _, step = _step(doc, reaction_id, step_id) + return {"rev": s.rev, "reaction": reaction_id, **balance.check(doc, step)} + + +@router.post(STEP + "/balance", dependencies=GUARD) +async def balance_step(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(default={})) -> dict: + s, doc = _snapshot(doc_id) + page, _, step = _step(doc, reaction_id, step_id) + wanted = body.get("coefficients") + if wanted is None: + found = balance.check(doc, step) + wanted = ((found.get("suggestion") or {}).get("coefficients")) + if wanted is None: + raise HTTPException(422, "This step has no balancing coefficients to apply: " + ( + "it is already balanced." if found["balanced"] else "add the missing co-products first (see check).")) + elif not isinstance(wanted, dict) or not all(isinstance(k, str) and isinstance(v, int) and not isinstance(v, bool) and 1 <= v <= 999 for k, v in wanted.items()): + raise HTTPException(422, "coefficients must map object ids to whole numbers from 1 to 999") + ops = balance.coefficient_ops(reactions.step_path(page["id"], reaction_id, step_id), step, wanted) + out = await _commit(doc_id, "Balance reaction", ops, body, s.rev) + _, after = _snapshot(doc_id) + _, _, step = _step(after, reaction_id, step_id) + return {**out, "coefficients": step.get("coefficients") or {}, "check": balance.check(after, step)} + + +async def _view(doc_id: str, reaction_id: str, step_id: str) -> tuple[object, dict, dict, dict, dict]: + s, doc = _snapshot(doc_id) + page, reaction, step = _step(doc, reaction_id, step_id) + try: + derived = await asyncio.to_thread(STORE.derive_now, doc_id) + except Exception: + derived = None + if derived is None or derived.get("rev") != s.rev: + s, doc = _snapshot(doc_id) + page, reaction, step = _step(doc, reaction_id, step_id) + return s, doc, page, reaction, stoich.compute(doc, reaction, step, derived) + + +@router.get(STEP + "/stoich") +async def step_stoich(doc_id: str, reaction_id: str, step_id: str) -> dict: + s, _, _, _, view = await _view(doc_id, reaction_id, step_id) + return {"rev": s.rev, **view} + + +@router.post(STEP + "/stoich-table", dependencies=GUARD) +async def step_stoich_table(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(default={})) -> dict: + s, doc, page, _, view = await _view(doc_id, reaction_id, step_id) + ops, table = stoich.table_ops(doc, page, view, reactions.used_ids(doc), _point(body.get("at"))) + out = await _commit(doc_id, "Stoichiometry grid", ops, body, s.rev) + return {**out, "table": table["id"], "stoich": view} From 60ec373dde45abd3765e67907bb353d0ee678df5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:09:45 -0500 Subject: [PATCH 018/279] fix(chem): show grid amounts the way chemists write them (0.5.0) Rounding 9.9997 to three figures printed 10.00, masses under a gram printed as 0.601 g, and a product's mass column showed the isolated amount instead of the theoretical one; three figures now survive a carry, masses and amounts switch unit at 1 and volumes at 0.1, and isolated mass has its own column. --- backend/app/services/chem/stoich.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/backend/app/services/chem/stoich.py b/backend/app/services/chem/stoich.py index d81f7299..89e9b0a8 100644 --- a/backend/app/services/chem/stoich.py +++ b/backend/app/services/chem/stoich.py @@ -141,7 +141,7 @@ def compute(doc: dict, reaction: dict, step: dict, derived: dict | None) -> dict "rows": rows, "yield": summary, "warnings": notes} -HEADERS = ("Compound", "Formula", "Role", "MW", "Equiv", "Amount", "Mass", "Volume", "Yield") +HEADERS = ("Compound", "Formula", "Role", "MW", "Equiv", "Amount", "Mass", "Volume", "Isolated", "Yield") ROLE_NAMES = {"reactant": "reactant", "agent": "reagent", "product": "product"} PADDING = 3.0 GRID_GAP_BONDS = 1.5 @@ -150,29 +150,32 @@ def compute(doc: dict, reaction: dict, step: dict, derived: dict | None) -> dict def sig3(v: float) -> str: if v == 0: return "0" - places = max(0, 2 - int(math.floor(math.log10(abs(v))))) + exponent = int(math.floor(math.log10(abs(v)))) + if abs(round(v, 2 - exponent)) >= 10 ** (exponent + 1): + exponent += 1 + places = max(0, 2 - exponent) return f"{round(v, places):.{places}f}" -def _scaled(v: float | None, steps: tuple[tuple[float, str], ...]) -> str: +def _scaled(v: float | None, steps: tuple[tuple[float, str], ...], least: float) -> str: if v is None: return "" for factor, unit in reversed(steps): - if abs(v) * factor >= 0.1 or unit == steps[0][1]: + if abs(v) * factor >= least or unit == steps[0][1]: return f"{sig3(v * factor)} {unit}" return "" def amount_text(mmol: float | None) -> str: - return _scaled(mmol, ((1000.0, "ยตmol"), (1.0, "mmol"), (0.001, "mol"))) + return _scaled(mmol, ((1000.0, "ยตmol"), (1.0, "mmol"), (0.001, "mol")), 1.0) def mass_text(mg: float | None) -> str: - return _scaled(mg, ((1000.0, "ยตg"), (1.0, "mg"), (0.001, "g"), (0.000001, "kg"))) + return _scaled(mg, ((1000.0, "ยตg"), (1.0, "mg"), (0.001, "g"), (0.000001, "kg")), 1.0) def volume_text(ml: float | None) -> str: - return _scaled(ml, ((1000.0, "ยตL"), (1.0, "mL"), (0.001, "L"))) + return _scaled(ml, ((1000.0, "ยตL"), (1.0, "mL"), (0.001, "L")), 0.1) def _formula_runs(text: str) -> list[dict]: @@ -194,13 +197,15 @@ def _cells(row: dict) -> list[list[dict]]: f"{row['mw']:.2f}" if row["mw"] else "", sig3(row["equiv"]) if row.get("equiv") else "", amount_text(row["mmol"]), - mass_text(row["actual_mg"] if row["role"] == "product" and row.get("actual_mg") else row["mass_mg"]), + mass_text(row["mass_mg"]), volume_text(row.get("volume_ml")), + mass_text(row.get("actual_mg")) if row["role"] == "product" else "", f"{row['yield_pct']:.1f}%" if row.get("yield_pct") is not None else "", ] out = [] for n, t in enumerate(texts): - out.append(_formula_runs(row["formula"] or "") if n == 1 else [{"t": t or ""}]) + formula = n == 1 or (n == 0 and row["formula"] and row["label"] == row["formula"]) + out.append(_formula_runs(row["formula"] or "") if formula else [{"t": t or ""}]) return out From e14f40b4a604fdeac7eea6e325ad7945af9770ab Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:11:08 -0500 Subject: [PATCH 019/279] feat(mcp): add reaction tools for agents (0.5.0) Agents can now perceive a drawing's reaction steps, map a step's atoms, export a step as reaction SMILES or RXN and read its stoichiometry with the balance check; the two that change the drawing ask the person first like the other changing tools and land as one agent undo step each. --- backend/app/routers/mcp.py | 135 ++++++++++++++++++++++++++++++++++++- 1 file changed, 134 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 82bdee12..62dfa35a 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -1,3 +1,5 @@ +import asyncio +import copy import json import time import uuid @@ -50,6 +52,10 @@ - extensions_list: the Form extensions FormChem found (installed by FormPortal or run from a folder by form.ext), their state and their commands. - extension_command {{id, command, args?}}: runs a command an extension contributes, in the open window. The window asks the person to allow the extension the first time. - handoff {{state?, note?}}: tells the person where your work stands: working, ready (done, for them to look at), question (you need their input; say what in note) or clear. It shows in the window. With no state it lists the current handoffs. +- perceive_reactions {{doc?, page?}}: works out the reaction steps from the arrows and the structures around them and writes them to the drawing (one undo step); steps set by hand are kept. Returns reaction and step ids. +- map_reaction {{doc?, reaction?, step?, mode?}}: maps reactant atoms to product atoms and marks broken, formed and changed bonds (one undo step); mode clear removes the mapping. +- export_reaction {{doc?, reaction?, step?, format?}}: a step as reaction SMILES or RXN (V2000 or V3000). Read only. +- reaction_stoichiometry {{doc?, reaction?, step?}}: moles, equivalents, masses, volumes, limiting reagent and yields from the amounts in the step's grid, with the balance check. Read only. ## Asking the person run_command, extension_command and handoff with a state change what the person sees, so the first such call from an agent asks the person in the FormChem window: Deny, Allow once or Always allow. With no window open there is nobody to ask, and the call is refused with a sentence saying so. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are already trusted and are never asked. @@ -99,9 +105,21 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = _tool("handoff", "Tells the person where your work stands: working (still on it), ready (done, for them to look at) or question (you need their input, say what in note); clear removes your handoff. " "It shows in the FormChem window. With no state, lists the current handoffs.", {"state": {"type": "string", "enum": list(HANDOFF_STATES)}, "note": {"type": "string", "description": "One short line for the person"}}), + _tool("perceive_reactions", "Works out the reaction steps of a drawing from where its structures sit around the reaction arrows (before the tail: reactants, after the head: products, beside the arrow: agents and conditions text; " + "plus signs join) and writes them to the drawing as one undo step. Steps someone set by hand are kept. Returns every reaction with its step ids.", + {"doc": {"type": "string", "description": "Drawing id from get_context; may be left out when one drawing is open"}, "page": {"type": "string", "description": "Page id; all pages when left out"}}), + _tool("map_reaction", "Maps the atoms of one reaction step (reactant atom to product atom numbers) and marks the bonds broken, formed or changed in order, as one undo step. " + "mode discard (default) maps from scratch, keep keeps the numbers already drawn, alter may change them, clear removes the mapping.", + {"doc": {"type": "string"}, "reaction": {"type": "string", "description": "Reaction id from perceive_reactions; the first reaction when left out"}, + "step": {"type": "string", "description": "Step id; the first step when left out"}, "mode": {"type": "string", "enum": ["discard", "keep", "alter", "clear"]}}), + _tool("export_reaction", "One reaction step as reaction SMILES (format smiles) or an RXN file (rxn for V2000, rxnv3000), with its map numbers. Does not change the drawing.", + {"doc": {"type": "string"}, "reaction": {"type": "string"}, "step": {"type": "string"}, "format": {"type": "string", "enum": ["smiles", "rxn", "rxnv3000"]}}, read=True), + _tool("reaction_stoichiometry", "The stoichiometry of one reaction step worked out from the amounts the person typed in its grid and the molecular weights: moles, equivalents, masses, volumes, " + "the limiting reagent, theoretical yields and the percent yield, plus the balance check. Does not change the drawing.", + {"doc": {"type": "string"}, "reaction": {"type": "string"}, "step": {"type": "string"}}, read=True), ] NAMES = {t["name"] for t in TOOLS} -MUTATING = {"run_command", "extension_command"} +MUTATING = {"run_command", "extension_command", "perceive_reactions", "map_reaction"} def _ok(text: str, data: dict | None = None) -> dict: @@ -339,6 +357,121 @@ async def t_handoff(a: Agent, args: dict) -> dict: return _ok("\n".join(_handoff_line(h) for h in items) if items else "No handoff from any agent.", {"handoffs": items}) +def _drawing(args: dict) -> tuple[str, dict]: + from app.services.store import STORE + wanted = str(args.get("doc") or "").strip() + if not wanted: + open_ids = list(STORE.sessions) + if len(open_ids) != 1: + raise ToolError("Give doc, a drawing id from get_context." if open_ids else "No drawing is open. Open or create one first (run_command new-document or open-recent).") + wanted = open_ids[0] + try: + s = STORE.get(wanted) + except KeyError: + raise ToolError(f"No open drawing has the id {wanted}. get_context lists the open drawings.") from None + with s.lock: + return wanted, copy.deepcopy(s.doc) + + +def _reaction_step(doc: dict, args: dict) -> tuple[dict, dict, dict]: + from app.services.chem import reactions + try: + return reactions.find_step(doc, str(args.get("reaction") or "") or None, str(args.get("step") or "") or None) + except reactions.ReactionError as exc: + raise ToolError(f"{exc} perceive_reactions lists the reactions and their step ids.") from None + + +async def _apply(a: Agent, doc_id: str, label: str, ops: list[dict]) -> dict | None: + from app.services import ops as opsmod + from app.services.store import STORE + if not ops: + return None + try: + return await STORE.apply(doc_id, {"label": label, "ops": ops}, "agent", agent=a.name) + except opsmod.OpError as exc: + raise ToolError(f"The drawing refused the change: {exc}. Call get_context and try again.") from None + + +async def t_perceive_reactions(a: Agent, args: dict) -> dict: + from app.services.chem import reactions + doc_id, doc = _drawing(args) + page = str(args.get("page") or "").strip() + try: + ops, summaries = await asyncio.to_thread(reactions.perceive_ops, doc, [page] if page else None) + except reactions.ReactionError as exc: + raise ToolError(str(exc)) from None + done = await _apply(a, doc_id, "Perceive reactions", ops) + _, after = _drawing({"doc": doc_id}) + lines = [f"{'Wrote' if done else 'No change to'} the reactions of {doc_id}" + (f" (rev {done['rev']}, one undo step)." if done else ".")] + listing = [] + for p in after.get("pages") or []: + for r in p.get("reactions") or []: + for n, st in enumerate(r.get("steps") or []): + lines.append(f"- reaction {r['id']} step {n + 1} {st['id']}{' (set by hand)' if st.get('explicit') else ''}: " + f"{' + '.join(st.get('reactants') or []) or 'nothing'} -> {' + '.join(st.get('products') or []) or 'nothing'}" + + (f" ยท agents {', '.join(st['agents'])}" if st.get("agents") else "") + (f" ยท conditions {', '.join(st['conditions'])}" if st.get("conditions") else "")) + listing.append({"page": p.get("id"), **r}) + if not listing: + lines.append("No reaction arrow has structures before or after it.") + return _ok("\n".join(lines), {"doc": doc_id, "changed": bool(done), "rev": done["rev"] if done else None, "summary": summaries, "reactions": listing}) + + +async def t_map_reaction(a: Agent, args: dict) -> dict: + from app.services.chem import mapping, reactions + doc_id, doc = _drawing(args) + _, reaction, step = _reaction_step(doc, args) + mode = str(args.get("mode") or "discard") + try: + ops, info = await asyncio.to_thread(mapping.map_ops, doc, step, mode) + except reactions.ReactionError as exc: + raise ToolError(str(exc)) from None + done = await _apply(a, doc_id, "Clear mapping" if mode == "clear" else "Map atoms", ops) + if mode == "clear": + text = f"Cleared {info['cleared']} map numbers in step {step['id']}." if done else f"Step {step['id']} had no map numbers." + else: + c = info.get("centres") or {} + text = (f"Mapped step {step['id']} of reaction {reaction['id']}: {info['quality']}, {info['mapped']} map numbers; " + f"{c.get('broken', 0)} bonds broken, {c.get('formed', 0)} formed, {c.get('order', 0)} changed in order." + ("" if done else " The drawing already showed this mapping.")) + return _ok(text, {"doc": doc_id, "reaction": reaction["id"], "step": step["id"], "changed": bool(done), "rev": done["rev"] if done else None, "mapping": info}) + + +async def t_export_reaction(a: Agent, args: dict) -> dict: + from app.services.chem import reactions, rxnio + doc_id, doc = _drawing(args) + _, reaction, step = _reaction_step(doc, args) + fmt = str(args.get("format") or "smiles") + try: + text, warnings = rxnio.export_step(doc, step, fmt, str(doc.get("title") or "")) + except reactions.ReactionError as exc: + raise ToolError(str(exc)) from None + notes = "".join(f"\nNote: {w['text']}" for w in warnings) + return _ok(text + notes, {"doc": doc_id, "reaction": reaction["id"], "step": step["id"], "format": fmt, "text": text, "warnings": warnings}) + + +async def t_reaction_stoichiometry(a: Agent, args: dict) -> dict: + from app.services.chem import balance, stoich + from app.services.store import STORE + doc_id, doc = _drawing(args) + _, reaction, step = _reaction_step(doc, args) + derived = await asyncio.to_thread(STORE.derive_now, doc_id) + view = stoich.compute(doc, reaction, step, derived) + checked = balance.check(doc, step) + lines = [f"Step {step['id']} of reaction {reaction['id']}" + (f", limiting reagent {view['limiting']}" if view["limiting"] else "") + ":"] + for r in view["rows"]: + parts = [r["role"], r["label"], f"MW {r['mw']:.2f}" if r["mw"] else "MW unknown"] + if r.get("equiv"): + parts.append(f"{stoich.sig3(r['equiv'])} equiv") + for value in (stoich.amount_text(r["mmol"]), stoich.mass_text(r["mass_mg"]), stoich.volume_text(r.get("volume_ml"))): + if value: + parts.append(value) + if r.get("yield_pct") is not None: + parts.append(f"yield {r['yield_pct']:.1f}%") + lines.append("- " + " ยท ".join(parts)) + lines.append("Balanced." if checked["balanced"] else "Not balanced.") + lines.extend(f"Note: {w['text']}" for w in view["warnings"] + checked["warnings"]) + return _ok("\n".join(lines), {"doc": doc_id, "stoich": view, "check": checked}) + + async def _send_handoffs(client: Client, msg: dict) -> None: await client.send({"t": "handoffs", "items": _handoff_list()}) From ac58266cdf3732b80388b13246873bb4dde5d0e1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:11:22 -0500 Subject: [PATCH 020/279] chore(agents): sync the tools reference and manifest for the reaction tools (0.5.0) The harness skill's tools reference, its .agents mirror and agents/manifest.json are generated from TOOLS in mcp.py, so they are regenerated with ./formchem agents sync after the four reaction tools were added; the skill validator reports zero FAIL. --- .../formchem-harness/references/tools.md | 47 ++++++++++++++++++- .../formchem-harness/references/tools.md | 47 ++++++++++++++++++- agents/manifest.json | 14 ++++-- 3 files changed, 103 insertions(+), 5 deletions(-) diff --git a/.agents/skills/formchem-harness/references/tools.md b/.agents/skills/formchem-harness/references/tools.md index d73cfc33..8b50525a 100644 --- a/.agents/skills/formchem-harness/references/tools.md +++ b/.agents/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 6 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 10 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -12,6 +12,10 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `extensions_list` | read-only | | `extension_command` | approval-gated | | `handoff` | approval-gated when it changes something | +| `perceive_reactions` | approval-gated | +| `map_reaction` | approval-gated | +| `export_reaction` | read-only | +| `reaction_stoichiometry` | read-only | ## get_context @@ -65,6 +69,47 @@ Tells the person where your work stands: working (still on it), ready (done, for | `state` | working or ready or question or clear | no | | | `note` | string | no | One short line for the person | +## perceive_reactions + +Works out the reaction steps of a drawing from where its structures sit around the reaction arrows (before the tail: reactants, after the head: products, beside the arrow: agents and conditions text; plus signs join) and writes them to the drawing as one undo step. Steps someone set by hand are kept. Returns every reaction with its step ids. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from get_context; may be left out when one drawing is open | +| `page` | string | no | Page id; all pages when left out | + +## map_reaction + +Maps the atoms of one reaction step (reactant atom to product atom numbers) and marks the bonds broken, formed or changed in order, as one undo step. mode discard (default) maps from scratch, keep keeps the numbers already drawn, alter may change them, clear removes the mapping. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | | +| `reaction` | string | no | Reaction id from perceive_reactions; the first reaction when left out | +| `step` | string | no | Step id; the first step when left out | +| `mode` | discard or keep or alter or clear | no | | + +## export_reaction + +One reaction step as reaction SMILES (format smiles) or an RXN file (rxn for V2000, rxnv3000), with its map numbers. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | | +| `reaction` | string | no | | +| `step` | string | no | | +| `format` | smiles or rxn or rxnv3000 | no | | + +## reaction_stoichiometry + +The stoichiometry of one reaction step worked out from the amounts the person typed in its grid and the molecular weights: moles, equivalents, masses, volumes, the limiting reagent, theoretical yields and the percent yield, plus the balance check. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | | +| `reaction` | string | no | | +| `step` | string | no | | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/.claude/skills/formchem-harness/references/tools.md b/.claude/skills/formchem-harness/references/tools.md index d73cfc33..8b50525a 100644 --- a/.claude/skills/formchem-harness/references/tools.md +++ b/.claude/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 6 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 10 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -12,6 +12,10 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `extensions_list` | read-only | | `extension_command` | approval-gated | | `handoff` | approval-gated when it changes something | +| `perceive_reactions` | approval-gated | +| `map_reaction` | approval-gated | +| `export_reaction` | read-only | +| `reaction_stoichiometry` | read-only | ## get_context @@ -65,6 +69,47 @@ Tells the person where your work stands: working (still on it), ready (done, for | `state` | working or ready or question or clear | no | | | `note` | string | no | One short line for the person | +## perceive_reactions + +Works out the reaction steps of a drawing from where its structures sit around the reaction arrows (before the tail: reactants, after the head: products, beside the arrow: agents and conditions text; plus signs join) and writes them to the drawing as one undo step. Steps someone set by hand are kept. Returns every reaction with its step ids. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from get_context; may be left out when one drawing is open | +| `page` | string | no | Page id; all pages when left out | + +## map_reaction + +Maps the atoms of one reaction step (reactant atom to product atom numbers) and marks the bonds broken, formed or changed in order, as one undo step. mode discard (default) maps from scratch, keep keeps the numbers already drawn, alter may change them, clear removes the mapping. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | | +| `reaction` | string | no | Reaction id from perceive_reactions; the first reaction when left out | +| `step` | string | no | Step id; the first step when left out | +| `mode` | discard or keep or alter or clear | no | | + +## export_reaction + +One reaction step as reaction SMILES (format smiles) or an RXN file (rxn for V2000, rxnv3000), with its map numbers. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | | +| `reaction` | string | no | | +| `step` | string | no | | +| `format` | smiles or rxn or rxnv3000 | no | | + +## reaction_stoichiometry + +The stoichiometry of one reaction step worked out from the amounts the person typed in its grid and the molecular weights: moles, equivalents, masses, volumes, the limiting reagent, theoretical yields and the percent yield, plus the balance check. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | | +| `reaction` | string | no | | +| `step` | string | no | | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/agents/manifest.json b/agents/manifest.json index 8a3672a5..1b2fd65b 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -9,17 +9,25 @@ "run_command", "extensions_list", "extension_command", - "handoff" + "handoff", + "perceive_reactions", + "map_reaction", + "export_reaction", + "reaction_stoichiometry" ], "read_only": [ "get_context", "list_commands", - "extensions_list" + "extensions_list", + "export_reaction", + "reaction_stoichiometry" ], "approval_gated": [ "run_command", "extension_command", - "handoff" + "handoff", + "perceive_reactions", + "map_reaction" ], "transports": [ "stdio", From 7d17e4441936bfa5494aded7cba3ebf7c987f18e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:13:06 -0500 Subject: [PATCH 021/279] fix(chem): write Kekule bonds in RXN exports (0.5.0) Reaction templates went into the RXN writer still aromatic, so benzene rings came out as bond type 4, which V2000 reserves for queries; RXN molecules are now kekulised like single molfiles, while reaction SMILES keeps aromatic lower case. --- backend/app/services/chem/rxnio.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/backend/app/services/chem/rxnio.py b/backend/app/services/chem/rxnio.py index f945970b..b7ecbe08 100644 --- a/backend/app/services/chem/rxnio.py +++ b/backend/app/services/chem/rxnio.py @@ -26,7 +26,7 @@ def plain_text(obj: dict | None) -> str: return " ".join("".join(str(r.get("t") or "") for r in obj.get("runs") or [] if isinstance(r, dict)).split()) -def molecule(doc: dict, frag: dict) -> tuple[Chem.Mol, list[dict]]: +def molecule(doc: dict, frag: dict, kekulize: bool = False) -> tuple[Chem.Mol, list[dict]]: mol, notes = io._writable(frag, doc.get("expansions")) bonds = frag.get("bonds") or {} for b in mol.GetBonds(): @@ -36,10 +36,15 @@ def molecule(doc: dict, frag: dict) -> tuple[Chem.Mol, list[dict]]: if status: b.SetIntProp("molReactStatus", status) b.ClearProp(convert.ID_PROP) + if kekulize: + try: + Chem.Kekulize(mol, clearAromaticFlags=True) + except Exception: + notes.append(warning("cannot_kekulise", "Aromatic bonds were written as type 4 because the system cannot be kekulised.")) return mol.GetMol(), notes -def build(doc: dict, step: dict) -> tuple[rdChemReactions.ChemicalReaction, list[dict]]: +def build(doc: dict, step: dict, kekulize: bool = False) -> tuple[rdChemReactions.ChemicalReaction, list[dict]]: rxn = rdChemReactions.ChemicalReaction() notes: list[dict] = [] add = {"reactant": rxn.AddReactantTemplate, "product": rxn.AddProductTemplate, "agent": rxn.AddAgentTemplate} @@ -54,7 +59,7 @@ def build(doc: dict, step: dict) -> tuple[rdChemReactions.ChemicalReaction, list if n != 1: notes.append(warning("coefficient_dropped", f"The coefficient {n:g} of {oid} has no place in the format and is not written.")) for frag in frags: - mol, more = molecule(doc, frag) + mol, more = molecule(doc, frag, kekulize) notes.extend(more) add[role](mol) if not rxn.GetNumReactantTemplates() and not rxn.GetNumProductTemplates(): @@ -73,7 +78,7 @@ def _header(block: str, title: str, comment: str) -> str: def export_step(doc: dict, step: dict, fmt: str, title: str | None = None) -> tuple[str, list[dict]]: if fmt not in FORMATS: raise ReactionError(f"format must be one of {', '.join(FORMATS)}") - rxn, notes = build(doc, step) + rxn, notes = build(doc, step, fmt != "smiles") conditions = "; ".join(t for t in (plain_text((doc.get("objects") or {}).get(c)) for c in step.get("conditions") or []) if t) if fmt == "smiles": if conditions: From d19a2e334bad560ffe71910c4108c185cab2ce71 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:57:45 -0500 Subject: [PATCH 022/279] feat(render): let node specs carry nested children (0.5.0) Gradients, clip paths and other grouped graphics need child elements; the keyed patcher now recurses into them instead of rebuilding. --- frontend/src/canvas/render/svg.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/canvas/render/svg.ts b/frontend/src/canvas/render/svg.ts index 3a94be17..05b9ef65 100644 --- a/frontend/src/canvas/render/svg.ts +++ b/frontend/src/canvas/render/svg.ts @@ -3,7 +3,7 @@ export const SVG_NS = 'http://www.w3.org/2000/svg'; export type Attrs = Record; export interface SpanSpec { a: Attrs; text: string } -export interface NodeSpec { tag: string; a: Attrs; spans?: SpanSpec[] } +export interface NodeSpec { tag: string; a: Attrs; spans?: SpanSpec[]; kids?: NodeSpec[] } export function svgEl(tag: K, attrs?: Attrs): SVGElementTagNameMap[K] { const node = document.createElementNS(SVG_NS, tag); @@ -49,6 +49,7 @@ export function patchChildren(group: Element, specs: readonly NodeSpec[]): void setAttrs(node, spec.a, ATTRS.get(node)); ATTRS.set(node, spec.a); if (spec.spans) patchSpans(node, spec.spans); + else if (spec.kids || node.children.length) patchChildren(node, spec.kids ?? []); i++; } while (group.children.length > i) group.lastChild!.remove(); From 939919ec6304308b3a703da9bd9f9b675e66b517 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:57:54 -0500 Subject: [PATCH 023/279] feat(render): keep lone pair centres on atom views (0.5.0) Electron-pushing arrows anchored to a lone pair start where the pair is drawn, so the atom view now records each pair's centre. --- frontend/src/canvas/render/atom.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/src/canvas/render/atom.ts b/frontend/src/canvas/render/atom.ts index f6c99780..095b30f2 100644 --- a/frontend/src/canvas/render/atom.ts +++ b/frontend/src/canvas/render/atom.ts @@ -9,6 +9,7 @@ export interface AtomView { box: Box | null; clip: Box[]; labelled: boolean; + pairs: V[]; } const CPK: Readonly> = { @@ -112,11 +113,13 @@ export function atomView(atom: Atom, nbrs: readonly Neighbour[], style: Style, h } const pairs = Math.min(4, atom.lone_pairs ?? 0); + const pairAt: V[] = []; for (let i = 0; i < pairs; i++) { const angle = !nbrs.length && !taken.length ? [Math.PI / 2, 0, -Math.PI / 2, Math.PI][i] : freeAngles(atom, nbrs, taken)[0]; taken.push(angle); const d = dirOf(angle); const c = reach(angle, 0.33 * L); + pairAt.push(c); if (style.lone_pair === 'bar') { const half = 1.4; specs.push({ tag: 'line', a: { x1: fmt(c[0] - d[1] * half), y1: fmt(c[1] + d[0] * half), x2: fmt(c[0] + d[1] * half), y2: fmt(c[1] - d[0] * half), stroke: colour, 'stroke-width': fmt(style.line_width), class: 'fc-ln fc-mark' } }); @@ -133,5 +136,5 @@ export function atomView(atom: Atom, nbrs: readonly Neighbour[], style: Style, h specs.push({ tag: 'text', a: textAttrs({ 'text-anchor': 'middle', class: 'fc-label fc-map' }), spans: [{ a: { x: fmt(p[0]), y: fmt(p[1] + cap / 2), 'font-size': fmt(size) }, text: String(atom.map) }] }); } - return { specs, box, clip, labelled: !!model }; + return { specs, box, clip, labelled: !!model, pairs: pairAt }; } From 8c7bc044ae84fa8dac0aaa511eeed1b275a85778 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:58:27 -0500 Subject: [PATCH 024/279] feat(render): add the object kind registry and paint helpers (0.5.0) Every non-chemistry kind gets its own view module; the registry lets the renderer, bounds and hit testing dispatch by kind, and the paint helpers share stroke, dash, fill, rotation and label rules. --- frontend/src/canvas/render/objects.ts | 76 +++++++++++++++++++++++++ frontend/src/canvas/render/paint.ts | 80 +++++++++++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 frontend/src/canvas/render/objects.ts create mode 100644 frontend/src/canvas/render/paint.ts diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts new file mode 100644 index 00000000..b3ca6e8c --- /dev/null +++ b/frontend/src/canvas/render/objects.ts @@ -0,0 +1,76 @@ +import type { Derived, DocObject, FormChemDocument, Id, ObjectKind, Style } from '../../engine/model'; +import { isFragment, resolveStyle } from '../../engine/model'; +import type { Box, V } from './geom'; +import type { NodeSpec } from './svg'; + +export interface ChemGeometry { + atomPos(frag: Id, atom: Id): V | null; + lonePair(frag: Id, atom: Id, index: number): V | null; + bondLength(frag: Id): number; +} + +export interface MediaRef { href: string | null; failed: boolean } + +export interface ObjectCtx { + doc: FormChemDocument; + style: Style; + colour: string; + chem: ChemGeometry; + derived: Derived | null; + boxOf(id: Id): Box | null; + media(id: Id): MediaRef; +} + +export interface ObjectView { specs: NodeSpec[]; box: Box | null } + +export type ObjectOf = Extract; + +export interface ObjectKindDef { + view(obj: ObjectOf, ctx: ObjectCtx): ObjectView; + deps?(obj: ObjectOf, doc: FormChemDocument): unknown[]; +} + +type Registry = { [K in ObjectKind]?: ObjectKindDef }; + +export const OBJECT_KINDS: Registry = {}; + +export function kindDef(kind: string): ObjectKindDef | undefined { + return (OBJECT_KINDS as Record | undefined>)[kind]; +} + +export function objectView(obj: DocObject, ctx: ObjectCtx): ObjectView | null { + const def = kindDef(obj.kind); + return def ? def.view(obj as never, ctx) : null; +} + +export function objectDeps(obj: DocObject, doc: FormChemDocument): unknown[] { + return kindDef(obj.kind)?.deps?.(obj as never, doc) ?? []; +} + +export function docChem(doc: FormChemDocument): ChemGeometry { + return { + atomPos(f, a) { + const frag = doc.objects[f]; + const atom = isFragment(frag) ? frag.atoms[a] : undefined; + return atom ? [atom.x, atom.y] : null; + }, + lonePair: () => null, + bondLength(f) { + const frag = doc.objects[f]; + return frag ? resolveStyle(doc, frag).bond_length : resolveStyle(doc).bond_length; + }, + }; +} + +export function docCtx(doc: FormChemDocument, obj: DocObject, boxOf: (id: Id) => Box | null = () => null): ObjectCtx { + const style = resolveStyle(doc, obj); + return { + doc, + style, + colour: obj.color ?? style.foreground, + chem: docChem(doc), + derived: null, + boxOf, + media: () => ({ href: null, failed: false }), + }; +} diff --git a/frontend/src/canvas/render/paint.ts b/frontend/src/canvas/render/paint.ts new file mode 100644 index 00000000..24e1d788 --- /dev/null +++ b/frontend/src/canvas/render/paint.ts @@ -0,0 +1,80 @@ +import type { Dash, Font, ShapeFill, Stroke } from '../../engine/model'; +import { fmt } from './geom'; +import { cssFamily, measure } from './measure'; +import type { Attrs, NodeSpec } from './svg'; + +export function dashArray(dash: Dash | undefined, width: number): string | null { + const w = Math.max(width, 0.3); + switch (dash) { + case 'dash': + return `${fmt(6 * w)} ${fmt(3 * w)}`; + case 'dot': + return `${fmt(0.01)} ${fmt(2.5 * w)}`; + case 'dash_dot': + return `${fmt(6 * w)} ${fmt(2.5 * w)} ${fmt(0.01)} ${fmt(2.5 * w)}`; + default: + return null; + } +} + +export function strokeAttrs(stroke: Stroke | null | undefined, colour: string, lineWidth: number): Attrs { + if (stroke === null) return { stroke: 'none' }; + const w = stroke?.width ?? lineWidth; + const a: Attrs = { stroke: stroke?.color ?? colour, 'stroke-width': fmt(w), class: 'fc-ln' }; + const d = dashArray(stroke?.dash, w); + if (d) { + a['stroke-dasharray'] = d; + if (stroke?.dash === 'dot' || stroke?.dash === 'dash_dot') a['stroke-linecap'] = 'round'; + } + return a; +} + +export interface Paint { a: Attrs; defs: NodeSpec[] } + +export function fillPaint(fill: ShapeFill | undefined, gradientId: string): Paint { + if (!fill) return { a: { fill: 'none' }, defs: [] }; + if (fill.type === 'solid') return { a: { fill: fill.color }, defs: [] }; + const rad = ((fill.angle ?? 0) * Math.PI) / 180; + const dx = Math.cos(rad) / 2, dy = -Math.sin(rad) / 2; + const stops: NodeSpec[] = [...fill.stops] + .sort((p, q) => p.pos - q.pos) + .map((s) => ({ tag: 'stop', a: { offset: fmt(Math.min(1, Math.max(0, s.pos))), 'stop-color': s.color } })); + const grad: NodeSpec = { + tag: 'linearGradient', + a: { id: gradientId, x1: fmt(0.5 - dx), y1: fmt(0.5 - dy), x2: fmt(0.5 + dx), y2: fmt(0.5 + dy) }, + kids: stops, + }; + return { a: { fill: `url(#${gradientId})` }, defs: [grad] }; +} + +export function rotation(rot: number | undefined, cx: number, cy: number): string | null { + return rot ? `rotate(${fmt(-rot)} ${fmt(cx)} ${fmt(cy)})` : null; +} + +export function withRotation(specs: NodeSpec[], rot: number | undefined, cx: number, cy: number): NodeSpec[] { + const tf = rotation(rot, cx, cy); + if (!tf) return specs; + return [{ tag: 'g', a: { transform: tf }, kids: specs }]; +} + +export function rotatedBox(x: number, y: number, w: number, h: number, rot: number | undefined): { x: number; y: number; w: number; h: number } { + if (!rot) return { x, y, w, h }; + const r = (rot * Math.PI) / 180; + const c = Math.abs(Math.cos(r)), s = Math.abs(Math.sin(r)); + const W = w * c + h * s, H = w * s + h * c; + return { x: x + w / 2 - W / 2, y: y + h / 2 - H / 2, w: W, h: H }; +} + +export interface Label { text: string; x: number; y: number; w: number; h: number; spec: NodeSpec } + +export function label(text: string, at: readonly [number, number], font: Font, size: number, colour: string, anchor: 'start' | 'middle' | 'end' = 'start', opts: { bold?: boolean; italic?: boolean; cls?: string } = {}): Label { + const bold = opts.bold ?? !!font.bold, italic = opts.italic ?? !!font.italic; + const w = measure.width(text, size, font.family, bold, italic); + const face = measure.face(font.family, bold, italic); + const x = anchor === 'middle' ? at[0] - w / 2 : anchor === 'end' ? at[0] - w : at[0]; + const a: Attrs = { class: opts.cls ?? 'fc-text', x: fmt(at[0]), y: fmt(at[1]), 'font-family': cssFamily(font.family), 'font-size': fmt(size), fill: colour }; + if (anchor !== 'start') a['text-anchor'] = anchor; + if (bold) a['font-weight'] = 'bold'; + if (italic) a['font-style'] = 'italic'; + return { text, x, y: at[1] - face.ascent * size, w, h: (face.ascent + face.descent) * size, spec: { tag: 'text', a, spans: [{ a: {}, text }] } }; +} From 84cbad8631c7df8e50150acab3a5649af9879231 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:59:24 -0500 Subject: [PATCH 025/279] feat(render): resolve arrow anchors to atoms, bonds, lone pairs and forming bonds (0.5.0) Anchored arrow ends follow the chemistry as drawn and stop 0.15 bond lengths short, as FORMAT.md and spec A 6.3 require. --- frontend/src/canvas/render/anchors.ts | 65 +++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 frontend/src/canvas/render/anchors.ts diff --git a/frontend/src/canvas/render/anchors.ts b/frontend/src/canvas/render/anchors.ts new file mode 100644 index 00000000..b37b18b3 --- /dev/null +++ b/frontend/src/canvas/render/anchors.ts @@ -0,0 +1,65 @@ +import type { Anchor, ArrowObject, FormChemDocument, Fragment, Id } from '../../engine/model'; +import { isFragment } from '../../engine/model'; +import { add, dirOf, mid, mul, unit, type V } from './geom'; +import type { ChemGeometry } from './objects'; + +export const ANCHOR_GAP = 0.15; + +function fallbackPair(frag: Fragment, atom: Id, at: V, index: number, L: number): V { + let sx = 0, sy = 0; + for (const b of Object.values(frag.bonds)) { + const other = b.a === atom ? b.b : b.b === atom ? b.a : null; + const o = other ? frag.atoms[other] : undefined; + if (!o) continue; + const d = unit([o.x - at[0], o.y - at[1]]); + sx += d[0]; + sy += d[1]; + } + const away = Math.hypot(sx, sy) > 1e-6 ? Math.atan2(sy, -sx) : Math.PI / 2; + const turn = [0, 1, -1, 2][index % 4] * (Math.PI / 2.5); + return add(at, mul(dirOf(away + turn), 0.33 * L)); +} + +export function anchorPoint(anchor: Anchor, doc: FormChemDocument, chem: ChemGeometry): V | null { + const frag = doc.objects[anchor.object]; + if (!isFragment(frag)) return null; + const pos = (a: Id): V | null => chem.atomPos(anchor.object, a); + if ('bond' in anchor) { + const b = frag.bonds[anchor.bond]; + const p = b ? pos(b.a) : null, q = b ? pos(b.b) : null; + return p && q ? mid(p, q) : null; + } + if ('between' in anchor) { + const p = pos(anchor.between[0]), q = pos(anchor.between[1]); + return p && q ? mid(p, q) : null; + } + const p = pos(anchor.atom); + if (!p) return null; + if (anchor.lone_pair === undefined) return p; + return chem.lonePair(anchor.object, anchor.atom, anchor.lone_pair) ?? fallbackPair(frag, anchor.atom, p, anchor.lone_pair, chem.bondLength(anchor.object)); +} + +export interface ArrowEnds { tail: V; head: V; trimTail: number; trimHead: number } + +export function arrowEnds(obj: ArrowObject, doc: FormChemDocument, chem: ChemGeometry): ArrowEnds { + let tail: V = [obj.x1, obj.y1], head: V = [obj.x2, obj.y2]; + let trimTail = 0, trimHead = 0; + const t = obj.anchors?.tail, h = obj.anchors?.head; + const tp = t ? anchorPoint(t, doc, chem) : null; + const hp = h ? anchorPoint(h, doc, chem) : null; + if (t && tp) { + tail = tp; + trimTail = ANCHOR_GAP * chem.bondLength(t.object); + } + if (h && hp) { + head = hp; + trimHead = ANCHOR_GAP * chem.bondLength(h.object); + } + return { tail, head, trimTail, trimHead }; +} + +export function anchorDeps(obj: ArrowObject, doc: FormChemDocument): unknown[] { + const out: unknown[] = []; + for (const a of [obj.anchors?.tail, obj.anchors?.head]) if (a) out.push(doc.objects[a.object]); + return out; +} From c229b9ba5922aec77ea917550d459144b7ac6697 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:00:22 -0500 Subject: [PATCH 026/279] feat(render): draw arrows of every type with full, half, open and hollow heads (0.5.0) Straight and arced shafts share one curve model, so equilibrium pairs, retro shafts, no-go marks and anchored electron-pushing arrows all bend and trim the same way. --- frontend/src/canvas/render/arrow.ts | 271 ++++++++++++++++++++++++++ frontend/src/canvas/render/objects.ts | 5 +- 2 files changed, 275 insertions(+), 1 deletion(-) create mode 100644 frontend/src/canvas/render/arrow.ts diff --git a/frontend/src/canvas/render/arrow.ts b/frontend/src/canvas/render/arrow.ts new file mode 100644 index 00000000..2ff1dfdb --- /dev/null +++ b/frontend/src/canvas/render/arrow.ts @@ -0,0 +1,271 @@ +import type { ArrowHead, ArrowObject, ArrowType, FormChemDocument, Style } from '../../engine/model'; +import { bondSpacing } from '../../engine/model'; +import { anchorDeps, arrowEnds } from './anchors'; +import { add, dist, fmt, left, lerp, mul, pts, sub, unit, type Box, type V } from './geom'; +import type { ChemGeometry, ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import type { Attrs, NodeSpec } from './svg'; + +export type Curve = + | { kind: 'line'; a: V; b: V } + | { kind: 'arc'; c: V; r: number; a0: number; sweep: number }; + +export function curveLength(k: Curve): number { + return k.kind === 'line' ? dist(k.a, k.b) : k.r * Math.abs(k.sweep); +} + +export function curvePoint(k: Curve, s: number): V { + if (k.kind === 'line') { + const l = dist(k.a, k.b); + return l > 1e-9 ? lerp(k.a, k.b, s / l) : k.a; + } + const t = k.a0 + Math.sign(k.sweep) * (s / k.r); + return [k.c[0] + k.r * Math.cos(t), k.c[1] + k.r * Math.sin(t)]; +} + +export function subCurve(k: Curve, s0: number, s1: number): Curve { + if (k.kind === 'line') return { kind: 'line', a: curvePoint(k, s0), b: curvePoint(k, s1) }; + const sg = Math.sign(k.sweep); + return { kind: 'arc', c: k.c, r: k.r, a0: k.a0 + (sg * s0) / k.r, sweep: (sg * (s1 - s0)) / k.r }; +} + +export function offsetCurve(k: Curve, o: number): Curve { + if (k.kind === 'line') { + const n = mul(left(unit(sub(k.b, k.a))), o); + return { kind: 'line', a: add(k.a, n), b: add(k.b, n) }; + } + return { ...k, r: Math.max(0.1, k.r + o * Math.sign(k.sweep)) }; +} + +export function reverseCurve(k: Curve): Curve { + return k.kind === 'line' ? { kind: 'line', a: k.b, b: k.a } : { ...k, a0: k.a0 + k.sweep, sweep: -k.sweep }; +} + +export function curvePath(k: Curve): string { + const a = curvePoint(k, 0); + if (k.kind === 'line') return `M${fmt(a[0])} ${fmt(a[1])}L${fmt(k.b[0])} ${fmt(k.b[1])}`; + const b = curvePoint(k, curveLength(k)); + const large = Math.abs(k.sweep) > Math.PI ? 1 : 0; + return `M${fmt(a[0])} ${fmt(a[1])}A${fmt(k.r)} ${fmt(k.r)} 0 ${large} ${k.sweep > 0 ? 1 : 0} ${fmt(b[0])} ${fmt(b[1])}`; +} + +export function curveSamples(k: Curve, n = 24): V[] { + if (k.kind === 'line') return [k.a, k.b]; + const l = curveLength(k); + const out: V[] = []; + for (let i = 0; i <= n; i++) out.push(curvePoint(k, (l * i) / n)); + return out; +} + +export function bentCurve(a: V, b: V, bendDeg: number): Curve { + const chord = dist(a, b); + const th = Math.min(Math.abs(bendDeg), 359) * (Math.PI / 180); + if (chord < 1e-6 || th < 1e-3) return { kind: 'line', a, b }; + const s = Math.sign(bendDeg); + const r = chord / (2 * Math.sin(th / 2)); + const n = left(unit(sub(b, a))); + const m = lerp(a, b, 0.5); + const c = sub(m, mul(n, s * r * Math.cos(th / 2))); + const a0 = Math.atan2(a[1] - c[1], a[0] - c[0]); + const end = (sw: number): V => [c[0] + r * Math.cos(a0 + sw), c[1] + r * Math.sin(a0 + sw)]; + const sweep = dist(end(th), b) <= dist(end(-th), b) ? th : -th; + return { kind: 'arc', c, r, a0, sweep }; +} + +export interface ArrowShape { + shafts: { curve: Curve; dashed: boolean }[]; + strokes: V[][]; + fills: V[][]; + outlines: V[][]; + lw: number; +} + +interface Defaults { head: ArrowHead; tail: ArrowHead } + +const DEFAULTS: Record = { + forward: { head: 'full', tail: 'none' }, + equilibrium: { head: 'half_left', tail: 'half_left' }, + equilibrium_unbalanced: { head: 'half_left', tail: 'half_left' }, + reversible: { head: 'full', tail: 'full' }, + resonance: { head: 'full', tail: 'full' }, + retro: { head: 'open', tail: 'none' }, + nogo_cross: { head: 'full', tail: 'none' }, + nogo_slash: { head: 'full', tail: 'none' }, + dashed: { head: 'full', tail: 'none' }, + curved: { head: 'full', tail: 'none' }, + fishhook: { head: 'half_left', tail: 'none' }, + arc: { head: 'full', tail: 'none' }, + plain: { head: 'none', tail: 'none' }, + fragmentation: { head: 'full', tail: 'none' }, + dissociation: { head: 'full', tail: 'none' }, +}; + +const rotate = (d: V, deg: number): V => { + const r = (deg * Math.PI) / 180, c = Math.cos(r), s = Math.sin(r); + return [d[0] * c + d[1] * s, -d[0] * s + d[1] * c]; +}; + +function bendOf(obj: ArrowObject): number { + const b = obj.bend ?? 0; + if (obj.type !== 'arc') return b; + if (!b) return 180; + return Math.sign(b) * Math.min(345, Math.max(15, Math.abs(b))); +} + +interface HeadDims { hl: number; hw: number } + +function head(shape: ArrowShape, k: Curve, atEnd: boolean, kind: ArrowHead, d: HeadDims): number { + if (kind === 'none') return 0; + const l = curveLength(k); + const back = Math.min(d.hl, l); + const tip = curvePoint(k, atEnd ? l : 0); + const behind = curvePoint(k, atEnd ? l - back : back); + const u = unit(sub(tip, behind)); + const n = left(u); + const base = sub(tip, mul(u, d.hl)); + const notch = sub(tip, mul(u, 0.75 * d.hl)); + const l1 = add(base, mul(n, d.hw)), r1 = sub(base, mul(n, d.hw)); + switch (kind) { + case 'full': + shape.fills.push([tip, l1, notch, r1]); + return 0.7 * d.hl; + case 'half_left': + shape.fills.push([tip, l1, notch]); + return 0; + case 'half_right': + shape.fills.push([tip, r1, notch]); + return 0; + case 'open': + shape.strokes.push([l1, tip, r1]); + return 0; + case 'hollow': + shape.outlines.push([tip, l1, r1]); + return d.hl; + } +} + +function single(shape: ArrowShape, k: Curve, h: ArrowHead, t: ArrowHead, d: HeadDims, dashed: boolean): void { + const l = curveLength(k); + const ch = head(shape, k, true, h, d); + const ct = head(shape, k, false, t, d); + if (l - ch - ct > 0.01) shape.shafts.push({ curve: subCurve(k, ct, l - ch), dashed }); +} + +function retro(shape: ArrowShape, k: Curve, g: number, obj: ArrowObject): void { + const W = obj.head_width ?? g; + const Lc = obj.head_length ?? 1.6 * W; + const l = curveLength(k); + const tip = curvePoint(k, l); + const u = unit(sub(tip, curvePoint(k, Math.max(0, l - Lc)))); + const n = left(u); + const base = sub(tip, mul(u, Lc)); + shape.strokes.push([add(base, mul(n, W)), tip, sub(base, mul(n, W))]); + const back = (Lc * (g / 2)) / Math.max(W, 1e-6); + for (const o of [g / 2, -g / 2]) { + const side = offsetCurve(k, o); + shape.shafts.push({ curve: subCurve(side, 0, Math.max(0, curveLength(side) - back)), dashed: !!obj.dashed }); + } +} + +export function arrowShape(obj: ArrowObject, doc: FormChemDocument, style: Style, chem: ChemGeometry): ArrowShape { + const lw = obj.line_width ?? style.line_width; + const shape: ArrowShape = { shafts: [], strokes: [], fills: [], outlines: [], lw }; + const ends = arrowEnds(obj, doc, chem); + let k = bentCurve(ends.tail, ends.head, bendOf(obj)); + const full = curveLength(k); + if (full < 1e-6) return shape; + if (ends.trimTail || ends.trimHead) { + const s0 = Math.min(ends.trimTail, full * 0.4), s1 = full - Math.min(ends.trimHead, full * 0.4); + k = subCurve(k, s0, s1); + } + const l = curveLength(k); + const def = DEFAULTS[obj.type] ?? DEFAULTS.forward; + const h = obj.head ?? def.head, t = obj.tail ?? def.tail; + const d: HeadDims = { hl: obj.head_length ?? 6 * lw, hw: obj.head_width ?? 2.5 * lw }; + const dashed = !!obj.dashed || obj.type === 'dashed'; + const L = style.bond_length; + const g = bondSpacing(style); + switch (obj.type) { + case 'equilibrium': + case 'equilibrium_unbalanced': + case 'reversible': { + const upper = offsetCurve(k, g / 2); + let lower = reverseCurve(offsetCurve(k, -g / 2)); + if (obj.type === 'equilibrium_unbalanced') { + const f = Math.min(1, Math.max(0.1, obj.shorter ?? 0.6)); + const ll = curveLength(lower); + lower = subCurve(lower, (ll * (1 - f)) / 2, (ll * (1 + f)) / 2); + } + single(shape, upper, h, 'none', d, dashed); + single(shape, lower, t, 'none', d, dashed); + break; + } + case 'retro': + retro(shape, k, Math.max(g, 2.5 * lw), obj); + break; + case 'fragmentation': { + shape.shafts.push({ curve: k, dashed }); + const end = curvePoint(k, l); + const n = left(unit(sub(end, curvePoint(k, Math.max(0, l - Math.min(l, d.hl)))))); + const arm: Curve = { kind: 'line', a: end, b: add(end, mul(n, Math.max(0.35 * l, 2.5 * d.hl))) }; + single(shape, arm, h, 'none', d, false); + break; + } + default: { + single(shape, k, h, t, d, dashed); + const m = curvePoint(k, l / 2); + const u = unit(sub(curvePoint(k, Math.min(l, l / 2 + 0.5)), curvePoint(k, Math.max(0, l / 2 - 0.5)))); + const half = Math.max(0.18 * L, 2 * d.hw); + if (obj.type === 'nogo_cross') { + for (const deg of [45, -45]) { + const v = rotate(u, deg); + shape.strokes.push([sub(m, mul(v, half)), add(m, mul(v, half))]); + } + } else if (obj.type === 'nogo_slash') { + const v = rotate(u, 60); + shape.strokes.push([sub(m, mul(v, half)), add(m, mul(v, half))]); + } else if (obj.type === 'dissociation') { + const a = curvePoint(k, 0); + const n = left(unit(sub(curvePoint(k, Math.min(l, 1)), a))); + shape.strokes.push([add(a, mul(n, 1.6 * d.hw)), sub(a, mul(n, 1.6 * d.hw))]); + } + } + } + return shape; +} + +export function shapePoints(shape: ArrowShape): V[] { + const out: V[] = []; + for (const s of shape.shafts) out.push(...curveSamples(s.curve)); + for (const list of [shape.strokes, shape.fills, shape.outlines]) for (const p of list) out.push(...p); + return out; +} + +export function shapeBox(shape: ArrowShape): Box | null { + const ps = shapePoints(shape); + if (!ps.length) return null; + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const [x, y] of ps) { + x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); + } + const m = shape.lw / 2; + return { x: x0 - m, y: y0 - m, w: x1 - x0 + 2 * m, h: y1 - y0 + 2 * m }; +} + +function arrowView(obj: ArrowObject, ctx: ObjectCtx): ObjectView { + const shape = arrowShape(obj, ctx.doc, ctx.style, ctx.chem); + const c = ctx.colour, w = fmt(shape.lw); + const line = (extra: Attrs): Attrs => ({ fill: 'none', stroke: c, 'stroke-width': w, class: 'fc-ln', ...extra }); + const specs: NodeSpec[] = []; + const dash = `${fmt(1.2 * ctx.style.hash_spacing)} ${fmt(0.8 * ctx.style.hash_spacing)}`; + for (const s of shape.shafts) { + const a = line({ d: curvePath(s.curve), 'stroke-linecap': 'butt' }); + if (s.dashed) a['stroke-dasharray'] = dash; + specs.push({ tag: 'path', a }); + } + for (const p of shape.strokes) specs.push({ tag: 'polyline', a: line({ points: pts(p), 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' }) }); + for (const p of shape.outlines) specs.push({ tag: 'polygon', a: line({ points: pts(p), 'stroke-linejoin': 'miter' }) }); + for (const p of shape.fills) specs.push({ tag: 'polygon', a: { points: pts(p), fill: c, stroke: 'none', class: 'fc-head' } }); + return { specs, box: shapeBox(shape) }; +} + +export const arrowKind: ObjectKindDef<'arrow'> = { view: arrowView, deps: anchorDeps }; diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index b3ca6e8c..80648318 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -1,5 +1,6 @@ import type { Derived, DocObject, FormChemDocument, Id, ObjectKind, Style } from '../../engine/model'; import { isFragment, resolveStyle } from '../../engine/model'; +import { arrowKind } from './arrow'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -32,7 +33,9 @@ export interface ObjectKindDef { type Registry = { [K in ObjectKind]?: ObjectKindDef }; -export const OBJECT_KINDS: Registry = {}; +export const OBJECT_KINDS: Registry = { + arrow: arrowKind, +}; export function kindDef(kind: string): ObjectKindDef | undefined { return (OBJECT_KINDS as Record | undefined>)[kind]; From 8be6b66489cb6f7896c5435c754eeda13e692713 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:00:33 -0500 Subject: [PATCH 027/279] feat(render): draw plus, equals, dot and bullet symbols (0.5.0) Reaction symbols are stroked crosses and bars at 0.6 bond lengths in the style's line width, with filled dots for adducts and salts. --- frontend/src/canvas/render/objects.ts | 2 ++ frontend/src/canvas/render/plus.ts | 32 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 frontend/src/canvas/render/plus.ts diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index 80648318..105870e9 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -1,6 +1,7 @@ import type { Derived, DocObject, FormChemDocument, Id, ObjectKind, Style } from '../../engine/model'; import { isFragment, resolveStyle } from '../../engine/model'; import { arrowKind } from './arrow'; +import { plusKind } from './plus'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -35,6 +36,7 @@ type Registry = { [K in ObjectKind]?: ObjectKindDef }; export const OBJECT_KINDS: Registry = { arrow: arrowKind, + plus: plusKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { diff --git a/frontend/src/canvas/render/plus.ts b/frontend/src/canvas/render/plus.ts new file mode 100644 index 00000000..2dc2efa6 --- /dev/null +++ b/frontend/src/canvas/render/plus.ts @@ -0,0 +1,32 @@ +import type { PlusObject } from '../../engine/model'; +import { fmt } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import type { NodeSpec } from './svg'; + +export const plusSize = (obj: PlusObject, bondLength: number): number => obj.size ?? 0.6 * bondLength; + +function plusView(obj: PlusObject, ctx: ObjectCtx): ObjectView { + const s = plusSize(obj, ctx.style.bond_length); + const h = s / 2, lw = ctx.style.line_width, c = ctx.colour; + const { x, y } = obj; + const bar = (x1: number, y1: number, x2: number, y2: number): NodeSpec => ({ + tag: 'line', + a: { x1: fmt(x1), y1: fmt(y1), x2: fmt(x2), y2: fmt(y2), stroke: c, 'stroke-width': fmt(lw), 'stroke-linecap': 'butt', class: 'fc-ln' }, + }); + const dot = (r: number): NodeSpec => ({ tag: 'circle', a: { cx: fmt(x), cy: fmt(y), r: fmt(r), fill: c, stroke: 'none' } }); + const box = { x: x - h, y: y - h, w: s, h: s }; + switch (obj.symbol ?? 'plus') { + case 'equals': { + const g = s * 0.18; + return { specs: [bar(x - h, y - g, x + h, y - g), bar(x - h, y + g, x + h, y + g)], box }; + } + case 'dot': + return { specs: [dot(Math.max(lw, s * 0.08))], box }; + case 'bullet': + return { specs: [dot(Math.max(1.5 * lw, s * 0.18))], box }; + default: + return { specs: [bar(x - h, y, x + h, y), bar(x, y - h, x, y + h)], box }; + } +} + +export const plusKind: ObjectKindDef<'plus'> = { view: plusView }; From c12db426f3a5df8bcf0fd6a91bd46b6f6582ceca Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:09 -0500 Subject: [PATCH 028/279] feat(render): draw square, round and curly brackets with repeat and charge labels (0.5.0) Polymer and complex brackets show their count or semantic tag at the lower right and charge or connectivity at the upper right, rotated with the bracket. --- frontend/src/canvas/render/bracket.ts | 70 +++++++++++++++++++++++++++ frontend/src/canvas/render/objects.ts | 2 + frontend/src/canvas/render/paint.ts | 19 +++++--- 3 files changed, 85 insertions(+), 6 deletions(-) create mode 100644 frontend/src/canvas/render/bracket.ts diff --git a/frontend/src/canvas/render/bracket.ts b/frontend/src/canvas/render/bracket.ts new file mode 100644 index 00000000..0e01df14 --- /dev/null +++ b/frontend/src/canvas/render/bracket.ts @@ -0,0 +1,70 @@ +import type { BracketObject, BracketSemantic } from '../../engine/model'; +import { fmt, union, type Box } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { label, rotatedBox, withRotation } from './paint'; +import type { NodeSpec } from './svg'; + +const SEMANTIC_TEXT: Partial> = { + sru: 'n', copolymer: 'co', alt: 'alt', ran: 'ran', blk: 'blk', mon: 'mon', mer: 'mer', + xl: 'xl', grf: 'grf', mod: 'mod', mix: 'mix', f: 'f', c: 'c', +}; + +export function bracketLabel(obj: BracketObject): string | null { + if (obj.label) return obj.label; + if (obj.semantic === 'multiple' && obj.repeat) return String(obj.repeat); + return obj.semantic ? SEMANTIC_TEXT[obj.semantic] ?? null : null; +} + +type Cmd = [string, ...number[]]; + +function side(obj: BracketObject, t: number, mirror: boolean): string { + const { x, y, h } = obj; + const cx = obj.x + obj.w / 2; + const fx = (X: number): number => (mirror ? 2 * cx - X : X); + let cmds: Cmd[]; + if (obj.shape === 'round') { + const xc = x - t / 3, a = 0.15 * h; + cmds = [['M', x + t, y], ['C', xc, y + a, xc, y + h - a, x + t, y + h]]; + } else if (obj.shape === 'curly') { + const q = Math.min(t, h / 4), xm = x + t / 2, ym = y + h / 2; + cmds = [ + ['M', x + t, y], ['Q', xm, y, xm, y + q], ['L', xm, ym - q], ['Q', xm, ym, x, ym], + ['Q', xm, ym, xm, ym + q], ['L', xm, y + h - q], ['Q', xm, y + h, x + t, y + h], + ]; + } else { + cmds = [['M', x + t, y], ['L', x, y], ['L', x, y + h], ['L', x + t, y + h]]; + } + return cmds.map(([op, ...n]) => op + n.map((v, i) => fmt(i % 2 ? v : fx(v))).join(' ')).join(''); +} + +function bracketView(obj: BracketObject, ctx: ObjectCtx): ObjectView { + const { x, y, w, h } = obj; + const L = ctx.style.bond_length; + const t = Math.max(0.5, Math.min(Math.max(0.12 * h, 0.15 * L), w / 3)); + const c = ctx.colour; + const a = { fill: 'none', stroke: c, 'stroke-width': fmt(ctx.style.line_width), 'stroke-linejoin': 'miter', 'stroke-linecap': 'butt', class: 'fc-ln' }; + const sides = obj.sides ?? 'both'; + const specs: NodeSpec[] = []; + if (sides !== 'right') specs.push({ tag: 'path', a: { ...a, d: side(obj, t, false) } }); + if (sides !== 'left') specs.push({ tag: 'path', a: { ...a, d: side(obj, t, true) } }); + const boxes: Box[] = [{ x: x - (obj.shape === 'curly' ? 0 : 0.1 * t), y, w: w + (obj.shape === 'curly' ? 0 : 0.2 * t), h }]; + const font = ctx.style.caption_font; + const size = font.size * 0.85; + const lower = bracketLabel(obj); + if (lower) { + const lab = label(lower, [x + w + 1.2, y + h + size * 0.3], font, size, c, 'start', { italic: /^[a-z]$/.test(lower) || undefined }); + specs.push(lab.spec); + boxes.push(lab); + } + const upper = [obj.charge_label, obj.connect && obj.connect !== 'ht' ? obj.connect : null].filter((s): s is string => !!s).join(' '); + if (upper) { + const lab = label(upper, [x + w + 1.2, y + size * 0.35], font, size, c); + specs.push(lab.spec); + boxes.push(lab); + } + const all = union(boxes)!; + const out = withRotation(specs, obj.rot, x + w / 2, y + h / 2); + return { specs: out, box: rotatedBox(all, obj.rot, x + w / 2, y + h / 2) }; +} + +export const bracketKind: ObjectKindDef<'bracket'> = { view: bracketView }; diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index 105870e9..a2eb4255 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -2,6 +2,7 @@ import type { Derived, DocObject, FormChemDocument, Id, ObjectKind, Style } from import { isFragment, resolveStyle } from '../../engine/model'; import { arrowKind } from './arrow'; import { plusKind } from './plus'; +import { bracketKind } from './bracket'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -37,6 +38,7 @@ type Registry = { [K in ObjectKind]?: ObjectKindDef }; export const OBJECT_KINDS: Registry = { arrow: arrowKind, plus: plusKind, + bracket: bracketKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { diff --git a/frontend/src/canvas/render/paint.ts b/frontend/src/canvas/render/paint.ts index 24e1d788..cbb153ea 100644 --- a/frontend/src/canvas/render/paint.ts +++ b/frontend/src/canvas/render/paint.ts @@ -57,12 +57,19 @@ export function withRotation(specs: NodeSpec[], rot: number | undefined, cx: num return [{ tag: 'g', a: { transform: tf }, kids: specs }]; } -export function rotatedBox(x: number, y: number, w: number, h: number, rot: number | undefined): { x: number; y: number; w: number; h: number } { - if (!rot) return { x, y, w, h }; - const r = (rot * Math.PI) / 180; - const c = Math.abs(Math.cos(r)), s = Math.abs(Math.sin(r)); - const W = w * c + h * s, H = w * s + h * c; - return { x: x + w / 2 - W / 2, y: y + h / 2 - H / 2, w: W, h: H }; +export function rotatePoint(p: readonly [number, number], rot: number | undefined, cx: number, cy: number): [number, number] { + if (!rot) return [p[0], p[1]]; + const r = (rot * Math.PI) / 180, c = Math.cos(r), s = Math.sin(r); + const dx = p[0] - cx, dy = p[1] - cy; + return [cx + dx * c + dy * s, cy - dx * s + dy * c]; +} + +export function rotatedBox(b: { x: number; y: number; w: number; h: number }, rot: number | undefined, cx = b.x + b.w / 2, cy = b.y + b.h / 2): { x: number; y: number; w: number; h: number } { + if (!rot) return { x: b.x, y: b.y, w: b.w, h: b.h }; + const corners = [[b.x, b.y], [b.x + b.w, b.y], [b.x + b.w, b.y + b.h], [b.x, b.y + b.h]].map((p) => rotatePoint(p as [number, number], rot, cx, cy)); + const xs = corners.map((p) => p[0]), ys = corners.map((p) => p[1]); + const x0 = Math.min(...xs), y0 = Math.min(...ys); + return { x: x0, y: y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0 }; } export interface Label { text: string; x: number; y: number; w: number; h: number; spec: NodeSpec } From 36d7cefded9967f7ffeb6a76fc87556f83ece948 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:32 -0500 Subject: [PATCH 029/279] feat(render): draw rectangles, rounded rectangles, ellipses, polygons and paths (0.5.0) Shapes take their stroke, dash, solid or linear gradient fill, opacity, rotation and drop shadow from the object, falling back to the style's line width and foreground. --- frontend/src/canvas/render/objects.ts | 2 + frontend/src/canvas/render/shape.ts | 60 +++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 frontend/src/canvas/render/shape.ts diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index a2eb4255..235e3492 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -3,6 +3,7 @@ import { isFragment, resolveStyle } from '../../engine/model'; import { arrowKind } from './arrow'; import { plusKind } from './plus'; import { bracketKind } from './bracket'; +import { shapeKind } from './shape'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -39,6 +40,7 @@ export const OBJECT_KINDS: Registry = { arrow: arrowKind, plus: plusKind, bracket: bracketKind, + shape: shapeKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { diff --git a/frontend/src/canvas/render/shape.ts b/frontend/src/canvas/render/shape.ts new file mode 100644 index 00000000..cc615ce6 --- /dev/null +++ b/frontend/src/canvas/render/shape.ts @@ -0,0 +1,60 @@ +import type { ShapeObject } from '../../engine/model'; +import { fmt, inflate, pts, union, type V } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { fillPaint, rotatedBox, rotation, strokeAttrs } from './paint'; +import type { Attrs, NodeSpec } from './svg'; + +export function polygonPoints(x: number, y: number, w: number, h: number, sides: number | undefined): V[] { + const n = Math.round(Math.min(12, Math.max(3, sides ?? 6))); + const cx = x + w / 2, cy = y + h / 2; + const t0 = -Math.PI / 2 + (n % 2 ? 0 : Math.PI / n); + const out: V[] = []; + for (let i = 0; i < n; i++) { + const t = t0 + (2 * Math.PI * i) / n; + out.push([cx + (w / 2) * Math.cos(t), cy + (h / 2) * Math.sin(t)]); + } + return out; +} + +export const cornerRadius = (obj: ShapeObject): number => Math.min(obj.radius ?? 0.1 * Math.min(obj.w, obj.h), Math.min(obj.w, obj.h) / 2); + +function geomSpec(obj: ShapeObject, a: Attrs): NodeSpec { + const { x, y, w, h } = obj; + switch (obj.geom) { + case 'ellipse': + return { tag: 'ellipse', a: { cx: fmt(x + w / 2), cy: fmt(y + h / 2), rx: fmt(w / 2), ry: fmt(h / 2), ...a } }; + case 'polygon': + return { tag: 'polygon', a: { points: pts(polygonPoints(x, y, w, h, obj.sides)), ...a } }; + case 'path': + return { tag: 'path', a: { d: obj.path ?? '', transform: `translate(${fmt(x)} ${fmt(y)})`, ...a } }; + case 'round_rect': { + const r = fmt(cornerRadius(obj)); + return { tag: 'rect', a: { x: fmt(x), y: fmt(y), width: fmt(w), height: fmt(h), rx: r, ry: r, ...a } }; + } + default: + return { tag: 'rect', a: { x: fmt(x), y: fmt(y), width: fmt(w), height: fmt(h), ...a } }; + } +} + +function shapeView(obj: ShapeObject, ctx: ObjectCtx): ObjectView { + const stroke = strokeAttrs(obj.stroke, ctx.colour, ctx.style.line_width); + const fill = fillPaint(obj.fill, `fc-grad-${obj.id}`); + const lw = obj.stroke === null ? 0 : obj.stroke?.width ?? ctx.style.line_width; + const body: NodeSpec[] = [...fill.defs]; + if (obj.shadow) { + const sh: Attrs = obj.fill ? { fill: obj.shadow.color, stroke: 'none' } : { fill: 'none', stroke: obj.shadow.color, 'stroke-width': fmt(lw || ctx.style.line_width) }; + body.push({ tag: 'g', a: { transform: `translate(${fmt(obj.shadow.dx)} ${fmt(obj.shadow.dy)})`, class: 'fc-shadow' }, kids: [geomSpec(obj, sh)] }); + } + body.push(geomSpec(obj, { ...fill.a, ...stroke, 'stroke-linejoin': 'miter' })); + const g: Attrs = {}; + const tf = rotation(obj.rot, obj.x + obj.w / 2, obj.y + obj.h / 2); + if (tf) g.transform = tf; + if (obj.opacity !== undefined && obj.opacity < 1) g.opacity = fmt(Math.max(0, obj.opacity)); + const specs = Object.keys(g).length ? [{ tag: 'g', a: g, kids: body }] : body; + const base = inflate({ x: obj.x, y: obj.y, w: obj.w, h: obj.h }, lw / 2); + const boxes = [base]; + if (obj.shadow) boxes.push({ ...base, x: base.x + obj.shadow.dx, y: base.y + obj.shadow.dy }); + return { specs, box: rotatedBox(union(boxes)!, obj.rot, obj.x + obj.w / 2, obj.y + obj.h / 2) }; +} + +export const shapeKind: ObjectKindDef<'shape'> = { view: shapeView }; From 3b402e14bfc9913ae69ea2ca872255e1f7bd652f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:48 -0500 Subject: [PATCH 030/279] feat(render): draw polylines and smooth Bezier lines (0.5.0) A smooth line passes a Catmull-Rom Bezier through its points so dragging a point bends the curve locally; the sampled outline is shared with bounds and hit testing. --- frontend/src/canvas/render/line.ts | 56 +++++++++++++++++++++++++++ frontend/src/canvas/render/objects.ts | 2 + 2 files changed, 58 insertions(+) create mode 100644 frontend/src/canvas/render/line.ts diff --git a/frontend/src/canvas/render/line.ts b/frontend/src/canvas/render/line.ts new file mode 100644 index 00000000..0f8205c3 --- /dev/null +++ b/frontend/src/canvas/render/line.ts @@ -0,0 +1,56 @@ +import type { LineObject, Point } from '../../engine/model'; +import { fmt, inflate, type V } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { strokeAttrs } from './paint'; + +type Seg = [V, V, V, V]; + +export function smoothSegments(ps: readonly Point[]): Seg[] { + const out: Seg[] = []; + for (let i = 0; i < ps.length - 1; i++) { + const p0 = ps[Math.max(0, i - 1)], p1 = ps[i], p2 = ps[i + 1], p3 = ps[Math.min(ps.length - 1, i + 2)]; + const c1: V = [p1[0] + (p2[0] - p0[0]) / 6, p1[1] + (p2[1] - p0[1]) / 6]; + const c2: V = [p2[0] - (p3[0] - p1[0]) / 6, p2[1] - (p3[1] - p1[1]) / 6]; + out.push([p1, c1, c2, p2]); + } + return out; +} + +const bez = (s: Seg, t: number): V => { + const u = 1 - t; + const a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t; + return [a * s[0][0] + b * s[1][0] + c * s[2][0] + d * s[3][0], a * s[0][1] + b * s[1][1] + c * s[2][1] + d * s[3][1]]; +}; + +export function linePoints(obj: LineObject): V[] { + if (!obj.smooth || obj.points.length < 3) return obj.points.map((p) => [p[0], p[1]] as V); + const out: V[] = [obj.points[0]]; + for (const s of smoothSegments(obj.points)) for (let i = 1; i <= 12; i++) out.push(bez(s, i / 12)); + return out; +} + +export function linePath(obj: LineObject): string { + const ps = obj.points; + if (!ps.length) return ''; + let d = `M${fmt(ps[0][0])} ${fmt(ps[0][1])}`; + if (obj.smooth && ps.length >= 3) { + for (const [, c1, c2, p] of smoothSegments(ps)) d += `C${fmt(c1[0])} ${fmt(c1[1])} ${fmt(c2[0])} ${fmt(c2[1])} ${fmt(p[0])} ${fmt(p[1])}`; + } else { + for (let i = 1; i < ps.length; i++) d += `L${fmt(ps[i][0])} ${fmt(ps[i][1])}`; + } + return d; +} + +function lineView(obj: LineObject, ctx: ObjectCtx): ObjectView { + if (obj.points.length < 2) return { specs: [], box: null }; + const stroke = strokeAttrs(obj.stroke, ctx.colour, ctx.style.line_width); + const lw = obj.stroke === null ? 0 : obj.stroke?.width ?? ctx.style.line_width; + const a = { d: linePath(obj), fill: 'none', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', ...stroke }; + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const [x, y] of linePoints(obj)) { + x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); + } + return { specs: [{ tag: 'path', a }], box: inflate({ x: x0, y: y0, w: x1 - x0, h: y1 - y0 }, lw / 2) }; +} + +export const lineKind: ObjectKindDef<'line'> = { view: lineView }; diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index 235e3492..f654925c 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -4,6 +4,7 @@ import { arrowKind } from './arrow'; import { plusKind } from './plus'; import { bracketKind } from './bracket'; import { shapeKind } from './shape'; +import { lineKind } from './line'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -41,6 +42,7 @@ export const OBJECT_KINDS: Registry = { plus: plusKind, bracket: bracketKind, shape: shapeKind, + line: lineKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { From a4e56e75f981441bc61e0e334441ea51cecb4690 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:02:52 -0500 Subject: [PATCH 031/279] feat(render): compute stoichiometry grid values for display (0.5.0) Moles, implied amounts, the limiting reagent, theoretical and percent yield follow from the step's typed amounts and the derived masses; they are shown, never written back, as FORMAT.md requires. --- frontend/src/canvas/render/stoich.ts | 147 +++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 frontend/src/canvas/render/stoich.ts diff --git a/frontend/src/canvas/render/stoich.ts b/frontend/src/canvas/render/stoich.ts new file mode 100644 index 00000000..83202bca --- /dev/null +++ b/frontend/src/canvas/render/stoich.ts @@ -0,0 +1,147 @@ +import type { FormChemDocument, Id, ReactionStep, Stoich, StoichComponent } from '../../engine/model'; + +export type StoichRole = 'reactant' | 'agent' | 'product'; +export type StoichField = 'equiv' | 'mmol' | 'mass' | 'volume'; + +export interface StoichRow { + id: Id; + role: StoichRole; + label: string; + formula?: string; + mw?: number; + equiv?: number; + mmol?: number; + mass_mg?: number; + volume_ml?: number; + density?: number; + conc?: number; + purity: number; + given: ReadonlySet; + limiting: boolean; + theo_mmol?: number; + theo_mg?: number; +} + +export interface StoichGrid { + rows: StoichRow[]; + limiting?: Id; + refMmol?: number; + product?: Id; + theoMmol?: number; + theoMg?: number; + isolatedMg?: number; + yieldPct?: number; +} + +export interface SpeciesInfo { mw?: number; formula?: string; name?: string } + +export function findStep(doc: FormChemDocument, reaction: Id, step: Id): ReactionStep | undefined { + for (const p of doc.pages) { + const r = p.reactions?.find((x) => x.id === reaction); + const s = r?.steps.find((x) => x.id === step); + if (s) return s; + } + return undefined; +} + +const finite = (n: number | undefined): n is number => typeof n === 'number' && Number.isFinite(n); +const pos = (n: number | undefined): n is number => finite(n) && n > 0; + +function directMmol(c: StoichComponent, mw: number | undefined, purity: number): number | undefined { + if (finite(c.mass_mg) && pos(mw)) return (c.mass_mg * purity) / mw; + if (finite(c.volume_ml) && pos(c.conc_m)) return c.conc_m * c.volume_ml; + if (finite(c.volume_ml) && pos(c.density_g_ml) && pos(mw)) return (c.volume_ml * c.density_g_ml * 1000 * purity) / mw; + return undefined; +} + +export function computeStoich(step: ReactionStep, info: (id: Id) => SpeciesInfo): StoichGrid { + const st: Stoich = step.stoich ?? { components: {} }; + const comps = st.components ?? {}; + const coef = (id: Id): number => (pos(step.coefficients?.[id]) ? step.coefficients![id] : 1); + const order: [Id, StoichRole][] = []; + const seen = new Set(); + const push = (id: Id, role: StoichRole): void => { + if (seen.has(id)) return; + seen.add(id); + order.push([id, role]); + }; + for (const id of step.reactants) push(id, 'reactant'); + for (const id of step.agents) push(id, 'agent'); + for (const id of step.products) push(id, 'product'); + for (const id of Object.keys(comps)) push(id, 'agent'); + + const rows: StoichRow[] = order.map(([id, role]) => { + const c = comps[id] ?? {}; + const sp = info(id); + const mw = pos(c.mw) ? c.mw : sp.mw; + const purity = (pos(c.purity_pct) ? Math.min(c.purity_pct, 100) : 100) / 100; + const given = new Set(); + if (finite(c.equiv)) given.add('equiv'); + if (finite(c.mass_mg)) given.add('mass'); + if (finite(c.volume_ml)) given.add('volume'); + let mmol = directMmol(c, mw, purity); + if (role === 'product' && id === st.product && mmol === undefined && finite(st.isolated_mg) && pos(mw)) { + mmol = st.isolated_mg / mw; + given.add('mass'); + } + return { + id, role, label: c.label ?? sp.name ?? sp.formula ?? id, formula: sp.formula, mw, mmol, + equiv: c.equiv, density: c.density_g_ml, conc: c.conc_m, purity, given, limiting: false, + }; + }); + + const reactants = rows.filter((r) => r.role === 'reactant'); + let limiting = st.limiting && rows.some((r) => r.id === st.limiting) ? st.limiting : undefined; + if (!limiting) { + let best = Infinity; + for (const r of reactants) { + if (!finite(r.mmol)) continue; + const v = r.mmol / coef(r.id); + if (v < best) { + best = v; + limiting = r.id; + } + } + } + if (!limiting) limiting = reactants.find((r) => r.equiv === 1)?.id ?? reactants[0]?.id; + const lim = rows.find((r) => r.id === limiting); + let refMmol = lim?.mmol; + if (!finite(refMmol) && pos(st.scale_mmol)) refMmol = st.scale_mmol * (pos(lim?.equiv) ? lim!.equiv! : 1); + const unitMmol = finite(refMmol) && lim ? refMmol / (pos(lim.equiv) ? lim.equiv! : 1) : undefined; + if (lim) { + lim.limiting = true; + if (!finite(lim.mmol) && finite(refMmol)) lim.mmol = refMmol; + } + + for (const r of rows) { + if (r.role !== 'product' && !finite(r.mmol) && finite(r.equiv) && finite(unitMmol)) r.mmol = r.equiv * unitMmol; + if (finite(r.mmol)) { + const c = comps[r.id] ?? {}; + r.mass_mg = finite(c.mass_mg) ? c.mass_mg : pos(r.mw) ? (r.mmol * r.mw) / r.purity : undefined; + r.volume_ml = finite(c.volume_ml) ? c.volume_ml : pos(r.conc) ? r.mmol / r.conc : pos(r.density) && finite(r.mass_mg) ? r.mass_mg / (r.density * 1000) : undefined; + if (r.role !== 'product' && !finite(r.equiv) && finite(refMmol) && refMmol > 0) r.equiv = (r.mmol / refMmol) * (pos(lim?.equiv) ? lim!.equiv! : 1); + } + if (r.role === 'product' && finite(refMmol) && lim) { + r.theo_mmol = (refMmol / coef(lim.id)) * coef(r.id); + if (pos(r.mw)) r.theo_mg = r.theo_mmol * r.mw; + } + } + + const grid: StoichGrid = { rows, limiting, refMmol }; + const product = rows.find((r) => r.id === st.product) ?? rows.find((r) => r.role === 'product'); + if (product) { + grid.product = product.id; + grid.theoMmol = product.theo_mmol; + grid.theoMg = product.theo_mg; + const isolated = finite(st.isolated_mg) ? st.isolated_mg : product.given.has('mass') ? product.mass_mg : undefined; + grid.isolatedMg = isolated; + if (finite(isolated) && pos(product.theo_mg)) grid.yieldPct = (isolated / product.theo_mg) * 100; + } + return grid; +} + +export function sig(n: number | undefined, digits = 3): string { + if (!finite(n)) return ''; + if (n === 0) return '0'; + return String(Number(n.toPrecision(digits))); +} From 8f972d8801d702defb47f1b5fb7a09e7a96c0422 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:03:42 -0500 Subject: [PATCH 032/279] feat(render): draw tables and live stoichiometry grids (0.5.0) Plain tables draw their runs, header and borders; a table bound to a reaction step draws the grid from the step's amounts and derived masses, with computed values in italic, so it is always current. --- frontend/src/canvas/render/objects.ts | 3 + frontend/src/canvas/render/table.ts | 122 ++++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 frontend/src/canvas/render/table.ts diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index f654925c..655151b0 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -5,6 +5,7 @@ import { plusKind } from './plus'; import { bracketKind } from './bracket'; import { shapeKind } from './shape'; import { lineKind } from './line'; +import { tableKind } from './table'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -33,6 +34,7 @@ export type ObjectOf = Extract; export interface ObjectKindDef { view(obj: ObjectOf, ctx: ObjectCtx): ObjectView; deps?(obj: ObjectOf, doc: FormChemDocument): unknown[]; + derived?: boolean; } type Registry = { [K in ObjectKind]?: ObjectKindDef }; @@ -43,6 +45,7 @@ export const OBJECT_KINDS: Registry = { bracket: bracketKind, shape: shapeKind, line: lineKind, + table: tableKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { diff --git a/frontend/src/canvas/render/table.ts b/frontend/src/canvas/render/table.ts new file mode 100644 index 00000000..1a2c465f --- /dev/null +++ b/frontend/src/canvas/render/table.ts @@ -0,0 +1,122 @@ +import type { Align, FormChemDocument, Id, Run, TableObject } from '../../engine/model'; +import { fmt, type Box } from './geom'; +import { measure } from './measure'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { computeStoich, findStep, sig, type StoichGrid } from './stoich'; +import type { NodeSpec } from './svg'; +import { textView } from './text'; + +interface GridCell { runs: Run[]; align?: Align; formula?: boolean } +interface GridRow { h: number; cells: (GridCell | null)[] } +interface Grid { x: number; y: number; cols: number[]; rows: GridRow[]; header: boolean; borders: 'all' | 'outer' | 'none'; pad: number } + +export const STOICH_COLUMNS = ['Compound', 'Role', 'MW', 'Equiv', 'mmol', 'Mass (mg)', 'Volume (mL)']; + +function gridSpecs(g: Grid, ctx: ObjectCtx): ObjectView { + const specs: NodeSpec[] = []; + const W = g.cols.reduce((n, c) => n + c, 0); + const H = g.rows.reduce((n, r) => n + r.h, 0); + const lw = ctx.style.line_width, c = ctx.colour; + const line = (x1: number, y1: number, x2: number, y2: number, w = lw): NodeSpec => ({ + tag: 'line', a: { x1: fmt(x1), y1: fmt(y1), x2: fmt(x2), y2: fmt(y2), stroke: c, 'stroke-width': fmt(w), 'stroke-linecap': 'square', class: 'fc-ln' }, + }); + let y = g.y; + g.rows.forEach((row, ri) => { + let x = g.x; + row.cells.forEach((cell, ci) => { + const w = g.cols[ci] ?? 0; + if (cell && cell.runs.some((r) => r.t)) { + const runs = g.header && ri === 0 ? cell.runs.map((r) => (r.b === undefined ? { ...r, b: true } : r)) : cell.runs; + const tv = textView({ x: x + g.pad, y: y + g.pad, w: Math.max(1, w - 2 * g.pad), runs, align: cell.align, formula: cell.formula }, ctx.style, c); + specs.push(...tv.specs); + } + x += w; + }); + y += row.h; + }); + if (g.borders !== 'none') specs.push({ tag: 'rect', a: { x: fmt(g.x), y: fmt(g.y), width: fmt(W), height: fmt(H), fill: 'none', stroke: c, 'stroke-width': fmt(lw), class: 'fc-ln' } }); + if (g.borders === 'all') { + let x = g.x; + for (let i = 0; i < g.cols.length - 1; i++) specs.push(line((x += g.cols[i]), g.y, x, g.y + H)); + let yy = g.y; + for (let i = 0; i < g.rows.length - 1; i++) specs.push(line(g.x, (yy += g.rows[i].h), g.x + W, yy)); + } + if (g.header && g.rows.length > 1 && g.borders !== 'all') specs.push(line(g.x, g.y + g.rows[0].h, g.x + W, g.y + g.rows[0].h, lw * 1.5)); + const box: Box = { x: g.x - lw / 2, y: g.y - lw / 2, w: W + lw, h: H + lw }; + return { specs, box }; +} + +const cell = (t: string, opts: { i?: boolean; align?: Align; formula?: boolean } = {}): GridCell => + ({ runs: [opts.i ? { t, i: true } : { t }], align: opts.align, formula: opts.formula }); + +function numCell(v: number | undefined, given: boolean): GridCell { + return cell(sig(v), { i: !given && v !== undefined, align: 'r' }); +} + +function stoichRows(grid: StoichGrid): GridCell[][] { + const out: GridCell[][] = [STOICH_COLUMNS.map((t, i) => cell(t, { align: i >= 2 ? 'r' : 'l' }))]; + for (const r of grid.rows) { + const role = r.role === 'reactant' ? (r.limiting ? 'limiting' : 'reactant') : r.role === 'agent' ? 'reagent' : 'product'; + out.push([ + cell(r.label, { formula: r.label === r.formula }), + cell(role), + cell(r.mw !== undefined ? r.mw.toFixed(2) : '', { align: 'r' }), + r.role === 'product' ? cell('') : numCell(r.equiv, r.given.has('equiv')), + numCell(r.mmol, false), + numCell(r.mass_mg, r.given.has('mass')), + numCell(r.volume_ml, r.given.has('volume')), + ]); + } + if (grid.theoMg !== undefined || grid.theoMmol !== undefined) { + out.push([cell('Theoretical yield'), cell(''), cell(''), cell(''), cell(sig(grid.theoMmol), { i: true, align: 'r' }), cell(sig(grid.theoMg), { i: true, align: 'r' }), cell('')]); + } + if (grid.yieldPct !== undefined) { + out.push([cell('Yield'), cell(''), cell(''), cell(''), cell(''), cell(sig(grid.isolatedMg), { align: 'r' }), cell(`${grid.yieldPct.toFixed(1)} %`, { i: true, align: 'r' })]); + } + return out; +} + +function stoichGrid(obj: TableObject, ctx: ObjectCtx): Grid | null { + if (!obj.stoich) return null; + const step = findStep(ctx.doc, obj.stoich.reaction, obj.stoich.step); + if (!step) return null; + const computed = computeStoich(step, (id) => { + const d = ctx.derived?.fragments[id]; + return { mw: d?.mw, formula: d?.formula, name: ctx.doc.objects[id]?.name }; + }); + const cells = stoichRows(computed); + const pad = obj.padding ?? 3; + const font = ctx.style.caption_font; + const rowH = font.size * 1.2 + 2 * pad; + let cols = obj.cols; + if (cols.length !== STOICH_COLUMNS.length) { + cols = STOICH_COLUMNS.map((_, ci) => { + let w = 0; + cells.forEach((row, ri) => { + const t = row[ci]?.runs.map((r) => r.t).join('') ?? ''; + w = Math.max(w, measure.width(t, font.size, font.family, ri === 0 || !!font.bold, !!row[ci]?.runs[0]?.i)); + }); + return Math.max(20, w + 2 * pad + 2); + }); + } + return { x: obj.x, y: obj.y, cols, rows: cells.map((r) => ({ h: rowH, cells: r })), header: true, borders: obj.borders ?? 'all', pad }; +} + +function tableView(obj: TableObject, ctx: ObjectCtx): ObjectView { + const g = stoichGrid(obj, ctx) ?? { + x: obj.x, y: obj.y, cols: obj.cols, + rows: obj.rows.map((r) => ({ h: r.h, cells: r.cells.map((c) => (c.runs ? { runs: c.runs } : null)) })), + header: !!obj.header, borders: obj.borders ?? 'all', pad: obj.padding ?? 3, + }; + return gridSpecs(g, ctx); +} + +function tableDeps(obj: TableObject, doc: FormChemDocument): unknown[] { + if (!obj.stoich) return []; + const step = findStep(doc, obj.stoich.reaction, obj.stoich.step); + if (!step) return [null]; + const ids: Id[] = [...step.reactants, ...step.agents, ...step.products]; + return [step, ...ids.map((id) => doc.objects[id]?.name)]; +} + +export const tableKind: ObjectKindDef<'table'> = { view: tableView, deps: tableDeps, derived: true }; From 9afdf8560da2b521ca8400237e1251d0115754fc Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:04:12 -0500 Subject: [PATCH 033/279] feat(render): draw images from document media with crop, opacity and rotation (0.5.0) Pictures load from the engine's document media URL through a small cache; until a file loads, or if it cannot, the image's box shows a placeholder so the layout never jumps. --- frontend/src/canvas/render/image.ts | 120 ++++++++++++++++++++++++++ frontend/src/canvas/render/objects.ts | 2 + 2 files changed, 122 insertions(+) create mode 100644 frontend/src/canvas/render/image.ts diff --git a/frontend/src/canvas/render/image.ts b/frontend/src/canvas/render/image.ts new file mode 100644 index 00000000..e328aa56 --- /dev/null +++ b/frontend/src/canvas/render/image.ts @@ -0,0 +1,120 @@ +import type { FormChemDocument, Id, ImageObject } from '../../engine/model'; +import { fmt } from './geom'; +import type { MediaRef, ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { label, rotatedBox, rotation } from './paint'; +import type { Attrs, NodeSpec } from './svg'; + +export type MediaUrl = (doc: FormChemDocument, media: Id) => string; + +const engineMediaUrl: MediaUrl = (doc, media) => `/api/documents/${encodeURIComponent(doc.id)}/media/${encodeURIComponent(media)}`; + +type LoadState = 'loading' | 'ok' | 'error'; + +export class MediaCache { + private state = new Map(); + private listeners = new Set<() => void>(); + private resolve: MediaUrl = engineMediaUrl; + epoch = 0; + + setUrl(fn: MediaUrl | null): void { + this.resolve = fn ?? engineMediaUrl; + this.state.clear(); + this.bump(); + } + + url(doc: FormChemDocument, media: Id): string { + return this.resolve(doc, media); + } + + ref(doc: FormChemDocument, media: Id): MediaRef { + const url = this.resolve(doc, media); + let s = this.state.get(url); + if (!s) { + s = 'loading'; + this.state.set(url, s); + this.load(url); + } + return { href: s === 'ok' ? url : null, failed: s === 'error' }; + } + + subscribe(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + private load(url: string): void { + if (typeof Image === 'undefined') { + this.state.set(url, 'error'); + return; + } + const img = new Image(); + img.onload = () => this.settle(url, 'ok'); + img.onerror = () => this.settle(url, 'error'); + img.src = url; + } + + private settle(url: string, s: LoadState): void { + if (this.state.get(url) !== 'loading') return; + this.state.set(url, s); + this.bump(); + } + + private bump(): void { + this.epoch++; + for (const fn of this.listeners) fn(); + } +} + +export const mediaCache = new MediaCache(); + +export const setMediaUrl = (fn: MediaUrl | null): void => mediaCache.setUrl(fn); + +function placeholder(obj: ImageObject, ctx: ObjectCtx, failed: boolean): NodeSpec[] { + const { x, y, w, h } = obj; + const c = ctx.colour; + const a: Attrs = { fill: 'none', stroke: c, 'stroke-opacity': '0.35', 'stroke-width': fmt(ctx.style.line_width), class: 'fc-ln fc-image-missing' }; + const out: NodeSpec[] = [ + { tag: 'rect', a: { ...a, x: fmt(x), y: fmt(y), width: fmt(w), height: fmt(h), 'stroke-dasharray': `${fmt(3)} ${fmt(2)}` } }, + { tag: 'path', a: { ...a, d: `M${fmt(x)} ${fmt(y)}L${fmt(x + w)} ${fmt(y + h)}M${fmt(x + w)} ${fmt(y)}L${fmt(x)} ${fmt(y + h)}` } }, + ]; + const name = ctx.doc.media?.[obj.media]?.name; + if (failed && name && w > 20 && h > 12) { + const font = ctx.style.caption_font; + const lab = label(name, [x + w / 2, y + h / 2 + font.size * 0.3], font, Math.min(font.size, h / 3), c, 'middle'); + lab.spec.a['fill-opacity'] = '0.6'; + out.push(lab.spec); + } + return out; +} + +function imageView(obj: ImageObject, ctx: ObjectCtx): ObjectView { + const { x, y, w, h } = obj; + const ref = ctx.media(obj.media); + const specs: NodeSpec[] = []; + if (ref.href) { + const cr = obj.crop ?? { l: 0, t: 0, r: 0, b: 0 }; + const fw = Math.max(0.01, 1 - cr.l - cr.r), fh = Math.max(0.01, 1 - cr.t - cr.b); + const W = w / fw, H = h / fh; + const a: Attrs = { href: ref.href, x: fmt(x - cr.l * W), y: fmt(y - cr.t * H), width: fmt(W), height: fmt(H), preserveAspectRatio: 'none' }; + const cropped = cr.l || cr.t || cr.r || cr.b; + if (cropped) { + const id = `fc-clip-${obj.id}`; + specs.push({ tag: 'clipPath', a: { id }, kids: [{ tag: 'rect', a: { x: fmt(x), y: fmt(y), width: fmt(w), height: fmt(h) } }] }); + a['clip-path'] = `url(#${id})`; + } + specs.push({ tag: 'image', a }); + } else { + specs.push(...placeholder(obj, ctx, ref.failed)); + } + const g: Attrs = {}; + const tf = rotation(obj.rot, x + w / 2, y + h / 2); + if (tf) g.transform = tf; + if (obj.opacity !== undefined && obj.opacity < 1) g.opacity = fmt(Math.max(0, obj.opacity)); + return { specs: Object.keys(g).length ? [{ tag: 'g', a: g, kids: specs }] : specs, box: rotatedBox({ x, y, w, h }, obj.rot) }; +} + +function imageDeps(obj: ImageObject, doc: FormChemDocument): unknown[] { + return [doc.id, doc.media?.[obj.media], mediaCache.epoch]; +} + +export const imageKind: ObjectKindDef<'image'> = { view: imageView, deps: imageDeps }; diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index 655151b0..a3a21b00 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -6,6 +6,7 @@ import { bracketKind } from './bracket'; import { shapeKind } from './shape'; import { lineKind } from './line'; import { tableKind } from './table'; +import { imageKind } from './image'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -46,6 +47,7 @@ export const OBJECT_KINDS: Registry = { shape: shapeKind, line: lineKind, table: tableKind, + image: imageKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { From 0cefa280280567c951b9b94f1fb78b70d3617066 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:04:42 -0500 Subject: [PATCH 034/279] feat(render): draw TLC plates with origin, front, lanes, spots and Rf values (0.5.0) Spots are placed from their stored Rf between the origin and front lines, so resizing a plate never moves a value; circle, ellipse and tailing smear spots can be outlined, filled or hatched. --- frontend/src/canvas/render/objects.ts | 2 + frontend/src/canvas/render/tlc.ts | 100 ++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 frontend/src/canvas/render/tlc.ts diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index a3a21b00..417dcf2e 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -7,6 +7,7 @@ import { shapeKind } from './shape'; import { lineKind } from './line'; import { tableKind } from './table'; import { imageKind } from './image'; +import { tlcKind } from './tlc'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -48,6 +49,7 @@ export const OBJECT_KINDS: Registry = { line: lineKind, table: tableKind, image: imageKind, + tlc: tlcKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { diff --git a/frontend/src/canvas/render/tlc.ts b/frontend/src/canvas/render/tlc.ts new file mode 100644 index 00000000..e2698c81 --- /dev/null +++ b/frontend/src/canvas/render/tlc.ts @@ -0,0 +1,100 @@ +import type { TlcObject, TlcSpot } from '../../engine/model'; +import { fmt, union, type Box } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { label } from './paint'; +import type { Attrs, NodeSpec } from './svg'; + +export interface TlcLayout { + originY: number; + frontY: number; + laneX: number[]; + laneW: number; +} + +export function tlcLayout(obj: TlcObject): TlcLayout { + const origin = obj.origin ?? 0.1, front = obj.front ?? 0.1; + const n = Math.max(1, obj.lanes.length); + const laneW = obj.w / n; + return { + originY: obj.y + obj.h - origin * obj.h, + frontY: obj.y + front * obj.h, + laneX: obj.lanes.map((_, i) => obj.x + laneW * (i + 0.5)), + laneW, + }; +} + +export interface SpotGeom { cx: number; cy: number; rx: number; ry: number } + +export function spotGeom(spot: TlcSpot, laneX: number, lay: TlcLayout): SpotGeom { + const rx = spot.rx ?? Math.max(0.8, Math.min(2.5, lay.laneW * 0.3)); + const ry = spot.shape === 'circle' || spot.shape === undefined ? rx : spot.ry ?? rx * 0.7; + return { cx: laneX, cy: lay.originY - spot.rf * (lay.originY - lay.frontY), rx, ry }; +} + +function spotPath(s: SpotGeom, smear: boolean): string { + const { cx, cy, rx, ry } = s; + if (!smear) { + return `M${fmt(cx - rx)} ${fmt(cy)}A${fmt(rx)} ${fmt(ry)} 0 1 1 ${fmt(cx + rx)} ${fmt(cy)}A${fmt(rx)} ${fmt(ry)} 0 1 1 ${fmt(cx - rx)} ${fmt(cy)}Z`; + } + const tail = cy + 3.2 * ry; + return `M${fmt(cx - rx)} ${fmt(cy)}A${fmt(rx)} ${fmt(ry)} 0 0 1 ${fmt(cx + rx)} ${fmt(cy)}Q${fmt(cx + rx * 0.6)} ${fmt(cy + 2 * ry)} ${fmt(cx)} ${fmt(tail)}Q${fmt(cx - rx * 0.6)} ${fmt(cy + 2 * ry)} ${fmt(cx - rx)} ${fmt(cy)}Z`; +} + +function spotSpecs(obj: TlcObject, spot: TlcSpot, s: SpotGeom, ctx: ObjectCtx): NodeSpec[] { + const colour = spot.color ?? ctx.colour; + const lw = fmt(ctx.style.line_width); + const d = spotPath(s, spot.shape === 'smear'); + const fill = spot.fill ?? 'filled'; + const outline: Attrs = { d, stroke: colour, 'stroke-width': lw, class: 'fc-ln fc-spot', fill: fill === 'filled' ? colour : 'none' }; + if (fill !== 'hatched') return [{ tag: 'path', a: outline }]; + const id = `fc-spot-${obj.id}-${spot.id}`; + const top = s.cy - s.ry, bottom = s.cy + (spot.shape === 'smear' ? 3.2 : 1) * s.ry; + const step = Math.max(0.8, ctx.style.line_width * 2.2); + let hatch = ''; + for (let k = s.cx - s.rx - (bottom - top); k <= s.cx + s.rx; k += step) hatch += `M${fmt(k)} ${fmt(bottom)}L${fmt(k + (bottom - top))} ${fmt(top)}`; + return [ + { tag: 'clipPath', a: { id }, kids: [{ tag: 'path', a: { d } }] }, + { tag: 'path', a: { d: hatch, stroke: colour, 'stroke-width': fmt(ctx.style.line_width * 0.6), fill: 'none', 'clip-path': `url(#${id})` } }, + { tag: 'path', a: outline }, + ]; +} + +function tlcView(obj: TlcObject, ctx: ObjectCtx): ObjectView { + const { x, y, w, h } = obj; + const c = ctx.colour, lw = ctx.style.line_width; + const lay = tlcLayout(obj); + const ln = (x1: number, y1: number, x2: number, y2: number, extra: Attrs = {}): NodeSpec => ({ + tag: 'line', a: { x1: fmt(x1), y1: fmt(y1), x2: fmt(x2), y2: fmt(y2), stroke: c, 'stroke-width': fmt(lw), class: 'fc-ln', ...extra }, + }); + const specs: NodeSpec[] = [ + { tag: 'rect', a: { x: fmt(x), y: fmt(y), width: fmt(w), height: fmt(h), fill: 'none', stroke: c, 'stroke-width': fmt(lw), class: 'fc-ln fc-plate' } }, + ln(x, lay.originY, x + w, lay.originY, { class: 'fc-ln fc-origin' }), + ln(x, lay.frontY, x + w, lay.frontY, { 'stroke-dasharray': `${fmt(3 * lw + 1)} ${fmt(2 * lw + 1)}`, class: 'fc-ln fc-front' }), + ]; + const boxes: Box[] = [{ x: x - lw / 2, y: y - lw / 2, w: w + lw, h: h + lw }]; + const font = ctx.style.caption_font; + const tick = Math.min(2, lay.laneW * 0.2); + obj.lanes.forEach((lane, i) => { + const lx = lay.laneX[i]; + specs.push(ln(lx, lay.originY - tick, lx, lay.originY + tick)); + for (const spot of lane.spots) { + const s = spotGeom(spot, lx, lay); + specs.push(...spotSpecs(obj, spot, s, ctx)); + if (obj.show_rf) { + const size = font.size * 0.7; + const lab = label(spot.rf.toFixed(2), [s.cx + s.rx + 1.2, s.cy + size * 0.35], font, size, c); + specs.push(lab.spec); + boxes.push(lab); + } + } + if (lane.label) { + const size = font.size * 0.8; + const lab = label(lane.label, [lx, y + h + size * 1.1], font, size, c, 'middle'); + specs.push(lab.spec); + boxes.push(lab); + } + }); + return { specs, box: union(boxes) }; +} + +export const tlcKind: ObjectKindDef<'tlc'> = { view: tlcView }; From 90f979a2b11655f91cfa8c3f88e86de80689ae6f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:11 -0500 Subject: [PATCH 035/279] feat(render): draw s, p, d, dz2, sp, sigma and pi orbitals with phase fills (0.5.0) Lobes follow the filled, hollow and shaded variants of spec A 6.5, the phase flag swaps which lobe is filled, and an orbital attached to an atom stays centred on it. --- frontend/src/canvas/render/objects.ts | 2 + frontend/src/canvas/render/orbital.ts | 80 +++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 frontend/src/canvas/render/orbital.ts diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index 417dcf2e..2d7ceda5 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -8,6 +8,7 @@ import { lineKind } from './line'; import { tableKind } from './table'; import { imageKind } from './image'; import { tlcKind } from './tlc'; +import { orbitalKind } from './orbital'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -50,6 +51,7 @@ export const OBJECT_KINDS: Registry = { table: tableKind, image: imageKind, tlc: tlcKind, + orbital: orbitalKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { diff --git a/frontend/src/canvas/render/orbital.ts b/frontend/src/canvas/render/orbital.ts new file mode 100644 index 00000000..ea78db8a --- /dev/null +++ b/frontend/src/canvas/render/orbital.ts @@ -0,0 +1,80 @@ +import type { FormChemDocument, OrbitalObject } from '../../engine/model'; +import { fmt, type V } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { withRotation } from './paint'; +import type { Attrs, NodeSpec } from './svg'; + +type Phase = 'a' | 'b'; + +export function orbitalCentre(obj: OrbitalObject, ctx: Pick): V { + const at = obj.atom ? ctx.chem.atomPos(obj.atom.object, obj.atom.atom) : null; + return at ?? [obj.x, obj.y]; +} + +function lobe(c: V, deg: number, len: number, wd: number): string { + const r = (deg * Math.PI) / 180; + const u: V = [Math.cos(r), -Math.sin(r)], n: V = [-u[1], u[0]]; + const p = (along: number, across: number): string => `${fmt(c[0] + u[0] * along + n[0] * across)} ${fmt(c[1] + u[1] * along + n[1] * across)}`; + return `M${p(0, 0)}C${p(0.25 * len, -1.2 * wd)} ${p(len, -wd)} ${p(len, 0)}C${p(len, wd)} ${p(0.25 * len, 1.2 * wd)} ${p(0, 0)}Z`; +} + +function paint(obj: OrbitalObject, phase: Phase, colour: string, lw: number): Attrs { + const swapped = obj.phase ? (phase === 'a' ? 'b' : 'a') : phase; + const fill = obj.fill ?? 'shaded'; + const a: Attrs = { stroke: colour, 'stroke-width': fmt(lw), 'stroke-linejoin': 'round', class: 'fc-ln fc-lobe' }; + if (fill === 'hollow' || (fill === 'shaded' && swapped === 'b')) a.fill = 'none'; + else { + a.fill = colour; + if (fill === 'filled' && swapped === 'b') a['fill-opacity'] = '0.3'; + } + return a; +} + +function orbitalView(obj: OrbitalObject, ctx: ObjectCtx): ObjectView { + const c = orbitalCentre(obj, ctx); + const s = Math.max(1, obj.size); + const lw = ctx.style.line_width, col = ctx.colour; + const specs: NodeSpec[] = []; + const addLobe = (deg: number, len: number, wd: number, ph: Phase): void => { + specs.push({ tag: 'path', a: { d: lobe(c, deg, len, wd), ...paint(obj, ph, col, lw) } }); + }; + const ellipse = (cx: number, cy: number, rx: number, ry: number, ph: Phase): void => { + specs.push({ tag: 'ellipse', a: { cx: fmt(cx), cy: fmt(cy), rx: fmt(rx), ry: fmt(ry), ...paint(obj, ph, col, lw) } }); + }; + switch (obj.type) { + case 's': + ellipse(c[0], c[1], s * 0.5, s * 0.5, 'a'); + break; + case 'p': + addLobe(0, s, 0.55 * s, 'a'); + addLobe(180, s, 0.55 * s, 'b'); + break; + case 'd': + [45, 135, 225, 315].forEach((deg, i) => addLobe(deg, s, 0.42 * s, i % 2 ? 'b' : 'a')); + break; + case 'dz2': + addLobe(90, s, 0.5 * s, 'a'); + addLobe(270, s, 0.5 * s, 'a'); + ellipse(c[0], c[1], 0.5 * s, 0.18 * s, 'b'); + break; + case 'sp': + addLobe(0, s, 0.6 * s, 'a'); + addLobe(180, 0.38 * s, 0.25 * s, 'b'); + break; + case 'sigma': + ellipse(c[0], c[1], s, 0.42 * s, 'a'); + break; + case 'pi': + ellipse(c[0], c[1] - 0.42 * s, 0.9 * s, 0.3 * s, 'a'); + ellipse(c[0], c[1] + 0.42 * s, 0.9 * s, 0.3 * s, 'b'); + break; + } + const m = lw / 2; + return { specs: withRotation(specs, obj.rot, c[0], c[1]), box: { x: c[0] - s - m, y: c[1] - s - m, w: 2 * s + lw, h: 2 * s + lw } }; +} + +function orbitalDeps(obj: OrbitalObject, doc: FormChemDocument): unknown[] { + return obj.atom ? [doc.objects[obj.atom.object]] : []; +} + +export const orbitalKind: ObjectKindDef<'orbital'> = { view: orbitalView, deps: orbitalDeps }; From 741150ad286f03ff3306e1cbcf725c28379c7a0f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:27 -0500 Subject: [PATCH 036/279] feat(render): give groups a view that draws nothing and bounds their children (0.5.0) Members of a group are drawn by their own kinds, integral or not; the group itself only contributes the union of its children's boxes for selection and hit testing. --- frontend/src/canvas/render/group.ts | 18 ++++++++++++++++++ frontend/src/canvas/render/objects.ts | 2 ++ 2 files changed, 20 insertions(+) create mode 100644 frontend/src/canvas/render/group.ts diff --git a/frontend/src/canvas/render/group.ts b/frontend/src/canvas/render/group.ts new file mode 100644 index 00000000..92459d23 --- /dev/null +++ b/frontend/src/canvas/render/group.ts @@ -0,0 +1,18 @@ +import type { FormChemDocument, GroupObject } from '../../engine/model'; +import { union, type Box } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; + +function groupView(obj: GroupObject, ctx: ObjectCtx): ObjectView { + const boxes: Box[] = []; + for (const id of obj.children) { + const b = ctx.boxOf(id); + if (b) boxes.push(b); + } + return { specs: [], box: union(boxes) }; +} + +function groupDeps(obj: GroupObject, doc: FormChemDocument): unknown[] { + return obj.children.map((id) => doc.objects[id]); +} + +export const groupKind: ObjectKindDef<'group'> = { view: groupView, deps: groupDeps }; diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index 2d7ceda5..f2361c83 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -9,6 +9,7 @@ import { tableKind } from './table'; import { imageKind } from './image'; import { tlcKind } from './tlc'; import { orbitalKind } from './orbital'; +import { groupKind } from './group'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -52,6 +53,7 @@ export const OBJECT_KINDS: Registry = { image: imageKind, tlc: tlcKind, orbital: orbitalKind, + group: groupKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { From c7cd0b022880aaa9d9b726bb28974943efb89d7a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:38 -0500 Subject: [PATCH 037/279] feat(render): place captions under their target structure (0.5.0) A caption with a target and offset is laid out from the target's bottom centre, so it moves with the structure; text and captions join the kind registry for shared bounds. --- frontend/src/canvas/render/caption.ts | 34 +++++++++++++++++++++++++++ frontend/src/canvas/render/objects.ts | 3 +++ 2 files changed, 37 insertions(+) create mode 100644 frontend/src/canvas/render/caption.ts diff --git a/frontend/src/canvas/render/caption.ts b/frontend/src/canvas/render/caption.ts new file mode 100644 index 00000000..e90bc183 --- /dev/null +++ b/frontend/src/canvas/render/caption.ts @@ -0,0 +1,34 @@ +import type { CaptionObject, FormChemDocument, TextFields, TextObject } from '../../engine/model'; +import type { Box } from './geom'; +import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; +import { textView } from './text'; + +export function captionAt(obj: CaptionObject, target: Box | null, width: number): { x: number; y: number } { + if (!obj.target || !obj.offset || !target) return { x: obj.x, y: obj.y }; + const top = target.y + target.h + obj.offset[1]; + const cx = target.x + target.w / 2 + obj.offset[0]; + return { x: cx - width / 2, y: top }; +} + +export function placedCaption(obj: CaptionObject, ctx: ObjectCtx): TextFields { + if (!obj.target || !obj.offset) return obj; + const target = ctx.boxOf(obj.target); + if (!target) return obj; + const w = textView(obj, ctx.style, ctx.colour).box.w; + return { ...obj, ...captionAt(obj, target, w) }; +} + +const textKindView = (obj: TextObject, ctx: ObjectCtx): ObjectView => textView(obj, ctx.style, ctx.colour); + +function captionView(obj: CaptionObject, ctx: ObjectCtx): ObjectView { + return textView(placedCaption(obj, ctx), ctx.style, ctx.colour); +} + +function captionDeps(obj: CaptionObject, doc: FormChemDocument): unknown[] { + if (!obj.target) return []; + const t = doc.objects[obj.target]; + return t?.kind === 'group' ? [t, ...t.children.map((id) => doc.objects[id])] : [t]; +} + +export const textKind: ObjectKindDef<'text'> = { view: textKindView }; +export const captionKind: ObjectKindDef<'caption'> = { view: captionView, deps: captionDeps }; diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts index f2361c83..27a6cff2 100644 --- a/frontend/src/canvas/render/objects.ts +++ b/frontend/src/canvas/render/objects.ts @@ -10,6 +10,7 @@ import { imageKind } from './image'; import { tlcKind } from './tlc'; import { orbitalKind } from './orbital'; import { groupKind } from './group'; +import { captionKind, textKind } from './caption'; import type { Box, V } from './geom'; import type { NodeSpec } from './svg'; @@ -54,6 +55,8 @@ export const OBJECT_KINDS: Registry = { tlc: tlcKind, orbital: orbitalKind, group: groupKind, + text: textKind, + caption: captionKind, }; export function kindDef(kind: string): ObjectKindDef | undefined { From 95d3080a6ce280176aebeb4bdc99367df0d0df6d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:49 -0500 Subject: [PATCH 038/279] feat(render): compute object bounds for every kind from the document (0.5.0) Tools and selection can ask objectBox(obj, doc) without a mounted renderer; it runs the same view code as drawing, so a box always matches what is on screen. --- frontend/src/canvas/render/bounds.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 frontend/src/canvas/render/bounds.ts diff --git a/frontend/src/canvas/render/bounds.ts b/frontend/src/canvas/render/bounds.ts new file mode 100644 index 00000000..c1c8d54f --- /dev/null +++ b/frontend/src/canvas/render/bounds.ts @@ -0,0 +1,25 @@ +import type { DocObject, FormChemDocument, Id } from '../../engine/model'; +import { fragmentBounds } from '../../engine/model'; +import type { Box } from './geom'; +import { docCtx, objectView } from './objects'; + +const MAX_DEPTH = 32; +const cache = new WeakMap(); + +export function objectBox(obj: DocObject, doc: FormChemDocument, depth = 0): Box | null { + if (obj.kind === 'fragment') return fragmentBounds(obj); + const hit = cache.get(obj); + if (hit && hit.doc === doc) return hit.box; + const boxOf = (id: Id): Box | null => { + const o = doc.objects[id]; + return o && depth < MAX_DEPTH ? objectBox(o, doc, depth + 1) : null; + }; + const box = objectView(obj, docCtx(doc, obj, boxOf))?.box ?? null; + cache.set(obj, { doc, box }); + return box; +} + +export function objectBoxById(doc: FormChemDocument, id: Id): Box | null { + const o = doc.objects[id]; + return o ? objectBox(o, doc) : null; +} From 9ca52f8e6ac0bf58d82e25318f3e6498361a777f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:06:26 -0500 Subject: [PATCH 039/279] feat(canvas): add a hit test helper for non-chemistry objects (0.5.0) hitObject(obj, docPoint, tol, doc) measures against the drawn geometry: arrow shafts and heads, line and shape outlines, filled shape interiors, bracket sides, orbital extent and boxes for the rest. --- frontend/src/canvas/hit-objects.ts | 124 +++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 frontend/src/canvas/hit-objects.ts diff --git a/frontend/src/canvas/hit-objects.ts b/frontend/src/canvas/hit-objects.ts new file mode 100644 index 00000000..691b8795 --- /dev/null +++ b/frontend/src/canvas/hit-objects.ts @@ -0,0 +1,124 @@ +import type { BracketObject, DocObject, FormChemDocument, Point, ShapeObject, Style } from '../engine/model'; +import { defaultStyle, resolveStyle } from '../engine/model'; +import { arrowShape, curveSamples } from './render/arrow'; +import { objectBox } from './render/bounds'; +import type { Box, V } from './render/geom'; +import { linePoints } from './render/line'; +import { docChem, type ChemGeometry } from './render/objects'; +import { orbitalCentre } from './render/orbital'; +import { rotatePoint } from './render/paint'; +import { polygonPoints } from './render/shape'; + +const EMPTY = { objects: {}, pages: [], style: {} } as unknown as FormChemDocument; +const NO_CHEM: ChemGeometry = { atomPos: () => null, lonePair: () => null, bondLength: () => defaultStyle().bond_length }; + +function segDist(p: V, a: V, b: V): number { + const vx = b[0] - a[0], vy = b[1] - a[1]; + const l2 = vx * vx + vy * vy; + const t = l2 > 0 ? Math.max(0, Math.min(1, ((p[0] - a[0]) * vx + (p[1] - a[1]) * vy) / l2)) : 0; + return Math.hypot(p[0] - (a[0] + t * vx), p[1] - (a[1] + t * vy)); +} + +function polyDist(p: V, ps: readonly V[], closed = false): number { + let d = Infinity; + for (let i = 1; i < ps.length; i++) d = Math.min(d, segDist(p, ps[i - 1], ps[i])); + if (closed && ps.length > 2) d = Math.min(d, segDist(p, ps[ps.length - 1], ps[0])); + return ps.length === 1 ? Math.hypot(p[0] - ps[0][0], p[1] - ps[0][1]) : d; +} + +function inPoly(p: V, ps: readonly V[]): boolean { + let inside = false; + for (let i = 0, j = ps.length - 1; i < ps.length; j = i++) { + const [xi, yi] = ps[i], [xj, yj] = ps[j]; + if ((yi > p[1]) !== (yj > p[1]) && p[0] < ((xj - xi) * (p[1] - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; +} + +function boxDist(p: V, b: Box): number { + const dx = Math.max(b.x - p[0], 0, p[0] - (b.x + b.w)); + const dy = Math.max(b.y - p[1], 0, p[1] - (b.y + b.h)); + return Math.hypot(dx, dy); +} + +const rectPoints = (x: number, y: number, w: number, h: number): V[] => [[x, y], [x + w, y], [x + w, y + h], [x, y + h]]; + +function shapeDist(o: ShapeObject, p: V, lw: number): number { + const q = rotatePoint(p, o.rot ? -o.rot : 0, o.x + o.w / 2, o.y + o.h / 2); + const filled = !!o.fill; + if (o.geom === 'ellipse') { + const rx = Math.max(o.w / 2, 1e-6), ry = Math.max(o.h / 2, 1e-6); + const k = Math.hypot((q[0] - o.x - rx) / rx, (q[1] - o.y - ry) / ry); + if (filled && k <= 1) return 0; + return Math.max(0, Math.abs(k - 1) * Math.min(rx, ry) - lw / 2); + } + if (o.geom === 'path') return boxDist(q, o); + const ps = o.geom === 'polygon' ? polygonPoints(o.x, o.y, o.w, o.h, o.sides) : rectPoints(o.x, o.y, o.w, o.h); + if (filled && inPoly(q, ps)) return 0; + return Math.max(0, polyDist(q, ps, true) - lw / 2); +} + +function bracketDist(o: BracketObject, p: V, style: Style): number { + const q = rotatePoint(p, o.rot ? -o.rot : 0, o.x + o.w / 2, o.y + o.h / 2); + const sides = o.sides ?? 'both'; + let d = Infinity; + if (sides !== 'right') d = Math.min(d, segDist(q, [o.x, o.y], [o.x, o.y + o.h])); + if (sides !== 'left') d = Math.min(d, segDist(q, [o.x + o.w, o.y], [o.x + o.w, o.y + o.h])); + return Math.max(0, d - style.line_width / 2 - Math.min(o.w / 3, 0.15 * style.bond_length)); +} + +function rotatedRectDist(p: V, b: { x: number; y: number; w: number; h: number; rot?: number }): number { + return boxDist(rotatePoint(p, b.rot ? -b.rot : 0, b.x + b.w / 2, b.y + b.h / 2), b); +} + +export function objectDistance(obj: DocObject, p: Point, doc?: FormChemDocument, depth = 0): number { + const d = doc ?? EMPTY; + const style = doc ? resolveStyle(doc, obj) : defaultStyle(); + const chem = doc ? docChem(doc) : NO_CHEM; + switch (obj.kind) { + case 'fragment': + return Infinity; + case 'arrow': { + const s = arrowShape(obj, d, style, chem); + let best = Infinity; + for (const sh of s.shafts) best = Math.min(best, polyDist(p, curveSamples(sh.curve, 32))); + for (const st of s.strokes) best = Math.min(best, polyDist(p, st)); + for (const poly of [...s.fills, ...s.outlines]) best = inPoly(p, poly) ? 0 : Math.min(best, polyDist(p, poly, true)); + return Math.max(0, best - s.lw / 2); + } + case 'line': { + if (obj.points.length < 2) return Infinity; + const lw = obj.stroke === null ? 0 : obj.stroke?.width ?? style.line_width; + return Math.max(0, polyDist(p, linePoints(obj)) - lw / 2); + } + case 'shape': + return shapeDist(obj, p, obj.stroke === null ? 0 : obj.stroke?.width ?? style.line_width); + case 'bracket': + return bracketDist(obj, p, style); + case 'orbital': { + const c = orbitalCentre(obj, { chem }); + return Math.max(0, Math.hypot(p[0] - c[0], p[1] - c[1]) - obj.size); + } + case 'image': + return rotatedRectDist(p, obj); + case 'group': { + if (!doc || depth > 32) return Infinity; + let best = Infinity; + for (const id of obj.children) { + const c = doc.objects[id]; + if (c && !c.hidden) best = Math.min(best, objectDistance(c, p, doc, depth + 1)); + } + return best; + } + default: { + const b = objectBox(obj, d); + return b ? boxDist(p, b) : Infinity; + } + } +} + +export function hitObject(obj: DocObject, docPoint: Point, tol: number, doc?: FormChemDocument): number | null { + if (obj.hidden) return null; + const dist = objectDistance(obj, docPoint, doc); + return dist <= tol ? dist : null; +} From 462ef0d089f2c268fecc34453056b07e13a87b4a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:07:40 -0500 Subject: [PATCH 040/279] feat(render): dispatch every object kind through the registry in the renderer (0.5.0) Arrows, symbols, brackets, shapes, lines, tables, images, TLC plates and orbitals now draw in an objects layer as keyed nodes patched in place, re-laid out only when the object, its style, its anchors or its inputs change; the renderer exposes objectBox for hit testing. --- frontend/src/canvas/render/index.ts | 7 ++ frontend/src/canvas/render/renderer.ts | 106 +++++++++++++++++++------ 2 files changed, 90 insertions(+), 23 deletions(-) diff --git a/frontend/src/canvas/render/index.ts b/frontend/src/canvas/render/index.ts index 645757fe..f2ad4f50 100644 --- a/frontend/src/canvas/render/index.ts +++ b/frontend/src/canvas/render/index.ts @@ -2,3 +2,10 @@ export { createRenderer, type FormChemRenderer, type RenderStats } from './rende export { implicitHydrogens } from './valence'; export { perceive, type Ring, type Topology } from './rings'; export { measure, cssFamily, bundledFamily } from './measure'; +export { objectBox, objectBoxById } from './bounds'; +export { OBJECT_KINDS, objectView, docCtx, type ObjectCtx, type ObjectView, type ChemGeometry } from './objects'; +export { anchorPoint, arrowEnds } from './anchors'; +export { arrowShape, bentCurve, type Curve } from './arrow'; +export { computeStoich, findStep, type StoichGrid, type StoichRow } from './stoich'; +export { mediaCache, setMediaUrl, type MediaUrl } from './image'; +export { tlcLayout, spotGeom } from './tlc'; diff --git a/frontend/src/canvas/render/renderer.ts b/frontend/src/canvas/render/renderer.ts index bab9cc79..4bfdb901 100644 --- a/frontend/src/canvas/render/renderer.ts +++ b/frontend/src/canvas/render/renderer.ts @@ -1,17 +1,18 @@ -import type { Atom, Bond, DerivedFragment, DocObject, FormChemDocument, Fragment, Id, Page, Style, TextObject, CaptionObject } from '../../engine/model'; +import type { Atom, Bond, Derived, DerivedFragment, DocObject, FormChemDocument, Fragment, Id, Page, Style, TextObject, CaptionObject } from '../../engine/model'; import { resolveStyle } from '../../engine/model'; import { applyOps, touched } from '../../engine/ops'; import type { Hit, RenderDisplay, RenderState, Renderer, Viewport } from '../types'; import { atomColour, atomView, type AtomView } from './atom'; import { bondHalfWidth, bondView, circleView, segmentsCross, type BondCtx, type Cut } from './bond'; import { fmt, union, type Box, type V } from './geom'; +import { mediaCache } from './image'; import type { Neighbour, ShownStyle } from './label'; import { measure } from './measure'; +import { docChem, kindDef, objectDeps, type ChemGeometry, type ObjectCtx } from './objects'; import { MarkLayer, type Geometry, type Mark } from './overlay'; import { perceive, type Topology } from './rings'; -import { Keyed, setAttrs, svgEl } from './svg'; +import { Keyed, setAttrs, svgEl, type NodeSpec } from './svg'; import { stereoMarks } from './stereo'; -import { textView } from './text'; import { implicitHydrogens } from './valence'; interface AtomRec { ref: Atom; h: number; view: AtomView } @@ -36,18 +37,19 @@ interface FragRec { circleNodes: Keyed; } -interface TextRec { ref: DocObject; styleRefs: unknown[]; style: Style; styleKey: string; epoch: number; box: Box; node: SVGGElement } +interface ObjRec { ref: DocObject; styleRefs: unknown[]; style: Style; styleKey: string; epoch: number; deps: unknown[]; box: Box | null } type TextLike = TextObject | CaptionObject; -export interface RenderStats { fragments: number; atoms: number; bonds: number; patched: number; ms: number } +export interface RenderStats { fragments: number; atoms: number; bonds: number; objects: number; patched: number; ms: number } export interface FormChemRenderer extends Renderer { setPage(id: Id | null): void; stats(): RenderStats; + objectBox(id: Id): Box | null; } -const LAYERS = ['page', 'bonds', 'atoms', 'text', 'stereo', 'selection', 'hover', 'warnings', 'preview'] as const; +const LAYERS = ['page', 'objects', 'bonds', 'atoms', 'text', 'stereo', 'selection', 'hover', 'warnings', 'preview'] as const; type LayerName = (typeof LAYERS)[number]; function effectiveDoc(state: RenderState): FormChemDocument { @@ -142,14 +144,18 @@ export function createRenderer(): FormChemRenderer { let doc: FormChemDocument | null = null; let order: Id[] = []; const frags = new Map(); - const texts = new Map(); + const texts = new Map(); let textNodes: Keyed | null = null; + const objs = new Map(); + let objNodes: Keyed | null = null; + let derivedNow: Derived | null = null; + let mediaWatch: (() => void) | null = null; let selection: MarkLayer | null = null; let hover: MarkLayer | null = null; let warnings: MarkLayer | null = null; let preview: MarkLayer | null = null; let overlayInputs: unknown[] = []; - let stats: RenderStats = { fragments: 0, atoms: 0, bonds: 0, patched: 0, ms: 0 }; + let stats: RenderStats = { fragments: 0, atoms: 0, bonds: 0, objects: 0, patched: 0, ms: 0 }; let fontWatch: (() => void) | null = null; let display: RenderDisplay | undefined; let stereoNodes: Keyed | null = null; @@ -378,16 +384,46 @@ export function createRenderer(): FormChemRenderer { frags.delete(id); } - function syncText(id: Id, obj: TextLike): number { - const prev = texts.get(id); + const chem: ChemGeometry = { + atomPos: (f, a) => geometry.atomPos(f, a) ?? (doc ? docChem(doc).atomPos(f, a) : null), + lonePair: (f, a, i) => frags.get(f)?.atoms.get(a)?.view.pairs[i] ?? null, + bondLength: (f) => frags.get(f)?.style.bond_length ?? (doc ? docChem(doc).bondLength(f) : 14.4), + }; + + const ctxFor = (obj: DocObject, style: Style): ObjectCtx => ({ + doc: doc!, + style, + colour: obj.color ?? style.foreground, + chem, + derived: derivedNow, + boxOf: (id) => geometry.objectBox(id), + media: (m) => mediaCache.ref(doc!, m), + }); + + function syncObject(id: Id, obj: DocObject, recs: Map, nodes: Keyed): number { + const def = kindDef(obj.kind); + if (!def) { + recs.delete(id); + nodes.drop(id); + return 0; + } + const prev = recs.get(id); const st = styleFor(doc!, obj, prev); - if (prev && prev.ref === obj && prev.styleKey === st.styleKey && prev.epoch === measure.epoch) return 0; - const view = textView(obj, st.style, obj.color ?? st.style.foreground); - const node = textNodes!.get(id); - texts.set(id, { ref: obj, styleRefs: st.styleRefs, style: st.style, styleKey: st.styleKey, epoch: measure.epoch, box: view.box, node }); - return textNodes!.patch(id, view.specs) ? 1 : 0; + const deps = objectDeps(obj, doc!); + if (def.derived) deps.push(derivedNow); + if (prev && prev.ref === obj && prev.styleKey === st.styleKey && prev.epoch === measure.epoch && sameList(prev.deps, deps)) return 0; + let view: { specs: NodeSpec[]; box: Box | null }; + try { + view = def.view(obj as never, ctxFor(obj, st.style)); + } catch { + view = { specs: [], box: null }; + } + recs.set(id, { ref: obj, styleRefs: st.styleRefs, style: st.style, styleKey: st.styleKey, epoch: measure.epoch, deps, box: view.box }); + return nodes.patch(id, view.specs) ? 1 : 0; } + const syncText = (id: Id, obj: TextLike): number => syncObject(id, obj, texts, textNodes!); + function contentBounds(d: FormChemDocument, ids: readonly Id[]): Box | null { const boxes: Box[] = []; for (const id of ids) { @@ -428,7 +464,7 @@ export function createRenderer(): FormChemRenderer { return p && q ? [[p.x, p.y] as V, [q.x, q.y] as V] : null; }, objectBox(id) { - const t = texts.get(id); + const t = texts.get(id) ?? objs.get(id); if (t) return t.box; const rec = frags.get(id); if (rec?.frag) { @@ -494,7 +530,7 @@ export function createRenderer(): FormChemRenderer { if (state.preview?.length) { const t = touched(state.preview); for (const [oid, r] of t.objects) { - if (!frags.has(oid) && !texts.has(oid)) continue; + if (!frags.has(oid) && !texts.has(oid) && !objs.has(oid)) continue; if (r.whole && !r.atoms.size && !r.bonds.size) pv.push({ kind: 'object', id: oid }); for (const a of r.atoms) if (d.objects[oid] && (d.objects[oid] as Fragment).atoms?.[a]) pv.push({ kind: 'atom', frag: oid, id: a }); for (const b of r.bonds) if (d.objects[oid] && (d.objects[oid] as Fragment).bonds?.[b]) pv.push({ kind: 'bond', frag: oid, id: b }); @@ -527,6 +563,7 @@ export function createRenderer(): FormChemRenderer { const d = effectiveDoc(state); doc = d; display = state.display; + derivedNow = state.derived; const page = d.pages.find((p) => p.id === pageId) ?? d.pages[0]; const ids = page ? flatten(d, page.order) : []; let patched = 0; @@ -535,11 +572,12 @@ export function createRenderer(): FormChemRenderer { for (const id of ids) { const o = d.objects[id]; live.add(id); - if (o.kind === 'fragment') { - patched += syncFragment(id, o, state.derived?.fragments[id], fresh); - } else if (o.kind === 'text' || o.kind === 'caption') { - patched += syncText(id, o); - } + if (o.kind === 'fragment') patched += syncFragment(id, o, state.derived?.fragments[id], fresh); + } + for (const id of ids) { + const o = d.objects[id]; + if (o.kind === 'text' || o.kind === 'caption') patched += syncText(id, o); + else if (o.kind !== 'fragment') patched += syncObject(id, o, objs, objNodes!); } for (const id of [...frags.keys()]) if (!live.has(id) || d.objects[id]?.kind !== 'fragment') dropFragment(id); for (const id of [...texts.keys()]) { @@ -549,6 +587,13 @@ export function createRenderer(): FormChemRenderer { textNodes!.drop(id); } } + for (const id of [...objs.keys()]) { + const k = d.objects[id]?.kind; + if (!live.has(id) || !k || k === 'fragment' || k === 'text' || k === 'caption') { + objs.delete(id); + objNodes!.drop(id); + } + } if (!sameList(ids, order)) { order = ids; for (const id of ids) { @@ -559,12 +604,14 @@ export function createRenderer(): FormChemRenderer { } const t = textNodes!.nodes.get(id); if (t) layers.text.appendChild(t.node); + const g = objNodes!.nodes.get(id); + if (g) layers.objects.appendChild(g.node); } } if (page) syncPage(d, page); syncOverlays(state, d); syncStereo(state, d); - stats = { fragments: frags.size, atoms: 0, bonds: 0, patched, ms: performance.now() - t0 }; + stats = { fragments: frags.size, atoms: 0, bonds: 0, objects: objs.size + texts.size, patched, ms: performance.now() - t0 }; } function watchFonts(): void { @@ -598,6 +645,10 @@ export function createRenderer(): FormChemRenderer { pageRect = svgEl('rect', { class: 'fc-page' }); layers.page.appendChild(pageRect); textNodes = new Keyed(layers.text, (id) => svgEl('g', { class: 'fc-text-obj', 'data-id': id })); + objNodes = new Keyed(layers.objects, (id) => svgEl('g', { class: 'fc-obj', 'data-id': id })); + mediaWatch = mediaCache.subscribe(() => { + if (last) render(last); + }); stereoNodes = new Keyed(layers.stereo, (id) => svgEl('g', { class: 'fc-stereo-mark', 'data-id': id })); selection = new MarkLayer(layers.selection, 'fc-sel'); hover = new MarkLayer(layers.hover, 'fc-hover'); @@ -621,6 +672,10 @@ export function createRenderer(): FormChemRenderer { const b = frags.get(frag)?.atoms.get(atom)?.view.box; return b ? { x: b.x, y: b.y, w: b.w, h: b.h } : null; }, + objectBox(id: Id): Box | null { + const b = geometry.objectBox(id); + return b ? { x: b.x, y: b.y, w: b.w, h: b.h } : null; + }, setPage(id: Id | null): void { if (id === pageId) return; pageId = id; @@ -637,11 +692,16 @@ export function createRenderer(): FormChemRenderer { destroy(): void { fontWatch?.(); fontWatch = null; + mediaWatch?.(); + mediaWatch = null; root?.remove(); svg?.classList.remove('fc-canvas'); svg?.style.removeProperty('--fc-zoom'); frags.clear(); texts.clear(); + objs.clear(); + objNodes = null; + derivedNow = null; order = []; overlayInputs = []; stereoInputs = []; From de5fcd528d23e12eb806fce02300483603765b2b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:14:24 -0500 Subject: [PATCH 041/279] fix(render): keep TLC Rf labels from covering neighbouring lanes (0.5.0) On narrow plates an Rf value that does not fit beside its spot moves to the plate's right edge, once per value, and labels use a smaller size. --- frontend/src/canvas/render/tlc.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/frontend/src/canvas/render/tlc.ts b/frontend/src/canvas/render/tlc.ts index e2698c81..de056b3b 100644 --- a/frontend/src/canvas/render/tlc.ts +++ b/frontend/src/canvas/render/tlc.ts @@ -1,5 +1,6 @@ import type { TlcObject, TlcSpot } from '../../engine/model'; import { fmt, union, type Box } from './geom'; +import { measure } from './measure'; import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; import { label } from './paint'; import type { Attrs, NodeSpec } from './svg'; @@ -74,21 +75,31 @@ function tlcView(obj: TlcObject, ctx: ObjectCtx): ObjectView { const boxes: Box[] = [{ x: x - lw / 2, y: y - lw / 2, w: w + lw, h: h + lw }]; const font = ctx.style.caption_font; const tick = Math.min(2, lay.laneW * 0.2); + const rfSize = font.size * 0.6; + const margin = new Set(); + const rfLabel = (text: string, at: readonly [number, number]): void => { + const lab = label(text, at, font, rfSize, c, 'start', { cls: 'fc-text fc-rf' }); + specs.push(lab.spec); + boxes.push(lab); + }; obj.lanes.forEach((lane, i) => { const lx = lay.laneX[i]; specs.push(ln(lx, lay.originY - tick, lx, lay.originY + tick)); for (const spot of lane.spots) { const s = spotGeom(spot, lx, lay); specs.push(...spotSpecs(obj, spot, s, ctx)); - if (obj.show_rf) { - const size = font.size * 0.7; - const lab = label(spot.rf.toFixed(2), [s.cx + s.rx + 1.2, s.cy + size * 0.35], font, size, c); - specs.push(lab.spec); - boxes.push(lab); + if (!obj.show_rf) continue; + const text = spot.rf.toFixed(2); + const room = lay.laneW / 2 - s.rx - 1; + if (measure.width(text, rfSize, font.family) <= room) rfLabel(text, [s.cx + s.rx + 0.8, s.cy + rfSize * 0.35]); + else if (!margin.has(text)) { + margin.add(text); + specs.push(ln(x + w, s.cy, x + w + 1.5, s.cy)); + rfLabel(text, [x + w + 2.2, s.cy + rfSize * 0.35]); } } if (lane.label) { - const size = font.size * 0.8; + const size = font.size * 0.7; const lab = label(lane.label, [lx, y + h + size * 1.1], font, size, c, 'middle'); specs.push(lab.spec); boxes.push(lab); From aadf038ac5a860489eec81633a6bac3802414ec6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:58:20 -0500 Subject: [PATCH 042/279] feat(tools): add rectangle, rounded rectangle, ellipse and polygon tools (0.5.0) Shapes are drawn by dragging a box (Shift square, Alt from the centre) or placed at a default size by a click, on a shared drag-to-size base that the other annotation tools reuse; each gesture is one transaction. --- frontend/src/canvas/tools/index.ts | 6 + frontend/src/canvas/tools/objects.ts | 186 +++++++++++++++++++++++++++ frontend/src/canvas/tools/shape.ts | 32 +++++ 3 files changed, 224 insertions(+) create mode 100644 frontend/src/canvas/tools/objects.ts create mode 100644 frontend/src/canvas/tools/shape.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index 170598f0..fe764ff7 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -6,6 +6,7 @@ import { EraserTool } from './eraser'; import { ElementTool, LabelTool, TextTool } from './label'; import { RingTool } from './ring'; import { SelectTool } from './select'; +import { ShapeTool } from './shape'; import { HandTool, ZoomTool } from './view'; const bond = (kind: BondKindId, label: string, icon: string, keys?: string[]): ToolDef => ({ @@ -50,6 +51,10 @@ export const TOOLS: ToolDef[] = [ { id: 'label', label: 'Atom label', icon: 'atomLabel', group: 'atom', keys: ['A'], create: () => new LabelTool() }, { id: 'text', label: 'Text', icon: 'textBox', group: 'text', keys: ['T'], create: () => new TextTool() }, { id: 'eraser', label: 'Eraser', icon: 'eraser', group: 'eraser', keys: ['E'], create: () => new EraserTool() }, + { id: 'shape-rect', label: 'Rectangle', icon: 'shapes', group: 'shape', create: () => new ShapeTool('shape-rect', 'rect') }, + { id: 'shape-round-rect', label: 'Rounded rectangle', icon: 'shapeRoundRect', group: 'shape', create: () => new ShapeTool('shape-round-rect', 'round_rect') }, + { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, + { id: 'shape-polygon', label: 'Polygon', icon: 'shapePolygon', group: 'shape', create: () => new ShapeTool('shape-polygon', 'polygon') }, { id: 'hand', label: 'Hand', icon: 'hand', group: 'hand', keys: ['H'], create: () => new HandTool() }, { id: 'zoom', label: 'Zoom', icon: 'zoomIn', group: 'zoom', keys: ['Z'], create: () => new ZoomTool() }, ]; @@ -64,6 +69,7 @@ export { EraserTool } from './eraser'; export { ElementTool, LabelTool, TextTool } from './label'; export { RingTool } from './ring'; export { SelectTool } from './select'; +export { ShapeTool } from './shape'; export { HandTool, ZoomTool } from './view'; export { HOVER_KEY_MAP, hoverKey, TWO_LETTER_MS } from './hotkeys'; export * from './transform'; diff --git a/frontend/src/canvas/tools/objects.ts b/frontend/src/canvas/tools/objects.ts new file mode 100644 index 00000000..026b24f9 --- /dev/null +++ b/frontend/src/canvas/tools/objects.ts @@ -0,0 +1,186 @@ +import { isFragment, newId, type Bounds, type DocObject, type FormChemDocument, type Fragment, type Id, type Point } from '../../engine/model'; +import { angleFrom, dist, polar, snapAngle, type Rect } from '../geom'; +import type { Hit, Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, moved, objectBounds, previewDraft, topLevelObjects } from './common'; +import type { Draft } from './draft'; + +export const SNAP_STEP = 15; +export const MIN_BOX = 2; + +export const objectId = (): Id => newId('o'); +export const itemId = (): Id => newId('l'); + +export const clicks = (p: ToolPointer): number => (p as ToolPointer & { clicks?: number }).clicks ?? 1; + +export function snapEnd(from: Point, to: Point, step = SNAP_STEP): Point { + const l = dist(from, to); + if (l < 1e-9) return to; + return polar(from, snapAngle(angleFrom(from, to), step), l); +} + +export function boxFrom(a: Point, b: Point, opts: { square?: boolean; centre?: boolean } = {}): Rect { + let dx = b[0] - a[0]; + let dy = b[1] - a[1]; + if (opts.square) { + const s = Math.max(Math.abs(dx), Math.abs(dy)); + dx = Math.sign(dx || 1) * s; + dy = Math.sign(dy || 1) * s; + } + if (opts.centre) { + const w = Math.max(MIN_BOX, 2 * Math.abs(dx)); + const h = Math.max(MIN_BOX, 2 * Math.abs(dy)); + return { x: a[0] - w / 2, y: a[1] - h / 2, w, h }; + } + return { x: Math.min(a[0], a[0] + dx), y: Math.min(a[1], a[1] + dy), w: Math.max(MIN_BOX, Math.abs(dx)), h: Math.max(MIN_BOX, Math.abs(dy)) }; +} + +export const boxAround = (c: Point, w: number, h: number): Rect => ({ x: c[0] - w / 2, y: c[1] - h / 2, w, h }); + +export const inflateRect = (r: Rect, d: number): Rect => ({ x: r.x - d, y: r.y - d, w: r.w + 2 * d, h: r.h + 2 * d }); + +export function fragmentBox(frag: Fragment): Bounds | null { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const a of Object.values(frag.atoms)) { + x0 = Math.min(x0, a.x); y0 = Math.min(y0, a.y); x1 = Math.max(x1, a.x); y1 = Math.max(y1, a.y); + } + return x0 === Infinity ? null : { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} + +export function fragmentOfHit(doc: FormChemDocument, h: Hit): Fragment | null { + if (h.kind === 'atom' || h.kind === 'bond') { + const f = doc.objects[h.frag]; + return isFragment(f) ? f : null; + } + if (h.kind === 'object') { + const f = doc.objects[h.object]; + return isFragment(f) ? f : null; + } + return null; +} + +export function fragmentAt(doc: FormChemDocument, page: Id, p: Point, pad: number): Fragment | null { + let best: Fragment | null = null; + let bestArea = Infinity; + for (const id of topLevelObjects(doc, page)) { + const o = doc.objects[id]; + if (!isFragment(o) || o.hidden || o.locked) continue; + const b = fragmentBox(o); + if (!b) continue; + const r = inflateRect(b, pad); + if (p[0] < r.x || p[0] > r.x + r.w || p[1] < r.y || p[1] > r.y + r.h) continue; + const area = r.w * r.h; + if (area < bestArea) { bestArea = area; best = o; } + } + return best; +} + +export function parentGroups(doc: FormChemDocument): Map { + const out = new Map(); + for (const o of Object.values(doc.objects)) if (o.kind === 'group') for (const c of o.children) out.set(c, o.id); + return out; +} + +export function outermostGroup(doc: FormChemDocument, id: Id): Id | null { + const parent = parentGroups(doc); + let top = id; + let found: Id | null = null; + const seen = new Set(); + while (parent.has(top) && !seen.has(top)) { + seen.add(top); + top = parent.get(top)!; + found = top; + } + return found; +} + +export function groupHit(doc: FormChemDocument, h: Hit): Hit { + const id = h.kind === 'atom' || h.kind === 'bond' ? h.frag : h.kind === 'object' ? h.object : null; + if (!id || h.kind === 'none') return h; + const g = outermostGroup(doc, id); + return g ? { kind: 'object', object: g, d: h.d } : h; +} + +export function boundsOf(doc: FormChemDocument, id: Id): Rect | null { + const o = doc.objects[id]; + return o ? objectBounds(doc, o) : null; +} + +export function addObjects(d: Draft, ...objs: DocObject[]): void { + for (const o of objs) d.addObject(o); +} + +export function ensureMediaMap(d: Draft): void { + if (!d.doc.media) d.push({ op: 'set', path: ['media'], value: {} }); +} + +export abstract class BoxTool implements Tool { + readonly cursor: string = 'crosshair'; + protected start: ToolPointer | null = null; + protected oid: Id = ''; + + constructor(readonly id: string, protected readonly label: string) {} + + protected abstract build(ctx: ToolContext, d: Draft, r: Rect, p: ToolPointer, dragged: boolean): boolean; + + protected abstract clickBox(ctx: ToolContext, at: Point): Rect; + + protected click(_ctx: ToolContext, _p: ToolPointer): boolean { + return false; + } + + deactivate(ctx: ToolContext): void { + this.cancel(ctx); + } + + down(_ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + this.start = p; + this.oid = objectId(); + } + + move(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + if (!s) { + ctx.setHover(p.hit); + return; + } + if (!moved(s, p)) return; + const d = draftFor(ctx); + previewDraft(ctx, this.build(ctx, d, this.rect(s, p), p, true) ? d : null); + } + + up(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + this.start = null; + if (!s) return; + const dragged = moved(s, p); + if (!dragged && this.click(ctx, s)) { + ctx.client.preview(null); + return; + } + const d = draftFor(ctx); + const r = dragged ? this.rect(s, p) : this.clickBox(ctx, s.doc); + if (!this.build(ctx, d, r, p, dragged)) { + ctx.client.preview(null); + return; + } + commitDraft(ctx, this.label, d); + } + + key(ctx: ToolContext, e: KeyboardEvent): boolean { + if (e.key === 'Escape' && this.start) { + this.cancel(ctx); + return true; + } + return false; + } + + protected rect(s: ToolPointer, p: ToolPointer): Rect { + return boxFrom(s.doc, p.doc, { square: p.shift, centre: p.alt }); + } + + protected cancel(ctx: ToolContext): void { + if (this.start) ctx.client.preview(null); + this.start = null; + } +} diff --git a/frontend/src/canvas/tools/shape.ts b/frontend/src/canvas/tools/shape.ts new file mode 100644 index 00000000..a742735a --- /dev/null +++ b/frontend/src/canvas/tools/shape.ts @@ -0,0 +1,32 @@ +import type { Point, ShapeObject } from '../../engine/model'; +import type { Rect } from '../geom'; +import type { ToolContext, ToolPointer } from '../types'; +import type { Draft } from './draft'; +import { BoxTool, boxAround } from './objects'; + +export type ShapeGeom = 'rect' | 'round_rect' | 'ellipse' | 'polygon'; + +export const POLYGON_SIDES = 6; +export const SHAPE_CLICK_BONDS = 3; + +export function shapeObject(id: string, geom: ShapeGeom, r: Rect, sides = POLYGON_SIDES): ShapeObject { + const o: ShapeObject = { id, kind: 'shape', geom, x: r.x, y: r.y, w: r.w, h: r.h, fill: null }; + if (geom === 'polygon') o.sides = Math.max(3, Math.min(12, Math.round(sides))); + return o; +} + +export class ShapeTool extends BoxTool { + constructor(id: string, readonly geom: ShapeGeom, readonly sides = POLYGON_SIDES) { + super(id, 'Add shape'); + } + + protected clickBox(ctx: ToolContext, at: Point): Rect { + const s = ctx.style().bond_length * SHAPE_CLICK_BONDS; + return boxAround(at, s, this.geom === 'rect' || this.geom === 'round_rect' ? s * 0.75 : s); + } + + protected build(_ctx: ToolContext, d: Draft, r: Rect, _p: ToolPointer, _dragged: boolean): boolean { + d.addObject(shapeObject(this.oid, this.geom, r, this.sides)); + return true; + } +} From 9f4a7452e49fd1ad276f6de74965095924f8d745 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:58:44 -0500 Subject: [PATCH 043/279] feat(tools): add reaction arrow tools for every straight arrow kind (0.5.0) Forward, equilibrium, retrosynthetic, resonance, no-go, dashed and plain arrows are drawn by dragging (Shift snaps to 15 degrees, Alt picks the alternate variant such as unbalanced equilibrium or the slashed no-go) or placed four bond lengths long by a click. --- frontend/src/canvas/tools/arrow.ts | 109 +++++++++++++++++++++++++++++ frontend/src/canvas/tools/index.ts | 17 +++++ 2 files changed, 126 insertions(+) create mode 100644 frontend/src/canvas/tools/arrow.ts diff --git a/frontend/src/canvas/tools/arrow.ts b/frontend/src/canvas/tools/arrow.ts new file mode 100644 index 00000000..ef34469e --- /dev/null +++ b/frontend/src/canvas/tools/arrow.ts @@ -0,0 +1,109 @@ +import type { ArrowHead, ArrowObject, ArrowType, Id, Point } from '../../engine/model'; +import { dist } from '../geom'; +import type { Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, moved, previewDraft } from './common'; +import type { Draft } from './draft'; +import { objectId, snapEnd } from './objects'; + +export type ArrowKind = 'forward' | 'equilibrium' | 'retro' | 'resonance' | 'nogo' | 'dashed' | 'plain'; + +export const ARROW_CLICK_BONDS = 4; + +export const ARROW_KINDS: Record = { + forward: { type: 'forward', alt: 'dashed' }, + equilibrium: { type: 'equilibrium', alt: 'equilibrium_unbalanced' }, + retro: { type: 'retro', alt: 'retro' }, + resonance: { type: 'resonance', alt: 'reversible' }, + nogo: { type: 'nogo_cross', alt: 'nogo_slash' }, + dashed: { type: 'dashed', alt: 'forward' }, + plain: { type: 'plain', alt: 'plain' }, +}; + +const HEADS: Partial> = { + forward: { head: 'full', tail: 'none' }, + dashed: { head: 'full', tail: 'none' }, + resonance: { head: 'full', tail: 'full' }, + reversible: { head: 'full', tail: 'full' }, + plain: { head: 'none', tail: 'none' }, +}; + +export function arrowObject(id: Id, type: ArrowType, tail: Point, head: Point): ArrowObject { + const o: ArrowObject = { id, kind: 'arrow', type, x1: tail[0], y1: tail[1], x2: head[0], y2: head[1] }; + const heads = HEADS[type]; + if (heads) { + o.head = heads.head; + o.tail = heads.tail; + } + if (type === 'dashed') o.dashed = true; + return o; +} + +export class ArrowTool implements Tool { + readonly cursor = 'crosshair'; + private start: ToolPointer | null = null; + private oid: Id = ''; + + constructor(readonly id: string, readonly kind: ArrowKind) {} + + deactivate(ctx: ToolContext): void { + this.cancel(ctx); + } + + down(_ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + this.start = p; + this.oid = objectId(); + } + + move(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + if (!s) { + ctx.setHover(p.hit); + return; + } + if (!moved(s, p)) return; + previewDraft(ctx, this.draft(ctx, s, p, true)); + } + + up(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + this.start = null; + if (!s) return; + const d = this.draft(ctx, s, p, moved(s, p)); + if (!d) { + ctx.client.preview(null); + return; + } + commitDraft(ctx, 'Add arrow', d); + } + + key(ctx: ToolContext, e: KeyboardEvent): boolean { + if (e.key === 'Escape' && this.start) { + this.cancel(ctx); + return true; + } + return false; + } + + typeFor(p: ToolPointer): ArrowType { + const k = ARROW_KINDS[this.kind]; + return p.alt ? k.alt : k.type; + } + + private draft(ctx: ToolContext, s: ToolPointer, p: ToolPointer, dragged: boolean): Draft | null { + const tail = s.doc; + let head: Point; + if (dragged) { + head = p.shift ? snapEnd(tail, p.doc) : p.doc; + if (dist(tail, head) < 1) return null; + } else head = [tail[0] + ctx.style().bond_length * ARROW_CLICK_BONDS, tail[1]]; + const d = draftFor(ctx); + d.addObject(arrowObject(this.oid, this.typeFor(p), tail, head)); + return d; + } + + private cancel(ctx: ToolContext): void { + if (this.start) ctx.client.preview(null); + this.start = null; + } +} diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index fe764ff7..07317c14 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -1,4 +1,5 @@ import type { Tool, ToolDef } from '../types'; +import { ArrowTool, type ArrowKind } from './arrow'; import { BondTool } from './bond'; import type { BondKindId } from './build'; import { ChainTool } from './chain'; @@ -27,6 +28,14 @@ const ring = (id: string, label: string, icon: string, keys?: string[]): ToolDef create: () => new RingTool(id), }); +const arrow = (kind: ArrowKind, label: string, icon: string): ToolDef => ({ + id: `arrow-${kind}`, + label, + icon, + group: 'arrow', + create: () => new ArrowTool(`arrow-${kind}`, kind), +}); + export const TOOLS: ToolDef[] = [ { id: 'select', label: 'Select', icon: 'cursor', group: 'select', keys: ['V'], create: () => new SelectTool('select') }, { id: 'lasso', label: 'Lasso', icon: 'lasso', group: 'select', keys: ['L'], create: () => new SelectTool('lasso', true) }, @@ -51,6 +60,13 @@ export const TOOLS: ToolDef[] = [ { id: 'label', label: 'Atom label', icon: 'atomLabel', group: 'atom', keys: ['A'], create: () => new LabelTool() }, { id: 'text', label: 'Text', icon: 'textBox', group: 'text', keys: ['T'], create: () => new TextTool() }, { id: 'eraser', label: 'Eraser', icon: 'eraser', group: 'eraser', keys: ['E'], create: () => new EraserTool() }, + arrow('forward', 'Reaction arrow', 'arrow'), + arrow('equilibrium', 'Equilibrium arrow', 'arrowEquilibrium'), + arrow('retro', 'Retrosynthetic arrow', 'arrowRetro'), + arrow('resonance', 'Resonance arrow', 'arrowResonance'), + arrow('nogo', 'No-go arrow', 'arrowNogo'), + arrow('dashed', 'Dashed arrow', 'arrowDashed'), + arrow('plain', 'Line arrow', 'arrowPlain'), { id: 'shape-rect', label: 'Rectangle', icon: 'shapes', group: 'shape', create: () => new ShapeTool('shape-rect', 'rect') }, { id: 'shape-round-rect', label: 'Rounded rectangle', icon: 'shapeRoundRect', group: 'shape', create: () => new ShapeTool('shape-round-rect', 'round_rect') }, { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, @@ -63,6 +79,7 @@ export const toolDef = (id: string): ToolDef | undefined => TOOLS.find((t) => t. export const elementTool = (symbol: string): Tool => new ElementTool(symbol); +export { ArrowTool, arrowObject, ARROW_KINDS, type ArrowKind } from './arrow'; export { BondTool } from './bond'; export { ChainTool } from './chain'; export { EraserTool } from './eraser'; From 78f29afd0aca77acdc9ca5ce971d3155faacf37f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:59:23 -0500 Subject: [PATCH 044/279] feat(tools): add anchored electron-pushing and fishhook arrow tools (0.5.0) A drag from an atom, lone pair or bond to an atom, bond or the gap between two atoms anchors both ends (0.15 bond lengths short) with a 90 degree arc bulging away from nearby atoms; anywhere else it falls back to a free arc. Alt flips the bulge, Shift puts a fishhook barb on the right. --- frontend/src/canvas/tools/curved.ts | 233 ++++++++++++++++++++++++++++ frontend/src/canvas/tools/index.ts | 4 + 2 files changed, 237 insertions(+) create mode 100644 frontend/src/canvas/tools/curved.ts diff --git a/frontend/src/canvas/tools/curved.ts b/frontend/src/canvas/tools/curved.ts new file mode 100644 index 00000000..d1fe81e6 --- /dev/null +++ b/frontend/src/canvas/tools/curved.ts @@ -0,0 +1,233 @@ +import { isFragment, type Anchor, type ArrowObject, type FormChemDocument, type Fragment, type Id, type Point } from '../../engine/model'; +import { add, dist, dot, lerp, mid, norm, scale, sub } from '../geom'; +import type { Hit, Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, moved, previewDraft } from './common'; +import type { Draft } from './draft'; +import { objectId } from './objects'; + +export type CurvedHead = 'full' | 'half'; + +export const CURVED_BEND = 90; +export const MAX_BEND = 345; +export const ANCHOR_GAP = 0.15; +const BETWEEN_REACH = 0.35; +const BETWEEN_SPAN = 3; +const SIDE_REACH = 3; + +export interface ArrowEnd { at: Point; anchor?: Anchor } + +export const leftOf = (tail: Point, head: Point): Point => { + const d = norm(sub(head, tail)); + return [d[1], -d[0]]; +}; + +export function arcMid(tail: Point, head: Point, bend: number): Point { + const c = dist(tail, head); + const m = mid(tail, head); + if (!bend || c < 1e-9) return m; + const s = (c / 2) * Math.tan((bend * Math.PI) / 720); + return add(m, scale(leftOf(tail, head), s)); +} + +export function bendThrough(tail: Point, head: Point, p: Point): number { + const c = dist(tail, head); + if (c < 1e-9) return 0; + const h = dot(sub(p, mid(tail, head)), leftOf(tail, head)); + const deg = (4 * Math.atan((2 * h) / c) * 180) / Math.PI; + return Math.max(-MAX_BEND, Math.min(MAX_BEND, deg)); +} + +export function anchorPoint(doc: FormChemDocument, a: Anchor): Point | null { + const f = doc.objects[a.object]; + if (!isFragment(f)) return null; + if ('bond' in a) { + const b = f.bonds[a.bond]; + const p = b && f.atoms[b.a]; + const q = b && f.atoms[b.b]; + return p && q ? mid([p.x, p.y], [q.x, q.y]) : null; + } + if ('between' in a) { + const p = f.atoms[a.between[0]]; + const q = f.atoms[a.between[1]]; + return p && q ? mid([p.x, p.y], [q.x, q.y]) : null; + } + const at = f.atoms[a.atom]; + return at ? [at.x, at.y] : null; +} + +const sameAnchor = (a?: Anchor, b?: Anchor): boolean => !!a && !!b && JSON.stringify(a) === JSON.stringify(b); + +function betweenAnchor(frag: Fragment, p: Point, bond: number): ArrowEnd | null { + const atoms = Object.values(frag.atoms); + let best: ArrowEnd | null = null; + let bestD = BETWEEN_REACH * bond; + for (let i = 0; i < atoms.length; i++) { + for (let j = i + 1; j < atoms.length; j++) { + const a = atoms[i], b = atoms[j]; + const span = dist([a.x, a.y], [b.x, b.y]); + if (span > BETWEEN_SPAN * bond || span < 0.5 * bond) continue; + const m = mid([a.x, a.y], [b.x, b.y]); + const d = dist(m, p); + if (d < bestD) { + bestD = d; + best = { at: m, anchor: { object: frag.id, between: [a.id, b.id] } }; + } + } + } + return best; +} + +export function endAt(doc: FormChemDocument, page: Id, h: Hit, p: Point, bond: number, opts: { tail: boolean; atomOnly?: boolean }): ArrowEnd { + if (h.kind === 'atom') { + const f = doc.objects[h.frag]; + const a = isFragment(f) ? f.atoms[h.atom] : undefined; + if (a) { + const anchor: Anchor = opts.tail && !opts.atomOnly && (a.lone_pairs ?? 0) > 0 ? { object: h.frag, atom: a.id, lone_pair: 0 } : { object: h.frag, atom: a.id }; + return { at: [a.x, a.y], anchor }; + } + } + if (h.kind === 'bond') { + const anchor: Anchor = { object: h.frag, bond: h.bond }; + const at = anchorPoint(doc, anchor); + if (at) return { at, anchor }; + } + if (!opts.tail && h.kind === 'none') { + const pg = doc.pages.find((q) => q.id === page) ?? doc.pages[0]; + let best: ArrowEnd | null = null; + for (const id of pg.order) { + const f = doc.objects[id]; + if (!isFragment(f)) continue; + const e = betweenAnchor(f, p, bond); + if (e && (!best || dist(e.at, p) < dist(best.at, p))) best = e; + } + if (best) return best; + } + return { at: p }; +} + +function anchoredAtoms(a?: Anchor): Id[] { + if (!a) return []; + if ('atom' in a) return [a.atom]; + if ('between' in a) return [...a.between]; + return []; +} + +export function defaultSide(doc: FormChemDocument, tail: ArrowEnd, head: ArrowEnd, bond: number): 1 | -1 { + const m = mid(tail.at, head.at); + const n = leftOf(tail.at, head.at); + const skip = new Set([...anchoredAtoms(tail.anchor), ...anchoredAtoms(head.anchor)]); + for (const a of [tail.anchor, head.anchor]) { + if (a && 'bond' in a) { + const f = doc.objects[a.object]; + const b = isFragment(f) ? f.bonds[a.bond] : undefined; + if (b) { skip.add(b.a); skip.add(b.b); } + } + } + let best: Point | null = null; + let bestD = SIDE_REACH * bond; + for (const o of Object.values(doc.objects)) { + if (!isFragment(o)) continue; + for (const a of Object.values(o.atoms)) { + if (skip.has(a.id)) continue; + const d = dist([a.x, a.y], m); + if (d < bestD) { bestD = d; best = [a.x, a.y]; } + } + } + return best && dot(sub(best, m), n) > 0 ? -1 : 1; +} + +export function curvedArrow(id: Id, head: CurvedHead, tail: ArrowEnd, tip: ArrowEnd, bend: number, bond: number, barbRight = false): ArrowObject { + const gap = ANCHOR_GAP * bond; + const span = dist(tail.at, tip.at); + const k = span > 3 * gap ? gap / span : 0; + const t = tail.anchor ? lerp(tail.at, tip.at, k) : tail.at; + const h = tip.anchor ? lerp(tip.at, tail.at, k) : tip.at; + const o: ArrowObject = { + id, + kind: 'arrow', + type: head === 'full' ? 'curved' : 'fishhook', + x1: t[0], y1: t[1], x2: h[0], y2: h[1], + bend, + head: head === 'full' ? 'full' : barbRight ? 'half_right' : 'half_left', + tail: 'none', + }; + if (tail.anchor || tip.anchor) { + o.anchors = {}; + if (tail.anchor) o.anchors.tail = tail.anchor; + if (tip.anchor) o.anchors.head = tip.anchor; + } + return o; +} + +export class CurvedArrowTool implements Tool { + readonly cursor = 'crosshair'; + private start: { p: ToolPointer; end: ArrowEnd } | null = null; + private oid: Id = ''; + + constructor(readonly id: string, readonly head: CurvedHead) {} + + deactivate(ctx: ToolContext): void { + this.cancel(ctx); + } + + down(ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + const doc = ctx.client.doc; + this.start = { p, end: endAt(doc, ctx.page(), p.hit, p.doc, ctx.style().bond_length, { tail: true, atomOnly: p.mod }) }; + this.oid = objectId(); + } + + move(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + if (!s) { + ctx.setHover(p.hit); + return; + } + ctx.setHover(p.hit); + if (!moved(s.p, p)) return; + previewDraft(ctx, this.draft(ctx, p)); + } + + up(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + if (!s) return; + if (!moved(s.p, p)) { + this.cancel(ctx); + return; + } + const d = this.draft(ctx, p); + this.start = null; + if (!d) { + ctx.client.preview(null); + return; + } + commitDraft(ctx, this.head === 'full' ? 'Add electron-pushing arrow' : 'Add fishhook arrow', d); + } + + key(ctx: ToolContext, e: KeyboardEvent): boolean { + if (e.key === 'Escape' && this.start) { + this.cancel(ctx); + return true; + } + return false; + } + + private draft(ctx: ToolContext, p: ToolPointer): Draft | null { + const s = this.start; + if (!s) return null; + const bond = ctx.style().bond_length; + const doc = ctx.client.doc; + let tip = endAt(doc, ctx.page(), p.hit, p.doc, bond, { tail: false }); + if (sameAnchor(tip.anchor, s.end.anchor)) tip = { at: p.doc }; + if (dist(s.end.at, tip.at) < 1) return null; + const side = defaultSide(doc, s.end, tip, bond) * (p.alt ? -1 : 1); + const d = draftFor(ctx, [s.end.anchor?.object ?? '', tip.anchor?.object ?? ''].filter(Boolean)); + d.addObject(curvedArrow(this.oid, this.head, s.end, tip, side * CURVED_BEND, bond, p.shift)); + return d; + } + + private cancel(ctx: ToolContext): void { + if (this.start) ctx.client.preview(null); + this.start = null; + } +} diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index 07317c14..9b583615 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -3,6 +3,7 @@ import { ArrowTool, type ArrowKind } from './arrow'; import { BondTool } from './bond'; import type { BondKindId } from './build'; import { ChainTool } from './chain'; +import { CurvedArrowTool } from './curved'; import { EraserTool } from './eraser'; import { ElementTool, LabelTool, TextTool } from './label'; import { RingTool } from './ring'; @@ -67,6 +68,8 @@ export const TOOLS: ToolDef[] = [ arrow('nogo', 'No-go arrow', 'arrowNogo'), arrow('dashed', 'Dashed arrow', 'arrowDashed'), arrow('plain', 'Line arrow', 'arrowPlain'), + { id: 'arrow-curved', label: 'Electron-pushing arrow', icon: 'arrowCurved', group: 'arrow', create: () => new CurvedArrowTool('arrow-curved', 'full') }, + { id: 'arrow-fishhook', label: 'Fishhook arrow', icon: 'arrowFishhook', group: 'arrow', create: () => new CurvedArrowTool('arrow-fishhook', 'half') }, { id: 'shape-rect', label: 'Rectangle', icon: 'shapes', group: 'shape', create: () => new ShapeTool('shape-rect', 'rect') }, { id: 'shape-round-rect', label: 'Rounded rectangle', icon: 'shapeRoundRect', group: 'shape', create: () => new ShapeTool('shape-round-rect', 'round_rect') }, { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, @@ -82,6 +85,7 @@ export const elementTool = (symbol: string): Tool => new ElementTool(symbol); export { ArrowTool, arrowObject, ARROW_KINDS, type ArrowKind } from './arrow'; export { BondTool } from './bond'; export { ChainTool } from './chain'; +export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; export { ElementTool, LabelTool, TextTool } from './label'; export { RingTool } from './ring'; From 7ada76c4e98bbd17ac459e84567c0f5067a78eaa Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 19:59:38 -0500 Subject: [PATCH 045/279] feat(tools): add plus, equals and adduct dot tools (0.5.0) A click places the symbol; it snaps vertically onto the centre line of a reaction component within three bond lengths (Alt places it exactly), as one transaction. --- frontend/src/canvas/tools/index.ts | 5 ++++ frontend/src/canvas/tools/plus.ts | 47 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 frontend/src/canvas/tools/plus.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index 9b583615..fed4e251 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -6,6 +6,7 @@ import { ChainTool } from './chain'; import { CurvedArrowTool } from './curved'; import { EraserTool } from './eraser'; import { ElementTool, LabelTool, TextTool } from './label'; +import { PlusTool } from './plus'; import { RingTool } from './ring'; import { SelectTool } from './select'; import { ShapeTool } from './shape'; @@ -70,6 +71,9 @@ export const TOOLS: ToolDef[] = [ arrow('plain', 'Line arrow', 'arrowPlain'), { id: 'arrow-curved', label: 'Electron-pushing arrow', icon: 'arrowCurved', group: 'arrow', create: () => new CurvedArrowTool('arrow-curved', 'full') }, { id: 'arrow-fishhook', label: 'Fishhook arrow', icon: 'arrowFishhook', group: 'arrow', create: () => new CurvedArrowTool('arrow-fishhook', 'half') }, + { id: 'plus', label: 'Plus sign', icon: 'plus', group: 'symbol', create: () => new PlusTool('plus', 'plus') }, + { id: 'plus-equals', label: 'Equals sign', icon: 'equals', group: 'symbol', create: () => new PlusTool('plus-equals', 'equals') }, + { id: 'plus-dot', label: 'Adduct dot', icon: 'adductDot', group: 'symbol', create: () => new PlusTool('plus-dot', 'dot') }, { id: 'shape-rect', label: 'Rectangle', icon: 'shapes', group: 'shape', create: () => new ShapeTool('shape-rect', 'rect') }, { id: 'shape-round-rect', label: 'Rounded rectangle', icon: 'shapeRoundRect', group: 'shape', create: () => new ShapeTool('shape-round-rect', 'round_rect') }, { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, @@ -88,6 +92,7 @@ export { ChainTool } from './chain'; export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; export { ElementTool, LabelTool, TextTool } from './label'; +export { PlusTool } from './plus'; export { RingTool } from './ring'; export { SelectTool } from './select'; export { ShapeTool } from './shape'; diff --git a/frontend/src/canvas/tools/plus.ts b/frontend/src/canvas/tools/plus.ts new file mode 100644 index 00000000..03a5a4ce --- /dev/null +++ b/frontend/src/canvas/tools/plus.ts @@ -0,0 +1,47 @@ +import type { FormChemDocument, Id, PlusObject, Point } from '../../engine/model'; +import type { Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, objectBounds, topLevelObjects } from './common'; +import { objectId } from './objects'; + +export type PlusSymbol = NonNullable; + +const SNAP_ROW = 0.75; +const SNAP_GAP = 3; +const SNAP_KINDS = new Set(['fragment', 'group', 'text', 'caption', 'image']); + +export function reactionLine(doc: FormChemDocument, page: Id, at: Point, bond: number): number | null { + let best: number | null = null; + let bestD = SNAP_ROW * bond; + for (const id of topLevelObjects(doc, page)) { + const o = doc.objects[id]; + if (!o || o.hidden || !SNAP_KINDS.has(o.kind)) continue; + const r = objectBounds(doc, o); + if (!r) continue; + const gap = Math.max(r.x - at[0], 0, at[0] - (r.x + r.w)); + if (gap > SNAP_GAP * bond) continue; + const cy = r.y + r.h / 2; + const d = Math.abs(cy - at[1]); + if (d < bestD) { bestD = d; best = cy; } + } + return best; +} + +export class PlusTool implements Tool { + readonly cursor = 'crosshair'; + + constructor(readonly id: string, readonly symbol: PlusSymbol) {} + + move(ctx: ToolContext, p: ToolPointer): void { + ctx.setHover(p.hit); + } + + up(ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + const d = draftFor(ctx); + const y = p.alt ? null : reactionLine(d.doc, d.page, p.doc, ctx.style().bond_length); + const o: PlusObject = { id: objectId(), kind: 'plus', x: p.doc[0], y: y ?? p.doc[1] }; + if (this.symbol !== 'plus') o.symbol = this.symbol; + d.addObject(o); + commitDraft(ctx, 'Add plus sign', d); + } +} From 8aba28cbdb5d04eaa41211f29ccf4bafea79467b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:00:00 -0500 Subject: [PATCH 046/279] feat(tools): add round, square and curly bracket tools (0.5.0) Dragging a box around atoms records the enclosed fragment and atoms, and a pair crossing exactly two bonds becomes a repeat unit labelled n; a click on a structure brackets the whole fragment and a double-click on a bracket edits its label. --- frontend/src/canvas/tools/bracket.ts | 92 ++++++++++++++++++++++++++++ frontend/src/canvas/tools/index.ts | 5 ++ 2 files changed, 97 insertions(+) create mode 100644 frontend/src/canvas/tools/bracket.ts diff --git a/frontend/src/canvas/tools/bracket.ts b/frontend/src/canvas/tools/bracket.ts new file mode 100644 index 00000000..3239fa17 --- /dev/null +++ b/frontend/src/canvas/tools/bracket.ts @@ -0,0 +1,92 @@ +import { isFragment, type BracketObject, type FormChemDocument, type Id, type Point } from '../../engine/model'; +import { objectPath } from '../../engine/ops'; +import { inRect, type Rect } from '../geom'; +import type { ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, topLevelObjects } from './common'; +import type { Draft } from './draft'; +import { BoxTool, boxAround, clicks, fragmentBox, fragmentOfHit, inflateRect } from './objects'; + +export type BracketShape = BracketObject['shape']; + +export const BRACKET_PAD = 0.4; +export const BRACKET_CLICK_BONDS = 3; +export const REPEAT_LABEL = 'n'; + +export interface Enclosed { fragment: Id; atoms: Id[]; crossing: number } + +export function enclosed(doc: FormChemDocument, page: Id, r: Rect): Enclosed | null { + let found: Enclosed | null = null; + for (const id of topLevelObjects(doc, page)) { + const f = doc.objects[id]; + if (!isFragment(f)) continue; + const inside = new Set(Object.values(f.atoms).filter((a) => inRect([a.x, a.y], r)).map((a) => a.id)); + if (!inside.size) continue; + if (found) return null; + let crossing = 0; + for (const b of Object.values(f.bonds)) if (inside.has(b.a) !== inside.has(b.b)) crossing += 1; + found = { fragment: f.id, atoms: [...inside], crossing }; + } + return found; +} + +export function bracketObject(id: Id, shape: BracketShape, r: Rect, inside: Enclosed | null): BracketObject { + const o: BracketObject = { id, kind: 'bracket', shape, sides: 'both', x: r.x, y: r.y, w: r.w, h: r.h }; + if (inside) { + o.fragment = inside.fragment; + o.atoms = inside.atoms; + if (inside.crossing === 2) { + o.semantic = 'sru'; + o.label = REPEAT_LABEL; + } + } + return o; +} + +export function editBracketLabel(ctx: ToolContext, oid: Id): boolean { + const o = ctx.client.doc.objects[oid]; + if (!o || o.kind !== 'bracket') return false; + const before = o.label ?? ''; + ctx.editText([o.x + o.w, o.y + o.h], before, (text) => { + if (text === null) return; + const value = text.trim(); + if (value === before) return; + const d = draftFor(ctx, [oid]); + if (d.doc.objects[oid]?.kind !== 'bracket') return; + d.push(value ? { op: 'set', path: objectPath(oid, 'label'), value } : { op: 'set', path: objectPath(oid, 'label') }); + commitDraft(ctx, 'Set bracket label', d); + }); + return true; +} + +export class BracketTool extends BoxTool { + constructor(id: string, readonly shape: BracketShape) { + super(id, 'Add bracket'); + } + + protected click(ctx: ToolContext, p: ToolPointer): boolean { + const h = p.hit; + if (h.kind === 'object' && ctx.client.doc.objects[h.object]?.kind === 'bracket') { + if (clicks(p) >= 2) editBracketLabel(ctx, h.object); + return true; + } + const f = fragmentOfHit(ctx.client.doc, h); + if (!f) return false; + const b = fragmentBox(f); + if (!b) return false; + const r = inflateRect(b, BRACKET_PAD * ctx.style().bond_length); + const d = draftFor(ctx, [f.id]); + d.addObject(bracketObject(this.oid, this.shape, r, { fragment: f.id, atoms: Object.keys(f.atoms), crossing: 0 })); + commitDraft(ctx, this.label, d); + return true; + } + + protected clickBox(ctx: ToolContext, at: Point): Rect { + const s = ctx.style().bond_length * BRACKET_CLICK_BONDS; + return boxAround(at, s, s); + } + + protected build(_ctx: ToolContext, d: Draft, r: Rect, _p: ToolPointer, dragged: boolean): boolean { + d.addObject(bracketObject(this.oid, this.shape, r, dragged ? enclosed(d.doc, d.page, r) : null)); + return true; + } +} diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index fed4e251..ea16c566 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -1,6 +1,7 @@ import type { Tool, ToolDef } from '../types'; import { ArrowTool, type ArrowKind } from './arrow'; import { BondTool } from './bond'; +import { BracketTool } from './bracket'; import type { BondKindId } from './build'; import { ChainTool } from './chain'; import { CurvedArrowTool } from './curved'; @@ -74,6 +75,9 @@ export const TOOLS: ToolDef[] = [ { id: 'plus', label: 'Plus sign', icon: 'plus', group: 'symbol', create: () => new PlusTool('plus', 'plus') }, { id: 'plus-equals', label: 'Equals sign', icon: 'equals', group: 'symbol', create: () => new PlusTool('plus-equals', 'equals') }, { id: 'plus-dot', label: 'Adduct dot', icon: 'adductDot', group: 'symbol', create: () => new PlusTool('plus-dot', 'dot') }, + { id: 'bracket-round', label: 'Round brackets', icon: 'bracketRound', group: 'bracket', create: () => new BracketTool('bracket-round', 'round') }, + { id: 'bracket-square', label: 'Square brackets', icon: 'bracketSquare', group: 'bracket', create: () => new BracketTool('bracket-square', 'square') }, + { id: 'bracket-curly', label: 'Curly braces', icon: 'bracketCurly', group: 'bracket', create: () => new BracketTool('bracket-curly', 'curly') }, { id: 'shape-rect', label: 'Rectangle', icon: 'shapes', group: 'shape', create: () => new ShapeTool('shape-rect', 'rect') }, { id: 'shape-round-rect', label: 'Rounded rectangle', icon: 'shapeRoundRect', group: 'shape', create: () => new ShapeTool('shape-round-rect', 'round_rect') }, { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, @@ -88,6 +92,7 @@ export const elementTool = (symbol: string): Tool => new ElementTool(symbol); export { ArrowTool, arrowObject, ARROW_KINDS, type ArrowKind } from './arrow'; export { BondTool } from './bond'; +export { BracketTool, editBracketLabel } from './bracket'; export { ChainTool } from './chain'; export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; From e16a3aa7c75edca494075cc38a269a856c8eaf09 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:00:25 -0500 Subject: [PATCH 047/279] feat(tools): add the line and polyline tool (0.5.0) A drag draws a straight line; a click starts a polyline that gains a point per click and ends on a double-click, a click on its first point (closing it), Escape to cancel or a tool change, committed as one transaction. Shift snaps each segment to 15 degrees. --- frontend/src/canvas/tools/index.ts | 3 + frontend/src/canvas/tools/line.ts | 121 +++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 frontend/src/canvas/tools/line.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index ea16c566..f6b70494 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -7,6 +7,7 @@ import { ChainTool } from './chain'; import { CurvedArrowTool } from './curved'; import { EraserTool } from './eraser'; import { ElementTool, LabelTool, TextTool } from './label'; +import { LineTool } from './line'; import { PlusTool } from './plus'; import { RingTool } from './ring'; import { SelectTool } from './select'; @@ -82,6 +83,7 @@ export const TOOLS: ToolDef[] = [ { id: 'shape-round-rect', label: 'Rounded rectangle', icon: 'shapeRoundRect', group: 'shape', create: () => new ShapeTool('shape-round-rect', 'round_rect') }, { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, { id: 'shape-polygon', label: 'Polygon', icon: 'shapePolygon', group: 'shape', create: () => new ShapeTool('shape-polygon', 'polygon') }, + { id: 'line', label: 'Line and polyline', icon: 'line', group: 'shape', create: () => new LineTool('line') }, { id: 'hand', label: 'Hand', icon: 'hand', group: 'hand', keys: ['H'], create: () => new HandTool() }, { id: 'zoom', label: 'Zoom', icon: 'zoomIn', group: 'zoom', keys: ['Z'], create: () => new ZoomTool() }, ]; @@ -97,6 +99,7 @@ export { ChainTool } from './chain'; export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; export { ElementTool, LabelTool, TextTool } from './label'; +export { LineTool } from './line'; export { PlusTool } from './plus'; export { RingTool } from './ring'; export { SelectTool } from './select'; diff --git a/frontend/src/canvas/tools/line.ts b/frontend/src/canvas/tools/line.ts new file mode 100644 index 00000000..5a69fcc7 --- /dev/null +++ b/frontend/src/canvas/tools/line.ts @@ -0,0 +1,121 @@ +import type { Id, LineObject, Point } from '../../engine/model'; +import { dist } from '../geom'; +import type { Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, moved, previewDraft } from './common'; +import type { Draft } from './draft'; +import { clicks, objectId, snapEnd } from './objects'; + +export const lineObject = (id: Id, points: Point[]): LineObject => ({ id, kind: 'line', points: points.map((p) => [p[0], p[1]] as Point) }); + +const CLOSE_PX = 6; + +export class LineTool implements Tool { + readonly cursor = 'crosshair'; + private start: ToolPointer | null = null; + private points: Point[] | null = null; + private oid: Id = ''; + + constructor(readonly id: string) {} + + deactivate(ctx: ToolContext): void { + if (this.points && this.points.length > 1) this.finish(ctx); + this.cancel(ctx); + } + + down(ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + if (this.points) { + if (clicks(p) >= 2) { + this.finish(ctx); + return; + } + this.start = p; + return; + } + this.start = p; + this.oid = objectId(); + } + + move(ctx: ToolContext, p: ToolPointer): void { + const pts = this.points; + const s = this.start; + if (!pts && !s) { + ctx.setHover(p.hit); + return; + } + if (pts) { + previewDraft(ctx, this.draft(ctx, [...pts, this.next(pts[pts.length - 1], p)])); + return; + } + if (s && moved(s, p)) previewDraft(ctx, this.draft(ctx, [s.doc, this.next(s.doc, p)])); + } + + up(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + this.start = null; + if (!s) return; + const pts = this.points; + if (pts) { + const at = this.next(pts[pts.length - 1], p); + if (dist(at, pts[0]) * ctx.viewport().zoom <= CLOSE_PX && pts.length > 2) { + pts.push([pts[0][0], pts[0][1]]); + this.finish(ctx); + return; + } + if (dist(at, pts[pts.length - 1]) * ctx.viewport().zoom > CLOSE_PX / 2) pts.push(at); + previewDraft(ctx, this.draft(ctx, pts)); + return; + } + if (moved(s, p)) { + const d = this.draft(ctx, [s.doc, this.next(s.doc, p)]); + if (d) commitDraft(ctx, 'Add line', d); + else ctx.client.preview(null); + return; + } + this.points = [s.doc]; + } + + key(ctx: ToolContext, e: KeyboardEvent): boolean { + if (!this.points && !this.start) return false; + if (e.key === 'Escape') { + this.cancel(ctx); + return true; + } + if (e.key === 'Enter') { + this.finish(ctx); + return true; + } + if (e.key === 'Backspace' && this.points && this.points.length > 1) { + this.points.pop(); + previewDraft(ctx, this.draft(ctx, this.points)); + return true; + } + return false; + } + + private next(from: Point, p: ToolPointer): Point { + return p.shift ? snapEnd(from, p.doc) : p.doc; + } + + private draft(ctx: ToolContext, pts: Point[]): Draft | null { + if (pts.length < 2 || pts.every((q) => dist(q, pts[0]) < 0.5)) return null; + const d = draftFor(ctx); + d.addObject(lineObject(this.oid, pts)); + return d; + } + + private finish(ctx: ToolContext): void { + const pts = this.points; + this.points = null; + this.start = null; + const d = pts ? this.draft(ctx, pts) : null; + if (d) commitDraft(ctx, 'Add line', d); + else ctx.client.preview(null); + } + + private cancel(ctx: ToolContext): void { + if (this.points || this.start) ctx.client.preview(null); + this.points = null; + this.start = null; + } +} From d578330627e80fc540a0f956448386b2fd957d62 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:00:44 -0500 Subject: [PATCH 048/279] feat(tools): add the table tool (0.5.0) Dragging sizes the table and fits whole 48 by 18 pt cells into it (1 to 50 each way) with equal column widths and row heights; a click places a 3 by 3 table, Shift adds a header row, Alt sizes from the centre. --- frontend/src/canvas/tools/index.ts | 3 ++ frontend/src/canvas/tools/table.ts | 44 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 frontend/src/canvas/tools/table.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index f6b70494..bb809584 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -12,6 +12,7 @@ import { PlusTool } from './plus'; import { RingTool } from './ring'; import { SelectTool } from './select'; import { ShapeTool } from './shape'; +import { TableTool } from './table'; import { HandTool, ZoomTool } from './view'; const bond = (kind: BondKindId, label: string, icon: string, keys?: string[]): ToolDef => ({ @@ -84,6 +85,7 @@ export const TOOLS: ToolDef[] = [ { id: 'shape-ellipse', label: 'Ellipse', icon: 'shapeEllipse', group: 'shape', create: () => new ShapeTool('shape-ellipse', 'ellipse') }, { id: 'shape-polygon', label: 'Polygon', icon: 'shapePolygon', group: 'shape', create: () => new ShapeTool('shape-polygon', 'polygon') }, { id: 'line', label: 'Line and polyline', icon: 'line', group: 'shape', create: () => new LineTool('line') }, + { id: 'table', label: 'Table', icon: 'table', group: 'table', create: () => new TableTool('table') }, { id: 'hand', label: 'Hand', icon: 'hand', group: 'hand', keys: ['H'], create: () => new HandTool() }, { id: 'zoom', label: 'Zoom', icon: 'zoomIn', group: 'zoom', keys: ['Z'], create: () => new ZoomTool() }, ]; @@ -104,6 +106,7 @@ export { PlusTool } from './plus'; export { RingTool } from './ring'; export { SelectTool } from './select'; export { ShapeTool } from './shape'; +export { TableTool, tableObject } from './table'; export { HandTool, ZoomTool } from './view'; export { HOVER_KEY_MAP, hoverKey, TWO_LETTER_MS } from './hotkeys'; export * from './transform'; diff --git a/frontend/src/canvas/tools/table.ts b/frontend/src/canvas/tools/table.ts new file mode 100644 index 00000000..e915c1e5 --- /dev/null +++ b/frontend/src/canvas/tools/table.ts @@ -0,0 +1,44 @@ +import type { Id, Point, TableObject, TableRow } from '../../engine/model'; +import type { Rect } from '../geom'; +import type { ToolContext, ToolPointer } from '../types'; +import type { Draft } from './draft'; +import { BoxTool, boxFrom, itemId } from './objects'; + +export const CELL_W = 48; +export const CELL_H = 18; +export const CLICK_GRID = 3; +export const MAX_GRID = 50; + +const fit = (span: number, cell: number): number => Math.max(1, Math.min(MAX_GRID, Math.round(span / cell))); + +export function tableObject(id: Id, x: number, y: number, cols: number, rows: number, w = cols * CELL_W, h = rows * CELL_H): TableObject { + const cw = w / cols; + const rh = h / rows; + const out: TableRow[] = []; + for (let r = 0; r < rows; r++) out.push({ id: itemId(), h: rh, cells: Array.from({ length: cols }, () => ({ runs: [] })) }); + return { id, kind: 'table', x, y, cols: Array.from({ length: cols }, () => cw), rows: out, borders: 'all' }; +} + +export const tableFor = (id: Id, r: Rect): TableObject => tableObject(id, r.x, r.y, fit(r.w, CELL_W), fit(r.h, CELL_H), r.w, r.h); + +export class TableTool extends BoxTool { + constructor(id: string) { + super(id, 'Add table'); + } + + protected clickBox(_ctx: ToolContext, at: Point): Rect { + return { x: at[0], y: at[1], w: CLICK_GRID * CELL_W, h: CLICK_GRID * CELL_H }; + } + + protected rect(s: ToolPointer, p: ToolPointer): Rect { + const r = boxFrom(s.doc, p.doc, { centre: p.alt }); + return { ...r, w: Math.max(r.w, CELL_W / 2), h: Math.max(r.h, CELL_H / 2) }; + } + + protected build(_ctx: ToolContext, d: Draft, r: Rect, p: ToolPointer, _dragged: boolean): boolean { + const t = tableFor(this.oid, r); + if (p.shift) t.header = true; + d.addObject(t); + return true; + } +} From 387c7ee06801a5c4b11a5f6b0287c62162cd8586 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:03 -0500 Subject: [PATCH 049/279] feat(tools): add the TLC plate tool (0.5.0) Dragging places a plate with one lane per 20 pt of width (at least one) and the default origin and front; a click on a plate adds a spot to the nearest lane with its Rf taken from the click height, each as one transaction. --- frontend/src/canvas/tools/index.ts | 3 ++ frontend/src/canvas/tools/tlc.ts | 73 ++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 frontend/src/canvas/tools/tlc.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index bb809584..dc1fb9a1 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -13,6 +13,7 @@ import { RingTool } from './ring'; import { SelectTool } from './select'; import { ShapeTool } from './shape'; import { TableTool } from './table'; +import { TlcTool } from './tlc'; import { HandTool, ZoomTool } from './view'; const bond = (kind: BondKindId, label: string, icon: string, keys?: string[]): ToolDef => ({ @@ -86,6 +87,7 @@ export const TOOLS: ToolDef[] = [ { id: 'shape-polygon', label: 'Polygon', icon: 'shapePolygon', group: 'shape', create: () => new ShapeTool('shape-polygon', 'polygon') }, { id: 'line', label: 'Line and polyline', icon: 'line', group: 'shape', create: () => new LineTool('line') }, { id: 'table', label: 'Table', icon: 'table', group: 'table', create: () => new TableTool('table') }, + { id: 'tlc', label: 'TLC plate', icon: 'tlcPlate', group: 'tlc', create: () => new TlcTool('tlc') }, { id: 'hand', label: 'Hand', icon: 'hand', group: 'hand', keys: ['H'], create: () => new HandTool() }, { id: 'zoom', label: 'Zoom', icon: 'zoomIn', group: 'zoom', keys: ['Z'], create: () => new ZoomTool() }, ]; @@ -107,6 +109,7 @@ export { RingTool } from './ring'; export { SelectTool } from './select'; export { ShapeTool } from './shape'; export { TableTool, tableObject } from './table'; +export { TlcTool, addSpot, rfAt } from './tlc'; export { HandTool, ZoomTool } from './view'; export { HOVER_KEY_MAP, hoverKey, TWO_LETTER_MS } from './hotkeys'; export * from './transform'; diff --git a/frontend/src/canvas/tools/tlc.ts b/frontend/src/canvas/tools/tlc.ts new file mode 100644 index 00000000..44773a98 --- /dev/null +++ b/frontend/src/canvas/tools/tlc.ts @@ -0,0 +1,73 @@ +import type { Id, Point, TlcLane, TlcObject, TlcSpot } from '../../engine/model'; +import { objectPath } from '../../engine/ops'; +import type { Rect } from '../geom'; +import type { ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor } from './common'; +import type { Draft } from './draft'; +import { BoxTool, boxAround, itemId } from './objects'; + +export const TLC_W = 60; +export const TLC_H = 90; +export const LANE_PT = 20; +export const ORIGIN = 0.1; +export const FRONT = 0.1; + +export const laneCount = (w: number): number => Math.max(1, Math.floor(w / LANE_PT)); + +export const lanes = (n: number): TlcLane[] => Array.from({ length: n }, () => ({ id: itemId(), spots: [] })); + +export function tlcObject(id: Id, r: Rect): TlcObject { + return { id, kind: 'tlc', x: r.x, y: r.y, w: r.w, h: r.h, lanes: lanes(laneCount(r.w)) }; +} + +export const laneX = (t: TlcObject, i: number): number => t.x + (t.w * (i + 1)) / (t.lanes.length + 1); + +export function rfAt(t: TlcObject, y: number): number { + const origin = t.y + t.h * (1 - (t.origin ?? ORIGIN)); + const front = t.y + t.h * (t.front ?? FRONT); + const span = origin - front; + if (span <= 0) return 0; + return Math.max(0, Math.min(1, Math.round(((origin - y) / span) * 100) / 100)); +} + +export function nearestLane(t: TlcObject, x: number): number { + let best = -1; + let bestD = Infinity; + t.lanes.forEach((_, i) => { + const d = Math.abs(laneX(t, i) - x); + if (d < bestD) { bestD = d; best = i; } + }); + return best; +} + +export function addSpot(d: Draft, oid: Id, at: Point): boolean { + const t = d.doc.objects[oid]; + if (!t || t.kind !== 'tlc' || !t.lanes.length) return false; + const i = nearestLane(t, at[0]); + const spot: TlcSpot = { id: itemId(), rf: rfAt(t, at[1]) }; + d.push({ op: 'ins', path: objectPath(oid, 'lanes', { id: t.lanes[i].id }, 'spots'), value: spot }); + return true; +} + +export class TlcTool extends BoxTool { + constructor(id: string) { + super(id, 'Add TLC plate'); + } + + protected click(ctx: ToolContext, p: ToolPointer): boolean { + const h = p.hit; + if (h.kind !== 'object' || ctx.client.doc.objects[h.object]?.kind !== 'tlc') return false; + const d = draftFor(ctx, [h.object]); + if (addSpot(d, h.object, p.doc)) commitDraft(ctx, 'Add TLC spot', d); + return true; + } + + protected clickBox(_ctx: ToolContext, at: Point): Rect { + return boxAround(at, TLC_W, TLC_H); + } + + protected build(_ctx: ToolContext, d: Draft, r: Rect, _p: ToolPointer, _dragged: boolean): boolean { + d.addObject(tlcObject(this.oid, r)); + return true; + } +} From f8d923fb6ba9a1ae35f2533d3568c101474a43d8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:24 -0500 Subject: [PATCH 050/279] feat(tools): add orbital tools for s, p, d, dz2, sp, sigma and pi lobes (0.5.0) A click on an atom centres the orbital on it and attaches it; a click elsewhere places it free; dragging from the start point turns it toward the pointer in 15 degree steps (Alt free). p and pi lobes stand upright by default. --- frontend/src/canvas/tools/index.ts | 17 ++++++ frontend/src/canvas/tools/orbital.ts | 84 ++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 frontend/src/canvas/tools/orbital.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index dc1fb9a1..93afd0de 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -8,6 +8,7 @@ import { CurvedArrowTool } from './curved'; import { EraserTool } from './eraser'; import { ElementTool, LabelTool, TextTool } from './label'; import { LineTool } from './line'; +import { OrbitalTool, type OrbitalType } from './orbital'; import { PlusTool } from './plus'; import { RingTool } from './ring'; import { SelectTool } from './select'; @@ -42,6 +43,14 @@ const arrow = (kind: ArrowKind, label: string, icon: string): ToolDef => ({ create: () => new ArrowTool(`arrow-${kind}`, kind), }); +const orbital = (type: OrbitalType, label: string, icon: string): ToolDef => ({ + id: `orbital-${type}`, + label, + icon, + group: 'orbital', + create: () => new OrbitalTool(`orbital-${type}`, type), +}); + export const TOOLS: ToolDef[] = [ { id: 'select', label: 'Select', icon: 'cursor', group: 'select', keys: ['V'], create: () => new SelectTool('select') }, { id: 'lasso', label: 'Lasso', icon: 'lasso', group: 'select', keys: ['L'], create: () => new SelectTool('lasso', true) }, @@ -88,6 +97,13 @@ export const TOOLS: ToolDef[] = [ { id: 'line', label: 'Line and polyline', icon: 'line', group: 'shape', create: () => new LineTool('line') }, { id: 'table', label: 'Table', icon: 'table', group: 'table', create: () => new TableTool('table') }, { id: 'tlc', label: 'TLC plate', icon: 'tlcPlate', group: 'tlc', create: () => new TlcTool('tlc') }, + orbital('p', 'p orbital', 'orbitalP'), + orbital('s', 's orbital', 'orbitalS'), + orbital('d', 'd orbital', 'orbitalD'), + orbital('dz2', 'dz2 orbital', 'orbitalDz2'), + orbital('sp', 'sp hybrid orbital', 'orbitalSp'), + orbital('sigma', 'Sigma bond orbital', 'orbitalSigma'), + orbital('pi', 'Pi bond orbital', 'orbitalPi'), { id: 'hand', label: 'Hand', icon: 'hand', group: 'hand', keys: ['H'], create: () => new HandTool() }, { id: 'zoom', label: 'Zoom', icon: 'zoomIn', group: 'zoom', keys: ['Z'], create: () => new ZoomTool() }, ]; @@ -104,6 +120,7 @@ export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; export { ElementTool, LabelTool, TextTool } from './label'; export { LineTool } from './line'; +export { OrbitalTool, orbitalObject, type OrbitalType } from './orbital'; export { PlusTool } from './plus'; export { RingTool } from './ring'; export { SelectTool } from './select'; diff --git a/frontend/src/canvas/tools/orbital.ts b/frontend/src/canvas/tools/orbital.ts new file mode 100644 index 00000000..1f2ae814 --- /dev/null +++ b/frontend/src/canvas/tools/orbital.ts @@ -0,0 +1,84 @@ +import { isFragment, type Id, type OrbitalObject, type Point } from '../../engine/model'; +import { angleFrom, snapAngle } from '../geom'; +import type { Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, moved, previewDraft } from './common'; +import type { Draft } from './draft'; +import { objectId } from './objects'; + +export type OrbitalType = OrbitalObject['type']; + +export const ORBITAL_SIZE: Record = { s: 0.6, p: 1, d: 1, dz2: 1, sp: 1, sigma: 1.2, pi: 1.2 }; +export const ORBITAL_ROT: Partial> = { p: 90, pi: 90 }; + +interface Start { p: ToolPointer; centre: Point; atom?: { object: Id; atom: Id } } + +export function orbitalObject(id: Id, type: OrbitalType, centre: Point, bond: number, rot?: number, atom?: { object: Id; atom: Id }): OrbitalObject { + const o: OrbitalObject = { id, kind: 'orbital', type, x: centre[0], y: centre[1], size: ORBITAL_SIZE[type] * bond }; + const r = rot ?? ORBITAL_ROT[type]; + if (r) o.rot = r; + if (atom) o.atom = atom; + return o; +} + +export class OrbitalTool implements Tool { + readonly cursor = 'crosshair'; + private start: Start | null = null; + private oid: Id = ''; + + constructor(readonly id: string, readonly type: OrbitalType) {} + + deactivate(ctx: ToolContext): void { + if (this.start) ctx.client.preview(null); + this.start = null; + } + + down(ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + this.oid = objectId(); + const h = p.hit; + if (h.kind === 'atom') { + const f = ctx.client.doc.objects[h.frag]; + const a = isFragment(f) ? f.atoms[h.atom] : undefined; + if (a) { + this.start = { p, centre: [a.x, a.y], atom: { object: h.frag, atom: a.id } }; + return; + } + } + this.start = { p, centre: p.doc }; + } + + move(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + if (!s) { + ctx.setHover(p.hit); + return; + } + if (moved(s.p, p)) previewDraft(ctx, this.draft(ctx, s, p, true)); + } + + up(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + this.start = null; + if (!s) return; + commitDraft(ctx, 'Add orbital', this.draft(ctx, s, p, moved(s.p, p))); + } + + key(ctx: ToolContext, e: KeyboardEvent): boolean { + if (e.key === 'Escape' && this.start) { + this.deactivate(ctx); + return true; + } + return false; + } + + private draft(ctx: ToolContext, s: Start, p: ToolPointer, dragged: boolean): Draft { + let rot: number | undefined; + if (dragged) { + const a = angleFrom(s.centre, p.doc); + rot = p.alt ? Math.round(a * 10) / 10 : snapAngle(a, 15); + } + const d = draftFor(ctx, s.atom ? [s.atom.object] : []); + d.addObject(orbitalObject(this.oid, this.type, s.centre, ctx.style().bond_length, rot, s.atom)); + return d; + } +} From 146bde290618fdb07a51f3a0095eb3033dac650a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:01:50 -0500 Subject: [PATCH 051/279] feat(tools): add the image tool with a swappable media uploader (0.5.0) A click or a dragged box opens the file picker, uploads the picture through uploadMedia (POST /api/documents/{id}/media, proposed for the engine) and commits the media record and the image object as one transaction, sized from the picture or fitted into the box. --- frontend/src/canvas/tools/image.ts | 126 +++++++++++++++++++++++++++++ frontend/src/canvas/tools/index.ts | 3 + 2 files changed, 129 insertions(+) create mode 100644 frontend/src/canvas/tools/image.ts diff --git a/frontend/src/canvas/tools/image.ts b/frontend/src/canvas/tools/image.ts new file mode 100644 index 00000000..e7b3cd17 --- /dev/null +++ b/frontend/src/canvas/tools/image.ts @@ -0,0 +1,126 @@ +import { docUrl } from '../../engine/client'; +import type { Id, ImageObject, Media, Point } from '../../engine/model'; +import { t } from '../../i18n'; +import { upload } from '../../io/api'; +import { toast } from '../../ui/toast'; +import type { Rect } from '../geom'; +import type { Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor, moved } from './common'; +import { boxFrom, ensureMediaMap, objectId } from './objects'; + +export interface MediaUpload { id: Id; media: Media } +export type MediaUploader = (doc: Id, file: File) => Promise; + +export const IMAGE_ACCEPT = 'image/png,image/jpeg,image/gif,image/webp,image/svg+xml'; +export const IMAGE_MAX_PT = 240; +const PX_PT = 72 / 96; + +export const mediaUrl = (doc: Id): string => docUrl(doc, 'media'); + +export const engineMediaUploader: MediaUploader = (doc, file) => upload(mediaUrl(doc), [file], 'file'); + +let uploader: MediaUploader = engineMediaUploader; + +export function setMediaUploader(fn: MediaUploader): void { + uploader = fn; +} + +export const uploadMedia = (doc: Id, file: File): Promise => uploader(doc, file); + +export function pickImage(): Promise { + return new Promise((resolve) => { + const input = document.createElement('input'); + input.type = 'file'; + input.accept = IMAGE_ACCEPT; + input.addEventListener('change', () => resolve(input.files?.[0] ?? null), { once: true }); + input.addEventListener('cancel', () => resolve(null), { once: true }); + input.click(); + }); +} + +export async function naturalSize(file: File): Promise<{ w: number; h: number } | null> { + try { + const bmp = await createImageBitmap(file); + const out = { w: bmp.width, h: bmp.height }; + bmp.close(); + return out.w > 0 && out.h > 0 ? out : null; + } catch { + return null; + } +} + +export function imageBox(at: Point, px: { w: number; h: number } | null, drawn: Rect | null): Rect { + const w0 = (px?.w ?? 400) * PX_PT; + const h0 = (px?.h ?? 300) * PX_PT; + if (drawn) { + const k = Math.min(drawn.w / w0, drawn.h / h0); + return { x: drawn.x, y: drawn.y, w: w0 * k, h: h0 * k }; + } + const k = Math.min(1, IMAGE_MAX_PT / Math.max(w0, h0)); + return { x: at[0], y: at[1], w: w0 * k, h: h0 * k }; +} + +export async function placeImage(ctx: ToolContext, at: Point, drawn: Rect | null, file?: File | null): Promise { + const chosen = file ?? (await pickImage()); + if (!chosen) return null; + const client = ctx.client; + const doc = client.id; + try { + const [px, sent] = await Promise.all([naturalSize(chosen), uploadMedia(doc, chosen)]); + if (ctx.client.id !== doc) return null; + const media: Media = { ...sent.media }; + if (px && media.w === undefined) { media.w = px.w; media.h = px.h; } + const d = draftFor(ctx); + ensureMediaMap(d); + d.push({ op: 'set', path: ['media', sent.id], value: media }); + const r = imageBox(at, px, drawn); + const o: ImageObject = { id: objectId(), kind: 'image', media: sent.id, x: r.x, y: r.y, w: r.w, h: r.h }; + d.addObject(o); + return commitDraft(ctx, 'Add image', d) ? o.id : null; + } catch (e) { + toast(`${t('Could not add the image')}: ${e instanceof Error ? e.message : String(e)}`, 'error'); + return null; + } +} + +export class ImageTool implements Tool { + readonly cursor = 'crosshair'; + private start: ToolPointer | null = null; + + constructor(readonly id: string) {} + + deactivate(ctx: ToolContext): void { + if (this.start) ctx.band?.(null); + this.start = null; + } + + down(_ctx: ToolContext, p: ToolPointer): void { + if (p.button === 0) this.start = p; + } + + move(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + if (!s) { + ctx.setHover(p.hit); + return; + } + if (moved(s, p)) ctx.band?.({ kind: 'rect', a: s.doc, b: p.doc }); + } + + up(ctx: ToolContext, p: ToolPointer): void { + const s = this.start; + this.start = null; + if (!s) return; + ctx.band?.(null); + const drawn = moved(s, p) ? boxFrom(s.doc, p.doc) : null; + void placeImage(ctx, s.doc, drawn); + } + + key(ctx: ToolContext, e: KeyboardEvent): boolean { + if (e.key === 'Escape' && this.start) { + this.deactivate(ctx); + return true; + } + return false; + } +} diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index 93afd0de..330d07c6 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -6,6 +6,7 @@ import type { BondKindId } from './build'; import { ChainTool } from './chain'; import { CurvedArrowTool } from './curved'; import { EraserTool } from './eraser'; +import { ImageTool } from './image'; import { ElementTool, LabelTool, TextTool } from './label'; import { LineTool } from './line'; import { OrbitalTool, type OrbitalType } from './orbital'; @@ -97,6 +98,7 @@ export const TOOLS: ToolDef[] = [ { id: 'line', label: 'Line and polyline', icon: 'line', group: 'shape', create: () => new LineTool('line') }, { id: 'table', label: 'Table', icon: 'table', group: 'table', create: () => new TableTool('table') }, { id: 'tlc', label: 'TLC plate', icon: 'tlcPlate', group: 'tlc', create: () => new TlcTool('tlc') }, + { id: 'image', label: 'Image', icon: 'image', group: 'image', create: () => new ImageTool('image') }, orbital('p', 'p orbital', 'orbitalP'), orbital('s', 's orbital', 'orbitalS'), orbital('d', 'd orbital', 'orbitalD'), @@ -118,6 +120,7 @@ export { BracketTool, editBracketLabel } from './bracket'; export { ChainTool } from './chain'; export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; +export { ImageTool, placeImage, setMediaUploader, uploadMedia, type MediaUpload, type MediaUploader } from './image'; export { ElementTool, LabelTool, TextTool } from './label'; export { LineTool } from './line'; export { OrbitalTool, orbitalObject, type OrbitalType } from './orbital'; From 746e0c8d2172bf8531ac405309b77723c5fdf264 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:02:17 -0500 Subject: [PATCH 052/279] feat(tools): add the caption tool that attaches text to a structure (0.5.0) A click on or just around a structure types a caption centred half a bond length under it, targeted at the fragment with its offset recorded; Ctrl or Cmd-click adds the next bold compound number; a click on a caption edits it, and empty space gives a free caption. --- frontend/src/canvas/tools/caption.ts | 72 ++++++++++++++++++++++++++++ frontend/src/canvas/tools/index.ts | 3 ++ 2 files changed, 75 insertions(+) create mode 100644 frontend/src/canvas/tools/caption.ts diff --git a/frontend/src/canvas/tools/caption.ts b/frontend/src/canvas/tools/caption.ts new file mode 100644 index 00000000..5e0a8a4c --- /dev/null +++ b/frontend/src/canvas/tools/caption.ts @@ -0,0 +1,72 @@ +import type { CaptionObject, FormChemDocument, Fragment, Id, Point } from '../../engine/model'; +import type { Tool, ToolContext, ToolPointer } from '../types'; +import { commitDraft, draftFor } from './common'; +import { editTextObject } from './label'; +import { fragmentAt, fragmentBox, fragmentOfHit, objectId } from './objects'; + +export const CAPTION_GAP = 0.5; +const CHAR_EM = 0.55; + +export function nextCompoundNumber(doc: FormChemDocument): string { + let n = 0; + for (const o of Object.values(doc.objects)) { + if (o.kind !== 'caption' || !o.number) continue; + const v = parseInt(o.number.value, 10); + if (Number.isFinite(v)) n = Math.max(n, v); + } + return String(n + 1); +} + +export function captionFor(id: Id, frag: Fragment | null, at: Point, text: string, size: number, bond: number, numbered = false): CaptionObject { + const w = Math.max(size * 0.6, text.length * size * CHAR_EM); + const box = frag ? fragmentBox(frag) : null; + const o: CaptionObject = { id, kind: 'caption', x: at[0], y: at[1], align: 'c', runs: [numbered ? { t: text, b: true } : { t: text }] }; + if (frag && box) { + const gap = CAPTION_GAP * bond; + const cx = box.x + box.w / 2; + o.x = cx - w / 2; + o.y = box.y + box.h + gap; + o.target = frag.id; + o.offset = [0, gap]; + } + if (numbered) o.number = { auto: true, value: text }; + return o; +} + +export class CaptionTool implements Tool { + readonly cursor = 'text'; + + constructor(readonly id: string) {} + + move(ctx: ToolContext, p: ToolPointer): void { + ctx.setHover(p.hit); + } + + up(ctx: ToolContext, p: ToolPointer): void { + if (p.button !== 0) return; + const doc = ctx.client.doc; + const h = p.hit; + if (h.kind === 'object' && (doc.objects[h.object]?.kind === 'caption' || doc.objects[h.object]?.kind === 'text')) { + editTextObject(ctx, h.object); + return; + } + const style = ctx.style(); + const frag = fragmentOfHit(doc, h) ?? fragmentAt(doc, ctx.page(), p.doc, style.bond_length * CAPTION_GAP); + const size = style.caption_font.size; + if (p.mod && frag) { + const d = draftFor(ctx, [frag.id]); + d.addObject(captionFor(objectId(), frag, p.doc, nextCompoundNumber(doc), size, style.bond_length, true)); + commitDraft(ctx, 'Add compound number', d); + return; + } + const preview = captionFor('', frag, p.doc, '', size, style.bond_length); + const at: Point = frag ? [preview.x + size * 0.3, preview.y + size * 0.6] : p.doc; + ctx.editText(at, '', (text) => { + if (text === null || !text.trim()) return; + const d = draftFor(ctx, frag ? [frag.id] : []); + const live = frag && d.doc.objects[frag.id]?.kind === 'fragment' ? (d.doc.objects[frag.id] as Fragment) : null; + d.addObject(captionFor(objectId(), live, p.doc, text, size, ctx.style().bond_length)); + commitDraft(ctx, 'Add caption', d); + }); + } +} diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index 330d07c6..af9ed10a 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -3,6 +3,7 @@ import { ArrowTool, type ArrowKind } from './arrow'; import { BondTool } from './bond'; import { BracketTool } from './bracket'; import type { BondKindId } from './build'; +import { CaptionTool } from './caption'; import { ChainTool } from './chain'; import { CurvedArrowTool } from './curved'; import { EraserTool } from './eraser'; @@ -75,6 +76,7 @@ export const TOOLS: ToolDef[] = [ ring('ring8', 'Cyclooctane', 'ring8'), { id: 'label', label: 'Atom label', icon: 'atomLabel', group: 'atom', keys: ['A'], create: () => new LabelTool() }, { id: 'text', label: 'Text', icon: 'textBox', group: 'text', keys: ['T'], create: () => new TextTool() }, + { id: 'caption', label: 'Caption', icon: 'captions', group: 'text', create: () => new CaptionTool('caption') }, { id: 'eraser', label: 'Eraser', icon: 'eraser', group: 'eraser', keys: ['E'], create: () => new EraserTool() }, arrow('forward', 'Reaction arrow', 'arrow'), arrow('equilibrium', 'Equilibrium arrow', 'arrowEquilibrium'), @@ -117,6 +119,7 @@ export const elementTool = (symbol: string): Tool => new ElementTool(symbol); export { ArrowTool, arrowObject, ARROW_KINDS, type ArrowKind } from './arrow'; export { BondTool } from './bond'; export { BracketTool, editBracketLabel } from './bracket'; +export { CaptionTool, nextCompoundNumber } from './caption'; export { ChainTool } from './chain'; export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; From 6e732eb46a4a788280598ebe4ee9cf0004c58f73 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:02:24 -0500 Subject: [PATCH 053/279] fix(tools): delete a group's members with the group (0.5.0) Draft.removeObject dropped only the group record, leaving its members in no container, so the engine rejected every delete or erase of a group; members are now removed in the same transaction. --- frontend/src/canvas/tools/draft.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/frontend/src/canvas/tools/draft.ts b/frontend/src/canvas/tools/draft.ts index 8adaa3a8..fddbcff3 100644 --- a/frontend/src/canvas/tools/draft.ts +++ b/frontend/src/canvas/tools/draft.ts @@ -131,13 +131,20 @@ export class Draft { if (!this.doc.objects[oid]) return; const where = this.containerOf(oid); if (where) this.push({ op: 'del', path: where.path, id: oid }); - this.push({ op: 'set', path: objectPath(oid) }); + this.dropTree(oid, 0); if (where?.group) { const g = this.doc.objects[where.group]; if (g && g.kind === 'group' && g.children.length === 0) this.removeObject(g.id); } } + private dropTree(oid: Id, depth: number): void { + const o = this.doc.objects[oid]; + if (!o) return; + this.push({ op: 'set', path: objectPath(oid) }); + if (o.kind === 'group' && depth < 32) for (const c of o.children) this.dropTree(c, depth + 1); + } + mergeFragments(into: Id, from: Id): void { if (into === from) return; const src = this.frag(from); From f1b456f11c1b9a09049c398a49363f384bfede05 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:03:10 -0500 Subject: [PATCH 054/279] feat(tools): reshape and resize selected objects by their handles (0.5.0) A single selected arrow gets tail, head and arc-bend handles (an end let go of its anchor), a line one handle per point, and shapes, images, brackets, TLC plates and tables eight box handles (Shift keeps the aspect, images always do); the select tool grabs them before anything else and commits one transaction per drag. --- frontend/src/canvas/tools/handles.ts | 133 +++++++++++++++++++++++++++ frontend/src/canvas/tools/index.ts | 1 + frontend/src/canvas/tools/select.ts | 24 ++++- 3 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 frontend/src/canvas/tools/handles.ts diff --git a/frontend/src/canvas/tools/handles.ts b/frontend/src/canvas/tools/handles.ts new file mode 100644 index 00000000..934a2e02 --- /dev/null +++ b/frontend/src/canvas/tools/handles.ts @@ -0,0 +1,133 @@ +import { isFragment, type ArrowObject, type DocObject, type FormChemDocument, type Id, type Point } from '../../engine/model'; +import { objectPath } from '../../engine/ops'; +import { dist, type Rect } from '../geom'; +import type { Selection } from '../types'; +import { objectBounds } from './common'; +import { arcMid, bendThrough } from './curved'; +import type { Draft } from './draft'; +import { MIN_BOX, snapEnd } from './objects'; + +export type BoxHandle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'; +export type HandleKind = 'tail' | 'head' | 'bend' | 'point' | BoxHandle; + +export interface ObjectHandle { object: Id; kind: HandleKind; at: Point; index?: number } + +export interface HandleDrag { shift: boolean; alt: boolean } + +const BOXED = new Set(['shape', 'image', 'bracket', 'tlc', 'table']); +const BOX_HANDLES: [BoxHandle, number, number][] = [ + ['nw', 0, 0], ['n', 0.5, 0], ['ne', 1, 0], ['e', 1, 0.5], ['se', 1, 1], ['s', 0.5, 1], ['sw', 0, 1], ['w', 0, 0.5], +]; + +export const HANDLE_CURSORS: Record = { + tail: 'move', head: 'move', bend: 'grab', point: 'move', + nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize', n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize', +}; + +export function handledObject(doc: FormChemDocument, sel: Selection): DocObject | null { + if (sel.atoms.size || sel.bonds.size || sel.objects.size !== 1) return null; + const o = doc.objects[[...sel.objects][0]]; + if (!o || isFragment(o) || o.locked || o.hidden) return null; + return o.kind === 'arrow' || o.kind === 'line' || BOXED.has(o.kind) ? o : null; +} + +export function objectHandles(doc: FormChemDocument, sel: Selection): ObjectHandle[] { + const o = handledObject(doc, sel); + if (!o) return []; + if (o.kind === 'arrow') { + const t: Point = [o.x1, o.y1]; + const h: Point = [o.x2, o.y2]; + return [ + { object: o.id, kind: 'tail', at: t }, + { object: o.id, kind: 'head', at: h }, + { object: o.id, kind: 'bend', at: arcMid(t, h, o.bend ?? 0) }, + ]; + } + if (o.kind === 'line') return o.points.map((p, index) => ({ object: o.id, kind: 'point', at: [p[0], p[1]], index })); + const r = objectBounds(doc, o); + if (!r) return []; + return BOX_HANDLES.map(([kind, fx, fy]) => ({ object: o.id, kind, at: [r.x + r.w * fx, r.y + r.h * fy] })); +} + +export function handleAt(doc: FormChemDocument, sel: Selection, p: Point, zoom: number, slopPx: number): ObjectHandle | null { + let best: ObjectHandle | null = null; + let bestD = slopPx / Math.max(zoom, 1e-6); + for (const h of objectHandles(doc, sel)) { + const d = dist(h.at, p); + if (d <= bestD) { bestD = d; best = h; } + } + return best; +} + +export function resizeBox(r: Rect, kind: BoxHandle, p: Point, keepAspect: boolean): Rect { + let x0 = r.x, y0 = r.y, x1 = r.x + r.w, y1 = r.y + r.h; + if (kind.includes('w')) x0 = Math.min(p[0], x1 - MIN_BOX); + if (kind.includes('e')) x1 = Math.max(p[0], x0 + MIN_BOX); + if (kind.includes('n')) y0 = Math.min(p[1], y1 - MIN_BOX); + if (kind.includes('s')) y1 = Math.max(p[1], y0 + MIN_BOX); + if (keepAspect && kind.length === 2 && r.w > 0 && r.h > 0) { + const k = Math.max((x1 - x0) / r.w, (y1 - y0) / r.h); + const w = r.w * k, h = r.h * k; + if (kind.includes('w')) x0 = x1 - w; else x1 = x0 + w; + if (kind.includes('n')) y0 = y1 - h; else y1 = y0 + h; + } + return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} + +function dropAnchor(d: Draft, o: ArrowObject, end: 'tail' | 'head'): void { + const a = o.anchors; + if (!a || !a[end]) return; + const other = end === 'tail' ? a.head : a.tail; + if (other) d.push({ op: 'set', path: objectPath(o.id, 'anchors'), value: end === 'tail' ? { head: other } : { tail: other } }); + else d.push({ op: 'set', path: objectPath(o.id, 'anchors') }); +} + +export function dragHandle(d: Draft, h: ObjectHandle, p: Point, m: HandleDrag): void { + const o = d.doc.objects[h.object]; + if (!o) return; + const set = (key: string, value: unknown): void => d.push({ op: 'set', path: objectPath(o.id, key), value }); + if (o.kind === 'arrow') { + if (h.kind === 'bend') { + let bend = bendThrough([o.x1, o.y1], [o.x2, o.y2], p); + if (m.shift) bend = Math.round(bend / 15) * 15; + else if (Math.abs(bend) < 3) bend = 0; + if (bend) set('bend', bend); + else if (o.bend !== undefined) d.push({ op: 'set', path: objectPath(o.id, 'bend') }); + return; + } + const tail = h.kind === 'tail'; + const fixed: Point = tail ? [o.x2, o.y2] : [o.x1, o.y1]; + const at = m.shift ? snapEnd(fixed, p) : p; + if (dist(at, fixed) < 1) return; + set(tail ? 'x1' : 'x2', at[0]); + set(tail ? 'y1' : 'y2', at[1]); + dropAnchor(d, o, tail ? 'tail' : 'head'); + return; + } + if (o.kind === 'line' && h.kind === 'point' && h.index !== undefined) { + const pts = o.points.map((q) => [q[0], q[1]] as Point); + const prev = pts[h.index - 1] ?? pts[h.index + 1]; + pts[h.index] = m.shift && prev ? snapEnd(prev, p) : p; + set('points', pts); + return; + } + if (!BOXED.has(o.kind) || h.kind.length > 2 || !/^[nsew]+$/.test(h.kind)) return; + const r = objectBounds(d.doc, o); + if (!r) return; + const next = resizeBox(r, h.kind as BoxHandle, p, m.shift || o.kind === 'image'); + if (o.kind === 'table') { + const kx = next.w / Math.max(r.w, 1e-9); + const ky = next.h / Math.max(r.h, 1e-9); + set('x', next.x); + set('y', next.y); + set('cols', o.cols.map((c) => c * kx)); + set('rows', o.rows.map((row) => ({ ...row, h: row.h * ky }))); + return; + } + set('x', next.x); + set('y', next.y); + set('w', next.w); + set('h', next.h); +} + +export const handleLabel = (h: ObjectHandle): string => (h.kind === 'bend' ? 'Bend arrow' : h.kind === 'tail' || h.kind === 'head' ? 'Move arrow end' : h.kind === 'point' ? 'Move point' : 'Resize'); diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index af9ed10a..99aebd1f 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -123,6 +123,7 @@ export { CaptionTool, nextCompoundNumber } from './caption'; export { ChainTool } from './chain'; export { CurvedArrowTool, arcMid, bendThrough, anchorPoint } from './curved'; export { EraserTool } from './eraser'; +export { dragHandle, handleAt, handledObject, objectHandles, HANDLE_CURSORS, type HandleKind, type ObjectHandle } from './handles'; export { ImageTool, placeImage, setMediaUploader, uploadMedia, type MediaUpload, type MediaUploader } from './image'; export { ElementTool, LabelTool, TextTool } from './label'; export { LineTool } from './line'; diff --git a/frontend/src/canvas/tools/select.ts b/frontend/src/canvas/tools/select.ts index 42c7cd75..8eb041f3 100644 --- a/frontend/src/canvas/tools/select.ts +++ b/frontend/src/canvas/tools/select.ts @@ -6,6 +6,7 @@ import { MERGE_FRACTION } from './build'; import { atomsOfSelection, commitDraft, draftFor, EMPTY_SELECTION, makeSelection, moved, objectBounds, previewDraft, selectFragment, selectionEmpty, splitKey, topLevelObjects } from './common'; import type { AtomRef, Draft } from './draft'; import { deleteSelection } from './edit'; +import { dragHandle, handleAt, handleLabel, HANDLE_CURSORS, type ObjectHandle } from './handles'; import { hoverKey } from './hotkeys'; import { nudge, rotateHandle, rotateSelection, selectionBounds, translateSelection } from './transform'; @@ -17,6 +18,7 @@ const MARQUEE_ID = 'o_preview_marquee'; type Mode = | { kind: 'move'; start: ToolPointer; sel: Selection; dragging: boolean; duplicate: boolean } | { kind: 'rotate'; start: ToolPointer; sel: Selection; centre: Point } + | { kind: 'handle'; start: ToolPointer; handle: ObjectHandle } | { kind: 'marquee'; start: ToolPointer; base: Selection; add: boolean; touch: boolean } | { kind: 'lasso'; start: ToolPointer; base: Selection; add: boolean; touch: boolean; points: Point[] }; @@ -152,6 +154,11 @@ export class SelectTool implements Tool { const now = Date.now(); const dbl = this.lastClick && now - this.lastClick.at <= DOUBLE_CLICK_MS && dist(this.lastClick.screen, p.screen) <= HANDLE_SLOP_PX; this.lastClick = { at: now, screen: p.screen }; + const grip = handleAt(ctx.client.doc, sel, p.doc, ctx.viewport().zoom, HANDLE_SLOP_PX); + if (grip) { + this.mode = { kind: 'handle', start: p, handle: grip }; + return; + } if (!selectionEmpty(sel)) { const h = rotateHandle(ctx.client.doc, sel, ctx.viewport().zoom); const r = selectionBounds(ctx.client.doc, sel); @@ -183,9 +190,13 @@ export class SelectTool implements Tool { const m = this.mode; if (!m) { ctx.setHover(p.hit); + const grip = handleAt(ctx.client.doc, ctx.selection(), p.doc, ctx.viewport().zoom, HANDLE_SLOP_PX); + ctx.setCursor(grip ? HANDLE_CURSORS[grip.kind] : this.cursor); return; } - if (m.kind === 'move') { + if (m.kind === 'handle') { + if (moved(m.start, p)) previewDraft(ctx, this.handleDraft(ctx, m, p)); + } else if (m.kind === 'move') { if (!m.dragging && !moved(m.start, p)) return; m.dragging = true; previewDraft(ctx, this.moveDraft(ctx, m, p).d); @@ -216,7 +227,10 @@ export class SelectTool implements Tool { const m = this.mode; this.mode = null; if (!m) return; - if (m.kind === 'move') { + if (m.kind === 'handle') { + if (moved(m.start, p)) commitDraft(ctx, handleLabel(m.handle), this.handleDraft(ctx, m, p)); + else ctx.client.preview(null); + } else if (m.kind === 'move') { if (!m.dragging) return; const { d, sel } = this.moveDraft(ctx, m, p); if (commitDraft(ctx, m.duplicate ? 'Duplicate' : 'Move', d)) ctx.setSelection(sel); @@ -296,6 +310,12 @@ export class SelectTool implements Tool { return { d, sel }; } + private handleDraft(ctx: ToolContext, m: Extract, p: ToolPointer): Draft { + const d = draftFor(ctx, [m.handle.object]); + dragHandle(d, m.handle, p.doc, { shift: p.shift, alt: p.alt }); + return d; + } + private rotateDraft(ctx: ToolContext, m: Extract, p: ToolPointer): Draft { const d = draftFor(ctx); let deg = angleFrom(m.centre, p.doc) - angleFrom(m.centre, m.start.doc); From abe44e13f34a542ac8d0fd4748432146d8646dc6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:03:21 -0500 Subject: [PATCH 055/279] feat(tools): select the outermost group on click (0.5.0) Clicking any member of a group selects the group as one object so it moves, rotates and deletes as a whole; Alt-click or a double-click still reaches the member under the pointer. --- frontend/src/canvas/tools/select.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/src/canvas/tools/select.ts b/frontend/src/canvas/tools/select.ts index 8eb041f3..810463c6 100644 --- a/frontend/src/canvas/tools/select.ts +++ b/frontend/src/canvas/tools/select.ts @@ -7,6 +7,7 @@ import { atomsOfSelection, commitDraft, draftFor, EMPTY_SELECTION, makeSelection import type { AtomRef, Draft } from './draft'; import { deleteSelection } from './edit'; import { dragHandle, handleAt, handleLabel, HANDLE_CURSORS, type ObjectHandle } from './handles'; +import { groupHit } from './objects'; import { hoverKey } from './hotkeys'; import { nudge, rotateHandle, rotateSelection, selectionBounds, translateSelection } from './transform'; @@ -167,7 +168,7 @@ export class SelectTool implements Tool { return; } } - const h = p.hit; + const h = dbl || p.alt ? p.hit : groupHit(ctx.client.doc, p.hit); if (h.kind !== 'none') { if (dbl && (h.kind === 'atom' || h.kind === 'bond')) { ctx.setSelection(selectFragment(ctx.client.doc, h.frag)); From 8d5a1c910dcb9c08d862fae6f0527305a890608f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:03:56 -0500 Subject: [PATCH 056/279] feat(app): add bring to front, bring forward, send backward and send to back (0.5.0) Pure handlers reorder the selected objects inside the page order or group child list that holds them, keeping their relative order, and commit the moves as one transaction for the integration step to wire to the Arrange commands. --- frontend/src/app/object-commands.ts | 79 +++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 frontend/src/app/object-commands.ts diff --git a/frontend/src/app/object-commands.ts b/frontend/src/app/object-commands.ts new file mode 100644 index 00000000..8ba3f0a0 --- /dev/null +++ b/frontend/src/app/object-commands.ts @@ -0,0 +1,79 @@ +import { splitKey } from '../canvas/selection'; +import type { Selection } from '../canvas/types'; +import type { DocumentClient } from '../engine/client-api'; +import type { FormChemDocument, Id } from '../engine/model'; +import { objectPath, pagePath, type Op, type Path } from '../engine/ops'; +import { t } from '../i18n'; + +export type ZOrder = 'front' | 'forward' | 'backward' | 'back'; + +interface Container { path: Path; list: Id[] } + +export function selectedIds(sel: Selection): Id[] { + const out = new Set(sel.objects); + for (const k of sel.atoms) out.add(splitKey(k)[0]); + for (const k of sel.bonds) out.add(splitKey(k)[0]); + return [...out]; +} + +export function containerOf(doc: FormChemDocument, id: Id): Container | null { + for (const p of doc.pages) if (p.order.includes(id)) return { path: pagePath(p.id, 'order'), list: p.order }; + for (const o of Object.values(doc.objects)) if (o.kind === 'group' && o.children.includes(id)) return { path: objectPath(o.id, 'children'), list: o.children }; + return null; +} + +export function reorder(list: readonly Id[], chosen: ReadonlySet, how: ZOrder): Id[] { + const out = [...list]; + if (how === 'front') return [...out.filter((id) => !chosen.has(id)), ...out.filter((id) => chosen.has(id))]; + if (how === 'back') return [...out.filter((id) => chosen.has(id)), ...out.filter((id) => !chosen.has(id))]; + if (how === 'forward') { + for (let i = out.length - 2; i >= 0; i--) { + if (chosen.has(out[i]) && !chosen.has(out[i + 1])) [out[i], out[i + 1]] = [out[i + 1], out[i]]; + } + return out; + } + for (let i = 1; i < out.length; i++) { + if (chosen.has(out[i]) && !chosen.has(out[i - 1])) [out[i], out[i - 1]] = [out[i - 1], out[i]]; + } + return out; +} + +export function moveOps(path: Path, from: readonly Id[], to: readonly Id[]): Op[] { + const cur = [...from]; + const ops: Op[] = []; + to.forEach((id, k) => { + const j = cur.indexOf(id); + if (j < 0 || j === k) return; + cur.splice(j, 1); + cur.splice(k, 0, id); + ops.push({ op: 'move', path, from: j, to: k }); + }); + return ops; +} + +export function zOrderOps(doc: FormChemDocument, sel: Selection, how: ZOrder): Op[] { + const groups = new Map }>(); + for (const id of selectedIds(sel)) { + const c = containerOf(doc, id); + if (!c) continue; + const key = JSON.stringify(c.path); + const g = groups.get(key) ?? { c, chosen: new Set() }; + g.chosen.add(id); + groups.set(key, g); + } + const ops: Op[] = []; + for (const { c, chosen } of groups.values()) ops.push(...moveOps(c.path, c.list, reorder(c.list, chosen, how))); + return ops; +} + +const Z_LABELS: Record = { front: 'Bring to Front', forward: 'Bring Forward', backward: 'Send Backward', back: 'Send to Back' }; + +export function arrange(client: DocumentClient, sel: Selection, how: ZOrder): boolean { + const ops = zOrderOps(client.doc, sel, how); + return ops.length > 0 && client.commit(t(Z_LABELS[how]), ops) !== null; +} + +export const bringToFront = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'front'); +export const bringForward = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'forward'); +export const sendBackward = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'backward'); +export const sendToBack = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'back'); From eae9d7c76d253820efe831a234e6fd175c731eb0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:04:17 -0500 Subject: [PATCH 057/279] feat(app): add group and ungroup handlers (0.5.0) Group gathers the top-level objects of the selection into a new group object standing where the frontmost of them stood; ungroup puts a group's children back into its container at its place, keeping their order. Each is one transaction and returns the selection to show. --- frontend/src/app/object-commands.ts | 88 +++++++++++++++++++++++++++-- 1 file changed, 84 insertions(+), 4 deletions(-) diff --git a/frontend/src/app/object-commands.ts b/frontend/src/app/object-commands.ts index 8ba3f0a0..d482b701 100644 --- a/frontend/src/app/object-commands.ts +++ b/frontend/src/app/object-commands.ts @@ -1,7 +1,8 @@ -import { splitKey } from '../canvas/selection'; -import type { Selection } from '../canvas/types'; +import { makeSelection, splitKey, topLevel } from '../canvas/selection'; +import { currentPage, Draft } from '../canvas/tools/draft'; +import { selectionKey, type Selection } from '../canvas/types'; import type { DocumentClient } from '../engine/client-api'; -import type { FormChemDocument, Id } from '../engine/model'; +import { isFragment, newId, type FormChemDocument, type GroupObject, type Id } from '../engine/model'; import { objectPath, pagePath, type Op, type Path } from '../engine/ops'; import { t } from '../i18n'; @@ -73,7 +74,86 @@ export function arrange(client: DocumentClient, sel: Selection, how: ZOrder): bo return ops.length > 0 && client.commit(t(Z_LABELS[how]), ops) !== null; } -export const bringToFront = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'front'); +export function selectObjects(doc: FormChemDocument, ids: Iterable): Selection { + const atoms: string[] = [], bonds: string[] = [], objects: Id[] = []; + for (const id of ids) { + const o = doc.objects[id]; + if (!o) continue; + objects.push(id); + if (isFragment(o)) { + for (const a of Object.keys(o.atoms)) atoms.push(selectionKey(id, a)); + for (const b of Object.keys(o.bonds)) bonds.push(selectionKey(id, b)); + } + } + return makeSelection(atoms, bonds, objects); +} + +export function groupDraft(d: Draft, sel: Selection): Id | null { + const page = d.doc.pages.find((p) => p.id === d.page) ?? d.doc.pages[0]; + const tops = new Set(selectedIds(sel).map((id) => topLevel(d.doc, id))); + const items = page.order.filter((id) => tops.has(id)); + if (items.length < 2) return null; + const at = page.order.indexOf(items[items.length - 1]) - (items.length - 1); + for (const id of items) d.push({ op: 'del', path: pagePath(page.id, 'order'), id }); + const group: GroupObject = { id: newId('o'), kind: 'group', children: items }; + d.push({ op: 'set', path: objectPath(group.id), value: group }, { op: 'ins', path: pagePath(page.id, 'order'), index: at, value: group.id }); + return group.id; +} + +export function groupsToUngroup(doc: FormChemDocument, sel: Selection): Id[] { + const parent = new Map(); + for (const o of Object.values(doc.objects)) if (o.kind === 'group') for (const c of o.children) parent.set(c, o.id); + const out = new Set(); + for (const id of selectedIds(sel)) { + if (doc.objects[id]?.kind === 'group') out.add(id); + else if (parent.has(id)) out.add(parent.get(id)!); + } + for (const id of [...out]) { + let up = parent.get(id); + while (up) { + if (out.has(up)) { out.delete(id); break; } + up = parent.get(up); + } + } + return [...out]; +} + +export function ungroupDraft(d: Draft, sel: Selection): Id[] { + const freed: Id[] = []; + for (const gid of groupsToUngroup(d.doc, sel)) { + const g = d.doc.objects[gid]; + const c = containerOf(d.doc, gid); + if (!g || g.kind !== 'group' || !c) continue; + const at = c.list.indexOf(gid); + const kids = [...g.children]; + d.push({ op: 'del', path: c.path, id: gid }); + kids.forEach((kid, k) => d.push({ op: 'ins', path: c.path, index: at + k, value: kid })); + d.push({ op: 'set', path: objectPath(gid) }); + freed.push(...kids); + } + return freed; +} + +const draftOn = (client: DocumentClient, sel: Selection, page?: Id): Draft => { + const doc = client.doc; + return new Draft(doc, page && doc.pages.some((p) => p.id === page) ? page : currentPage(doc, selectedIds(sel))); +}; + +export function groupSelection(client: DocumentClient, sel: Selection, page?: Id): Selection | null { + const d = draftOn(client, sel, page); + const gid = groupDraft(d, sel); + if (!gid || !client.commit(t('Group'), d.ops)) return null; + return makeSelection([], [], [gid]); +} + +export function ungroupSelection(client: DocumentClient, sel: Selection, page?: Id): Selection | null { + const d = draftOn(client, sel, page); + const freed = ungroupDraft(d, sel); + if (!freed.length || !client.commit(t('Ungroup'), d.ops)) return null; + return selectObjects(client.doc, freed); +} + +export const bringToFront =(client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'front'); export const bringForward = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'forward'); export const sendBackward = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'backward'); export const sendToBack = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'back'); From 63a68b2f668a59c9146b424ce962e080625977df Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:04:59 -0500 Subject: [PATCH 058/279] feat(app): add align, distribute and Arrange command definitions for objects (0.5.0) alignObjects and distributeObjects run the tools' align and distribute on a client and selection without a canvas context, and objectCommandDefs builds the bring-front, bring-forward, send-backward, send-back, group and ungroup commands with their keys for the integration step to register. --- frontend/src/app/object-commands.ts | 48 +++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/object-commands.ts b/frontend/src/app/object-commands.ts index d482b701..9ee35154 100644 --- a/frontend/src/app/object-commands.ts +++ b/frontend/src/app/object-commands.ts @@ -1,5 +1,7 @@ -import { makeSelection, splitKey, topLevel } from '../canvas/selection'; +import { isEmpty, makeSelection, splitKey, topLevel } from '../canvas/selection'; import { currentPage, Draft } from '../canvas/tools/draft'; +import { alignSelection, distributeSelection, type AlignHow } from '../canvas/tools/transform'; +import type { CommandDef } from '../commands/registry'; import { selectionKey, type Selection } from '../canvas/types'; import type { DocumentClient } from '../engine/client-api'; import { isFragment, newId, type FormChemDocument, type GroupObject, type Id } from '../engine/model'; @@ -153,7 +155,49 @@ export function ungroupSelection(client: DocumentClient, sel: Selection, page?: return selectObjects(client.doc, freed); } -export const bringToFront =(client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'front'); +export function alignObjects(client: DocumentClient, sel: Selection, how: AlignHow, page?: Id): boolean { + const d = draftOn(client, sel, page); + alignSelection(d, sel, how); + return !d.empty && client.commit(t('Align'), d.ops) !== null; +} + +export function distributeObjects(client: DocumentClient, sel: Selection, axis: 'h' | 'v', page?: Id): boolean { + const d = draftOn(client, sel, page); + distributeSelection(d, sel, axis); + return !d.empty && client.commit(t('Distribute'), d.ops) !== null; +} + +export interface ObjectCommandHost { + readonly client: DocumentClient | null; + selection(): Selection; + setSelection(s: Selection): void; + page(): { id: Id } | null | undefined; +} + +export function objectCommandDefs(host: ObjectCommandHost, enabled: () => boolean): CommandDef[] { + const NEED = 'Select something on the canvas first'; + const run = (fn: (c: DocumentClient, s: Selection, page?: Id) => unknown) => (): void => { + const c = host.client; + if (c && !isEmpty(host.selection())) fn(c, host.selection(), host.page()?.id); + }; + const pick = (fn: (c: DocumentClient, s: Selection, page?: Id) => Selection | null) => run((c, s, p) => { + const next = fn(c, s, p); + if (next) host.setSelection(next); + }); + const z = (id: string, label: string, icon: string, keys: string[], how: ZOrder): CommandDef => ({ + id, label: () => t(label), group: 'Arrange', icon, keys, mutates: true, when: NEED, enabled, run: run((c, s) => arrange(c, s, how)), + }); + return [ + z('bring-front', 'Bring to Front', 'bringFront', ['Shift+Mod+]'], 'front'), + z('bring-forward', 'Bring Forward', 'bringForward', ['Mod+]'], 'forward'), + z('send-backward', 'Send Backward', 'sendBackward', ['Mod+['], 'backward'), + z('send-back', 'Send to Back', 'sendBack', ['Shift+Mod+['], 'back'), + { id: 'group', label: () => t('Group'), group: 'Arrange', icon: 'group', keys: ['Mod+G'], mutates: true, when: NEED, enabled, run: pick(groupSelection) }, + { id: 'ungroup', label: () => t('Ungroup'), group: 'Arrange', icon: 'ungroup', keys: ['Shift+Mod+G'], mutates: true, when: NEED, enabled, run: pick(ungroupSelection) }, + ]; +} + +export const bringToFront = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'front'); export const bringForward = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'forward'); export const sendBackward = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'backward'); export const sendToBack = (client: DocumentClient, sel: Selection): boolean => arrange(client, sel, 'back'); From d75f7f55ee9493e537a72dd6bdd05cc86e9d68d2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:11:17 -0500 Subject: [PATCH 059/279] fix(tools): include a bent arrow's arc in its bounds (0.5.0) Marquee selection, alignment and the rotate handle used only the two arrow ends, so a curved arrow's bulge fell outside its box; the arc's midpoint (or its whole circle past a half turn) now counts. --- frontend/src/canvas/tools/common.ts | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/frontend/src/canvas/tools/common.ts b/frontend/src/canvas/tools/common.ts index 60e89168..ba3e5f01 100644 --- a/frontend/src/canvas/tools/common.ts +++ b/frontend/src/canvas/tools/common.ts @@ -83,8 +83,25 @@ export function objectBounds(doc: FormChemDocument, obj: DocObject, depth = 0): const longest = Math.max(1, ...lines.map((l) => l.length)); return { x: obj.x, y: obj.y, w: obj.w ?? longest * size * 0.6, h: lines.length * size * 1.2 }; } - case 'arrow': - return { x: Math.min(obj.x1, obj.x2), y: Math.min(obj.y1, obj.y2), w: Math.abs(obj.x2 - obj.x1), h: Math.abs(obj.y2 - obj.y1) }; + case 'arrow': { + const pts: Rect[] = [{ x: obj.x1, y: obj.y1, w: 0, h: 0 }, { x: obj.x2, y: obj.y2, w: 0, h: 0 }]; + const c = Math.hypot(obj.x2 - obj.x1, obj.y2 - obj.y1); + if (obj.bend && c > 0) { + const lx = (obj.y2 - obj.y1) / c; + const ly = -(obj.x2 - obj.x1) / c; + const s = (c / 2) * Math.tan((obj.bend * Math.PI) / 720); + const mx = (obj.x1 + obj.x2) / 2 + lx * s; + const my = (obj.y1 + obj.y2) / 2 + ly * s; + pts.push({ x: mx, y: my, w: 0, h: 0 }); + if (Math.abs(obj.bend) > 180) { + const r = c / (2 * Math.sin((Math.abs(obj.bend) * Math.PI) / 360)); + const ox = mx - lx * Math.sign(s) * r; + const oy = my - ly * Math.sign(s) * r; + pts.push({ x: ox - r, y: oy - r, w: 2 * r, h: 2 * r }); + } + } + return unionRect(pts); + } case 'plus': { const s = obj.size ?? resolveStyle(doc, obj).bond_length * 0.6; return { x: obj.x - s / 2, y: obj.y - s / 2, w: s, h: s }; From 8fefb98ab0fcec02198fe6faa53b286db06ef6bb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 060/279] feat(templates): add ring and polycycle template data (0.5.0) Rings 3 to 8, benzene, dienes, chair conformers and cubane are stored as ring specs or hand-placed fragments, and fused, bridged and steroid skeletons as SMILES laid out by the engine, so the library is original data rather than copied clip art. --- backend/app/data/templates/polycycles.json | 25 ++++++ backend/app/data/templates/rings.json | 88 ++++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 backend/app/data/templates/polycycles.json create mode 100644 backend/app/data/templates/rings.json diff --git a/backend/app/data/templates/polycycles.json b/backend/app/data/templates/polycycles.json new file mode 100644 index 00000000..200e421a --- /dev/null +++ b/backend/app/data/templates/polycycles.json @@ -0,0 +1,25 @@ +{ + "category": "polycycles", + "name": "Polycycles", + "order": 20, + "templates": [ + { "id": "naphthalene", "name": "Naphthalene", "tags": ["fused", "arene", "bicyclic", "C10H8"], "smiles": "c1ccc2ccccc2c1" }, + { "id": "anthracene", "name": "Anthracene", "tags": ["fused", "arene", "tricyclic", "acene"], "smiles": "c1ccc2cc3ccccc3cc2c1" }, + { "id": "phenanthrene", "name": "Phenanthrene", "tags": ["fused", "arene", "tricyclic"], "smiles": "c1ccc2c(c1)ccc1ccccc12" }, + { "id": "pyrene", "name": "Pyrene", "tags": ["fused", "arene", "tetracyclic", "PAH"], "smiles": "c1cc2ccc3cccc4ccc(c1)c2c34" }, + { "id": "azulene", "name": "Azulene", "tags": ["fused", "non-benzenoid", "bicyclic"], "smiles": "c1ccc2cccc2cc1" }, + { "id": "biphenyl", "name": "Biphenyl", "tags": ["arene", "biaryl"], "smiles": "c1ccc(cc1)-c1ccccc1" }, + { "id": "fluorene", "name": "Fluorene", "tags": ["fused", "tricyclic"], "smiles": "C1c2ccccc2-c2ccccc12" }, + { "id": "indane", "name": "Indane", "tags": ["fused", "bicyclic", "benzocyclopentane"], "smiles": "C1Cc2ccccc2C1" }, + { "id": "indene", "name": "Indene", "tags": ["fused", "bicyclic"], "smiles": "C1C=Cc2ccccc12" }, + { "id": "tetralin", "name": "Tetralin", "tags": ["fused", "bicyclic", "tetrahydronaphthalene"], "smiles": "C1CCc2ccccc2C1" }, + { "id": "decalin", "name": "Decalin", "tags": ["fused", "bicyclic", "saturated"], "smiles": "C1CCC2CCCCC2C1" }, + { "id": "norbornane", "name": "Norbornane", "tags": ["bridged", "bicyclo[2.2.1]heptane"], "smiles": "C1CC2CCC1C2" }, + { "id": "bicyclo-2-2-2-octane", "name": "Bicyclo[2.2.2]octane", "tags": ["bridged"], "smiles": "C1CC2CCC1CC2" }, + { "id": "adamantane", "name": "Adamantane", "tags": ["bridged", "cage", "diamondoid"], "smiles": "C1C2CC3CC1CC(C2)C3" }, + { "id": "spiro-4-5-decane", "name": "Spiro[4.5]decane", "tags": ["spiro"], "smiles": "C1CCC2(CC1)CCCC2" }, + { "id": "steroid", "name": "Steroid skeleton (gonane)", "tags": ["steroid", "tetracyclic", "cyclopentanoperhydrophenanthrene", "gonane"], "smiles": "C1CCC2C(C1)CCC1C2CCC2CCCC21" }, + { "id": "estrane", "name": "Estrane", "tags": ["steroid", "tetracyclic"], "smiles": "CC12CCCC1C1CCC3CCCCC3C1CC2" }, + { "id": "androstane", "name": "Androstane", "tags": ["steroid", "tetracyclic"], "smiles": "CC12CCCC1C1CCC3CCCCC3(C)C1CC2" } + ] +} diff --git a/backend/app/data/templates/rings.json b/backend/app/data/templates/rings.json new file mode 100644 index 00000000..f22964e2 --- /dev/null +++ b/backend/app/data/templates/rings.json @@ -0,0 +1,88 @@ +{ + "category": "rings", + "name": "Rings", + "order": 10, + "templates": [ + { "id": "cyclopropane", "name": "Cyclopropane", "tags": ["C3", "cycloalkane", "three-membered"], "ring": { "elements": ["C", "C", "C"], "orders": [1, 1, 1] } }, + { "id": "cyclobutane", "name": "Cyclobutane", "tags": ["C4", "cycloalkane", "four-membered"], "ring": { "elements": ["C", "C", "C", "C"], "orders": [1, 1, 1, 1] } }, + { "id": "cyclopentane", "name": "Cyclopentane", "tags": ["C5", "cycloalkane", "five-membered"], "ring": { "elements": ["C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1] } }, + { "id": "cyclohexane", "name": "Cyclohexane", "tags": ["C6", "cycloalkane", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1, 1] } }, + { "id": "cycloheptane", "name": "Cycloheptane", "tags": ["C7", "cycloalkane", "seven-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1, 1, 1] } }, + { "id": "cyclooctane", "name": "Cyclooctane", "tags": ["C8", "cycloalkane", "eight-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C", "C"], "orders": [1, 1, 1, 1, 1, 1, 1, 1] } }, + { "id": "benzene", "name": "Benzene", "tags": ["arene", "aromatic", "phenyl", "C6H6"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "cyclopentadiene", "name": "Cyclopentadiene", "tags": ["diene", "C5H6", "five-membered"], "ring": { "elements": ["C", "C", "C", "C", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "cyclohexene", "name": "Cyclohexene", "tags": ["alkene", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 1, 1, 1, 1] } }, + { "id": "cyclohexa-1-3-diene", "name": "Cyclohexa-1,3-diene", "tags": ["diene", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 1, 1] } }, + { "id": "cyclohexa-1-4-diene", "name": "Cyclohexa-1,4-diene", "tags": ["diene", "six-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 1, 2, 1, 1] } }, + { "id": "cycloheptatriene", "name": "Cycloheptatriene", "tags": ["tropylidene", "seven-membered"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1, 1] } }, + { "id": "cyclooctatetraene", "name": "Cyclooctatetraene", "tags": ["COT", "eight-membered", "annulene"], "ring": { "elements": ["C", "C", "C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1, 2, 1] } }, + { + "id": "chair", "name": "Cyclohexane chair", "tags": ["conformation", "chair", "perspective"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "a1": { "id": "a1", "element": "C", "x": 0, "y": 15 }, + "a2": { "id": "a2", "element": "C", "x": 14, "y": 21 }, + "a3": { "id": "a3", "element": "C", "x": 31, "y": 16 }, + "a4": { "id": "a4", "element": "C", "x": 45, "y": 6 }, + "a5": { "id": "a5", "element": "C", "x": 31, "y": 0 }, + "a6": { "id": "a6", "element": "C", "x": 14, "y": 5 } }, + "bonds": { + "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1 }, + "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1 }, + "b3": { "id": "b3", "a": "a3", "b": "a4", "order": 1 }, + "b4": { "id": "b4", "a": "a4", "b": "a5", "order": 1 }, + "b5": { "id": "b5", "a": "a5", "b": "a6", "order": 1 }, + "b6": { "id": "b6", "a": "a6", "b": "a1", "order": 1 } } } + ] + }, + { + "id": "chair-flipped", "name": "Cyclohexane chair (flipped)", "tags": ["conformation", "chair", "perspective", "ring flip"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "a1": { "id": "a1", "element": "C", "x": 45, "y": 15 }, + "a2": { "id": "a2", "element": "C", "x": 31, "y": 21 }, + "a3": { "id": "a3", "element": "C", "x": 14, "y": 16 }, + "a4": { "id": "a4", "element": "C", "x": 0, "y": 6 }, + "a5": { "id": "a5", "element": "C", "x": 14, "y": 0 }, + "a6": { "id": "a6", "element": "C", "x": 31, "y": 5 } }, + "bonds": { + "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1 }, + "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1 }, + "b3": { "id": "b3", "a": "a3", "b": "a4", "order": 1 }, + "b4": { "id": "b4", "a": "a4", "b": "a5", "order": 1 }, + "b5": { "id": "b5", "a": "a5", "b": "a6", "order": 1 }, + "b6": { "id": "b6", "a": "a6", "b": "a1", "order": 1 } } } + ] + }, + { + "id": "cubane", "name": "Cubane", "tags": ["polycycle", "perspective", "C8H8"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "a1": { "id": "a1", "element": "C", "x": 0, "y": 8 }, + "a2": { "id": "a2", "element": "C", "x": 20, "y": 8 }, + "a3": { "id": "a3", "element": "C", "x": 20, "y": 28 }, + "a4": { "id": "a4", "element": "C", "x": 0, "y": 28 }, + "a5": { "id": "a5", "element": "C", "x": 8, "y": 0 }, + "a6": { "id": "a6", "element": "C", "x": 28, "y": 0 }, + "a7": { "id": "a7", "element": "C", "x": 28, "y": 20 }, + "a8": { "id": "a8", "element": "C", "x": 8, "y": 20 } }, + "bonds": { + "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1, "z": 2 }, + "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1, "z": 2 }, + "b3": { "id": "b3", "a": "a3", "b": "a4", "order": 1, "z": 2 }, + "b4": { "id": "b4", "a": "a4", "b": "a1", "order": 1, "z": 2 }, + "b5": { "id": "b5", "a": "a5", "b": "a6", "order": 1 }, + "b6": { "id": "b6", "a": "a6", "b": "a7", "order": 1 }, + "b7": { "id": "b7", "a": "a7", "b": "a8", "order": 1 }, + "b8": { "id": "b8", "a": "a8", "b": "a5", "order": 1 }, + "b9": { "id": "b9", "a": "a1", "b": "a5", "order": 1, "z": 1 }, + "b10": { "id": "b10", "a": "a2", "b": "a6", "order": 1, "z": 1 }, + "b11": { "id": "b11", "a": "a3", "b": "a7", "order": 1, "z": 1 }, + "b12": { "id": "b12", "a": "a4", "b": "a8", "order": 1 } } } + ] + } + ] +} From 1124634f4bdb4c7bb7e3e5bbd49b03d9d882de52 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 061/279] feat(templates): add heterocycle template data (0.5.0) Azines, azoles, fused heteroaromatics and saturated heterocycles cover the common scaffolds; monocycles use the flat-bottom ring generator so they land in the same orientation as the ring tools. --- backend/app/data/templates/heterocycles.json | 54 ++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 backend/app/data/templates/heterocycles.json diff --git a/backend/app/data/templates/heterocycles.json b/backend/app/data/templates/heterocycles.json new file mode 100644 index 00000000..4a5bf281 --- /dev/null +++ b/backend/app/data/templates/heterocycles.json @@ -0,0 +1,54 @@ +{ + "category": "heterocycles", + "name": "Heterocycles", + "order": 30, + "templates": [ + { "id": "pyridine", "name": "Pyridine", "tags": ["azine", "six-membered", "aromatic", "N"], "ring": { "elements": ["C", "C", "C", "N", "C", "C"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "pyrimidine", "name": "Pyrimidine", "tags": ["diazine", "1,3-diazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "C", "C", "N", "C", "N"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "pyrazine", "name": "Pyrazine", "tags": ["diazine", "1,4-diazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "C", "N", "C", "C", "N"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "pyridazine", "name": "Pyridazine", "tags": ["diazine", "1,2-diazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "C", "C", "N", "N", "C"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "triazine", "name": "1,3,5-Triazine", "tags": ["triazine", "six-membered", "aromatic"], "ring": { "elements": ["C", "N", "C", "N", "C", "N"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "pyran-2-one", "name": "2-Pyranone", "tags": ["pyrone", "lactone", "six-membered", "O"], "smiles": "O=c1cccco1" }, + { "id": "pyridin-2-one", "name": "2-Pyridone", "tags": ["pyridone", "lactam", "six-membered"], "smiles": "O=c1cccc[nH]1" }, + { "id": "furan", "name": "Furan", "tags": ["five-membered", "aromatic", "O"], "ring": { "elements": ["C", "C", "C", "O", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "thiophene", "name": "Thiophene", "tags": ["five-membered", "aromatic", "S"], "ring": { "elements": ["C", "C", "C", "S", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "pyrrole", "name": "Pyrrole", "tags": ["five-membered", "aromatic", "N", "azole"], "ring": { "elements": ["C", "C", "C", "N", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "imidazole", "name": "Imidazole", "tags": ["azole", "1,3-diazole", "five-membered", "aromatic"], "ring": { "elements": ["C", "N", "C", "N", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "pyrazole", "name": "Pyrazole", "tags": ["azole", "1,2-diazole", "five-membered", "aromatic"], "ring": { "elements": ["C", "C", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "oxazole", "name": "Oxazole", "tags": ["azole", "five-membered", "aromatic", "O", "N"], "ring": { "elements": ["C", "N", "C", "O", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "isoxazole", "name": "Isoxazole", "tags": ["azole", "five-membered", "aromatic", "O", "N"], "ring": { "elements": ["C", "C", "N", "O", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "thiazole", "name": "Thiazole", "tags": ["azole", "five-membered", "aromatic", "S", "N"], "ring": { "elements": ["C", "N", "C", "S", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "triazole-1-2-3", "name": "1,2,3-Triazole", "tags": ["azole", "triazole", "click", "five-membered"], "ring": { "elements": ["C", "N", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "triazole-1-2-4", "name": "1,2,4-Triazole", "tags": ["azole", "triazole", "five-membered"], "ring": { "elements": ["N", "C", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "tetrazole", "name": "Tetrazole", "tags": ["azole", "five-membered", "carboxylic acid isostere"], "ring": { "elements": ["N", "N", "N", "N", "C"], "orders": [1, 2, 1, 1, 2] } }, + { "id": "indole", "name": "Indole", "tags": ["fused", "bicyclic", "benzopyrrole", "N"], "smiles": "c1ccc2[nH]ccc2c1" }, + { "id": "benzofuran", "name": "Benzofuran", "tags": ["fused", "bicyclic", "O"], "smiles": "c1ccc2occc2c1" }, + { "id": "benzothiophene", "name": "Benzothiophene", "tags": ["fused", "bicyclic", "S"], "smiles": "c1ccc2sccc2c1" }, + { "id": "benzimidazole", "name": "Benzimidazole", "tags": ["fused", "bicyclic", "azole"], "smiles": "c1ccc2[nH]cnc2c1" }, + { "id": "benzoxazole", "name": "Benzoxazole", "tags": ["fused", "bicyclic", "azole"], "smiles": "c1ccc2ocnc2c1" }, + { "id": "benzothiazole", "name": "Benzothiazole", "tags": ["fused", "bicyclic", "azole"], "smiles": "c1ccc2scnc2c1" }, + { "id": "quinoline", "name": "Quinoline", "tags": ["fused", "bicyclic", "azine", "benzopyridine"], "smiles": "c1ccc2ncccc2c1" }, + { "id": "isoquinoline", "name": "Isoquinoline", "tags": ["fused", "bicyclic", "azine"], "smiles": "c1ccc2cnccc2c1" }, + { "id": "quinazoline", "name": "Quinazoline", "tags": ["fused", "bicyclic", "diazine"], "smiles": "c1ccc2ncncc2c1" }, + { "id": "quinoxaline", "name": "Quinoxaline", "tags": ["fused", "bicyclic", "diazine"], "smiles": "c1ccc2nccnc2c1" }, + { "id": "purine", "name": "Purine", "tags": ["fused", "bicyclic", "nucleobase core", "imidazopyrimidine"], "smiles": "c1ncc2[nH]cnc2n1" }, + { "id": "pteridine", "name": "Pteridine", "tags": ["fused", "bicyclic", "folate core"], "smiles": "c1cnc2ncncc2n1" }, + { "id": "carbazole", "name": "Carbazole", "tags": ["fused", "tricyclic", "N"], "smiles": "c1ccc2c(c1)[nH]c1ccccc12" }, + { "id": "acridine", "name": "Acridine", "tags": ["fused", "tricyclic", "azine"], "smiles": "c1ccc2nc3ccccc3cc2c1" }, + { "id": "phenothiazine", "name": "Phenothiazine", "tags": ["fused", "tricyclic", "S", "N"], "smiles": "c1ccc2c(c1)Nc1ccccc1S2" }, + { "id": "coumarin", "name": "Coumarin", "tags": ["fused", "bicyclic", "lactone", "chromen-2-one"], "smiles": "O=c1ccc2ccccc2o1" }, + { "id": "pyrrolidine", "name": "Pyrrolidine", "tags": ["saturated", "five-membered", "amine"], "ring": { "elements": ["C", "C", "C", "N", "C"], "orders": [1, 1, 1, 1, 1] } }, + { "id": "tetrahydrofuran", "name": "Tetrahydrofuran", "tags": ["THF", "saturated", "five-membered", "ether"], "ring": { "elements": ["C", "C", "C", "O", "C"], "orders": [1, 1, 1, 1, 1] } }, + { "id": "tetrahydrothiophene", "name": "Tetrahydrothiophene", "tags": ["thiolane", "saturated", "five-membered"], "ring": { "elements": ["C", "C", "C", "S", "C"], "orders": [1, 1, 1, 1, 1] } }, + { "id": "piperidine", "name": "Piperidine", "tags": ["saturated", "six-membered", "amine"], "ring": { "elements": ["C", "C", "C", "N", "C", "C"], "orders": [1, 1, 1, 1, 1, 1] } }, + { "id": "piperazine", "name": "Piperazine", "tags": ["saturated", "six-membered", "diamine"], "ring": { "elements": ["C", "C", "N", "C", "C", "N"], "orders": [1, 1, 1, 1, 1, 1] } }, + { "id": "morpholine", "name": "Morpholine", "tags": ["saturated", "six-membered", "amine", "ether"], "ring": { "elements": ["C", "C", "O", "C", "C", "N"], "orders": [1, 1, 1, 1, 1, 1] } }, + { "id": "tetrahydropyran", "name": "Tetrahydropyran", "tags": ["oxane", "THP", "saturated", "six-membered"], "ring": { "elements": ["C", "C", "C", "O", "C", "C"], "orders": [1, 1, 1, 1, 1, 1] } }, + { "id": "dioxane", "name": "1,4-Dioxane", "tags": ["saturated", "six-membered", "ether"], "ring": { "elements": ["C", "C", "O", "C", "C", "O"], "orders": [1, 1, 1, 1, 1, 1] } }, + { "id": "aziridine", "name": "Aziridine", "tags": ["three-membered", "N"], "ring": { "elements": ["C", "C", "N"], "orders": [1, 1, 1] } }, + { "id": "oxirane", "name": "Oxirane", "tags": ["epoxide", "three-membered", "O"], "ring": { "elements": ["C", "C", "O"], "orders": [1, 1, 1] } }, + { "id": "azetidine", "name": "Azetidine", "tags": ["four-membered", "N"], "ring": { "elements": ["C", "C", "N", "C"], "orders": [1, 1, 1, 1] } }, + { "id": "oxetane", "name": "Oxetane", "tags": ["four-membered", "O"], "ring": { "elements": ["C", "C", "O", "C"], "orders": [1, 1, 1, 1] } }, + { "id": "azepane", "name": "Azepane", "tags": ["seven-membered", "N"], "ring": { "elements": ["C", "C", "C", "C", "N", "C", "C"], "orders": [1, 1, 1, 1, 1, 1, 1] } } + ] +} From 3bf40ef1ebfb3d85d834d57324fcb47b62841914 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 062/279] feat(templates): add amino acid template data (0.5.0) The 20 proteinogenic amino acids are written as L-configured SMILES (checked against CIP: S throughout, R for cysteine) plus two zwitterions and a dipeptide backbone. --- backend/app/data/templates/amino-acids.json | 30 +++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 backend/app/data/templates/amino-acids.json diff --git a/backend/app/data/templates/amino-acids.json b/backend/app/data/templates/amino-acids.json new file mode 100644 index 00000000..7c779af6 --- /dev/null +++ b/backend/app/data/templates/amino-acids.json @@ -0,0 +1,30 @@ +{ + "category": "amino-acids", + "name": "Amino acids", + "order": 40, + "templates": [ + { "id": "glycine", "name": "Glycine", "tags": ["Gly", "G", "amino acid", "nonpolar"], "smiles": "NCC(=O)O" }, + { "id": "l-alanine", "name": "L-Alanine", "tags": ["Ala", "A", "amino acid", "nonpolar"], "smiles": "N[C@@H](C)C(=O)O" }, + { "id": "l-valine", "name": "L-Valine", "tags": ["Val", "V", "amino acid", "nonpolar", "branched"], "smiles": "N[C@@H](C(C)C)C(=O)O" }, + { "id": "l-leucine", "name": "L-Leucine", "tags": ["Leu", "L", "amino acid", "nonpolar", "branched"], "smiles": "N[C@@H](CC(C)C)C(=O)O" }, + { "id": "l-isoleucine", "name": "L-Isoleucine", "tags": ["Ile", "I", "amino acid", "nonpolar", "branched"], "smiles": "N[C@@H]([C@@H](C)CC)C(=O)O" }, + { "id": "l-proline", "name": "L-Proline", "tags": ["Pro", "P", "amino acid", "cyclic", "imino acid"], "smiles": "OC(=O)[C@@H]1CCCN1" }, + { "id": "l-phenylalanine", "name": "L-Phenylalanine", "tags": ["Phe", "F", "amino acid", "aromatic"], "smiles": "N[C@@H](Cc1ccccc1)C(=O)O" }, + { "id": "l-tryptophan", "name": "L-Tryptophan", "tags": ["Trp", "W", "amino acid", "aromatic", "indole"], "smiles": "N[C@@H](Cc1c[nH]c2ccccc12)C(=O)O" }, + { "id": "l-tyrosine", "name": "L-Tyrosine", "tags": ["Tyr", "Y", "amino acid", "aromatic", "phenol"], "smiles": "N[C@@H](Cc1ccc(O)cc1)C(=O)O" }, + { "id": "l-methionine", "name": "L-Methionine", "tags": ["Met", "M", "amino acid", "sulfur"], "smiles": "N[C@@H](CCSC)C(=O)O" }, + { "id": "l-cysteine", "name": "L-Cysteine", "tags": ["Cys", "C", "amino acid", "sulfur", "thiol"], "smiles": "N[C@@H](CS)C(=O)O" }, + { "id": "l-serine", "name": "L-Serine", "tags": ["Ser", "S", "amino acid", "polar", "hydroxyl"], "smiles": "N[C@@H](CO)C(=O)O" }, + { "id": "l-threonine", "name": "L-Threonine", "tags": ["Thr", "T", "amino acid", "polar", "hydroxyl"], "smiles": "N[C@@H]([C@@H](C)O)C(=O)O" }, + { "id": "l-asparagine", "name": "L-Asparagine", "tags": ["Asn", "N", "amino acid", "polar", "amide"], "smiles": "N[C@@H](CC(N)=O)C(=O)O" }, + { "id": "l-glutamine", "name": "L-Glutamine", "tags": ["Gln", "Q", "amino acid", "polar", "amide"], "smiles": "N[C@@H](CCC(N)=O)C(=O)O" }, + { "id": "l-aspartic-acid", "name": "L-Aspartic acid", "tags": ["Asp", "D", "amino acid", "acidic", "aspartate"], "smiles": "N[C@@H](CC(=O)O)C(=O)O" }, + { "id": "l-glutamic-acid", "name": "L-Glutamic acid", "tags": ["Glu", "E", "amino acid", "acidic", "glutamate"], "smiles": "N[C@@H](CCC(=O)O)C(=O)O" }, + { "id": "l-lysine", "name": "L-Lysine", "tags": ["Lys", "K", "amino acid", "basic"], "smiles": "N[C@@H](CCCCN)C(=O)O" }, + { "id": "l-arginine", "name": "L-Arginine", "tags": ["Arg", "R", "amino acid", "basic", "guanidine"], "smiles": "N[C@@H](CCCNC(N)=N)C(=O)O" }, + { "id": "l-histidine", "name": "L-Histidine", "tags": ["His", "H", "amino acid", "basic", "imidazole"], "smiles": "N[C@@H](Cc1c[nH]cn1)C(=O)O" }, + { "id": "glycine-zwitterion", "name": "Glycine (zwitterion)", "tags": ["Gly", "zwitterion", "amino acid"], "smiles": "[NH3+]CC(=O)[O-]" }, + { "id": "l-alanine-zwitterion", "name": "L-Alanine (zwitterion)", "tags": ["Ala", "zwitterion", "amino acid"], "smiles": "[NH3+][C@@H](C)C(=O)[O-]" }, + { "id": "peptide-bond", "name": "Dipeptide backbone", "tags": ["peptide", "amide", "backbone", "Gly-Gly"], "smiles": "NCC(=O)NCC(=O)O" } + ] +} From cfb518c50bd04111236401330e8d1748c07be25f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 063/279] feat(templates): add sugar and nucleotide template data (0.5.0) Haworth pyranoses and furanoses and a Fischer glucose are hand-placed fragments with bold front bonds; nucleobases, nucleosides and AMP and ATP are stereo SMILES laid out by the engine. --- backend/app/data/templates/nucleotides.json | 21 ++ backend/app/data/templates/sugars.json | 204 ++++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 backend/app/data/templates/nucleotides.json create mode 100644 backend/app/data/templates/sugars.json diff --git a/backend/app/data/templates/nucleotides.json b/backend/app/data/templates/nucleotides.json new file mode 100644 index 00000000..3a6075bf --- /dev/null +++ b/backend/app/data/templates/nucleotides.json @@ -0,0 +1,21 @@ +{ + "category": "nucleotides", + "name": "Nucleotides", + "order": 60, + "templates": [ + { "id": "adenine", "name": "Adenine", "tags": ["nucleobase", "purine", "A", "DNA", "RNA"], "smiles": "Nc1ncnc2[nH]cnc12" }, + { "id": "guanine", "name": "Guanine", "tags": ["nucleobase", "purine", "G", "DNA", "RNA"], "smiles": "Nc1nc2[nH]cnc2c(=O)[nH]1" }, + { "id": "cytosine", "name": "Cytosine", "tags": ["nucleobase", "pyrimidine", "C", "DNA", "RNA"], "smiles": "Nc1cc[nH]c(=O)n1" }, + { "id": "thymine", "name": "Thymine", "tags": ["nucleobase", "pyrimidine", "T", "DNA"], "smiles": "Cc1c[nH]c(=O)[nH]c1=O" }, + { "id": "uracil", "name": "Uracil", "tags": ["nucleobase", "pyrimidine", "U", "RNA"], "smiles": "O=c1cc[nH]c(=O)[nH]1" }, + { "id": "adenosine", "name": "Adenosine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](CO)[C@@H](O)[C@H]1O" }, + { "id": "guanosine", "name": "Guanosine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "Nc1nc2n(cnc2c(=O)[nH]1)[C@@H]1O[C@H](CO)[C@@H](O)[C@H]1O" }, + { "id": "cytidine", "name": "Cytidine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "Nc1ccn([C@@H]2O[C@H](CO)[C@@H](O)[C@H]2O)c(=O)n1" }, + { "id": "uridine", "name": "Uridine", "tags": ["nucleoside", "ribose", "RNA"], "smiles": "O=c1ccn([C@@H]2O[C@H](CO)[C@@H](O)[C@H]2O)c(=O)[nH]1" }, + { "id": "deoxyadenosine", "name": "2'-Deoxyadenosine", "tags": ["nucleoside", "deoxyribose", "DNA"], "smiles": "Nc1ncnc2c1ncn2[C@H]1C[C@H](O)[C@@H](CO)O1" }, + { "id": "thymidine", "name": "Thymidine", "tags": ["nucleoside", "deoxyribose", "DNA"], "smiles": "Cc1cn([C@H]2C[C@H](O)[C@@H](CO)O2)c(=O)[nH]c1=O" }, + { "id": "amp", "name": "Adenosine monophosphate (AMP)", "tags": ["nucleotide", "phosphate", "AMP"], "smiles": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)O)[C@@H](O)[C@H]1O" }, + { "id": "atp", "name": "Adenosine triphosphate (ATP)", "tags": ["nucleotide", "triphosphate", "ATP", "energy"], "smiles": "Nc1ncnc2c1ncn2[C@@H]1O[C@H](COP(=O)(O)OP(=O)(O)OP(=O)(O)O)[C@@H](O)[C@H]1O" }, + { "id": "phosphodiester", "name": "Phosphodiester linkage", "tags": ["backbone", "phosphate", "DNA", "RNA"], "smiles": "COP(=O)(O)OC" } + ] +} diff --git a/backend/app/data/templates/sugars.json b/backend/app/data/templates/sugars.json new file mode 100644 index 00000000..37d03a7c --- /dev/null +++ b/backend/app/data/templates/sugars.json @@ -0,0 +1,204 @@ +{ + "category": "sugars", + "name": "Sugars", + "order": 50, + "templates": [ + { + "id": "beta-d-glucopyranose", "name": "beta-D-Glucopyranose (Haworth)", "tags": ["glucose", "pyranose", "Haworth", "hexose", "carbohydrate"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "c1": { "id": "c1", "element": "C", "x": 56, "y": 37 }, + "c2": { "id": "c2", "element": "C", "x": 42, "y": 52 }, + "c3": { "id": "c3", "element": "C", "x": 14, "y": 52 }, + "c4": { "id": "c4", "element": "C", "x": 0, "y": 37 }, + "c5": { "id": "c5", "element": "C", "x": 14, "y": 22 }, + "o5": { "id": "o5", "element": "O", "x": 42, "y": 22 }, + "o1": { "id": "o1", "element": "O", "x": 56, "y": 23 }, + "o2": { "id": "o2", "element": "O", "x": 42, "y": 66 }, + "o3": { "id": "o3", "element": "O", "x": 14, "y": 40 }, + "o4": { "id": "o4", "element": "O", "x": 0, "y": 51 }, + "c6": { "id": "c6", "element": "C", "x": 14, "y": 8 }, + "o6": { "id": "o6", "element": "O", "x": 1.53, "y": 0.8 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true }, + "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true }, + "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true }, + "b4": { "id": "b4", "a": "c4", "b": "c5", "order": 1 }, + "b5": { "id": "b5", "a": "c5", "b": "o5", "order": 1 }, + "b6": { "id": "b6", "a": "o5", "b": "c1", "order": 1 }, + "b7": { "id": "b7", "a": "c1", "b": "o1", "order": 1 }, + "b8": { "id": "b8", "a": "c2", "b": "o2", "order": 1 }, + "b9": { "id": "b9", "a": "c3", "b": "o3", "order": 1 }, + "b10": { "id": "b10", "a": "c4", "b": "o4", "order": 1 }, + "b11": { "id": "b11", "a": "c5", "b": "c6", "order": 1 }, + "b12": { "id": "b12", "a": "c6", "b": "o6", "order": 1 } } } + ] + }, + { + "id": "alpha-d-glucopyranose", "name": "alpha-D-Glucopyranose (Haworth)", "tags": ["glucose", "pyranose", "Haworth", "hexose", "carbohydrate", "anomer"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "c1": { "id": "c1", "element": "C", "x": 56, "y": 37 }, + "c2": { "id": "c2", "element": "C", "x": 42, "y": 52 }, + "c3": { "id": "c3", "element": "C", "x": 14, "y": 52 }, + "c4": { "id": "c4", "element": "C", "x": 0, "y": 37 }, + "c5": { "id": "c5", "element": "C", "x": 14, "y": 22 }, + "o5": { "id": "o5", "element": "O", "x": 42, "y": 22 }, + "o1": { "id": "o1", "element": "O", "x": 56, "y": 51 }, + "o2": { "id": "o2", "element": "O", "x": 42, "y": 66 }, + "o3": { "id": "o3", "element": "O", "x": 14, "y": 40 }, + "o4": { "id": "o4", "element": "O", "x": 0, "y": 51 }, + "c6": { "id": "c6", "element": "C", "x": 14, "y": 8 }, + "o6": { "id": "o6", "element": "O", "x": 1.53, "y": 0.8 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true }, + "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true }, + "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true }, + "b4": { "id": "b4", "a": "c4", "b": "c5", "order": 1 }, + "b5": { "id": "b5", "a": "c5", "b": "o5", "order": 1 }, + "b6": { "id": "b6", "a": "o5", "b": "c1", "order": 1 }, + "b7": { "id": "b7", "a": "c1", "b": "o1", "order": 1 }, + "b8": { "id": "b8", "a": "c2", "b": "o2", "order": 1 }, + "b9": { "id": "b9", "a": "c3", "b": "o3", "order": 1 }, + "b10": { "id": "b10", "a": "c4", "b": "o4", "order": 1 }, + "b11": { "id": "b11", "a": "c5", "b": "c6", "order": 1 }, + "b12": { "id": "b12", "a": "c6", "b": "o6", "order": 1 } } } + ] + }, + { + "id": "pyranose-ring", "name": "Pyranose ring (Haworth)", "tags": ["pyranose", "Haworth", "skeleton", "oxane"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "c1": { "id": "c1", "element": "C", "x": 56, "y": 15 }, + "c2": { "id": "c2", "element": "C", "x": 42, "y": 30 }, + "c3": { "id": "c3", "element": "C", "x": 14, "y": 30 }, + "c4": { "id": "c4", "element": "C", "x": 0, "y": 15 }, + "c5": { "id": "c5", "element": "C", "x": 14, "y": 0 }, + "o5": { "id": "o5", "element": "O", "x": 42, "y": 0 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true }, + "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true }, + "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true }, + "b4": { "id": "b4", "a": "c4", "b": "c5", "order": 1 }, + "b5": { "id": "b5", "a": "c5", "b": "o5", "order": 1 }, + "b6": { "id": "b6", "a": "o5", "b": "c1", "order": 1 } } } + ] + }, + { + "id": "beta-d-ribofuranose", "name": "beta-D-Ribofuranose (Haworth)", "tags": ["ribose", "furanose", "Haworth", "pentose", "carbohydrate"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "o4": { "id": "o4", "element": "O", "x": 37, "y": 8 }, + "c1": { "id": "c1", "element": "C", "x": 61, "y": 22 }, + "c2": { "id": "c2", "element": "C", "x": 51, "y": 38 }, + "c3": { "id": "c3", "element": "C", "x": 23, "y": 38 }, + "c4": { "id": "c4", "element": "C", "x": 13, "y": 22 }, + "o1": { "id": "o1", "element": "O", "x": 61, "y": 8 }, + "o2": { "id": "o2", "element": "O", "x": 51, "y": 52 }, + "o3": { "id": "o3", "element": "O", "x": 23, "y": 52 }, + "c5": { "id": "c5", "element": "C", "x": 13, "y": 8 }, + "o5": { "id": "o5", "element": "O", "x": 0.53, "y": 0.8 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true }, + "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true }, + "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true }, + "b4": { "id": "b4", "a": "c4", "b": "o4", "order": 1 }, + "b5": { "id": "b5", "a": "o4", "b": "c1", "order": 1 }, + "b6": { "id": "b6", "a": "c1", "b": "o1", "order": 1 }, + "b7": { "id": "b7", "a": "c2", "b": "o2", "order": 1 }, + "b8": { "id": "b8", "a": "c3", "b": "o3", "order": 1 }, + "b9": { "id": "b9", "a": "c4", "b": "c5", "order": 1 }, + "b10": { "id": "b10", "a": "c5", "b": "o5", "order": 1 } } } + ] + }, + { + "id": "2-deoxy-beta-d-ribofuranose", "name": "2-Deoxy-beta-D-ribofuranose (Haworth)", "tags": ["deoxyribose", "furanose", "Haworth", "DNA sugar"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "o4": { "id": "o4", "element": "O", "x": 37, "y": 8 }, + "c1": { "id": "c1", "element": "C", "x": 61, "y": 22 }, + "c2": { "id": "c2", "element": "C", "x": 51, "y": 38 }, + "c3": { "id": "c3", "element": "C", "x": 23, "y": 38 }, + "c4": { "id": "c4", "element": "C", "x": 13, "y": 22 }, + "o1": { "id": "o1", "element": "O", "x": 61, "y": 8 }, + "o3": { "id": "o3", "element": "O", "x": 23, "y": 52 }, + "c5": { "id": "c5", "element": "C", "x": 13, "y": 8 }, + "o5": { "id": "o5", "element": "O", "x": 0.53, "y": 0.8 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true }, + "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true }, + "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true }, + "b4": { "id": "b4", "a": "c4", "b": "o4", "order": 1 }, + "b5": { "id": "b5", "a": "o4", "b": "c1", "order": 1 }, + "b6": { "id": "b6", "a": "c1", "b": "o1", "order": 1 }, + "b8": { "id": "b8", "a": "c3", "b": "o3", "order": 1 }, + "b9": { "id": "b9", "a": "c4", "b": "c5", "order": 1 }, + "b10": { "id": "b10", "a": "c5", "b": "o5", "order": 1 } } } + ] + }, + { + "id": "furanose-ring", "name": "Furanose ring (Haworth)", "tags": ["furanose", "Haworth", "skeleton", "oxolane"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "o4": { "id": "o4", "element": "O", "x": 24, "y": 0 }, + "c1": { "id": "c1", "element": "C", "x": 48, "y": 14 }, + "c2": { "id": "c2", "element": "C", "x": 38, "y": 30 }, + "c3": { "id": "c3", "element": "C", "x": 10, "y": 30 }, + "c4": { "id": "c4", "element": "C", "x": 0, "y": 14 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "c2", "order": 1, "bold": true }, + "b2": { "id": "b2", "a": "c2", "b": "c3", "order": 1, "bold": true }, + "b3": { "id": "b3", "a": "c3", "b": "c4", "order": 1, "bold": true }, + "b4": { "id": "b4", "a": "c4", "b": "o4", "order": 1 }, + "b5": { "id": "b5", "a": "o4", "b": "c1", "order": 1 } } } + ] + }, + { + "id": "d-glucose-fischer", "name": "D-Glucose (Fischer)", "tags": ["glucose", "Fischer", "open chain", "aldohexose"], + "objects": [ + { "id": "f1", "kind": "fragment", + "atoms": { + "c1": { "id": "c1", "element": "C", "x": 14.4, "y": 7.2 }, + "o1": { "id": "o1", "element": "O", "x": 26.87, "y": 0 }, + "c2": { "id": "c2", "element": "C", "x": 14.4, "y": 21.6 }, + "c3": { "id": "c3", "element": "C", "x": 14.4, "y": 36 }, + "c4": { "id": "c4", "element": "C", "x": 14.4, "y": 50.4 }, + "c5": { "id": "c5", "element": "C", "x": 14.4, "y": 64.8 }, + "c6": { "id": "c6", "element": "C", "x": 14.4, "y": 79.2 }, + "o6": { "id": "o6", "element": "O", "x": 14.4, "y": 93.6 }, + "h2": { "id": "h2", "element": "H", "x": 0, "y": 21.6 }, + "o2": { "id": "o2", "element": "O", "x": 28.8, "y": 21.6 }, + "o3": { "id": "o3", "element": "O", "x": 0, "y": 36 }, + "h3": { "id": "h3", "element": "H", "x": 28.8, "y": 36 }, + "h4": { "id": "h4", "element": "H", "x": 0, "y": 50.4 }, + "o4": { "id": "o4", "element": "O", "x": 28.8, "y": 50.4 }, + "h5": { "id": "h5", "element": "H", "x": 0, "y": 64.8 }, + "o5": { "id": "o5", "element": "O", "x": 28.8, "y": 64.8 } }, + "bonds": { + "b1": { "id": "b1", "a": "c1", "b": "o1", "order": 2 }, + "b2": { "id": "b2", "a": "c1", "b": "c2", "order": 1 }, + "b3": { "id": "b3", "a": "c2", "b": "c3", "order": 1 }, + "b4": { "id": "b4", "a": "c3", "b": "c4", "order": 1 }, + "b5": { "id": "b5", "a": "c4", "b": "c5", "order": 1 }, + "b6": { "id": "b6", "a": "c5", "b": "c6", "order": 1 }, + "b7": { "id": "b7", "a": "c6", "b": "o6", "order": 1 }, + "b8": { "id": "b8", "a": "c2", "b": "h2", "order": 1 }, + "b9": { "id": "b9", "a": "c2", "b": "o2", "order": 1 }, + "b10": { "id": "b10", "a": "c3", "b": "o3", "order": 1 }, + "b11": { "id": "b11", "a": "c3", "b": "h3", "order": 1 }, + "b12": { "id": "b12", "a": "c4", "b": "h4", "order": 1 }, + "b13": { "id": "b13", "a": "c4", "b": "o4", "order": 1 }, + "b14": { "id": "b14", "a": "c5", "b": "h5", "order": 1 }, + "b15": { "id": "b15", "a": "c5", "b": "o5", "order": 1 } } } + ] + }, + { "id": "glucose-smiles", "name": "beta-D-Glucose (skeletal)", "tags": ["glucose", "pyranose", "skeletal", "stereo"], "smiles": "OC[C@H]1O[C@@H](O)[C@H](O)[C@@H](O)[C@@H]1O" }, + { "id": "fructose-smiles", "name": "beta-D-Fructofuranose (skeletal)", "tags": ["fructose", "furanose", "ketose", "skeletal"], "smiles": "OC[C@H]1O[C@](O)(CO)[C@@H](O)[C@@H]1O" } + ] +} From 79531a0ba36603c598368c55d0eb2eb8d40aeff7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 064/279] feat(templates): add protecting group and reagent template data (0.5.0) Protecting groups carry a star attachment atom so they read as substituents, and common reagents and solvents give schemes their agents in one click. --- .../app/data/templates/protecting-groups.json | 32 ++++++++++++ backend/app/data/templates/reagents.json | 50 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 backend/app/data/templates/protecting-groups.json create mode 100644 backend/app/data/templates/reagents.json diff --git a/backend/app/data/templates/protecting-groups.json b/backend/app/data/templates/protecting-groups.json new file mode 100644 index 00000000..3f5448ee --- /dev/null +++ b/backend/app/data/templates/protecting-groups.json @@ -0,0 +1,32 @@ +{ + "category": "protecting-groups", + "name": "Protecting groups", + "order": 70, + "templates": [ + { "id": "boc", "name": "Boc (tert-butoxycarbonyl)", "tags": ["amine protection", "carbamate", "Boc"], "smiles": "*C(=O)OC(C)(C)C" }, + { "id": "cbz", "name": "Cbz (benzyloxycarbonyl)", "tags": ["amine protection", "carbamate", "Z", "Cbz"], "smiles": "*C(=O)OCc1ccccc1" }, + { "id": "fmoc", "name": "Fmoc (fluorenylmethoxycarbonyl)", "tags": ["amine protection", "carbamate", "peptide synthesis"], "smiles": "*C(=O)OCC1c2ccccc2-c2ccccc21" }, + { "id": "alloc", "name": "Alloc (allyloxycarbonyl)", "tags": ["amine protection", "carbamate"], "smiles": "*C(=O)OCC=C" }, + { "id": "bn", "name": "Bn (benzyl)", "tags": ["alcohol protection", "amine protection", "ether"], "smiles": "*Cc1ccccc1" }, + { "id": "pmb", "name": "PMB (p-methoxybenzyl)", "tags": ["alcohol protection", "ether", "MPM"], "smiles": "*Cc1ccc(OC)cc1" }, + { "id": "ac", "name": "Ac (acetyl)", "tags": ["alcohol protection", "amine protection", "ester", "amide"], "smiles": "*C(C)=O" }, + { "id": "bz", "name": "Bz (benzoyl)", "tags": ["alcohol protection", "ester"], "smiles": "*C(=O)c1ccccc1" }, + { "id": "piv", "name": "Piv (pivaloyl)", "tags": ["alcohol protection", "ester", "Pv"], "smiles": "*C(=O)C(C)(C)C" }, + { "id": "tms", "name": "TMS (trimethylsilyl)", "tags": ["alcohol protection", "silyl ether"], "smiles": "*[Si](C)(C)C" }, + { "id": "tbs", "name": "TBS (tert-butyldimethylsilyl)", "tags": ["alcohol protection", "silyl ether", "TBDMS"], "smiles": "*[Si](C)(C)C(C)(C)C" }, + { "id": "tips", "name": "TIPS (triisopropylsilyl)", "tags": ["alcohol protection", "silyl ether"], "smiles": "*[Si](C(C)C)(C(C)C)C(C)C" }, + { "id": "tbdps", "name": "TBDPS (tert-butyldiphenylsilyl)", "tags": ["alcohol protection", "silyl ether"], "smiles": "*[Si](c1ccccc1)(c1ccccc1)C(C)(C)C" }, + { "id": "trityl", "name": "Tr (trityl)", "tags": ["alcohol protection", "amine protection", "triphenylmethyl"], "smiles": "*C(c1ccccc1)(c1ccccc1)c1ccccc1" }, + { "id": "mom", "name": "MOM (methoxymethyl)", "tags": ["alcohol protection", "acetal"], "smiles": "*COC" }, + { "id": "mem", "name": "MEM (2-methoxyethoxymethyl)", "tags": ["alcohol protection", "acetal"], "smiles": "*COCCOC" }, + { "id": "sem", "name": "SEM (2-(trimethylsilyl)ethoxymethyl)", "tags": ["alcohol protection", "amine protection", "acetal"], "smiles": "*COCC[Si](C)(C)C" }, + { "id": "thp", "name": "THP (tetrahydropyranyl)", "tags": ["alcohol protection", "acetal"], "smiles": "*C1CCCCO1" }, + { "id": "ts", "name": "Ts (tosyl)", "tags": ["amine protection", "sulfonyl", "leaving group"], "smiles": "*S(=O)(=O)c1ccc(C)cc1" }, + { "id": "ms", "name": "Ms (mesyl)", "tags": ["sulfonyl", "leaving group"], "smiles": "*S(=O)(=O)C" }, + { "id": "ns", "name": "Ns (2-nitrobenzenesulfonyl)", "tags": ["amine protection", "sulfonyl", "nosyl"], "smiles": "*S(=O)(=O)c1ccccc1[N+](=O)[O-]" }, + { "id": "acetonide", "name": "Acetonide (isopropylidene)", "tags": ["diol protection", "ketal"], "smiles": "*OC(C)(C)O*" }, + { "id": "benzylidene", "name": "Benzylidene acetal", "tags": ["diol protection", "acetal"], "smiles": "*OC(O*)c1ccccc1" }, + { "id": "dioxolane", "name": "1,3-Dioxolane (ketone protection)", "tags": ["carbonyl protection", "ketal", "ethylene glycol"], "smiles": "*C1(*)OCCO1" }, + { "id": "phthalimide", "name": "Phthalimide (Phth)", "tags": ["amine protection", "imide", "Gabriel"], "smiles": "*N1C(=O)c2ccccc2C1=O" } + ] +} diff --git a/backend/app/data/templates/reagents.json b/backend/app/data/templates/reagents.json new file mode 100644 index 00000000..06341a53 --- /dev/null +++ b/backend/app/data/templates/reagents.json @@ -0,0 +1,50 @@ +{ + "category": "reagents", + "name": "Reagents and solvents", + "order": 80, + "templates": [ + { "id": "dcc", "name": "DCC", "tags": ["coupling", "carbodiimide", "dicyclohexylcarbodiimide"], "smiles": "C1CCC(CC1)N=C=NC1CCCCC1" }, + { "id": "edc", "name": "EDC", "tags": ["coupling", "carbodiimide"], "smiles": "CCN=C=NCCCN(C)C" }, + { "id": "hatu", "name": "HATU", "tags": ["coupling", "uronium", "peptide"], "smiles": "CN(C)C(On1nnc2cccnc21)=[N+](C)C.F[P-](F)(F)(F)(F)F" }, + { "id": "dmap", "name": "DMAP", "tags": ["base", "acylation catalyst", "4-dimethylaminopyridine"], "smiles": "CN(C)c1ccncc1" }, + { "id": "triethylamine", "name": "Triethylamine", "tags": ["base", "Et3N", "TEA"], "smiles": "CCN(CC)CC" }, + { "id": "dipea", "name": "DIPEA", "tags": ["base", "Hunig's base", "iPr2NEt"], "smiles": "CCN(C(C)C)C(C)C" }, + { "id": "dbu", "name": "DBU", "tags": ["base", "amidine"], "smiles": "C1CCC2=NCCCN2CC1" }, + { "id": "pyridine-reagent", "name": "Pyridine", "tags": ["base", "solvent"], "smiles": "c1ccncc1" }, + { "id": "nabh4", "name": "Sodium borohydride", "tags": ["reductant", "hydride", "NaBH4"], "smiles": "[Na+].[BH4-]" }, + { "id": "lialh4", "name": "Lithium aluminium hydride", "tags": ["reductant", "hydride", "LAH", "LiAlH4"], "smiles": "[Li+].[AlH4-]" }, + { "id": "dibal", "name": "DIBAL-H", "tags": ["reductant", "hydride", "diisobutylaluminium hydride"], "smiles": "CC(C)C[AlH]CC(C)C" }, + { "id": "nah", "name": "Sodium hydride", "tags": ["base", "hydride", "NaH"], "smiles": "[Na+].[H-]" }, + { "id": "nbuli", "name": "n-Butyllithium", "tags": ["base", "organolithium", "nBuLi"], "smiles": "[Li]CCCC" }, + { "id": "lda", "name": "LDA", "tags": ["base", "amide", "lithium diisopropylamide"], "smiles": "[Li+].CC(C)[N-]C(C)C" }, + { "id": "k2co3", "name": "Potassium carbonate", "tags": ["base", "K2CO3"], "smiles": "[K+].[K+].[O-]C([O-])=O" }, + { "id": "mcpba", "name": "mCPBA", "tags": ["oxidant", "peracid", "epoxidation"], "smiles": "OOC(=O)c1cccc(Cl)c1" }, + { "id": "tempo", "name": "TEMPO", "tags": ["oxidant", "radical", "nitroxide"], "smiles": "CC1(C)CCCC(C)(C)N1[O]" }, + { "id": "tscl", "name": "Tosyl chloride", "tags": ["sulfonylation", "TsCl"], "smiles": "Cc1ccc(cc1)S(Cl)(=O)=O" }, + { "id": "mscl", "name": "Mesyl chloride", "tags": ["sulfonylation", "MsCl"], "smiles": "CS(Cl)(=O)=O" }, + { "id": "socl2", "name": "Thionyl chloride", "tags": ["chlorination", "acid chloride", "SOCl2"], "smiles": "O=S(Cl)Cl" }, + { "id": "oxalyl-chloride", "name": "Oxalyl chloride", "tags": ["chlorination", "acid chloride", "Swern"], "smiles": "O=C(Cl)C(Cl)=O" }, + { "id": "boc2o", "name": "Di-tert-butyl dicarbonate", "tags": ["Boc2O", "protection"], "smiles": "CC(C)(C)OC(=O)OC(=O)OC(C)(C)C" }, + { "id": "nbs", "name": "NBS", "tags": ["bromination", "N-bromosuccinimide"], "smiles": "BrN1C(=O)CCC1=O" }, + { "id": "tbaf", "name": "TBAF", "tags": ["fluoride", "desilylation", "tetrabutylammonium fluoride"], "smiles": "CCCC[N+](CCCC)(CCCC)CCCC.[F-]" }, + { "id": "pph3", "name": "Triphenylphosphine", "tags": ["phosphine", "PPh3", "Wittig", "Mitsunobu"], "smiles": "c1ccc(cc1)P(c1ccccc1)c1ccccc1" }, + { "id": "dead", "name": "DEAD", "tags": ["Mitsunobu", "azodicarboxylate"], "smiles": "CCOC(=O)N=NC(=O)OCC" }, + { "id": "diad", "name": "DIAD", "tags": ["Mitsunobu", "azodicarboxylate"], "smiles": "CC(C)OC(=O)N=NC(=O)OC(C)C" }, + { "id": "tfa", "name": "Trifluoroacetic acid", "tags": ["acid", "TFA", "deprotection"], "smiles": "OC(=O)C(F)(F)F" }, + { "id": "acetic-acid", "name": "Acetic acid", "tags": ["acid", "solvent", "AcOH"], "smiles": "CC(=O)O" }, + { "id": "water", "name": "Water", "tags": ["solvent", "H2O"], "smiles": "O" }, + { "id": "methanol", "name": "Methanol", "tags": ["solvent", "MeOH"], "smiles": "CO" }, + { "id": "ethanol", "name": "Ethanol", "tags": ["solvent", "EtOH"], "smiles": "CCO" }, + { "id": "thf", "name": "THF", "tags": ["solvent", "ether", "tetrahydrofuran"], "smiles": "C1CCOC1" }, + { "id": "diethyl-ether", "name": "Diethyl ether", "tags": ["solvent", "ether", "Et2O"], "smiles": "CCOCC" }, + { "id": "dcm", "name": "Dichloromethane", "tags": ["solvent", "DCM", "CH2Cl2"], "smiles": "ClCCl" }, + { "id": "chloroform", "name": "Chloroform", "tags": ["solvent", "CHCl3"], "smiles": "ClC(Cl)Cl" }, + { "id": "dmf", "name": "DMF", "tags": ["solvent", "dimethylformamide"], "smiles": "CN(C)C=O" }, + { "id": "dmso", "name": "DMSO", "tags": ["solvent", "dimethyl sulfoxide"], "smiles": "CS(C)=O" }, + { "id": "acetonitrile", "name": "Acetonitrile", "tags": ["solvent", "MeCN"], "smiles": "CC#N" }, + { "id": "ethyl-acetate", "name": "Ethyl acetate", "tags": ["solvent", "EtOAc"], "smiles": "CCOC(C)=O" }, + { "id": "acetone", "name": "Acetone", "tags": ["solvent", "ketone"], "smiles": "CC(C)=O" }, + { "id": "toluene", "name": "Toluene", "tags": ["solvent", "arene", "PhMe"], "smiles": "Cc1ccccc1" }, + { "id": "hexane", "name": "Hexane", "tags": ["solvent", "alkane"], "smiles": "CCCCCC" } + ] +} From c209a7d9ac9a1bb366ccf3d7813be50c4dcaf709 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 065/279] feat(templates): add an original glassware vector set (0.5.0) Flasks, beaker, tube, cylinder, funnels, condenser, thermometer and hotplate are drawn from scratch as grouped shape and line objects in the document format, not traced from any vendor art. --- backend/app/data/templates/glassware.json | 126 ++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 backend/app/data/templates/glassware.json diff --git a/backend/app/data/templates/glassware.json b/backend/app/data/templates/glassware.json new file mode 100644 index 00000000..645f621e --- /dev/null +++ b/backend/app/data/templates/glassware.json @@ -0,0 +1,126 @@ +{ + "category": "glassware", + "name": "Glassware", + "order": 90, + "templates": [ + { + "id": "round-bottom-flask", "name": "Round-bottom flask", "tags": ["flask", "RBF", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s2", "s1"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 46, "path": "M12 0 L28 0 M14 0 L14 15.17 A16 16 0 1 0 26 15.17 L26 0", "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 46, "path": "M6.14 38 A16 16 0 0 0 33.86 38 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 } + ] + }, + { + "id": "erlenmeyer-flask", "name": "Erlenmeyer flask", "tags": ["flask", "conical", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s2", "s1"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 44, "h": 55, "path": "M16 0 L28 0 M18 0 L18 18 L3 50 Q1 55 6 55 L38 55 Q43 55 41 50 L26 18 L26 0", "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 44, "h": 55, "path": "M7.69 40 L36.31 40 L41 50 Q43 55 38 55 L6 55 Q1 55 3 50 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 } + ] + }, + { + "id": "beaker", "name": "Beaker", "tags": ["beaker", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s2", "s1", "l1", "l2", "l3"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 52, "path": "M0 0 Q3 1 4 4 L4 48 Q4 52 8 52 L36 52 Q40 52 40 48 L40 2", "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 52, "path": "M4 28 L40 28 L40 48 Q40 52 36 52 L8 52 Q4 52 4 48 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 }, + { "id": "l1", "kind": "line", "points": [[30, 16], [36, 16]], "stroke": { "width": 0.6 } }, + { "id": "l2", "kind": "line", "points": [[32, 24], [36, 24]], "stroke": { "width": 0.6 } }, + { "id": "l3", "kind": "line", "points": [[30, 32], [36, 32]], "stroke": { "width": 0.6 } } + ] + }, + { + "id": "test-tube", "name": "Test tube", "tags": ["tube", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s2", "s1"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 14, "h": 48, "path": "M0 0 L2 0 L2 43 A5 5 0 0 0 12 43 L12 0 L14 0", "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 14, "h": 48, "path": "M2 32 L12 32 L12 43 A5 5 0 0 1 2 43 Z", "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 } + ] + }, + { + "id": "graduated-cylinder", "name": "Graduated cylinder", "tags": ["cylinder", "measuring", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s3", "s1", "s2", "l1", "l2", "l3", "l4", "l5", "l6"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 24, "h": 72, "path": "M2 0 Q5 0 5 3 L5 72 M19 72 L19 0", "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "round_rect", "x": 0, "y": 72, "w": 24, "h": 6, "radius": 1.5, "stroke": { "width": 1 }, "fill": null }, + { "id": "s3", "kind": "shape", "geom": "rect", "x": 5, "y": 40, "w": 14, "h": 32, "stroke": null, "fill": { "type": "solid", "color": "#9fcbf5" }, "opacity": 0.7 }, + { "id": "l1", "kind": "line", "points": [[14, 12], [19, 12]], "stroke": { "width": 0.6 } }, + { "id": "l2", "kind": "line", "points": [[16, 22], [19, 22]], "stroke": { "width": 0.6 } }, + { "id": "l3", "kind": "line", "points": [[14, 32], [19, 32]], "stroke": { "width": 0.6 } }, + { "id": "l4", "kind": "line", "points": [[16, 42], [19, 42]], "stroke": { "width": 0.6 } }, + { "id": "l5", "kind": "line", "points": [[14, 52], [19, 52]], "stroke": { "width": 0.6 } }, + { "id": "l6", "kind": "line", "points": [[16, 62], [19, 62]], "stroke": { "width": 0.6 } } + ] + }, + { + "id": "separatory-funnel", "name": "Separatory funnel", "tags": ["funnel", "extraction", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s1", "s2", "s3", "l1"] }, + { "id": "s1", "kind": "shape", "geom": "round_rect", "x": 15, "y": 0, "w": 10, "h": 6, "radius": 1.5, "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "path", "x": 0, "y": 6, "w": 40, "h": 58, "path": "M17 0 L17 4 C2 12 0 40 17 52 L17 58 M23 58 L23 52 C40 40 38 12 23 4 L23 0", "stroke": { "width": 1 }, "fill": null }, + { "id": "s3", "kind": "shape", "geom": "rect", "x": 11, "y": 64, "w": 18, "h": 4, "stroke": { "width": 1 }, "fill": null }, + { "id": "l1", "kind": "line", "points": [[20, 68], [20, 92]], "stroke": { "width": 1.6 } } + ] + }, + { + "id": "condenser", "name": "Condenser", "tags": ["condenser", "reflux", "distillation", "Liebig", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s1", "l1", "l2", "l3", "l4", "l5", "l6"] }, + { "id": "s1", "kind": "shape", "geom": "round_rect", "x": 6, "y": 12, "w": 16, "h": 86, "radius": 3, "stroke": { "width": 1 }, "fill": null }, + { "id": "l1", "kind": "line", "points": [[12, 0], [12, 110]], "stroke": { "width": 1 } }, + { "id": "l2", "kind": "line", "points": [[16, 0], [16, 110]], "stroke": { "width": 1 } }, + { "id": "l3", "kind": "line", "points": [[22, 20], [30, 20]], "stroke": { "width": 1 } }, + { "id": "l4", "kind": "line", "points": [[22, 24], [30, 24]], "stroke": { "width": 1 } }, + { "id": "l5", "kind": "line", "points": [[0, 86], [6, 86]], "stroke": { "width": 1 } }, + { "id": "l6", "kind": "line", "points": [[0, 90], [6, 90]], "stroke": { "width": 1 } } + ] + }, + { + "id": "filter-funnel", "name": "Filter funnel", "tags": ["funnel", "filtration", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s1", "l1"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 40, "h": 50, "path": "M0 0 L40 0 M0 0 L17 22 L17 50 M40 0 L23 22 L23 50", "stroke": { "width": 1 }, "fill": null }, + { "id": "l1", "kind": "line", "points": [[5, 2], [20, 19], [35, 2]], "stroke": { "width": 0.6, "dash": "dash" } } + ] + }, + { + "id": "buchner-funnel", "name": "Buchner funnel", "tags": ["funnel", "vacuum filtration", "glassware", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s1", "l1"] }, + { "id": "s1", "kind": "shape", "geom": "path", "x": 0, "y": 0, "w": 44, "h": 56, "path": "M0 0 L44 0 L44 4 Q44 22 26 24 L26 30 L24 30 L24 56 L20 56 L20 30 L18 30 L18 24 Q0 22 0 4 Z", "stroke": { "width": 1 }, "fill": null }, + { "id": "l1", "kind": "line", "points": [[3, 14], [41, 14]], "stroke": { "width": 0.8, "dash": "dot" } } + ] + }, + { + "id": "thermometer", "name": "Thermometer", "tags": ["thermometer", "temperature", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s1", "s3", "s2"] }, + { "id": "s1", "kind": "shape", "geom": "round_rect", "x": 2, "y": 0, "w": 6, "h": 82, "radius": 3, "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "ellipse", "x": 0, "y": 78, "w": 10, "h": 12, "stroke": { "width": 1 }, "fill": { "type": "solid", "color": "#d9534f" } }, + { "id": "s3", "kind": "shape", "geom": "rect", "x": 4, "y": 34, "w": 2, "h": 46, "stroke": null, "fill": { "type": "solid", "color": "#d9534f" } } + ] + }, + { + "id": "stirrer-hotplate", "name": "Stirrer hotplate", "tags": ["hotplate", "stirrer", "heating", "apparatus"], + "order": ["g1"], + "objects": [ + { "id": "g1", "kind": "group", "children": ["s1", "s2", "s3", "s4"] }, + { "id": "s1", "kind": "shape", "geom": "rect", "x": 0, "y": 0, "w": 70, "h": 4, "stroke": { "width": 1 }, "fill": null }, + { "id": "s2", "kind": "shape", "geom": "round_rect", "x": 4, "y": 4, "w": 62, "h": 24, "radius": 3, "stroke": { "width": 1 }, "fill": null }, + { "id": "s3", "kind": "shape", "geom": "ellipse", "x": 14, "y": 12, "w": 8, "h": 8, "stroke": { "width": 1 }, "fill": null }, + { "id": "s4", "kind": "shape", "geom": "ellipse", "x": 48, "y": 12, "w": 8, "h": 8, "stroke": { "width": 1 }, "fill": null } + ] + } + ] +} From 8d4a883c4573e107e4f418c50efdad54ce55a434 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 066/279] feat(templates): add the templates service (0.5.0) Loads the built-in and user template files, lays out SMILES and ring specs once and caches them, and hands out each insertion with fresh ids and optional scaling to the drawing's bond length. --- backend/app/services/templates.py | 301 ++++++++++++++++++++++++++++++ 1 file changed, 301 insertions(+) create mode 100644 backend/app/services/templates.py diff --git a/backend/app/services/templates.py b/backend/app/services/templates.py new file mode 100644 index 00000000..24bed42d --- /dev/null +++ b/backend/app/services/templates.py @@ -0,0 +1,301 @@ +import copy +import json +import math +import sys +import threading +from dataclasses import dataclass, field +from pathlib import Path + +from app.core import config +from app.services.chem import DEFAULT_BOND_LENGTH, io +from app.services.model import ELEMENTS, new_id + +BUILTIN_DIR = Path(__file__).resolve().parents[1] / "data" / "templates" +MAX_FILE_BYTES = 4 * 1024 * 1024 +ID_OK = set("abcdefghijklmnopqrstuvwxyz0123456789-_") +_LOCK = threading.RLock() + + +@dataclass +class Template: + id: str + name: str + category: str + tags: list[str] + source: dict + origin: str + objects: list[dict] | None = None + order: list[str] = field(default_factory=list) + error: str | None = None + + +@dataclass +class Catalogue: + categories: list[dict] + templates: dict[str, Template] + stamp: tuple + + +_catalogue: Catalogue | None = None + + +def builtin_dir() -> Path: + if getattr(sys, "frozen", False): + return config.resource_dir() / "templates" + return BUILTIN_DIR + + +def user_dir() -> Path: + return config.data_dir() / "templates" + + +def _files() -> list[tuple[Path, str]]: + out: list[tuple[Path, str]] = [] + for root, origin in ((builtin_dir(), "builtin"), (user_dir(), "user")): + try: + out.extend((p, origin) for p in sorted(root.glob("*.json")) if p.is_file()) + except OSError: + continue + return out + + +def _stamp(files: list[tuple[Path, str]]) -> tuple: + marks = [] + for p, _ in files: + try: + st = p.stat() + marks.append((str(p), st.st_mtime_ns, st.st_size)) + except OSError: + continue + return tuple(marks) + + +def _slug(value: object) -> str | None: + if not isinstance(value, str): + return None + s = value.strip().lower() + return s if 0 < len(s) <= 64 and set(s) <= ID_OK else None + + +def _source(raw: dict) -> dict | None: + if isinstance(raw.get("smiles"), str) and raw["smiles"].strip(): + return {"smiles": raw["smiles"].strip()} + ring = raw.get("ring") + if isinstance(ring, dict): + els, orders = ring.get("elements"), ring.get("orders") + if (isinstance(els, list) and 3 <= len(els) <= 12 and all(e in ELEMENTS for e in els) + and isinstance(orders, list) and len(orders) == len(els) and all(o in (1, 2, 3, 1.5) for o in orders)): + return {"ring": {"elements": els, "orders": orders}} + return None + objects = raw.get("objects") + if isinstance(objects, list) and objects and all(isinstance(o, dict) and isinstance(o.get("id"), str) and isinstance(o.get("kind"), str) for o in objects): + return {"objects": objects, "order": raw.get("order") if isinstance(raw.get("order"), list) else None} + return None + + +def _read_file(path: Path, origin: str, cats: dict[str, dict], found: dict[str, Template]) -> None: + try: + if path.stat().st_size > MAX_FILE_BYTES: + return + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + if not isinstance(data, dict) or not isinstance(data.get("templates"), list): + return + cat = _slug(data.get("category")) or _slug(path.stem) or "templates" + name = data.get("name") if isinstance(data.get("name"), str) and data.get("name") else cat.replace("-", " ").capitalize() + order = data.get("order") if isinstance(data.get("order"), (int, float)) else 1000 + entry = cats.setdefault(cat, {"id": cat, "name": name, "order": order, "origin": origin, "count": 0}) + for raw in data["templates"]: + if not isinstance(raw, dict): + continue + tid = _slug(raw.get("id")) + src = _source(raw) + if not tid or not src: + continue + if origin == "user": + tid = f"user-{tid}" + if tid in found: + continue + tags = [t for t in raw.get("tags", []) if isinstance(t, str)] if isinstance(raw.get("tags"), list) else [] + label = raw.get("name") if isinstance(raw.get("name"), str) and raw.get("name") else tid + found[tid] = Template(tid, label, cat, tags, src, origin) + entry["count"] += 1 + + +def catalogue() -> Catalogue: + global _catalogue + with _LOCK: + files = _files() + stamp = _stamp(files) + if _catalogue is not None and _catalogue.stamp == stamp: + return _catalogue + cats: dict[str, dict] = {} + found: dict[str, Template] = {} + for path, origin in files: + _read_file(path, origin, cats, found) + ordered = sorted((c for c in cats.values() if c["count"]), key=lambda c: (c["order"], c["name"].lower())) + _catalogue = Catalogue([{k: c[k] for k in ("id", "name", "count", "origin")} for c in ordered], found, stamp) + return _catalogue + + +def _ring(spec: dict, length: float) -> list[dict]: + els, orders = spec["elements"], spec["orders"] + n = len(els) + radius = length / (2 * math.sin(math.pi / n)) + start = -90.0 - 180.0 / n + pts = [] + for k in range(n): + phi = math.radians(start + k * 360.0 / n) + pts.append((radius * math.cos(phi), -radius * math.sin(phi))) + x0, y0 = min(p[0] for p in pts), min(p[1] for p in pts) + atoms = {f"a{k + 1}": {"id": f"a{k + 1}", "element": els[k], "x": round(pts[k][0] - x0, 3), "y": round(pts[k][1] - y0, 3)} for k in range(n)} + bonds = {f"b{k + 1}": {"id": f"b{k + 1}", "a": f"a{k + 1}", "b": f"a{(k + 1) % n + 1}", "order": orders[k]} for k in range(n)} + return [{"id": "f1", "kind": "fragment", "atoms": atoms, "bonds": bonds}] + + +def _smiles(text: str) -> list[dict]: + res = io.read_text(text, "smiles", DEFAULT_BOND_LENGTH, (0.0, 0.0)) + frags = [f for f in res.fragments if f.get("atoms")] + if not frags: + raise ValueError(res.warnings[0]["text"] if res.warnings else "no structure") + return frags + + +def _top_level(objects: list[dict], order: list | None) -> list[str]: + ids = [o["id"] for o in objects] + if order and all(isinstance(i, str) and i in ids for i in order): + return list(order) + inside = {c for o in objects if o.get("kind") == "group" for c in o.get("children", []) if isinstance(c, str)} + return [i for i in ids if i not in inside] + + +def _build(t: Template) -> None: + if t.objects is not None or t.error: + return + try: + if "smiles" in t.source: + objs = _smiles(t.source["smiles"]) + order = None + elif "ring" in t.source: + objs = _ring(t.source["ring"], DEFAULT_BOND_LENGTH) + order = None + else: + objs = copy.deepcopy(t.source["objects"]) + order = t.source.get("order") + t.objects = objs + t.order = _top_level(objs, order) + except Exception as exc: + t.error = str(exc) or type(exc).__name__ + + +def _points(o: dict) -> list[tuple[float, float]]: + kind = o.get("kind") + num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) + if kind == "fragment": + return [(a["x"], a["y"]) for a in o.get("atoms", {}).values() if num(a.get("x")) and num(a.get("y"))] + if kind == "line": + return [(p[0], p[1]) for p in o.get("points", []) if isinstance(p, list) and len(p) >= 2 and num(p[0]) and num(p[1])] + if kind == "arrow": + return [(o[k1], o[k2]) for k1, k2 in (("x1", "y1"), ("x2", "y2")) if num(o.get(k1)) and num(o.get(k2))] + if num(o.get("x")) and num(o.get("y")): + x, y = o["x"], o["y"] + w = o["w"] if num(o.get("w")) else 0 + h = o["h"] if num(o.get("h")) else 0 + return [(x, y), (x + w, y + h)] + return [] + + +def bounds(objects: list[dict]) -> dict: + pts = [p for o in objects for p in _points(o)] + if not pts: + return {"x": 0, "y": 0, "w": 0, "h": 0} + x0, y0 = min(p[0] for p in pts), min(p[1] for p in pts) + x1, y1 = max(p[0] for p in pts), max(p[1] for p in pts) + return {"x": round(x0, 3), "y": round(y0, 3), "w": round(x1 - x0, 3), "h": round(y1 - y0, 3)} + + +def _scaled(objects: list[dict], k: float) -> list[dict]: + if abs(k - 1) < 1e-9: + return objects + for o in objects: + if o.get("kind") != "fragment": + continue + for a in o.get("atoms", {}).values(): + a["x"] = round(a["x"] * k, 3) + a["y"] = round(a["y"] * k, 3) + return objects + + +def _fresh(objects: list[dict], order: list[str]) -> tuple[list[dict], list[str]]: + used: set[str] = set() + + def make(prefix: str) -> str: + while True: + i = new_id(prefix) + if i not in used: + used.add(i) + return i + + obj_ids = {o["id"]: make("f" if o.get("kind") == "fragment" else "o") for o in objects} + out = [] + for raw in objects: + o = copy.deepcopy(raw) + o["id"] = obj_ids[raw["id"]] + if o.get("kind") == "fragment": + atom_ids = {k: make("a") for k in o.get("atoms", {})} + o["atoms"] = {atom_ids[k]: {**a, "id": atom_ids[k]} for k, a in o.get("atoms", {}).items()} + bonds = {} + for b in o.get("bonds", {}).values(): + if b.get("a") in atom_ids and b.get("b") in atom_ids: + bid = make("b") + bonds[bid] = {**b, "id": bid, "a": atom_ids[b["a"]], "b": atom_ids[b["b"]]} + o["bonds"] = bonds + elif o.get("kind") == "group": + o["children"] = [obj_ids[c] for c in o.get("children", []) if c in obj_ids] + for key in ("rows", "lanes"): + for item in o.get(key, []) if isinstance(o.get(key), list) else []: + if isinstance(item, dict) and "id" in item: + item["id"] = make("l") + out.append(o) + return out, [obj_ids[i] for i in order if i in obj_ids] + + +def _summary(t: Template) -> dict: + return {"id": t.id, "name": t.name, "category": t.category, "tags": t.tags, "origin": t.origin} + + +def listing(with_objects: bool = False) -> dict: + cat = catalogue() + items = [] + with _LOCK: + for t in cat.templates.values(): + item = _summary(t) + if with_objects: + _build(t) + if t.error: + item["error"] = t.error + else: + item["objects"] = t.objects + item["order"] = t.order + item["bounds"] = bounds(t.objects or []) + items.append(item) + order = {c["id"]: i for i, c in enumerate(cat.categories)} + items.sort(key=lambda i: order.get(i["category"], len(order))) + return {"categories": cat.categories, "templates": items, "count": len(items)} + + +def fragment(template_id: str, bond_length: float | None = None) -> dict | None: + cat = catalogue() + t = cat.templates.get(template_id) + if t is None: + return None + with _LOCK: + _build(t) + if t.error: + raise ValueError(f"template {template_id} could not be built: {t.error}") + base = copy.deepcopy(t.objects or []) + order = list(t.order) + k = (bond_length / DEFAULT_BOND_LENGTH) if bond_length else 1.0 + objects, top = _fresh(_scaled(base, k), order) + return {**_summary(t), "objects": objects, "order": top, "bounds": bounds(objects)} From f40e002365176aedaf67b108b51351f1fc5440a3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:05:32 -0500 Subject: [PATCH 067/279] feat(templates): add the templates router (0.5.0) GET /api/templates lists categories and templates (with objects=1 for thumbnails) and GET /api/templates/{id} returns objects ready to insert as one transaction. --- backend/app/routers/templates.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 backend/app/routers/templates.py diff --git a/backend/app/routers/templates.py b/backend/app/routers/templates.py new file mode 100644 index 00000000..d54b4359 --- /dev/null +++ b/backend/app/routers/templates.py @@ -0,0 +1,31 @@ +import math + +from fastapi import APIRouter, HTTPException + +from app.services import templates + +router = APIRouter() + + +def _bond_length(value: float | None) -> float | None: + if value is None: + return None + if not math.isfinite(value) or not 1 <= value <= 500: + raise HTTPException(422, "bond_length must be a number of points from 1 to 500") + return value + + +@router.get("/api/templates") +def list_templates(objects: bool = False) -> dict: + return templates.listing(with_objects=objects) + + +@router.get("/api/templates/{template_id}") +def get_template(template_id: str, bond_length: float | None = None) -> dict: + try: + found = templates.fragment(template_id, _bond_length(bond_length)) + except ValueError as exc: + raise HTTPException(422, str(exc)) + if found is None: + raise HTTPException(404, f"no template {template_id}") + return found From 6985e8c073864643a516ac348c5884840d76c8f6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:06:54 -0500 Subject: [PATCH 068/279] feat(stoich): compute stoichiometry for a reaction step in the window (0.5.0) Moles, equivalents against the limiting reagent, implied masses and volumes, theoretical yield and percent yield are worked out in TypeScript from the typed values and the derived molecular weights, with a local average-mass fallback, and are never stored (spec B AC11.1 gives 8.19 mmol, 9.83 mmol and 0.713 mL). --- frontend/src/chem/stoich.ts | 241 ++++++++++++++++++++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 frontend/src/chem/stoich.ts diff --git a/frontend/src/chem/stoich.ts b/frontend/src/chem/stoich.ts new file mode 100644 index 00000000..3c27c5c9 --- /dev/null +++ b/frontend/src/chem/stoich.ts @@ -0,0 +1,241 @@ +import type { Derived, FormChemDocument, Id, Page, Reaction, ReactionStep, Stoich, StoichComponent } from '../engine/model'; +import { isFragment } from '../engine/model'; +import { fragmentCounts, hillFormula } from './formula'; + +export type StoichRole = 'reactant' | 'agent' | 'product'; +export type AmountSource = 'mass' | 'volume' | 'equiv' | 'scale' | 'yield' | null; + +export interface StepRef { page: Id; reaction: Id; step: Id } + +export interface StepEntry { ref: StepRef; step: ReactionStep; index: number; reactionIndex: number } + +export interface StoichRow { + id: Id; + role: StoichRole; + name: string; + formula: string; + coef: number; + typed: StoichComponent; + mw: number | null; + mwFrom: 'typed' | 'engine' | 'local' | null; + purity: number; + mmol: number | null; + equiv: number | null; + massMg: number | null; + volumeMl: number | null; + density: number | null; + concM: number | null; + source: AmountSource; + limiting: boolean; +} + +export interface StoichResult { + rows: StoichRow[]; + limiting: Id | null; + limitingAuto: boolean; + refMmol: number | null; + scaleMmol: number | null; + product: Id | null; + theoMmol: number | null; + theoMg: number | null; + isolatedMg: number | null; + yieldPct: number | null; +} + +const WEIGHTS: Readonly> = Object.freeze({ + H: 1.008, He: 4.0026, Li: 6.94, Be: 9.0122, B: 10.81, C: 12.011, N: 14.007, O: 15.999, F: 18.998, Ne: 20.18, + Na: 22.99, Mg: 24.305, Al: 26.982, Si: 28.085, P: 30.974, S: 32.06, Cl: 35.45, Ar: 39.95, K: 39.098, Ca: 40.078, + Sc: 44.956, Ti: 47.867, V: 50.942, Cr: 51.996, Mn: 54.938, Fe: 55.845, Co: 58.933, Ni: 58.693, Cu: 63.546, Zn: 65.38, + Ga: 69.723, Ge: 72.63, As: 74.922, Se: 78.971, Br: 79.904, Kr: 83.798, Rb: 85.468, Sr: 87.62, Y: 88.906, Zr: 91.224, + Nb: 92.906, Mo: 95.95, Ru: 101.07, Rh: 102.91, Pd: 106.42, Ag: 107.87, Cd: 112.41, In: 114.82, Sn: 118.71, Sb: 121.76, + Te: 127.6, I: 126.9, Xe: 131.29, Cs: 132.91, Ba: 137.33, La: 138.91, Ce: 140.12, Nd: 144.24, Sm: 150.36, Eu: 151.96, + Gd: 157.25, Yb: 173.05, Hf: 178.49, Ta: 180.95, W: 183.84, Re: 186.21, Os: 190.23, Ir: 192.22, Pt: 195.08, Au: 196.97, + Hg: 200.59, Tl: 204.38, Pb: 207.2, Bi: 208.98, Th: 232.04, U: 238.03, +}); + +const pos = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null); +const nonNeg = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null); + +export function averageMass(counts: Record): number | null { + let sum = 0; + for (const [el, n] of Object.entries(counts)) { + const w = WEIGHTS[el]; + if (w === undefined) return null; + sum += w * n; + } + return sum > 0 ? sum : null; +} + +export function reactionSteps(doc: FormChemDocument): StepEntry[] { + const out: StepEntry[] = []; + for (const page of doc.pages) { + (page.reactions ?? []).forEach((r: Reaction, ri: number) => { + (r.steps ?? []).forEach((s, si) => { + out.push({ ref: { page: page.id, reaction: r.id, step: s.id }, step: s, index: si, reactionIndex: ri }); + }); + }); + } + return out; +} + +export function findStep(doc: FormChemDocument, ref: StepRef | null): ReactionStep | null { + if (!ref) return null; + const page: Page | undefined = doc.pages.find((p) => p.id === ref.page); + const r = page?.reactions?.find((x) => x.id === ref.reaction); + return r?.steps?.find((s) => s.id === ref.step) ?? null; +} + +export function stepFor(doc: FormChemDocument, ids: readonly Id[] | null, pageId?: Id | null): StepEntry | null { + const all = reactionSteps(doc); + if (!all.length) return null; + if (ids?.length) { + const want = new Set(ids); + const hit = all.find((e) => want.has(e.step.arrow) || [...e.step.reactants, ...e.step.products, ...e.step.agents, ...(e.step.conditions ?? [])].some((id) => want.has(id))); + if (hit) return hit; + } + return all.find((e) => e.ref.page === pageId) ?? all[0]; +} + +function objectText(doc: FormChemDocument, id: Id): string { + const o = doc.objects[id] as { runs?: { t?: string }[] } | undefined; + return Array.isArray(o?.runs) ? o.runs.map((r) => r.t ?? '').join('').replace(/\s+/g, ' ').trim() : ''; +} + +interface Identity { name: string; formula: string; mw: number | null; mwFrom: 'engine' | 'local' | null } + +function identify(doc: FormChemDocument, id: Id, derived: Derived | null, engineMw: Readonly> | undefined): Identity { + const o = doc.objects[id]; + if (!isFragment(o)) { + const text = objectText(doc, id); + const mw = pos(engineMw?.[id]); + return { name: o?.name || text || id, formula: '', mw, mwFrom: mw ? 'engine' : null }; + } + const d = derived?.fragments[id]; + const counts = fragmentCounts(o, { expansions: doc.expansions, derived }); + const formula = d?.formula || hillFormula(counts); + const generic = Object.values(o.atoms).some((a) => (a.element === '*' || a.element === 'R#') && !a.expansion); + const fromEngine = pos(d?.mw) ?? pos(engineMw?.[id]); + const local = generic ? null : averageMass(counts.counts); + const mw = fromEngine ?? local; + return { name: o.name || formula || id, formula, mw, mwFrom: fromEngine ? 'engine' : local ? 'local' : null }; +} + +function directMmol(t: StoichComponent, mw: number | null, purity: number): { mmol: number; source: AmountSource } | null { + const f = purity / 100; + const mass = pos(t.mass_mg); + if (mass !== null && mw) return { mmol: (mass * f) / mw, source: 'mass' }; + const vol = pos(t.volume_ml); + if (vol === null) return null; + const conc = pos(t.conc_m); + if (conc !== null) return { mmol: conc * vol, source: 'volume' }; + const density = pos(t.density_g_ml); + if (density !== null && mw) return { mmol: (vol * density * 1000 * f) / mw, source: 'volume' }; + return null; +} + +export function computeStoich( + doc: FormChemDocument, + step: ReactionStep, + derived: Derived | null, + engineMw?: Readonly>, +): StoichResult { + const data: Stoich = step.stoich ?? { components: {} }; + const comps = data.components ?? {}; + const coefOf = (id: Id): number => pos(step.coefficients?.[id]) ?? 1; + const seen = new Set(); + const rows: StoichRow[] = []; + const add = (ids: readonly Id[], role: StoichRole): void => { + for (const id of ids) { + if (seen.has(id) || !doc.objects[id]) continue; + seen.add(id); + const typed = comps[id] ?? {}; + const ident = identify(doc, id, derived, engineMw); + const typedMw = pos(typed.mw); + rows.push({ + id, role, name: typed.label?.trim() || ident.name, formula: ident.formula, coef: coefOf(id), typed, + mw: typedMw ?? ident.mw, mwFrom: typedMw ? 'typed' : ident.mwFrom, + purity: Math.min(100, pos(typed.purity_pct) ?? 100), + mmol: null, equiv: null, massMg: null, volumeMl: null, + density: pos(typed.density_g_ml), concM: pos(typed.conc_m), source: null, limiting: false, + }); + } + }; + add(step.reactants, 'reactant'); + add(step.agents, 'agent'); + add(step.products, 'product'); + + const inputs = rows.filter((r) => r.role !== 'product'); + for (const r of inputs) { + const d = directMmol(r.typed, r.mw, r.purity); + if (d) { r.mmol = d.mmol; r.source = d.source; } + } + + const reactants = rows.filter((r) => r.role === 'reactant'); + const chosen = data.limiting ? inputs.find((r) => r.id === data.limiting) : undefined; + let lim: StoichRow | undefined = chosen; + if (!lim) { + const measured = reactants.filter((r) => r.mmol !== null && pos(r.typed.equiv) === null); + lim = measured.sort((a, b) => (a.mmol as number) / a.coef - (b.mmol as number) / b.coef)[0] ?? reactants[0]; + } + const scale = pos(data.scale_mmol); + if (lim && lim.mmol === null && scale !== null) { lim.mmol = scale; lim.source = 'scale'; } + const ref = lim?.mmol ?? null; + if (lim) lim.limiting = true; + + for (const r of inputs) { + const eq = pos(r.typed.equiv); + if (r.mmol === null && eq !== null && ref !== null) { r.mmol = eq * ref; r.source = 'equiv'; } + r.equiv = eq ?? (r.mmol !== null && ref ? r.mmol / ref : null); + const f = r.purity / 100; + r.massMg = pos(r.typed.mass_mg) ?? (r.mmol !== null && r.mw ? (r.mmol * r.mw) / f : null); + r.volumeMl = pos(r.typed.volume_ml) ?? (r.mmol !== null && r.concM ? r.mmol / r.concM + : r.massMg !== null && r.density ? r.massMg / r.density / 1000 : null); + } + + const products = rows.filter((r) => r.role === 'product'); + const limCoef = lim?.coef ?? 1; + for (const p of products) { + p.equiv = p.coef / limCoef; + p.mmol = ref !== null ? (ref * p.coef) / limCoef : null; + p.massMg = p.mmol !== null && p.mw ? p.mmol * p.mw : null; + p.source = p.mmol !== null ? 'yield' : null; + } + const product = (data.product && products.find((p) => p.id === data.product)) || products[0]; + const isolated = nonNeg(data.isolated_mg); + const theoMg = product?.massMg ?? null; + return { + rows, + limiting: lim?.id ?? null, + limitingAuto: !chosen, + refMmol: ref, + scaleMmol: scale, + product: product?.id ?? null, + theoMmol: product?.mmol ?? null, + theoMg, + isolatedMg: isolated, + yieldPct: isolated !== null && theoMg ? (isolated / theoMg) * 100 : null, + }; +} + +export function sig(n: number | null | undefined, digits = 3): string { + if (typeof n !== 'number' || !Number.isFinite(n)) return ''; + if (n === 0) return '0'; + const mag = Math.floor(Math.log10(Math.abs(n))); + const decimals = Math.max(0, digits - 1 - mag); + return n.toFixed(Math.min(decimals, 6)); +} + +export function fixed(n: number | null | undefined, decimals: number): string { + return typeof n === 'number' && Number.isFinite(n) ? n.toFixed(decimals) : ''; +} + +export function typedText(n: number | undefined): string { + return typeof n === 'number' && Number.isFinite(n) ? String(+n.toPrecision(10)) : ''; +} + +export function parseAmount(text: string): number | null | undefined { + const s = text.trim().replace(/\s+/g, '').replace(',', '.'); + if (!s) return null; + const n = Number(s); + return Number.isFinite(n) && n >= 0 ? n : undefined; +} From 77608020a76094fc71c4c1d8628c9d8f9d234cc5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:06:54 -0500 Subject: [PATCH 069/279] feat(stoich): build the ops that store typed stoichiometry values (0.5.0) One typed cell becomes one set of ops under step.stoich.components, creating the stoich record when absent and clearing the other amount fields so the last typed amount is the row's source of truth. --- frontend/src/chem/stoich-ops.ts | 59 +++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 frontend/src/chem/stoich-ops.ts diff --git a/frontend/src/chem/stoich-ops.ts b/frontend/src/chem/stoich-ops.ts new file mode 100644 index 00000000..12f41b70 --- /dev/null +++ b/frontend/src/chem/stoich-ops.ts @@ -0,0 +1,59 @@ +import type { FormChemDocument, Id, Stoich, StoichComponent } from '../engine/model'; +import type { Op, Path } from '../engine/ops'; +import { findStep, type StepRef } from './stoich'; + +export type ComponentField = 'equiv' | 'mass_mg' | 'volume_ml' | 'density_g_ml' | 'conc_m' | 'purity_pct' | 'mw' | 'label'; +export type StepField = 'scale_mmol' | 'limiting' | 'product' | 'isolated_mg'; + +const AMOUNTS: readonly ComponentField[] = ['equiv', 'mass_mg', 'volume_ml']; + +export const stepPath = (ref: StepRef): Path => ['pages', { id: ref.page }, 'reactions', { id: ref.reaction }, 'steps', { id: ref.step }]; +const stoichPath = (ref: StepRef): Path => [...stepPath(ref), 'stoich']; + +const blank = (v: unknown): boolean => v === null || v === undefined || v === ''; + +function clean(comp: StoichComponent): StoichComponent { + const out: Record = {}; + for (const [k, v] of Object.entries(comp)) if (!blank(v)) out[k] = v; + return out as StoichComponent; +} + +export function componentEdit(doc: FormChemDocument, ref: StepRef, comp: Id, field: ComponentField, value: number | string | null): Op[] { + const step = findStep(doc, ref); + if (!step) return []; + const data: Stoich | undefined = step.stoich; + const current: StoichComponent = data?.components?.[comp] ?? {}; + if ((current as Record)[field] === (blank(value) ? undefined : value)) return []; + const next: Record = { ...current, [field]: blank(value) ? undefined : value }; + if (!blank(value) && AMOUNTS.includes(field)) for (const other of AMOUNTS) if (other !== field) next[other] = undefined; + const cleaned = clean(next as StoichComponent); + const empty = Object.keys(cleaned).length === 0; + if (!data) return empty ? [] : [{ op: 'set', path: stoichPath(ref), value: { components: { [comp]: cleaned } } }]; + if (!data.components) return empty ? [] : [{ op: 'set', path: [...stoichPath(ref), 'components'], value: { [comp]: cleaned } }]; + const base: Path = [...stoichPath(ref), 'components', comp]; + if (!data.components[comp] || empty) return [empty ? { op: 'set', path: base } : { op: 'set', path: base, value: cleaned }]; + const ops: Op[] = []; + for (const key of new Set([...Object.keys(current), ...Object.keys(cleaned)])) { + const before = (current as Record)[key]; + const after = (cleaned as Record)[key]; + if (before === after) continue; + ops.push(after === undefined ? { op: 'set', path: [...base, key] } : { op: 'set', path: [...base, key], value: after }); + } + return ops; +} + +export function stepEdit(doc: FormChemDocument, ref: StepRef, field: StepField, value: number | string | null, opts: { limiting?: Id | null } = {}): Op[] { + const step = findStep(doc, ref); + if (!step) return []; + const data = step.stoich; + const now = (data as Record | undefined)?.[field]; + if (now === (blank(value) ? undefined : value)) return []; + if (!data) return blank(value) ? [] : [{ op: 'set', path: stoichPath(ref), value: { components: {}, [field]: value } }]; + const ops: Op[] = [blank(value) ? { op: 'set', path: [...stoichPath(ref), field] } : { op: 'set', path: [...stoichPath(ref), field], value }]; + const lim = opts.limiting; + if (field === 'scale_mmol' && !blank(value) && lim && data.components?.[lim]) { + const comp = data.components[lim]; + for (const key of ['mass_mg', 'volume_ml', 'equiv'] as const) if (comp[key] !== undefined) ops.push({ op: 'set', path: [...stoichPath(ref), 'components', lim, key] }); + } + return ops; +} From 6ce000a98c0ee77aad64cf3ff5755ef222967dad Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:10:32 -0500 Subject: [PATCH 070/279] feat(stoich): add the stoichiometry panel (0.5.0) A grid for the selected reaction step with one keyed row per component: typed cells commit one transaction each and show computed values as placeholders, so nothing is rebuilt while the person types; molecular weights come from the derived cache and are reconciled with the engine's stoich endpoint when it answers. --- frontend/src/ui/stoich-panel.ts | 402 ++++++++++++++++++++++++++++++++ 1 file changed, 402 insertions(+) create mode 100644 frontend/src/ui/stoich-panel.ts diff --git a/frontend/src/ui/stoich-panel.ts b/frontend/src/ui/stoich-panel.ts new file mode 100644 index 00000000..cb0a46cc --- /dev/null +++ b/frontend/src/ui/stoich-panel.ts @@ -0,0 +1,402 @@ +import { commandStateChanged } from '../app/commands-shell'; +import { computeStoich, findStep, fixed, parseAmount, reactionSteps, sig, stepFor, typedText, type StepEntry, type StepRef, type StoichResult, type StoichRow } from '../chem/stoich'; +import { componentEdit, stepEdit, type ComponentField, type StepField } from '../chem/stoich-ops'; +import type { DocEvent } from '../engine/client-api'; +import type { Derived, FormChemDocument, Id } from '../engine/model'; +import type { Op } from '../engine/ops'; +import { t } from '../i18n'; +import { get } from '../io/api'; +import { el, escapeHtml, patchList, q, qa, setAttr, setClass, setDisabled, setHidden, setHtml, setText, setTitle, setValue } from './dom'; +import { icon } from './icons'; + +export const STOICH_OPEN_KEY = 'formchem.stoichOpen'; + +const DASH = 'โ€“'; +const ENGINE_DELAY_MS = 400; + +type Col = { key: ComponentField | 'role' | 'mmol'; label: string; unit?: string; input: boolean; product: boolean }; + +const COLS: Col[] = [ + { key: 'label', label: 'Component', input: true, product: true }, + { key: 'role', label: 'Role', input: false, product: true }, + { key: 'mw', label: 'MW', unit: 'g/mol', input: true, product: true }, + { key: 'equiv', label: 'Equiv', input: true, product: false }, + { key: 'mass_mg', label: 'Mass', unit: 'mg', input: true, product: false }, + { key: 'volume_ml', label: 'Volume', unit: 'mL', input: true, product: false }, + { key: 'density_g_ml', label: 'Density', unit: 'g/mL', input: true, product: false }, + { key: 'conc_m', label: 'Conc', unit: 'M', input: true, product: false }, + { key: 'purity_pct', label: 'Purity', unit: '%', input: true, product: false }, + { key: 'mmol', label: 'mmol', input: false, product: true }, +]; + +const ROLE_LABEL: Record = { reactant: 'Reactant', agent: 'Reagent', product: 'Product' }; +const NUMERIC = new Set(['mw', 'equiv', 'mass_mg', 'volume_ml', 'density_g_ml', 'conc_m', 'purity_pct']); + +export interface StoichSource { + readonly id: Id; + readonly doc: FormChemDocument; + readonly derived: Derived | null; + readonly rev: number; + on(fn: (e: DocEvent) => void): () => void; + commit(label: string, ops: Op[], opts?: { coalesce?: string }): unknown; +} + +let panel: HTMLElement | null = null; +let open = false; +const listeners = new Set<(open: boolean) => void>(); +let source: StoichSource | null = null; +let sourceOff: (() => void) | null = null; +let scope: Id[] | null = null; +let scopePage: Id | null = null; +let pinned: StepRef | null = null; +let shown: { entry: StepEntry; result: StoichResult } | null = null; +let queued = false; + +let engineMw: Record = {}; +let engineKey = ''; +let engineTimer: number | undefined; +let engineMissing = false; + +function readOpen(): boolean { + try { return localStorage.getItem(STOICH_OPEN_KEY) === '1'; } catch { return false; } +} + +function saveOpen(on: boolean): void { + try { localStorage.setItem(STOICH_OPEN_KEY, on ? '1' : '0'); } catch { return; } +} + +function apply(): void { + if (!panel) return; + setClass(panel, 'is-open', open); + const inner = q(panel, '.fc-sp'); + setAttr(inner, 'aria-hidden', open ? null : 'true'); + if (open) inner.removeAttribute('inert'); else inner.setAttribute('inert', ''); +} + +const head = (c: Col): string => `${escapeHtml(t(c.label))}${c.unit ? ` ${escapeHtml(c.unit)}` : ''}`; + +function markup(): string { + return `
+
+${escapeHtml(t('Stoichiometry'))} + + + +
+
+

${escapeHtml(t('Draw a reaction arrow with reactants and products, then type amounts here.'))}

+
+ +${COLS.map((c) => ``).join('')} +${COLS.map(head).join('')} + +
+
+
+
+ + + + +${escapeHtml(t('Theoretical yield'))}${DASH} +${escapeHtml(t('Yield'))}${DASH} +
+
`; +} + +export function mountStoichPanel(host: HTMLElement): HTMLElement { + if (panel) return panel; + const section = el(`
${markup()}
`); + host.appendChild(section); + panel = section; + open = readOpen(); + wire(section); + apply(); + refreshSoon(); + requestAnimationFrame(() => requestAnimationFrame(() => section.classList.add('is-animated'))); + return section; +} + +export function isStoichOpen(): boolean { return open; } + +export function setStoichOpen(on: boolean): void { + if (on === open) return; + open = on; + saveOpen(on); + apply(); + if (on) refreshSoon(); + for (const l of [...listeners]) l(on); + commandStateChanged(); +} + +export function toggleStoich(): void { setStoichOpen(!open); } + +export function onStoichToggle(fn: (open: boolean) => void): () => void { + listeners.add(fn); + return () => { listeners.delete(fn); }; +} + +export function setStoichSource(next: StoichSource | null): void { + if (next === source) return; + sourceOff?.(); + sourceOff = null; + source = next; + scope = null; + pinned = null; + engineMw = {}; + engineKey = ''; + if (next) sourceOff = next.on((e) => { if (e.type === 'tx' || e.type === 'reset' || e.type === 'derived') refreshSoon(); }); + refreshSoon(); +} + +export function setStoichScope(objectIds: readonly Id[] | null, pageId: Id | null = null): void { + scope = objectIds && objectIds.length ? [...objectIds] : null; + scopePage = pageId; + if (scope && source) { + const hit = stepFor(source.doc, scope, pageId); + const want = new Set(scope); + if (hit && (want.has(hit.step.arrow) || [...hit.step.reactants, ...hit.step.products, ...hit.step.agents].some((id) => want.has(id)))) pinned = null; + } + refreshSoon(); +} + +export function currentStoichStep(): StepRef | null { return shown?.entry.ref ?? null; } + +function refreshSoon(): void { + if (queued) return; + queued = true; + queueMicrotask(() => { queued = false; refreshStoich(); }); +} + +function sameRef(a: StepRef | null, b: StepRef | null): boolean { + return !!a && !!b && a.page === b.page && a.reaction === b.reaction && a.step === b.step; +} + +function resolveEntry(doc: FormChemDocument): StepEntry | null { + if (pinned) { + const step = findStep(doc, pinned); + if (step) return reactionSteps(doc).find((e) => sameRef(e.ref, pinned)) ?? null; + pinned = null; + } + return stepFor(doc, scope, scopePage); +} + +export function refreshStoich(): void { + if (!panel) return; + const s = source; + const entry = s && open ? resolveEntry(s.doc) : null; + if (!s || !entry) { + shown = null; + render(null, s ? reactionSteps(s.doc) : []); + return; + } + const derived = s.derived && s.derived.rev === s.rev ? s.derived : null; + const result = computeStoich(s.doc, entry.step, derived, engineMw); + shown = { entry, result }; + render(shown, reactionSteps(s.doc)); + reconcileSoon(s, entry, result); +} + +function stepLabel(e: StepEntry, all: StepEntry[]): string { + const multi = new Set(all.map((x) => x.ref.reaction)).size > 1; + return multi ? `${t('Reaction')} ${e.reactionIndex + 1}, ${t('step')} ${e.index + 1}` : `${t('Step')} ${e.index + 1}`; +} + +function renderSteps(all: StepEntry[], current: StepEntry | null): void { + const sel = q(panel as HTMLElement, '[data-sp="step"]'); + const key = all.map((e) => `${e.ref.page}/${e.ref.reaction}/${e.ref.step}`).join('|'); + setHtml(sel, all.map((e) => ``).join(''), key); + setValue(sel, current ? `${current.ref.page}/${current.ref.reaction}/${current.ref.step}` : ''); + setHidden(sel, all.length < 2); +} + +function rowNode(row: StoichRow): HTMLElement { + const cells = COLS.map((c) => { + if (c.key === 'role') return ''; + if (c.key === 'mmol') return ''; + const mode = NUMERIC.has(c.key) ? ' inputmode="decimal"' : ''; + return ``; + }).join(''); + const tr = el(`${cells}
`).querySelector('tr') as HTMLElement; + updateRow(tr, row); + return tr; +} + +function typedOf(row: StoichRow, key: ComponentField): string { + const v = (row.typed as Record)[key]; + if (key === 'label') return typeof v === 'string' ? v : ''; + return typedText(typeof v === 'number' ? v : undefined); +} + +function computedOf(row: StoichRow, key: ComponentField): string { + switch (key) { + case 'label': return row.name; + case 'mw': return fixed(row.mw, 2); + case 'equiv': return sig(row.equiv, 3); + case 'mass_mg': return sig(row.massMg, 3); + case 'volume_ml': return sig(row.volumeMl, 3); + case 'density_g_ml': return ''; + case 'conc_m': return ''; + case 'purity_pct': return row.role === 'product' ? '' : '100'; + } +} + +function updateRow(tr: HTMLElement, row: StoichRow): void { + setClass(tr, 'is-limiting', row.limiting); + setClass(tr, 'is-product', row.role === 'product'); + setAttr(tr, 'data-role', row.role); + setText(tr.querySelector('.fc-sp-role'), t(ROLE_LABEL[row.role]) + (row.limiting ? ` ยท ${t('limiting')}` : '')); + setText(tr.querySelector('.fc-sp-out'), sig(row.mmol, 3) || DASH); + for (const input of qa(tr, 'input[data-f]')) { + const key = input.dataset.f as ComponentField; + const col = COLS.find((c) => c.key === key); + const locked = row.role === 'product' && !col?.product; + setDisabled(input, locked); + setValue(input, locked ? '' : typedOf(row, key)); + setAttr(input, 'placeholder', computedOf(row, key) || (locked ? '' : DASH)); + const source = (key === 'mass_mg' && row.source === 'mass') || (key === 'volume_ml' && row.source === 'volume') || (key === 'equiv' && row.source === 'equiv'); + setClass(input, 'is-source', source); + setClass(input, 'is-typed', !!typedOf(row, key)); + } + const name = tr.querySelector('input[data-f="label"]'); + if (name) setTitle(name, row.formula ? `${row.name} (${row.formula})` : row.name); +} + +function renderOptions(sel: HTMLSelectElement, items: { id: Id; label: string }[], value: string, auto: string | null): void { + const opts = [...(auto !== null ? [{ id: '', label: auto }] : []), ...items]; + setHtml(sel, opts.map((o) => ``).join(''), opts.map((o) => `${o.id}:${o.label}`).join('|')); + setValue(sel, value); + setDisabled(sel, items.length === 0); +} + +function render(view: { entry: StepEntry; result: StoichResult } | null, all: StepEntry[]): void { + const root = panel as HTMLElement; + renderSteps(all, view?.entry ?? null); + const body = q(root, '.fc-sp-grid tbody'); + const rows = view?.result.rows ?? []; + patchList(body, rows, { key: (r) => r.id, create: rowNode, update: updateRow }); + setHidden(q(root, '.fc-sp-empty'), rows.length > 0); + setClass(root, 'is-empty', rows.length === 0); + const r = view?.result; + const data = view?.entry.step.stoich; + const scale = q(root, '[data-step="scale_mmol"]'); + setValue(scale, typedText(data?.scale_mmol)); + setAttr(scale, 'placeholder', sig(r?.refMmol, 3) || DASH); + setDisabled(scale, !r); + const isolated = q(root, '[data-step="isolated_mg"]'); + setValue(isolated, typedText(data?.isolated_mg)); + setAttr(isolated, 'placeholder', DASH); + setDisabled(isolated, !r?.product); + const inputsOf = rows.filter((x) => x.role !== 'product'); + const autoName = r?.limitingAuto && r.limiting ? rows.find((x) => x.id === r.limiting)?.name : null; + renderOptions(q(root, '[data-step="limiting"]'), inputsOf.map((x) => ({ id: x.id, label: x.name })), data?.limiting ?? '', autoName ? `${t('Auto')} (${autoName})` : t('Auto')); + renderOptions(q(root, '[data-step="product"]'), rows.filter((x) => x.role === 'product').map((x) => ({ id: x.id, label: x.name })), data?.product ?? r?.product ?? '', null); + setText(root.querySelector('[data-out="theo"]'), r?.theoMg !== null && r?.theoMg !== undefined ? `${sig(r.theoMg, 3)} mg ยท ${sig(r.theoMmol, 3)} mmol` : DASH); + setText(root.querySelector('[data-out="yield"]'), r?.yieldPct !== null && r?.yieldPct !== undefined ? `${fixed(r.yieldPct, 1)} %` : DASH); +} + +function commit(ops: Op[], label: string): void { + if (!source || !ops.length) return; + source.commit(label, ops); +} + +function commitCell(input: HTMLInputElement): void { + const tr = input.closest('tr[data-key]'); + const view = shown; + if (!tr || !view || !source) return; + const comp = tr.dataset.key as Id; + const key = input.dataset.f as ComponentField; + const row = view.result.rows.find((r) => r.id === comp); + if (!row) return; + let value: number | string | null; + if (key === 'label') value = input.value.trim() || null; + else { + const parsed = parseAmount(input.value); + if (parsed === undefined || (key === 'purity_pct' && parsed !== null && (parsed <= 0 || parsed > 100))) { input.value = typedOf(row, key); return; } + value = parsed === 0 && key !== 'equiv' ? null : parsed; + } + commit(componentEdit(source.doc, view.entry.ref, comp, key, value), t('Edit Stoichiometry')); +} + +function commitStep(control: HTMLInputElement | HTMLSelectElement): void { + const view = shown; + if (!view || !source) return; + const field = control.dataset.step as StepField; + let value: number | string | null; + if (control instanceof HTMLSelectElement) value = control.value || null; + else { + const parsed = parseAmount(control.value); + if (parsed === undefined) { control.value = typedText((view.entry.step.stoich as Record | undefined)?.[field]); return; } + value = parsed === 0 && field === 'scale_mmol' ? null : parsed; + } + commit(stepEdit(source.doc, view.entry.ref, field, value, { limiting: view.result.limiting }), t('Edit Stoichiometry')); +} + +function wire(root: HTMLElement): void { + root.addEventListener('change', (e) => { + const target = e.target as HTMLElement; + if (target instanceof HTMLInputElement && target.dataset.f) commitCell(target); + else if ((target instanceof HTMLInputElement || target instanceof HTMLSelectElement) && target.dataset.step) commitStep(target); + else if (target instanceof HTMLSelectElement && target.dataset.sp === 'step') { + const [page, reaction, step] = target.value.split('/'); + pinned = page && reaction && step ? { page, reaction, step } : null; + refreshSoon(); + } + }); + root.addEventListener('keydown', (e) => { + const target = e.target; + if (!(target instanceof HTMLInputElement)) return; + e.stopPropagation(); + if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); target.blur(); } + else if (e.key === 'Escape') { + e.preventDefault(); + const tr = target.closest('tr[data-key]'); + const row = tr ? shown?.result.rows.find((r) => r.id === tr.dataset.key) : undefined; + if (row && target.dataset.f) target.value = typedOf(row, target.dataset.f as ComponentField); + else if (target.dataset.step) target.value = typedText((shown?.entry.step.stoich as Record | undefined)?.[target.dataset.step]); + target.blur(); + } + }); + root.addEventListener('focusout', () => { queueMicrotask(() => { if (!root.contains(document.activeElement)) refreshSoon(); }); }); + root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('[data-sp="close"]'); + if (b) setStoichOpen(false); + }); +} + +function engineUrl(docId: Id, ref: StepRef): string { + return `/api/docs/${encodeURIComponent(docId)}/reactions/${encodeURIComponent(ref.reaction)}/steps/${encodeURIComponent(ref.step)}/stoich`; +} + +function engineWeights(raw: unknown): Record { + const out: Record = {}; + const comps = (raw as { components?: unknown; rows?: unknown } | null)?.components ?? (raw as { rows?: unknown } | null)?.rows; + const take = (id: unknown, rec: unknown): void => { + const mw = (rec as { mw?: unknown } | null)?.mw; + if (typeof id === 'string' && typeof mw === 'number' && Number.isFinite(mw) && mw > 0) out[id] = mw; + }; + if (Array.isArray(comps)) for (const c of comps) take((c as { id?: unknown; object?: unknown })?.id ?? (c as { object?: unknown })?.object, c); + else if (comps && typeof comps === 'object') for (const [id, c] of Object.entries(comps)) take(id, c); + return out; +} + +function reconcileSoon(s: StoichSource, entry: StepEntry, result: StoichResult): void { + if (engineMissing) return; + const unsure = result.rows.some((r) => r.mwFrom !== 'typed' && r.mwFrom !== 'engine'); + const key = `${s.id}@${s.rev}/${entry.ref.reaction}/${entry.ref.step}`; + if (!unsure || key === engineKey) return; + engineKey = key; + window.clearTimeout(engineTimer); + engineTimer = window.setTimeout(() => { + get(engineUrl(s.id, entry.ref)).then((raw) => { + if (source !== s || engineKey !== key) return; + const found = engineWeights(raw); + if (!Object.keys(found).length) return; + engineMw = { ...engineMw, ...found }; + refreshSoon(); + }).catch((e: unknown) => { + const status = (e as { status?: number })?.status; + if (status === 405 || (status === 404 && (e as Error).message === 'Not Found')) engineMissing = true; + }); + }, ENGINE_DELAY_MS); +} From 2e3f898b2badaa808e508f167ba89ddbefd1134d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:10:32 -0500 Subject: [PATCH 071/279] style(stoich): style the stoichiometry panel (0.5.0) The panel takes a reserved row under the stage that opens by height, with a sticky header, tabular numbers and an accent mark on the amount that is each row's source of truth. --- frontend/index.html | 1 + frontend/src/styles/stoich.css | 54 ++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 frontend/src/styles/stoich.css diff --git a/frontend/index.html b/frontend/index.html index 07b62cd8..29e67499 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -101,6 +101,7 @@ + diff --git a/frontend/src/styles/stoich.css b/frontend/src/styles/stoich.css new file mode 100644 index 00000000..683ad17c --- /dev/null +++ b/frontend/src/styles/stoich.css @@ -0,0 +1,54 @@ +.fc-workspace > .fc-stoich { grid-column: 1 / -1; grid-row: 2; height: 0; min-width: 0; overflow: hidden; background: var(--surface-0); border-top: 0 solid var(--line-1); } +.fc-stoich.is-open { height: var(--fc-stoich-h, 236px); border-top-width: 1px; } +.fc-stoich.is-animated { transition: height var(--transition-normal), border-top-width var(--transition-normal); } + +.fc-sp { display: grid; grid-template-rows: 36px minmax(0, 1fr) 42px; height: var(--fc-stoich-h, 236px); min-width: 0; color: var(--text-primary); font-size: var(--fc-12); } +.fc-sp-head { display: flex; align-items: center; gap: var(--space-2); min-width: 0; padding: 0 var(--space-2) 0 var(--space-4); border-bottom: 1px solid var(--line-1); } +.fc-sp-title { flex: none; color: var(--text-secondary); font-size: var(--fc-11); font-weight: 600; letter-spacing: 0.4px; text-transform: uppercase; } +.fc-sp-spacer { flex: 1 1 auto; } +.fc-sp-step, .fc-sp-sel { height: var(--ctl-sm); min-width: 0; max-width: 220px; padding: 0 6px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-field); color: var(--text-primary); font: inherit; font-size: var(--fc-12); outline: 0; } +.fc-sp-step:focus, .fc-sp-sel:focus { border-color: var(--accent-color); } +.fc-sp-step[hidden] { display: none; } +.fc-sp-sel:disabled { color: var(--text-muted); } +.fc-sp-head .fc-btn { flex: none; gap: 6px; } + +.fc-sp-body { position: relative; min-height: 0; } +.fc-sp-scroll { height: 100%; overflow: auto; overscroll-behavior: contain; } +.fc-sp-empty { position: absolute; inset: 28px 0 0; display: grid; place-items: center; margin: 0; padding: 0 var(--space-4); color: var(--text-muted); font-size: var(--fc-12); text-align: center; pointer-events: none; } +.fc-sp-empty[hidden] { display: none; } + +.fc-sp-grid { width: 100%; min-width: 880px; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-variant-numeric: tabular-nums; } +.fc-sp-col-label { width: 24%; } +.fc-sp-col-role { width: 128px; } +.fc-sp-col-mw, .fc-sp-col-mass_mg, .fc-sp-col-mmol { width: 92px; } +.fc-sp-col-equiv, .fc-sp-col-volume_ml, .fc-sp-col-density_g_ml, .fc-sp-col-conc_m, .fc-sp-col-purity_pct { width: 80px; } +.fc-sp-grid thead th { position: sticky; top: 0; z-index: var(--z-local-2); height: 28px; padding: 0 8px; overflow: hidden; background: var(--surface-1); border-bottom: 1px solid var(--line-1); color: var(--text-secondary); font-size: var(--fc-11); font-weight: 600; text-align: right; text-overflow: ellipsis; white-space: nowrap; } +.fc-sp-grid thead th.fc-sp-c-label, .fc-sp-grid thead th.fc-sp-c-role { text-align: left; } +.fc-sp-unit { color: var(--text-muted); font-weight: 400; } + +.fc-sp-row td { height: 30px; padding: 0 2px; border-bottom: 1px solid var(--line-0); white-space: nowrap; } +.fc-sp-row:last-child td { border-bottom: 0; } +.fc-sp-row.is-product td { background: var(--surface-1); } +.fc-sp-in { box-sizing: border-box; width: 100%; height: 24px; padding: 0 6px; border: 1px solid transparent; border-radius: var(--radius-sm); background: transparent; color: var(--text-primary); font: inherit; font-family: var(--font-mono); font-size: var(--fc-12); text-align: right; outline: 0; } +.fc-sp-c-label .fc-sp-in { font-family: var(--font-ui); text-align: left; text-overflow: ellipsis; } +.fc-sp-in:hover:not(:disabled) { border-color: var(--line-2); background: var(--surface-field); } +.fc-sp-in:focus { border-color: var(--accent-color); background: var(--surface-field); } +.fc-sp-in::placeholder { color: var(--text-muted); opacity: 1; } +.fc-sp-in:disabled { cursor: default; } +.fc-sp-in.is-typed { font-weight: 600; } +.fc-sp-in.is-source { box-shadow: inset 2px 0 0 var(--accent-color); } +.fc-sp-role { display: block; padding: 0 6px; overflow: hidden; color: var(--text-secondary); text-overflow: ellipsis; } +.fc-sp-row.is-limiting .fc-sp-role { color: var(--accent-ink); font-weight: 600; } +.fc-sp-out { display: block; padding: 0 8px; font-family: var(--font-mono); text-align: right; } + +.fc-sp-foot { display: flex; align-items: center; gap: var(--space-4); min-width: 0; padding: 0 var(--space-4); overflow-x: auto; overflow-y: hidden; scrollbar-width: none; border-top: 1px solid var(--line-1); background: var(--surface-1); white-space: nowrap; } +.fc-sp-foot::-webkit-scrollbar { display: none; } +.fc-sp-field { display: inline-flex; flex: none; align-items: center; gap: 6px; color: var(--text-secondary); } +.fc-sp-foot .fc-sp-in { width: 84px; border-color: var(--line-2); background: var(--surface-field); } +.fc-sp-foot .fc-sp-in:focus { border-color: var(--accent-color); } +.fc-sp-stat { display: inline-flex; flex: none; align-items: baseline; gap: 6px; color: var(--text-secondary); } +.fc-sp-field + .fc-sp-stat { margin-left: auto; } +.fc-sp-stat b { min-width: 7ch; color: var(--text-primary); font-family: var(--font-mono); font-weight: 600; } + +.fc-stoich :where(button, select, input):focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-stoich .fc-sp-in:focus-visible { outline: 0; } From d28a308a4fbfc691844cb9ec3069375d21d467cf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:11:43 -0500 Subject: [PATCH 072/279] feat(stoich): insert the stoichiometry grid as a table (0.5.0) Insert as table commits one transaction that adds a TableObject bound to the step through stoich {reaction, step}, placed under the reaction with rows written from the current computed grid so it reads correctly before the table renderer keeps it in sync. --- frontend/src/chem/stoich-ops.ts | 57 +++++++++++++++++++++++++++++++-- frontend/src/ui/stoich-panel.ts | 27 ++++++++++++++-- 2 files changed, 79 insertions(+), 5 deletions(-) diff --git a/frontend/src/chem/stoich-ops.ts b/frontend/src/chem/stoich-ops.ts index 12f41b70..8943c247 100644 --- a/frontend/src/chem/stoich-ops.ts +++ b/frontend/src/chem/stoich-ops.ts @@ -1,6 +1,6 @@ -import type { FormChemDocument, Id, Stoich, StoichComponent } from '../engine/model'; +import { fragmentBounds, isFragment, newId, resolveStyle, type FormChemDocument, type Id, type Stoich, type StoichComponent, type TableObject, type TableRow } from '../engine/model'; import type { Op, Path } from '../engine/ops'; -import { findStep, type StepRef } from './stoich'; +import { findStep, fixed, sig, type StepRef, type StoichResult, type StoichRole } from './stoich'; export type ComponentField = 'equiv' | 'mass_mg' | 'volume_ml' | 'density_g_ml' | 'conc_m' | 'purity_pct' | 'mw' | 'label'; export type StepField = 'scale_mmol' | 'limiting' | 'product' | 'isolated_mg'; @@ -57,3 +57,56 @@ export function stepEdit(doc: FormChemDocument, ref: StepRef, field: StepField, } return ops; } + +export interface TableText { + header: string[]; + roles: Record; + theoretical: string; + isolated: string; +} + +const TABLE_COLS = [96, 52, 48, 40, 46, 52, 50]; +const ROW_H = 18; + +function stepBox(doc: FormChemDocument, ids: Id[]): { x: number; y: number; bottom: number } | null { + let x = Infinity, y = Infinity, bottom = -Infinity; + const take = (x0: number, y0: number, y1: number): void => { x = Math.min(x, x0); y = Math.min(y, y0); bottom = Math.max(bottom, y1); }; + for (const id of ids) { + const o = doc.objects[id] as unknown as Record | undefined; + if (!o) continue; + if (isFragment(o)) { + const b = fragmentBounds(o); + if (b) take(b.x, b.y, b.y + b.h); + } else if (typeof o.x1 === 'number' && typeof o.y1 === 'number' && typeof o.x2 === 'number' && typeof o.y2 === 'number') { + take(Math.min(o.x1, o.x2), Math.min(o.y1, o.y2), Math.max(o.y1, o.y2)); + } else if (typeof o.x === 'number' && typeof o.y === 'number') { + take(o.x, o.y, o.y + (typeof o.h === 'number' ? o.h : 12)); + } + } + return Number.isFinite(x) && Number.isFinite(bottom) ? { x, y, bottom } : null; +} + +const cell = (text: string): { runs: { t: string }[] } => ({ runs: text ? [{ t: text }] : [] }); + +export function stoichTableOps(doc: FormChemDocument, ref: StepRef, result: StoichResult, text: TableText): { ops: Op[]; id: Id } | null { + const step = findStep(doc, ref); + const page = doc.pages.find((p) => p.id === ref.page); + if (!step || !page) return null; + const rows: TableRow[] = [{ id: newId('l'), h: ROW_H, cells: text.header.map(cell) }]; + for (const r of result.rows) { + rows.push({ id: newId('l'), h: ROW_H, cells: [r.name, text.roles[r.role], fixed(r.mw, 2), sig(r.equiv, 3), sig(r.mmol, 3), sig(r.massMg, 3), sig(r.volumeMl, 3)].map(cell) }); + } + if (result.product && result.theoMg !== null) rows.push({ id: newId('l'), h: ROW_H, cells: [text.theoretical, '', '', '', sig(result.theoMmol, 3), sig(result.theoMg, 3), ''].map(cell) }); + if (result.isolatedMg !== null) rows.push({ id: newId('l'), h: ROW_H, cells: [text.isolated, '', '', '', '', sig(result.isolatedMg, 3), result.yieldPct !== null ? `${fixed(result.yieldPct, 1)} %` : ''].map(cell) }); + const box = stepBox(doc, [step.arrow, ...step.reactants, ...step.agents, ...step.products, ...(step.conditions ?? [])]); + const gap = 2 * resolveStyle(doc).bond_length; + const margin = page.margins ?? 36; + const id = newId('o'); + const table: TableObject = { + id, kind: 'table', name: 'Stoichiometry', + x: box ? +box.x.toFixed(3) : margin, y: box ? +(box.bottom + gap).toFixed(3) : margin, + cols: [...TABLE_COLS], rows, padding: 3, header: true, borders: 'all', + stoich: { reaction: ref.reaction, step: ref.step }, + }; + return { id, ops: [{ op: 'set', path: ['objects', id], value: table }, { op: 'ins', path: ['pages', { id: page.id }, 'order'], value: id }] }; +} diff --git a/frontend/src/ui/stoich-panel.ts b/frontend/src/ui/stoich-panel.ts index cb0a46cc..7730c7bb 100644 --- a/frontend/src/ui/stoich-panel.ts +++ b/frontend/src/ui/stoich-panel.ts @@ -1,6 +1,6 @@ import { commandStateChanged } from '../app/commands-shell'; import { computeStoich, findStep, fixed, parseAmount, reactionSteps, sig, stepFor, typedText, type StepEntry, type StepRef, type StoichResult, type StoichRow } from '../chem/stoich'; -import { componentEdit, stepEdit, type ComponentField, type StepField } from '../chem/stoich-ops'; +import { componentEdit, stepEdit, stoichTableOps, type ComponentField, type StepField } from '../chem/stoich-ops'; import type { DocEvent } from '../engine/client-api'; import type { Derived, FormChemDocument, Id } from '../engine/model'; import type { Op } from '../engine/ops'; @@ -81,6 +81,7 @@ function markup(): string { ${escapeHtml(t('Stoichiometry'))} +
@@ -277,6 +278,7 @@ function render(view: { entry: StepEntry; result: StoichResult } | null, all: St patchList(body, rows, { key: (r) => r.id, create: rowNode, update: updateRow }); setHidden(q(root, '.fc-sp-empty'), rows.length > 0); setClass(root, 'is-empty', rows.length === 0); + setDisabled(q(root, '[data-sp="table"]'), rows.length === 0); const r = view?.result; const data = view?.entry.step.stoich; const scale = q(root, '[data-step="scale_mmol"]'); @@ -359,11 +361,30 @@ function wire(root: HTMLElement): void { }); root.addEventListener('focusout', () => { queueMicrotask(() => { if (!root.contains(document.activeElement)) refreshSoon(); }); }); root.addEventListener('click', (e) => { - const b = (e.target as HTMLElement).closest('[data-sp="close"]'); - if (b) setStoichOpen(false); + const b = (e.target as HTMLElement).closest('[data-sp]'); + if (!b || b.disabled) return; + if (b.dataset.sp === 'close') setStoichOpen(false); + else if (b.dataset.sp === 'table') insertStoichTable(); }); } +export function insertStoichTable(): Id | null { + const s = source; + if (!s) return null; + const entry = shown?.entry ?? resolveEntry(s.doc); + if (!entry) return null; + const derived = s.derived && s.derived.rev === s.rev ? s.derived : null; + const result = shown?.entry === entry ? shown.result : computeStoich(s.doc, entry.step, derived, engineMw); + const built = stoichTableOps(s.doc, entry.ref, result, { + header: [t('Component'), t('Role'), 'MW', t('Equiv'), 'mmol', `${t('Mass')} (mg)`, `${t('Volume')} (mL)`], + roles: { reactant: t(ROLE_LABEL.reactant), agent: t(ROLE_LABEL.agent), product: t(ROLE_LABEL.product) }, + theoretical: t('Theoretical yield'), + isolated: t('Isolated'), + }); + if (!built) return null; + return s.commit(t('Insert Stoichiometry Table'), built.ops) ? built.id : null; +} + function engineUrl(docId: Id, ref: StepRef): string { return `/api/docs/${encodeURIComponent(docId)}/reactions/${encodeURIComponent(ref.reaction)}/steps/${encodeURIComponent(ref.step)}/stoich`; } From 5facaa8f3db637a2c41daa18ecf4f74fcbeaf523 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:17:27 -0500 Subject: [PATCH 073/279] feat(templates): add a light SVG thumbnail renderer for templates (0.5.0) Template cards need a static picture of fragments, shapes and lines without mounting a canvas per card, so thumbnails are one SVG string per template built from the window's own label, ring and double-bond helpers and drawn in currentColor. --- frontend/src/ui/template-thumb.ts | 171 ++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 frontend/src/ui/template-thumb.ts diff --git a/frontend/src/ui/template-thumb.ts b/frontend/src/ui/template-thumb.ts new file mode 100644 index 00000000..2daa9f72 --- /dev/null +++ b/frontend/src/ui/template-thumb.ts @@ -0,0 +1,171 @@ +import { sideNormal } from '../chem/graph'; +import { doubleBondSides } from '../chem/rings'; +import { atomLabel } from '../chem/valence'; +import { isFragment, type DocObject, type Fragment, type Id, type LineObject, type ShapeObject } from '../engine/model'; +import { escapeHtml } from './dom'; + +export interface ThumbBounds { x: number; y: number; w: number; h: number } + +const FONT = 10; +const SPACING = 2.6; +const HALF_CHAR = 3.4; +const KNOCK = 4.6; + +const n = (v: number): string => (Math.round(v * 100) / 100).toString(); + +function line(x1: number, y1: number, x2: number, y2: number, extra = ''): string { + return ``; +} + +function labelSvg(frag: Fragment, id: Id): { svg: string; shown: boolean } { + const a = frag.atoms[id]; + const lab = atomLabel(frag, id); + if (!lab.show) return { svg: '', shown: false }; + const left = lab.side === 'left'; + const x = left ? a.x + HALF_CHAR : a.x - HALF_CHAR; + const spans = lab.runs.map((r) => { + const t = escapeHtml(r.t); + if (r.sub) return `${t}`; + if (r.sup) return `${t}`; + return `${t}`; + }).join(''); + return { svg: `${spans}`, shown: true }; +} + +function fragmentSvg(frag: Fragment): string { + const labels = new Map(); + for (const id of Object.keys(frag.atoms)) { + const l = labelSvg(frag, id); + if (l.shown) labels.set(id, l.svg); + } + const sides = doubleBondSides(frag); + const out: string[] = []; + for (const b of Object.values(frag.bonds)) { + const pa = frag.atoms[b.a], pb = frag.atoms[b.b]; + if (!pa || !pb) continue; + const dx = pb.x - pa.x, dy = pb.y - pa.y; + const len = Math.hypot(dx, dy) || 1; + const ux = dx / len, uy = dy / len; + const ca = labels.has(b.a) ? KNOCK : 0, cb = labels.has(b.b) ? KNOCK : 0; + const x1 = pa.x + ux * ca, y1 = pa.y + uy * ca, x2 = pb.x - ux * cb, y2 = pb.y - uy * cb; + const order = b.order ?? 1; + const stereo = b.stereo ?? 'none'; + if (stereo === 'wedge' || stereo === 'hash') { + const px = -uy * 1.5, py = ux * 1.5; + if (stereo === 'wedge') out.push(``); + else { + const steps = Math.max(3, Math.round(len / 2.5)); + for (let i = 1; i <= steps; i++) { + const f = i / steps; + const cx = x1 + (x2 - x1) * f, cy = y1 + (y2 - y1) * f; + out.push(line(cx + px * f, cy + py * f, cx - px * f, cy - py * f)); + } + } + continue; + } + const bold = b.bold ? ' class="is-bold"' : ''; + if (order === 2 || order === 1.5) { + const side = sides.get(b.id) ?? 'centre'; + if (side === 'centre') { + const ox = -uy * SPACING / 2, oy = ux * SPACING / 2; + out.push(line(x1 + ox, y1 + oy, x2 + ox, y2 + oy), line(x1 - ox, y1 - oy, x2 - ox, y2 - oy)); + } else { + const [nx, ny] = sideNormal([pa.x, pa.y], [pb.x, pb.y], side); + const trim = labels.has(b.a) || labels.has(b.b) ? 0 : SPACING * 0.9; + out.push(line(x1, y1, x2, y2, bold)); + const dash = order === 1.5 ? ' stroke-dasharray="1.6 1.4"' : ''; + out.push(line(x1 + nx * SPACING + ux * trim, y1 + ny * SPACING + uy * trim, x2 + nx * SPACING - ux * trim, y2 + ny * SPACING - uy * trim, dash)); + } + } else if (order === 3) { + const ox = -uy * SPACING, oy = ux * SPACING; + out.push(line(x1, y1, x2, y2), line(x1 + ox, y1 + oy, x2 + ox, y2 + oy), line(x1 - ox, y1 - oy, x2 - ox, y2 - oy)); + } else { + out.push(line(x1, y1, x2, y2, bold)); + } + } + return `${out.join('')}${[...labels.values()].join('')}`; +} + +function paint(stroke: ShapeObject['stroke'], fill: ShapeObject['fill'], opacity?: number): string { + const parts: string[] = []; + if (stroke === null) parts.push('stroke="none"'); + else { + if (stroke?.color) parts.push(`stroke="${escapeHtml(stroke.color)}"`); + if (stroke?.dash === 'dash') parts.push('stroke-dasharray="3 2"'); + else if (stroke?.dash === 'dot') parts.push('stroke-dasharray="0.8 1.6"'); + else if (stroke?.dash === 'dash_dot') parts.push('stroke-dasharray="3 1.5 0.8 1.5"'); + } + if (fill && fill.type === 'solid') parts.push(`fill="${escapeHtml(fill.color)}"`, 'class="is-own-fill"'); + else if (fill && fill.type === 'linear') parts.push(`fill="${escapeHtml(fill.stops[0]?.color ?? 'none')}"`, 'class="is-own-fill"'); + if (typeof opacity === 'number') parts.push(`opacity="${n(opacity)}"`); + return parts.join(' '); +} + +function shapeSvg(s: ShapeObject): string { + const attrs = paint(s.stroke, s.fill, s.opacity); + const rot = s.rot ? ` transform="rotate(${n(-s.rot)} ${n(s.x + s.w / 2)} ${n(s.y + s.h / 2)})"` : ''; + switch (s.geom) { + case 'rect': return ``; + case 'round_rect': { + const r = s.radius ?? Math.min(s.w, s.h) * 0.1; + return ``; + } + case 'ellipse': return ``; + case 'polygon': { + const k = Math.max(3, Math.min(12, s.sides ?? 6)); + const pts = Array.from({ length: k }, (_, i) => { + const t = (-90 + (i * 360) / k) * (Math.PI / 180); + return `${n(s.x + s.w / 2 + (s.w / 2) * Math.cos(t))},${n(s.y + s.h / 2 + (s.h / 2) * Math.sin(t))}`; + }).join(' '); + return ``; + } + case 'path': return s.path ? `` : ''; + } +} + +function lineSvg(l: LineObject): string { + if (!Array.isArray(l.points) || l.points.length < 2) return ''; + return ``; +} + +function textSvg(o: DocObject): string { + const r = o as { x?: number; y?: number; runs?: { t?: string }[] }; + if (typeof r.x !== 'number' || typeof r.y !== 'number' || !Array.isArray(r.runs)) return ''; + return `${escapeHtml(r.runs.map((x) => x.t ?? '').join(''))}`; +} + +function objectSvg(o: DocObject, byId: Map, depth = 0): string { + if (isFragment(o)) return fragmentSvg(o); + if (o.kind === 'shape') return shapeSvg(o as ShapeObject); + if (o.kind === 'line') return lineSvg(o as LineObject); + if (o.kind === 'text' || o.kind === 'caption') return textSvg(o); + if (o.kind === 'group' && depth < 8) return ((o as { children?: Id[] }).children ?? []).map((id) => byId.get(id)).filter((c): c is DocObject => !!c).map((c) => objectSvg(c, byId, depth + 1)).join(''); + return ''; +} + +export function thumbBounds(objects: readonly DocObject[]): ThumbBounds | null { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + const take = (x: number, y: number): void => { x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }; + for (const o of objects) { + const r = o as unknown as Record; + if (isFragment(o)) for (const a of Object.values(o.atoms)) take(a.x, a.y); + else if (o.kind === 'line') for (const p of (o as LineObject).points ?? []) take(p[0], p[1]); + else if (typeof r.x === 'number' && typeof r.y === 'number') { + take(r.x, r.y); + take(r.x + (typeof r.w === 'number' ? r.w : 0), r.y + (typeof r.h === 'number' ? r.h : FONT)); + } + } + return Number.isFinite(x0) ? { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } : null; +} + +export function templateThumb(objects: readonly DocObject[], order?: readonly Id[]): string { + const byId = new Map(objects.map((o) => [o.id, o] as [Id, DocObject])); + const top = order?.length ? order.map((id) => byId.get(id)).filter((o): o is DocObject => !!o) : objects; + const b = thumbBounds(objects); + if (!b) return ''; + const pad = 8; + const side = Math.max(b.w, b.h, 24) + pad * 2; + const vx = b.x + b.w / 2 - side / 2, vy = b.y + b.h / 2 - side / 2; + const body = top.map((o) => objectSvg(o, byId)).join(''); + return ``; +} From 8873d2dda0e8b6a22c9760e719bcfa38b6c8d18a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:17:27 -0500 Subject: [PATCH 074/279] feat(templates): add the insert template dialog (0.5.0) A searchable category grid on the shared dialog shell with lazily drawn thumbnails in reserved cards; a click fetches the template with fresh ids at the drawing's bond length and inserts it centred in view as one transaction (also exported for the insert-template command and agents). --- frontend/src/ui/template-dialog.ts | 267 +++++++++++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 frontend/src/ui/template-dialog.ts diff --git a/frontend/src/ui/template-dialog.ts b/frontend/src/ui/template-dialog.ts new file mode 100644 index 00000000..d6faa4bf --- /dev/null +++ b/frontend/src/ui/template-dialog.ts @@ -0,0 +1,267 @@ +import type { EngineDocumentClient } from '../engine/client'; +import { isFragment, resolveStyle, type DocObject, type Fragment, type Id, type Point, type StyleOverride } from '../engine/model'; +import type { Op } from '../engine/ops'; +import { session } from '../engine/session'; +import { t } from '../i18n'; +import { get } from '../io/api'; +import { Dialog } from './dialogs'; +import { el, escapeHtml, q, qa, setAttr, setClass, setHidden, setHtml, setText } from './dom'; +import { icon } from './icons'; +import { templateThumb, thumbBounds } from './template-thumb'; +import { toast } from './toast'; + +export interface TemplateCategory { id: string; name: string; count: number; origin?: string } + +export interface TemplateItem { + id: string; + name: string; + category: string; + tags: string[]; + origin?: string; + objects?: DocObject[]; + order?: Id[]; + error?: string; +} + +export interface TemplateLibrary { categories: TemplateCategory[]; templates: TemplateItem[] } + +export interface TemplateInsert { id: string; name: string; objects: DocObject[]; order: Id[]; bounds: { x: number; y: number; w: number; h: number } } + +export interface TemplateHooks { + placement?(client: EngineDocumentClient): { page: Id; at: Point } | null; + inserted?(client: EngineDocumentClient, fragments: Fragment[]): void; + createOptions?(): { preset?: string; style?: StyleOverride }; +} + +const LIST_URL = '/api/templates?objects=1'; +const ITEM_URL = (id: string): string => `/api/templates/${encodeURIComponent(id)}`; + +let library: Promise | null = null; +const thumbs = new Map(); + +export function loadTemplates(force = false): Promise { + if (!library || force) { + library = get>(LIST_URL).then((raw) => ({ + categories: Array.isArray(raw.categories) ? raw.categories.filter((c) => c && typeof c.id === 'string') : [], + templates: Array.isArray(raw.templates) ? raw.templates.filter((x) => x && typeof x.id === 'string') : [], + })); + library.catch(() => { library = null; }); + } + return library; +} + +export function thumbFor(item: TemplateItem): string { + let svg = thumbs.get(item.id); + if (svg === undefined) { + svg = item.objects?.length ? templateThumb(item.objects, item.order) : ''; + thumbs.set(item.id, svg); + } + return svg; +} + +export function matches(item: TemplateItem, category: string | null, query: string): boolean { + if (category && item.category !== category) return false; + if (!query) return true; + const hay = `${item.name} ${item.tags.join(' ')} ${item.category}`.toLowerCase(); + return query.split(/\s+/).every((w) => hay.includes(w)); +} + +function shift(o: DocObject, dx: number, dy: number): DocObject { + const r = { ...(o as unknown as Record) }; + const move = (k: string, d: number): void => { if (typeof r[k] === 'number') r[k] = +((r[k] as number) + d).toFixed(3); }; + if (isFragment(o)) { + r.atoms = Object.fromEntries(Object.entries(o.atoms).map(([id, a]) => [id, { ...a, x: +(a.x + dx).toFixed(3), y: +(a.y + dy).toFixed(3) }])); + } else if (Array.isArray(r.points)) { + r.points = (r.points as Point[]).map((p) => [+(p[0] + dx).toFixed(3), +(p[1] + dy).toFixed(3)]); + } else { + move('x', dx); move('y', dy); move('x1', dx); move('y1', dy); move('x2', dx); move('y2', dy); + } + return r as unknown as DocObject; +} + +export function placeTemplateOps(client: EngineDocumentClient, found: TemplateInsert, spot: { page: Id; at: Point } | null): { ops: Op[]; fragments: Fragment[] } | null { + const page = client.doc.pages.find((p) => p.id === spot?.page) ?? client.doc.pages[0]; + if (!page) return null; + const size = page.size === 'auto' ? { w: 612, h: 792 } : page.size; + const centre: Point = spot && spot.page === page.id ? spot.at : [size.w / 2, size.h / 2]; + const b = thumbBounds(found.objects) ?? found.bounds; + const dx = centre[0] - (b.x + b.w / 2), dy = centre[1] - (b.y + b.h / 2); + const moved = found.objects.map((o) => shift(o, dx, dy)); + const ops: Op[] = moved.map((o) => ({ op: 'set', path: ['objects', o.id], value: o })); + for (const id of found.order) ops.push({ op: 'ins', path: ['pages', { id: page.id }, 'order'], value: id }); + return { ops, fragments: moved.filter(isFragment) }; +} + +export async function insertTemplate(id: string, hooks: TemplateHooks = {}, fromAgent = false): Promise { + const refuse = (text: string): undefined => { + toast(text, 'error'); + if (fromAgent) throw new Error(text); + return undefined; + }; + const had = session.active; + let found: TemplateInsert; + try { + const length = had ? resolveStyle(had.doc).bond_length : undefined; + found = await get(`${ITEM_URL(id)}${length ? `?bond_length=${length}` : ''}`); + } catch (e) { + return refuse(`${t('Could not load the template')}: ${e instanceof Error ? e.message : String(e)}`); + } + if (!Array.isArray(found.objects) || !found.objects.length || !Array.isArray(found.order)) return refuse(t('The template is empty.')); + let created = ''; + const c = session.active ?? await session.create(hooks.createOptions?.() ?? {}).catch((e: unknown) => { created = e instanceof Error ? e.message : String(e); return null; }); + if (!c) return refuse(`${t('Could not create a drawing')}: ${created}`); + if (!had) { + const length = resolveStyle(c.doc).bond_length; + if (Math.abs(length - 14.4) > 1e-6) { + try { found = await get(`${ITEM_URL(id)}?bond_length=${length}`); } catch { void 0; } + } + } + const placed = placeTemplateOps(c, found, hooks.placement?.(c) ?? null); + if (!placed) return refuse(t('The drawing has no page to insert into.')); + let errors: string[] = []; + const off = c.on((e) => { if (e.type === 'rejected') errors = e.errors; }); + const tx = c.commit(`${t('Insert Template')}: ${found.name}`, placed.ops); + off(); + if (!tx) return refuse(`${t('Could not insert the template')}: ${errors[0] ?? ''}`); + hooks.inserted?.(c, placed.fragments); + return `Inserted template ${found.name} (${found.order.join(', ')}) into "${c.title || 'Untitled'}" (${c.id}) as one undo step`; +} + +export function templateCard(item: TemplateItem): HTMLElement { + const n = el(``); + setText(q(n, '.fc-tl-name'), item.name); + setAttr(n, 'title', item.tags.length ? `${item.name} (${item.tags.join(', ')})` : item.name); + return n; +} + +export function fillThumb(card: HTMLElement, item: TemplateItem): void { + const box = q(card, '.fc-tl-thumb'); + const svg = thumbFor(item); + setHtml(box, svg || icon('template', 24), svg ? `t:${item.id}` : 'blank'); + setClass(box, 'is-blank', !svg); +} + +export function lazyThumbs(root: HTMLElement, items: Map): IntersectionObserver { + const io = new IntersectionObserver((entries) => { + for (const e of entries) { + if (!e.isIntersecting) continue; + const card = e.target as HTMLElement; + const item = items.get(card.dataset.tlId ?? ''); + if (item) fillThumb(card, item); + io.unobserve(card); + } + }, { root, rootMargin: '160px 0px' }); + return io; +} + +class TemplateDialog extends Dialog { + private readonly search = el(``); + private readonly chips = el('
'); + private readonly grid = el('
'); + private readonly status = el('

'); + private readonly items = new Map(); + private category: string | null = null; + private query = ''; + private built = false; + private busy = false; + private observer: IntersectionObserver | null = null; + hooks: TemplateHooks = {}; + + constructor() { + super(t('Insert Template'), 820); + setClass(this.frame, 'fc-tl-dialog', true); + const bar = el(`
`); + setAttr(this.search, 'placeholder', t('Search templates')); + setAttr(this.search, 'aria-label', t('Search templates')); + q(bar, '.fc-search').appendChild(this.search); + setAttr(this.chips, 'aria-label', t('Template categories')); + bar.appendChild(this.chips); + const scroll = el('
'); + scroll.append(this.grid, this.status); + this.body.append(bar, scroll); + setText(this.status, t('Loading templates...')); + this.search.addEventListener('input', () => { this.query = this.search.value.trim().toLowerCase(); this.filter(); }); + this.search.addEventListener('keydown', (e) => { + if (e.key !== 'Enter' || e.isComposing) return; + const first = qa(this.grid, '.fc-tl-card:not([hidden])')[0]; + if (first) { e.preventDefault(); first.click(); } + }); + this.chips.addEventListener('click', (e) => { + const chip = (e.target as HTMLElement).closest('[data-tl-cat]'); + if (!chip) return; + const cat = chip.dataset.tlCat || null; + this.category = cat === this.category ? null : cat; + this.filter(); + }); + this.grid.addEventListener('click', (e) => { + const card = (e.target as HTMLElement).closest('[data-tl-id]'); + if (card?.dataset.tlId) void this.pick(card.dataset.tlId); + }); + this.observer = lazyThumbs(scroll, this.items); + } + + show(hooks: TemplateHooks): void { + this.hooks = hooks; + this.open(this.search); + this.search.select(); + if (!this.built) void this.load(); + } + + private async load(): Promise { + try { + const lib = await loadTemplates(); + this.build(lib); + } catch (e) { + setText(this.status, `${t('Could not load the templates')}: ${e instanceof Error ? e.message : String(e)}`); + } + } + + private build(lib: TemplateLibrary): void { + this.built = true; + const all = ``; + setHtml(this.chips, all + lib.categories.map((c) => ``).join(''), 'cats'); + const frag = document.createDocumentFragment(); + for (const item of lib.templates) { + if (item.error) continue; + this.items.set(item.id, item); + const card = templateCard(item); + frag.appendChild(card); + this.observer?.observe(card); + } + this.grid.appendChild(frag); + this.filter(); + } + + private filter(): void { + for (const chip of qa(this.chips, '[data-tl-cat]')) setAttr(chip, 'aria-pressed', (chip.dataset.tlCat || null) === this.category ? 'true' : 'false'); + let shown = 0; + for (const card of qa(this.grid, '.fc-tl-card')) { + const item = this.items.get(card.dataset.tlId ?? ''); + const on = !!item && matches(item, this.category, this.query); + setHidden(card, !on); + if (on) shown++; + } + if (this.built) setText(this.status, shown ? '' : t('No templates match this search.')); + setHidden(this.status, this.built && shown > 0); + } + + private async pick(id: string): Promise { + if (this.busy) return; + this.busy = true; + setClass(this.grid, 'is-busy', true); + try { + const done = await insertTemplate(id, this.hooks); + if (done) this.close(); + } finally { + this.busy = false; + setClass(this.grid, 'is-busy', false); + } + } +} + +let dialog: TemplateDialog | null = null; + +export function templateDialog(hooks: TemplateHooks = {}): void { + dialog ??= new TemplateDialog(); + dialog.show(hooks); +} From 15971afe94f4cfa62ea9b63e70da172e6a74479a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:17:27 -0500 Subject: [PATCH 075/279] feat(home): add a Templates section builder for Home (0.5.0) Home gets the same template library as the dialog: category chips, search and keyed cards that are built once and filtered in place, with an optional limit and a See all button for the Start page. --- frontend/src/ui/home-templates.ts | 118 ++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 frontend/src/ui/home-templates.ts diff --git a/frontend/src/ui/home-templates.ts b/frontend/src/ui/home-templates.ts new file mode 100644 index 00000000..e482c5d8 --- /dev/null +++ b/frontend/src/ui/home-templates.ts @@ -0,0 +1,118 @@ +import { t } from '../i18n'; +import { el, escapeHtml, q, qa, setAttr, setHidden, setHtml, setText } from './dom'; +import { icon } from './icons'; +import { fillThumb, loadTemplates, matches, templateCard, type TemplateItem, type TemplateLibrary } from './template-dialog'; + +export interface HomeTemplatesOptions { + insert(id: string): void; + limit?: number; + title?: boolean; +} + +export interface HomeTemplates { + readonly root: HTMLElement; + refresh(force?: boolean): Promise; + setCategory(id: string | null): void; +} + +const x = (s: string): string => escapeHtml(t(s)); + +function markup(opts: HomeTemplatesOptions): string { + const head = opts.title === false ? '' : `

${x('Templates')}

`; + const more = opts.limit ? `` : ''; + return `
+
${head}
+${more}
+

${x('Loading templates...')}

+
`; +} + +export function homeTemplatesSection(host: HTMLElement, opts: HomeTemplatesOptions): HomeTemplates { + const root = el(markup(opts)); + host.appendChild(root); + const chips = q(root, '.fc-home-filters'); + const grid = q(root, '.fc-tl-grid'); + const empty = q(root, '.fc-home-tl-empty'); + const input = q(root, '.fc-home-tl-input'); + const items = new Map(); + let category: string | null = null; + let query = ''; + let loaded = false; + + const io = new IntersectionObserver((entries) => { + for (const e of entries) { + if (!e.isIntersecting) continue; + const card = e.target as HTMLElement; + const item = items.get(card.dataset.tlId ?? ''); + if (item) fillThumb(card, item); + io.unobserve(card); + } + }, { rootMargin: '200px 0px' }); + + const filter = (): void => { + for (const chip of qa(chips, '[data-tl-cat]')) setAttr(chip, 'aria-pressed', (chip.dataset.tlCat || null) === category ? 'true' : 'false'); + let shown = 0; + for (const card of qa(grid, '.fc-tl-card')) { + const item = items.get(card.dataset.tlId ?? ''); + const on = !!item && matches(item, category, query) && (!opts.limit || shown < opts.limit); + setHidden(card, !on); + if (on) shown++; + } + if (loaded) setText(empty, t('No templates match this filter.')); + setHidden(empty, loaded && shown > 0); + }; + + const build = (lib: TemplateLibrary): void => { + const key = lib.templates.map((i) => i.id).join('|'); + setHtml(chips, lib.categories.map((c) => ``).join(''), `c:${lib.categories.map((c) => c.id).join('|')}`); + if (grid.dataset.key !== key) { + grid.dataset.key = key; + const have = new Map(qa(grid, '.fc-tl-card').map((n) => [n.dataset.tlId ?? '', n])); + items.clear(); + let cursor: Element | null = grid.firstElementChild; + for (const item of lib.templates) { + if (item.error) continue; + items.set(item.id, item); + let card = have.get(item.id); + have.delete(item.id); + if (!card) { card = templateCard(item); io.observe(card); } + if (card !== cursor) grid.insertBefore(card, cursor); else cursor = cursor.nextElementSibling; + } + for (const stale of have.values()) { io.unobserve(stale); stale.remove(); } + } + loaded = true; + filter(); + }; + + const refresh = async (force = false): Promise => { + try { + build(await loadTemplates(force)); + } catch (e) { + setText(empty, `${t('Could not load the templates')}: ${e instanceof Error ? e.message : String(e)}`); + setHidden(empty, false); + } + }; + + chips.addEventListener('click', (e) => { + const chip = (e.target as HTMLElement).closest('[data-tl-cat]'); + if (!chip) return; + e.stopPropagation(); + const cat = chip.dataset.tlCat || null; + category = cat === category ? null : cat; + filter(); + }); + input.addEventListener('input', () => { query = input.value.trim().toLowerCase(); filter(); }); + grid.addEventListener('click', (e) => { + const card = (e.target as HTMLElement).closest('[data-tl-id]'); + if (!card?.dataset.tlId) return; + e.stopPropagation(); + opts.insert(card.dataset.tlId); + }); + + void refresh(); + return { + root, + refresh, + setCategory(id) { category = id; filter(); }, + }; +} From f10ad7c38c5109a00ae2e7a2e6e57eb726627809 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:17:27 -0500 Subject: [PATCH 076/279] style(templates): style the template dialog, cards and Home section (0.5.0) Cards reserve their thumbnail box before the SVG arrives, thumbnails sit on a white page tile with non-scaling strokes, and the dialog scrolls inside a fixed-height area so filtering never resizes it. --- frontend/index.html | 1 + frontend/src/styles/templates.css | 36 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 frontend/src/styles/templates.css diff --git a/frontend/index.html b/frontend/index.html index 29e67499..6e2e8a18 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -98,6 +98,7 @@ + diff --git a/frontend/src/styles/templates.css b/frontend/src/styles/templates.css new file mode 100644 index 00000000..3b365e72 --- /dev/null +++ b/frontend/src/styles/templates.css @@ -0,0 +1,36 @@ +.fc-th { display: block; width: 100%; height: 100%; overflow: visible; color: inherit; } +.fc-th * { vector-effect: non-scaling-stroke; stroke-width: 1.15px; } +.fc-th .is-bold { stroke-width: 3px; } +.fc-th .is-fill { fill: currentColor; stroke: none; } +.fc-th text { fill: currentColor; stroke: none; font-weight: 400; } +.fc-th tspan { fill: currentColor; } + +.fc-tl-dialog .fc-dialog-body { grid-template-rows: auto minmax(0, 1fr); overflow: hidden; padding-bottom: 0; } +.fc-tl-bar { display: grid; gap: var(--space-2); } +.fc-tl-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.fc-tl-chip { display: inline-flex; align-items: center; gap: 6px; flex: none; height: var(--ctl-sm); padding: 0 10px; border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: transparent; color: var(--text-secondary); font: inherit; font-size: var(--fc-12); white-space: nowrap; cursor: pointer; } +.fc-tl-chip:hover { border-color: var(--line-3); color: var(--text-primary); } +.fc-tl-chip[aria-pressed="true"] { border-color: color-mix(in srgb, var(--accent-color) 60%, var(--line-2)); background: var(--surface-raised); color: var(--text-primary); } +.fc-tl-count { color: var(--text-muted); font-size: var(--fc-11); font-variant-numeric: tabular-nums; } +.fc-tl-scroll { position: relative; height: min(480px, calc(100vh - 260px)); min-height: 200px; margin: 0 calc(-1 * var(--space-4)); padding: 2px var(--space-4) var(--space-4); overflow-y: auto; overscroll-behavior: contain; } +.fc-tl-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr)); gap: var(--space-2); } +.fc-tl-grid.is-busy { cursor: progress; } +.fc-tl-grid.is-busy .fc-tl-card { pointer-events: none; } +.fc-tl-card { display: grid; grid-template-rows: 84px auto; gap: 6px; min-width: 0; padding: 8px 8px 7px; border: 1px solid var(--line-1); border-radius: var(--radius-md); background: var(--surface-1); color: var(--text-primary); font: inherit; text-align: center; cursor: pointer; transition: border-color var(--transition-fast), background-color var(--transition-fast); } +.fc-tl-card[hidden] { display: none; } +.fc-tl-card:hover { border-color: var(--accent-line); background: var(--surface-raised); } +.fc-tl-card:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-tl-thumb { display: block; box-sizing: border-box; min-width: 0; height: 84px; padding: 4px; overflow: hidden; border-radius: var(--radius); background: #ffffff; color: #111111; } +.fc-tl-thumb.is-blank { display: grid; place-items: center; background: var(--surface-2); color: var(--text-muted); } +.fc-tl-name { min-width: 0; overflow: hidden; color: var(--text-secondary); font-size: var(--fc-11); line-height: 1.3; text-overflow: ellipsis; white-space: nowrap; } +.fc-tl-card:hover .fc-tl-name { color: var(--text-primary); } +.fc-tl-status { margin: var(--space-4) 0 0; color: var(--text-muted); font-size: var(--fc-12); text-align: center; } +.fc-tl-status[hidden] { display: none; } + +.fc-home-tl { display: grid; gap: var(--space-3); min-width: 0; } +.fc-home-tl-block .fc-home-block-head > .fc-btn-ghost { margin-left: 0; } +.fc-home-tl .fc-tl-grid { grid-template-columns: repeat(auto-fill, minmax(124px, 1fr)); min-height: 120px; } +.fc-home-tl .fc-tl-card { grid-template-rows: 92px auto; } +.fc-home-tl .fc-tl-thumb { height: 92px; } +.fc-home-tl-empty { margin: 0; color: var(--text-muted); font-size: var(--fc-12); } +.fc-home-tl-empty[hidden] { display: none; } From 64733e72e1e2821ae18875fbae7e767991124450 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:17:27 -0500 Subject: [PATCH 077/279] fix(templates): draw the cyclohexane chairs as a true chair projection (0.5.0) The first chair coordinates read as a skewed hexagon; the new ones are a projection of an ideal chair with three pairs of parallel bonds, the footrest down and the headrest up, plus its mirror. --- backend/app/data/templates/rings.json | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/backend/app/data/templates/rings.json b/backend/app/data/templates/rings.json index f22964e2..b33ef570 100644 --- a/backend/app/data/templates/rings.json +++ b/backend/app/data/templates/rings.json @@ -21,12 +21,12 @@ "objects": [ { "id": "f1", "kind": "fragment", "atoms": { - "a1": { "id": "a1", "element": "C", "x": 0, "y": 15 }, - "a2": { "id": "a2", "element": "C", "x": 14, "y": 21 }, - "a3": { "id": "a3", "element": "C", "x": 31, "y": 16 }, - "a4": { "id": "a4", "element": "C", "x": 45, "y": 6 }, - "a5": { "id": "a5", "element": "C", "x": 31, "y": 0 }, - "a6": { "id": "a6", "element": "C", "x": 14, "y": 5 } }, + "a1": { "id": "a1", "element": "C", "x": 0, "y": 16.4 }, + "a2": { "id": "a2", "element": "C", "x": 10.8, "y": 9 }, + "a3": { "id": "a3", "element": "C", "x": 32.4, "y": 20.9 }, + "a4": { "id": "a4", "element": "C", "x": 43.2, "y": 4.4 }, + "a5": { "id": "a5", "element": "C", "x": 32.4, "y": 11.9 }, + "a6": { "id": "a6", "element": "C", "x": 10.8, "y": 0 } }, "bonds": { "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1 }, "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1 }, @@ -41,12 +41,12 @@ "objects": [ { "id": "f1", "kind": "fragment", "atoms": { - "a1": { "id": "a1", "element": "C", "x": 45, "y": 15 }, - "a2": { "id": "a2", "element": "C", "x": 31, "y": 21 }, - "a3": { "id": "a3", "element": "C", "x": 14, "y": 16 }, - "a4": { "id": "a4", "element": "C", "x": 0, "y": 6 }, - "a5": { "id": "a5", "element": "C", "x": 14, "y": 0 }, - "a6": { "id": "a6", "element": "C", "x": 31, "y": 5 } }, + "a1": { "id": "a1", "element": "C", "x": 43.2, "y": 16.4 }, + "a2": { "id": "a2", "element": "C", "x": 32.4, "y": 9 }, + "a3": { "id": "a3", "element": "C", "x": 10.8, "y": 20.9 }, + "a4": { "id": "a4", "element": "C", "x": 0, "y": 4.4 }, + "a5": { "id": "a5", "element": "C", "x": 10.8, "y": 11.9 }, + "a6": { "id": "a6", "element": "C", "x": 32.4, "y": 0 } }, "bonds": { "b1": { "id": "b1", "a": "a1", "b": "a2", "order": 1 }, "b2": { "id": "b2", "a": "a2", "b": "a3", "order": 1 }, From 6dee179355b4b1b504eac1364325dfc0a5110a8d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:18:16 -0500 Subject: [PATCH 078/279] docs(templates): document the template library format and API (0.5.0) Templates can come from SMILES, a ring spec or document-format objects, and people can drop their own files in the data folder, so the three sources, the folders and the endpoints are written down where contributors will look. --- docs/TEMPLATES.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/TEMPLATES.md diff --git a/docs/TEMPLATES.md b/docs/TEMPLATES.md new file mode 100644 index 00000000..0d4195e3 --- /dev/null +++ b/docs/TEMPLATES.md @@ -0,0 +1,49 @@ +# FormChem templates + +The template library behind Insert > Template and the Templates section on Home. Every built-in template is original data written for FormChem: structures are SMILES, ring specs or hand-placed fragments, and the glassware is a vector set drawn from scratch. Nothing is copied from another product's library or clip art. + +## Where templates live + +| Folder | Origin | Ids | +| --- | --- | --- | +| `backend/app/data/templates/*.json` | built in, shipped with the engine | the id in the file | +| `~/formchem/templates/*.json` (`FORMCHEM_DATA_DIR/templates`) | the person's own library | `user-` plus the id in the file | + +The engine reads both folders on the first request and again whenever a file in them changes (by modification time and size). A file that does not parse is skipped, and so is a template without a valid id and exactly one usable source; a template whose source cannot be built (a SMILES RDKit refuses) is listed with an `error` and cannot be inserted. + +## File format + +One JSON file per category: + +```json +{ "category": "rings", "name": "Rings", "order": 10, + "templates": [ + { "id": "benzene", "name": "Benzene", "tags": ["arene", "aromatic"], "ring": { "elements": ["C", "C", "C", "C", "C", "C"], "orders": [2, 1, 2, 1, 2, 1] } }, + { "id": "naphthalene", "name": "Naphthalene", "tags": ["fused"], "smiles": "c1ccc2ccccc2c1" }, + { "id": "chair", "name": "Cyclohexane chair", "objects": [ { "id": "f1", "kind": "fragment", "atoms": {}, "bonds": {} } ] } + ] } +``` + +| Field | Meaning | +| --- | --- | +| `category` | category id (lower case letters, digits, `-`, `_`); files with the same id share one category | +| `name` | category name shown on the chips | +| `order` | sort key for categories, lower first (default 1000) | +| `templates[].id` | template id, unique across the library (same characters as `category`) | +| `templates[].name`, `tags` | shown on the card and searched by the search box | + +Each template gives exactly one source: + +- `smiles`: laid out once by the engine's RDKit depiction at the default bond length (14.4 pt), with wedges for stereocentres. Several dot-separated components become one fragment, as when pasting SMILES. Use this for anything whose drawing RDKit lays out well (fused and bridged rings, amino acids, reagents). +- `ring`: a regular ring of 3 to 12 atoms generated with a flat bottom edge, the orientation of the ring tools. `elements[k]` is atom k counting anticlockwise from the bottom-left atom, and `orders[k]` the bond from atom k to atom k + 1 (1, 2, 3 or 1.5). +- `objects`: objects in the document format of docs/FORMAT.md (fragments, shapes, lines, text and groups), with any short ids. Use this for drawings that depend on their exact geometry: Haworth and Fischer projections, chairs and cages in perspective, glassware. Coordinates are points; the template is moved as a whole, so its origin does not matter. An optional `order` lists the top-level objects; without it every object that is not a group member is top level. + +## API + +| Request | Answer | +| --- | --- | +| `GET /api/templates` | `{ categories: [{ id, name, count, origin }], templates: [{ id, name, category, tags, origin }], count }` | +| `GET /api/templates?objects=1` | the same, each template also carrying `objects`, `order` and `bounds` with the file's own ids, for thumbnails | +| `GET /api/templates/{id}?bond_length=14.4` | `{ id, name, category, tags, origin, objects, order, bounds }` with fresh document ids on every call, fragment coordinates scaled from 14.4 pt to `bond_length` | + +The window inserts the answer as one transaction: a `set` for every object and an `ins` into the page `order` for every top-level id, all moved so the template's bounds are centred in the view. From 8c54fa27aa915944d73142be63f34a582b33a1c2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:19:06 -0500 Subject: [PATCH 079/279] fix(stoich): follow the engine's reference rule and stoich route (0.5.0) The engine treats a typed scale as the reference ahead of the limiting reagent's own amount and serves the grid under /api/documents, so the window computes the same reference, clears the scale in the same transaction when the person types an amount on the limiting row, and asks the right route for molecular weights. --- frontend/src/chem/stoich.ts | 5 +++-- frontend/src/ui/stoich-panel.ts | 7 +++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/frontend/src/chem/stoich.ts b/frontend/src/chem/stoich.ts index 3c27c5c9..64d3e5ce 100644 --- a/frontend/src/chem/stoich.ts +++ b/frontend/src/chem/stoich.ts @@ -178,8 +178,9 @@ export function computeStoich( lim = measured.sort((a, b) => (a.mmol as number) / a.coef - (b.mmol as number) / b.coef)[0] ?? reactants[0]; } const scale = pos(data.scale_mmol); - if (lim && lim.mmol === null && scale !== null) { lim.mmol = scale; lim.source = 'scale'; } - const ref = lim?.mmol ?? null; + const limEquiv = lim ? pos(lim.typed.equiv) : null; + const ref = scale ?? (lim && lim.mmol !== null ? lim.mmol / (limEquiv ?? 1) : null); + if (lim && scale !== null) { lim.mmol = scale * (limEquiv ?? 1); lim.source = 'scale'; } if (lim) lim.limiting = true; for (const r of inputs) { diff --git a/frontend/src/ui/stoich-panel.ts b/frontend/src/ui/stoich-panel.ts index 7730c7bb..f508b6e3 100644 --- a/frontend/src/ui/stoich-panel.ts +++ b/frontend/src/ui/stoich-panel.ts @@ -317,7 +317,10 @@ function commitCell(input: HTMLInputElement): void { if (parsed === undefined || (key === 'purity_pct' && parsed !== null && (parsed <= 0 || parsed > 100))) { input.value = typedOf(row, key); return; } value = parsed === 0 && key !== 'equiv' ? null : parsed; } - commit(componentEdit(source.doc, view.entry.ref, comp, key, value), t('Edit Stoichiometry')); + const ops = componentEdit(source.doc, view.entry.ref, comp, key, value); + const scaleSet = view.entry.step.stoich?.scale_mmol !== undefined; + if (ops.length && row.limiting && scaleSet && value !== null && (key === 'mass_mg' || key === 'volume_ml')) ops.push(...stepEdit(source.doc, view.entry.ref, 'scale_mmol', null)); + commit(ops, t('Edit Stoichiometry')); } function commitStep(control: HTMLInputElement | HTMLSelectElement): void { @@ -386,7 +389,7 @@ export function insertStoichTable(): Id | null { } function engineUrl(docId: Id, ref: StepRef): string { - return `/api/docs/${encodeURIComponent(docId)}/reactions/${encodeURIComponent(ref.reaction)}/steps/${encodeURIComponent(ref.step)}/stoich`; + return `/api/documents/${encodeURIComponent(docId)}/reactions/${encodeURIComponent(ref.reaction)}/steps/${encodeURIComponent(ref.step)}/stoich`; } function engineWeights(raw: unknown): Record { From abb1fef25ee1795bb9d8a8f1a6c25cd790ebf434 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:22:21 -0500 Subject: [PATCH 080/279] feat(engine): serve the reaction and template routes (0.5.0) The reactions and templates routers from phase 5 were written but never included, so the window got 404 for perception, mapping, stoichiometry and the template library. --- backend/app/main.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/app/main.py b/backend/app/main.py index 9b514653..bf596053 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -13,7 +13,7 @@ from app.core import config from app.core.local_guard import LocalGuard from app.core.window_key import WindowKeyGuard -from app.routers import chat, chem, commands, documents, extensions, library, live, mcp, system, terminal +from app.routers import chat, chem, commands, documents, extensions, library, live, mcp, reactions, system, templates, terminal from app.services import claude_code, consent, history from app.services import terminal as terminals from app.services.chat import engine as chat_engine @@ -63,6 +63,8 @@ async def lifespan(this: FastAPI): app.include_router(library.router) app.include_router(documents.router) app.include_router(chem.router) +app.include_router(reactions.router) +app.include_router(templates.router) app.include_router(commands.router) app.include_router(extensions.router) app.include_router(terminal.router) From 147bece0509954cffa80f24fc5a5116b27c7d398 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:22:21 -0500 Subject: [PATCH 081/279] build(setup): bundle the template library into the frozen engine (0.5.0) templates.builtin_dir() reads the resource dir when frozen, so the sidecar must carry backend/app/data/templates or the library is empty in the desktop app. --- setup/freeze_backend | 1 + setup/freeze_backend.bat | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/setup/freeze_backend b/setup/freeze_backend index 5a1113d2..dbb60c56 100755 --- a/setup/freeze_backend +++ b/setup/freeze_backend @@ -18,6 +18,7 @@ pyinstaller --noconfirm --clean --onefile --name formchem-engine \ --distpath dist-engine --workpath build/pyinstaller --specpath build/pyinstaller \ --add-data "$FORMCHEM_ROOT/frontend/dist${sep}frontend_dist" \ --add-data "$FORMCHEM_ROOT/THIRD-PARTY-NOTICES.txt${sep}." \ + --add-data "$FORMCHEM_ROOT/backend/app/data/templates${sep}templates" \ --collect-submodules app --collect-submodules uvicorn \ --collect-all rdkit --collect-all indigo \ ${extra[@]+"${extra[@]}"} \ diff --git a/setup/freeze_backend.bat b/setup/freeze_backend.bat index 399bac5a..156ab61e 100644 --- a/setup/freeze_backend.bat +++ b/setup/freeze_backend.bat @@ -17,7 +17,7 @@ if "%FORMCHEM_ENGINE_WINDOWED%"=="0" set "WINDOWED=" cd backend if exist build\pyinstaller rmdir /s /q build\pyinstaller if exist dist-engine rmdir /s /q dist-engine -pyinstaller --noconfirm --clean --onefile %WINDOWED% --name formchem-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\THIRD-PARTY-NOTICES.txt;." --collect-submodules app --collect-submodules uvicorn --collect-all rdkit --collect-all indigo %FONTS% "%ROOT%\backend\formchem_engine.py" || exit /b 1 +pyinstaller --noconfirm --clean --onefile %WINDOWED% --name formchem-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\THIRD-PARTY-NOTICES.txt;." --add-data "%ROOT%\backend\app\data\templates;templates" --collect-submodules app --collect-submodules uvicorn --collect-all rdkit --collect-all indigo %FONTS% "%ROOT%\backend\formchem_engine.py" || exit /b 1 if not exist "%ROOT%\src-tauri\binaries" mkdir "%ROOT%\src-tauri\binaries" copy /y dist-engine\formchem-engine.exe "%ROOT%\src-tauri\binaries\formchem-engine-%TRIPLE%.exe" >nul || exit /b 1 "%ROOT%\src-tauri\binaries\formchem-engine-%TRIPLE%.exe" --selfcheck || exit /b 1 From c3a0db679c781c4aaeb46a01ea15c3f39dbff576 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:23:26 -0500 Subject: [PATCH 082/279] feat(engine): upload and serve a drawing's media files (0.5.0) The image tool and the renderer both need the engine to hold picture bytes: POST stores sniffed PNG, JPEG, GIF, WebP or SVG bytes in the session (the window's transaction lists them in doc.media, so the package writer saves them) and GET serves them with their mime type. --- backend/app/routers/documents.py | 29 ++++++++++++++++- backend/app/services/package.py | 53 ++++++++++++++++++++++++++++++++ backend/app/services/store.py | 27 ++++++++++++++++ 3 files changed, 108 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/documents.py b/backend/app/routers/documents.py index 1b30a4ec..e8f0d444 100644 --- a/backend/app/routers/documents.py +++ b/backend/app/routers/documents.py @@ -1,7 +1,7 @@ import asyncio from pathlib import Path -from fastapi import APIRouter, Body, Depends, HTTPException, Request +from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response from starlette.datastructures import UploadFile as StarletteUpload from app.core import config, files, window_key @@ -165,6 +165,33 @@ async def close(doc_id: str) -> dict: return await STORE.close(doc_id) +@router.post("/api/documents/{doc_id}/media", dependencies=GUARD) +async def upload_media(doc_id: str, request: Request) -> dict: + _session(doc_id) + form = await request.form() + found = [v for v in form.getlist("file") if isinstance(v, StarletteUpload)] + if not found: + raise HTTPException(400, "Send the picture as a multipart field named file.") + data = await found[0].read(UPLOAD_LIMIT + 1) + if len(data) > UPLOAD_LIMIT: + raise HTTPException(413, f"The picture is larger than {UPLOAD_LIMIT // (1024 * 1024)} MB.") + try: + return STORE.add_media(doc_id, data, Path(found[0].filename or "").name) + except StoreError as exc: + raise HTTPException(415, str(exc)) + + +@router.get("/api/documents/{doc_id}/media/{media_id}") +def get_media(doc_id: str, media_id: str) -> Response: + _session(doc_id) + try: + data, mime = STORE.media_bytes(doc_id, media_id) + except StoreError as exc: + raise HTTPException(404, str(exc)) + return Response(data, media_type=mime, headers={"cache-control": "private, max-age=31536000, immutable", "x-content-type-options": "nosniff", + "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'"}) + + @router.get("/api/documents/{doc_id}/versions") def versions(doc_id: str) -> dict: _session(doc_id) diff --git a/backend/app/services/package.py b/backend/app/services/package.py index b04d3a01..109d793c 100644 --- a/backend/app/services/package.py +++ b/backend/app/services/package.py @@ -36,6 +36,59 @@ def media_ext(mime: str | None) -> str: return EXT_BY_MIME.get(mime) or mimetypes.guess_extension(mime) or ".bin" +def _jpeg_size(data: bytes) -> tuple[int, int] | None: + i = 2 + while i + 9 < len(data): + if data[i] != 0xFF: + i += 1 + continue + marker = data[i + 1] + if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7 or marker == 0xFF: + i += 1 if marker == 0xFF else 2 + continue + length = int.from_bytes(data[i + 2:i + 4], "big") + if marker in (0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF): + return int.from_bytes(data[i + 7:i + 9], "big"), int.from_bytes(data[i + 5:i + 7], "big") + i += 2 + length + return None + + +def _webp_size(data: bytes) -> tuple[int, int] | None: + chunk = data[12:16] + if chunk == b"VP8 " and len(data) >= 30: + return int.from_bytes(data[26:28], "little") & 0x3FFF, int.from_bytes(data[28:30], "little") & 0x3FFF + if chunk == b"VP8L" and len(data) >= 25: + bits = int.from_bytes(data[21:25], "little") + return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1 + if chunk == b"VP8X" and len(data) >= 30: + return int.from_bytes(data[24:27], "little") + 1, int.from_bytes(data[27:30], "little") + 1 + return None + + +def _is_svg(head: bytes) -> bool: + return head.startswith((b" dict | None: + size: tuple[int, int] | None = None + if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24: + mime, size = "image/png", (int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big")) + elif data.startswith(b"\xff\xd8\xff"): + mime, size = "image/jpeg", _jpeg_size(data) + elif data[:6] in (b"GIF87a", b"GIF89a") and len(data) >= 10: + mime, size = "image/gif", (int.from_bytes(data[6:8], "little"), int.from_bytes(data[8:10], "little")) + elif data.startswith(b"RIFF") and data[8:12] == b"WEBP": + mime, size = "image/webp", _webp_size(data) + elif _is_svg(data[:4096].lstrip(b"\xef\xbb\xbf \t\r\n").lower()): + mime = "image/svg+xml" + else: + return None + out: dict = {"mime": mime} + if size and size[0] > 0 and size[1] > 0: + out["w"], out["h"] = size + return out + + def clean(doc: dict) -> dict: out = copy.deepcopy(doc) out.pop("derived", None) diff --git a/backend/app/services/store.py b/backend/app/services/store.py index c237be8f..99591ff5 100644 --- a/backend/app/services/store.py +++ b/backend/app/services/store.py @@ -1,5 +1,6 @@ import asyncio import copy +import hashlib import logging import threading import time @@ -141,6 +142,32 @@ def snapshot(self, doc_id: str) -> dict: out["derived"] = copy.deepcopy(s.derived) return out + def add_media(self, doc_id: str, data: bytes, name: str) -> dict: + s = self.get(doc_id) + found = package.sniff_image(data) + if found is None: + raise StoreError("FormChem places PNG, JPEG, GIF, WebP and SVG pictures.") + media = {"name": files.safe_name(name, "Image"), "mime": found["mime"], "bytes": len(data), + **({"w": found["w"], "h": found["h"]} if "w" in found else {}), "sha256": hashlib.sha256(data).hexdigest()} + with s.lock: + listed = s.doc.get("media") if isinstance(s.doc.get("media"), dict) else {} + mid = model.new_id("m") + while mid in s.media or mid in listed: + mid = model.new_id("m") + s.media[mid] = data + return {"id": mid, "media": media} + + def media_bytes(self, doc_id: str, media_id: str) -> tuple[bytes, str]: + s = self.get(doc_id) + with s.lock: + data = s.media.get(media_id) + listed = s.doc.get("media") if isinstance(s.doc.get("media"), dict) else {} + entry = listed.get(media_id) if isinstance(listed.get(media_id), dict) else {} + if data is None: + raise StoreError(f"The drawing has no media file {media_id}.") + mime = entry.get("mime") if isinstance(entry.get("mime"), str) else None + return data, mime or (package.sniff_image(data) or {}).get("mime") or "application/octet-stream" + def find_path(self, path: Path) -> Session | None: for s in self.sessions.values(): if s.path is not None and s.path == path: From ff72817a0ed62839737efbcc43f873831a3c0a12 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:24:55 -0500 Subject: [PATCH 083/279] feat(window): mount the stoichiometry panel and the template library (0.5.0) The panel follows the active drawing and the canvas selection, View gets its toggle, and Insert Template and the stoichiometry grid replace their placeholders with the real commands. --- frontend/src/app.ts | 12 ++++++++++++ frontend/src/app/canvas.ts | 2 ++ frontend/src/app/commands-shell.ts | 9 +++++++-- frontend/src/app/documents.ts | 2 ++ frontend/src/app/menus.ts | 2 +- 5 files changed, 24 insertions(+), 3 deletions(-) diff --git a/frontend/src/app.ts b/frontend/src/app.ts index e73ba6e4..a6e8dc9f 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -25,6 +25,8 @@ import { MenuBar } from './ui/menu'; import { menusInWindow, NativeMenus, setMenusInWindow, wantsNativeMenus } from './ui/native-menu'; import { preferencesDialog } from './ui/prefs'; import { mountStatus } from './ui/status'; +import { insertStoichTable, isStoichOpen, mountStoichPanel, toggleStoich } from './ui/stoich-panel'; +import { insertTemplate, templateDialog, type TemplateHooks } from './ui/template-dialog'; import { applyTheme, readDensity, watchSharedTheme } from './ui/themes'; import { mountTitleTools } from './ui/titlebar'; import { toast } from './ui/toast'; @@ -201,6 +203,11 @@ export function startApp(): ShellHosts { syncGrid(h.stage); let home: Home | null = null; const canvas = mountCanvas(h, () => !!home?.isOpen()); + const tplHooks: TemplateHooks = { + placement: (c) => canvas.placement(c), + inserted: (c, frags) => canvas.inserted(c, frags), + createOptions: () => { const preset = canvas.preset(); return { ...(preset ? { preset } : {}), style: canvas.style() }; }, + }; let native: NativeMenus | null = null; let recentIds: string[] = []; let recentOff: () => void = () => undefined; @@ -253,6 +260,10 @@ export function startApp(): ShellHosts { palette: openPalette, toggleAnalysis, analysisOpen: isAnalysisOpen, + insertTemplate: (id?: string) => (id ? insertTemplate(id, tplHooks, true) : templateDialog(tplHooks)), + toggleStoich, + stoichOpen: isStoichOpen, + insertStoichTable: () => insertStoichTable(), terminal: () => { leaveHome(); dock.toggle(); }, terminalOpen: () => dock.isOpen(), newTerminal: () => { leaveHome(); void dock.newTerminal(); }, @@ -296,6 +307,7 @@ export function startApp(): ShellHosts { const tools = mountTitleTools(h.titleTools, commands); mountAnalysisPanel(h.panel); + mountStoichPanel(h.workspace); mountStatus(h, live); mountPalette(); diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index 357d802b..f920c65f 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -9,6 +9,7 @@ import type { Fragment, Id, Point, StyleOverride } from '../engine/model'; import { session } from '../engine/session'; import { setAnalysisScope } from '../ui/analysis-panel'; import { drawStyleOverride, drawStylePreset, loadSettings, pref, PREFS_EVENT } from '../ui/prefs/store'; +import { setStoichScope } from '../ui/stoich-panel'; import { mountToolRail, type ToolRail } from '../ui/tool-rail'; import { registerCanvasCommands } from './canvas-commands'; import { commandStateChanged } from './commands-shell'; @@ -56,6 +57,7 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan for (const id of s.objects) if (view.doc.objects[id]?.kind === 'fragment') ids.add(id); setAnalysisScope([...ids]); } + setStoichScope(isEmpty(s) ? null : [...new Set([...fragmentsTouched(s), ...s.objects])], view.page()?.id ?? null); commandStateChanged(); }; view.on('selection', scope); diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index 6e94f1f0..3f8ffbe1 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -10,6 +10,10 @@ export interface ShellCommandDeps { palette(): unknown; toggleAnalysis(): unknown; analysisOpen(): boolean; + insertTemplate(id?: string): unknown; + toggleStoich(): unknown; + stoichOpen(): boolean; + insertStoichTable(): unknown; terminal(): unknown; newTerminal(): unknown; claudeCode(): unknown; @@ -172,6 +176,7 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { { id: 'show-grid', label: () => t('Show Grid'), group: 'View', icon: 'grid', checked: () => deps.gridOn?.() ?? true, run: () => deps.showGrid() }, later('show-rulers', 'Show Rulers', 'View', '0.5.0', 'ruler'), { id: 'toggle-analysis', label: () => t('Analysis Panel'), group: 'View', icon: 'panelProps', checked: () => deps.analysisOpen(), run: () => deps.toggleAnalysis() }, + { id: 'show-stoichiometry', label: () => t('Stoichiometry Panel'), group: 'View', icon: 'table', checked: () => deps.stoichOpen(), run: () => deps.toggleStoich() }, { id: 'view-terminal', label: () => t('Terminal and Claude Code'), group: 'View', keys: ['Mod+`'], icon: 'terminal', checked: () => deps.terminalOpen?.() ?? false, run: () => deps.terminal() }, { id: 'new-terminal', label: () => t('New Terminal'), group: 'View', icon: 'terminal', run: () => deps.newTerminal() }, { id: 'claude-code', label: () => t('Claude Code'), group: 'View', keys: ['Shift+Mod+`'], icon: 'agent', run: () => deps.claudeCode() }, @@ -181,7 +186,7 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { { id: 'insert-smiles', label: () => t('Structure from SMILES...'), group: 'Insert', mutates: true, description: 'Adds the structure of a SMILES string to the active drawing (a new one when none is open) at the middle of the visible page, selected, as one undo step. With smiles it inserts that string; without it asks the person for one.', params: { smiles: { type: 'string', description: 'SMILES to insert, such as c1ccccc1O; leave it out to ask the person', example: 'c1ccccc1O' } }, run: (params) => deps.insertSmiles(typeof params?.smiles === 'string' ? params.smiles : undefined) }, later('insert-name', 'Structure from Name...', 'Insert', '0.9.0'), - later('insert-template', 'Template...', 'Insert', '0.5.0', 'template'), + { id: 'insert-template', label: () => t('Template...'), group: 'Insert', icon: 'template', mutates: true, description: 'Opens the template library; with id it inserts that template (fresh ids, scaled to the drawing bond length) centred in the view of the active drawing, or a new one, as one undo step. GET /api/templates lists the ids.', params: { id: { type: 'string', description: 'Template id from GET /api/templates, such as benzene or l-alanine; leave it out to open the library', example: 'benzene' } }, run: (params) => deps.insertTemplate(typeof params?.id === 'string' ? params.id : undefined) }, later('insert-arrow', 'Arrow', 'Insert', '0.5.0', 'arrow'), later('insert-shape', 'Shape', 'Insert', '0.5.0', 'shapes'), later('insert-table', 'Table', 'Insert', '0.5.0', 'table'), @@ -197,7 +202,7 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { later('set-reaction-roles', 'Set Reaction Roles', 'Reaction', '0.5.0'), later('map-atoms', 'Map Atoms', 'Reaction', '0.5.0'), later('clear-mapping', 'Clear Atom Mapping', 'Reaction', '0.5.0'), - later('stoichiometry-grid', 'Stoichiometry Grid', 'Reaction', '0.5.0', 'table'), + { id: 'stoichiometry-grid', label: () => t('Insert Stoichiometry Table'), group: 'Reaction', icon: 'table', mutates: true, description: 'Inserts the stoichiometry grid of the selected reaction step as a table under the reaction, or refreshes the table already bound to that step, as one undo step.', when: 'Draw a reaction with an arrow first', enabled: () => deps.hasDocument(), run: () => deps.insertStoichTable() }, later('bring-front', 'Bring to Front', 'Arrange', '0.5.0', 'bringFront'), later('bring-forward', 'Bring Forward', 'Arrange', '0.5.0', 'bringForward'), diff --git a/frontend/src/app/documents.ts b/frontend/src/app/documents.ts index 6af11a0e..c2334fe3 100644 --- a/frontend/src/app/documents.ts +++ b/frontend/src/app/documents.ts @@ -8,6 +8,7 @@ import { setAnalysisSource } from '../ui/analysis-panel'; import { askSaveChanges, promptName } from '../ui/dialogs'; import { inTauri } from '../ui/dom'; import { chooseStructureFiles } from '../ui/home'; +import { setStoichSource } from '../ui/stoich-panel'; import { setDocTitle } from '../ui/titlebar'; import { toast } from '../ui/toast'; import { commandStateChanged } from './commands-shell'; @@ -253,6 +254,7 @@ export class DocumentActions { this.off = null; this.shown = c; setAnalysisSource(c); + setStoichSource(c); if (c) { this.hadDocument = true; this.hooks.hideHome(); diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 1b100951..088c1390 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -17,7 +17,7 @@ export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource return [ { label: 'File', items: () => ['home', 'new-document', 'open', recent(), '-', 'new-window', 'close-window', 'close-document', '-', 'save', 'save-as', 'save-copy', '-', 'import', EXPORT, 'print', '-', 'preferences'] }, { label: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', COPY_AS, 'paste', 'duplicate', 'delete', '-', 'select-all', 'find'] }, - { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', '-', 'toggle-analysis', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, + { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', '-', 'toggle-analysis', 'show-stoichiometry', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, { label: 'Insert', items: ['insert-smiles', 'insert-name', 'insert-template', '-', 'insert-text', 'insert-arrow', 'insert-shape', 'insert-table', 'insert-image'] }, { label: 'Structure', items: ['clean-structure', 'layout-structure', 'check-structure', '-', 'expand-abbreviation', 'contract-abbreviation', '-', 'add-hydrogens', 'remove-hydrogens', 'show-stereo', '-', 'flip-horizontal', 'flip-vertical'] }, { label: 'Reaction', items: ['add-reaction-arrow', 'set-reaction-roles', '-', 'map-atoms', 'clear-mapping', '-', 'stoichiometry-grid'] }, From ccfdb38d688ab71f7c37a7d8483475549a05eff2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:25:26 -0500 Subject: [PATCH 084/279] feat(home): show the template library on Home (0.5.0) Start and the Templates page now list the engine's 206 templates with categories, search and thumbnails; a click inserts the template into the open drawing or a new one. --- frontend/src/app.ts | 1 + frontend/src/ui/home.ts | 47 ++++++++++------------------------------- 2 files changed, 12 insertions(+), 36 deletions(-) diff --git a/frontend/src/app.ts b/frontend/src/app.ts index a6e8dc9f..c83bc698 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -335,6 +335,7 @@ export function startApp(): ShellHosts { preferences: () => commands.run('preferences'), agents: () => commands.run('agents'), runCommand: (id) => commands.run(id), + openTemplate: (id) => { if (session.active) leaveHome(); void insertTemplate(id, tplHooks); }, moreMenu: (kind, item, at) => cardMenu(kind, item, at, (ids) => home?.forget(ids), openItem), onLibrary: (lib) => { recentOff(); diff --git a/frontend/src/ui/home.ts b/frontend/src/ui/home.ts index 36c8fcd4..11b19ec2 100644 --- a/frontend/src/ui/home.ts +++ b/frontend/src/ui/home.ts @@ -3,7 +3,9 @@ import { get, post } from '../io/api'; import { brandMark, PRODUCT_NAME } from './brand'; import { el, escapeHtml, q, qa, setAttr, setClass, setHidden, setText } from './dom'; import { EMPTY_LIBRARY, homeIcon, patchCards, type Library, type LibraryItem, type ListKind } from './home-cards'; +import { homeTemplatesSection } from './home-templates'; import { icon } from './icons'; +import { loadTemplates } from './template-dialog'; import { toast } from './toast'; export type { Library, LibraryItem, ListKind } from './home-cards'; @@ -18,6 +20,7 @@ export interface HomeHooks { preferences(): void; agents(): void; runCommand(id: string): void; + openTemplate?(id: string): void; moreMenu?(kind: ListKind, item: LibraryItem, at: { x: number; y: number }): void; openItem?(kind: ListKind, item: LibraryItem): void; onLibrary?(library: Library): void; @@ -30,7 +33,6 @@ const NAV_MIN = 180; const NAV_MAX = 420; const RECENT_ON_START = 8; const FORMATS = ['FCHEM', 'MOL', 'SDF', 'RXN', 'SMILES', 'CDXML', 'CDX', 'CML', 'CIF', 'PDB', 'JDX']; -const CATEGORIES = ['Rings', 'Amino acids', 'Sugars', 'Nucleotides', 'Reaction schemes', 'Glassware', 'Teaching', 'Journal styles']; const KINDS: ListKind[] = ['recent', 'templates', 'databases', 'trash']; export const STRUCTURE_ACCEPT = '.fchem,.mol,.sdf,.sd,.rxn,.rdf,.smi,.smiles,.cdxml,.cdx,.cml,.cif,.pdb,.jdx,.dx'; @@ -63,12 +65,7 @@ function pageHead(title: string, sub: string, actions = ''): string { return `

${x(title)}

${x(sub)}

${actions ? `
${actions}
` : ''}
`; } -function templateTools(): string { - return `
${CATEGORIES.map((c) => ``).join('')}
`; -} - const EMPTY_RECENT = 'No drawings yet. New drawings and the files you open appear here.'; -const EMPTY_TEMPLATES = 'No templates yet. Template structures arrive with the drawing tools.'; const EMPTY_DATABASES = 'No structure databases yet.'; function markup(): string { @@ -114,11 +111,11 @@ ${navItem('trash', 'delete', 'Trash')}

${x('Recent drawings')}

${grid('recent', RECENT_ON_START, EMPTY_RECENT)}

${x('Demos')}

${x('Demos arrive with the drawing tools')}

-

${x('Templates')}

${templateTools()}
${grid('templates', 0, EMPTY_TEMPLATES)}
+

${x('Databases')}

${grid('databases', RECENT_ON_START, EMPTY_DATABASES)}
- + @@ -144,14 +141,16 @@ export class Home { private lib: Library = EMPTY_LIBRARY; private loaded = false; private seq = 0; - private category: string | null = null; - private query = ''; constructor(host: HTMLElement, private readonly hooks: HomeHooks) { this.root = el(markup()); host.appendChild(this.root); this.sidePanel(); this.wire(); + const insert = (id: string): void => this.hooks.openTemplate?.(id); + homeTemplatesSection(q(this.root, '[data-tl-host="start"]'), { insert, limit: 12 }); + homeTemplatesSection(q(this.root, '[data-tl-host="page"]'), { insert, title: false }); + void loadTemplates().then((lib) => setText(this.root.querySelector('[data-count="templates"]'), String(lib.templates.length))).catch(() => undefined); this.dropZone(); } @@ -236,9 +235,8 @@ export class Home { setLibrary(raw: Partial): void { this.lib = normalise(raw); this.loaded = true; - for (const k of KINDS) setText(this.root.querySelector(`[data-count="${k}"]`), String(this.lib.counts[k])); + for (const k of KINDS) if (k !== 'templates') setText(this.root.querySelector(`[data-count="${k}"]`), String(this.lib.counts[k])); for (const k of KINDS) if (k !== 'templates') this.renderList(k); - this.filterTemplates(this.category, this.query); this.hooks.onLibrary?.(this.lib); } @@ -258,25 +256,8 @@ export class Home { } } - private items(kind: ListKind): LibraryItem[] { - const all = this.lib[kind]; - if (kind !== 'templates' || (!this.category && !this.query)) return all; - const q = this.query; - return all.filter((i) => (!this.category || i.category === this.category) && (!q || `${i.name} ${i.category ?? ''} ${i.description ?? ''}`.toLowerCase().includes(q))); - } - - private filterTemplates(category: string | null, query: string): void { - this.category = category; - this.query = query; - for (const chip of qa(this.root, '.fc-chip[data-cat]')) setAttr(chip, 'aria-pressed', chip.dataset.cat === category ? 'true' : 'false'); - for (const input of qa(this.root, '.fc-tpl-search')) if (document.activeElement !== input && input.value.trim().toLowerCase() !== query) input.value = query; - const filtered = this.lib.templates.length > 0 && this.items('templates').length === 0; - for (const e of qa(this.root, '.fc-home-empty[data-empty="templates"]')) setText(e, filtered ? t('No templates match this filter.') : t(EMPTY_TEMPLATES)); - this.renderList('templates'); - } - private renderList(kind: ListKind): void { - const items = this.items(kind); + const items = this.lib[kind]; for (const g of qa(this.root, `.fc-home-grid[data-list="${kind}"]`)) { const limit = Number(g.dataset.limit) || 0; patchCards(g, kind, limit ? items.slice(0, limit) : items); @@ -319,8 +300,6 @@ export class Home { return; } if (card) { this.activate(card); return; } - const cat = target.closest('.fc-chip[data-cat]')?.dataset.cat; - if (cat) { this.filterTemplates(cat === this.category ? null : cat, this.query); return; } const btn = target.closest('[data-a]'); if (!btn || btn.disabled) return; const a = btn.dataset.a; @@ -331,10 +310,6 @@ export class Home { else if (a === 'agents') this.hooks.agents(); else if (a === 'local') toast(t('Your drawings, templates and databases stay in your FormChem folder on this computer.')); }); - this.root.addEventListener('input', (e) => { - const input = e.target as HTMLElement; - if (input instanceof HTMLInputElement && input.classList.contains('fc-tpl-search')) this.filterTemplates(this.category, input.value.trim().toLowerCase()); - }); this.root.addEventListener('contextmenu', (e) => { const card = (e.target as HTMLElement).closest('.fc-card'); if (!card || !this.hooks.moreMenu) return; From 8f3dca8239a42bfd43d86af3a7f7fe4bd8a9d964 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:25:53 -0500 Subject: [PATCH 085/279] feat(rail): give the annotation tools their own rail groups (0.5.0) Arrows (W), symbols (P), brackets (K), orbitals (O), shapes (G), table, TLC and image now sit in named, keyed groups in two families after Text instead of trailing unnamed at the bottom. --- frontend/src/ui/tool-rail.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/frontend/src/ui/tool-rail.ts b/frontend/src/ui/tool-rail.ts index 6438937d..4cd763f5 100644 --- a/frontend/src/ui/tool-rail.ts +++ b/frontend/src/ui/tool-rail.ts @@ -22,6 +22,14 @@ export const RAIL_GROUPS: readonly RailGroup[] = [ { id: 'ring', label: 'Rings', key: 'R', family: 1 }, { id: 'atom', label: 'Atom Label', key: 'A', family: 1 }, { id: 'text', label: 'Text', key: 'T', family: 2 }, + { id: 'arrow', label: 'Arrows', key: 'W', family: 4 }, + { id: 'symbol', label: 'Symbols', key: 'P', family: 4 }, + { id: 'bracket', label: 'Brackets', key: 'K', family: 4 }, + { id: 'orbital', label: 'Orbitals', key: 'O', family: 4 }, + { id: 'shape', label: 'Shapes', key: 'G', family: 5 }, + { id: 'table', label: 'Table', key: '', family: 5 }, + { id: 'tlc', label: 'TLC', key: '', family: 5 }, + { id: 'image', label: 'Image', key: '', family: 5 }, { id: 'eraser', label: 'Eraser', key: 'E', family: 2 }, { id: 'hand', label: 'Hand', key: 'H', family: 3 }, { id: 'zoom', label: 'Zoom', key: 'Z', family: 3 }, From 13310e7e408741c478f41538fbedf6158e853680 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:26:21 -0500 Subject: [PATCH 086/279] feat(window): register the arrange and insert commands for drawn objects (0.5.0) Z-order, group and ungroup come from object-commands, and Insert Arrow, Shape, Table, Image and Add Reaction Arrow pick the matching tool or place a picture, so their placeholders go. --- frontend/src/app/canvas-commands.ts | 16 +++++++++++++++- frontend/src/app/canvas.ts | 2 ++ frontend/src/app/commands-shell.ts | 12 ------------ 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index 8f40b24e..b2121584 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -2,12 +2,13 @@ import { makeSelection, fragmentsTouched, isEmpty } from '../canvas/selection'; import { align, distribute, flipHorizontal, flipVertical, rotate90, type AlignHow } from '../canvas/tools'; import { atomsOfSelection, commitDraft, draftFor } from '../canvas/tools/common'; import { deleteSelection } from '../canvas/tools/edit'; +import { placeImage } from '../canvas/tools/image'; import { duplicateSelection } from '../canvas/tools/select'; import { translateSelection } from '../canvas/tools/transform'; import { selectionKey } from '../canvas/types'; import type { CanvasView } from '../canvas/view'; import { commands, type CommandDef } from '../commands/registry'; -import type { DerivedFragment, Fragment, Id } from '../engine/model'; +import type { DerivedFragment, Fragment, Id, Point } from '../engine/model'; import { atomPath, bondPath, type Op } from '../engine/ops'; import { t } from '../i18n'; import { post } from '../io/api'; @@ -152,6 +153,11 @@ function checkStructure(view: CanvasView): void { dlg.open(); } +function visibleCentre(view: CanvasView): Point { + const r = view.root.getBoundingClientRect(); + return view.toDoc(r.left + r.width / 2, r.top + r.height / 2); +} + function duplicate(view: CanvasView): void { const ctx = view.context; const sel = view.selection(); @@ -181,6 +187,9 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { const alignCmd = (id: string, label: string, icon: string, how: AlignHow): CommandDef => ({ id, label: () => t(label), group: 'Arrange', icon, mutates: true, when: NEED_SELECTION, enabled: selected, run: () => { align(ctx(), how); }, }); + const tool = (id: string, label: string, icon: string, toolId: string, group: string): CommandDef => ({ + id, label: () => t(label), group, icon, when: NEED_DRAWING, enabled: open, run: () => { view.setTool(toolId); view.focus(); }, + }); const defs: CommandDef[] = [ { id: 'zoom-in', label: () => t('Zoom In'), group: 'View', keys: ['Mod+='], icon: 'zoomIn', when: NEED_DRAWING, enabled: open, run: () => view.zoomIn() }, @@ -205,6 +214,11 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { { id: 'check-structure', label: () => t('Check Structure'), group: 'Structure', icon: 'approve', description: 'Lists valence errors and chemistry warnings for the selection, with links that select the atoms.', when: NEED_DRAWING, enabled: open, run: () => checkStructure(view) }, { id: 'show-analysis', label: () => t('Show Analysis'), group: 'Analysis', icon: 'panelProps', run: () => setAnalysisOpen(true) }, { id: 'insert-text', label: () => t('Text'), group: 'Insert', icon: 'textBox', when: NEED_DRAWING, enabled: open, run: () => { view.setTool('text'); view.focus(); } }, + tool('insert-arrow', 'Arrow', 'arrow', 'arrow-forward', 'Insert'), + tool('insert-shape', 'Shape', 'shapes', 'shape-rect', 'Insert'), + tool('insert-table', 'Table', 'table', 'table', 'Insert'), + { id: 'insert-image', label: () => t('Image...'), group: 'Insert', icon: 'image', mutates: true, description: 'Asks the person for a PNG, JPEG, GIF, WebP or SVG picture and places it in the middle of the visible page as one undo step.', when: NEED_DRAWING, enabled: open, run: () => { void placeImage(view.context, visibleCentre(view), null); } }, + tool('add-reaction-arrow', 'Add Reaction Arrow', 'arrow', 'arrow-forward', 'Reaction'), ]; return commands.register(...defs); } diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index f920c65f..4af8b0c8 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -13,6 +13,7 @@ import { setStoichScope } from '../ui/stoich-panel'; import { mountToolRail, type ToolRail } from '../ui/tool-rail'; import { registerCanvasCommands } from './canvas-commands'; import { commandStateChanged } from './commands-shell'; +import { objectCommandDefs } from './object-commands'; export interface CanvasHosts { stage: HTMLElement; stageCol: HTMLElement } @@ -42,6 +43,7 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan const open = (): boolean => !!view.client && !homeOpen(); commands.register(...rail.commands().map((c) => ({ ...c, enabled: open }))); registerCanvasCommands({ view, homeOpen }); + commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); view.setDisplay(display()); document.addEventListener(PREFS_EVENT, () => view.setDisplay(display())); diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index 3f8ffbe1..b3217e27 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -187,10 +187,6 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { { id: 'insert-smiles', label: () => t('Structure from SMILES...'), group: 'Insert', mutates: true, description: 'Adds the structure of a SMILES string to the active drawing (a new one when none is open) at the middle of the visible page, selected, as one undo step. With smiles it inserts that string; without it asks the person for one.', params: { smiles: { type: 'string', description: 'SMILES to insert, such as c1ccccc1O; leave it out to ask the person', example: 'c1ccccc1O' } }, run: (params) => deps.insertSmiles(typeof params?.smiles === 'string' ? params.smiles : undefined) }, later('insert-name', 'Structure from Name...', 'Insert', '0.9.0'), { id: 'insert-template', label: () => t('Template...'), group: 'Insert', icon: 'template', mutates: true, description: 'Opens the template library; with id it inserts that template (fresh ids, scaled to the drawing bond length) centred in the view of the active drawing, or a new one, as one undo step. GET /api/templates lists the ids.', params: { id: { type: 'string', description: 'Template id from GET /api/templates, such as benzene or l-alanine; leave it out to open the library', example: 'benzene' } }, run: (params) => deps.insertTemplate(typeof params?.id === 'string' ? params.id : undefined) }, - later('insert-arrow', 'Arrow', 'Insert', '0.5.0', 'arrow'), - later('insert-shape', 'Shape', 'Insert', '0.5.0', 'shapes'), - later('insert-table', 'Table', 'Insert', '0.5.0', 'table'), - later('insert-image', 'Image...', 'Insert', '0.5.0', 'image'), later('expand-abbreviation', 'Expand Abbreviation', 'Structure', '0.6.0'), later('contract-abbreviation', 'Contract Abbreviation', 'Structure', '0.6.0'), @@ -198,19 +194,11 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { later('remove-hydrogens', 'Remove Explicit Hydrogens', 'Structure', '0.6.0'), later('show-stereo', 'Show Stereochemistry', 'Structure', '0.6.0'), - later('add-reaction-arrow', 'Add Reaction Arrow', 'Reaction', '0.5.0', 'arrow'), later('set-reaction-roles', 'Set Reaction Roles', 'Reaction', '0.5.0'), later('map-atoms', 'Map Atoms', 'Reaction', '0.5.0'), later('clear-mapping', 'Clear Atom Mapping', 'Reaction', '0.5.0'), { id: 'stoichiometry-grid', label: () => t('Insert Stoichiometry Table'), group: 'Reaction', icon: 'table', mutates: true, description: 'Inserts the stoichiometry grid of the selected reaction step as a table under the reaction, or refreshes the table already bound to that step, as one undo step.', when: 'Draw a reaction with an arrow first', enabled: () => deps.hasDocument(), run: () => deps.insertStoichTable() }, - later('bring-front', 'Bring to Front', 'Arrange', '0.5.0', 'bringFront'), - later('bring-forward', 'Bring Forward', 'Arrange', '0.5.0', 'bringForward'), - later('send-backward', 'Send Backward', 'Arrange', '0.5.0', 'sendBackward'), - later('send-back', 'Send to Back', 'Arrange', '0.5.0', 'sendBack'), - later('group', 'Group', 'Arrange', '0.5.0', 'group'), - later('ungroup', 'Ungroup', 'Arrange', '0.5.0', 'ungroup'), - later('compute-properties', 'Compute Properties', 'Analysis', '0.6.0'), later('copy-analysis', 'Copy Analysis', 'Analysis', '0.6.0', 'copy'), From 0d655192458dcde01bcf31d9ec58e32b618d8ca5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:28:32 -0500 Subject: [PATCH 087/279] fix(commands): point Find and Show Rulers at the versions that build them (0.5.0) Neither ships in 0.5.0, so their disabled reason now names 0.11.0 (structure search) and 0.12.0 (page layout) instead of promising this release. --- frontend/src/app/commands-shell.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index b3217e27..5578ba3a 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -126,8 +126,8 @@ const LATER: Record = { '0.13.0': 'Arrives in 0.13.0 with the demos', }; -function later(id: string, label: string, group: string, version: string, icon?: string): CommandDef { - const when = LATER[version] ?? `Arrives in ${version}`; +function later(id: string, label: string, group: string, version: string, icon?: string, note?: string): CommandDef { + const when = note ?? LATER[version] ?? `Arrives in ${version}`; const def: CommandDef = { id, label: () => t(label), group, when, description: when, enabled: () => false, run: () => undefined }; if (icon) def.icon = icon; return def; @@ -171,10 +171,10 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { later('copy-svg', 'Copy as SVG', 'Edit', '0.7.0'), { id: 'paste', label: () => t('Paste'), group: 'Edit', icon: 'paste', when: 'A text field has focus', enabled: () => !!focusedField(), run: fieldOr('paste', deps.paste) }, { id: 'select-all', label: () => t('Select All'), group: 'Edit', keys: ['Mod+A'], icon: 'selectAll', run: () => (fieldSelectAll() ? undefined : deps.selectAll()) }, - later('find', 'Find...', 'Edit', '0.5.0', 'find'), + later('find', 'Find...', 'Edit', '0.11.0', 'find', 'Arrives in 0.11.0 with structure search'), { id: 'show-grid', label: () => t('Show Grid'), group: 'View', icon: 'grid', checked: () => deps.gridOn?.() ?? true, run: () => deps.showGrid() }, - later('show-rulers', 'Show Rulers', 'View', '0.5.0', 'ruler'), + later('show-rulers', 'Show Rulers', 'View', '0.12.0', 'ruler', 'Arrives in 0.12.0 with page layout'), { id: 'toggle-analysis', label: () => t('Analysis Panel'), group: 'View', icon: 'panelProps', checked: () => deps.analysisOpen(), run: () => deps.toggleAnalysis() }, { id: 'show-stoichiometry', label: () => t('Stoichiometry Panel'), group: 'View', icon: 'table', checked: () => deps.stoichOpen(), run: () => deps.toggleStoich() }, { id: 'view-terminal', label: () => t('Terminal and Claude Code'), group: 'View', keys: ['Mod+`'], icon: 'terminal', checked: () => deps.terminalOpen?.() ?? false, run: () => deps.terminal() }, From a43280b8154feec54030e7592bb8941e491cf3ea Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:29:00 -0500 Subject: [PATCH 088/279] feat(reactions): write a reaction export to a chosen file (0.5.0) The desktop window has no file system plugin, so Export Reaction asks the native save dialog for a path and the engine writes the RXN or reaction SMILES there. --- backend/app/routers/reactions.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/reactions.py b/backend/app/routers/reactions.py index 6e2e1edb..29527015 100644 --- a/backend/app/routers/reactions.py +++ b/backend/app/routers/reactions.py @@ -1,10 +1,11 @@ import asyncio import copy import math +from pathlib import Path from fastapi import APIRouter, Body, Depends, HTTPException, Request -from app.core import window_key +from app.core import files, window_key from app.services import ops as opsmod from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, balance, mapping, reactions, rxnio, scheme, stoich from app.services.store import STORE @@ -138,6 +139,20 @@ def export_step(doc_id: str, reaction_id: str, step_id: str, format: str = "rxn" return {"format": format, "text": text, "warnings": warnings, "engine": ENGINE} +@router.post(STEP + "/export", dependencies=GUARD) +async def export_step_file(doc_id: str, reaction_id: str, step_id: str, body: dict = Body(...)) -> dict: + path = body.get("path") + if not isinstance(path, str) or not Path(path.strip()).expanduser().is_absolute(): + raise HTTPException(422, "Give the absolute path of the file to write.") + fmt = body.get("format") if isinstance(body.get("format"), str) else "rxn" + found = export_step(doc_id, reaction_id, step_id, fmt) + try: + written = await asyncio.to_thread(files.write_atomic, path.strip(), found["text"].encode("utf-8")) + except OSError as exc: + raise HTTPException(400, f"Could not write {Path(path).name}: {exc.strerror or exc}.") + return {**found, "path": str(written)} + + def _text(body: dict) -> str: text = body.get("text") if not isinstance(text, str) or not text.strip(): From 1fe3eb9033f4576d4926297663f66341bb154421 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:29:01 -0500 Subject: [PATCH 089/279] feat(reaction): add the Reaction menu commands over the engine routes (0.5.0) Perceive, map, clear mapping, check and balance, copy or export as reaction SMILES or RXN, and insert a reaction from the clipboard now call the phase 5 engine routes; Set Reaction Roles is honestly retargeted to 0.6.0. --- frontend/src/app/canvas.ts | 2 + frontend/src/app/commands-shell.ts | 4 +- frontend/src/app/menus.ts | 6 +- frontend/src/app/reaction-commands.ts | 198 ++++++++++++++++++++++++++ frontend/src/engine/reactions-api.ts | 66 +++++++++ 5 files changed, 271 insertions(+), 5 deletions(-) create mode 100644 frontend/src/app/reaction-commands.ts create mode 100644 frontend/src/engine/reactions-api.ts diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index 4af8b0c8..181db2e3 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -14,6 +14,7 @@ import { mountToolRail, type ToolRail } from '../ui/tool-rail'; import { registerCanvasCommands } from './canvas-commands'; import { commandStateChanged } from './commands-shell'; import { objectCommandDefs } from './object-commands'; +import { registerReactionCommands } from './reaction-commands'; export interface CanvasHosts { stage: HTMLElement; stageCol: HTMLElement } @@ -44,6 +45,7 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan commands.register(...rail.commands().map((c) => ({ ...c, enabled: open }))); registerCanvasCommands({ view, homeOpen }); commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); + registerReactionCommands({ view, homeOpen }); view.setDisplay(display()); document.addEventListener(PREFS_EVENT, () => view.setDisplay(display())); diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index 5578ba3a..9fafa32f 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -194,9 +194,7 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { later('remove-hydrogens', 'Remove Explicit Hydrogens', 'Structure', '0.6.0'), later('show-stereo', 'Show Stereochemistry', 'Structure', '0.6.0'), - later('set-reaction-roles', 'Set Reaction Roles', 'Reaction', '0.5.0'), - later('map-atoms', 'Map Atoms', 'Reaction', '0.5.0'), - later('clear-mapping', 'Clear Atom Mapping', 'Reaction', '0.5.0'), + later('set-reaction-roles', 'Set Reaction Roles', 'Reaction', '0.6.0', undefined, 'Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing'), { id: 'stoichiometry-grid', label: () => t('Insert Stoichiometry Table'), group: 'Reaction', icon: 'table', mutates: true, description: 'Inserts the stoichiometry grid of the selected reaction step as a table under the reaction, or refreshes the table already bound to that step, as one undo step.', when: 'Draw a reaction with an arrow first', enabled: () => deps.hasDocument(), run: () => deps.insertStoichTable() }, later('compute-properties', 'Compute Properties', 'Analysis', '0.6.0'), diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 088c1390..64b80339 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -7,7 +7,9 @@ const EXTENSIONS_FALLBACK: MenuItem[] = ['ext-panel', 'ext-reload', 'ext-manage' const EXPORT: MenuItem = { label: 'Export', items: ['export-png', 'export-svg', 'export-pdf', '-', 'export-cdxml', 'export-mol', 'export-smiles'] }; const COPY_AS: MenuItem = { label: 'Copy As', items: ['copy-smiles', 'copy-molfile', 'copy-inchi', 'copy-svg'] }; -const ALIGN: MenuItem = { label: 'Align', items: ['align-left', 'align-center', 'align-right', '-', 'align-top', 'align-middle', 'align-bottom'] }; +const REACTION_COPY: MenuItem = { label: 'Copy Reaction As', items: ['copy-reaction-smiles', 'copy-reaction-rxn'] }; +const REACTION_EXPORT: MenuItem = { label: 'Export Reaction', items: ['export-reaction-smiles', 'export-reaction-rxn'] }; +const ALIGN: MenuItem ={ label: 'Align', items: ['align-left', 'align-center', 'align-right', '-', 'align-top', 'align-middle', 'align-bottom'] }; export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource): MenuDef[] { const recent = (): MenuItem => { @@ -20,7 +22,7 @@ export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', '-', 'toggle-analysis', 'show-stoichiometry', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, { label: 'Insert', items: ['insert-smiles', 'insert-name', 'insert-template', '-', 'insert-text', 'insert-arrow', 'insert-shape', 'insert-table', 'insert-image'] }, { label: 'Structure', items: ['clean-structure', 'layout-structure', 'check-structure', '-', 'expand-abbreviation', 'contract-abbreviation', '-', 'add-hydrogens', 'remove-hydrogens', 'show-stereo', '-', 'flip-horizontal', 'flip-vertical'] }, - { label: 'Reaction', items: ['add-reaction-arrow', 'set-reaction-roles', '-', 'map-atoms', 'clear-mapping', '-', 'stoichiometry-grid'] }, + { label: 'Reaction', items: ['add-reaction-arrow', 'perceive-reactions', 'set-reaction-roles', '-', 'map-atoms', 'clear-mapping', '-', 'check-reaction', 'balance-reaction', '-', 'show-stoichiometry', 'stoichiometry-grid', '-', 'paste-reaction', REACTION_COPY, REACTION_EXPORT] }, { label: 'Arrange', items: ['bring-front', 'bring-forward', 'send-backward', 'send-back', '-', ALIGN, 'distribute-h', 'distribute-v', '-', 'rotate-90', '-', 'group', 'ungroup'] }, { label: 'Analysis', items: ['show-analysis', 'compute-properties', '-', 'copy-analysis'] }, { label: '3D', items: ['view-3d', '-', 'build-3d', 'minimize-3d', 'conformers'] }, diff --git a/frontend/src/app/reaction-commands.ts b/frontend/src/app/reaction-commands.ts new file mode 100644 index 00000000..b7e7184f --- /dev/null +++ b/frontend/src/app/reaction-commands.ts @@ -0,0 +1,198 @@ +import { fragmentsTouched, isEmpty } from '../canvas/selection'; +import type { CanvasView } from '../canvas/view'; +import { reactionSteps, stepFor } from '../chem/stoich'; +import { commands, type CommandDef } from '../commands/registry'; +import type { DocumentClient } from '../engine/client-api'; +import type { Id } from '../engine/model'; +import { reactionsApi, warningText, type CheckAnswer, type ReactionFormat, type StepRef } from '../engine/reactions-api'; +import { session } from '../engine/session'; +import { t } from '../i18n'; +import { copyText, Dialog, promptName } from '../ui/dialogs'; +import { el, inTauri, setText } from '../ui/dom'; +import { toast } from '../ui/toast'; + +export interface ReactionCommandDeps { + view: CanvasView; + homeOpen(): boolean; +} + +const NEED_DRAWING = 'Open or create a drawing first'; +const NEED_REACTION = 'Draw a reaction arrow with reactants and products first'; +const EXT: Record = { rxn: 'rxn', rxnv3000: 'rxn', smiles: 'smi' }; + +const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const fail = (what: string) => (e: unknown): void => { toast(`${t(what)}: ${errText(e)}`, 'error'); }; + +function scopeIds(view: CanvasView): Id[] | null { + const s = view.selection(); + return isEmpty(s) ? null : [...new Set([...fragmentsTouched(s), ...s.objects])]; +} + +function chosenStep(view: CanvasView, client: DocumentClient): StepRef | null { + return stepFor(client.doc, scopeIds(view), view.page()?.id ?? null)?.ref ?? null; +} + +async function ensureStep(view: CanvasView, client: DocumentClient): Promise { + const have = chosenStep(view, client); + if (have) return have; + const page = view.page()?.id; + const done = await reactionsApi.perceive(client.id, page); + const found = done.pages.find((p) => p.page === page) ?? done.pages[0]; + const r = found?.reactions[0]; + const s = r?.steps[0]; + if (found && r && s) return { page: found.page, reaction: r.id, step: s.id }; + toast(t('No reaction found: draw an arrow with structures on both sides.'), 'error'); + return null; +} + +async function perceive(view: CanvasView, client: DocumentClient): Promise { + const done = await reactionsApi.perceive(client.id, view.page()?.id); + const steps = done.summary.reduce((n, s) => n + s.steps, 0); + const found = done.summary.reduce((n, s) => n + s.reactions, 0); + if (!steps) { toast(t('No reaction found: draw an arrow with structures on both sides.')); return; } + toast(`${t('Reactions')}: ${found}, ${t('steps')}: ${steps}${done.changed ? '' : ` (${t('unchanged')})`}`); +} + +async function mapAtoms(view: CanvasView, client: DocumentClient): Promise { + const step = await ensureStep(view, client); + if (!step) return; + const done = await reactionsApi.map(client.id, step); + const m = done.mapping; + const c = m.centres; + const quality = m.quality === 'complete' ? t('complete') : m.quality ?? ''; + const centres = c ? `; ${t('bonds broken')} ${c.broken}, ${t('formed')} ${c.formed}, ${t('changed order')} ${c.order}` : ''; + toast(`${t('Mapped atoms')}: ${m.mapped ?? 0} (${quality})${centres}`); +} + +async function clearMap(view: CanvasView, client: DocumentClient): Promise { + const step = chosenStep(view, client); + if (!step) { toast(t(NEED_REACTION), 'error'); return; } + const done = await reactionsApi.clearMap(client.id, step); + toast(done.changed ? `${t('Cleared atom map numbers')}: ${done.mapping.cleared ?? 0}` : t('The step has no atom mapping.')); +} + +let checkDialog: Dialog | null = null; + +function row(text: string, cls = ''): HTMLElement { + const r = el(`
`); + setText(r.firstElementChild, text); + return r; +} + +const num = (v: number): string => (Number.isInteger(v) ? String(v) : v.toFixed(3)); + +function showCheck(view: CanvasView, client: DocumentClient, step: StepRef, res: CheckAnswer): void { + const dlg = (checkDialog ??= new Dialog(t('Check Balance'), 480)); + dlg.body.replaceChildren(); + dlg.foot.replaceChildren(); + const list = el('
'); + const head = el('

'); + setText(head, res.balanced ? t('The reaction is balanced.') : t('The reaction is not balanced.')); + list.appendChild(head); + for (const e of res.elements) list.appendChild(row(`${e.element}: ${num(e.left)} / ${num(e.right)}${e.diff ? ` (${e.diff > 0 ? '+' : ''}${num(e.diff)})` : ''}`)); + list.appendChild(row(`${t('Charge')}: ${num(res.charge.left)} / ${num(res.charge.right)}`)); + list.appendChild(row(`${t('Mass')}: ${res.mass.left.toFixed(2)} / ${res.mass.right.toFixed(2)} g/mol`)); + for (const w of res.warnings) { const text = warningText(w); if (text) list.appendChild(row(text)); } + const co = res.suggestion?.co_products?.[0]; + if (co) list.appendChild(row(`${t('Missing co-products')}: ${co.add.map((a) => `${a.coefficient > 1 ? `${a.coefficient} ` : ''}${a.name}`).join(', ')}`)); + dlg.body.appendChild(list); + if (res.suggestion?.coefficients) { + dlg.button(t('Balance'), 'primary', () => { + dlg.close(); + void reactionsApi.balance(client.id, step).then(() => toast(t('Balanced the reaction.'))).catch(fail('Could not balance the reaction')); + }); + } + dlg.button(t('Close'), res.suggestion?.coefficients ? 'ghost' : 'primary', () => { dlg.close(); view.focus(); }); + dlg.open(); +} + +async function check(view: CanvasView, client: DocumentClient): Promise { + const step = await ensureStep(view, client); + if (!step) return; + showCheck(view, client, step, await reactionsApi.check(client.id, step)); +} + +async function balance(view: CanvasView, client: DocumentClient): Promise { + const step = await ensureStep(view, client); + if (!step) return; + const done = await reactionsApi.balance(client.id, step); + toast(done.changed ? t('Balanced the reaction.') : t('The reaction is already balanced.')); +} + +function noteWarnings(list: Array): string { + const first = list.map(warningText).find(Boolean); + return first ? ` (${first})` : ''; +} + +async function copyReaction(view: CanvasView, client: DocumentClient, format: ReactionFormat): Promise { + const step = await ensureStep(view, client); + if (!step) return; + const out = await reactionsApi.exportText(client.id, step, format); + if (!(await copyText(out.text))) throw new Error(t('the clipboard is not available')); + toast(`${format === 'smiles' ? t('Copied the reaction SMILES') : t('Copied the reaction as RXN')}${noteWarnings(out.warnings)}`); +} + +function stemOf(client: DocumentClient): string { + return (client.doc.title || 'reaction').replace(/[\\/:*?"<>|]+/g, ' ').trim() || 'reaction'; +} + +async function exportReaction(view: CanvasView, client: DocumentClient, format: ReactionFormat): Promise { + const step = await ensureStep(view, client); + if (!step) return; + const name = `${stemOf(client)}.${EXT[format]}`; + if (inTauri()) { + const { invoke } = await import('@tauri-apps/api/core'); + const path = await invoke('plugin:dialog|save', { options: { defaultPath: name, filters: [{ name: format === 'smiles' ? 'SMILES' : 'RXN', extensions: [EXT[format]] }] } }); + if (!path) return; + const out = await reactionsApi.exportFile(client.id, step, format, path); + toast(`${t('Exported the reaction to')} ${out.path ?? path}${noteWarnings(out.warnings)}`); + return; + } + const out = await reactionsApi.exportText(client.id, step, format); + const url = URL.createObjectURL(new Blob([out.text], { type: format === 'smiles' ? 'chemical/x-daylight-smiles' : 'chemical/x-mdl-rxnfile' })); + const a = document.createElement('a'); + a.href = url; + a.download = name; + a.click(); + window.setTimeout(() => URL.revokeObjectURL(url), 1000); + toast(`${t('Exported the reaction to')} ${name}${noteWarnings(out.warnings)}`); +} + +async function readClipboard(): Promise { + try { + const text = await navigator.clipboard.readText(); + if (text.trim()) return text; + } catch { void 0; } + return promptName(t('Insert Reaction'), '', t('Insert'), t('Reaction SMILES or RXN')); +} + +async function importReaction(view: CanvasView): Promise { + const text = await readClipboard(); + if (!text?.trim()) return; + const client = session.active ?? await session.create({}); + const done = await reactionsApi.importText(client.id, text, view.client === client ? view.page()?.id : undefined); + toast(`${t('Inserted a reaction')} (${done.format})${noteWarnings(done.warnings)}`); +} + +export function registerReactionCommands(deps: ReactionCommandDeps): () => void { + const { view } = deps; + const open = (): boolean => !!view.client && !deps.homeOpen(); + const hasSteps = (): boolean => open() && !!view.client && reactionSteps(view.client.doc).length > 0; + const on = (what: string, fn: (v: CanvasView, c: DocumentClient) => Promise) => (): void => { + const c = view.client; + if (c) void fn(view, c).catch(fail(what)); + }; + const defs: CommandDef[] = [ + { id: 'perceive-reactions', label: () => t('Perceive Reactions'), group: 'Reaction', icon: 'arrow', mutates: true, description: 'Reads the reaction arrows on the page and stores each step with its reactants, products, agents and conditions, as one undo step.', when: NEED_DRAWING, enabled: open, run: on('Could not perceive the reactions', perceive) }, + { id: 'map-atoms', label: () => t('Map Atoms'), group: 'Reaction', mutates: true, description: 'Maps the atoms of the selected reaction step (perceiving reactions first when none is stored) and marks the bonds broken, formed and changed, as one undo step.', when: NEED_DRAWING, enabled: open, run: on('Could not map the atoms', mapAtoms) }, + { id: 'clear-mapping', label: () => t('Clear Atom Mapping'), group: 'Reaction', mutates: true, description: 'Removes the atom map numbers and reacting-centre marks of the selected reaction step.', when: NEED_REACTION, enabled: hasSteps, run: on('Could not clear the mapping', clearMap) }, + { id: 'check-reaction', label: () => t('Check Balance...'), group: 'Reaction', icon: 'approve', description: 'Shows the element, charge and mass balance of the selected reaction step, with a suggestion when it is not balanced.', when: NEED_DRAWING, enabled: open, run: on('Could not check the reaction', check) }, + { id: 'balance-reaction', label: () => t('Balance Reaction'), group: 'Reaction', mutates: true, description: 'Sets the coefficients of the selected reaction step to the balanced values, as one undo step.', when: NEED_DRAWING, enabled: open, run: on('Could not balance the reaction', balance) }, + { id: 'copy-reaction-smiles', label: () => t('Copy Reaction SMILES'), group: 'Reaction', icon: 'copy', when: NEED_DRAWING, enabled: open, run: on('Could not copy the reaction', (v, c) => copyReaction(v, c, 'smiles')) }, + { id: 'copy-reaction-rxn', label: () => t('Copy Reaction as RXN'), group: 'Reaction', icon: 'copy', when: NEED_DRAWING, enabled: open, run: on('Could not copy the reaction', (v, c) => copyReaction(v, c, 'rxn')) }, + { id: 'export-reaction-smiles', label: () => t('Export Reaction SMILES...'), group: 'Reaction', icon: 'download', when: NEED_DRAWING, enabled: open, run: on('Could not export the reaction', (v, c) => exportReaction(v, c, 'smiles')) }, + { id: 'export-reaction-rxn', label: () => t('Export Reaction as RXN...'), group: 'Reaction', icon: 'download', when: NEED_DRAWING, enabled: open, run: on('Could not export the reaction', (v, c) => exportReaction(v, c, 'rxn')) }, + { id: 'paste-reaction', label: () => t('Insert Reaction from Clipboard'), group: 'Reaction', icon: 'paste', mutates: true, description: 'Reads reaction SMILES or an RXN file from the clipboard and lays it out on the page with its roles set, as one undo step.', enabled: () => !deps.homeOpen(), run: () => { void importReaction(view).catch(fail('Could not insert the reaction')); } }, + ]; + return commands.register(...defs); +} diff --git a/frontend/src/engine/reactions-api.ts b/frontend/src/engine/reactions-api.ts new file mode 100644 index 00000000..162f0677 --- /dev/null +++ b/frontend/src/engine/reactions-api.ts @@ -0,0 +1,66 @@ +import { del, get, post } from '../io/api'; +import { live } from '../io/live'; +import { docUrl } from './client'; +import type { Id, Reaction } from './model'; +import type { Transaction } from './ops'; + +export interface StepRef { page: Id; reaction: Id; step: Id } + +export type ReactionFormat = 'smiles' | 'rxn' | 'rxnv3000'; +export type MapMode = 'discard' | 'keep' | 'alter'; + +export interface Changed { changed: boolean; tx: Transaction | null; rev: number } + +export interface PerceiveSummary { page: Id; reactions: number; steps: number; explicit: number; stale: Id[] | number; changed: boolean } +export interface PerceiveAnswer extends Changed { summary: PerceiveSummary[]; pages: Array<{ page: Id; reactions: Reaction[] }> } + +export interface MappingInfo { + mode: string; + mapped?: number; + unmapped?: number; + cleared?: number; + quality?: string; + centres?: { broken: number; formed: number; order: number }; + warnings?: Array; +} +export interface MapAnswer extends Changed { mapping: MappingInfo } + +export interface ElementBalance { element: string; left: number; right: number; diff: number } +export interface SpeciesRow { id: Id; role: string; coefficient: number; formula: string; mw: number | null; charge: number } +export interface CoProduct { name: string; smiles: string; coefficient: number } +export interface Suggestion { coefficients?: Record; co_products?: Array<{ add: CoProduct[]; coefficients: Record }> } +export interface CheckAnswer { + rev: number; + reaction: Id; + step: Id; + balanced: boolean; + species: SpeciesRow[]; + elements: ElementBalance[]; + charge: { left: number; right: number; diff: number }; + mass: { left: number; right: number; diff: number }; + suggestion: Suggestion | null; + warnings: Array; +} +export interface BalanceAnswer extends Changed { coefficients: Record; check: CheckAnswer } + +export interface ExportAnswer { format: ReactionFormat; text: string; warnings: Array; engine?: string; path?: string } +export interface ImportAnswer extends Changed { page: Id; format: string; objects: Id[]; reaction: Reaction | null; warnings: Array } +export interface StoichTableAnswer extends Changed { table: Id | null } + +const seg = encodeURIComponent; +const stepUrl = (doc: Id, s: StepRef, tail: string): string => docUrl(doc, `reactions/${seg(s.reaction)}/steps/${seg(s.step)}/${tail}`); +const withClient = (body: Record = {}): Record => (live.clientId ? { ...body, client: live.clientId } : body); + +export const warningText = (w: string | { text?: string; code?: string }): string => (typeof w === 'string' ? w : w.text ?? w.code ?? ''); + +export const reactionsApi = { + perceive: (doc: Id, page?: Id): Promise => post(docUrl(doc, 'reactions/perceive'), withClient(page ? { page } : {})), + map: (doc: Id, s: StepRef, mode: MapMode = 'discard'): Promise => post(stepUrl(doc, s, 'map'), withClient({ mode })), + clearMap: (doc: Id, s: StepRef): Promise => del(`${stepUrl(doc, s, 'map')}?centres=true${live.clientId ? `&client=${seg(live.clientId)}` : ''}`), + check: (doc: Id, s: StepRef): Promise => get(stepUrl(doc, s, 'check')), + balance: (doc: Id, s: StepRef, coefficients?: Record): Promise => post(stepUrl(doc, s, 'balance'), withClient(coefficients ? { coefficients } : {})), + exportText: (doc: Id, s: StepRef, format: ReactionFormat): Promise => get(`${stepUrl(doc, s, 'export')}?format=${format}`), + exportFile: (doc: Id, s: StepRef, format: ReactionFormat, path: string): Promise => post(stepUrl(doc, s, 'export'), { format, path }), + importText: (doc: Id, text: string, page?: Id): Promise => post(docUrl(doc, 'reactions/import'), withClient(page ? { text, page } : { text })), + stoichTable: (doc: Id, s: StepRef): Promise => post(stepUrl(doc, s, 'stoich-table'), withClient()), +}; From 0821529eec9cc5ed2f55e3608b6551b2670f79bf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:29:16 -0500 Subject: [PATCH 090/279] fix(stoich): refresh the bound grid in the engine instead of adding another (0.5.0) Insert as table and the Reaction menu item added a second table on every click; when the step already has a bound table the engine's stoich-table route now rewrites its rows in place as one undo step. --- frontend/src/ui/stoich-panel.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/frontend/src/ui/stoich-panel.ts b/frontend/src/ui/stoich-panel.ts index f508b6e3..3414c084 100644 --- a/frontend/src/ui/stoich-panel.ts +++ b/frontend/src/ui/stoich-panel.ts @@ -4,10 +4,12 @@ import { componentEdit, stepEdit, stoichTableOps, type ComponentField, type Step import type { DocEvent } from '../engine/client-api'; import type { Derived, FormChemDocument, Id } from '../engine/model'; import type { Op } from '../engine/ops'; +import { reactionsApi } from '../engine/reactions-api'; import { t } from '../i18n'; import { get } from '../io/api'; import { el, escapeHtml, patchList, q, qa, setAttr, setClass, setDisabled, setHidden, setHtml, setText, setTitle, setValue } from './dom'; import { icon } from './icons'; +import { toast } from './toast'; export const STOICH_OPEN_KEY = 'formchem.stoichOpen'; @@ -376,6 +378,11 @@ export function insertStoichTable(): Id | null { if (!s) return null; const entry = shown?.entry ?? resolveEntry(s.doc); if (!entry) return null; + const bound = Object.values(s.doc.objects).find((o) => o.kind === 'table' && o.stoich?.reaction === entry.ref.reaction && o.stoich.step === entry.ref.step); + if (bound) { + void reactionsApi.stoichTable(s.id, entry.ref).catch((e: unknown) => toast(`${t('Could not refresh the stoichiometry table')}: ${e instanceof Error ? e.message : String(e)}`, 'error')); + return bound.id; + } const derived = s.derived && s.derived.rev === s.rev ? s.derived : null; const result = shown?.entry === entry ? shown.result : computeStoich(s.doc, entry.step, derived, engineMw); const built = stoichTableOps(s.doc, entry.ref, result, { From f6aae3125a6e6ec869fd53d60b34e4d5c742cfb1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:30:00 -0500 Subject: [PATCH 091/279] refactor(render): draw the stoichiometry grid from the panel's computation (0.5.0) Two TypeScript stoichiometry modules disagreed on precedence (the renderer let the limiting reagent's typed amount beat scale_mmol); the canvas grid now uses chem/stoich, which follows the engine's scale-wins rule, so the panel and the drawn table always show the same numbers. --- frontend/src/canvas/render/index.ts | 1 - frontend/src/canvas/render/stoich.ts | 147 --------------------------- frontend/src/canvas/render/table.ts | 36 ++++--- 3 files changed, 17 insertions(+), 167 deletions(-) delete mode 100644 frontend/src/canvas/render/stoich.ts diff --git a/frontend/src/canvas/render/index.ts b/frontend/src/canvas/render/index.ts index f2ad4f50..ed2be1db 100644 --- a/frontend/src/canvas/render/index.ts +++ b/frontend/src/canvas/render/index.ts @@ -6,6 +6,5 @@ export { objectBox, objectBoxById } from './bounds'; export { OBJECT_KINDS, objectView, docCtx, type ObjectCtx, type ObjectView, type ChemGeometry } from './objects'; export { anchorPoint, arrowEnds } from './anchors'; export { arrowShape, bentCurve, type Curve } from './arrow'; -export { computeStoich, findStep, type StoichGrid, type StoichRow } from './stoich'; export { mediaCache, setMediaUrl, type MediaUrl } from './image'; export { tlcLayout, spotGeom } from './tlc'; diff --git a/frontend/src/canvas/render/stoich.ts b/frontend/src/canvas/render/stoich.ts deleted file mode 100644 index 83202bca..00000000 --- a/frontend/src/canvas/render/stoich.ts +++ /dev/null @@ -1,147 +0,0 @@ -import type { FormChemDocument, Id, ReactionStep, Stoich, StoichComponent } from '../../engine/model'; - -export type StoichRole = 'reactant' | 'agent' | 'product'; -export type StoichField = 'equiv' | 'mmol' | 'mass' | 'volume'; - -export interface StoichRow { - id: Id; - role: StoichRole; - label: string; - formula?: string; - mw?: number; - equiv?: number; - mmol?: number; - mass_mg?: number; - volume_ml?: number; - density?: number; - conc?: number; - purity: number; - given: ReadonlySet; - limiting: boolean; - theo_mmol?: number; - theo_mg?: number; -} - -export interface StoichGrid { - rows: StoichRow[]; - limiting?: Id; - refMmol?: number; - product?: Id; - theoMmol?: number; - theoMg?: number; - isolatedMg?: number; - yieldPct?: number; -} - -export interface SpeciesInfo { mw?: number; formula?: string; name?: string } - -export function findStep(doc: FormChemDocument, reaction: Id, step: Id): ReactionStep | undefined { - for (const p of doc.pages) { - const r = p.reactions?.find((x) => x.id === reaction); - const s = r?.steps.find((x) => x.id === step); - if (s) return s; - } - return undefined; -} - -const finite = (n: number | undefined): n is number => typeof n === 'number' && Number.isFinite(n); -const pos = (n: number | undefined): n is number => finite(n) && n > 0; - -function directMmol(c: StoichComponent, mw: number | undefined, purity: number): number | undefined { - if (finite(c.mass_mg) && pos(mw)) return (c.mass_mg * purity) / mw; - if (finite(c.volume_ml) && pos(c.conc_m)) return c.conc_m * c.volume_ml; - if (finite(c.volume_ml) && pos(c.density_g_ml) && pos(mw)) return (c.volume_ml * c.density_g_ml * 1000 * purity) / mw; - return undefined; -} - -export function computeStoich(step: ReactionStep, info: (id: Id) => SpeciesInfo): StoichGrid { - const st: Stoich = step.stoich ?? { components: {} }; - const comps = st.components ?? {}; - const coef = (id: Id): number => (pos(step.coefficients?.[id]) ? step.coefficients![id] : 1); - const order: [Id, StoichRole][] = []; - const seen = new Set(); - const push = (id: Id, role: StoichRole): void => { - if (seen.has(id)) return; - seen.add(id); - order.push([id, role]); - }; - for (const id of step.reactants) push(id, 'reactant'); - for (const id of step.agents) push(id, 'agent'); - for (const id of step.products) push(id, 'product'); - for (const id of Object.keys(comps)) push(id, 'agent'); - - const rows: StoichRow[] = order.map(([id, role]) => { - const c = comps[id] ?? {}; - const sp = info(id); - const mw = pos(c.mw) ? c.mw : sp.mw; - const purity = (pos(c.purity_pct) ? Math.min(c.purity_pct, 100) : 100) / 100; - const given = new Set(); - if (finite(c.equiv)) given.add('equiv'); - if (finite(c.mass_mg)) given.add('mass'); - if (finite(c.volume_ml)) given.add('volume'); - let mmol = directMmol(c, mw, purity); - if (role === 'product' && id === st.product && mmol === undefined && finite(st.isolated_mg) && pos(mw)) { - mmol = st.isolated_mg / mw; - given.add('mass'); - } - return { - id, role, label: c.label ?? sp.name ?? sp.formula ?? id, formula: sp.formula, mw, mmol, - equiv: c.equiv, density: c.density_g_ml, conc: c.conc_m, purity, given, limiting: false, - }; - }); - - const reactants = rows.filter((r) => r.role === 'reactant'); - let limiting = st.limiting && rows.some((r) => r.id === st.limiting) ? st.limiting : undefined; - if (!limiting) { - let best = Infinity; - for (const r of reactants) { - if (!finite(r.mmol)) continue; - const v = r.mmol / coef(r.id); - if (v < best) { - best = v; - limiting = r.id; - } - } - } - if (!limiting) limiting = reactants.find((r) => r.equiv === 1)?.id ?? reactants[0]?.id; - const lim = rows.find((r) => r.id === limiting); - let refMmol = lim?.mmol; - if (!finite(refMmol) && pos(st.scale_mmol)) refMmol = st.scale_mmol * (pos(lim?.equiv) ? lim!.equiv! : 1); - const unitMmol = finite(refMmol) && lim ? refMmol / (pos(lim.equiv) ? lim.equiv! : 1) : undefined; - if (lim) { - lim.limiting = true; - if (!finite(lim.mmol) && finite(refMmol)) lim.mmol = refMmol; - } - - for (const r of rows) { - if (r.role !== 'product' && !finite(r.mmol) && finite(r.equiv) && finite(unitMmol)) r.mmol = r.equiv * unitMmol; - if (finite(r.mmol)) { - const c = comps[r.id] ?? {}; - r.mass_mg = finite(c.mass_mg) ? c.mass_mg : pos(r.mw) ? (r.mmol * r.mw) / r.purity : undefined; - r.volume_ml = finite(c.volume_ml) ? c.volume_ml : pos(r.conc) ? r.mmol / r.conc : pos(r.density) && finite(r.mass_mg) ? r.mass_mg / (r.density * 1000) : undefined; - if (r.role !== 'product' && !finite(r.equiv) && finite(refMmol) && refMmol > 0) r.equiv = (r.mmol / refMmol) * (pos(lim?.equiv) ? lim!.equiv! : 1); - } - if (r.role === 'product' && finite(refMmol) && lim) { - r.theo_mmol = (refMmol / coef(lim.id)) * coef(r.id); - if (pos(r.mw)) r.theo_mg = r.theo_mmol * r.mw; - } - } - - const grid: StoichGrid = { rows, limiting, refMmol }; - const product = rows.find((r) => r.id === st.product) ?? rows.find((r) => r.role === 'product'); - if (product) { - grid.product = product.id; - grid.theoMmol = product.theo_mmol; - grid.theoMg = product.theo_mg; - const isolated = finite(st.isolated_mg) ? st.isolated_mg : product.given.has('mass') ? product.mass_mg : undefined; - grid.isolatedMg = isolated; - if (finite(isolated) && pos(product.theo_mg)) grid.yieldPct = (isolated / product.theo_mg) * 100; - } - return grid; -} - -export function sig(n: number | undefined, digits = 3): string { - if (!finite(n)) return ''; - if (n === 0) return '0'; - return String(Number(n.toPrecision(digits))); -} diff --git a/frontend/src/canvas/render/table.ts b/frontend/src/canvas/render/table.ts index 1a2c465f..f8d7d6d5 100644 --- a/frontend/src/canvas/render/table.ts +++ b/frontend/src/canvas/render/table.ts @@ -1,8 +1,8 @@ +import { computeStoich, findStep, sig, type StoichResult } from '../../chem/stoich'; import type { Align, FormChemDocument, Id, Run, TableObject } from '../../engine/model'; import { fmt, type Box } from './geom'; import { measure } from './measure'; import type { ObjectCtx, ObjectKindDef, ObjectView } from './objects'; -import { computeStoich, findStep, sig, type StoichGrid } from './stoich'; import type { NodeSpec } from './svg'; import { textView } from './text'; @@ -49,28 +49,28 @@ function gridSpecs(g: Grid, ctx: ObjectCtx): ObjectView { const cell = (t: string, opts: { i?: boolean; align?: Align; formula?: boolean } = {}): GridCell => ({ runs: [opts.i ? { t, i: true } : { t }], align: opts.align, formula: opts.formula }); -function numCell(v: number | undefined, given: boolean): GridCell { - return cell(sig(v), { i: !given && v !== undefined, align: 'r' }); +function numCell(v: number | null, given: boolean): GridCell { + return cell(sig(v), { i: !given && v !== null, align: 'r' }); } -function stoichRows(grid: StoichGrid): GridCell[][] { +function stoichRows(grid: StoichResult): GridCell[][] { const out: GridCell[][] = [STOICH_COLUMNS.map((t, i) => cell(t, { align: i >= 2 ? 'r' : 'l' }))]; for (const r of grid.rows) { const role = r.role === 'reactant' ? (r.limiting ? 'limiting' : 'reactant') : r.role === 'agent' ? 'reagent' : 'product'; out.push([ - cell(r.label, { formula: r.label === r.formula }), + cell(r.name, { formula: r.name === r.formula }), cell(role), - cell(r.mw !== undefined ? r.mw.toFixed(2) : '', { align: 'r' }), - r.role === 'product' ? cell('') : numCell(r.equiv, r.given.has('equiv')), + cell(r.mw !== null ? r.mw.toFixed(2) : '', { align: 'r' }), + r.role === 'product' ? cell('') : numCell(r.equiv, r.typed.equiv !== undefined), numCell(r.mmol, false), - numCell(r.mass_mg, r.given.has('mass')), - numCell(r.volume_ml, r.given.has('volume')), + numCell(r.massMg, r.typed.mass_mg !== undefined), + numCell(r.volumeMl, r.typed.volume_ml !== undefined), ]); } - if (grid.theoMg !== undefined || grid.theoMmol !== undefined) { + if (grid.theoMg !== null || grid.theoMmol !== null) { out.push([cell('Theoretical yield'), cell(''), cell(''), cell(''), cell(sig(grid.theoMmol), { i: true, align: 'r' }), cell(sig(grid.theoMg), { i: true, align: 'r' }), cell('')]); } - if (grid.yieldPct !== undefined) { + if (grid.yieldPct !== null) { out.push([cell('Yield'), cell(''), cell(''), cell(''), cell(''), cell(sig(grid.isolatedMg), { align: 'r' }), cell(`${grid.yieldPct.toFixed(1)} %`, { i: true, align: 'r' })]); } return out; @@ -78,13 +78,10 @@ function stoichRows(grid: StoichGrid): GridCell[][] { function stoichGrid(obj: TableObject, ctx: ObjectCtx): Grid | null { if (!obj.stoich) return null; - const step = findStep(ctx.doc, obj.stoich.reaction, obj.stoich.step); + const page = ctx.doc.pages.find((p) => p.reactions?.some((r) => r.id === obj.stoich!.reaction)); + const step = page ? findStep(ctx.doc, { page: page.id, ...obj.stoich }) : null; if (!step) return null; - const computed = computeStoich(step, (id) => { - const d = ctx.derived?.fragments[id]; - return { mw: d?.mw, formula: d?.formula, name: ctx.doc.objects[id]?.name }; - }); - const cells = stoichRows(computed); + const cells = stoichRows(computeStoich(ctx.doc, step, ctx.derived)); const pad = obj.padding ?? 3; const font = ctx.style.caption_font; const rowH = font.size * 1.2 + 2 * pad; @@ -113,10 +110,11 @@ function tableView(obj: TableObject, ctx: ObjectCtx): ObjectView { function tableDeps(obj: TableObject, doc: FormChemDocument): unknown[] { if (!obj.stoich) return []; - const step = findStep(doc, obj.stoich.reaction, obj.stoich.step); + const page = doc.pages.find((p) => p.reactions?.some((r) => r.id === obj.stoich!.reaction)); + const step = page ? findStep(doc, { page: page.id, ...obj.stoich }) : null; if (!step) return [null]; const ids: Id[] = [...step.reactants, ...step.agents, ...step.products]; - return [step, ...ids.map((id) => doc.objects[id]?.name)]; + return [step, ...ids.map((id) => doc.objects[id])]; } export const tableKind: ObjectKindDef<'table'> = { view: tableView, deps: tableDeps, derived: true }; From 1fb8ec5b32a5136b88fd80659e658b1cc6103b20 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:30:46 -0500 Subject: [PATCH 092/279] fix(tools): move an attached caption by its offset (0.5.0) The renderer places a caption from its target and offset, so moving the caption alone changed only its x, y cache and it snapped back; the transform now rewrites the offset (and the cache) from the target's bounds before and after, captions last. --- frontend/src/canvas/tools/transform.ts | 31 ++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/frontend/src/canvas/tools/transform.ts b/frontend/src/canvas/tools/transform.ts index f23e8598..7689e66e 100644 --- a/frontend/src/canvas/tools/transform.ts +++ b/frontend/src/canvas/tools/transform.ts @@ -6,7 +6,7 @@ import { atomsOfSelection, commitDraft, draftFor, objectBounds, selectionEmpty } import type { Draft } from './draft'; export type Mapper = (p: Point) => Point; -export interface MapOpts { rotate?: number; mirror?: 'h' | 'v'; invertWedges?: boolean } +export interface MapOpts { rotate?: number; mirror?: 'h' | 'v'; invertWedges?: boolean; base?: FormChemDocument } export interface Unit { frag?: Id; atoms?: Set; object?: Id; rect: Rect; ref: Point } @@ -63,8 +63,27 @@ function mapObject(d: Draft, obj: DocObject, f: Mapper, o: MapOpts, depth = 0): } if (o.invertWedges) invertWedges(d, obj.id, null); return; - case 'text': - case 'caption': { + case 'caption': + if (obj.target && obj.offset && o.base) { + const was = o.base.objects[obj.target]; + const now = d.doc.objects[obj.target]; + const before = was ? objectBounds(o.base, was) : null; + const after = now ? objectBounds(d.doc, now) : null; + const own = objectBounds(d.doc, obj); + if (before && after && own) { + const top = f([before.x + before.w / 2 + obj.offset[0], before.y + before.h + obj.offset[1]]); + set('offset', [top[0] - (after.x + after.w / 2), top[1] - (after.y + after.h)]); + set('x', top[0] - own.w / 2); + set('y', top[1]); + return; + } + } + { + const r = objectBounds(d.doc, obj); + if (r) boxed(r.x, r.y, r.w, r.h); + } + return; + case 'text': { const r = objectBounds(d.doc, obj); if (r) boxed(r.x, r.y, r.w, r.h); return; @@ -142,10 +161,14 @@ export function mapSelection(d: Draft, sel: Selection, f: Mapper, o: MapOpts = { } if (o.invertWedges) invertWedges(d, fid, atoms); } + const later: DocObject[] = []; for (const oid of sel.objects) { const obj = doc.objects[oid]; - if (obj && !isFragment(obj)) mapObject(d, obj, f, o); + if (!obj || isFragment(obj)) continue; + if (obj.kind === 'caption' && obj.target) later.push(obj); + else mapObject(d, obj, f, { ...o, base: doc }); } + for (const obj of later) mapObject(d, obj, f, { ...o, base: doc }); } export function translateSelection(d: Draft, sel: Selection, dx: number, dy: number): void { From 41d07a8490f0da7d4f581151d6e07cefda1769d9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:31:11 -0500 Subject: [PATCH 093/279] fix(canvas): hit drawn objects by what is drawn (0.5.0) hit.ts treated an arrow's bend in degrees as a length, so a 90 degree curved arrow claimed a box thousands of points wide and swallowed clicks meant for objects under it; arrows now use the rendered box, and arrows, lines, shapes, brackets, orbitals and images are hit on their drawn outline. --- frontend/src/canvas/hit.ts | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/frontend/src/canvas/hit.ts b/frontend/src/canvas/hit.ts index 1a6d701a..deb880c3 100644 --- a/frontend/src/canvas/hit.ts +++ b/frontend/src/canvas/hit.ts @@ -1,4 +1,6 @@ import { bondSpacing, isFragment, resolveStyle, type Bond, type Bounds, type DocObject, type FormChemDocument, type Fragment, type Id, type Page, type Point, type Run, type Style } from '../engine/model'; +import { objectDistance as drawnDistance } from './hit-objects'; +import { objectBox as drawnBox } from './render/bounds'; import { makeSelection } from './selection'; import { selectionKey, type Hit, type Selection } from './types'; @@ -106,11 +108,8 @@ export function objectBounds(doc: FormChemDocument, id: Id, objectBox?: (id: Id) const lh = typeof o.line_spacing === 'number' ? o.line_spacing : m.size * 1.2; return { x: o.x, y: o.y, w: o.w ?? Math.max(m.size * 0.6, m.chars * m.size * 0.55), h: m.lines * lh }; } - case 'arrow': { - const bend = Math.abs(o.bend ?? 0) * Math.hypot(o.x2 - o.x1, o.y2 - o.y1) / 2; - const x = Math.min(o.x1, o.x2) - bend, y = Math.min(o.y1, o.y2) - bend; - return { x, y, w: Math.abs(o.x2 - o.x1) + 2 * bend, h: Math.abs(o.y2 - o.y1) + 2 * bend }; - } + case 'arrow': + return drawnBox(o, doc); case 'plus': { const s = o.size ?? 0.6 * style.bond_length; return { x: o.x - s / 2, y: o.y - s / 2, w: s, h: s }; @@ -147,12 +146,12 @@ export function objectBounds(doc: FormChemDocument, id: Id, objectBox?: (id: Id) } } +const DRAWN_HIT = new Set(['arrow', 'line', 'shape', 'bracket', 'orbital', 'image']); + function objectDistance(doc: FormChemDocument, o: DocObject, p: Point, objectBox?: (id: Id) => Box | null): number { - if (o.kind === 'arrow' && !o.bend) return segmentDistance(p, [o.x1, o.y1], [o.x2, o.y2]).d; - if (o.kind === 'line' && o.points.length > 1) { - let d = Infinity; - for (let i = 1; i < o.points.length; i++) d = Math.min(d, segmentDistance(p, o.points[i - 1], o.points[i]).d); - return d; + if (DRAWN_HIT.has(o.kind)) { + const d = drawnDistance(o, p, doc); + if (Number.isFinite(d)) return d; } const b = objectBounds(doc, o.id, objectBox); return b ? boxDistance(p, b) : Infinity; From 408f5f39ab6fe53385ffd9c718004e9ee4ae8111 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:31:42 -0500 Subject: [PATCH 094/279] feat(canvas): draw the select tool's object handles (0.5.0) The select tool already grabbed arrow ends, bends, line points and the eight box handles, but nothing showed them; the view now draws them with the rotate handle while Select or Lasso holds one object. --- frontend/src/canvas/view.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 8ef7aa92..4186c7ed 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -9,6 +9,7 @@ import { openCanvasMenu } from './context'; import { hitExists, hitTest, NO_HIT, objectBounds, sameHit, styleFor, visibleOrder, type Box } from './hit'; import { EMPTY_SELECTION, isEmpty, prune, sameSelection, selectAllOnPage } from './selection'; import { TextEditor, type TextEditOptions } from './text-editor'; +import { objectHandles } from './tools/handles'; import type { Band, Hit, RenderDisplay, Renderer, Selection, Tool, ToolContext, ToolDef, ToolPointer, Viewport } from './types'; export const PT_PX = 96 / 72; @@ -22,6 +23,8 @@ const WHEEL_ZOOM = 0.006; const CLICK_MS = 420; const CLICK_PX = 5; const HANDLE_STEM = 24; +const OBJECT_HANDLE_PX = 7; +const OBJECT_HANDLE_TOOLS = new Set(['select', 'lasso']); export type { Band }; @@ -609,6 +612,15 @@ export class CanvasView { const r = 4.5; d = `M${x.toFixed(1)} ${(y + r).toFixed(1)}V${(y + HANDLE_STEM).toFixed(1)}M${(x + r).toFixed(1)} ${y.toFixed(1)}A${r} ${r} 0 1 0 ${(x - r).toFixed(1)} ${y.toFixed(1)}A${r} ${r} 0 1 0 ${(x + r).toFixed(1)} ${y.toFixed(1)}Z`; } + if (this.doc_ && this.activated && OBJECT_HANDLE_TOOLS.has(this.toolId)) { + for (const h of objectHandles(this.doc, this.sel)) { + const [x, y] = this.toScreen(h.at); + const s = OBJECT_HANDLE_PX / 2; + d += h.kind === 'bend' + ? `M${(x + s).toFixed(1)} ${y.toFixed(1)}A${s} ${s} 0 1 0 ${(x - s).toFixed(1)} ${y.toFixed(1)}A${s} ${s} 0 1 0 ${(x + s).toFixed(1)} ${y.toFixed(1)}Z` + : `M${(x - s).toFixed(1)} ${(y - s).toFixed(1)}h${2 * s}v${2 * s}h${-2 * s}Z`; + } + } if (this.handlePath.getAttribute('d') !== d) this.handlePath.setAttribute('d', d); } From 67c76299faf566365102a7990169029c6b469fa9 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:31:48 -0500 Subject: [PATCH 095/279] fix(canvas): draw a drawing as soon as it becomes active (0.5.0) setClient marked only the viewport dirty, so a drawing opened from Home (whose snapshot already carries its derived data, so no later event follows) stayed an empty page until the pointer moved over the canvas. --- frontend/src/canvas/view.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 4186c7ed..1a1b1740 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -290,7 +290,7 @@ export class CanvasView { this.activate(); } this.fitIfReady(); - this.viewDirty = true; + this.viewDirty = this.renderDirty = true; this.invalidate(); this.emit('client'); this.emit('selection'); From 4a5d17b51dc81e22d498bfe4dcc6bda4a56cd68e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:32:36 -0500 Subject: [PATCH 096/279] feat(icons): draw the 24 annotation tool icons (0.5.0) The new arrow, symbol, bracket, shape, TLC and orbital tools fell back to the cursor icon in the rail; each now has its own inline currentColor glyph in the 24 box at the shared 1.6 stroke. --- frontend/src/ui/icons.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/frontend/src/ui/icons.ts b/frontend/src/ui/icons.ts index 3af6d9a4..91b2376b 100644 --- a/frontend/src/ui/icons.ts +++ b/frontend/src/ui/icons.ts @@ -277,6 +277,30 @@ export const ICONS: Record = { ring8: ringIcon(8), ringBenzene: benzeneIcon(), atomLabel: L(''), + arrowEquilibrium: L(''), + arrowRetro: L(''), + arrowResonance: L(''), + arrowNogo: L(''), + arrowDashed: L(''), + arrowPlain: L(''), + arrowCurved: L(``), + arrowFishhook: L(''), + equals: L(''), + adductDot: L(``), + bracketRound: L(''), + bracketSquare: L(''), + bracketCurly: L(''), + shapeRoundRect: L(''), + shapeEllipse: L(''), + shapePolygon: ringIcon(5), + tlcPlate: L(``), + orbitalP: L(``), + orbitalS: L(``), + orbitalD: L(``), + orbitalDz2: L(``), + orbitalSp: L(``), + orbitalSigma: L(``), + orbitalPi: L(``), }; export function icon(name: string, size = 16): string { From dff9bc53cbb55aa2873e9a3042ba1ce38eda3d52 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:33:45 -0500 Subject: [PATCH 097/279] docs(format): settle the phase 5 reaction, stoichiometry, arrow, caption and media rules (0.5.0) The engine, the panel and the renderer disagreed or guessed on these points: perception distances, the scale-wins stoichiometry precedence, arc and head geometry, how the five special arrow types draw, attached caption placement, the stoichiometry grid columns and how media bytes enter a drawing. --- docs/FORMAT.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 50920687..6a4fe0cb 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -272,11 +272,11 @@ Built from 0.6.0. An abbreviation atom (`label` `"OTs"`, `expansion` `"e5k2..."` ### caption (built from 0.5.0) -A text object (same fields) attached to a structure: `target` (a fragment or group id it moves with), `offset` (`[dx, dy]` from the target's bounds' bottom centre to the caption's top centre), and `number` for compound numbering: `{ "auto": true, "value": "1a" }`. Renumber compounds rewrites `value` in document order. +A text object (same fields) attached to a structure: `target` (a fragment or group id it moves with), `offset` (`[dx, dy]` from the target's bounds' bottom centre to the caption's top centre), and `number` for compound numbering: `{ "auto": true, "value": "1a" }`. Renumber compounds rewrites `value` in document order. When `target` and `offset` are both present the caption is placed from them and `x`, `y` are a cache that writers keep in step; moving the caption alone rewrites `offset`, and moving its target moves it with no write. ### arrow (built from 0.5.0) -`type`: `forward`, `equilibrium`, `equilibrium_unbalanced`, `reversible`, `resonance`, `retro`, `nogo_cross`, `nogo_slash`, `dashed`, `curved`, `fishhook`, `arc`, `plain`, `fragmentation`, `dissociation`. Geometry: `x1`, `y1` (tail), `x2`, `y2` (head), `bend` (signed arc sweep in degrees, 0 straight, positive bulges to the left of tail to head; `arc` sweeps 15 to 345). Heads: `head` and `tail` each `"full"`, `"half_left"`, `"half_right"`, `"open"`, `"hollow"`, `"none"`; optional `head_length`, `head_width` (points; defaults 6 and 2.5 times the line width), `shorter` (fraction for the unbalanced equilibrium, default 0.6), `line_width`, `dashed`. Anchors: `anchors.tail` and `anchors.head`, each `{ "object": "f...", "atom": "a..." }`, `{ "object": "f...", "bond": "b..." }`, `{ "object": "f...", "atom": "a...", "lone_pair": 0 }` or `{ "object": "f...", "between": ["a...", "a..."] }`; anchored ends follow the chemistry and stop 0.15 bond lengths short. +`type`: `forward`, `equilibrium`, `equilibrium_unbalanced`, `reversible`, `resonance`, `retro`, `nogo_cross`, `nogo_slash`, `dashed`, `curved`, `fishhook`, `arc`, `plain`, `fragmentation`, `dissociation`. Geometry: `x1`, `y1` (tail), `x2`, `y2` (head), `bend` (signed arc sweep in degrees, 0 straight, positive bulges to the left of tail to head; `arc` sweeps 15 to 345, and an absent or zero `bend` on an `arc` arrow draws a 180 degree sweep). Heads: `head` and `tail` each `"full"`, `"half_left"`, `"half_right"`, `"open"`, `"hollow"`, `"none"`; optional `head_length`, `head_width` (points; defaults 6 and 2.5 times the line width; `head_width` is the half width of the head, measured from the shaft), `shorter` (fraction for the unbalanced equilibrium, default 0.6), `line_width`, `dashed`. Anchors: `anchors.tail` and `anchors.head`, each `{ "object": "f...", "atom": "a..." }`, `{ "object": "f...", "bond": "b..." }`, `{ "object": "f...", "atom": "a...", "lone_pair": 0 }` or `{ "object": "f...", "between": ["a...", "a..."] }`; anchored ends follow the chemistry and stop 0.15 bond lengths short. `reversible` is drawn as two parallel full-headed arrows in opposite directions (the equilibrium layout with full heads); `resonance` is one shaft with a full head at each end; `fragmentation` is a bar from tail to head with a short arm at the head, perpendicular to the bar on its left, carrying the head; `dissociation` is a forward arrow with a short bar across its tail. ### plus (built from 0.5.0) @@ -296,12 +296,14 @@ A text object (same fields) attached to a structure: `target` (a fragment or gro ### table (built from 0.5.0) -`x`, `y`, `cols` (column widths), `rows` (`[ { "id": "l...", "h": 18, "cells": [ { "runs": [...] }, { "object": "f..." } ] } ]`; a cell holds runs or names a fragment object that it owns), `padding` (default 3), `header` (true styles the first row), `borders` (`"all"`, `"outer"`, `"none"`), `auto_grow`. Optional `stoich` (`{ "reaction": "r...", "step": "r..." }`, built from 0.5.0) makes the table a stoichiometry grid for that reaction step: its rows are written from the step's `stoich` data and the derived masses whenever either changes, and editing a cell edits the step's data, not the runs. +`x`, `y`, `cols` (column widths), `rows` (`[ { "id": "l...", "h": 18, "cells": [ { "runs": [...] }, { "object": "f..." } ] } ]`; a cell holds runs or names a fragment object that it owns), `padding` (default 3), `header` (true styles the first row), `borders` (`"all"`, `"outer"`, `"none"`), `auto_grow`. Optional `stoich` (`{ "reaction": "r...", "step": "r..." }`, built from 0.5.0) makes the table a stoichiometry grid for that reaction step: the window draws it live from the step's `stoich` data and the derived masses with the columns Compound, Role, MW, Equiv, mmol, Mass (mg), Volume (mL) (`cols` gives their widths when it has seven entries), and editing a cell edits the step's data, not the runs. Its `rows` are the written copy for readers that do not compute (exports, agents); they are rewritten when the grid is refreshed (inserting the grid again for a step that already has one refreshes it in place), and the engine's refresh writes the columns Compound, Formula, Role, MW, Equiv, Amount, Mass, Volume, Isolated, Yield. ### image (built from 0.5.0) `media` (a media id), `x`, `y`, `w`, `h`, `rot`, `crop` (`{ "l": 0, "t": 0, "r": 0, "b": 0 }` as fractions), `opacity`. +Media bytes reach a drawing in two steps. `POST /api/documents/{id}/media` (multipart field `file`, up to 50 MB, PNG, JPEG, GIF, WebP or SVG recognised from the bytes, anything else 415) keeps the bytes in the open drawing under a fresh `m` id and answers `{ "id": "m...", "media": { "name", "mime", "bytes", "w", "h", "sha256" } }` (`w` and `h` in pixels when the engine can read them); it does not change document.json. The window then commits one transaction that sets `media[id]` to that record and adds the image object, so placing a picture is one undo step. `GET /api/documents/{id}/media/{media_id}` serves the bytes with their mime type. Bytes whose id is not listed in `media` when the drawing is saved are not written to the package. + ### group (built from 0.4.0) `children` (object ids, back to front; at least one), `integral` (true: members cannot be selected one by one). A group's members are not in any page `order`. @@ -325,6 +327,8 @@ Built from 0.5.0. `page.reactions` lists reactions; each is `{ "id": "r...", "st `arrow` is the arrow object the step is bound to. Roles are object ids on the same page. With `explicit` false the roles were inferred from geometry (left of the tail: reactants; right of the head: products; in the arrow's band above or below: agents, and text there: conditions) and are recomputed when objects move; with `explicit` true the person or an agent set them and they are kept. Plus signs carry no role. Products of one step may be reactants of the next. +Inference measures along the arrow's shaft: an object is an agent or condition when its centre lies between the tail and the head and it comes within 1.5 bond lengths of the shaft; reactants and products must come within 2.5 bond lengths of the shaft's line and may overlap the tail or head by 0.5 bond lengths. Walking away from the arrow, the nearest structure takes the role and the next one joins only across a plus sign or a gap under 1 bond length. A retrosynthetic arrow swaps the sides; resonance, curved, fishhook, arc, plain, fragmentation and dissociation arrows are not steps. A step read from a reaction file has `explicit` true. + A step may carry `stoich` (built from 0.5.0), the person's amounts for a stoichiometry grid: ```json @@ -334,6 +338,8 @@ A step may carry `stoich` (built from 0.5.0), the person's amounts for a stoichi Keys of `components` are reactant, agent or product object ids of the step. Each component may give `equiv`, `mass_mg`, `volume_ml`, `density_g_ml`, `conc_m` (mol per litre, for solutions), `purity_pct` (default 100), `mw` (overrides the derived molecular weight, for example for a salt or hydrate) and `label`. Only what the person typed is stored; moles, the amounts implied by `equiv` and `scale_mmol`, the limiting reagent when `limiting` is absent (the reactant with the fewest moles divided by its coefficient), the theoretical yield of `product` and the percent yield from `isolated_mg` are computed from these values and the derived molecular weights, and are never stored. +When `scale_mmol` is present it is the reference amount (mmol of the limiting reagent at one equivalent) and wins over the limiting reagent's own typed amount; otherwise the reference is the limiting reagent's typed amount divided by its `equiv` (default 1). A window that lets the person type an amount on the limiting reagent removes `scale_mmol` in the same transaction, and typing `scale_mmol` removes the limiting reagent's typed `mass_mg`, `volume_ml` and `equiv`. Typing one of `mass_mg`, `volume_ml` or `equiv` removes the other two from that component. + ## The derived cache What the engine computes from a fragment is engine output, never user data. It is not part of document.json and is never written into a `.fchem` package; it is rebuilt after load and broadcast after every transaction, keyed by fragment id and the document revision it was computed at. From 812d34b71b1f2be1892f2cc23eecb742c029e353 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:34:12 -0500 Subject: [PATCH 098/279] feat(derive): add each reaction step's balance check to the derived cache (0.5.0) The check is cheap (about a millisecond for a two plus two step), so the engine now broadcasts it with every derive under a top-level reactions slot, and the contract and the window model describe it. --- backend/app/services/chem/derive.py | 23 ++++++++++++++++++++++- docs/FORMAT.md | 1 + frontend/src/engine/model.ts | 10 +++++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/backend/app/services/chem/derive.py b/backend/app/services/chem/derive.py index a245301d..ab305973 100644 --- a/backend/app/services/chem/derive.py +++ b/backend/app/services/chem/derive.py @@ -7,6 +7,8 @@ from app.services.chem import ENGINE, ids, mass, perceive, warning CACHE_SIZE = 2048 +REACTION_CHECKS = 64 +CHECK_FIELDS = ("balanced", "elements", "charge", "mass", "warnings") ATOM_FIELDS = ("element", "charge", "isotope", "radical", "hydrogens", "label", "expansion", "generic", "rgroup", "map", "query", "ignore_warnings") BOND_FIELDS = ("a", "b", "order", "stereo", "query", "topology") @@ -85,16 +87,35 @@ def fragments_of(doc: dict) -> dict[str, dict]: return {k: o for k, o in (doc.get("objects") or {}).items() if isinstance(o, dict) and o.get("kind") == "fragment"} +def reaction_checks(doc: dict) -> dict: + from app.services.chem import balance + out: dict = {} + for page in doc.get("pages") or []: + for reaction in page.get("reactions") or []: + for step in reaction.get("steps") or []: + if len(out) >= REACTION_CHECKS or not isinstance(step, dict) or not isinstance(step.get("id"), str): + continue + try: + found = balance.check(doc, step) + except Exception: + continue + out[step["id"]] = {k: found[k] for k in CHECK_FIELDS if k in found} + return out + + def derive_document(doc: dict, rev: int = 0, only: list[str] | None = None) -> dict: expansions = doc.get("expansions") or {} frags = fragments_of(doc) chosen = frags if only is None else {k: v for k, v in frags.items() if k in set(only)} - return { + out = { "doc": doc.get("id", ""), "rev": rev, "engine": ENGINE, "fragments": {fid: derive_fragment(f, expansions, rev) for fid, f in chosen.items()}, } + if only is None: + out["reactions"] = reaction_checks(doc) + return out def clear_cache() -> None: diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 6a4fe0cb..f9b44c4b 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -357,6 +357,7 @@ What the engine computes from a fragment is engine output, never user data. It i | `aromatic_rings` | lists of atom ids, one per aromatic ring | | `cip` | map of atom or bond id to `R`, `S`, `r`, `s`, `E`, `Z`, `M`, `P` (built from 0.6.0) | | `warnings` | `[ { "code": "...", "atoms": [], "bonds": [], "text": "..." } ]` | +| `reactions` | map of reaction step id to the step's balance check: `{ "balanced": true, "elements": [ { "element": "C", "left": 4, "right": 4, "diff": 0 } ], "charge": { "left": 0, "right": 0, "diff": 0 }, "mass": { "left": 106.12, "right": 106.12, "diff": 0 }, "warnings": [] }` (built from 0.5.0). This slot sits beside `fragments` at the top level of the derived message, not inside a fragment; it counts reactants and products with their coefficients (agents are not counted) and covers at most 64 steps | The window draws immediately from its own default-valence table and ring perception, and replaces its guesses with the engine's values when they arrive for the current revision. diff --git a/frontend/src/engine/model.ts b/frontend/src/engine/model.ts index 5e4409ff..67b06578 100644 --- a/frontend/src/engine/model.ts +++ b/frontend/src/engine/model.ts @@ -372,7 +372,15 @@ export interface DerivedFragment { cip?: Record; warnings?: ChemWarning[]; } -export interface Derived { doc: Id; rev: number; fragments: Record } +export interface BalanceSide { left: number; right: number; diff: number } +export interface DerivedReactionCheck { + balanced: boolean; + elements: Array<{ element: string } & BalanceSide>; + charge: BalanceSide; + mass: BalanceSide; + warnings: ChemWarning[]; +} +export interface Derived { doc: Id; rev: number; fragments: Record; reactions?: Record } export const ELEMENTS: readonly string[] = [ 'H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', From dc4c9752497496c49d7866454a220a77f7b52a80 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:41:09 -0500 Subject: [PATCH 099/279] fix(render): move only the nodes whose z-order changed (0.5.0) Any change to the page order (adding an arrow, a caption or a template, or a z-order command) re-appended every fragment, text and object node in all four layers, which a MutationObserver showed as the whole drawing being detached and reattached; the layers now insert only the nodes that are out of place. --- frontend/src/canvas/render/renderer.ts | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/frontend/src/canvas/render/renderer.ts b/frontend/src/canvas/render/renderer.ts index 4bfdb901..4f44c334 100644 --- a/frontend/src/canvas/render/renderer.ts +++ b/frontend/src/canvas/render/renderer.ts @@ -123,6 +123,14 @@ function allCrossings(frag: Fragment): Map> { const sameList =(a: readonly unknown[], b: readonly unknown[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); +function inOrder(parent: Element, want: readonly Element[]): void { + let next: ChildNode | null = parent.firstChild; + for (const n of want) { + if (n === next) { next = n.nextSibling; continue; } + parent.insertBefore(n, next); + } +} + export function shownStyle(style: Style, d: RenderDisplay | undefined): ShownStyle { if (!d) return style; const out: ShownStyle = { ...style }; @@ -596,17 +604,22 @@ export function createRenderer(): FormChemRenderer { } if (!sameList(ids, order)) { order = ids; + const bonds: Element[] = [], atoms: Element[] = [], texts_: Element[] = [], objects: Element[] = []; for (const id of ids) { const f = frags.get(id); if (f) { - layers.bonds.appendChild(f.gBonds); - layers.atoms.appendChild(f.gAtoms); + bonds.push(f.gBonds); + atoms.push(f.gAtoms); } const t = textNodes!.nodes.get(id); - if (t) layers.text.appendChild(t.node); + if (t) texts_.push(t.node); const g = objNodes!.nodes.get(id); - if (g) layers.objects.appendChild(g.node); + if (g) objects.push(g.node); } + inOrder(layers.bonds, bonds); + inOrder(layers.atoms, atoms); + inOrder(layers.text, texts_); + inOrder(layers.objects, objects); } if (page) syncPage(d, page); syncOverlays(state, d); From 39fed855e779b9c4cfac6c1f6831ac45e6554f25 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:41:09 -0500 Subject: [PATCH 100/279] fix(tools): keep an attached caption's x, y cache in step with its target (0.5.0) Moving a structure moved its caption on screen but left the stored x, y behind, so marquee selection, alignment and anything else reading the cache found the caption where it used to be; the move now rewrites the cache in the same transaction. --- docs/FORMAT.md | 2 +- frontend/src/canvas/tools/transform.ts | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/FORMAT.md b/docs/FORMAT.md index f9b44c4b..5370c1cf 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -272,7 +272,7 @@ Built from 0.6.0. An abbreviation atom (`label` `"OTs"`, `expansion` `"e5k2..."` ### caption (built from 0.5.0) -A text object (same fields) attached to a structure: `target` (a fragment or group id it moves with), `offset` (`[dx, dy]` from the target's bounds' bottom centre to the caption's top centre), and `number` for compound numbering: `{ "auto": true, "value": "1a" }`. Renumber compounds rewrites `value` in document order. When `target` and `offset` are both present the caption is placed from them and `x`, `y` are a cache that writers keep in step; moving the caption alone rewrites `offset`, and moving its target moves it with no write. +A text object (same fields) attached to a structure: `target` (a fragment or group id it moves with), `offset` (`[dx, dy]` from the target's bounds' bottom centre to the caption's top centre), and `number` for compound numbering: `{ "auto": true, "value": "1a" }`. Renumber compounds rewrites `value` in document order. When `target` and `offset` are both present the caption is placed from them and `x`, `y` are a cache that writers keep in step; moving the caption alone rewrites `offset`, and moving its target moves it with the target while the same transaction refreshes `x`, `y`. ### arrow (built from 0.5.0) diff --git a/frontend/src/canvas/tools/transform.ts b/frontend/src/canvas/tools/transform.ts index 7689e66e..6c177acc 100644 --- a/frontend/src/canvas/tools/transform.ts +++ b/frontend/src/canvas/tools/transform.ts @@ -169,6 +169,18 @@ export function mapSelection(d: Draft, sel: Selection, f: Mapper, o: MapOpts = { else mapObject(d, obj, f, { ...o, base: doc }); } for (const obj of later) mapObject(d, obj, f, { ...o, base: doc }); + for (const c of Object.values(doc.objects)) { + if (c.kind !== 'caption' || !c.target || !c.offset || d.doc.objects[c.id] !== c) continue; + const was = doc.objects[c.target]; + const now = d.doc.objects[c.target]; + const before = was ? objectBounds(doc, was) : null; + const after = now ? objectBounds(d.doc, now) : null; + const own = objectBounds(doc, c); + if (!before || !after || !own || (before.x === after.x && before.y === after.y && before.w === after.w && before.h === after.h)) continue; + const cx = after.x + after.w / 2 + c.offset[0]; + d.push({ op: 'set', path: objectPath(c.id, 'x'), value: cx - own.w / 2 }); + d.push({ op: 'set', path: objectPath(c.id, 'y'), value: after.y + after.h + c.offset[1] }); + } } export function translateSelection(d: Draft, sel: Selection, dx: number, dy: number): void { From 67cbd78fadf2a005ac2460951e7963544cc0d307 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:47:13 -0500 Subject: [PATCH 101/279] docs(changelog): describe reactions and annotations in 0.5.0 (0.5.0) The 0.5.0 section lists what a person can now draw and do with reactions, stoichiometry, templates, Find and Rulers, with the known gaps in the same plain words as earlier versions. --- CHANGELOG.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9df4c667..3e3ec4b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,57 @@ Versions follow `v*.*.*` with dots. Dates are US Eastern. +## 0.5.0 ยท 2026-12-03 + +Reactions and annotations: draw a scheme with arrows, plus signs and conditions, and FormChem reads it as a reaction, maps its atoms, checks its balance and works out the amounts. + +### New + +- Reaction arrows of every kind: forward, equilibrium (also unbalanced), reversible, resonance, retrosynthetic, no-go, dashed, plain, fragmentation and dissociation, with full, half, open or hollow heads at either end. `Shift` snaps the angle to 15 degrees and `Alt` draws the arrow's other kind. +- Electron-pushing and fishhook arrows start on an atom, a lone pair or a bond and end on an atom, a bond or between two atoms where a new bond forms. They bulge away from the structure and follow it when it moves. +- Plus, equals and adduct dot signs that snap to the centre line of the structure beside them. +- Round, square and curly brackets. A bracket dragged around a repeat unit with two crossing bonds is labelled `n`; double-click a bracket to change its label. +- Rectangles, rounded rectangles, ellipses, polygons, lines and smooth polylines, with dashes, solid or gradient fills, opacity and shadows. +- Tables, TLC plates with lanes, spots and Rf values (click a plate to add a spot), and s, p, d, dz2, sp, sigma and pi orbitals that can sit on an atom. +- Insert > Image places a PNG, JPEG, GIF, WebP or SVG picture; it is saved inside the `.fchem` file. +- Captions attach to a structure and move with it; `Ctrl`-click with the caption tool adds the next compound number in bold. +- The selection tool shows handles: drag an arrow's ends or its bend, a line's points, or the eight handles of a box to resize it. +- Arrange has Bring to Front, Bring Forward, Send Backward, Send to Back, Group (`Ctrl+G`) and Ungroup (`Ctrl+Shift+G`). A click on a member selects its group; `Alt`-click or a double-click reaches the member. +- Reaction > Perceive Reactions reads the reactants, products, reagents and conditions from where they sit around each arrow, including schemes of several steps. +- Map Atoms numbers the reactant atoms onto the product atoms and marks the bonds broken, formed and changed; Clear Atom Mapping removes the numbers. +- Check Balance shows the element, charge and mass balance of a step and suggests coefficients or a missing co-product such as water or HCl; Balance Reaction applies the coefficients. +- The Stoichiometry panel (View or Reaction > Stoichiometry Panel): type a mass, a volume with its density, a solution's concentration, equivalents or a scale, and read the moles, the limiting reagent, the theoretical yield and the percent yield. Insert Stoichiometry Table puts the grid on the page, and inserting it again refreshes the same table. +- Copy a reaction as reaction SMILES or RXN, export it to a file, and Insert Reaction from Clipboard to lay out a pasted reaction as a drawn scheme. RXN files and CML or CDXML files with a reaction open as drawn schemes, with their conditions line kept. +- A template library of 206 original templates in nine categories (rings, polycycles, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and solvents, glassware), from Insert > Template and the Templates section on Home. Your own templates go in the `templates` folder of the FormChem data folder. +- Edit > Find looks for text in the drawing, steps through the matches with next and previous, and replaces them. +- View > Show Rulers shows rulers along the canvas, with guides you drag out of them. +- Agents get four reaction tools: `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`. + +### Improved + +- The tool rail has new groups with their own icons: Arrows (`W`), Symbols (`P`), Brackets (`K`), Shapes (`G`), Table, TLC, Image and Orbitals (`O`). +- Arrows, lines and outlined shapes are picked by what is drawn, so a click near a curved arrow no longer grabs it from far away. + +### Fixed + +- A drawing opened from Home stayed blank until the pointer moved over the canvas. + +### Known issues + +- Set Reaction Roles arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing. +- When a structure is the product of one step and the reactant of the next, mapping the second step replaces the first step's map numbers. +- The balance check counts reactants and products only, so a step whose atoms come from a reagent drawn above the arrow reads as unbalanced. +- A `.smi` file holding reaction SMILES does not open as a reaction; paste its text with Insert Reaction from Clipboard. +- `Enter` does not finish a polyline; double-click or click its first point. +- Templates land in the middle of the view and can overlap what is there, and cannot yet be fused onto an atom or a bond. Insert > Image puts the picture's corner, not its centre, in the middle of the view. + +### Under the hood + +- Every drawn object kind goes through one registry in the renderer, and a change of stacking order moves only the nodes whose place changed. +- The engine reads reactions with RDKit and maps atoms with Indigo. The window and the engine work out stoichiometry by one rule: a typed scale wins over the limiting reagent's own amount. +- The chemistry the engine sends after each change now carries the balance check of every reaction step. +- The reaction routes, the stoichiometry rules and the template format are documented beside the drawing format. + ## 0.4.0 ยท 2026-12-02 You can draw. FormChem now has its drawing canvas, so structures can be built with the mouse and the keyboard and look ready for a journal. From 71dbccd6f0842c954f29f74fe6816cbb0a6bcc07 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:48:24 -0500 Subject: [PATCH 102/279] docs(frontend): log the 0.5.0 object renderer, anchors, bounds and hit testing (0.5.0) The registry, the arrow curve model, anchor resolution, the keyed z-order move and drawn-outline hit testing carry no comments in code, so their reasons are recorded here by file and symbol. --- frontend/HASHOUT_LOG.md | 59 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index fbe3e265..ce53220d 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # frontend HASHOUT_LOG -Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.4.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, and from 0.4.0 the canvas: renderer, tools, view and tool rail. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.5.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -18,12 +18,18 @@ src/extensions/ host.ts and the vendored host-bridge.ts src/i18n/ index.ts, keys/part00.json, keys/part01.json, locales// (26 languages) src/engine/ model.ts and ops.ts (the format contract, docs/FORMAT.md), client.ts (one document mirror), session.ts src/chem/ graph, elements, label-text, valence, rings, formula (what the window draws without the engine) -src/canvas/ types.ts (contract), view.ts, hit.ts, selection.ts, text-editor.ts, context.ts, geom.ts, - render/ (SVG renderer), tools/ (every tool, hover keys, transforms) +src/canvas/ types.ts (contract), view.ts, hit.ts, hit-objects.ts, selection.ts, text-editor.ts, context.ts, geom.ts, + render/ (SVG renderer; objects.ts is the object kind registry, one module per kind, anchors.ts, + paint.ts, bounds.ts), tools/ (every tool, hover keys, transforms, handles.ts, objects.ts) +src/chem/stoich.ts stoichiometry for a reaction step (the window's one source), stoich-ops.ts for typed cells +src/engine/reactions-api.ts typed client for the engine's reaction routes +src/app/ also object-commands.ts (z-order, group, align) and reaction-commands.ts (the Reaction menu) +src/ui/ also stoich-panel.ts, template-dialog.ts, template-thumb.ts, home-templates.ts src/app/ also documents.ts (DocumentActions), canvas.ts (mountCanvas), canvas-commands.ts src/ui/ also tool-rail.ts public/fonts/ Arimo and Tinos (SIL OFL 1.1) with their licences -src/styles/ tokens.css (the only z-index source), base.css, shell.css, canvas.css, canvas-view.css, tool-rail.css +src/styles/ tokens.css (the only z-index source), base.css, shell.css, canvas.css, canvas-view.css, tool-rail.css, + stoich.css, templates.css public/ favicon.svg, manifest.webmanifest, splash.html index.html pre-paint script: theme, overlay title bar, native menus, dock reservation src-tauri/src/ main.rs (windows, chrome), traffic_lights.rs, reveal.rs, engine_start.rs @@ -140,6 +146,15 @@ assets/ formchem_mark.svg, icon_src/build.py, icon set 105. New drawings take the default style preset ยท app/documents.ts 106. The live view hides the renderer's page ยท styles/canvas-view.css 107. 150 new strings in part03.json ยท i18n/keys/part03.json +108. One registry draws every object kind ยท canvas/render/objects.ts, paint.ts, renderer.ts +109. Node specs nest children ยท canvas/render/svg.ts +110. Arrows are one curve model ยท canvas/render/arrow.ts +111. Anchors resolve against the drawn chemistry ยท canvas/render/anchors.ts, atom.ts +112. Brackets, shapes, lines, TLC plates and orbitals ยท canvas/render/bracket.ts, shape.ts, line.ts, tlc.ts, orbital.ts +113. Images draw from a media cache with a placeholder ยท canvas/render/image.ts +114. Bounds without a renderer ยท canvas/render/bounds.ts, group.ts +115. A z-order change moves only the nodes out of place ยท canvas/render/renderer.ts inOrder +116. Objects are hit by what is drawn ยท canvas/hit-objects.ts, canvas/hit.ts ## 1. Dependencies are the template's, nothing more ยท _v0.1.0 (package.json) @@ -569,6 +584,42 @@ The renderer draws a page rectangle for export, and in the live view it painted `./formchem i18n scan --write` wrote part03.json for the canvas, tool, menu and command strings (part02.json holds the 23 document and Analysis strings of 0.3.0). The locales still need the translations for part02 and part03; none were written by hand here. +## 108. One registry draws every object kind ยท _v0.5.0 (canvas/render/objects.ts, paint.ts, renderer.ts) + +`OBJECT_KINDS` maps each object kind to `{ view, deps?, derived? }`. A view takes the object and an `ObjectCtx` (the document, its style, the drawn chemistry from `docChem(doc)`, a `boxOf(id)` for other objects and the media cache) and returns `{ specs, box }`: keyed node specs and the drawn bounds. The renderer has one `objects` layer between `page` and `bonds`, so filled shapes and pictures sit behind structures and an arrow placed after a structure in z-order still stays under its labels; text and captions go through the same registry into the text layer. A kind is re-laid out only when the object record, the style, the font epoch or its `deps` change (an anchored arrow lists the fragments it points at, a caption its target), and the nodes are then patched, never rebuilt. A view that throws on malformed imported data draws nothing for that object instead of stopping the frame. `paint.ts` holds what the kinds share: `dashArray`, `strokeAttrs`, `fillPaint` (solid and linear gradient), `rotation`, `withRotation`, `rotatedBox` and `label` (one line of text with its box). Object strokes reuse the hairline class `fc-ln`, so no CSS was added. + +## 109. Node specs nest children ยท _v0.5.0 (canvas/render/svg.ts) + +Gradients and clip paths are elements inside the node that uses them, so `NodeSpec.kids` carries nested children and `patch` walks them recursively with the same keyed rules. Without it a gradient fill or a cropped picture would have needed a `defs` layer and global ids, which collide between drawings and break when a node is moved between layers. + +## 110. Arrows are one curve model ยท _v0.5.0 (canvas/render/arrow.ts) + +Every arrow is a line or a circular arc built from its tail, head and signed `bend` (`bentCurve`), with `subCurve`, `offsetCurve`, `reverseCurve` and `curveSamples` on that one model, so all 15 types bend the same way and heads sit on the curve's tangent. Heads follow FORMAT's defaults (length 6 times the line width, half width 2.5 times) with a notch at 75 percent of the length. Equilibrium is two shafts at the style's bond spacing (the clean-room acceptance asks for exactly the double bond spacing): the upper carries `head`, the lower, reversed, carries `tail`, both `half_left` by default so the barbs face out; unbalanced shortens the lower one to `shorter` (0.6), centred. Retro is two shafts at the larger of the bond spacing and 2.5 line widths ending on an open chevron. `reversible`, `resonance`, `fragmentation` and `dissociation` draw as FORMAT now states; an `arc` with no bend sweeps 180 degrees. + +## 111. Anchors resolve against the drawn chemistry ยท _v0.5.0 (canvas/render/anchors.ts, canvas/render/atom.ts) + +`anchorPoint` turns an anchor into a point from the drawn geometry, not the stored coordinates alone: an atom anchor is the atom centre, a bond anchor the bond midpoint, a `between` anchor the midpoint of the two atoms (a forming bond), and a lone pair anchor the pair's drawn centre, which is why `AtomView.pairs` now keeps the centres the atom view placed. When an atom shows no pairs, the lone pair end takes a free direction away from its neighbours. `arrowEnds` trims anchored ends along the curve by 0.15 bond lengths of the anchored fragment, capped at 40 percent of the arrow, so short mechanism arrows keep a visible shaft. `anchorDeps` lists the fragments an arrow depends on, so moving an atom re-lays out only the arrows anchored to its fragment; a MutationObserver showed one transaction moving an anchored atom produced attribute changes on that atom's label, the arrow and nothing else. + +## 112. Brackets, shapes, lines, TLC plates and orbitals ยท _v0.5.0 (canvas/render/bracket.ts, shape.ts, line.ts, tlc.ts, orbital.ts, plus.ts) + +Brackets put `label` (else `repeat` for a multiple group, else a semantic tag, `n` for `sru`) at the lower right, italic when it is one lower case letter, and `charge_label` with `connect` (unless `ht`) at the upper right. Shapes draw `round_rect` with a radius of 10 percent of the shorter side by default, regular polygons of 3 to 12 sides with a flat bottom for even counts, and `path` in the box's own space; fills, opacity, drop shadow and rotation come from paint.ts. Smooth lines convert a Catmull-Rom spline to cubic Beziers so the curve passes through every stored point, and `linePoints` gives the sampled outline the hit test uses. TLC lanes sit at (i + 1) / (n + 1) of the plate width, the rule the TLC tool uses, so no lane position is stored; Rf labels go beside a spot, or once per value at the plate's right edge when a lane is too narrow, so labels never cover the next lane. Orbitals fill the phase lobe solid and the other at 30 percent (`filled`), one lobe only (`shaded`) or none (`hollow`); `phase` swaps them, and an orbital with `atom` centres on that atom every frame. The plus kind draws plus, equals, dot and bullet at 0.6 bond lengths unless `size` is set. + +## 113. Images draw from a media cache with a placeholder ยท _v0.5.0 (canvas/render/image.ts) + +`MediaCache` loads each media id once from `/api/documents/{doc}/media/{id}` (`setMediaUrl(fn)` swaps the URL for a desktop shell) and asks for a new frame when a load ends. Until the picture has loaded the image draws a dashed box with a cross in its own size (and the media name once loading failed), so nothing jumps when it arrives. Crop is a clip path on the image, opacity and rotation are attributes. The engine's media routes landed at integration (backend log 72). + +## 114. Bounds without a renderer ยท _v0.5.0 (canvas/render/bounds.ts, canvas/render/group.ts) + +`objectBox(obj, doc)` and `objectBoxById(doc, id)` run the same view code as drawing, cached per object and document reference, so tools, hit testing and Arrange get the box that is drawn, bracket labels, TLC labels, arrow arcs and rotation included, without a renderer. Fragments use their atom positions. A group draws nothing (its members draw themselves, integral or not) and its box is the union of its children. + +## 115. A z-order change moves only the nodes out of place ยท _v0.5.0 (canvas/render/renderer.ts inOrder) + +When the page order changed (a new arrow, a caption, a template, any z-order command), the renderer re-appended every fragment, text and object node in all four layers, which a MutationObserver in the running app showed as the whole drawing detached and attached again. `inOrder(parent, want)` walks the wanted order and calls `insertBefore` only for a node that is not already next, so drawing a curved arrow now touches only the hover marks and a Ctrl-click caption removes no node at all. This is the zero-flash rule applied to stacking. + +## 116. Objects are hit by what is drawn ยท _v0.5.0 (canvas/hit-objects.ts, canvas/hit.ts) + +`hitObject(obj, p, tol, doc?)` answers a distance in points within `tol`, else null; `objectDistance` gives the raw distance. Arrows measure to shafts, marks and heads (inside a head is 0); lines to their sampled outline; a filled shape is hit anywhere inside and an unfilled one only on its outline, with rotation honoured; brackets on their two sides; orbitals by a circle of radius `size`; images by their rotated rectangle; groups by their nearest child. hit.ts calls it for those kinds and keeps its own rules for chemistry. The old arrow box in hit.ts read `bend` (degrees) as a length, so a 90 degree arrow 60 pt long claimed a 2700 pt box and took clicks meant for the shapes under it; arrows now fall back to the rendered box from bounds.ts. + ## Not verified at 0.4.0 The lasso tool in the real window (its band path is the marquee's), touch pinch and Safari gesture events, the Tauri webview (dialogs, native accelerators, `contenteditable="plaintext-only"` in older WebKit), light themes, the rotate handle on dark pages, extensions against a real package, and socket drop with resync during an edit. The title field collapses to a sliver at 1280 px wide because the menu bar takes the room; it predates this work. From 4b500672e625cc13c66e9753cddbe3b4565f21fd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:49:01 -0500 Subject: [PATCH 103/279] docs(frontend): log the 0.5.0 annotation tools, handles, captions and object commands (0.5.0) The gesture shape, the arrow and bracket rules, the caption cache, the handle drag and the per-container z-order are decisions the tools make without comments, so the log holds them. --- frontend/HASHOUT_LOG.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index ce53220d..bcba867a 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -155,6 +155,14 @@ assets/ formchem_mark.svg, icon_src/build.py, icon set 114. Bounds without a renderer ยท canvas/render/bounds.ts, group.ts 115. A z-order change moves only the nodes out of place ยท canvas/render/renderer.ts inOrder 116. Objects are hit by what is drawn ยท canvas/hit-objects.ts, canvas/hit.ts +117. Annotation tools share one gesture shape ยท canvas/tools/objects.ts BoxTool +118. Reaction arrows and electron-pushing arrows ยท canvas/tools/arrow.ts, curved.ts +119. Plus signs, brackets, tables, TLC plates and orbitals ยท canvas/tools/plus.ts, bracket.ts, table.ts, tlc.ts, orbital.ts, shape.ts, line.ts +120. The image tool and its swappable uploader ยท canvas/tools/image.ts +121. Captions are placed from their target; x, y are a cache ยท canvas/render/caption.ts, canvas/tools/caption.ts, transform.ts +122. Handles belong to the select tool and are drawn by the view ยท canvas/tools/handles.ts, select.ts, canvas/view.ts +123. A click selects the outermost group ยท canvas/tools/select.ts, draft.ts +124. Object commands work per container ยท app/object-commands.ts ## 1. Dependencies are the template's, nothing more ยท _v0.1.0 (package.json) @@ -620,6 +628,38 @@ When the page order changed (a new arrow, a caption, a template, any z-order com `hitObject(obj, p, tol, doc?)` answers a distance in points within `tol`, else null; `objectDistance` gives the raw distance. Arrows measure to shafts, marks and heads (inside a head is 0); lines to their sampled outline; a filled shape is hit anywhere inside and an unfilled one only on its outline, with rotation honoured; brackets on their two sides; orbitals by a circle of radius `size`; images by their rotated rectangle; groups by their nearest child. hit.ts calls it for those kinds and keeps its own rules for chemistry. The old arrow box in hit.ts read `bend` (degrees) as a length, so a 90 degree arrow 60 pt long claimed a 2700 pt box and took clicks meant for the shapes under it; arrows now fall back to the rendered box from bounds.ts. +## 117. Annotation tools share one gesture shape ยท _v0.5.0 (canvas/tools/objects.ts BoxTool) + +Every annotation tool previews with `client.preview` and commits once on pointer up through `commitDraft`, so one gesture is one undo step; Escape cancels any gesture and a tool change cancels too. The preview keeps one object id per gesture (`this.oid`), so the renderer patches one keyed node during a drag instead of creating one per pointer move. `BoxTool` is the shared drag-to-size tool: Shift makes it square, Alt draws from the centre, and a click places a default box (3 bond lengths; rectangles 3 by 2.25). New objects are not selected after creation, as with the bond, ring and text tools. Helpers in objects.ts: `snapEnd` (15 degrees), `boxFrom`, `fragmentOfHit`, `fragmentAt`, `outermostGroup`, `ensureMediaMap`, and `clicks(p)`, which reads the view's click count through a cast because `ToolPointer.clicks` is not in canvas/types.ts yet. + +## 118. Reaction arrows and electron-pushing arrows ยท _v0.5.0 (canvas/tools/arrow.ts, canvas/tools/curved.ts) + +Arrows are free by default and Shift snaps to 15 degrees (the task brief; the clean-room text has snap by default with Alt free, and the brief won). Alt picks the other kind (`ARROW_KINDS`): forward to dashed, equilibrium to unbalanced, resonance to reversible, no-go cross to slash. A click places a 4 bond length arrow. Forward, dashed, resonance, reversible and plain write `head` and `tail` explicitly; equilibrium, retro and no-go leave their heads to the renderer by `type`. The rail's arrow key is W because A is the atom label tool in this build. Curved arrows start on an atom, a bond or (when the atom shows lone pairs) lone pair 0; Ctrl or Cmd at the press anchors the atom instead. The head lands on an atom, a bond, or empty space within 0.35 bond lengths of the midpoint of two atoms of one fragment 0.5 to 3 bond lengths apart, which gives a `between` anchor for a forming bond. The bend is 90 degrees, bulging away from the nearest atom near the chord's midpoint that is not an anchor; Alt flips it. The fishhook barb is `half_left`, Shift gives `half_right`. Lone pair index 0 is a guess: the renderer decides where pairs sit. + +## 119. Plus signs, brackets, tables, TLC plates and orbitals ยท _v0.5.0 (canvas/tools/plus.ts, bracket.ts, table.ts, tlc.ts, orbital.ts, shape.ts, line.ts) + +A plus sign snaps its centre to the vertical centre of a fragment, group, text, caption or image within 3 bond lengths across and 0.75 down (`reactionLine`); Alt places it exactly. A bracket drag records `fragment` and `atoms` when the box holds atoms of one fragment, and exactly two crossing bonds make it `semantic: "sru"` with `label: "n"`; a click on a structure brackets the whole fragment 0.4 bond lengths outside its atoms, and a double-click on a bracket edits its label (empty removes it). Tables use 48 by 18 pt cells fitted to the drag (1 to 50 each way), filling the box exactly; Shift sets `header`. TLC lanes are max(1, floor(width / 20 pt)), the reading of the spec's "one lane for a narrow plate, plus one per 20 pt"; a click on a plate adds a spot to the nearest lane with Rf rounded to 0.01 through one `ins`. Orbital size is a factor of the bond length (s 0.6, sigma and pi 1.2, others 1), p and pi stand at 90 degrees unless dragged, and an orbital dropped on an atom stores `atom`. Shapes write `fill: null` and leave `stroke` to the style; the polygon has 6 sides. The line tool draws a line by drag and a polyline by clicks, ended by a double-click, a click on the first point or a tool change (which commits a polyline of two or more points); Enter cannot end it yet because the view's keyboard cursor takes Enter first. + +## 120. The image tool and its swappable uploader ยท _v0.5.0 (canvas/tools/image.ts) + +`pickImage` opens the file chooser, `uploadMedia` posts the bytes to `POST /api/documents/{id}/media`, and only after the engine answers does the tool commit ONE transaction that sets `media[id]` (creating the map when absent) and adds the image, so placing a picture is one undo step and a failed upload changes nothing (the toast reads "Could not add the image: [reason]"). The size is the picture's pixels times 0.75, capped at 240 pt on the longer side for a click; a dragged box fits the picture inside it keeping its aspect. When the engine sends no `w`, `h` the tool takes them from the decoded picture. `setMediaUploader(fn)` swaps the uploader for a desktop shell or a scratch check. Insert > Image places the picture's top-left at the view centre (`placeImage`), not its centre. + +## 121. Captions are placed from their target; x, y are a cache ยท _v0.5.0 (canvas/render/caption.ts, canvas/tools/caption.ts, canvas/tools/transform.ts) + +The caption tool writes `target` (the fragment, not its group), `offset` (from the target's bottom centre to the caption's top centre, half a bond length down) and a matching `x`, `y`; Ctrl or Cmd-click adds `{ auto: true, value: n }` with n one more than the highest number on any caption, as a bold run. The renderer places an attached caption from the target's drawn box and `offset` and ignores `x`, `y`, so every move by the window, an agent or a clean-up keeps it attached. Two fixes followed in the running app. Moving the caption alone changed only its cache and it snapped back, so `mapSelection` now maps captions last and rewrites `offset` from the target box before and after the move. Moving the structure left the cache behind, so marquee, align and anything else that read `x`, `y` found the caption at its old place; the same transaction now refreshes `x`, `y` of every caption whose target moved (checked: y 318 to 278, and a later caption drag rewrote `offset` by +30). FORMAT states the rule. + +## 122. Handles belong to the select tool and are drawn by the view ยท _v0.5.0 (canvas/tools/handles.ts, canvas/tools/select.ts, canvas/view.ts) + +`objectHandles(doc, selection)` returns `{ object, kind, at }` in document points: tail, head and bend for one selected arrow, one per point for a line, and eight box handles (nw to w) for shapes, images, brackets, TLC plates and tables. The select tool grabs them within 8 screen px before the rotate handle, shows the matching resize cursor on hover (`HANDLE_CURSORS`) and commits one transaction per drag (`dragHandle`). An arrow end dragged by its handle drops that end's anchor; Shift snaps ends to 15 degrees and the bend to 15 degree steps; a bend under 3 degrees clears it. Box handles ignore `rot` (rotated boxes resize in their unrotated frame), tables scale columns and rows, and images keep their aspect. The view draws them as 7 px squares (a circle for the bend) in the handle path while Select or Lasso is active and the selection is that one object, in screen space so they never scale with the page. + +## 123. A click selects the outermost group ยท _v0.5.0 (canvas/tools/select.ts, canvas/tools/draft.ts) + +A click on any member selects the outermost group, so the selection holds only the group id and `mapObject` moves each member once; Alt-click or a double-click reaches the member. The marquee already selected groups as units through `topLevelObjects`. Deleting or erasing a group was rejected by validation (FORMAT rule 3: its members are in no page order, so without the group they were reachable from no page), so `removeObject` now removes a group's members with it. Ctrl-drag duplicate still skips groups because `duplicateSelection` does not copy them. Not built: a highlight for the whole group, drill-down by a second click, Escape walking up a level. + +## 124. Object commands work per container ยท _v0.5.0 (app/object-commands.ts) + +`objectCommandDefs(host, enabled)` registers bring-front (Shift+Mod+]), bring-forward (Mod+]), send-backward (Mod+[), send-back (Shift+Mod+[), group (Mod+G) and ungroup (Shift+Mod+G); `CanvasView` satisfies `ObjectCommandHost` structurally. Z-order handles every container on its own: selected items in a page order move within it, selected members of a group move within its `children`, relative order is kept, and the `move` ops get their from and to from a working copy so every op is valid when it applies. A new group goes where its frontmost member was. Ungroup takes a selected group, or the direct parent of a selected member, and skips groups nested inside another group being ungrouped. `alignObjects` and `distributeObjects` do what the existing align and distribute commands do without a canvas, for agents. Flip and rotate already mapped arrows (bend negated on a flip), lines, boxed objects and groups in transform.ts, so nothing was added there. + ## Not verified at 0.4.0 The lasso tool in the real window (its band path is the marquee's), touch pinch and Safari gesture events, the Tauri webview (dialogs, native accelerators, `contenteditable="plaintext-only"` in older WebKit), light themes, the rotate handle on dark pages, extensions against a real package, and socket drop with resync during an edit. The title field collapses to a sliver at 1280 px wide because the menu bar takes the room; it predates this work. From 2264f8514b4f7b499de390cd747262b744084ada Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:49:52 -0500 Subject: [PATCH 104/279] docs(frontend): log the 0.5.0 stoichiometry, templates, Reaction commands and wiring (0.5.0) Records the single stoichiometry source and its scale-wins rule, the panel and template library layout choices, the Reaction menu over the engine routes, the shell wiring and what was not verified at 0.5.0. --- frontend/HASHOUT_LOG.md | 44 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index bcba867a..3898befb 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -163,6 +163,14 @@ assets/ formchem_mark.svg, icon_src/build.py, icon set 122. Handles belong to the select tool and are drawn by the view ยท canvas/tools/handles.ts, select.ts, canvas/view.ts 123. A click selects the outermost group ยท canvas/tools/select.ts, draft.ts 124. Object commands work per container ยท app/object-commands.ts +125. Stoichiometry has one source in the window, and a typed scale wins ยท chem/stoich.ts, chem/stoich-ops.ts, canvas/render/table.ts +126. The stoichiometry panel is a reserved workspace row ยท ui/stoich-panel.ts, styles/stoich.css +127. The template dialog, thumbnails and Home section ยท ui/template-dialog.ts, template-thumb.ts, home-templates.ts, styles/templates.css +128. The Reaction menu runs on the engine's routes ยท engine/reactions-api.ts, app/reaction-commands.ts +129. Wiring the drawn objects into the shell ยท ui/tool-rail.ts, ui/icons.ts, app/menus.ts, app/canvas-commands.ts, app/commands-shell.ts, ui/home.ts, app.ts +130. A drawing draws as soon as it becomes active ยท canvas/view.ts setClient +131. The derived reactions slot in the window model ยท engine/model.ts +132. Strings of 0.5.0 are not keyed yet ยท i18n/keys ## 1. Dependencies are the template's, nothing more ยท _v0.1.0 (package.json) @@ -660,6 +668,42 @@ A click on any member selects the outermost group, so the selection holds only t `objectCommandDefs(host, enabled)` registers bring-front (Shift+Mod+]), bring-forward (Mod+]), send-backward (Mod+[), send-back (Shift+Mod+[), group (Mod+G) and ungroup (Shift+Mod+G); `CanvasView` satisfies `ObjectCommandHost` structurally. Z-order handles every container on its own: selected items in a page order move within it, selected members of a group move within its `children`, relative order is kept, and the `move` ops get their from and to from a working copy so every op is valid when it applies. A new group goes where its frontmost member was. Ungroup takes a selected group, or the direct parent of a selected member, and skips groups nested inside another group being ungrouped. `alignObjects` and `distributeObjects` do what the existing align and distribute commands do without a canvas, for agents. Flip and rotate already mapped arrows (bend negated on a flip), lines, boxed objects and groups in transform.ts, so nothing was added there. +## 125. Stoichiometry has one source in the window, and a typed scale wins ยท _v0.5.0 (chem/stoich.ts, chem/stoich-ops.ts, canvas/render/table.ts) + +Phase 5 produced three computations: the engine's stoich.py, a renderer module for the drawn grid and the panel's chem/stoich.ts. The renderer's let the limiting reagent's typed amount beat `scale_mmol`, so the panel and the drawn table could show different numbers for the same step. canvas/render/stoich.ts is deleted and render/table.ts draws the grid from `computeStoich` in chem/stoich.ts, which follows the engine and FORMAT: `scale_mmol` is the reference when present, else the limiting reagent's typed amount divided by its typed equiv (default 1); limiting is `limiting` when set, else the reactant with the fewest mmol per coefficient among those with a typed amount, else the first reactant; theoretical yield is the reference times the product coefficient over the limiting coefficient. Only typed values are stored: stoich-ops.ts writes one transaction per typed cell ("Edit Stoichiometry"), and typing mass, volume or equiv clears the other two of that component, typing a scale clears the limiting reagent's typed amounts, typing an amount on the limiting reagent clears `scale_mmol`, and 0 clears a field. That transaction rule makes the two readings of "reference" coincide for anything the window writes. Molecular weight: typed `mw`, else the derived `mw` at the current revision, else the engine's stoich route (asked 400 ms after a revision when a row still lacks one; a 404 with the default detail stops further calls for the session), else `averageMass` from the IUPAC abridged weights of 76 elements (null when a fragment holds `*` or `R#`). AC11.1 (8.19 mmol, 9.83 mmol, 0.713 mL) and AC11.2 (86.9 %) hold in the window, the engine and the drawn grid. + +## 126. The stoichiometry panel is a reserved workspace row ยท _v0.5.0 (ui/stoich-panel.ts, styles/stoich.css) + +The panel is row 2 of `.fc-workspace` spanning every column, opened by height the way the Analysis panel opens by width, because `.fc-stage-col` turns into a row once the tool rail mounts and the 296 px side panel is far too narrow for ten columns. It is mounted once (`mountStoichPanel(h.workspace)`); rows are keyed by component id through `patchList`; inputs are patched with `setValue` and never while focused; computed values live in `placeholder`, so typing never rebuilds anything (row and input node identity was unchanged after four commits). The step is `stepFor(doc, selection, page)`: the step whose arrow or roles touch the selection, else the first on the page, else the first in the drawing, the same rule the Reaction commands use. The open state is `formchem.stoichOpen`. Insert as table calls the engine's `POST .../stoich-table` when a table bound to the step exists (rows rewritten in place, one undo step); the first insert is a local transaction from the computed grid. Earlier every click added another table. + +## 127. The template dialog, thumbnails and Home section ยท _v0.5.0 (ui/template-dialog.ts, ui/template-thumb.ts, ui/home-templates.ts, styles/templates.css) + +Thumbnails come from a light SVG renderer of their own (`templateThumb`), not a CanvasView per card: fragments with labels, ring-side double bonds, wedges and hashes, plus shapes, lines, text and groups, with `vector-effect: non-scaling-stroke`. They are drawn lazily by an IntersectionObserver into reserved 84 to 92 px tiles and cached as one SVG string per template for the session, so a list of 206 never jumps. Inserting is one transaction (a `set` per object and an `ins` into the page order per top-level id) centred on the view's placement, then the fragments are selected; with no drawing open, one is created with the person's preset and style and the template is fetched again at that drawing's bond length. The Home section uses its own classes and data attributes (`.fc-tl-card[data-tl-id]`, `.fc-chip[data-tl-cat]`), so Home's delegated handlers never see them; Home's old chips, search box, filter code and `CATEGORIES` were removed and the Templates badge counts the library (206). Not built: fusing a template onto a clicked atom or bond, collision avoidance, substructure search of templates, and saving a selection as a user template. + +## 128. The Reaction menu runs on the engine's routes ยท _v0.5.0 (engine/reactions-api.ts, app/reaction-commands.ts) + +reactions-api.ts is a typed client for every reaction route and sends the live client id, so the engine's broadcast of the route's transaction is recognised as the window's own. `registerReactionCommands({view, homeOpen})` adds perceive-reactions, map-atoms (perceiving first when the page has no stored step), clear-mapping, check-reaction (a dialog with elements, charge, mass, warnings, the co-product hint and a Balance button when coefficients are suggested), balance-reaction, copy-reaction-smiles, copy-reaction-rxn, export-reaction-smiles, export-reaction-rxn and paste-reaction (the clipboard, falling back to a prompt). Export downloads a Blob in a browser; the desktop window has no file system plugin, so it asks the native save dialog for a path and the engine's `POST .../export {format, path}` writes the file. Set Reaction Roles stays a disabled placeholder with the reason "until then Perceive Reactions sets the roles from the drawing" and is retargeted to 0.6.0. + +## 129. Wiring the drawn objects into the shell ยท _v0.5.0 (ui/tool-rail.ts, ui/icons.ts, app/menus.ts, app/canvas-commands.ts, app/commands-shell.ts, ui/home.ts, app.ts) + +`RAIL_GROUPS` gains arrow (W), symbol (P), bracket (K) and orbital (O) in one family and shape (G), table, tlc and image in the next, after Text; the keys avoid the rail's V B C R A T E H Z and the hover keys only fire over atoms and bonds, so W, P, K, G and O were free (Mod+G is Group, a different combination). ui/icons.ts has 24 new glyphs in the 24 box at the shared 1.6 stroke (the polygon is a pentagon so it differs from ring6). insert-arrow, insert-shape and insert-table pick their tool, add-reaction-arrow picks the forward arrow, insert-image places a picture at the visible centre, insert-template opens the library or, with `{id}`, inserts that template; the placeholders for them and the six arrange ids are gone. View gets Stoichiometry Panel; the Reaction menu is Add Reaction Arrow, Perceive Reactions, Set Reaction Roles, then mapping, balance, stoichiometry, and Insert Reaction from Clipboard with the Copy Reaction As and Export Reaction submenus. The macOS native menu is built from the same `buildMenus` definitions, so it needed no change. The rail has 17 slots now; it fits at 900 px tall, shorter windows were not checked. + +## 130. A drawing draws as soon as it becomes active ยท _v0.5.0 (canvas/view.ts setClient) + +`setClient` marked only the viewport dirty. A drawing opened from Home arrives with its derived data already in the snapshot, so no later event marked the render dirty and the page stayed empty until the pointer moved over the canvas (seen on 0.4.0 too). `setClient` now sets `renderDirty`; 55 to 94 nodes were drawn right after opening with no pointer movement. + +## 131. The derived reactions slot in the window model ยท _v0.5.0 (engine/model.ts) + +`Derived.reactions?` (step id to `DerivedReactionCheck`, with `BalanceSide` for elements, charge and mass) mirrors the engine's new top-level slot (backend log 74). The client adopts it with the rest of the derived message at its revision; the Check Balance dialog still asks the route, because it also wants the suggestion, which the cache does not carry. + +## 132. Strings of 0.5.0 are not keyed yet ยท _v0.5.0 (i18n/keys) + +About a hundred new strings (tool labels, rail groups, panel headings, Reaction command labels and toasts, template dialog text) go through `t()` but have no key in i18n/keys, and a few are plain literals still to wrap: the drawn grid's column headers and role words in canvas/render/table.ts (`STOICH_COLUMNS`), the disabled reasons of the reaction commands, and the undo labels the tools and the engine write. `./formchem i18n scan` finds the first group. The drawn grid's words are written into the document, so translating them is a product decision (journal output is usually English). Unit words and template names are `translate="no"`. + ## Not verified at 0.4.0 The lasso tool in the real window (its band path is the marquee's), touch pinch and Safari gesture events, the Tauri webview (dialogs, native accelerators, `contenteditable="plaintext-only"` in older WebKit), light themes, the rotate handle on dark pages, extensions against a real package, and socket drop with resync during an edit. The title field collapses to a sliver at 1280 px wide because the menu bar takes the room; it predates this work. + +## Not verified at 0.5.0 + +The macOS native menu with the new Reaction submenus and the desktop export path (no Tauri build here), the frozen sidecar carrying the template data, the rail at window heights under 900 px, rotated-box resizing by handles, bracket tilt for crossing bonds that are not perpendicular, table cell editing, TLC spot dragging, orbital phase and fill choices, and the arrow head-size handles (none of the last five are built). Everything else in entries 108 to 131 was exercised in the built window served by the engine under 4x CPU throttling, with a MutationObserver over the app for the zero-flash rule. From e7c5744ccd3d7177aceb1bb7d8e1d8ef02829567 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:51:50 -0500 Subject: [PATCH 105/279] docs(reactions): document perception, mapping, balance, stoichiometry and the reaction routes (0.5.0) FORMAT.md defines what a drawing stores; this page says how the engine reads and maps reactions, the shared stoichiometry rules, the RXN and reaction SMILES exchange, and every reaction route with its request and answer. --- docs/REACTIONS.md | 141 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 docs/REACTIONS.md diff --git a/docs/REACTIONS.md b/docs/REACTIONS.md new file mode 100644 index 00000000..cceb9028 --- /dev/null +++ b/docs/REACTIONS.md @@ -0,0 +1,141 @@ +# FormChem reactions + +How the engine reads reaction schemes, maps atoms, checks balance, works out stoichiometry and exchanges reactions as reaction SMILES and RXN, built from 0.5.0. What a drawing stores (`page.reactions`, a step's `coefficients` and `stoich`, `Atom.map`, `Bond.reacting`) is defined in [FORMAT.md](FORMAT.md), which wins over this page; this page describes the services behind the Reaction menu, the Stoichiometry panel and the agent tools, and their HTTP routes. + +## Contents + +- Where reactions live +- Perception +- Atom mapping +- Balance +- Stoichiometry +- Reaction SMILES and RXN +- HTTP API +- Agent tools +- The window +- Known limits + +## Where reactions live + +A page lists its reactions in `page.reactions`; each reaction has ordered `steps`, and each step names its `arrow` and the object ids of its `reactants`, `products`, `agents` and `conditions`, with `explicit`, optional `coefficients` and optional `stoich`. The engine code is in `backend/app/services/chem/`: `geometry.py` (boxes and the arrow frame), `reactions.py` (perception and step lookup), `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py` (export) and `scheme.py` (import and layout). The routes are in `backend/app/routers/reactions.py`. + +## Perception + +Perception reads every reaction arrow on a page and writes the steps it finds. Distances are measured in the arrow's own frame (along the shaft from the tail, and across it), so tilted and vertical arrows follow the same rules, and they are given in bond lengths of the drawing's style. + +| Rule | Value | +| --- | --- | +| Agents and conditions | centre between the tail and the head, within 1.5 bond lengths of the shaft | +| Reactants and products | reach within 2.5 bond lengths of the shaft's line; may overlap the tail or head by 0.5 bond lengths | +| Joining | walking away from the arrow, the nearest structure takes the role; the next joins only across a plus sign or a gap under 1 bond length; a step stops at another arrow | +| Text | captions never take a role; text in the band is a condition; text with `formula: true` may be a reactant or product | +| Arrow kinds | forward, equilibrium, unbalanced equilibrium, reversible, no-go and dashed arrows are steps; a retrosynthetic arrow swaps the sides; resonance, curved, fishhook, arc, plain, fragmentation and dissociation arrows are not steps | +| Direction | an arrow with `head: none` and a head at its tail points backwards | + +Steps whose products are the reactants of another step chain into one reaction, ordered by chain depth and then by arrow position; separate arrows are separate reactions, ordered top to bottom and left to right. Only top-level page objects are considered (a group counts as one object) and a bent arrow is read by its chord. + +Running perception again keeps reaction and step ids (matched by arrow), keeps `coefficients` and `stoich` for the ids still in the step, and writes nothing when the result equals what is stored. A step with `explicit: true` (set by the person, an agent, or read from a reaction file) is kept as it is, even when its arrow is gone; the summary reports it as stale. The whole change is one transaction labelled "Perceive reactions". + +## Atom mapping + +Mapping numbers reactant atoms onto product atoms (`Atom.map`) with Indigo's automapper and marks bonds of the step's fragments with `reacting` (`broken`, `formed`, `order`). Modes: + +| Mode | What it does | +| --- | --- | +| `discard` (default) | ignores existing numbers; tries up to 24 molecule orders within 6 seconds and keeps the mapping with the fewest unmapped atoms, then the fewest bond edits, then the fewest hydrogen moves, then improves it by swapping same-element product atoms | +| `keep` | keeps the drawn numbers and maps the rest, once, in drawn order | +| `alter` | starts from the drawn numbers and lets the mapper change them, once, in drawn order | +| `clear` | removes every map number and reacting mark of the step's fragments (the DELETE route) | + +Numbers are renumbered 1 to n in reactant order. Reacting marks are computed from the mapping; a bond with an unmapped end gets none. Agents are not mapped, and atoms inside abbreviations get no number (warning `abbreviations_unmapped`). The answer gives `quality`: `complete`, or `partial: n unmapped atoms`. + +## Balance + +The check counts the reactants and products of a step (not its agents), each times its coefficient, by element symbol (isotopes merged), with total charge and average mass on each side. When the step is not balanced the engine solves the element and charge conservation equations exactly; a unique positive solution with every coefficient at most 50 becomes a coefficient suggestion. Otherwise it tries adding up to two common co-products (water, HCl, HBr, CO2, SO2, N2, H2, NaCl) and suggests the combination with the smallest coefficient sum. Balancing writes the coefficients into the step; a coefficient of 1 is stored as absent. + +For each resonance arrow the check compares the nearest structure on each side: a different formula or charge gives the warning `resonance_formula`, a different heavy-atom skeleton gives `resonance_connectivity`. + +The derived cache carries the check of every step (at most 64) under its top-level `reactions` slot, so a window shows balance without asking. + +## Stoichiometry + +Only what the person typed is stored in `step.stoich`; everything else is computed. The rules, shared by the engine (`services/chem/stoich.py`) and the window (`frontend/src/chem/stoich.ts`): + +1. A component's moles come from a typed mass (with purity and molecular weight), a volume with density, or a volume with concentration. A typed amount wins over typed equivalents, which then only warn (`equiv_mismatch`) when they differ by more than 1 percent. +2. The reference amount is `scale_mmol` when present; otherwise the limiting reagent's typed amount divided by its `equiv` (default 1); otherwise the first reactant or agent with an amount. +3. The limiting reagent is `limiting` when it names a reactant; otherwise the reactant with the fewest moles per coefficient. +4. Amounts implied by `equiv` are the reference times `equiv`; masses and volumes follow from the molecular weight, density or concentration. +5. The theoretical yield of `product` (default the first product) is the limiting moles divided by the limiting coefficient times the product coefficient; the percent yield uses `isolated_mg`, or a product's own typed `mass_mg`. +6. The molecular weight is the component's typed `mw`, else the derived `mw` (summed over a group's fragments). + +The window keeps both readings of the reference equal by how it writes: typing an amount on the limiting reagent removes `scale_mmol`, typing `scale_mmol` removes the limiting reagent's typed amounts, and typing one of `mass_mg`, `volume_ml` or `equiv` removes the other two from that component. + +Checked values: 1.00 g benzoic acid with 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol, 9.83 mmol and 0.713 mL; 1000 mg isolated of 1151 mg theoretical is 86.9 %. + +A table with `stoich: {reaction, step}` is a stoichiometry grid. The engine's refresh (`POST .../stoich-table`) writes its `rows` with the columns Compound, Formula, Role, MW, Equiv, Amount, Mass, Volume, Isolated, Yield, at three significant figures, mass and amount switching unit at 1 (mg, g, kg; ยตmol, mmol, mol) and volume at 0.1 mL; it adds a table under the step the first time and rewrites the same table, keeping its row ids, afterwards. + +## Reaction SMILES and RXN + +Export (`GET .../export?format=`): + +| Format | Writes | +| --- | --- | +| `smiles` | reaction SMILES `reactants>agents>products` with map numbers, aromatic lower case | +| `rxn` | MDL RXN V2000: line 2 the reaction or drawing title, line 4 the conditions text, kekulised molecules with map numbers in the atom block | +| `rxnv3000` | RXN V3000, with the reacting marks as RXCTR (broken or formed 4, order changed 8, unchanged 2, centre and stereo 1) | + +Coefficients have no place in either format and are dropped with the warning `coefficient_dropped`; reaction SMILES drops text conditions with `conditions_dropped`. + +Import reads reaction SMILES, RXN V2000 and V3000, and CML or CDXML holding a reaction (`format` may be given as `smiles`, `rsmiles`, `rxn`, `rxnv3000`, `cml` or `cdxml`, or left out to detect it). The scheme is laid out on one centre line: 1 bond length between structures and plus signs, 0.5 between the arrow ends and the structures, agents above the arrow, the RXN conditions line as text under it, and the arrow at least 4 bond lengths long and as wide as what sits on it plus 7.2 pt each side. Structures that take no role go one row below. The step is written with `explicit: true`. File > Open lays out reaction files the same way. + +## HTTP API + +`{STEP}` stands for `/api/documents/{doc_id}/reactions/{reaction_id}/steps/{step_id}`. POST and DELETE routes need the window key (`x-formchem-window-key`), like every changing route of the engine. + +A changing route answers `{changed, tx, rev, ...}`: `tx` is the applied transaction, broadcast on the live socket like any other, or null with `changed: false` when nothing changed (no undo step is recorded). Bodies may carry `client` (the live client id, echoed in the broadcast) and `origin` (`user` by default, or `system`). Errors: 404 `{detail}` for an unknown drawing, page, reaction or step; 422 `{detail}` for bad input; 409 `{detail: {message, errors}}` when the engine refuses the transaction; 413 for text over 20 MB. + +| Route | Body or query | Answer | +| --- | --- | --- | +| `GET /api/documents/{doc_id}/reactions` | | `{rev, pages: [{page, reactions}]}` | +| `GET /api/documents/{doc_id}/reactions/preview` | `?page=` | `{rev, pages: [{page, reactions, steps, explicit, stale, changed}]}`: what perception would write; nothing changes | +| `POST /api/documents/{doc_id}/reactions/perceive` | `{page?, client?}` | `{changed, tx, rev, summary: [{page, reactions, steps, explicit, stale, changed}], pages: [{page, reactions}]}` | +| `POST {STEP}/map` | `{mode?: "discard", "keep" or "alter", centres?: true}` | `{changed, tx, rev, mapping: {mode, mapped, unmapped, orders_tried, quality, centres: {broken, formed, order}, warnings}}` | +| `DELETE {STEP}/map` | `?centres=true&client=` | `{changed, tx, rev, mapping: {mode: "clear", cleared}}` | +| `GET {STEP}/export` | `?format=rxn` (default), `rxnv3000` or `smiles` | `{format, text, warnings, engine}` | +| `POST {STEP}/export` | `{format?, path}` (absolute path) | the same plus `path`: the file was written there | +| `POST /api/chem/reactions/import` | `{text, format?, bond_length?, origin?: [x, y]}` | `{format, objects, reaction: {id, steps}, warnings}`; no drawing changes, ids are fresh but not checked against any drawing | +| `POST /api/documents/{doc_id}/reactions/import` | `{text, format?, page?, origin?}` | `{changed, tx, rev, page, format, objects: [ids], reaction, warnings}`; placed under the page's content unless `origin` is given | +| `GET /api/documents/{doc_id}/reactions/check` | `?page=` | `{rev, pages: [{page, steps: [{reaction, ...check}], resonance: [warning]}]}` | +| `GET {STEP}/check` | | `{rev, reaction, step, balanced, species, elements, charge, mass, suggestion, warnings}` | +| `POST {STEP}/balance` | `{coefficients?: {oid: 1 to 999}}` | `{changed, tx, rev, coefficients, check}`; without `coefficients` applies the suggestion (422 when there is none) | +| `GET {STEP}/stoich` | | `{rev, reaction, step, scale_mmol, reference_mmol, limiting, limiting_source, rows, yield, warnings}` | +| `POST {STEP}/stoich-table` | `{at?: [x, y]}` | `{changed, tx, rev, table, stoich}` | + +The check's parts: `species` is `[{id, role, coefficient, formula, mw, charge}]`; `elements` is `[{element, left, right, diff}]`; `charge` and `mass` are `{left, right, diff}`; `suggestion` is null, `{coefficients: {oid: n}}` or `{co_products: [{add: [{name, smiles, coefficient}], coefficients}]}`. + +A stoichiometry row is `{id, role, label, formula, mw, mw_source, coefficient, purity_pct, density_g_ml, conc_m, equiv_entered, equiv, mmol, mass_mg, volume_ml, source, actual_mg, limiting, yield_pct}`, where `source` is `mass`, `volume`, `solution` or `equiv` and a product's `mmol` and `mass_mg` are theoretical. `limiting_source` is `entered` or `computed`; `yield` is `{product, theoretical_mmol, theoretical_mg, isolated_mg, percent}`. + +Transaction labels: "Perceive reactions", "Map atoms", "Clear mapping", "Insert reaction", "Balance reaction" and "Stoichiometry grid". Amounts, coefficients and hand-set roles are written by the window with ordinary transactions on the step's path (`["pages", {"id": p}, "reactions", {"id": r}, "steps", {"id": s}, "stoich"]` and `... "coefficients"`); setting roles by hand sets `explicit: true` and the role lists in one transaction. + +## Agent tools + +The MCP server has four reaction tools (`backend/app/routers/mcp.py`); each takes `doc` (a drawing id from `get_context`, which may be left out when one drawing is open) and finds the step by `reaction` and `step` ids, or the first one. + +| Tool | Kind | What it does | +| --- | --- | --- | +| `perceive_reactions {doc?, page?}` | approval-gated | runs perception and lists reactions and steps, marking steps set by hand | +| `map_reaction {doc?, reaction?, step?, mode?}` | approval-gated | maps one step; `mode: "clear"` removes the mapping | +| `export_reaction {doc?, reaction?, step?, format?}` | read-only | the step as reaction SMILES or RXN (V2000 or V3000) | +| `reaction_stoichiometry {doc?, reaction?, step?}` | read-only | rows, limiting reagent, yields and the balance check | + +## The window + +The Reaction menu calls these routes: Perceive Reactions, Map Atoms (which perceives first when the page has no step), Clear Atom Mapping, Check Balance (a dialog with the suggestion and a Balance button), Balance Reaction, Stoichiometry Panel and Insert Stoichiometry Table, Insert Reaction from Clipboard, Copy Reaction As SMILES or RXN, and Export Reaction. A command acts on the step whose arrow or roles touch the selection, else the first step on the page. The Stoichiometry panel computes in the window by the rules above and asks the engine only for molecular weights it lacks. + +## Known limits + +- Map numbers live on atoms, so a structure that is the product of one step and the reactant of the next carries one set; mapping the second step overwrites the first step's numbers. +- Balance and the grid ignore agents, so a step whose atoms come from a reagent drawn above the arrow reads as unbalanced with no suggestion. +- A `.smi` file holding reaction SMILES opens as plain SMILES and fails; paste it as a reaction instead. +- The written grid rows refresh only when the grid is inserted again; the window draws the live grid with seven columns, the engine writes ten. +- Perception reads only top-level objects and treats a bent arrow by its chord. From 04a903573ca0a89328385c9539fa8c2acae26ffa Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:51:55 -0500 Subject: [PATCH 106/279] docs(backend): log the 0.5.0 reaction services and router (0.5.0) Perception distances, re-run rules, mapping order search, exact balancing, the stoichiometry precedence, RXN details and the route answer shape are reasons the code does not carry, so they are recorded by file and symbol. --- backend/HASHOUT_LOG.md | 55 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 4904c701..40abfe05 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # backend HASHOUT_LOG -Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.4.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, and from 0.3.0 it records the chemistry engine, the document store and the file format, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.5.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, and from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -10,15 +10,21 @@ backend/app/main.py app, middleware order, discovery file (engine.json) backend/app/core/ config.py (ports, data dirs, settings store), local_guard.py, window_key.py, seal.py, startup.py, runtime.py, ids.py backend/app/routers/ system (health, version, capabilities, settings, notices, window key and ticket), live (WebSocket), - library, commands, terminal, chat, extensions, mcp, documents (0.3.0), chem (0.3.0) + library, commands, terminal, chat, extensions, mcp, documents (0.3.0, media 0.5.0), chem (0.3.0), + reactions (0.5.0), templates (0.5.0) backend/app/core/files.py safe file names and free names for saves and imports (0.3.0) backend/app/services/ hub.py (client and agent table), bridge.py (window tools over the live channel), library.py, terminal.py, consent.py, claude_code.py, agent_programs.py, agent_lookup.py (vendored), formext_host.py (vendored), chat/ model.py, ops.py (the format contract and transactions, 0.3.0), store.py (open documents, undo, derive loop), package.py (.fchem zip), history.py (autosave, versions), importers.py + templates.py (the template library, 0.5.0) backend/app/services/chem/ abbrev, convert, perceive, ids, mass, layout, io, derive (RDKit and Indigo, 0.3.0) + geometry, reactions, rxnio, scheme, mapping, balance, stoich (reactions, 0.5.0) +backend/app/data/templates/ 206 original templates in nine category files (0.5.0) docs/FORMAT.md the document format, the single source for both languages (0.3.0) +docs/REACTIONS.md reaction perception, mapping, balance, stoichiometry and their routes (0.5.0) +docs/TEMPLATES.md the template file format and API (0.5.0) backend/requirements*.txt pins for the engine and for the desktop freeze formchem, formchem.bat one dispatcher for install, boot, serve, build, desktop, doctor, clean setup/ the commands behind the dispatcher, plus notices.py, i18n_tool.py, catalogue.py @@ -89,6 +95,15 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log 60. The skill packs describe what the code does, not the plan ยท .claude/skills, .agents/skills, agents/manifest.json 61. get_context lists open drawings and says what agents can do today ยท routers/mcp.py 62. The notices generator reads the flat font layout ยท setup/notices.py +63. Page geometry for reactions is an estimate in points ยท services/chem/geometry.py +64. Perception works in the arrow's own frame ยท services/chem/reactions.py +65. Re-perceiving keeps ids, explicit steps and writes nothing when equal ยท services/chem/reactions.py perceive_ops +66. Reaction SMILES and RXN from one builder ยท services/chem/rxnio.py +67. Reaction files open as drawn schemes ยท services/chem/scheme.py, services/importers.py +68. Mapping tries molecule orders and keeps the best score ยท services/chem/mapping.py +69. Balance solves exactly and suggests co-products ยท services/chem/balance.py +70. Stoichiometry: typed amounts win, a typed scale wins over them ยท services/chem/stoich.py +71. The reactions router: one transaction per changing route ยท routers/reactions.py ## 1. Ports and the data folder are FormChem's own ยท _v0.1.0 (app/core/config.py) @@ -337,3 +352,39 @@ The MCP text still said there were no documents. `get_context` now lists each op ## 62. The notices generator reads the flat font layout ยท _v0.4.0 (setup/notices.py) The bundled fonts sit flat in `frontend/public/fonts` with `Arimo-OFL.txt` and `Tinos-OFL.txt`, but the generator only looked for `fonts/full//OFL.txt`, so THIRD-PARTY-NOTICES.txt carried no font licences. It now reads both layouts (a `Family-OFL.txt` file and an optional `Family-VERSION` file beside the fonts, or the old folder), and the notices were regenerated with both families. The licence is SIL OFL 1.1: Arimo and Tinos moved from `apache/` to `ofl/` in google/fonts in April 2026, so the Apache-2.0 named in the brief and in the first FORMAT.md is out of date; OFL allows bundling with software as long as the licence and copyright travel with the files. + +## 63. Page geometry for reactions is an estimate in points ยท _v0.5.0 (services/chem/geometry.py) + +Perception, layout and the grid need boxes for every object without a renderer. `object_box(doc, oid, style)` covers every kind: fragments from atom positions (`fragment_box`), text by an estimate of 0.55 em per character and 1.2 line height with sub and superscripts at 75 percent (`text_box`), arrows from their ends plus the arc's midpoint when bent (`arrow_box`), groups as the union of their children, and boxed kinds from `x`, `y`, `w`, `h` and `rot`. The estimate errs a little wide, which is the safe side for "is this near the arrow". `Frame(tail, head)` gives `along(p)` and `across(p)` and `project(box) -> (s0, s1, t0, t1)`, the coordinates every perception rule is written in. The window's render/bounds.ts measures the drawn text instead, so the two can differ by a fraction of a character; nothing compares them. + +## 64. Perception works in the arrow's own frame ยท _v0.5.0 (services/chem/reactions.py) + +Measuring along the shaft (s from the tail) and across it (t) makes tilted and vertical arrows work with the same rules. The constants are bond lengths of the drawing: `BAND_BONDS = 1.5` (agents and conditions: centre between the ends, within 1.5 of the shaft, from clean-room spec A section 11), `ROW_BONDS = 2.5` (reactants and products reach within 2.5 of the shaft's line), `END_BONDS = 0.5` (an object may overlap an end by half a bond), `JOIN_BONDS = 1.0`. Walking away from the tail (or head), the nearest structure takes the role and the next joins only across a plus sign in the gap or a gap under one bond length, so in A + B -> C + D -> E the second step's reactants are C and D, and a step stops at another arrow. Captions never take a role; text takes one only as conditions in the band, or as a reactant or product when `formula` is true. Resonance, curved, fishhook, arc, plain, fragmentation and dissociation arrows are not steps; a retro arrow swaps the sides; an arrow with `head: none` and a tail head points backwards. Steps whose products are another step's reactants chain into one reaction, ordered by chain depth then arrow position; separate arrows are separate reactions, top to bottom, left to right. Only top-level page objects are looked at (a group is one object) and a bent arrow is read by its chord. FORMAT states the distances. + +## 65. Re-perceiving keeps ids, explicit steps and writes nothing when equal ยท _v0.5.0 (services/chem/reactions.py perceive_ops, preview) + +Perception is one `set` of `["pages", {id}, "reactions"]` labelled "Perceive reactions". Running it again keeps reaction and step ids (matched by arrow), keeps `coefficients` and `stoich` filtered to the ids still in the step, and returns no op when the result equals what is stored, so a second run answers `changed: false` and adds no undo step. A step with `explicit: true` is copied verbatim, even when its arrow was deleted (reported in the summary's `stale`), because the person or an agent set it on purpose. `preview` runs the same code without writing, for `GET .../reactions/preview`. + +## 66. Reaction SMILES and RXN from one builder ยท _v0.5.0 (services/chem/rxnio.py) + +`build(doc, step)` turns a step into an RDKit ChemicalReaction (groups expand to their fragments, agents included), and `export_step` writes `smiles`, `rxn` (V2000) or `rxnv3000`. RXN line 2 is the reaction or drawing title and line 4 the conditions text, which the importer reads back, so a round trip keeps the conditions. RXN molecules are kekulised like single molfiles, because an aromatic ring came out as bond type 4, which V2000 reserves for queries; reaction SMILES stays aromatic lower case. V3000 writes the `reacting` marks as RXCTR (broken and formed 4, order changed 8, unchanged 2, centre and stereo 1); RDKit has no V2000 writer for them. Coefficients have no place in either format and are dropped with `coefficient_dropped`; text conditions in reaction SMILES are dropped with `conditions_dropped`. + +## 67. Reaction files open as drawn schemes ยท _v0.5.0 (services/chem/scheme.py, services/importers.py) + +Imported reactions (RXN, reaction SMILES, CML or CDXML with a reaction) are laid out on one centre line: 1 bond length between structures and plus signs, 0.5 between the arrow ends and the structures, agents above the arrow, the arrow at least 4 bond lengths and as wide as the agents or the conditions text plus 7.2 pt each side. Structures that take no role go one row below. The step is written with `explicit: true`, because the file declared the roles. `importers.import_file` uses `scheme.layout` for reaction files and falls back to rows if layout raises; molecules with no usable coordinates (hydrogen-only species give NaN from `convert.from_mol`) are drawn in a row with a `no_coordinates` warning, the root cause being in `convert._ensure_2d` or `layout.depict`. `POST /api/chem/reactions/import` answers objects with fresh ids not checked against any drawing; `POST /api/documents/{id}/reactions/import` checks them and places the scheme under the page's content (`free_origin`). Not fixed: a `.smi` file holding reaction SMILES does not open, because `io.EXTENSIONS` maps `.smi` to `smiles` and `read_file` never detects `rsmiles`; the fix belongs in chem/io.py (a `>` in the first token). + +## 68. Mapping tries molecule orders and keeps the best score ยท _v0.5.0 (services/chem/mapping.py) + +Indigo's automap answer depends on the molecule order, and for the esterification some orders left a whole fragment unmapped. Discard mode therefore tries up to 24 molecule orders within 6 s (aam-timeout 3 s each), scores each by unmapped atoms, then bond edits, then hydrogen moves, keeps the best, and then swaps same-element product atoms while the score drops (up to 80 product atoms, 6 rounds). Keep and alter run once in the drawn order with the drawn numbers loaded. Map numbers are renumbered 1 to n in reactant order. The `reacting` marks (broken, formed, order) are computed from the mapping, not taken from Indigo, and a bond with an unmapped end gets none. AC11.3 holds: the acid's carbonyl carbon maps to the ester carbonyl and one C-O bond is formed (which oxygen ends in water is a tie the score cannot break). Map numbers live on atoms, so a structure that is the product of one step and the reactant of the next carries one set, and mapping the second step overwrites the first. Agents are not mapped, and atoms inside abbreviations get no number (`abbreviations_unmapped`). + +## 69. Balance solves exactly and suggests co-products ยท _v0.5.0 (services/chem/balance.py) + +`check(doc, step)` counts reactants and products, not agents (as the clean-room spec does), with their coefficients, by element symbol (isotopes merged), with charge and average mass. `solve(left, right)` solves the element and charge conservation system exactly with fractions; a unique positive solution with every coefficient up to 50 becomes `suggestion.coefficients`, otherwise up to two common co-products (water, HCl, HBr, CO2, SO2, N2, H2, NaCl) are tried and ranked by coefficient sum. `coefficient_ops` writes coefficient 1 as absent. The resonance check (AC11.4) takes the nearest structure on each side of a resonance arrow: a different formula or charge is `resonance_formula`, a different heavy-atom skeleton (all bonds single, no charges, hydrogens or isotopes) `resonance_connectivity`. Known effect: a step whose atoms come from a reagent drawn above the arrow (SOCl2) reads as unbalanced with no suggestion. + +## 70. Stoichiometry: typed amounts win, a typed scale wins over them ยท _v0.5.0 (services/chem/stoich.py) + +A typed amount (a mass, a volume with density, or a volume with concentration) wins over typed equivalents, which then only warn (`equiv_mismatch`) when they disagree by more than 1 percent. The reference is `scale_mmol`, else the typed limiting reactant's amount divided by its equiv, else the first reactant or agent with an amount; the window's chem/stoich.ts follows the same order (frontend log 125) and FORMAT states it with the clearing rules that keep the readings equal. Limiting is the typed one when it is a reactant, else the reactant with the fewest mmol per coefficient. Theoretical yield is limiting mmol over its coefficient times the product coefficient; percent yield uses `isolated_mg` for `product` (default the first product) or a product row's own `mass_mg`. Molecular weight is the component's `mw`, else the derived `mw` summed over a group's fragments. The grid (`grid`, `table_ops`) has the columns Compound, Formula, Role, MW, Equiv, Amount, Mass, Volume, Isolated, Yield, three significant figures, mass and amount switching unit at 1 (mg, g, kg; ยตmol, mmol, mol), volume at 0.1 (0.713 mL), formulas as subscript runs, and column widths from the same 0.55 em estimate. The window draws a live grid of seven columns; FORMAT documents both and a later change should settle on one set. AC11.1 and AC11.2 were checked through the route. + +## 71. The reactions router: one transaction per changing route ยท _v0.5.0 (routers/reactions.py) + +Every changing route answers `{changed, tx, rev, ...}`. `tx` is the applied transaction, broadcast on the live socket like any other with the body's `client` echoed, so the window that asked recognises its own change; `tx` is null and `changed` false when nothing changed, so no empty undo step is recorded. `origin` is `user` by default or `system`. Errors: 404 for an unknown drawing, page, reaction or step; 422 for bad input; 409 `{detail: {message, errors}}` when the store refuses the transaction; 413 for text over 20 MB. Mutating routes use the same window-key guard as documents.py. The router copies the document under the session lock, computes on the copy (mapping and reaction import in a worker thread) and commits through `STORE.apply`, so a long mapping never holds the lock. The ops are built from that copy and applied to whatever the document is when they arrive; a route does not check that the revision is unchanged, which is a gap only when the person edits the same step during a mapping. `POST .../export {format, path}` writes the export to an absolute path for the desktop window, which has no file system plugin. The routes and shapes are in docs/REACTIONS.md. From 7a027c519607648e21b7247eea5f9329e0fc0f4d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:52:36 -0500 Subject: [PATCH 107/279] docs(backend): log the 0.5.0 media routes, template library, derived reactions slot and MCP tools (0.5.0) Records why media bytes wait in the session until the window's transaction lists them, how the template library is built and cached, why the balance check rides in the derived cache, and how the phase 5 routers reach main.py and the frozen engine. --- backend/HASHOUT_LOG.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 40abfe05..93b68b77 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -104,6 +104,11 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log 69. Balance solves exactly and suggests co-products ยท services/chem/balance.py 70. Stoichiometry: typed amounts win, a typed scale wins over them ยท services/chem/stoich.py 71. The reactions router: one transaction per changing route ยท routers/reactions.py +72. Media bytes are held by the session, listed by the window's transaction ยท routers/documents.py, services/store.py, services/package.py +73. The template library is data, built once and cached ยท services/templates.py, routers/templates.py, data/templates +74. The derived cache carries each step's balance check ยท services/chem/derive.py reaction_checks +75. Four reaction tools on the MCP server ยท routers/mcp.py +76. Wiring the phase 5 routers and the frozen engine ยท app/main.py, setup/freeze_backend, setup/freeze_backend.bat ## 1. Ports and the data folder are FormChem's own ยท _v0.1.0 (app/core/config.py) @@ -388,3 +393,23 @@ A typed amount (a mass, a volume with density, or a volume with concentration) w ## 71. The reactions router: one transaction per changing route ยท _v0.5.0 (routers/reactions.py) Every changing route answers `{changed, tx, rev, ...}`. `tx` is the applied transaction, broadcast on the live socket like any other with the body's `client` echoed, so the window that asked recognises its own change; `tx` is null and `changed` false when nothing changed, so no empty undo step is recorded. `origin` is `user` by default or `system`. Errors: 404 for an unknown drawing, page, reaction or step; 422 for bad input; 409 `{detail: {message, errors}}` when the store refuses the transaction; 413 for text over 20 MB. Mutating routes use the same window-key guard as documents.py. The router copies the document under the session lock, computes on the copy (mapping and reaction import in a worker thread) and commits through `STORE.apply`, so a long mapping never holds the lock. The ops are built from that copy and applied to whatever the document is when they arrive; a route does not check that the revision is unchanged, which is a gap only when the person edits the same step during a mapping. `POST .../export {format, path}` writes the export to an absolute path for the desktop window, which has no file system plugin. The routes and shapes are in docs/REACTIONS.md. + +## 72. Media bytes are held by the session, listed by the window's transaction ยท _v0.5.0 (routers/documents.py, services/store.py add_media, media_bytes, services/package.py sniff_image) + +`POST /api/documents/{id}/media` (window key, multipart `file`, 50 MB) does not change document.json. `Store.add_media` keeps the bytes in `Session.media` under a fresh `m` id and answers `{id, media: {name, mime, bytes, w, h, sha256}}`; the window then commits one transaction that sets `media[id]` and adds the image object. Placing a picture is therefore one undo step, and an undo leaves bytes behind that the package writer drops, because it writes only ids listed in `doc.media`. `sniff_image` reads the mime type and pixel size from the bytes themselves (PNG, JPEG SOF, GIF, WebP VP8, VP8L and VP8X; SVG by its opening tag) and anything else is a 415, so the file name never decides the type. `GET /api/documents/{doc_id}/media/{media_id}` serves the bytes with the mime from `doc.media` (else sniffed), `cache-control: private, immutable`, `nosniff` and a `default-src 'none'` CSP, so an SVG opened directly in a tab runs nothing. It is a GET, so the renderer's image elements load it without the window key. Checked: an 80 by 40 PNG gave a media record with w 80, h 40 and sha256, and after save, close and reopen the record was identical and the GET answered 200. + +## 73. The template library is data, built once and cached ยท _v0.5.0 (services/templates.py, routers/templates.py, data/templates) + +Templates are JSON per category in the document fragment format, each with one source: `smiles` (laid out once by RDKit through `io.read_text`), `ring` (a generator for flat-bottom regular rings, the orientation of the ring tools) or `objects` (hand-placed objects for Haworth and Fischer projections, chairs, cubane and glassware). RDKit lays out fused, bridged and stereo structures well, but projections and clip art need their exact geometry. All 206 build in about 0.2 s on the first request and are cached until a file's modification time or size changes (`_stamp`); a file over 4 MB is skipped. `fragment(id, bond_length)` answers fresh ids on every call (atoms, bonds, objects, group children, row and lane ids), so the window commits the objects as they come, and scales fragment coordinates from 14.4 pt to the drawing's bond length while shapes and lines keep their size. User templates in `FORMCHEM_DATA_DIR/templates/*.json` merge in with ids prefixed `user-`. Amino acid and nucleoside SMILES were checked with RDKit CIP (L amino acids S, cysteine R; isoleucine 2S,3S; threonine 2S,3R; adenosine 1'R,2'R,3'S,4'R). Haworth and Fischer templates carry no wedges, so the engine sees them without stereo; the skeletal glucose and fructose templates carry it. Everything is original data; docs/TEMPLATES.md is the format. + +## 74. The derived cache carries each step's balance check ยท _v0.5.0 (services/chem/derive.py reaction_checks) + +The balance check costs about a millisecond for a two plus two step, so `derive_document` adds a top-level `reactions` slot beside `fragments`: step id to `{balanced, elements, charge, mass, warnings}` (`CHECK_FIELDS`), at most 64 steps (`REACTION_CHECKS`), and a step whose check raises is skipped rather than failing the whole derive. `store._shape_derived` passes extra top-level keys through, so the store needed no change; FORMAT's derived table and `Derived.reactions` in model.ts describe the slot. The suggestion is not in the cache: it is only worth computing when someone asks for it. + +## 75. Four reaction tools on the MCP server ยท _v0.5.0 (routers/mcp.py) + +`perceive_reactions` and `map_reaction` change the drawing and are in `MUTATING`, so they go through the approval gate; `export_reaction` and `reaction_stoichiometry` are read-only. They call the same services as the routes and commit through `STORE.apply` with origin `agent` (`_apply`), so an agent's perception or mapping is one undo step the person sees. A tool that cannot find the step names `perceive_reactions` as the next step. `get_context` and the guide's opening still say that dedicated drawing tools arrive in 0.8.0; a sentence there naming the four reaction tools is still to add. `./formchem agents sync` regenerated the tools reference and the manifest with ten tools. + +## 76. Wiring the phase 5 routers and the frozen engine ยท _v0.5.0 (app/main.py, setup/freeze_backend, setup/freeze_backend.bat) + +The reactions and templates routers were written on their own branches and never included, so the window got 404 for every reaction and template route until main.py included both after `chem`, before the static mount at `/` (the routers carry full paths, so no prefix). `templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen, so both freeze scripts add `backend/app/data/templates` as `templates` data; without it the desktop library would be empty. Not run: pyinstaller, so the frozen sidecar with the template data is unchecked. From d4e8f8e16cefed184f7573fda7a6d2e809ada467 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:53:07 -0500 Subject: [PATCH 108/279] docs(wiki): add the Reactions page (0.5.0) Explains how to draw a scheme FormChem can read, what Perceive Reactions, Map Atoms, Check Balance and the Stoichiometry panel do, and how reactions are copied, exported and opened, linked from the sidebar and Home. --- .docs/wiki/Home.md | 1 + .docs/wiki/Reactions.md | 71 +++++++++++++++++++++++++++++++++++++++++ .docs/wiki/_Sidebar.md | 1 + 3 files changed, 73 insertions(+) create mode 100644 .docs/wiki/Reactions.md diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index c84ef7a3..9b0cacd1 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -8,6 +8,7 @@ FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, wi | --- | --- | | [Getting Started](Getting-Started) | Install, boot, your first structure, the dispatcher commands, ports and the data folder | | [Drawing](Drawing) | The tools, the hover keys, drawing with the keyboard alone, and styles | +| [Reactions](Reactions) | Reaction schemes, roles, atom mapping, balance, stoichiometry, RXN and reaction SMILES | | [Agents](Agents) | The MCP server, agent configs, skills and consent | | [Terminal](Terminal) | The terminal and agent dock | | [Extensions](Extensions) | Form extensions in FormChem | diff --git a/.docs/wiki/Reactions.md b/.docs/wiki/Reactions.md new file mode 100644 index 00000000..4606bded --- /dev/null +++ b/.docs/wiki/Reactions.md @@ -0,0 +1,71 @@ +# Reactions + +From 0.5.0 FormChem reads a drawn scheme as a reaction: which structures react, which are reagents, what the conditions are. It can then map the atoms, check the balance and work out the amounts. Everything here is in the Reaction menu, and every change it makes is one undo step. The engine side, with every route, is [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md). + +## Draw the scheme + +1. Draw or insert the structures (Insert > Structure from SMILES, a template, or the drawing tools). +2. Pick the arrow tool (`W`, or Reaction > Add Reaction Arrow) and drag from the reactants towards the products. `Shift` snaps to 15 degrees; `Alt` draws the arrow's other kind (an equilibrium becomes unbalanced, a forward arrow dashed). +3. Put plus signs between structures with the symbol tool (`P`); a plus snaps to the centre line of the structure beside it. +4. Put reagents above or below the arrow, as structures or text (`T`), for example "reflux, 2 h". + +Several arrows in a row make a multi-step reaction: the product of one step is the reactant of the next. + +## Perceive Reactions + +Reaction > Perceive Reactions reads every reaction arrow on the page and stores its steps: + +| Role | Where it sits | +| --- | --- | +| Reactants | before the arrow's tail, within 2.5 bond lengths of the arrow's line | +| Products | after the arrow's head, within the same distance | +| Reagents | between the tail and the head, within 1.5 bond lengths of the arrow | +| Conditions | text in that same band | + +The nearest structure on each side takes the role; the next one joins it only across a plus sign or a gap under one bond length. Captions never take a role. Resonance, electron-pushing, fishhook, plain, fragmentation and dissociation arrows are not reaction steps; a retrosynthetic arrow reads from right to left. + +Running it again keeps the same reaction ids, your amounts and coefficients, and changes nothing when nothing moved. Steps read from a reaction file keep the roles the file gave. Set Reaction Roles, to choose roles by hand, arrives in 0.6.0. + +## Map Atoms + +Reaction > Map Atoms numbers each reactant atom with the product atom it becomes and marks the bonds that break, form or change order (it perceives first when the page has no step yet). The toast says whether every atom was mapped. Clear Atom Mapping removes the numbers and marks. Map numbers show next to the atoms. + +A command acts on the step whose arrow or structures you selected, or the first step on the page. + +## Check and balance + +Reaction > Check Balance... opens a dialog with the count of each element on both sides, the charge and the mass. When the step is not balanced it suggests coefficients (such as 2 A + B) or a missing co-product such as water or HCl. Balance Reaction, or the Balance button in the dialog, writes the coefficients. Reagents drawn above the arrow are not counted. + +A resonance arrow between two structures that are not resonance forms (different formula, charge or skeleton) shows a warning. + +## Stoichiometry + +View > Stoichiometry Panel (also in the Reaction menu) opens a grid under the canvas for the selected step: + +- Type a mass, or a volume with its density, or a volume with a solution's concentration, or equivalents, for each reactant and reagent; purity and a molecular weight of your own (for a salt or hydrate) are optional. +- Or type a scale in mmol for the reaction. +- The grid shows moles, equivalents, masses and volumes, marks the limiting reagent, and gives the theoretical yield. Type the isolated mass of the product for the percent yield. + +What you type is stored in the drawing; everything else is worked out. Typing a mass, a volume or equivalents for a component replaces the other two for that component, and a scale and the limiting reagent's own amount replace each other, so there is always one source for each number. Reaction > Insert Stoichiometry Table puts the grid on the page as a table under the reaction; inserting it again refreshes the same table. + +Example: 1.00 g benzoic acid with 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol and 9.83 mmol, so 0.713 mL of thionyl chloride. + +## Copy, export, paste and open + +- Reaction > Copy Reaction As > SMILES or RXN puts the step on the clipboard, with its map numbers. +- Reaction > Export Reaction writes a `.rxn` or reaction SMILES file; the RXN keeps the title and the conditions line. +- Reaction > Insert Reaction from Clipboard lays out pasted reaction SMILES or an RXN as a drawn scheme with an arrow, plus signs and the conditions under the arrow. +- File > Open opens `.rxn` files, and CML or CDXML files holding a reaction, as drawn schemes. + +Coefficients have no place in reaction SMILES or RXN and are left out. + +## For agents + +Four MCP tools: `perceive_reactions`, `map_reaction` (with `mode: "clear"` to remove a mapping), `export_reaction` and `reaction_stoichiometry`. The first two change the drawing and ask you first, like any agent change. See [Agents](Agents). + +## Known limits + +- A structure that is the product of one step and the reactant of the next has one set of map numbers; mapping the second step replaces the first step's numbers. +- A step whose atoms come from a reagent drawn above the arrow reads as unbalanced. +- A `.smi` file with reaction SMILES does not open as a reaction; paste its text with Insert Reaction from Clipboard. +- Perception reads top-level objects only (a group counts as one) and reads a bent arrow by its ends. diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index ad54eaf6..1884a9c6 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -3,6 +3,7 @@ - [Home](Home) - [Getting Started](Getting-Started) - [Drawing](Drawing) +- [Reactions](Reactions) - [Agents](Agents) - [Terminal](Terminal) - [Extensions](Extensions) From 19280634d7010b8abe7df027d749bc56f4b1f331 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:53:35 -0500 Subject: [PATCH 109/279] docs(wiki): add the Annotations page (0.5.0) Covers the arrow, symbol, bracket, shape, table, TLC, image, orbital and caption tools, handles, arranging and grouping, the template library, Find and the rulers, linked from the sidebar and Home. --- .docs/wiki/Annotations.md | 62 +++++++++++++++++++++++++++++++++++++++ .docs/wiki/Home.md | 1 + .docs/wiki/_Sidebar.md | 1 + 3 files changed, 64 insertions(+) create mode 100644 .docs/wiki/Annotations.md diff --git a/.docs/wiki/Annotations.md b/.docs/wiki/Annotations.md new file mode 100644 index 00000000..f01032ff --- /dev/null +++ b/.docs/wiki/Annotations.md @@ -0,0 +1,62 @@ +# Annotations + +Everything on the page that is not a structure: arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures and captions, plus arranging and grouping them, the template library, Find and the rulers. All of it arrived in 0.5.0. Each gesture is one undo step, and `Escape` cancels a gesture in progress. How each object is stored is in [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md). + +## The tools + +| Key | Group | Tools | What a click or drag does | +| --- | --- | --- | --- | +| `W` | Arrows | Reaction, equilibrium, retrosynthetic, resonance, no-go, dashed, line, electron-pushing, fishhook | Drag from tail to head; a click places an arrow four bond lengths long. `Shift` snaps to 15 degrees, `Alt` picks the other kind (equilibrium to unbalanced, resonance to reversible, no-go cross to slash, forward to dashed). | +| `P` | Symbols | Plus, equals, adduct dot | Click to place; the sign snaps to the centre line of the structure beside it (`Alt` places it exactly). | +| `K` | Brackets | Round, square, curly | Drag around atoms; a click on a structure brackets all of it. A repeat unit with two crossing bonds is labelled `n`. Double-click a bracket to change its label. | +| `G` | Shapes | Rectangle, rounded rectangle, ellipse, polygon, line and polyline | Drag a box (`Shift` square, `Alt` from the centre) or click for a default size. Lines: drag for a line, or click point by point and double-click (or click the first point) to finish a polyline. | +| | Table | Table | Drag to size: the cell count follows the drag (48 by 18 pt cells); `Shift` styles the first row as a header. | +| | TLC | TLC plate | Drag a plate; it gets one lane per 20 pt of width. Click on a plate to add a spot to the nearest lane at that height (Rf to 0.01). | +| | Image | Image | Choose a PNG, JPEG, GIF, WebP or SVG file; a click places it at its natural size (at most 240 pt), a drag fits it into the box. Also Insert > Image... | +| `O` | Orbitals | p, s, d, dz2, sp, sigma, pi | Click to place, drag to size and turn; dropped on an atom, it stays on that atom. | +| `T` | Text | Text, Caption | `Shift+T` steps to Caption: click a structure to attach its name under it; `Ctrl`-click (`Cmd` on macOS) adds the next compound number in bold. | + +Insert > Arrow, Shape and Table pick the same tools. + +## Electron-pushing arrows + +Start the drag on an atom, on a bond, or (when the atom shows lone pairs) on its lone pair; hold `Ctrl` or `Cmd` at the press to start on the atom itself. End on an atom, a bond, or in the space between two atoms where a new bond forms. The arrow bends 90 degrees away from the structure (`Alt` flips the bulge); the fishhook draws a half head (`Shift` for the other side). Both ends follow their atoms when the structure moves. Hover an atom and press `:` to add lone pairs first. + +## Handles + +With the selection tool, a single selected object shows its handles: an arrow's tail, head and bend (the round handle), a line's points, or eight handles around a shape, picture, bracket, table or TLC plate. Drag one to reshape; `Shift` snaps arrow ends to 15 degrees and the bend to 15 degree steps. Dragging an anchored arrow end frees it. Pictures keep their proportions; tables scale their columns and rows. + +## Captions + +A caption belongs to its structure: move the structure and the caption follows; drag the caption and it stays where you put it relative to the structure. Compound numbers count up from the highest number already on the page. + +## Arrange and group + +| Command | Keys | +| --- | --- | +| Arrange > Bring to Front | `Ctrl+Shift+]` | +| Bring Forward | `Ctrl+]` | +| Send Backward | `Ctrl+[` | +| Send to Back | `Ctrl+Shift+[` | +| Group | `Ctrl+G` | +| Ungroup | `Ctrl+Shift+G` | + +Align, distribute, flip and rotate work on objects as on structures. A click on any member of a group selects the whole group; `Alt`-click or a double-click reaches the member. Deleting a group deletes its members. Shapes and pictures are drawn behind structures, so a filled box never hides a label. + +## Templates + +Insert > Template... opens the library: 206 original templates in nine categories (rings, polycycles, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and solvents, glassware), with search by name and tag. Home shows the same library on Start and on its Templates page. A click inserts the template in the middle of the view as one undo step, at the drawing's bond length, and selects it; with no drawing open, a new one is made. + +Your own templates: put JSON files in `~/formchem/templates` (or `FORMCHEM_DATA_DIR/templates`) in the format of [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md); they show with the built-in ones. + +## Find + +Edit > Find... searches the text in the drawing. Next and Previous step through the matches, and Replace puts your text in place of a match, as one undo step. + +## Rulers + +View > Show Rulers shows rulers along the canvas. Drag out of a ruler to place a guide to line objects up against. + +## Not yet + +`Enter` does not finish a polyline. Templates cannot be fused onto an atom or a bond yet, and land in the middle of the view even if something is there. Bracket tilt for slanted bonds, table cell editing, dragging TLC spots and choosing an orbital's phase or fill come later. diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 9b0cacd1..0f4c6d77 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -8,6 +8,7 @@ FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, wi | --- | --- | | [Getting Started](Getting-Started) | Install, boot, your first structure, the dispatcher commands, ports and the data folder | | [Drawing](Drawing) | The tools, the hover keys, drawing with the keyboard alone, and styles | +| [Annotations](Annotations) | Arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures, captions, arranging and grouping, templates, Find and rulers | | [Reactions](Reactions) | Reaction schemes, roles, atom mapping, balance, stoichiometry, RXN and reaction SMILES | | [Agents](Agents) | The MCP server, agent configs, skills and consent | | [Terminal](Terminal) | The terminal and agent dock | diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index 1884a9c6..a12b29a5 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -3,6 +3,7 @@ - [Home](Home) - [Getting Started](Getting-Started) - [Drawing](Drawing) +- [Annotations](Annotations) - [Reactions](Reactions) - [Agents](Agents) - [Terminal](Terminal) From 790b230e45617153cae39c65eed3730078583921 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:53:49 -0500 Subject: [PATCH 110/279] docs(wiki): point Drawing and Home at the 0.5.0 tools and commands (0.5.0) Drawing gains the annotation tool groups, handles, the new Arrange and Edit commands and the template and reaction ways in; Home's status line names what 0.5.0 added. --- .docs/wiki/Drawing.md | 5 +++-- .docs/wiki/Home.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.docs/wiki/Drawing.md b/.docs/wiki/Drawing.md index 930c7208..07cb9e4e 100644 --- a/.docs/wiki/Drawing.md +++ b/.docs/wiki/Drawing.md @@ -17,8 +17,9 @@ Press a tool's key with the pointer away from atoms and bonds, or click it on th | `E` | Eraser | Eraser | Click or drag across atoms, bonds and objects to remove them. | | `H` | Hand | Hand | Drag to pan (holding `Space` pans with any tool). | | `Z` | Zoom | Zoom | Click to zoom in at the point, `Alt`-click to zoom out. `Ctrl` with the wheel zooms anywhere; View has Zoom In (`Ctrl+=`), Zoom Out (`Ctrl+-`), Zoom to Fit (`Ctrl+0`) and Actual Size (`Ctrl+1`). | +| `W` `P` `K` `G` `O` | Arrows, Symbols, Brackets, Shapes, Orbitals | and Table, TLC, Image, Caption (in Text) | The annotation tools of 0.5.0; see [Annotations](Annotations). Reaction arrows and plus signs make a scheme FormChem can read; see [Reactions](Reactions). | -Right-click an atom, a bond or the paper for its context menu. Structure has Clean Up Structure, Lay Out Structure, Check Structure and the flips; Arrange has align, distribute and Rotate 90 Degrees; Edit has Duplicate (`Ctrl+D`), Delete and Select All (`Ctrl+A`). +Right-click an atom, a bond or the paper for its context menu. Structure has Clean Up Structure, Lay Out Structure, Check Structure and the flips; Arrange has the stacking order, align, distribute, Rotate 90 Degrees, Group and Ungroup; Edit has Duplicate (`Ctrl+D`), Delete, Select All (`Ctrl+A`) and Find. With the selection tool, a selected arrow, line or box shows handles to reshape it. ## Hover keys @@ -68,7 +69,7 @@ While the pointer rests on an atom or a bond, its hover keys win over the tool k 5. Every hover key works on the atom or bond under the cursor: `O` for oxygen, `2` for a double bond, `Shift+6` for a ring, `4` for a chain of four, `Enter` then typing for a label. 6. The context-menu key or `Shift+F10` opens the menu of the atom or bond under the cursor. `Escape` leaves the cursor. -Structures can also come in without drawing: Insert > Structure from SMILES, or File > Open for molfile, SDF, RXN, SMILES, InChI, CML and CDXML files. +Structures can also come in without drawing: Insert > Structure from SMILES, Insert > Template... (206 rings, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and glassware), Reaction > Insert Reaction from Clipboard, or File > Open for molfile, SDF, RXN, SMILES, InChI, CML and CDXML files (RXN files and reactions in CML or CDXML open as drawn schemes). ## Styles diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 0f4c6d77..fa5105db 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ FormChem is the chemical structure drawing suite of the FormAI family: local-first, no account, on macOS, Windows and Linux. It runs in the browser or as a Tauri desktop app, with a local engine that holds every document, and an MCP server so Claude Code, Codex, Cursor or Antigravity can work in the same window you see. -FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, and 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel. +FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, and 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers. | Page | What it covers | | --- | --- | From fcbd30dcc1d66e085119bbe052ff62b1dc8981ed Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:54:06 -0500 Subject: [PATCH 111/279] docs(wiki): list the reaction tools and 0.5.0 commands for agents (0.5.0) The MCP server now has ten tools; the Agents page gives the four reaction tools with their arguments and which ask first, and the template, arrange and reaction commands agents can run. --- .docs/wiki/Agents.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index 74e12c77..f7e499fd 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -15,7 +15,16 @@ FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at ## Tools -Six tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff` (working, ready or question, with a note). The first three read; `run_command`, `extension_command` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run. +Ten tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` (working, ready or question, with a note), and from 0.5.0 four reaction tools: + +| Tool | Kind | What it does | +| --- | --- | --- | +| `perceive_reactions {doc?, page?}` | changes the drawing | reads the reaction arrows and stores each step's reactants, products, agents and conditions (one undo step); steps set by hand are kept; lists reaction and step ids | +| `map_reaction {doc?, reaction?, step?, mode?}` | changes the drawing | maps reactant atoms to product atoms and marks bonds broken, formed and changed (`mode`: `discard`, `keep`, `alter`, or `clear` to remove) | +| `export_reaction {doc?, reaction?, step?, format?}` | reads | a step as reaction SMILES (`smiles`) or RXN (`rxn`, `rxnv3000`) with its map numbers | +| `reaction_stoichiometry {doc?, reaction?, step?}` | reads | moles, equivalents, masses, volumes, the limiting reagent and yields from the amounts in the step, with the balance check | + +`doc` may be left out when one drawing is open; `reaction` and `step` default to the first. `get_context`, `list_commands`, `extensions_list`, `export_reaction` and `reaction_stoichiometry` read; `run_command`, `extension_command`, `perceive_reactions`, `map_reaction` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run. ## Working on drawings @@ -35,11 +44,13 @@ An agent changes drawings with the window's own commands, so every change is one | Add a structure | `run_command {id: "insert-smiles", params: {smiles: "c1ccccc1O"}}`: into the active drawing (a new one when none is open), centred in view, selected; the answer names the new fragment ids | | Open a file | `run_command {id: "open-recent", params: {path: "/abs/path/file.mol"}}` (a `.fchem`, or a structure file as a new drawing) | | Tidy or lay out | `clean-structure` or `layout-structure`: the selection, or every structure on the page | -| Arrange the selection | `select-all`, then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h`, `distribute-v` | +| Arrange the selection | `select-all`, then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h`, `distribute-v`, `bring-front`, `send-back`, `group`, `ungroup` | +| Insert a template | `run_command {id: "insert-template", params: {id: "benzene"}}`: one undo step, centred in view at the drawing's bond length; `GET /api/templates` lists the ids | +| Reactions | `perceive-reactions`, `map-atoms`, `clear-mapping`, `balance-reaction` through `run_command`, or the four reaction tools above, which also return the results; `check-reaction` and the Stoichiometry panel (`show-stoichiometry`) open for the person | | Check | `check-structure` opens a dialog for the person; formula and masses are in the Analysis panel (`show-analysis`) | | Undo, save | `undo`, `redo`, `save` (a drawing without a file asks the person for a name) | -Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Dedicated drawing tools for agents (atoms and bonds by id, reading structures back, rendering, conversion) arrive in 0.8.0. +Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Beyond the reaction tools, dedicated drawing tools for agents (atoms and bonds by id, reading structures back, rendering, conversion) arrive in 0.8.0. The engine's HTTP routes for reactions, templates and media are listed in [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md), [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md) and [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md). ## Consent From 4bc6cc617ffe712dac4f60d1d1a4b1ff270cabea Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:54:35 -0500 Subject: [PATCH 112/279] docs(wiki): describe 0.5.0 objects, reactions, media and the reaction services (0.5.0) Project Format now covers the drawn object kinds, captions and their cache, reaction steps with stoichiometry, and media; Architecture names the reaction, template and media services and how they join the document flow. --- .docs/wiki/Architecture.md | 15 +++++++++------ .docs/wiki/Project-Format.md | 8 ++++++-- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index c0adf8d8..9def3f86 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -1,10 +1,11 @@ # Architecture ``` -frontend/ vanilla TypeScript and Vite: engine/ (model, ops, document client, session), chem/ (valence, rings, formula), canvas/ (view, tools, render/), - app/ (menus, shell and canvas commands, documents, window tools), ui/ (shell, menus, Home, Preferences, tool rail, Analysis panel), dock/, extensions/, styles/ -backend/ FastAPI engine: core/ (config, guard, window key, seal), routers/ (system, live, library, commands, documents, chem, terminal, chat, extensions, mcp), - services/ (model, ops, store, history, package, importers, chem/ on RDKit) +frontend/ vanilla TypeScript and Vite: engine/ (model, ops, document client, session, reactions-api), chem/ (valence, rings, formula, stoich), + canvas/ (view, hit testing, tools, render/ with one module per object kind), app/ (menus, shell, canvas, object and reaction commands, + documents, window tools), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and Stoichiometry panels, template library), dock/, extensions/, styles/ +backend/ FastAPI engine: core/ (config, guard, window key, seal), routers/ (system, live, library, commands, documents, chem, reactions, templates, + terminal, chat, extensions, mcp), services/ (model, ops, store, history, package, importers, templates, chem/ on RDKit and Indigo), data/templates/ src-tauri/ the desktop shell; the engine runs as a frozen sidecar ``` @@ -18,8 +19,8 @@ The engine holds every open document in its store (`backend/app/services/store.p 2. **The window applies it at once.** `EngineDocumentClient.commit` validates and applies the ops to the mirror, marks the transaction pending and sends it on the live socket (or over HTTP when the socket is down). The person sees the change in the same frame. 3. **The engine applies it for good.** The store normalises the ops, applies them, validates the result (rolling the whole transaction back on any failure), raises the revision, records the inverse for undo, merges a stream of small edits that share a coalescing key, and schedules autosave and version snapshots (`history.py`). 4. **Everyone hears about it.** The engine broadcasts the transaction with the new revision to every window and agent. The sending window drops it from its pending list; other windows apply it to their mirror. After a dropped connection a window resyncs from a snapshot and resends what was still pending. -5. **The derived cache follows.** After each transaction the engine derives the chemistry of the changed fragments in a worker thread with RDKit (`services/chem/derive.py`, cached per fragment): canonical SMILES and CXSMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors and warnings. It broadcasts the result keyed by fragment id and revision. It is never saved: it is rebuilt whenever a drawing opens. -6. **The renderer patches.** The canvas (`canvas/render/`) draws in SVG keyed by object, atom and bond id. Ops share structure, so the renderer compares records by reference, re-lays out only the changed atoms and their neighbours, and patches the attributes of the nodes whose drawing changed; it never rebuilds the canvas. Until the derived cache for the current revision arrives, it draws implicit hydrogens and double-bond sides from the window's own tables (`frontend/src/chem/`); then it adopts the engine's values. Hit testing works on the model geometry, not on DOM nodes. +5. **The derived cache follows.** After each transaction the engine derives the chemistry of the changed fragments in a worker thread with RDKit (`services/chem/derive.py`, cached per fragment): canonical SMILES and CXSMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors and warnings, plus the balance check of every reaction step. It broadcasts the result keyed by fragment id and revision. It is never saved: it is rebuilt whenever a drawing opens. +6. **The renderer patches.** The canvas (`canvas/render/`) draws in SVG keyed by object, atom and bond id; every object kind (arrows, symbols, brackets, shapes, lines, tables, TLC plates, orbitals, images, captions, groups) goes through one registry, and a change of stacking order moves only the nodes out of place. Ops share structure, so the renderer compares records by reference, re-lays out only the changed atoms and their neighbours, and patches the attributes of the nodes whose drawing changed; it never rebuilds the canvas. Until the derived cache for the current revision arrives, it draws implicit hydrogens and double-bond sides from the window's own tables (`frontend/src/chem/`); then it adopts the engine's values. Hit testing works on the model geometry, not on DOM nodes. Undo and redo are engine operations: the engine applies the recorded inverse as a new transaction with origin `history` and broadcasts it like any other. @@ -38,3 +39,5 @@ Vanilla TypeScript, no UI framework. Every colour, space and z-index comes from ## Chemistry core RDKit (structure model, canonical SMILES, InChI, stereo, coordinates) and Indigo (chemical drawing formats) are pinned in `backend/requirements.txt`. The engine's chemistry service (`backend/app/services/chem/`, routes under `/api/chem`) is the authority for sanitising, valence, aromaticity, identifiers, formula and masses, 2D clean-up and layout, and reading SMILES, molfile, SDF, RXN, CML and CDXML. The window only computes what it must draw at once without the engine. + +From 0.5.0 the same service reads reactions: perception of roles around the arrows, atom mapping with Indigo, balance, stoichiometry, and reaction SMILES and RXN exchange, under `/api/documents/{id}/reactions` ([`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md)). Each changing reaction route applies one transaction through the store and broadcasts it like any other. The window computes stoichiometry itself for the panel and the drawn grid with the same rules (`frontend/src/chem/stoich.ts`). The template library (`/api/templates`) is data in `backend/app/data/templates` built once and cached, and pictures enter a drawing through `/api/documents/{id}/media`. diff --git a/.docs/wiki/Project-Format.md b/.docs/wiki/Project-Format.md index 5aaec615..d74320ed 100644 --- a/.docs/wiki/Project-Format.md +++ b/.docs/wiki/Project-Format.md @@ -20,10 +20,14 @@ The engine writes the package to a temporary file in the same folder and renames - `pages` is a list; each page has a size, margins and an `order` of object ids. - `objects` is a map by id. A fragment (`kind: "fragment"`) holds `atoms` and `bonds` maps; text objects carry runs of styled text. - Ids are short random strings, stable for life and never reused in a document. Agents, extensions and the renderer address everything by id. +- From 0.5.0 the other object kinds are drawn: `arrow` (15 types, heads at either end, a signed `bend`, and `anchors` that tie an end to an atom, a lone pair, a bond or the space between two atoms), `plus`, `bracket`, `shape`, `line`, `table`, `tlc`, `orbital`, `image` and `caption`. A `group` lists its `children` back to front; members are in no page `order`. +- A `caption` has a `target` (the structure it belongs to) and an `offset` from the target's bottom centre; its `x`, `y` are a cache kept in step whenever the target or the caption moves. Compound numbers are `number: {auto: true, value: "1"}`. +- `page.reactions` lists reactions and their steps: the arrow, the reactant, product, agent and condition object ids, `explicit` (roles set by hand or by a file, kept by perception), optional `coefficients`, and optional `stoich`, the amounts you typed in the Stoichiometry panel (`scale_mmol`, `limiting`, `product`, `isolated_mg`, and per component `equiv`, `mass_mg`, `volume_ml`, `density_g_ml`, `conc_m`, `purity_pct`, `mw`). Moles, masses implied by equivalents, the limiting reagent and yields are worked out, never stored. A `table` with `stoich: {reaction, step}` is a stoichiometry grid. Atom map numbers are `map` on atoms and reacting marks `reacting` on bonds. +- `media` maps a media id to `{name, mime, bytes, w, h, sha256}`; an `image` object names the id. The bytes go into the package as `media/[id].[ext]`, and only ids listed in `media` are written. ## What is not in the file -The engine's chemistry (canonical SMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors, warnings) is a derived cache. It is rebuilt when a drawing opens and broadcast after every change, keyed by fragment id and document revision, and never saved. Undo history is kept per open drawing by the engine and is not saved either. +The engine's chemistry (canonical SMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors, warnings, and from 0.5.0 the balance check of every reaction step) is a derived cache. It is rebuilt when a drawing opens and broadcast after every change, keyed by fragment id and document revision, and never saved. Undo history is kept per open drawing by the engine and is not saved either. ## Changes are transactions @@ -31,4 +35,4 @@ Every change is a transaction: a list of `set`, `ins`, `del` and `move` ops on J ## Other formats -Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length. Exporting to them arrives in 0.7.0. +Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length; RXN files and CML or CDXML files with a reaction open as drawn schemes with their roles set. A reaction step exports as reaction SMILES or RXN (V2000 or V3000) from 0.5.0 ([Reactions](Reactions)); exporting whole drawings to the other formats arrives in 0.7.0. Templates use the document format too ([`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md)). From 3364c871e0fab930116763acfa3469df16c280a4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:54:55 -0500 Subject: [PATCH 113/279] docs(readme): add reactions, annotations, stoichiometry and templates to the features (0.5.0) The feature grid gains a row for what 0.5.0 draws and computes, the MCP tile and agent paragraph name the four reaction tools, and reactions leave the coming-next list; the version badge is left to the release commit. --- README.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8a5d08c8..75fd6972 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ ## Features -FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas with the mouse or the keyboard, and the chemistry engine checks and measures every change. +FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms and works out the amounts. @@ -42,7 +42,12 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit - + + + + + + @@ -50,7 +55,6 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit ### Coming next -- Reactions, arrows and annotations - Stereochemistry, query structures and analysis - Reading and writing the common chemical file formats - Names, predicted spectra and spectrum viewing @@ -59,7 +63,7 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit ## Built for agents -The engine's MCP server drives the same command catalogue as the window through six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`. Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0. +The engine's MCP server drives the same command catalogue as the window through `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus four reaction tools: `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`. Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0. ```sh ./formchem agents install # writes .mcp.json, .codex/config.toml, .cursor/mcp.json and Antigravity's ~/.gemini/config/mcp_config.json, installs the skills @@ -96,7 +100,7 @@ cd formchem `./formchem desktop dev` opens the desktop window instead. On Windows use `formchem.bat install` and `formchem.bat`. The engine listens on `127.0.0.1:8220` (MCP at `/mcp`); `FORMCHEM_DATA_DIR` moves the data folder from `~/formchem`. > [!IMPORTANT] -> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures; reactions, export, stereo tools and 3D come in later versions. Nothing is built or released for download yet. +> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures and reactions; export, stereo tools and 3D come in later versions. Nothing is built or released for download yet. **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Report security issues privately as [`SECURITY.md`](SECURITY.md) describes. @@ -104,7 +108,7 @@ cd formchem | Path | What it is | |---|---| -| `backend/` | FastAPI engine: documents, live channel, terminal dock, extensions, MCP | +| `backend/` | FastAPI engine: documents, chemistry and reactions, templates, live channel, terminal dock, extensions, MCP | | `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, shell, menus, Home, Preferences, dock | | `setup/` | Install, boot, build, freeze and agent setup scripts | | `src-tauri/` | Desktop shell and the engine sidecar | From 5d4e02b4e823b5be6721ea61cfa135d174241dec Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:55:14 -0500 Subject: [PATCH 114/279] build(agents): give the generated MCP tools reference a contents list (0.5.0) With ten tools the reference passed 100 lines and the skill validator warned D4; the generator now writes the list from the TOOLS list, so the regenerated file and its mirror stay in step with sync --check. --- .../skills/formchem-harness/references/tools.md | 15 +++++++++++++++ .../skills/formchem-harness/references/tools.md | 15 +++++++++++++++ backend/HASHOUT_LOG.md | 5 +++++ setup/agents.py | 1 + 4 files changed, 36 insertions(+) diff --git a/.agents/skills/formchem-harness/references/tools.md b/.agents/skills/formchem-harness/references/tools.md index 8b50525a..d3fc2305 100644 --- a/.agents/skills/formchem-harness/references/tools.md +++ b/.agents/skills/formchem-harness/references/tools.md @@ -4,6 +4,21 @@ Generated by `./formchem agents sync` from the TOOLS list in `backend/app/router Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. +## Contents + +- Tool kinds (the table below) +- get_context +- list_commands +- run_command +- extensions_list +- extension_command +- handoff +- perceive_reactions +- map_reaction +- export_reaction +- reaction_stoichiometry +- Resource + | Tool | Kind | | --- | --- | | `get_context` | read-only | diff --git a/.claude/skills/formchem-harness/references/tools.md b/.claude/skills/formchem-harness/references/tools.md index 8b50525a..d3fc2305 100644 --- a/.claude/skills/formchem-harness/references/tools.md +++ b/.claude/skills/formchem-harness/references/tools.md @@ -4,6 +4,21 @@ Generated by `./formchem agents sync` from the TOOLS list in `backend/app/router Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. +## Contents + +- Tool kinds (the table below) +- get_context +- list_commands +- run_command +- extensions_list +- extension_command +- handoff +- perceive_reactions +- map_reaction +- export_reaction +- reaction_stoichiometry +- Resource + | Tool | Kind | | --- | --- | | `get_context` | read-only | diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 93b68b77..954b29a4 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -109,6 +109,7 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log 74. The derived cache carries each step's balance check ยท services/chem/derive.py reaction_checks 75. Four reaction tools on the MCP server ยท routers/mcp.py 76. Wiring the phase 5 routers and the frozen engine ยท app/main.py, setup/freeze_backend, setup/freeze_backend.bat +77. The generated tools reference carries a contents list ยท setup/agents.py tools_text ## 1. Ports and the data folder are FormChem's own ยท _v0.1.0 (app/core/config.py) @@ -413,3 +414,7 @@ The balance check costs about a millisecond for a two plus two step, so `derive_ ## 76. Wiring the phase 5 routers and the frozen engine ยท _v0.5.0 (app/main.py, setup/freeze_backend, setup/freeze_backend.bat) The reactions and templates routers were written on their own branches and never included, so the window got 404 for every reaction and template route until main.py included both after `chem`, before the static mount at `/` (the routers carry full paths, so no prefix). `templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen, so both freeze scripts add `backend/app/data/templates` as `templates` data; without it the desktop library would be empty. Not run: pyinstaller, so the frozen sidecar with the template data is unchecked. + +## 77. The generated tools reference carries a contents list ยท _v0.5.0 (setup/agents.py tools_text) + +With ten tools, `.claude/skills/formchem-harness/references/tools.md` grew past 100 lines and the god-tier-skill-creator validator warned D4 (a reference file of 100 lines or more needs a `## Contents` section). The file is generated, so a hand edit would be undone by the next sync and fail `sync --check`; `tools_text` now writes `## Contents` after the opening paragraphs, listing the kinds table, every tool section from the TOOLS list and the resource, so the list follows the server as tools are added. Both packs validate with zero FAIL and zero WARN afterwards. diff --git a/setup/agents.py b/setup/agents.py index 9ea28117..9a8c2d29 100644 --- a/setup/agents.py +++ b/setup/agents.py @@ -219,6 +219,7 @@ def tools_text() -> str: "Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step.", "", "Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); " "agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked.", "", + "## Contents", "", "- Tool kinds (the table below)"] + [f"- {t['name']}" for t in tools] + ["- Resource", "", "| Tool | Kind |", "| --- | --- |"] for t in tools: kind = "read-only" if t["read"] else "approval-gated" if t["name"] in data["always"] else "approval-gated when it changes something" if t["name"] in data["sometimes"] else "no approval" From e4cb12d2b3f87b4505fdf4e14f0c432fd3daa070 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:57:42 -0500 Subject: [PATCH 115/279] chore(skills): teach formchem-harness the reaction tools and 0.5.0 commands (0.5.0) A new reactions sub-skill drives perceive_reactions, map_reaction, export_reaction and reaction_stoichiometry from ids and quotes their numbers; the router, command catalogue and evals now describe ten tools, templates, arrangement and the Reaction menu, validated with zero FAIL and mirrored by agents sync. --- .agents/skills/formchem-harness/EVALS.json | 33 ++++++++++- .agents/skills/formchem-harness/SKILL.md | 24 ++++---- .../sub-skills/handoff/SUB-SKILL.md | 4 +- .../sub-skills/reactions/SUB-SKILL.md | 59 +++++++++++++++++++ .../session-and-connection/SUB-SKILL.md | 2 +- .../sub-skills/visual-qa/SUB-SKILL.md | 2 +- .../sub-skills/window-commands/SUB-SKILL.md | 7 ++- .../references/command-catalogue.md | 39 ++++++++++-- .claude/skills/formchem-harness/EVALS.json | 33 ++++++++++- .claude/skills/formchem-harness/SKILL.md | 24 ++++---- .../sub-skills/handoff/SUB-SKILL.md | 4 +- .../sub-skills/reactions/SUB-SKILL.md | 59 +++++++++++++++++++ .../session-and-connection/SUB-SKILL.md | 2 +- .../sub-skills/visual-qa/SUB-SKILL.md | 2 +- .../sub-skills/window-commands/SUB-SKILL.md | 7 ++- .../references/command-catalogue.md | 39 ++++++++++-- agents/manifest.json | 1 + 17 files changed, 297 insertions(+), 44 deletions(-) create mode 100644 .agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md create mode 100644 .claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md diff --git a/.agents/skills/formchem-harness/EVALS.json b/.agents/skills/formchem-harness/EVALS.json index b9836b2d..fb9b9f39 100644 --- a/.agents/skills/formchem-harness/EVALS.json +++ b/.agents/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.4.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.4.0 has drawings but no direct agent drawing tools (0.8.0); agents work through run_command and Form extensions, and several evals check that the agent stays inside that.", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.5.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.5.0 has drawings and four reaction tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water).", "evals": [ { "id": 1, @@ -138,10 +138,37 @@ "Calls extensions_list and uses an extension command only if one states that it reads the drawing or checks structures", "Reports valence errors only from that extension's answer; with no suitable extension, says the agent cannot read the rows and points the person at the Check Structure dialog instead of computing valence itself" ] + }, + { + "id": 13, + "name": "map-and-export-the-drawn-reaction", + "prompt": "Map the atoms of the esterification I drew in FormChem and give me the reaction SMILES.", + "files": [], + "expected_behavior": [ + "Calls get_context, then perceive_reactions, and keeps the reaction and step ids it returns", + "Calls map_reaction with those ids (mode left at discard) and reports the mapped count and the bonds broken and formed from its answer", + "Calls export_reaction with format smiles and quotes the text exactly, passing on any conditions_dropped warning", + "Ends with a ready handoff naming the drawing and that Undo removes the mapping" + ] + }, + { + "id": 14, + "name": "yield-without-amounts", + "prompt": "What is the theoretical yield of my FormChem reaction?", + "files": [], + "expected_behavior": [ + "Calls perceive_reactions, then reaction_stoichiometry for the step", + "Quotes the theoretical yield with its unit only when the answer gives one, never computing it from its own molecular weights", + "When no amounts are typed, posts a question handoff asking the person to type a mass, volume, equivalents or scale in the Stoichiometry panel, and says no tool can type them" + ] } ], "trigger_evals": [ {"query": "what can FormChem do at the moment", "should_trigger": true}, + {"query": "map the atoms of the reaction in my formchem drawing", "should_trigger": true}, + {"query": "export the drawn reaction in FormChem as an RXN file", "should_trigger": true}, + {"query": "what is the limiting reagent in my formchem scheme?", "should_trigger": true}, + {"query": "insert a cyclohexane chair template in FormChem", "should_trigger": true}, {"query": "open preferences in formchem", "should_trigger": true}, {"query": "is the formchem engine running? I get connection refused", "should_trigger": true}, {"query": "run the hello command of my formchem extension", "should_trigger": true}, @@ -167,6 +194,8 @@ {"query": "run the show-grid command in formvis", "should_trigger": false}, {"query": "install the molecule tools extension from FormPortal", "should_trigger": false}, {"query": "convert this SDF file to SMILES with RDKit in a Python script", "should_trigger": false}, - {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false} + {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false}, + {"query": "fix the perception distances in formchem's services/chem/reactions.py", "should_trigger": false}, + {"query": "balance this equation for me: Fe + O2 -> Fe2O3", "should_trigger": false} ] } diff --git a/.agents/skills/formchem-harness/SKILL.md b/.agents/skills/formchem-harness/SKILL.md index e8eb6343..c366af8b 100644 --- a/.agents/skills/formchem-harness/SKILL.md +++ b/.agents/skills/formchem-harness/SKILL.md @@ -1,25 +1,25 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw or insert a structure from SMILES, clean up a drawing, undo, select all, zoom, run a FormChem menu command or extension, read or change the open fchem drawing through an extension, check a structure for valence errors, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff) are available. Covers connecting on 127.0.0.1:8220 when the tools do not show up, the approval question, the commands catalogue, the extension drawing contract and handoff. There are no direct drawing tools before 0.8.0, so it also covers saying so plainly. Not for changing FormChem's source code (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, clean up, undo, zoom, run a menu command or extension, read or change the open fchem drawing through an extension, check valence, perceive a reaction scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry or yield, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) are available. Covers connecting on 127.0.0.1:8220, approval, the command catalogue, extension drawings, handoff, and what waits for the 0.8.0 drawing tools. Not for changing FormChem's source (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.4.0" + version: "0.5.0" --- # FormChem harness FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it. -## What exists today (0.4.0) +## What exists today (0.5.0) -FormChem 0.4.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws with tools and hover keys. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. +FormChem 0.5.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 adds reactions and annotations: arrows, plus signs, brackets, shapes, tables, TLC plates, orbitals, pictures and captions, reaction perception, atom mapping, balance, the Stoichiometry panel, a template library of 206, Find and rulers. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. -The MCP server still has six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. +The MCP server has ten tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, and the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. -**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected), undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, clean up, lay out, check structure and zoom (`window-commands`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). +**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out, check structure and zoom (`window-commands`). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, and read its stoichiometry and balance (`reactions`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). -**What it cannot do yet.** There are no direct drawing tools: no drawing atoms and bonds by call, no reading SMILES or InChIKey back through MCP (the formula in `get_context` is all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. +**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading SMILES or InChIKey of a structure back through MCP (the formula in `get_context` and the reaction tools' answers are all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) @@ -39,6 +39,7 @@ formchem-harness/ sub-skills/ session-and-connection/ connecting, get_context, the approval question, errors window-commands/ drawing work through run_command; references/command-catalogue.md + reactions/ the four reaction tools and the Reaction menu commands extension-drawings/ reading and changing the drawing through a Form extension handoff/ handoff states, notes, clearing, what the person sees visual-qa/ checking what the person sees without a render tool @@ -52,12 +53,13 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | --- | --- | | No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` | | "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` | -| Draw or insert a structure from SMILES, open a drawing or structure file, undo, save, select all, clean up, zoom | `window-commands` | +| Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` | +| The reaction in the drawing: its steps, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | | Read atoms, bonds, SMILES, InChIKey or valence errors from the open drawing, change it by id, check a structure | `extension-drawings` (and `window-commands` when no extension fits) | | Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` | | Tell the person you are done, ask them something, clear your note | `handoff` | | Check what the person sees, did the command work, which commands are on | `visual-qa` | -| Draw atom by atom, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists | +| Draw atom by atom, place an arrow or shape, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists | | Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` | ## When something fails @@ -74,11 +76,13 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | "takes no parameters" | The command does not accept arguments in this build | Run it without `params`; if it prompts, ask the person to fill the prompt | | "Could not read the SMILES" | `insert-smiles {smiles}` got a string the engine cannot parse; nothing was inserted | Check the SMILES, fix it once, or ask the person | | "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path | +| "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it | +| An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns | ## Done means - `get_context` was called first and its answer shaped the plan. -- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, and requests beyond the commands were answered with "the drawing tools arrive in 0.8.0". +- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, reaction numbers were quoted from the reaction tools, and requests beyond them were answered with "the drawing tools arrive in 0.8.0". - Every command run returned without `isError`, or its error was reported to the person. - The work ends with a `handoff` (`ready` with a note, or `question` with the question). diff --git a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md index 3707b779..a462491b 100644 --- a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md @@ -31,9 +31,9 @@ A handoff with a state changes what the person sees, so the first one from an ou - A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?" - No emoji, no markdown, no links the person cannot click. -## In 0.4.0 +## In 0.5.0 -A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). +A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). ## Procedure diff --git a/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md new file mode 100644 index 00000000..608eb305 --- /dev/null +++ b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md @@ -0,0 +1,59 @@ +--- +name: reactions +description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, and saying plainly what only the person can do (typing amounts, Set Reaction Roles before 0.6.0). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." +--- + +# Reactions + +## Purpose + +Answer reaction questions from what FormChem computes, not from the agent's own chemistry, and make reaction changes as undo steps the person sees. Hands back reaction and step ids, the engine's answers quoted as numbers, and a handoff naming what changed. + +## Preconditions + +`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. An agent cannot draw arrows or place structures by position before 0.8.0; `insert-smiles` and `insert-template` put things in the middle of the view, so a scheme is the person's to arrange. + +## Tools and commands + +| Goal | Call | Changes the drawing | +| --- | --- | --- | +| Find the steps and their roles | `perceive_reactions {doc?, page?}`: lists every reaction and step id, reactants, products, agents and conditions; steps set by hand say "(set by hand)" and are kept | yes, one undo step; "No change" when nothing moved | +| Map atoms | `map_reaction {doc?, reaction?, step?, mode?}`: `discard` (default) maps from scratch, `keep` keeps drawn numbers, `alter` may change them, `clear` removes them; the answer gives map numbers and bonds broken and formed | yes, one undo step | +| The reaction as text | `export_reaction {doc?, reaction?, step?, format?}`: `smiles`, `rxn` (V2000) or `rxnv3000`, with map numbers | no | +| Amounts and yields | `reaction_stoichiometry {doc?, reaction?, step?}`: rows with mmol, equiv, mass, volume, the limiting reagent, the theoretical and percent yield, and the balance check | no | +| Balance coefficients | `run_command {id: "balance-reaction"}` on the selected or first step; `check-reaction` opens the balance dialog for the person | yes, one undo step | +| Insert a template | `run_command {id: "insert-template", params: {id: "[template id]"}}`; the ids come from the engine's `GET /api/templates` | yes, one undo step | +| Paste a reaction | `paste-reaction` reads the person's clipboard; an agent cannot fill the clipboard, so it is the person's | yes | +| The grid on the page | `stoichiometry-grid` inserts or refreshes the grid for the selected or first step; `show-stoichiometry` opens the panel for the person | yes for the grid | + +`doc` may be left out when one drawing is open; `reaction` and `step` default to the first. The two changing tools ask the person the first time like any change. + +## Procedure + +1. **Context.** `get_context`; name the drawing by title. +2. **Steps first.** `perceive_reactions` before any step-level tool. Keep the reaction and step ids it returns; never guess ids. "No reaction arrow has structures before or after it" means the scheme is not drawn as FormChem reads it (structures within 2.5 bond lengths of the arrow's line, reagents within 1.5 of the arrow): say so and ask the person to move them. +3. **One step at a time.** Pass the ids to `map_reaction`, `export_reaction` or `reaction_stoichiometry`. A step not found names `perceive_reactions` as the next call: run it once, then retry once. +4. **Quote, do not compute.** Report formulas, masses, mmol and yields exactly as the tool printed them, with units. "Not balanced." with a suggestion is the engine's answer; offer `balance-reaction` only when the check suggests coefficients, and say "add the missing co-products first" when it suggests a co-product, which only the person can draw. +5. **Amounts are the person's.** No tool types amounts into the grid. When the answer lacks amounts, ask in a question handoff for the masses, volumes, equivalents or scale to type into the Stoichiometry panel, then read again. +6. **Hand off** what changed ("Mapped step 1 of Esterification: 7 atoms, one C-O bond formed; Undo removes it"). + +## Rules + +- Roles come from geometry: there is no command to set them by hand before 0.6.0 (Set Reaction Roles is off with that reason). A step read from an RXN file or set by hand keeps its roles. +- Reagents drawn above the arrow are not counted in the balance; a step whose atoms come from such a reagent reads as unbalanced. Say that instead of "the reaction is wrong". +- Mapping the second of two chained steps replaces the map numbers of the structure they share. Warn before mapping a second step when the first is already mapped. +- Coefficients are dropped from reaction SMILES and RXN (`coefficient_dropped`); text conditions are dropped from reaction SMILES (`conditions_dropped`). Pass the warnings on. + +## Gate + +- [ ] Every step-level call used ids returned by `perceive_reactions` in this session. +- [ ] Every number reported came from a tool answer, with its unit. +- [ ] Each changing call was reported with its undo step; no change was retried after a refusal. + +## Hands back + +Reaction and step ids, the quoted answers, and a ready or question handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root holds the generated arguments of all ten tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. diff --git a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index 50bde3ab..9bf19f2d 100644 --- a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -42,5 +42,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the six tools and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. +- [ ] The plan uses only the ten tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. - [ ] No change was attempted after a refusal. diff --git a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md index 34473333..7715e05c 100644 --- a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md @@ -7,7 +7,7 @@ description: "Checks what the person sees in FormChem when the agent cannot see ## Purpose -Never claim a visible result you did not confirm. In 0.4.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report, and ask the person for the rest. +Never claim a visible result you did not confirm. In 0.5.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found), and ask the person for the rest. ## What you can confirm today diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index cf216927..6c6a2355 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: window-commands -description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." +description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." --- # Window commands @@ -25,7 +25,10 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | --- | --- | | Open this file (absolute path to a `.fchem`, `.mol`, `.sdf`, `.smi`, `.cml`, `.cdxml`) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing | | Draw or insert a structure from SMILES | `run_command {id: "insert-smiles", params: {smiles: "[SMILES]"}}`: one undo step into the active drawing (a new one when none is open), centred in the visible page and selected; the answer names the new fragment ids and the drawing. Then `get_context` for the formula. If `list_commands {id: "insert-smiles"}` lists no `smiles` param (an older build), run it bare and post `handoff {state: "question", note: "Paste [SMILES] into the SMILES prompt and press Insert"}`; never claim the structure was drawn until the person confirms | -| Draw from a name, a molfile text or by atoms | No command does this before 0.8.0. Offer SMILES through `insert-smiles {smiles}`, or a file through `open-recent` | +| Insert a ring, amino acid, sugar, protecting group, reagent or glassware | `run_command {id: "insert-template", params: {id: "[template id]"}}`: one undo step, centred in view at the drawing's bond length, selected; without `id` it opens the library for the person. Ids such as `benzene`, `l-alanine` come from the engine's `GET /api/templates` | +| Draw from a name, a molfile text or by atoms; place an arrow, a shape or a caption | No command does this before 0.8.0 (the insert-arrow, insert-shape and insert-table commands only pick the person's tool). Offer SMILES through `insert-smiles {smiles}`, a template, or a file through `open-recent` | +| Stack or group objects | `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group`, `ungroup` on the selection; off with "Select something on the canvas first" when nothing is selected | +| Anything about the reaction in the drawing | Load `reactions` | | Undo the last change | `run_command {id: "undo"}`: one transaction, whoever made it | | Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure | | Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected | diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index 2fba324e..cb2d4371 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,12 +1,14 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.4.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.5.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents - Reading the catalogue - Drawings: open, save, close - Changing the drawing +- Templates, objects and arrangement +- Reactions - The canvas and the view - Registered but off until a later version - What no command does yet @@ -45,7 +47,35 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4. | `check-structure` | | opens a dialog for the person listing valence errors and chemistry warnings with links that select the atoms; the agent gets only "ran in the window" | | `insert-text` | | switches the person's canvas to the text tool | -`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` selects what it added). Each changing command is one undo step. `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group` and `ungroup` are registered but off in this build. +`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` and `insert-template` select what they added). Each changing command is one undo step. + +## Templates, objects and arrangement + +| Command | Params | What it does | +| --- | --- | --- | +| `insert-template` | `id` (optional) | with `id`: inserts that template (fresh ids, the drawing's bond length) centred in the view of the active drawing, or a new one, selected, as one undo step; the engine's `GET /api/templates` lists the 206 ids (`benzene`, `l-alanine` and so on). Without `id` it opens the library for the person | +| `bring-front`, `bring-forward`, `send-backward`, `send-back` | | change the stacking order of the selection within its page or group (Shift+Mod+], Mod+], Mod+[, Shift+Mod+[) | +| `group`, `ungroup` | | group the selection (Mod+G) or ungroup a selected group (Shift+Mod+G) | +| `insert-arrow`, `insert-shape`, `insert-table` | | pick the arrow, rectangle or table tool for the person; nothing is drawn until they drag | +| `insert-image` | | asks the person for a picture file; an agent cannot answer the chooser | +| `insert-text` | | switches the person's canvas to the text tool | + +## Reactions + +| Command | What it does | +| --- | --- | +| `add-reaction-arrow` | picks the reaction arrow tool for the person | +| `perceive-reactions` | reads the reaction arrows on the page and stores each step's roles (one undo step); the `perceive_reactions` tool does the same and returns the ids | +| `map-atoms`, `clear-mapping` | map or clear the selected or first step; `map_reaction` returns the result | +| `check-reaction` | opens the balance dialog for the person | +| `balance-reaction` | writes the suggested coefficients (one undo step); refused when the check suggests a missing co-product | +| `show-stoichiometry`, `stoichiometry-grid` | open the Stoichiometry panel for the person; insert or refresh the grid table on the page | +| `copy-reaction-smiles`, `copy-reaction-rxn` | put the step on the person's clipboard; `export_reaction` gives the agent the text | +| `export-reaction-smiles`, `export-reaction-rxn` | save the step to a file the person chooses | +| `paste-reaction` | lays out reaction SMILES or RXN from the person's clipboard as a drawn scheme | +| `set-reaction-roles` | off: "Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing" | + +The step is the one whose arrow or structures are selected, else the first on the page. ## The canvas and the view @@ -56,13 +86,14 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4. | `zoom-100` | actual size (Mod+1) | | `show-grid` | toggles the paper grid; the result says whether it is now on | | `show-analysis` | opens the Analysis panel | +| `find`, `show-rulers` | Edit > Find (next, previous, replace) and View > Show Rulers with guides, for the person | | `toggle-analysis`, `analysis-panel` | shows or hides the Analysis panel (formula, masses, m/z, elemental analysis from the engine, for the selection or the whole page) | | `tool-select`, `tool-bond`, `tool-chain`, `tool-ring`, `tool-atom`, `tool-text`, `tool-eraser`, `tool-hand`, `tool-zoom`, `tool:[id]` | pick a drawing tool for the person; they do not draw by themselves | ## Registered but off until a later version -`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); reactions, arrows, shapes, tables and images (0.5.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. `find`, `show-rulers`, `insert-template` and the stacking and grouping commands arrive in 0.5.0, and `add-hydrogens` and `remove-hydrogens` in 0.6.0. +`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `set-reaction-roles`, `add-hydrogens` and `remove-hydrogens` (0.6.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. ## What no command does yet -Drawing atoms and bonds at given positions, selecting particular atoms, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. +Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. diff --git a/.claude/skills/formchem-harness/EVALS.json b/.claude/skills/formchem-harness/EVALS.json index b9836b2d..fb9b9f39 100644 --- a/.claude/skills/formchem-harness/EVALS.json +++ b/.claude/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.4.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.4.0 has drawings but no direct agent drawing tools (0.8.0); agents work through run_command and Form extensions, and several evals check that the agent stays inside that.", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.5.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.5.0 has drawings and four reaction tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water).", "evals": [ { "id": 1, @@ -138,10 +138,37 @@ "Calls extensions_list and uses an extension command only if one states that it reads the drawing or checks structures", "Reports valence errors only from that extension's answer; with no suitable extension, says the agent cannot read the rows and points the person at the Check Structure dialog instead of computing valence itself" ] + }, + { + "id": 13, + "name": "map-and-export-the-drawn-reaction", + "prompt": "Map the atoms of the esterification I drew in FormChem and give me the reaction SMILES.", + "files": [], + "expected_behavior": [ + "Calls get_context, then perceive_reactions, and keeps the reaction and step ids it returns", + "Calls map_reaction with those ids (mode left at discard) and reports the mapped count and the bonds broken and formed from its answer", + "Calls export_reaction with format smiles and quotes the text exactly, passing on any conditions_dropped warning", + "Ends with a ready handoff naming the drawing and that Undo removes the mapping" + ] + }, + { + "id": 14, + "name": "yield-without-amounts", + "prompt": "What is the theoretical yield of my FormChem reaction?", + "files": [], + "expected_behavior": [ + "Calls perceive_reactions, then reaction_stoichiometry for the step", + "Quotes the theoretical yield with its unit only when the answer gives one, never computing it from its own molecular weights", + "When no amounts are typed, posts a question handoff asking the person to type a mass, volume, equivalents or scale in the Stoichiometry panel, and says no tool can type them" + ] } ], "trigger_evals": [ {"query": "what can FormChem do at the moment", "should_trigger": true}, + {"query": "map the atoms of the reaction in my formchem drawing", "should_trigger": true}, + {"query": "export the drawn reaction in FormChem as an RXN file", "should_trigger": true}, + {"query": "what is the limiting reagent in my formchem scheme?", "should_trigger": true}, + {"query": "insert a cyclohexane chair template in FormChem", "should_trigger": true}, {"query": "open preferences in formchem", "should_trigger": true}, {"query": "is the formchem engine running? I get connection refused", "should_trigger": true}, {"query": "run the hello command of my formchem extension", "should_trigger": true}, @@ -167,6 +194,8 @@ {"query": "run the show-grid command in formvis", "should_trigger": false}, {"query": "install the molecule tools extension from FormPortal", "should_trigger": false}, {"query": "convert this SDF file to SMILES with RDKit in a Python script", "should_trigger": false}, - {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false} + {"query": "check the valence of this molfile with RDKit, no app needed", "should_trigger": false}, + {"query": "fix the perception distances in formchem's services/chem/reactions.py", "should_trigger": false}, + {"query": "balance this equation for me: Fe + O2 -> Fe2O3", "should_trigger": false} ] } diff --git a/.claude/skills/formchem-harness/SKILL.md b/.claude/skills/formchem-harness/SKILL.md index e8eb6343..c366af8b 100644 --- a/.claude/skills/formchem-harness/SKILL.md +++ b/.claude/skills/formchem-harness/SKILL.md @@ -1,25 +1,25 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw or insert a structure from SMILES, clean up a drawing, undo, select all, zoom, run a FormChem menu command or extension, read or change the open fchem drawing through an extension, check a structure for valence errors, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff) are available. Covers connecting on 127.0.0.1:8220 when the tools do not show up, the approval question, the commands catalogue, the extension drawing contract and handoff. There are no direct drawing tools before 0.8.0, so it also covers saying so plainly. Not for changing FormChem's source code (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, clean up, undo, zoom, run a menu command or extension, read or change the open fchem drawing through an extension, check valence, perceive a reaction scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry or yield, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) are available. Covers connecting on 127.0.0.1:8220, approval, the command catalogue, extension drawings, handoff, and what waits for the 0.8.0 drawing tools. Not for changing FormChem's source (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.4.0" + version: "0.5.0" --- # FormChem harness FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it. -## What exists today (0.4.0) +## What exists today (0.5.0) -FormChem 0.4.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws with tools and hover keys. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. +FormChem 0.5.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 adds reactions and annotations: arrows, plus signs, brackets, shapes, tables, TLC plates, orbitals, pictures and captions, reaction perception, atom mapping, balance, the Stoichiometry panel, a template library of 206, Find and rulers. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. -The MCP server still has six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. +The MCP server has ten tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, and the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. -**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected), undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, clean up, lay out, check structure and zoom (`window-commands`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). +**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out, check structure and zoom (`window-commands`). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, and read its stoichiometry and balance (`reactions`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). -**What it cannot do yet.** There are no direct drawing tools: no drawing atoms and bonds by call, no reading SMILES or InChIKey back through MCP (the formula in `get_context` is all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. +**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading SMILES or InChIKey of a structure back through MCP (the formula in `get_context` and the reaction tools' answers are all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) @@ -39,6 +39,7 @@ formchem-harness/ sub-skills/ session-and-connection/ connecting, get_context, the approval question, errors window-commands/ drawing work through run_command; references/command-catalogue.md + reactions/ the four reaction tools and the Reaction menu commands extension-drawings/ reading and changing the drawing through a Form extension handoff/ handoff states, notes, clearing, what the person sees visual-qa/ checking what the person sees without a render tool @@ -52,12 +53,13 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | --- | --- | | No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` | | "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` | -| Draw or insert a structure from SMILES, open a drawing or structure file, undo, save, select all, clean up, zoom | `window-commands` | +| Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` | +| The reaction in the drawing: its steps, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | | Read atoms, bonds, SMILES, InChIKey or valence errors from the open drawing, change it by id, check a structure | `extension-drawings` (and `window-commands` when no extension fits) | | Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` | | Tell the person you are done, ask them something, clear your note | `handoff` | | Check what the person sees, did the command work, which commands are on | `visual-qa` | -| Draw atom by atom, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists | +| Draw atom by atom, place an arrow or shape, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists | | Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` | ## When something fails @@ -74,11 +76,13 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | "takes no parameters" | The command does not accept arguments in this build | Run it without `params`; if it prompts, ask the person to fill the prompt | | "Could not read the SMILES" | `insert-smiles {smiles}` got a string the engine cannot parse; nothing was inserted | Check the SMILES, fix it once, or ask the person | | "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path | +| "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it | +| An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns | ## Done means - `get_context` was called first and its answer shaped the plan. -- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, and requests beyond the commands were answered with "the drawing tools arrive in 0.8.0". +- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, reaction numbers were quoted from the reaction tools, and requests beyond them were answered with "the drawing tools arrive in 0.8.0". - Every command run returned without `isError`, or its error was reported to the person. - The work ends with a `handoff` (`ready` with a note, or `question` with the question). diff --git a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md index 3707b779..a462491b 100644 --- a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md @@ -31,9 +31,9 @@ A handoff with a state changes what the person sees, so the first one from an ou - A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?" - No emoji, no markdown, no links the person cannot click. -## In 0.4.0 +## In 0.5.0 -A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). +A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). ## Procedure diff --git a/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md new file mode 100644 index 00000000..608eb305 --- /dev/null +++ b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md @@ -0,0 +1,59 @@ +--- +name: reactions +description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, and saying plainly what only the person can do (typing amounts, Set Reaction Roles before 0.6.0). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." +--- + +# Reactions + +## Purpose + +Answer reaction questions from what FormChem computes, not from the agent's own chemistry, and make reaction changes as undo steps the person sees. Hands back reaction and step ids, the engine's answers quoted as numbers, and a handoff naming what changed. + +## Preconditions + +`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. An agent cannot draw arrows or place structures by position before 0.8.0; `insert-smiles` and `insert-template` put things in the middle of the view, so a scheme is the person's to arrange. + +## Tools and commands + +| Goal | Call | Changes the drawing | +| --- | --- | --- | +| Find the steps and their roles | `perceive_reactions {doc?, page?}`: lists every reaction and step id, reactants, products, agents and conditions; steps set by hand say "(set by hand)" and are kept | yes, one undo step; "No change" when nothing moved | +| Map atoms | `map_reaction {doc?, reaction?, step?, mode?}`: `discard` (default) maps from scratch, `keep` keeps drawn numbers, `alter` may change them, `clear` removes them; the answer gives map numbers and bonds broken and formed | yes, one undo step | +| The reaction as text | `export_reaction {doc?, reaction?, step?, format?}`: `smiles`, `rxn` (V2000) or `rxnv3000`, with map numbers | no | +| Amounts and yields | `reaction_stoichiometry {doc?, reaction?, step?}`: rows with mmol, equiv, mass, volume, the limiting reagent, the theoretical and percent yield, and the balance check | no | +| Balance coefficients | `run_command {id: "balance-reaction"}` on the selected or first step; `check-reaction` opens the balance dialog for the person | yes, one undo step | +| Insert a template | `run_command {id: "insert-template", params: {id: "[template id]"}}`; the ids come from the engine's `GET /api/templates` | yes, one undo step | +| Paste a reaction | `paste-reaction` reads the person's clipboard; an agent cannot fill the clipboard, so it is the person's | yes | +| The grid on the page | `stoichiometry-grid` inserts or refreshes the grid for the selected or first step; `show-stoichiometry` opens the panel for the person | yes for the grid | + +`doc` may be left out when one drawing is open; `reaction` and `step` default to the first. The two changing tools ask the person the first time like any change. + +## Procedure + +1. **Context.** `get_context`; name the drawing by title. +2. **Steps first.** `perceive_reactions` before any step-level tool. Keep the reaction and step ids it returns; never guess ids. "No reaction arrow has structures before or after it" means the scheme is not drawn as FormChem reads it (structures within 2.5 bond lengths of the arrow's line, reagents within 1.5 of the arrow): say so and ask the person to move them. +3. **One step at a time.** Pass the ids to `map_reaction`, `export_reaction` or `reaction_stoichiometry`. A step not found names `perceive_reactions` as the next call: run it once, then retry once. +4. **Quote, do not compute.** Report formulas, masses, mmol and yields exactly as the tool printed them, with units. "Not balanced." with a suggestion is the engine's answer; offer `balance-reaction` only when the check suggests coefficients, and say "add the missing co-products first" when it suggests a co-product, which only the person can draw. +5. **Amounts are the person's.** No tool types amounts into the grid. When the answer lacks amounts, ask in a question handoff for the masses, volumes, equivalents or scale to type into the Stoichiometry panel, then read again. +6. **Hand off** what changed ("Mapped step 1 of Esterification: 7 atoms, one C-O bond formed; Undo removes it"). + +## Rules + +- Roles come from geometry: there is no command to set them by hand before 0.6.0 (Set Reaction Roles is off with that reason). A step read from an RXN file or set by hand keeps its roles. +- Reagents drawn above the arrow are not counted in the balance; a step whose atoms come from such a reagent reads as unbalanced. Say that instead of "the reaction is wrong". +- Mapping the second of two chained steps replaces the map numbers of the structure they share. Warn before mapping a second step when the first is already mapped. +- Coefficients are dropped from reaction SMILES and RXN (`coefficient_dropped`); text conditions are dropped from reaction SMILES (`conditions_dropped`). Pass the warnings on. + +## Gate + +- [ ] Every step-level call used ids returned by `perceive_reactions` in this session. +- [ ] Every number reported came from a tool answer, with its unit. +- [ ] Each changing call was reported with its undo step; no change was retried after a refusal. + +## Hands back + +Reaction and step ids, the quoted answers, and a ready or question handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root holds the generated arguments of all ten tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. diff --git a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index 50bde3ab..9bf19f2d 100644 --- a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -42,5 +42,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the six tools and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. +- [ ] The plan uses only the ten tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. - [ ] No change was attempted after a refusal. diff --git a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md index 34473333..7715e05c 100644 --- a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md @@ -7,7 +7,7 @@ description: "Checks what the person sees in FormChem when the agent cannot see ## Purpose -Never claim a visible result you did not confirm. In 0.4.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report, and ask the person for the rest. +Never claim a visible result you did not confirm. In 0.5.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found), and ask the person for the rest. ## What you can confirm today diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index cf216927..6c6a2355 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: window-commands -description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." +description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." --- # Window commands @@ -25,7 +25,10 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | --- | --- | | Open this file (absolute path to a `.fchem`, `.mol`, `.sdf`, `.smi`, `.cml`, `.cdxml`) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing | | Draw or insert a structure from SMILES | `run_command {id: "insert-smiles", params: {smiles: "[SMILES]"}}`: one undo step into the active drawing (a new one when none is open), centred in the visible page and selected; the answer names the new fragment ids and the drawing. Then `get_context` for the formula. If `list_commands {id: "insert-smiles"}` lists no `smiles` param (an older build), run it bare and post `handoff {state: "question", note: "Paste [SMILES] into the SMILES prompt and press Insert"}`; never claim the structure was drawn until the person confirms | -| Draw from a name, a molfile text or by atoms | No command does this before 0.8.0. Offer SMILES through `insert-smiles {smiles}`, or a file through `open-recent` | +| Insert a ring, amino acid, sugar, protecting group, reagent or glassware | `run_command {id: "insert-template", params: {id: "[template id]"}}`: one undo step, centred in view at the drawing's bond length, selected; without `id` it opens the library for the person. Ids such as `benzene`, `l-alanine` come from the engine's `GET /api/templates` | +| Draw from a name, a molfile text or by atoms; place an arrow, a shape or a caption | No command does this before 0.8.0 (the insert-arrow, insert-shape and insert-table commands only pick the person's tool). Offer SMILES through `insert-smiles {smiles}`, a template, or a file through `open-recent` | +| Stack or group objects | `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group`, `ungroup` on the selection; off with "Select something on the canvas first" when nothing is selected | +| Anything about the reaction in the drawing | Load `reactions` | | Undo the last change | `run_command {id: "undo"}`: one transaction, whoever made it | | Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure | | Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected | diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index 2fba324e..cb2d4371 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,12 +1,14 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.4.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.5.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents - Reading the catalogue - Drawings: open, save, close - Changing the drawing +- Templates, objects and arrangement +- Reactions - The canvas and the view - Registered but off until a later version - What no command does yet @@ -45,7 +47,35 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4. | `check-structure` | | opens a dialog for the person listing valence errors and chemistry warnings with links that select the atoms; the agent gets only "ran in the window" | | `insert-text` | | switches the person's canvas to the text tool | -`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` selects what it added). Each changing command is one undo step. `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group` and `ungroup` are registered but off in this build. +`delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` and `insert-template` select what they added). Each changing command is one undo step. + +## Templates, objects and arrangement + +| Command | Params | What it does | +| --- | --- | --- | +| `insert-template` | `id` (optional) | with `id`: inserts that template (fresh ids, the drawing's bond length) centred in the view of the active drawing, or a new one, selected, as one undo step; the engine's `GET /api/templates` lists the 206 ids (`benzene`, `l-alanine` and so on). Without `id` it opens the library for the person | +| `bring-front`, `bring-forward`, `send-backward`, `send-back` | | change the stacking order of the selection within its page or group (Shift+Mod+], Mod+], Mod+[, Shift+Mod+[) | +| `group`, `ungroup` | | group the selection (Mod+G) or ungroup a selected group (Shift+Mod+G) | +| `insert-arrow`, `insert-shape`, `insert-table` | | pick the arrow, rectangle or table tool for the person; nothing is drawn until they drag | +| `insert-image` | | asks the person for a picture file; an agent cannot answer the chooser | +| `insert-text` | | switches the person's canvas to the text tool | + +## Reactions + +| Command | What it does | +| --- | --- | +| `add-reaction-arrow` | picks the reaction arrow tool for the person | +| `perceive-reactions` | reads the reaction arrows on the page and stores each step's roles (one undo step); the `perceive_reactions` tool does the same and returns the ids | +| `map-atoms`, `clear-mapping` | map or clear the selected or first step; `map_reaction` returns the result | +| `check-reaction` | opens the balance dialog for the person | +| `balance-reaction` | writes the suggested coefficients (one undo step); refused when the check suggests a missing co-product | +| `show-stoichiometry`, `stoichiometry-grid` | open the Stoichiometry panel for the person; insert or refresh the grid table on the page | +| `copy-reaction-smiles`, `copy-reaction-rxn` | put the step on the person's clipboard; `export_reaction` gives the agent the text | +| `export-reaction-smiles`, `export-reaction-rxn` | save the step to a file the person chooses | +| `paste-reaction` | lays out reaction SMILES or RXN from the person's clipboard as a drawn scheme | +| `set-reaction-roles` | off: "Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing" | + +The step is the one whose arrow or structures are selected, else the first on the page. ## The canvas and the view @@ -56,13 +86,14 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4. | `zoom-100` | actual size (Mod+1) | | `show-grid` | toggles the paper grid; the result says whether it is now on | | `show-analysis` | opens the Analysis panel | +| `find`, `show-rulers` | Edit > Find (next, previous, replace) and View > Show Rulers with guides, for the person | | `toggle-analysis`, `analysis-panel` | shows or hides the Analysis panel (formula, masses, m/z, elemental analysis from the engine, for the selection or the whole page) | | `tool-select`, `tool-bond`, `tool-chain`, `tool-ring`, `tool-atom`, `tool-text`, `tool-eraser`, `tool-hand`, `tool-zoom`, `tool:[id]` | pick a drawing tool for the person; they do not draw by themselves | ## Registered but off until a later version -`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); reactions, arrows, shapes, tables and images (0.5.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. `find`, `show-rulers`, `insert-template` and the stacking and grouping commands arrive in 0.5.0, and `add-hydrogens` and `remove-hydrogens` in 0.6.0. +`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `set-reaction-roles`, `add-hydrogens` and `remove-hydrogens` (0.6.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. ## What no command does yet -Drawing atoms and bonds at given positions, selecting particular atoms, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. +Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. diff --git a/agents/manifest.json b/agents/manifest.json index 1b2fd65b..0566cb45 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -40,6 +40,7 @@ "sub_skills": [ "extension-drawings", "handoff", + "reactions", "session-and-connection", "visual-qa", "window-commands" From d667284675f62d08d4d2fbe478451e71a2f2e69e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:59:38 -0500 Subject: [PATCH 116/279] chore(skills): add reactions and annotations specialists to formchem-skillset (0.5.0) Phase 5 code had no specialist: reactions maps the engine services, routes, window stoichiometry and Reaction menu with the one-reading rule, and annotations maps the object registry, tools, handles, captions, z-order, templates and media; the router, evals and neighbouring sub-skills point at them, validated with zero FAIL and mirrored by agents sync. --- .agents/skills/formchem-skillset/EVALS.json | 31 ++++++++- .agents/skills/formchem-skillset/SKILL.md | 17 +++-- .../sub-skills/agents/SUB-SKILL.md | 10 +-- .../sub-skills/annotations/SUB-SKILL.md | 63 +++++++++++++++++++ .../sub-skills/canvas/SUB-SKILL.md | 3 +- .../sub-skills/chemistry-engine/SUB-SKILL.md | 1 + .../sub-skills/reactions/SUB-SKILL.md | 61 ++++++++++++++++++ .claude/skills/formchem-skillset/EVALS.json | 31 ++++++++- .claude/skills/formchem-skillset/SKILL.md | 17 +++-- .../sub-skills/agents/SUB-SKILL.md | 10 +-- .../sub-skills/annotations/SUB-SKILL.md | 63 +++++++++++++++++++ .../sub-skills/canvas/SUB-SKILL.md | 3 +- .../sub-skills/chemistry-engine/SUB-SKILL.md | 1 + .../sub-skills/reactions/SUB-SKILL.md | 61 ++++++++++++++++++ agents/manifest.json | 2 + 15 files changed, 346 insertions(+), 28 deletions(-) create mode 100644 .agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md create mode 100644 .agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md create mode 100644 .claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md create mode 100644 .claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md diff --git a/.agents/skills/formchem-skillset/EVALS.json b/.agents/skills/formchem-skillset/EVALS.json index 8ed80a71..2f23d933 100644 --- a/.agents/skills/formchem-skillset/EVALS.json +++ b/.agents/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.4.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.5.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -111,10 +111,36 @@ "Makes the gesture preview through client.preview while dragging and commit once with commitDraft on pointer up", "Confirms one undo step per drag and none after Escape" ] + }, + { + "id": 11, + "name": "stoichiometry-panel-and-grid-disagree", + "prompt": "The FormChem stoichiometry panel says 8.19 mmol but the grid drawn on the page says 9.0 mmol for the same step. Fix it.", + "files": [], + "expected_behavior": [ + "Loads reactions and reads frontend/src/chem/stoich.ts, canvas/render/table.ts and the stoich paragraphs of docs/FORMAT.md", + "Keeps one window computation (chem/stoich.ts) with the scale-wins precedence of the engine's stoich.py instead of adding another", + "Checks AC11.1 (8.19 mmol, 9.83 mmol, 0.713 mL) in the panel, the drawn grid and GET .../stoich", + "Logs the reason in frontend/HASHOUT_LOG.md and adds no test files" + ] + }, + { + "id": 12, + "name": "anchored-arrow-left-behind", + "prompt": "In FormChem, when I move a structure, the electron-pushing arrow anchored to its oxygen stays where it was.", + "files": [], + "expected_behavior": [ + "Loads annotations and reads canvas/render/anchors.ts, arrow.ts and objects.ts", + "Checks that the arrow kind's deps list the anchored fragments so the renderer re-lays it out when they change", + "Verifies with a MutationObserver that one move changes only the atom's nodes and the anchored arrow, without rebuilding the layer" + ] } ], "trigger_evals": [ {"query": "add an MCP tool to formchem", "should_trigger": true}, + {"query": "formchem's perceive reactions picks the wrong reactants for a vertical arrow", "should_trigger": true}, + {"query": "add a new glassware template to the formchem template library", "should_trigger": true}, + {"query": "the curved arrow in formchem's renderer draws its head on the wrong side", "should_trigger": true}, {"query": "the formchem title bar flickers when I switch themes, fix it", "should_trigger": true}, {"query": "wire the extensions router into formchem's backend/app/main.py", "should_trigger": true}, {"query": "bump formchem to 0.2.1", "should_trigger": true}, @@ -140,6 +166,7 @@ {"query": "release formVFX 0.62.0", "should_trigger": false}, {"query": "update the extension catalogue page in FormPortal", "should_trigger": false}, {"query": "scaffold a Tauri 2 shell for my new todo app", "should_trigger": false}, - {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false} + {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false}, + {"query": "map the atoms of the reaction in my open FormChem drawing", "should_trigger": false} ] } diff --git a/.agents/skills/formchem-skillset/SKILL.md b/.agents/skills/formchem-skillset/SKILL.md index 06cdb174..406293cc 100644 --- a/.agents/skills/formchem-skillset/SKILL.md +++ b/.agents/skills/formchem-skillset/SKILL.md @@ -1,17 +1,17 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem file package, molfile and SMILES import, the y axis), the engine document store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings per fragment), the SVG canvas renderer patching on every edit, drawing tools (bond, chain, ring: one undo step per drag), hover hotkeys, hit testing at any zoom, selection, the window shell, title bar, themes, menus, the agent dock, Form extensions, adding an MCP tool, the Tauri shell, or a release and version bump. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis (their own skillsets), and not for standalone RDKit scripts outside the repo." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem package, imports), the engine store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings), reactions (perception, Indigo atom mapping, balance, stoichiometry, RXN), the SVG canvas renderer patching on every edit, drawing tools (one undo step per drag), hover hotkeys, hit testing, arrows, brackets, shapes, tables, TLC, captions, groups, templates, media, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.4.0" + version: "0.5.0" --- # FormChem skillset Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine as a sidecar. -**Where FormChem is (0.4.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 adds the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. Reactions and annotations (0.5.0), stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.5.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 adds reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. Stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. ## Subsystem map @@ -23,6 +23,8 @@ Route every change to FormChem's code through this file. It maps the subsystems | Chemistry engine on RDKit: conversion, sanitising, valence, aromaticity, identifiers, formula, masses, layout, file reading and writing, the derived cache | `backend/app/services/chem/`, `backend/app/routers/chem.py` | `chemistry-engine` | | Window documents and chemistry: the document client and session, the actions behind File and Insert, the Analysis panel, local valence, rings, labels and formula | `frontend/src/engine/client.ts`, `engine/session.ts`, `engine/client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (chemistry rules in `chemistry-engine`) | | Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | +| Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | +| Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | @@ -39,7 +41,8 @@ frontend commands/registry.ts -> nothing (DOM free; the cli and workers may impo engine/model.ts, engine/ops.ts -> nothing (pure, DOM free; the contract) chem/ -> engine/model.ts only (pure, no t(), no DOM) engine/client.ts, session.ts -> model, ops, client-api, io/api, io/live -canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings) +canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings); + render/table.ts also chem/stoich.ts, the one window stoichiometry source canvas/tools -> canvas/types.ts, engine/model, engine/ops, canvas/geom.ts canvas/view.ts, ui/tool-rail -> canvas/types.ts, hit.ts, selection.ts, ui/dom, ui/icons, i18n io/ -> registry only for the catalogue mirror @@ -80,6 +83,8 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | A new field or object kind, an op or path problem, a validation error, coalescing, the `.fchem` package shape | `document-format` | | SMILES, InChI, formula, masses, implicit hydrogens, valence errors, warnings, 2D clean-up or layout, a structure file reader or writer, the derived cache | `chemistry-engine` | | Drawing on the canvas: how a bond, label or wedge renders, a drawing tool, a hover hotkey, snapping, hit testing, selection, zoom and pan, the tool rail, canvas right-click menus | `canvas` | +| An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `annotations`, with `canvas` for the laws it builds on | +| Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | | A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | @@ -98,8 +103,8 @@ formchem-skillset/ SKILL.md this router, the subsystem map and the laws in short references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) - sub-skills/ engine, document-format, chemistry-engine, canvas, window-shell, menus, dock, - extensions, agents, desktop, release, clean-room + sub-skills/ engine, document-format, chemistry-engine, reactions, canvas, annotations, window-shell, + menus, dock, extensions, agents, desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from canvas/references/hover-keys.md the hover key map with the code that implements it ``` diff --git a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index 401642d7..da1bcc14 100644 --- a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -30,11 +30,11 @@ Give agents a small, honest tool surface that only describes what FormChem can d 4. Describe only what works now. A tool for a later phase lands in that phase. 5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. -## What agents can reach in 0.4.0 +## What agents can reach in 0.5.0 -- Six tools only. The drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present. -- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, and the canvas commands as the 0.4.0 integration enables them) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). -- `mcp.py` describes 0.4.0: `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. +- Ten tools: the six of the shell plus `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`); the `reactions` specialist owns them. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present. +- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). +- `mcp.py` describes the shell as of 0.4.0 (a sentence naming the reaction tools in `INSTRUCTIONS` and `get_context` is still to add): `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. - `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing. - A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window. @@ -43,7 +43,7 @@ Give agents a small, honest tool surface that only describes what FormChem can d - Agents in FormChem's own tabs send a live tab token in `x-formchem-inapp` and are never asked; everyone else goes through `consent.ask`. A refusal returns a sentence, never an exception. - Window-only abilities are window tools over `/api/live` through `bridge.window_call`; the engine never fakes a window answer. - The `handoff` live message is `{t: "handoff", agent, state, note, at}`; a window asks for the current list with `{t: "handoffs"}`. -- The manifest is generated, never edited by hand. +- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand; the generator writes the tools reference's `## Contents` list, which the skill validator requires past 100 lines. ## Gate diff --git a/.agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md new file mode 100644 index 00000000..c4cd61bd --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md @@ -0,0 +1,63 @@ +--- +name: annotations +description: "FormChem's drawn objects beyond structures: the object kind registry in frontend/src/canvas/render (objects.ts, paint.ts, anchors.ts, arrow.ts, bracket.ts, shape.ts, line.ts, table.ts, tlc.ts, orbital.ts, image.ts, caption.ts, group.ts, bounds.ts), drawn-outline hit testing (canvas/hit-objects.ts), the annotation tools and handles in canvas/tools, captions and their x, y cache, z-order and groups (app/object-commands.ts), the template library (backend services/templates.py, data/templates, ui/template-dialog.ts, template-thumb.ts, home-templates.ts) and media upload and serving. Use when an arrow, bracket, shape, table, TLC plate, orbital, picture or caption draws, hits or moves wrong, an anchored arrow does not follow its atom, a z-order change flashes, a template is added, or a new object kind is built." +--- + +# Annotations + +## Purpose + +Draw every non-chemistry object from the document alone, patch it like a bond, and edit it with one transaction per gesture. Hands back a kind, tool or template change that keeps the zero-flash rule and the format contract. + +## Preconditions + +`canvas` holds the renderer, view and tool laws this builds on; `document-format` holds the object fields (FORMAT.md, Text, captions and the other kinds). Read both first. + +## File map + +| Path | Role | +| --- | --- | +| `canvas/render/objects.ts` | `OBJECT_KINDS` (kind to `{ view, deps?, derived? }`), `ObjectCtx`, `ObjectView {specs, box}`, `docChem`, `docCtx`, `objectView`, `objectDeps` | +| `canvas/render/paint.ts`, `svg.ts` | shared stroke, fill, gradient, rotation and label helpers; `NodeSpec.kids` for nested gradients and clip paths | +| `canvas/render/anchors.ts`, `arrow.ts` | anchor points (atom, lone pair, bond, between), anchored ends trimmed 0.15 bond lengths; one curve model for all 15 arrow types and 6 head kinds | +| `canvas/render/` kind modules | `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`MediaCache`, `setMediaUrl`), `caption.ts`, `group.ts` | +| `canvas/render/bounds.ts`, `canvas/hit-objects.ts` | `objectBox(obj, doc)` without a renderer; `hitObject` and `objectDistance` by drawn outline | +| `canvas/render/renderer.ts` | the `objects` layer between `page` and `bonds`; `inOrder` moves only nodes out of place on a z-order change | +| `canvas/tools/objects.ts` | `BoxTool` and the shared helpers (`snapEnd`, `boxFrom`, `fragmentAt`, `outermostGroup`, `ensureMediaMap`) | +| `canvas/tools/` | `arrow.ts`, `curved.ts`, `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`uploadMedia`, `setMediaUploader`, `placeImage`), `caption.ts`, `handles.ts` (`objectHandles`, `dragHandle`), `transform.ts` (captions mapped last) | +| `frontend/src/app/object-commands.ts` | `objectCommandDefs`: z-order per container, group, ungroup, `alignObjects`, `distributeObjects` | +| `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/*.json` | the library: `catalogue`, `listing`, `fragment(id, bond_length)` with fresh ids; format in `docs/TEMPLATES.md` | +| `frontend/src/ui/template-dialog.ts`, `template-thumb.ts`, `home-templates.ts`, `styles/templates.css` | Insert > Template, the SVG thumbnails, the Home section | +| `backend/app/routers/documents.py` media routes, `services/store.py` `add_media`, `services/package.py` `sniff_image` | picture bytes held by the session until the window's transaction lists them | + +## Laws + +- **A kind is a registry entry, not a branch in the renderer.** A new kind adds a module with a pure `view(obj, ctx)` returning keyed specs and a box, plus `deps` for what else it reads (an anchored arrow lists its fragments, a caption its target). The renderer re-lays out on a change of the object, the style, the font epoch or the deps, and patches. +- **Bounds and hits come from the drawing.** Tools, Arrange and hit testing use `objectBox` and `hitObject`, never a second geometry estimate; the old one read an arrow's bend in degrees as a length. +- **One gesture, one transaction, one id.** A tool previews with a stable object id per gesture and commits once; an image commits only after the upload answered; Escape commits nothing. +- **Captions follow their target.** With `target` and `offset` the caption is placed from the target's drawn box; `x`, `y` are a cache that `transform.ts` refreshes in the same transaction when the target moves, and moving the caption rewrites `offset`. +- **Z-order is per container.** Page order and a group's `children` move separately with `move` ops computed on a working copy; a group's members are in no page order and are removed with the group. +- **Templates and glassware are original data.** Nothing from another product's library (`clean-room`); fresh ids on every insert, fragments scaled to the drawing's bond length, shapes kept at size. +- **Media is two steps.** POST stores bytes and returns the record; the window's one transaction lists `media[id]` and adds the image; the package writes only listed ids. + +## Procedure + +1. For a drawing fault, build a scratch drawing outside the repo with one of each kind and open it in the built window served by the engine; watch it under 4x CPU throttling with a MutationObserver over `.fc-app`. +2. Change the kind module, then bounds or hits if the shape changed, then the tool. +3. A new field is a FORMAT.md, `model.ts` and `model.py` change together (`document-format`); a new tool needs a rail group, an inline currentColor icon in `ui/icons.ts` and its strings through `t()`. +4. Log the reason in `frontend/HASHOUT_LOG.md` (entries 108 to 124 and 127 hold the current ones). + +## Gate + +- [ ] `cd frontend && npx tsc --noEmit` is clean. +- [ ] Drawing, moving and deleting the object each add exactly one undo step; moving an anchored atom changes only that atom's label and the arrows anchored to it. +- [ ] A z-order command and a new object create or move only their own nodes (MutationObserver), and nothing flashes. +- [ ] A template inserted from the dialog and from Home is one undo step; a picture survives save, close and reopen. + +## Hands back + +The changed kind, tool or template files, the contract text if a field changed, and the gate results. + +## Owned resources + +None of its own: the object fields are in `docs/FORMAT.md` and the template format in `docs/TEMPLATES.md`. diff --git a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md index a1a7ede7..17fe7f64 100644 --- a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md @@ -20,7 +20,8 @@ Let the person draw at the speed of thought while the document stays the only tr | `canvas/view.ts` | `CanvasView`: mounts the renderer, owns viewport, zoom and pan, pointer and key routing, hover, selection, the band, the keyboard atom cursor, `setClient`, at most one `renderer.update` per animation frame | | `canvas/hit.ts`, `selection.ts` | Hit testing and region selection on model geometry; selection sets and helpers | | `canvas/text-editor.ts`, `canvas/context.ts` | The in-place label and text editor; right-click menus for atom, bond, selection and background (`deleteSelectionOps`) | -| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest) | +| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups | +| Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text | | `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper | | `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key | diff --git a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index e0ab61c4..df7f56d9 100644 --- a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -27,6 +27,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `frontend/src/chem/` | Window-side rules: `elements.ts` (default valences, colours), `valence.ts` (implicit H, label text and side), `rings.ts` (smallest rings, double bond side), `label-text.ts`, `formula.ts` (`quickFormula`), `graph.ts` | | `frontend/src/canvas/render/valence.ts`, `render/rings.ts` | The renderer's own fast implicit-H table and ring perception, used while drawing | | `references/warning-codes.md` | Every warning code, the module that raises it and when. Open before adding or interpreting a warning | +| Reaction modules (0.5.0) | `chem/geometry.py`, `reactions.py`, `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py`, `scheme.py`, `derive.reaction_checks` and `routers/reactions.py` belong to the `reactions` specialist; they reuse `convert.to_mol` and the rules here | ## Rules diff --git a/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md new file mode 100644 index 00000000..f75ad6fe --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md @@ -0,0 +1,61 @@ +--- +name: reactions +description: "FormChem's reaction code: perception of roles around reaction arrows (services/chem/geometry.py, reactions.py), Indigo atom mapping (mapping.py), balance and co-product suggestions (balance.py), stoichiometry in the engine (stoich.py) and the window (frontend/src/chem/stoich.ts, stoich-ops.ts, ui/stoich-panel.ts), reaction SMILES and RXN export and scheme import (rxnio.py, scheme.py, importers.py), the routes in routers/reactions.py, the derived reactions slot, the four MCP reaction tools, and the Reaction menu (app/reaction-commands.ts, engine/reactions-api.ts). Use when a step gets the wrong roles, a mapping or balance is wrong, the stoichiometry panel and the drawn grid disagree, an RXN round trip loses something, or a reaction route or command is added." +--- + +# Reactions + +## Purpose + +Keep one reading of a drawn reaction across the engine, the window and agents. The engine computes roles, mapping, balance and exchange formats from the drawing and writes them as ordinary transactions; the window computes stoichiometry for instant display by the same rules. Hands back changed modules with their contract text in `docs/FORMAT.md` and `docs/REACTIONS.md` in step. + +## Preconditions + +Read `docs/FORMAT.md` (Reactions on a page, the table `stoich` rule, the derived cache) and `docs/REACTIONS.md` (rules, routes, shapes). Load `document-format` before building ops by hand and `clean-room` before any new reaction feature. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/services/chem/geometry.py` | `object_box` for every kind (text by a 0.55 em per character estimate), `Frame(tail, head)` with `along`, `across`, `project` | +| `chem/reactions.py` | `REACTION_ARROWS`, the constants `BAND_BONDS` 1.5, `ROW_BONDS` 2.5, `END_BONDS` 0.5, `JOIN_BONDS` 1.0; `infer_step`, `perceive_page`, `perceive_ops`, `preview`, `find_step`, `ReactionError` (422) and `NotFound` (404) | +| `chem/mapping.py` | `map_ops(doc, step, mode, centres)` (`discard`, `keep`, `alter`), `clear_ops`; the order search and scoring | +| `chem/balance.py` | `check`, `solve` (exact fractions), co-product candidates, `resonance`, `coefficient_ops` | +| `chem/stoich.py` | `compute(doc, reaction, step, derived)`, `grid`, `table_ops`, unit formatting at three significant figures | +| `chem/rxnio.py`, `chem/scheme.py` | export to `smiles`, `rxn`, `rxnv3000`; import and layout of reaction SMILES, RXN, CML and CDXML as a scheme (`insert_ops`) | +| `chem/derive.py` `reaction_checks` | the derived `reactions` slot: step id to balance check, at most 64 steps | +| `backend/app/routers/reactions.py` | every reaction route; `_commit` returns `{changed, tx, rev}` | +| `backend/app/routers/mcp.py` | `t_perceive_reactions`, `t_map_reaction`, `t_export_reaction`, `t_reaction_stoichiometry`, `_apply` | +| `frontend/src/chem/stoich.ts`, `chem/stoich-ops.ts` | the window's only stoichiometry computation (`computeStoich`, `stepFor`, `averageMass`) and the ops for one typed cell | +| `frontend/src/ui/stoich-panel.ts`, `styles/stoich.css` | the panel in row 2 of `.fc-workspace` | +| `frontend/src/canvas/render/table.ts` | draws a `stoich` table live from `computeStoich` | +| `frontend/src/engine/reactions-api.ts`, `app/reaction-commands.ts` | the typed route client and the Reaction menu commands | + +## Laws + +- **One reading of stoichiometry.** The engine's `stoich.py` and the window's `chem/stoich.ts` follow the same precedence: `scale_mmol` is the reference when present, else the limiting reagent's typed amount over its equiv, else the first amount; typed amounts beat typed equivalents. Never add a third computation; the renderer's own copy was deleted for disagreeing. Only typed values are stored, and the window's write rules (mass, volume or equiv replaces the other two; scale and the limiting reagent's amount replace each other) keep the two readings equal. +- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true`; re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md. +- **Routes are transactions.** A changing route builds ops on a copy and applies them with `STORE.apply`, returning `{changed, tx, rev}` and broadcasting the tx with the caller's `client`; no change means `changed: false` and no undo step. Agents go through `_apply` with origin `agent`. +- **Map numbers are atom data.** `Atom.map` and `Bond.reacting` are the only places mapping lives, so chained steps share the numbers of a shared structure. +- **Exchange keeps what the format can carry.** Kekulise RXN, keep reaction SMILES aromatic, put conditions on RXN line 4, report what is dropped as a warning code. + +## Procedure + +1. Reproduce with a scratch engine (`FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]`) and the route from `docs/REACTIONS.md`; the esterification (acetic acid + ethanol, H2SO4 above the arrow, ethyl acetate + water) and the two-step benzoic acid to N-ethylbenzamide scheme are the reference drawings. +2. Change the service, then the route or tool, then the window client, in that order; a new answer field goes into `docs/REACTIONS.md`, a stored field into FORMAT.md, `model.ts` and `model.py` together. +3. Log the reason in `backend/HASHOUT_LOG.md` or `frontend/HASHOUT_LOG.md` (entries 63 to 76 and 125 to 131 hold the current ones). + +## Gate + +- [ ] Esterification: perceive gives reactants acetic acid and ethanol, agent H2SO4, conditions text; a second perceive answers `changed: false`; map gives `complete`, one bond broken and one formed; check is balanced. +- [ ] AC11.1: 1.00 g benzoic acid, 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol, 9.83 mmol, 0.713 mL in the route, the panel and the drawn grid. AC11.2: 1000 mg of 1151 mg theoretical is 86.9 %. +- [ ] An RXN exported and imported again keeps roles, map numbers and the conditions text. +- [ ] `backend/venv/bin/python -m compileall -q backend/app` and `cd frontend && npx tsc --noEmit` are clean; after any MCP change `./formchem agents sync --check` passes. + +## Hands back + +The changed modules, the contract text updated in the same change, and the gate results. + +## Owned resources + +None of its own: the rules and routes are in `docs/REACTIONS.md` at the repository root, which this file points to instead of copying. diff --git a/.claude/skills/formchem-skillset/EVALS.json b/.claude/skills/formchem-skillset/EVALS.json index 8ed80a71..2f23d933 100644 --- a/.claude/skills/formchem-skillset/EVALS.json +++ b/.claude/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.4.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.5.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -111,10 +111,36 @@ "Makes the gesture preview through client.preview while dragging and commit once with commitDraft on pointer up", "Confirms one undo step per drag and none after Escape" ] + }, + { + "id": 11, + "name": "stoichiometry-panel-and-grid-disagree", + "prompt": "The FormChem stoichiometry panel says 8.19 mmol but the grid drawn on the page says 9.0 mmol for the same step. Fix it.", + "files": [], + "expected_behavior": [ + "Loads reactions and reads frontend/src/chem/stoich.ts, canvas/render/table.ts and the stoich paragraphs of docs/FORMAT.md", + "Keeps one window computation (chem/stoich.ts) with the scale-wins precedence of the engine's stoich.py instead of adding another", + "Checks AC11.1 (8.19 mmol, 9.83 mmol, 0.713 mL) in the panel, the drawn grid and GET .../stoich", + "Logs the reason in frontend/HASHOUT_LOG.md and adds no test files" + ] + }, + { + "id": 12, + "name": "anchored-arrow-left-behind", + "prompt": "In FormChem, when I move a structure, the electron-pushing arrow anchored to its oxygen stays where it was.", + "files": [], + "expected_behavior": [ + "Loads annotations and reads canvas/render/anchors.ts, arrow.ts and objects.ts", + "Checks that the arrow kind's deps list the anchored fragments so the renderer re-lays it out when they change", + "Verifies with a MutationObserver that one move changes only the atom's nodes and the anchored arrow, without rebuilding the layer" + ] } ], "trigger_evals": [ {"query": "add an MCP tool to formchem", "should_trigger": true}, + {"query": "formchem's perceive reactions picks the wrong reactants for a vertical arrow", "should_trigger": true}, + {"query": "add a new glassware template to the formchem template library", "should_trigger": true}, + {"query": "the curved arrow in formchem's renderer draws its head on the wrong side", "should_trigger": true}, {"query": "the formchem title bar flickers when I switch themes, fix it", "should_trigger": true}, {"query": "wire the extensions router into formchem's backend/app/main.py", "should_trigger": true}, {"query": "bump formchem to 0.2.1", "should_trigger": true}, @@ -140,6 +166,7 @@ {"query": "release formVFX 0.62.0", "should_trigger": false}, {"query": "update the extension catalogue page in FormPortal", "should_trigger": false}, {"query": "scaffold a Tauri 2 shell for my new todo app", "should_trigger": false}, - {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false} + {"query": "write an RDKit script that computes logP for a CSV of SMILES", "should_trigger": false}, + {"query": "map the atoms of the reaction in my open FormChem drawing", "should_trigger": false} ] } diff --git a/.claude/skills/formchem-skillset/SKILL.md b/.claude/skills/formchem-skillset/SKILL.md index 06cdb174..406293cc 100644 --- a/.claude/skills/formchem-skillset/SKILL.md +++ b/.claude/skills/formchem-skillset/SKILL.md @@ -1,17 +1,17 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem file package, molfile and SMILES import, the y axis), the engine document store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings per fragment), the SVG canvas renderer patching on every edit, drawing tools (bond, chain, ring: one undo step per drag), hover hotkeys, hit testing at any zoom, selection, the window shell, title bar, themes, menus, the agent dock, Form extensions, adding an MCP tool, the Tauri shell, or a release and version bump. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis (their own skillsets), and not for standalone RDKit scripts outside the repo." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem package, imports), the engine store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings), reactions (perception, Indigo atom mapping, balance, stoichiometry, RXN), the SVG canvas renderer patching on every edit, drawing tools (one undo step per drag), hover hotkeys, hit testing, arrows, brackets, shapes, tables, TLC, captions, groups, templates, media, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.4.0" + version: "0.5.0" --- # FormChem skillset Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine as a sidecar. -**Where FormChem is (0.4.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 adds the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. Reactions and annotations (0.5.0), stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.5.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 adds reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. Stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. ## Subsystem map @@ -23,6 +23,8 @@ Route every change to FormChem's code through this file. It maps the subsystems | Chemistry engine on RDKit: conversion, sanitising, valence, aromaticity, identifiers, formula, masses, layout, file reading and writing, the derived cache | `backend/app/services/chem/`, `backend/app/routers/chem.py` | `chemistry-engine` | | Window documents and chemistry: the document client and session, the actions behind File and Insert, the Analysis panel, local valence, rings, labels and formula | `frontend/src/engine/client.ts`, `engine/session.ts`, `engine/client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (chemistry rules in `chemistry-engine`) | | Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | +| Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | +| Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | @@ -39,7 +41,8 @@ frontend commands/registry.ts -> nothing (DOM free; the cli and workers may impo engine/model.ts, engine/ops.ts -> nothing (pure, DOM free; the contract) chem/ -> engine/model.ts only (pure, no t(), no DOM) engine/client.ts, session.ts -> model, ops, client-api, io/api, io/live -canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings) +canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings); + render/table.ts also chem/stoich.ts, the one window stoichiometry source canvas/tools -> canvas/types.ts, engine/model, engine/ops, canvas/geom.ts canvas/view.ts, ui/tool-rail -> canvas/types.ts, hit.ts, selection.ts, ui/dom, ui/icons, i18n io/ -> registry only for the catalogue mirror @@ -80,6 +83,8 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | A new field or object kind, an op or path problem, a validation error, coalescing, the `.fchem` package shape | `document-format` | | SMILES, InChI, formula, masses, implicit hydrogens, valence errors, warnings, 2D clean-up or layout, a structure file reader or writer, the derived cache | `chemistry-engine` | | Drawing on the canvas: how a bond, label or wedge renders, a drawing tool, a hover hotkey, snapping, hit testing, selection, zoom and pan, the tool rail, canvas right-click menus | `canvas` | +| An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `annotations`, with `canvas` for the laws it builds on | +| Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | | A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | @@ -98,8 +103,8 @@ formchem-skillset/ SKILL.md this router, the subsystem map and the laws in short references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) - sub-skills/ engine, document-format, chemistry-engine, canvas, window-shell, menus, dock, - extensions, agents, desktop, release, clean-room + sub-skills/ engine, document-format, chemistry-engine, reactions, canvas, annotations, window-shell, + menus, dock, extensions, agents, desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from canvas/references/hover-keys.md the hover key map with the code that implements it ``` diff --git a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index 401642d7..da1bcc14 100644 --- a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -30,11 +30,11 @@ Give agents a small, honest tool surface that only describes what FormChem can d 4. Describe only what works now. A tool for a later phase lands in that phase. 5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. -## What agents can reach in 0.4.0 +## What agents can reach in 0.5.0 -- Six tools only. The drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present. -- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, and the canvas commands as the 0.4.0 integration enables them) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). -- `mcp.py` describes 0.4.0: `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. +- Ten tools: the six of the shell plus `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`); the `reactions` specialist owns them. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present. +- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). +- `mcp.py` describes the shell as of 0.4.0 (a sentence naming the reaction tools in `INSTRUCTIONS` and `get_context` is still to add): `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. - `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing. - A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window. @@ -43,7 +43,7 @@ Give agents a small, honest tool surface that only describes what FormChem can d - Agents in FormChem's own tabs send a live tab token in `x-formchem-inapp` and are never asked; everyone else goes through `consent.ask`. A refusal returns a sentence, never an exception. - Window-only abilities are window tools over `/api/live` through `bridge.window_call`; the engine never fakes a window answer. - The `handoff` live message is `{t: "handoff", agent, state, note, at}`; a window asks for the current list with `{t: "handoffs"}`. -- The manifest is generated, never edited by hand. +- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand; the generator writes the tools reference's `## Contents` list, which the skill validator requires past 100 lines. ## Gate diff --git a/.claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md new file mode 100644 index 00000000..c4cd61bd --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/annotations/SUB-SKILL.md @@ -0,0 +1,63 @@ +--- +name: annotations +description: "FormChem's drawn objects beyond structures: the object kind registry in frontend/src/canvas/render (objects.ts, paint.ts, anchors.ts, arrow.ts, bracket.ts, shape.ts, line.ts, table.ts, tlc.ts, orbital.ts, image.ts, caption.ts, group.ts, bounds.ts), drawn-outline hit testing (canvas/hit-objects.ts), the annotation tools and handles in canvas/tools, captions and their x, y cache, z-order and groups (app/object-commands.ts), the template library (backend services/templates.py, data/templates, ui/template-dialog.ts, template-thumb.ts, home-templates.ts) and media upload and serving. Use when an arrow, bracket, shape, table, TLC plate, orbital, picture or caption draws, hits or moves wrong, an anchored arrow does not follow its atom, a z-order change flashes, a template is added, or a new object kind is built." +--- + +# Annotations + +## Purpose + +Draw every non-chemistry object from the document alone, patch it like a bond, and edit it with one transaction per gesture. Hands back a kind, tool or template change that keeps the zero-flash rule and the format contract. + +## Preconditions + +`canvas` holds the renderer, view and tool laws this builds on; `document-format` holds the object fields (FORMAT.md, Text, captions and the other kinds). Read both first. + +## File map + +| Path | Role | +| --- | --- | +| `canvas/render/objects.ts` | `OBJECT_KINDS` (kind to `{ view, deps?, derived? }`), `ObjectCtx`, `ObjectView {specs, box}`, `docChem`, `docCtx`, `objectView`, `objectDeps` | +| `canvas/render/paint.ts`, `svg.ts` | shared stroke, fill, gradient, rotation and label helpers; `NodeSpec.kids` for nested gradients and clip paths | +| `canvas/render/anchors.ts`, `arrow.ts` | anchor points (atom, lone pair, bond, between), anchored ends trimmed 0.15 bond lengths; one curve model for all 15 arrow types and 6 head kinds | +| `canvas/render/` kind modules | `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`MediaCache`, `setMediaUrl`), `caption.ts`, `group.ts` | +| `canvas/render/bounds.ts`, `canvas/hit-objects.ts` | `objectBox(obj, doc)` without a renderer; `hitObject` and `objectDistance` by drawn outline | +| `canvas/render/renderer.ts` | the `objects` layer between `page` and `bonds`; `inOrder` moves only nodes out of place on a z-order change | +| `canvas/tools/objects.ts` | `BoxTool` and the shared helpers (`snapEnd`, `boxFrom`, `fragmentAt`, `outermostGroup`, `ensureMediaMap`) | +| `canvas/tools/` | `arrow.ts`, `curved.ts`, `plus.ts`, `bracket.ts`, `shape.ts`, `line.ts`, `table.ts`, `tlc.ts`, `orbital.ts`, `image.ts` (`uploadMedia`, `setMediaUploader`, `placeImage`), `caption.ts`, `handles.ts` (`objectHandles`, `dragHandle`), `transform.ts` (captions mapped last) | +| `frontend/src/app/object-commands.ts` | `objectCommandDefs`: z-order per container, group, ungroup, `alignObjects`, `distributeObjects` | +| `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/*.json` | the library: `catalogue`, `listing`, `fragment(id, bond_length)` with fresh ids; format in `docs/TEMPLATES.md` | +| `frontend/src/ui/template-dialog.ts`, `template-thumb.ts`, `home-templates.ts`, `styles/templates.css` | Insert > Template, the SVG thumbnails, the Home section | +| `backend/app/routers/documents.py` media routes, `services/store.py` `add_media`, `services/package.py` `sniff_image` | picture bytes held by the session until the window's transaction lists them | + +## Laws + +- **A kind is a registry entry, not a branch in the renderer.** A new kind adds a module with a pure `view(obj, ctx)` returning keyed specs and a box, plus `deps` for what else it reads (an anchored arrow lists its fragments, a caption its target). The renderer re-lays out on a change of the object, the style, the font epoch or the deps, and patches. +- **Bounds and hits come from the drawing.** Tools, Arrange and hit testing use `objectBox` and `hitObject`, never a second geometry estimate; the old one read an arrow's bend in degrees as a length. +- **One gesture, one transaction, one id.** A tool previews with a stable object id per gesture and commits once; an image commits only after the upload answered; Escape commits nothing. +- **Captions follow their target.** With `target` and `offset` the caption is placed from the target's drawn box; `x`, `y` are a cache that `transform.ts` refreshes in the same transaction when the target moves, and moving the caption rewrites `offset`. +- **Z-order is per container.** Page order and a group's `children` move separately with `move` ops computed on a working copy; a group's members are in no page order and are removed with the group. +- **Templates and glassware are original data.** Nothing from another product's library (`clean-room`); fresh ids on every insert, fragments scaled to the drawing's bond length, shapes kept at size. +- **Media is two steps.** POST stores bytes and returns the record; the window's one transaction lists `media[id]` and adds the image; the package writes only listed ids. + +## Procedure + +1. For a drawing fault, build a scratch drawing outside the repo with one of each kind and open it in the built window served by the engine; watch it under 4x CPU throttling with a MutationObserver over `.fc-app`. +2. Change the kind module, then bounds or hits if the shape changed, then the tool. +3. A new field is a FORMAT.md, `model.ts` and `model.py` change together (`document-format`); a new tool needs a rail group, an inline currentColor icon in `ui/icons.ts` and its strings through `t()`. +4. Log the reason in `frontend/HASHOUT_LOG.md` (entries 108 to 124 and 127 hold the current ones). + +## Gate + +- [ ] `cd frontend && npx tsc --noEmit` is clean. +- [ ] Drawing, moving and deleting the object each add exactly one undo step; moving an anchored atom changes only that atom's label and the arrows anchored to it. +- [ ] A z-order command and a new object create or move only their own nodes (MutationObserver), and nothing flashes. +- [ ] A template inserted from the dialog and from Home is one undo step; a picture survives save, close and reopen. + +## Hands back + +The changed kind, tool or template files, the contract text if a field changed, and the gate results. + +## Owned resources + +None of its own: the object fields are in `docs/FORMAT.md` and the template format in `docs/TEMPLATES.md`. diff --git a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md index a1a7ede7..17fe7f64 100644 --- a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md @@ -20,7 +20,8 @@ Let the person draw at the speed of thought while the document stays the only tr | `canvas/view.ts` | `CanvasView`: mounts the renderer, owns viewport, zoom and pan, pointer and key routing, hover, selection, the band, the keyboard atom cursor, `setClient`, at most one `renderer.update` per animation frame | | `canvas/hit.ts`, `selection.ts` | Hit testing and region selection on model geometry; selection sets and helpers | | `canvas/text-editor.ts`, `canvas/context.ts` | The in-place label and text editor; right-click menus for atom, bond, selection and background (`deleteSelectionOps`) | -| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest) | +| `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups | +| Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text | | `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper | | `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key | diff --git a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index e0ab61c4..df7f56d9 100644 --- a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -27,6 +27,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `frontend/src/chem/` | Window-side rules: `elements.ts` (default valences, colours), `valence.ts` (implicit H, label text and side), `rings.ts` (smallest rings, double bond side), `label-text.ts`, `formula.ts` (`quickFormula`), `graph.ts` | | `frontend/src/canvas/render/valence.ts`, `render/rings.ts` | The renderer's own fast implicit-H table and ring perception, used while drawing | | `references/warning-codes.md` | Every warning code, the module that raises it and when. Open before adding or interpreting a warning | +| Reaction modules (0.5.0) | `chem/geometry.py`, `reactions.py`, `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py`, `scheme.py`, `derive.reaction_checks` and `routers/reactions.py` belong to the `reactions` specialist; they reuse `convert.to_mol` and the rules here | ## Rules diff --git a/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md new file mode 100644 index 00000000..f75ad6fe --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md @@ -0,0 +1,61 @@ +--- +name: reactions +description: "FormChem's reaction code: perception of roles around reaction arrows (services/chem/geometry.py, reactions.py), Indigo atom mapping (mapping.py), balance and co-product suggestions (balance.py), stoichiometry in the engine (stoich.py) and the window (frontend/src/chem/stoich.ts, stoich-ops.ts, ui/stoich-panel.ts), reaction SMILES and RXN export and scheme import (rxnio.py, scheme.py, importers.py), the routes in routers/reactions.py, the derived reactions slot, the four MCP reaction tools, and the Reaction menu (app/reaction-commands.ts, engine/reactions-api.ts). Use when a step gets the wrong roles, a mapping or balance is wrong, the stoichiometry panel and the drawn grid disagree, an RXN round trip loses something, or a reaction route or command is added." +--- + +# Reactions + +## Purpose + +Keep one reading of a drawn reaction across the engine, the window and agents. The engine computes roles, mapping, balance and exchange formats from the drawing and writes them as ordinary transactions; the window computes stoichiometry for instant display by the same rules. Hands back changed modules with their contract text in `docs/FORMAT.md` and `docs/REACTIONS.md` in step. + +## Preconditions + +Read `docs/FORMAT.md` (Reactions on a page, the table `stoich` rule, the derived cache) and `docs/REACTIONS.md` (rules, routes, shapes). Load `document-format` before building ops by hand and `clean-room` before any new reaction feature. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/services/chem/geometry.py` | `object_box` for every kind (text by a 0.55 em per character estimate), `Frame(tail, head)` with `along`, `across`, `project` | +| `chem/reactions.py` | `REACTION_ARROWS`, the constants `BAND_BONDS` 1.5, `ROW_BONDS` 2.5, `END_BONDS` 0.5, `JOIN_BONDS` 1.0; `infer_step`, `perceive_page`, `perceive_ops`, `preview`, `find_step`, `ReactionError` (422) and `NotFound` (404) | +| `chem/mapping.py` | `map_ops(doc, step, mode, centres)` (`discard`, `keep`, `alter`), `clear_ops`; the order search and scoring | +| `chem/balance.py` | `check`, `solve` (exact fractions), co-product candidates, `resonance`, `coefficient_ops` | +| `chem/stoich.py` | `compute(doc, reaction, step, derived)`, `grid`, `table_ops`, unit formatting at three significant figures | +| `chem/rxnio.py`, `chem/scheme.py` | export to `smiles`, `rxn`, `rxnv3000`; import and layout of reaction SMILES, RXN, CML and CDXML as a scheme (`insert_ops`) | +| `chem/derive.py` `reaction_checks` | the derived `reactions` slot: step id to balance check, at most 64 steps | +| `backend/app/routers/reactions.py` | every reaction route; `_commit` returns `{changed, tx, rev}` | +| `backend/app/routers/mcp.py` | `t_perceive_reactions`, `t_map_reaction`, `t_export_reaction`, `t_reaction_stoichiometry`, `_apply` | +| `frontend/src/chem/stoich.ts`, `chem/stoich-ops.ts` | the window's only stoichiometry computation (`computeStoich`, `stepFor`, `averageMass`) and the ops for one typed cell | +| `frontend/src/ui/stoich-panel.ts`, `styles/stoich.css` | the panel in row 2 of `.fc-workspace` | +| `frontend/src/canvas/render/table.ts` | draws a `stoich` table live from `computeStoich` | +| `frontend/src/engine/reactions-api.ts`, `app/reaction-commands.ts` | the typed route client and the Reaction menu commands | + +## Laws + +- **One reading of stoichiometry.** The engine's `stoich.py` and the window's `chem/stoich.ts` follow the same precedence: `scale_mmol` is the reference when present, else the limiting reagent's typed amount over its equiv, else the first amount; typed amounts beat typed equivalents. Never add a third computation; the renderer's own copy was deleted for disagreeing. Only typed values are stored, and the window's write rules (mass, volume or equiv replaces the other two; scale and the limiting reagent's amount replace each other) keep the two readings equal. +- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true`; re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md. +- **Routes are transactions.** A changing route builds ops on a copy and applies them with `STORE.apply`, returning `{changed, tx, rev}` and broadcasting the tx with the caller's `client`; no change means `changed: false` and no undo step. Agents go through `_apply` with origin `agent`. +- **Map numbers are atom data.** `Atom.map` and `Bond.reacting` are the only places mapping lives, so chained steps share the numbers of a shared structure. +- **Exchange keeps what the format can carry.** Kekulise RXN, keep reaction SMILES aromatic, put conditions on RXN line 4, report what is dropped as a warning code. + +## Procedure + +1. Reproduce with a scratch engine (`FORMCHEM_PORT=[port] FORMCHEM_DATA_DIR=[scratch]`) and the route from `docs/REACTIONS.md`; the esterification (acetic acid + ethanol, H2SO4 above the arrow, ethyl acetate + water) and the two-step benzoic acid to N-ethylbenzamide scheme are the reference drawings. +2. Change the service, then the route or tool, then the window client, in that order; a new answer field goes into `docs/REACTIONS.md`, a stored field into FORMAT.md, `model.ts` and `model.py` together. +3. Log the reason in `backend/HASHOUT_LOG.md` or `frontend/HASHOUT_LOG.md` (entries 63 to 76 and 125 to 131 hold the current ones). + +## Gate + +- [ ] Esterification: perceive gives reactants acetic acid and ethanol, agent H2SO4, conditions text; a second perceive answers `changed: false`; map gives `complete`, one bond broken and one formed; check is balanced. +- [ ] AC11.1: 1.00 g benzoic acid, 1.2 equiv thionyl chloride at 1.64 g/mL gives 8.19 mmol, 9.83 mmol, 0.713 mL in the route, the panel and the drawn grid. AC11.2: 1000 mg of 1151 mg theoretical is 86.9 %. +- [ ] An RXN exported and imported again keeps roles, map numbers and the conditions text. +- [ ] `backend/venv/bin/python -m compileall -q backend/app` and `cd frontend && npx tsc --noEmit` are clean; after any MCP change `./formchem agents sync --check` passes. + +## Hands back + +The changed modules, the contract text updated in the same change, and the gate results. + +## Owned resources + +None of its own: the rules and routes are in `docs/REACTIONS.md` at the repository root, which this file points to instead of copying. diff --git a/agents/manifest.json b/agents/manifest.json index 0566cb45..f00ed61c 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -50,6 +50,7 @@ "name": "formchem-skillset", "sub_skills": [ "agents", + "annotations", "canvas", "chemistry-engine", "clean-room", @@ -59,6 +60,7 @@ "engine", "extensions", "menus", + "reactions", "release", "window-shell" ] From dabe708391ce0c0177bd0d85c0326372d55c7823 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:48:52 -0500 Subject: [PATCH 117/279] feat(canvas): give the view doc-space overlay layers, edge insets and a reveal (0.5.0) Find highlights and ruler guides draw in doc space under one transform the view patches per frame, and fitting or revealing a hit keeps clear of chrome that sits over the canvas edges. --- frontend/src/canvas/view.ts | 48 ++++++++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 3 deletions(-) diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 1a1b1740..581addd9 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -6,6 +6,7 @@ import { contextMenuOpen } from '../ui/context-menu'; import { el, isMac, q, setClass, setStyleVar } from '../ui/dom'; import { modalOpen } from '../ui/menu'; import { openCanvasMenu } from './context'; +import { fmt } from './render/geom'; import { hitExists, hitTest, NO_HIT, objectBounds, sameHit, styleFor, visibleOrder, type Box } from './hit'; import { EMPTY_SELECTION, isEmpty, prune, sameSelection, selectAllOnPage } from './selection'; import { TextEditor, type TextEditOptions } from './text-editor'; @@ -25,9 +26,12 @@ const CLICK_PX = 5; const HANDLE_STEM = 24; const OBJECT_HANDLE_PX = 7; const OBJECT_HANDLE_TOOLS = new Set(['select', 'lasso']); +const REVEAL_PAD = 24; export type { Band }; +export interface Insets { top: number; right: number; bottom: number; left: number } + export interface ViewToolContext extends ToolContext { readonly view: CanvasView; band(b: Band | null): void; @@ -155,6 +159,8 @@ export class CanvasView { private readonly cursorPath: SVGPathElement; private readonly handlePath: SVGPathElement; private readonly live: HTMLElement; + private readonly docLayers: SVGGElement[] = []; + private insets_: Insets = { top: 0, right: 0, bottom: 0, left: 0 }; private kcursor: Hit | null = null; private growArmed = false; private readonly defs = new Map(); @@ -401,9 +407,44 @@ export class CanvasView { zoom100(): void { this.zoomAt(PT_PX); } zoomFit(box: Box = this.pageBox()): void { - if (!this.size.w || !this.size.h || box.w <= 0 || box.h <= 0) return; - const z = clampZoom(Math.min((this.size.w - 2 * FIT_PAD) / box.w, (this.size.h - 2 * FIT_PAD) / box.h, 8 * PT_PX)); - this.setViewport({ x: (this.size.w - box.w * z) / 2 - box.x * z, y: (this.size.h - box.h * z) / 2 - box.y * z, zoom: z }); + const i = this.insets_; + const w = this.size.w - i.left - i.right, h = this.size.h - i.top - i.bottom; + if (w <= 0 || h <= 0 || box.w <= 0 || box.h <= 0) return; + const z = clampZoom(Math.min((w - 2 * FIT_PAD) / box.w, (h - 2 * FIT_PAD) / box.h, 8 * PT_PX)); + this.setViewport({ x: i.left + (w - box.w * z) / 2 - box.x * z, y: i.top + (h - box.h * z) / 2 - box.y * z, zoom: z }); + } + + screenSize(): { w: number; h: number } { return { ...this.size }; } + + insets(): Insets { return { ...this.insets_ }; } + + setInsets(next: Partial): void { this.insets_ = { ...this.insets_, ...next }; } + + reveal(box: Box, avoid: Partial = {}): void { + const i = this.insets_, v = this.vp; + const left = i.left + (avoid.left ?? 0) + REVEAL_PAD, top = i.top + (avoid.top ?? 0) + REVEAL_PAD; + const right = this.size.w - i.right - (avoid.right ?? 0) - REVEAL_PAD, bottom = this.size.h - i.bottom - (avoid.bottom ?? 0) - REVEAL_PAD; + if (right <= left || bottom <= top) return; + const x0 = box.x * v.zoom + v.x, y0 = box.y * v.zoom + v.y, x1 = x0 + box.w * v.zoom, y1 = y0 + box.h * v.zoom; + if (x0 >= left && x1 <= right && y0 >= top && y1 <= bottom) return; + const w = right - left, h = bottom - top; + const z = box.w * v.zoom > w || box.h * v.zoom > h ? clampZoom(Math.min(w / Math.max(box.w, 1e-3), h / Math.max(box.h, 1e-3))) : v.zoom; + this.setViewport({ x: left + w / 2 - (box.x + box.w / 2) * z, y: top + h / 2 - (box.y + box.h / 2) * z, zoom: z }); + } + + docLayer(cls: string): SVGGElement { + const g = document.createElementNS(SVG_NS, 'g'); + g.setAttribute('class', cls); + this.overlay.insertBefore(g, this.cursorPath); + this.docLayers.push(g); + this.placeDocLayer(g); + return g; + } + + private placeDocLayer(g: SVGGElement): void { + const v = this.vp; + const tf = `translate(${fmt(v.x)} ${fmt(v.y)}) scale(${v.zoom})`; + if (g.getAttribute('transform') !== tf) g.setAttribute('transform', tf); } zoomToContent(): void { @@ -587,6 +628,7 @@ export class CanvasView { if (this.viewDirty) { this.viewDirty = false; this.renderer.setViewport({ ...this.vp }); + for (const g of this.docLayers) this.placeDocLayer(g); this.placePaper(); this.placeBand(); this.placeKeyCursor(); From 8a52a884cf75b2ced1e91e9e3f68f773e52c03ec Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:50:23 -0500 Subject: [PATCH 118/279] feat(canvas): search a page's text, labels, elements and formulas (0.5.0) Find indexes text objects, captions, table cells, atom labels and abbreviations once per document change, matches formulas by element counts and SMILES by the engine's canonical form, and builds Replace edits that keep each run's formatting. --- frontend/src/canvas/find.ts | 293 ++++++++++++++++++++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 frontend/src/canvas/find.ts diff --git a/frontend/src/canvas/find.ts b/frontend/src/canvas/find.ts new file mode 100644 index 00000000..7f5e2ba5 --- /dev/null +++ b/frontend/src/canvas/find.ts @@ -0,0 +1,293 @@ +import { isElement } from '../chem/elements'; +import { fragmentCounts } from '../chem/formula'; +import { edgesOf, graphOf } from '../chem/graph'; +import { reverseLabel } from '../chem/label-text'; +import { atomLabel } from '../chem/valence'; +import { resolveStyle, type Derived, type FormChemDocument, type Fragment, type Id, type Run, type TableObject } from '../engine/model'; +import { objectPath, type Op, type Path } from '../engine/ops'; +import type { Box } from './hit'; +import { fragmentSelection, makeSelection, pageObjects } from './selection'; +import { selectionKey, type Selection } from './types'; + +export type FindKind = 'text' | 'caption' | 'cell' | 'label' | 'element' | 'formula' | 'smiles'; + +export interface FindHit { + key: string; + target: string; + kind: FindKind; + object: Id; + atoms?: Id[]; + cell?: { row: Id; index: number; col: number }; + at?: number; + length?: number; + box: Box | null; +} + +export interface FindGeometry { + objectBox(id: Id): Box | null; + atomBox(frag: Id, atom: Id): Box | null; +} + +export interface FindOptions { + matchCase?: boolean; + smiles?: readonly string[]; +} + +interface TextEntry { kind: 'text' | 'caption' | 'cell'; object: Id; cell?: { row: Id; index: number; col: number }; text: string } +interface AtomEntry { frag: Id; atom: Id; element: string; texts: string[] } +interface FragEntry { frag: Fragment; counts: Record; components: Id[][]; smiles: string[] } + +export interface FindIndex { doc: FormChemDocument; texts: TextEntry[]; atoms: AtomEntry[]; frags: FragEntry[] } + +const plain = (runs: readonly Run[] | undefined): string => (runs ?? []).map((r) => r.t).join(''); + +function components(frag: Fragment): Id[][] { + const g = graphOf(frag); + const seen = new Set(); + const out: Id[][] = []; + for (const start of g.atoms) { + if (seen.has(start)) continue; + const comp: Id[] = []; + const stack = [start]; + seen.add(start); + while (stack.length) { + const id = stack.pop()!; + comp.push(id); + for (const e of edgesOf(g, id)) if (!seen.has(e.other)) { seen.add(e.other); stack.push(e.other); } + } + out.push(comp.sort()); + } + return out; +} + +export function parseFormula(text: string): Record | null { + const s = text.replace(/\s+/g, '').replace(/(\d*[+-]+\d*)$/, ''); + if (!s || !/^([A-Z][a-z]?\d*)+$/.test(s)) return null; + const counts: Record = {}; + for (const m of s.matchAll(/([A-Z][a-z]?)(\d*)/g)) { + if (!isElement(m[1])) return null; + const n = m[2] ? Number.parseInt(m[2], 10) : 1; + if (!n) return null; + counts[m[1]] = (counts[m[1]] ?? 0) + n; + } + return counts; +} + +const sameCounts = (a: Record, b: Record): boolean => { + const ka = Object.keys(a).filter((k) => a[k] > 0), kb = Object.keys(b).filter((k) => b[k] > 0); + return ka.length === kb.length && ka.every((k) => a[k] === b[k]); +}; + +export function formulaQuery(text: string): Record | null { + const counts = parseFormula(text); + if (!counts) return null; + const els = Object.keys(counts); + return els.length > 1 || /\d/.test(text) ? counts : null; +} + +export function smilesCandidate(text: string): boolean { + const s = text.trim(); + return s.length >= 2 && s.length <= 400 && /^[A-Za-z0-9@+\-[\]()=#$\\/%.:*]+$/.test(s) && /[BCNOPSFIcnops]/.test(s); +} + +function subFragment(frag: Fragment, atoms: readonly Id[]): Fragment { + const keep = new Set(atoms); + const sub: Fragment = { id: frag.id, kind: 'fragment', atoms: {}, bonds: {} }; + for (const id of atoms) sub.atoms[id] = frag.atoms[id]; + for (const b of Object.values(frag.bonds)) if (keep.has(b.a) && keep.has(b.b)) sub.bonds[b.id] = b; + return sub; +} + +export function findIndex(doc: FormChemDocument, pageId: Id | null, derived: Derived | null): FindIndex { + const index: FindIndex = { doc, texts: [], atoms: [], frags: [] }; + const page = doc.pages.find((p) => p.id === pageId) ?? doc.pages[0]; + if (!page) return index; + for (const id of pageObjects(doc, page)) { + const o = doc.objects[id]; + if (!o || o.hidden) continue; + if (o.kind === 'text' || o.kind === 'caption') index.texts.push({ kind: o.kind, object: id, text: plain(o.runs) }); + else if (o.kind === 'table') { + o.rows.forEach((row, ri) => row.cells.forEach((cell, col) => { + const text = plain(cell.runs); + if (text) index.texts.push({ kind: 'cell', object: id, cell: { row: row.id, index: ri, col }, text }); + })); + } else if (o.kind === 'fragment') { + const style = resolveStyle(doc, o); + const d = derived?.fragments[id] ?? null; + for (const a of Object.values(o.atoms)) { + const texts: string[] = []; + const lab = atomLabel(o, a.id, { showHeteroH: style.show_hetero_h, terminalCarbon: style.terminal_carbon, bondLength: style.bond_length, derived: d }); + if (lab.show && lab.text) texts.push(lab.text, reverseLabel(lab.text)); + if (a.label) texts.push(a.label); + const exp = a.expansion ? doc.expansions?.[a.expansion]?.label : undefined; + if (exp) texts.push(exp); + if (a.generic) texts.push(a.generic); + index.atoms.push({ frag: id, atom: a.id, element: a.element, texts: [...new Set(texts)] }); + } + const fromEngine = d?.formula ? parseFormula(d.formula) : null; + const counts = fromEngine ?? fragmentCounts(o, { expansions: doc.expansions, derived }).counts; + const smiles = d?.smiles ? [d.smiles, ...d.smiles.split('.')] : []; + if (Object.keys(o.atoms).length) index.frags.push({ frag: o, counts, components: components(o), smiles }); + } + } + return index; +} + +function occurrences(hay: string, needle: string, matchCase: boolean): number[] { + const out: number[] = []; + if (!needle) return out; + let h = hay, n = needle; + if (!matchCase) { + const lh = hay.toLowerCase(), ln = needle.toLowerCase(); + if (lh.length === hay.length && ln.length === needle.length) { h = lh; n = ln; } + } + for (let i = h.indexOf(n); i >= 0; i = h.indexOf(n, i + n.length)) out.push(i); + return out; +} + +const contains = (hay: string, needle: string, matchCase: boolean): boolean => + matchCase ? hay.includes(needle) : hay.toLowerCase().includes(needle.toLowerCase()); + +function elementQuery(text: string): string | null { + const s = text.trim(); + if (!s || s.length > 3) return null; + const sym = s[0].toUpperCase() + s.slice(1).toLowerCase(); + return isElement(sym) ? sym : null; +} + +function cellBox(t: TableObject, ri: number, col: number): Box | null { + const row = t.rows[ri]; + if (!row || col >= t.cols.length) return null; + let x = t.x, y = t.y; + for (let i = 0; i < col; i++) x += t.cols[i]; + for (let i = 0; i < ri; i++) y += t.rows[i].h; + return { x, y, w: t.cols[col], h: row.h }; +} + +function atomsBox(doc: FormChemDocument, frag: Id, atoms: readonly Id[], geo: FindGeometry): Box | null { + const f = doc.objects[frag]; + if (f?.kind !== 'fragment') return null; + const r = 0.3 * resolveStyle(doc, f).bond_length; + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const id of atoms) { + const a = f.atoms[id]; + if (!a) continue; + const b = geo.atomBox(frag, id) ?? { x: a.x - r, y: a.y - r, w: 2 * r, h: 2 * r }; + x0 = Math.min(x0, b.x); y0 = Math.min(y0, b.y); + x1 = Math.max(x1, b.x + b.w); y1 = Math.max(y1, b.y + b.h); + } + return x0 === Infinity ? null : { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} + +const ROW_PT = 8; + +export function search(index: FindIndex, query: string, opts: FindOptions, geo: FindGeometry): FindHit[] { + const q = query.trim(); + if (!q) return []; + const doc = index.doc; + const matchCase = !!opts.matchCase; + const hits: FindHit[] = []; + const seen = new Set(); + const push = (h: FindHit): void => { + if (seen.has(h.key)) return; + seen.add(h.key); + hits.push(h); + }; + + for (const e of index.texts) { + const target = e.cell ? `c:${e.object}:${e.cell.row}:${e.cell.col}` : `o:${e.object}`; + const o = doc.objects[e.object]; + const box = e.cell && o?.kind === 'table' ? cellBox(o, e.cell.index, e.cell.col) : geo.objectBox(e.object); + for (const at of occurrences(e.text, q, matchCase)) { + push({ key: `${target}@${at}`, target, kind: e.kind, object: e.object, ...(e.cell ? { cell: e.cell } : {}), at, length: q.length, box }); + } + } + + const symbol = elementQuery(q); + for (const a of index.atoms) { + const label = a.texts.some((s) => contains(s, q, matchCase)); + const element = !label && symbol !== null && a.element === symbol && (matchCase ? q.trim() === symbol : true); + if (!label && !element) continue; + const target = `a:${a.frag}/${a.atom}`; + push({ key: target, target, kind: label ? 'label' : 'element', object: a.frag, atoms: [a.atom], box: atomsBox(doc, a.frag, [a.atom], geo) }); + } + + const formula = formulaQuery(q); + const smiles = new Set(opts.smiles ?? []); + for (const f of index.frags) { + const whole = `f:${f.frag.id}`; + const wholeBox = (): Box | null => geo.objectBox(f.frag.id) ?? atomsBox(doc, f.frag.id, Object.keys(f.frag.atoms), geo); + if (formula && sameCounts(f.counts, formula)) { + push({ key: whole, target: whole, kind: 'formula', object: f.frag.id, box: wholeBox() }); + } else if (formula && f.components.length > 1) { + for (const comp of f.components) { + if (!sameCounts(fragmentCounts(subFragment(f.frag, comp), { expansions: doc.expansions }).counts, formula)) continue; + const key = `f:${f.frag.id}:${comp[0]}`; + push({ key, target: key, kind: 'formula', object: f.frag.id, atoms: comp, box: atomsBox(doc, f.frag.id, comp, geo) }); + } + } + if (smiles.size && f.smiles.some((s) => smiles.has(s))) push({ key: whole, target: whole, kind: 'smiles', object: f.frag.id, box: wholeBox() }); + } + + const order = hits.map((h, i) => ({ h, i, y: h.box ? Math.round(h.box.y / ROW_PT) : Infinity, x: h.box?.x ?? Infinity })); + order.sort((a, b) => a.y - b.y || a.x - b.x || a.i - b.i); + return order.map((o) => o.h); +} + +export function hitSelection(doc: FormChemDocument, hit: FindHit): Selection { + const o = doc.objects[hit.object]; + if (!o) return makeSelection(); + if (o.kind !== 'fragment') return makeSelection([], [], [hit.object]); + if (!hit.atoms) return fragmentSelection(o); + const keep = new Set(hit.atoms); + const bonds = Object.values(o.bonds).filter((b) => keep.has(b.a) && keep.has(b.b)).map((b) => selectionKey(o.id, b.id)); + return makeSelection(hit.atoms.map((a) => selectionKey(o.id, a)), bonds); +} + +export const replaceable = (hit: FindHit): boolean => (hit.kind === 'text' || hit.kind === 'caption' || hit.kind === 'cell') && hit.at !== undefined; + +export function spliceRuns(runs: readonly Run[], at: number, length: number, text: string): Run[] { + const out: Run[] = []; + let pos = 0, placed = false; + for (const r of runs) { + const start = pos, end = pos + r.t.length; + pos = end; + if (end <= at || start >= at + length) { out.push(r); continue; } + const head = r.t.slice(0, Math.max(0, at - start)); + const tail = r.t.slice(Math.min(r.t.length, at + length - start)); + const t = head + (placed ? '' : text) + tail; + placed = true; + if (t) out.push({ ...r, t }); + } + return out.length ? out : [{ ...(runs[0] ?? {}), t: '' }]; +} + +export function replaceOps(doc: FormChemDocument, hits: readonly FindHit[], text: string): Op[] { + const groups = new Map(); + for (const h of hits) { + if (!replaceable(h)) continue; + const list = groups.get(h.target); + if (list) list.push(h); + else groups.set(h.target, [h]); + } + const ops: Op[] = []; + for (const list of groups.values()) { + const first = list[0]; + const o = doc.objects[first.object]; + let runs: Run[] | undefined; + let path: Path; + if (first.cell && o?.kind === 'table') { + const ri = o.rows.findIndex((r) => r.id === first.cell!.row); + runs = o.rows[ri]?.cells[first.cell.col]?.runs; + path = objectPath(o.id, 'rows', { id: first.cell.row }, 'cells', first.cell.col, 'runs'); + } else if (o?.kind === 'text' || o?.kind === 'caption') { + runs = o.runs; + path = objectPath(o.id, 'runs'); + } else continue; + if (!runs) continue; + let next: Run[] = runs; + for (const h of [...list].sort((a, b) => (b.at ?? 0) - (a.at ?? 0))) next = spliceRuns(next, h.at!, h.length ?? 0, text); + if (plain(next) !== plain(runs)) ops.push({ op: 'set', path, value: next }); + } + return ops; +} From c7c0dddca92e664f5285f28b95b65089abdc21ae Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:51:29 -0500 Subject: [PATCH 119/279] feat(canvas): highlight find matches in a keyed doc-space layer (0.5.0) Each matched object, cell or atom keeps one rect that is patched in place as the hits change, so typing a query or moving between matches never rebuilds the layer. --- frontend/src/canvas/find-marks.ts | 29 +++++++++++++++++++++++++++++ frontend/src/styles/canvas-view.css | 2 ++ 2 files changed, 31 insertions(+) create mode 100644 frontend/src/canvas/find-marks.ts diff --git a/frontend/src/canvas/find-marks.ts b/frontend/src/canvas/find-marks.ts new file mode 100644 index 00000000..48cb342f --- /dev/null +++ b/frontend/src/canvas/find-marks.ts @@ -0,0 +1,29 @@ +import type { FindHit } from './find'; +import { fmt, inflate } from './render/geom'; +import { Keyed, svgEl } from './render/svg'; +import type { CanvasView } from './view'; + +const PAD_PT = 1.6; + +export class FindMarks { + private readonly keyed: Keyed; + + constructor(view: CanvasView) { + this.keyed = new Keyed(view.docLayer('fc-find-marks'), (id) => svgEl('g', { 'data-find': id })); + } + + sync(hits: readonly FindHit[], current: number): void { + const keep = new Set(); + const now = hits[current]?.target; + for (const h of hits) { + if (!h.box || keep.has(h.target)) continue; + keep.add(h.target); + const b = inflate(h.box, PAD_PT); + const cls = h.target === now ? 'fc-find-mark is-current' : 'fc-find-mark'; + this.keyed.patch(h.target, [{ tag: 'rect', a: { x: fmt(b.x), y: fmt(b.y), width: fmt(b.w), height: fmt(b.h), rx: fmt(PAD_PT), class: cls } }]); + } + this.keyed.keep(keep); + } + + clear(): void { this.keyed.clear(); } +} diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index 2e07f54f..3b20dbfd 100644 --- a/frontend/src/styles/canvas-view.css +++ b/frontend/src/styles/canvas-view.css @@ -22,6 +22,8 @@ .fc-canvas-svg text { cursor: inherit; } .fc-canvas-keycursor { fill: none; stroke: color-mix(in srgb, var(--fc-sel) 28%, transparent); stroke-linecap: round; } .fc-canvas:not(.has-key-cursor) .fc-canvas-keycursor { display: none; } +.fc-find-mark { fill: color-mix(in srgb, var(--warn) 20%, transparent); stroke: color-mix(in srgb, var(--warn) 65%, transparent); stroke-width: 1; vector-effect: non-scaling-stroke; } +.fc-find-mark.is-current { fill: color-mix(in srgb, var(--accent-color) 24%, transparent); stroke: var(--accent-color); stroke-width: 1.6; } .fc-canvas-live { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } .fc-text-edit { position: fixed; left: 0; top: 0; z-index: var(--z-raised); min-width: 1ch; max-width: 60vw; padding: 1px 3px; border: 1px solid var(--fc-sel); border-radius: var(--radius-xs); background: #ffffff; color: #000000; box-shadow: var(--shadow-sm); font-size: 13px; line-height: 1.15; white-space: pre; outline: none; caret-color: var(--fc-sel); transform: translate(0, -50%); user-select: text; -webkit-user-select: text; } From d989c6df5ec95a9cee83d73cf523b5cbeebe908c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:52:43 -0500 Subject: [PATCH 120/279] feat(ui): add the find bar with next, previous and replace (0.5.0) The bar is built once and docked over the canvas top edge, so opening it shifts nothing; each match selects its object or atoms and pans to it only when it is off screen, and Replace All lands as one undo step. --- frontend/src/styles/canvas-view.css | 16 ++ frontend/src/ui/find-bar.ts | 330 ++++++++++++++++++++++++++++ 2 files changed, 346 insertions(+) create mode 100644 frontend/src/ui/find-bar.ts diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index 3b20dbfd..15be5247 100644 --- a/frontend/src/styles/canvas-view.css +++ b/frontend/src/styles/canvas-view.css @@ -31,6 +31,22 @@ .fc-text-edit.is-multiline { transform: none; white-space: pre-wrap; text-align: left; } .fc-text-edit[hidden] { display: none; } +.fc-find { position: absolute; top: var(--space-2); right: var(--space-3); z-index: var(--z-local-5); display: flex; flex-direction: column; gap: var(--space-1); box-sizing: border-box; width: min(430px, calc(100% - 2 * var(--space-3))); padding: var(--space-1); border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-1); box-shadow: var(--shadow-md); color: var(--text-primary); font-size: var(--fc-12); } +.fc-find[hidden], .fc-find-row[hidden] { display: none; } +.fc-stage.has-rulers .fc-find { top: calc(var(--fc-ruler-size, 20px) + var(--space-2)); } +.fc-find-row { display: flex; align-items: center; gap: 2px; min-width: 0; } +.fc-find .fc-icon-btn { width: var(--ctl-sm); height: var(--ctl-sm); } +.fc-find .fc-icon-btn:disabled { opacity: 0.4; cursor: default; background: transparent; } +.fc-find-gap { flex: none; width: var(--ctl-sm); } +.fc-find-input { flex: 1 1 auto; min-width: 0; height: var(--ctl-sm); padding: 0 8px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--surface-field); color: var(--text-primary); font: inherit; font-size: var(--fc-12); outline: 0; } +.fc-find-input:focus { border-color: var(--accent-color); } +.fc-find.is-empty .fc-find-query { border-color: var(--danger-soft); } +.fc-find-count { flex: none; min-width: 64px; padding: 0 4px; color: var(--text-muted); font-size: var(--fc-11); font-variant-numeric: tabular-nums; text-align: right; white-space: nowrap; } +.fc-find-case.is-on { background: var(--accent-soft); color: var(--accent-ink); } +.fc-find-more .icon { transition: transform var(--transition-fast); } +.fc-find.has-replace .fc-find-more .icon { transform: rotate(90deg); } + @media (prefers-reduced-motion: reduce) { .fc-canvas-paper { will-change: auto; } + .fc-find-more .icon { transition: none; } } diff --git a/frontend/src/ui/find-bar.ts b/frontend/src/ui/find-bar.ts new file mode 100644 index 00000000..4a9984b6 --- /dev/null +++ b/frontend/src/ui/find-bar.ts @@ -0,0 +1,330 @@ +import { findIndex, hitSelection, replaceable, replaceOps, search, smilesCandidate, type FindGeometry, type FindHit, type FindIndex } from '../canvas/find'; +import { FindMarks } from '../canvas/find-marks'; +import { objectBounds } from '../canvas/hit'; +import type { CanvasView } from '../canvas/view'; +import type { DocumentClient } from '../engine/client-api'; +import type { Derived, DerivedFragment, FormChemDocument, Fragment, Id } from '../engine/model'; +import { t } from '../i18n'; +import { post } from '../io/api'; +import { el, q, setAttr, setClass, setDisabled, setHidden, setText, setTitle } from './dom'; +import { icon } from './icons'; +import { toast } from './toast'; + +export interface FindBar { + readonly root: HTMLElement; + isOpen(): boolean; + open(replace?: boolean): void; + close(): void; + next(): void; + previous(): void; + replace(): void; + replaceAll(): void; + count(): number; + onChange(fn: () => void): () => void; +} + +const SMILES_DELAY_MS = 280; + +const HTML = ``; + +interface Canonical { text: string; smiles: string[] | null } + +export function mountFindBar(host: HTMLElement, view: CanvasView): FindBar { + const root = el(HTML); + const input = q(root, '.fc-find-query'); + const withInput = q(root, '.fc-find-with'); + const countEl = q(root, '.fc-find-count'); + const more = q(root, '.fc-find-more'); + const caseBtn = q(root, '.fc-find-case'); + const prevBtn = q(root, '.fc-find-prev'); + const nextBtn = q(root, '.fc-find-next'); + const closeBtn = q(root, '.fc-find-close'); + const replaceRow = q(root, '.fc-find-replace'); + const oneBtn = q(root, '.fc-find-one'); + const allBtn = q(root, '.fc-find-all'); + host.appendChild(root); + + const marks = new FindMarks(view); + const listeners = new Set<() => void>(); + let open = false; + let matchCase = false; + let hits: FindHit[] = []; + let current = -1; + let index: FindIndex | null = null; + let indexFor: [FormChemDocument | null, Id | null, Derived | null] = [null, null, null]; + let canonical: Canonical = { text: '', smiles: null }; + let smilesTimer: number | undefined; + let raf = 0; + let pendingSelect = false; + let advanceFrom: { i: number; target: string; at: number } | null = null; + let offClient: (() => void) | null = null; + + const changed = (): void => { for (const fn of [...listeners]) fn(); }; + const query = (): string => input.value.trim(); + const derivedNow = (): Derived | null => view.client?.derived ?? null; + + const geo: FindGeometry = { + objectBox: (id) => { + const r = view.renderer as typeof view.renderer & { objectBox?: (id: Id) => { x: number; y: number; w: number; h: number } | null }; + return r.objectBox?.(id) ?? objectBounds(view.doc, id); + }, + atomBox: (f, a) => view.renderer.labelBox(f, a), + }; + + const labels = (): void => { + input.placeholder = t('Find text, labels, formulas or SMILES'); + setAttr(input, 'aria-label', t('Find')); + withInput.placeholder = t('Replace with'); + setAttr(withInput, 'aria-label', t('Replace with')); + setTitle(more, t('Show Replace')); + setAttr(more, 'aria-label', t('Show Replace')); + setTitle(caseBtn, t('Match Case')); + setAttr(caseBtn, 'aria-label', t('Match Case')); + setTitle(prevBtn, `${t('Previous Match')} (Shift+F3)`); + setAttr(prevBtn, 'aria-label', t('Previous Match')); + setTitle(nextBtn, `${t('Next Match')} (F3)`); + setAttr(nextBtn, 'aria-label', t('Next Match')); + setTitle(closeBtn, `${t('Close')} (Esc)`); + setAttr(closeBtn, 'aria-label', t('Close')); + setText(oneBtn, t('Replace')); + setText(allBtn, t('Replace All')); + }; + labels(); + + function freshIndex(): FindIndex | null { + const client = view.client; + if (!client) return null; + const doc = view.doc, page = view.page()?.id ?? null, derived = derivedNow(); + if (!index || indexFor[0] !== doc || indexFor[1] !== page || indexFor[2] !== derived) { + index = findIndex(doc, page, derived); + indexFor = [doc, page, derived]; + } + return index; + } + + function showCount(): void { + const n = hits.length; + const text = !query() ? '' : n ? t(`${current + 1} of ${n}`) : t('No results'); + setText(countEl, text); + setClass(root, 'is-empty', !!query() && !n); + setDisabled(prevBtn, !n); + setDisabled(nextBtn, !n); + const canReplace = hits.some(replaceable); + setDisabled(oneBtn, !canReplace || !view.client); + setDisabled(allBtn, !canReplace || !view.client); + } + + function avoid(): { top: number } { + const hostBox = view.root.getBoundingClientRect(), mine = root.getBoundingClientRect(); + return { top: Math.max(0, mine.bottom - hostBox.top - view.insets().top) }; + } + + function go(i: number, select = true): void { + if (!hits.length) { current = -1; marks.sync(hits, current); showCount(); return; } + current = ((i % hits.length) + hits.length) % hits.length; + const hit = hits[current]; + marks.sync(hits, current); + showCount(); + if (!select) return; + view.setSelection(hitSelection(view.doc, hit)); + if (hit.box) view.reveal(hit.box, avoid()); + } + + function run(select: boolean): void { + const idx = open ? freshIndex() : null; + const text = query(); + const keep = current >= 0 ? hits[current]?.key : undefined; + const smiles = canonical.text === text && canonical.smiles ? canonical.smiles : []; + hits = idx && text ? search(idx, text, { matchCase, smiles }, geo) : []; + if (advanceFrom) { + const from = advanceFrom; + advanceFrom = null; + let i = hits.findIndex((h, k) => k >= from.i && !(h.target === from.target && (h.at ?? 0) < from.at)); + if (i < 0) i = 0; + go(i, true); + } else if (select || current < 0) { + go(0, select && hits.length > 0); + } else { + const at = keep ? hits.findIndex((h) => h.key === keep) : -1; + current = at >= 0 ? at : Math.min(current, hits.length - 1); + marks.sync(hits, current); + showCount(); + } + changed(); + } + + function schedule(select = false): void { + pendingSelect ||= select; + if (raf) return; + raf = requestAnimationFrame(() => { + raf = 0; + const s = pendingSelect; + pendingSelect = false; + if (open) run(s); + }); + } + + async function canonicalise(text: string): Promise { + const out: string[] = []; + try { + const parsed = await post<{ fragments?: Fragment[] }>('/api/chem/parse', { text, format: 'smiles' }); + for (const f of parsed.fragments ?? []) { + const d = await post('/api/chem/derive', { fragment: f }); + if (d.smiles) out.push(d.smiles); + } + } catch { + out.length = 0; + } + if (canonical.text !== text) return; + canonical = { text, smiles: out }; + if (open && query() === text && out.length) schedule(current < 0); + } + + function onQuery(): void { + const text = query(); + window.clearTimeout(smilesTimer); + canonical = { text, smiles: null }; + if (smilesCandidate(text)) smilesTimer = window.setTimeout(() => { void canonicalise(text); }, SMILES_DELAY_MS); + current = -1; + schedule(true); + } + + function hook(client: DocumentClient | null): void { + offClient?.(); + offClient = client ? client.on((e) => { if (e.type === 'tx' || e.type === 'reset' || e.type === 'derived') schedule(false); }) : null; + index = null; + current = -1; + if (open) schedule(false); + } + + function openBar(replace = false): void { + if (replace) toggleReplace(true); + if (!open) { + open = true; + setHidden(root, false); + hook(view.client); + if (query()) schedule(false); + } + const field = replace && query() ? withInput : input; + field.focus({ preventScroll: true }); + field.select(); + changed(); + } + + function closeBar(): void { + if (!open) return; + open = false; + window.clearTimeout(smilesTimer); + offClient?.(); + offClient = null; + setHidden(root, true); + marks.clear(); + hits = []; + current = -1; + index = null; + view.focus(); + changed(); + } + + function toggleReplace(on: boolean = replaceRow.hidden !== false): void { + setHidden(replaceRow, !on); + setAttr(more, 'aria-expanded', on ? 'true' : 'false'); + setClass(root, 'has-replace', on); + const label = on ? t('Hide Replace') : t('Show Replace'); + setTitle(more, label); + setAttr(more, 'aria-label', label); + } + + function step(dir: 1 | -1): void { + if (!open) { openBar(); return; } + if (!hits.length) return; + go(current < 0 ? (dir > 0 ? 0 : hits.length - 1) : current + dir); + } + + function replaceOne(): void { + const client = view.client; + if (!client || !hits.length) return; + const i = current < 0 ? 0 : current; + const hit = hits[i]; + if (!replaceable(hit)) { + const next = hits.findIndex((h, k) => k > i && replaceable(h)); + go(next >= 0 ? next : hits.findIndex(replaceable)); + return; + } + const ops = replaceOps(view.doc, [hit], withInput.value); + if (!ops.length) { go(i + 1); return; } + advanceFrom = { i, target: hit.target, at: (hit.at ?? 0) + withInput.value.length }; + if (!client.commit(t('Replace'), ops)) advanceFrom = null; + } + + function replaceEvery(): void { + const client = view.client; + if (!client) return; + const all = hits.filter(replaceable); + const ops = replaceOps(view.doc, all, withInput.value); + if (!ops.length) return; + if (client.commit(t('Replace All'), ops)) { + current = -1; + toast(all.length === 1 ? t('Replaced 1 match') : t(`Replaced ${all.length} matches`)); + } + } + + const keys = (e: KeyboardEvent, enter: () => void): void => { + if (e.isComposing) return; + if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); closeBar(); return; } + if (e.key === 'F3') { e.preventDefault(); e.stopPropagation(); step(e.shiftKey ? -1 : 1); return; } + if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); enter(); } + }; + + input.addEventListener('input', onQuery); + input.addEventListener('keydown', (e) => keys(e, () => step(e.shiftKey ? -1 : 1))); + withInput.addEventListener('keydown', (e) => keys(e, () => ((e.ctrlKey || e.metaKey) ? replaceEvery() : replaceOne()))); + root.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !e.defaultPrevented) { e.preventDefault(); closeBar(); } }); + more.addEventListener('click', () => toggleReplace()); + caseBtn.addEventListener('click', () => { + matchCase = !matchCase; + setAttr(caseBtn, 'aria-pressed', matchCase ? 'true' : 'false'); + setClass(caseBtn, 'is-on', matchCase); + current = -1; + schedule(true); + }); + prevBtn.addEventListener('click', () => step(-1)); + nextBtn.addEventListener('click', () => step(1)); + closeBtn.addEventListener('click', () => closeBar()); + oneBtn.addEventListener('click', () => replaceOne()); + allBtn.addEventListener('click', () => replaceEvery()); + view.on('client', () => { if (open) hook(view.client); }); + view.on('page', () => { if (open) { current = -1; schedule(false); } }); + + return { + root, + isOpen: () => open, + open: openBar, + close: closeBar, + next: () => step(1), + previous: () => step(-1), + replace: replaceOne, + replaceAll: replaceEvery, + count: () => hits.length, + onChange(fn) { + listeners.add(fn); + return () => { listeners.delete(fn); }; + }, + }; +} From c5c5b9d54274688fd002543d8907e037e173a1ee Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:53:11 -0500 Subject: [PATCH 121/279] feat(app): wire Find, Find Next, Find Previous and Replace (0.5.0) The 0.11.0 placeholder gives way to real commands: Mod+F opens the find bar, F3 and Shift+F3 step through matches (Mod+G stays with Group) and Alt+Mod+F opens Replace. --- frontend/src/app/canvas-commands.ts | 14 ++++++++++++++ frontend/src/app/canvas.ts | 5 ++++- frontend/src/app/commands-shell.ts | 1 - 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index b2121584..74f4406b 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -14,12 +14,25 @@ import { t } from '../i18n'; import { post } from '../io/api'; import { setAnalysisOpen } from '../ui/analysis-panel'; import { Dialog } from '../ui/dialogs'; +import type { FindBar } from '../ui/find-bar'; import { el, setText } from '../ui/dom'; import { toast } from '../ui/toast'; export interface CanvasCommandDeps { view: CanvasView; homeOpen(): boolean; + find?: FindBar; +} + +function findCommands(bar: FindBar, open: () => boolean): CommandDef[] { + const NEED_DRAWING = 'Open or create a drawing first'; + const NEED_QUERY = 'Open the find bar and type what to find first'; + return [ + { id: 'find', label: () => t('Find...'), group: 'Edit', keys: ['Mod+F'], icon: 'find', description: 'Opens the find bar over the canvas. It finds text, captions, table cells, atom labels and abbreviations, element symbols, formulas such as C2H6O and SMILES in the active drawing; Enter or F3 goes to the next match and selects it.', when: NEED_DRAWING, enabled: open, run: () => bar.open() }, + { id: 'find-next', label: () => t('Find Next'), group: 'Edit', keys: ['F3'], description: 'Selects the next find match and pans to it when it is off screen.', when: NEED_QUERY, enabled: () => open() && (!bar.isOpen() || bar.count() > 0), run: () => bar.next() }, + { id: 'find-previous', label: () => t('Find Previous'), group: 'Edit', keys: ['Shift+F3'], description: 'Selects the previous find match and pans to it when it is off screen.', when: NEED_QUERY, enabled: () => open() && (!bar.isOpen() || bar.count() > 0), run: () => bar.previous() }, + { id: 'replace', label: () => t('Replace...'), group: 'Edit', keys: ['Alt+Mod+F'], icon: 'replace', mutates: true, description: 'Opens the find bar with its Replace row. Replace changes the current text match; Replace All changes every text match in one undo step.', when: NEED_DRAWING, enabled: open, run: () => bar.open(true) }, + ]; } interface LayoutAnswer { coords?: Record; stereo?: Record; warnings?: { text?: string }[] } @@ -219,6 +232,7 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { tool('insert-table', 'Table', 'table', 'table', 'Insert'), { id: 'insert-image', label: () => t('Image...'), group: 'Insert', icon: 'image', mutates: true, description: 'Asks the person for a PNG, JPEG, GIF, WebP or SVG picture and places it in the middle of the visible page as one undo step.', when: NEED_DRAWING, enabled: open, run: () => { void placeImage(view.context, visibleCentre(view), null); } }, tool('add-reaction-arrow', 'Add Reaction Arrow', 'arrow', 'arrow-forward', 'Reaction'), + ...(deps.find ? findCommands(deps.find, open) : []), ]; return commands.register(...defs); } diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index 181db2e3..506364cf 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -8,6 +8,7 @@ import type { EngineDocumentClient } from '../engine/client'; import type { Fragment, Id, Point, StyleOverride } from '../engine/model'; import { session } from '../engine/session'; import { setAnalysisScope } from '../ui/analysis-panel'; +import { mountFindBar } from '../ui/find-bar'; import { drawStyleOverride, drawStylePreset, loadSettings, pref, PREFS_EVENT } from '../ui/prefs/store'; import { setStoichScope } from '../ui/stoich-panel'; import { mountToolRail, type ToolRail } from '../ui/tool-rail'; @@ -43,7 +44,9 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan const rail = mountToolRail(h.stageCol, view); const open = (): boolean => !!view.client && !homeOpen(); commands.register(...rail.commands().map((c) => ({ ...c, enabled: open }))); - registerCanvasCommands({ view, homeOpen }); + const find = mountFindBar(h.stage, view); + find.onChange(() => commandStateChanged()); + registerCanvasCommands({ view, homeOpen, find }); commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); registerReactionCommands({ view, homeOpen }); diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index 9fafa32f..f9f18924 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -171,7 +171,6 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { later('copy-svg', 'Copy as SVG', 'Edit', '0.7.0'), { id: 'paste', label: () => t('Paste'), group: 'Edit', icon: 'paste', when: 'A text field has focus', enabled: () => !!focusedField(), run: fieldOr('paste', deps.paste) }, { id: 'select-all', label: () => t('Select All'), group: 'Edit', keys: ['Mod+A'], icon: 'selectAll', run: () => (fieldSelectAll() ? undefined : deps.selectAll()) }, - later('find', 'Find...', 'Edit', '0.11.0', 'find', 'Arrives in 0.11.0 with structure search'), { id: 'show-grid', label: () => t('Show Grid'), group: 'View', icon: 'grid', checked: () => deps.gridOn?.() ?? true, run: () => deps.showGrid() }, later('show-rulers', 'Show Rulers', 'View', '0.12.0', 'ruler', 'Arrives in 0.12.0 with page layout'), From 2b952b2366047b96d1224fb599bd27a5541f2df4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:55:07 -0500 Subject: [PATCH 122/279] feat(canvas): draw rulers whose pooled ticks follow pan and zoom (0.5.0) The rulers lie over the canvas edges instead of shrinking it, so toggling them never moves the drawing; a fixed pool of tick nodes is moved and relabelled in place each frame, and the corner switches units for this window. --- frontend/src/canvas/rulers.ts | 213 ++++++++++++++++++++++++++++ frontend/src/styles/canvas-view.css | 29 ++++ 2 files changed, 242 insertions(+) create mode 100644 frontend/src/canvas/rulers.ts diff --git a/frontend/src/canvas/rulers.ts b/frontend/src/canvas/rulers.ts new file mode 100644 index 00000000..3334e96e --- /dev/null +++ b/frontend/src/canvas/rulers.ts @@ -0,0 +1,213 @@ +import type { Units } from '../engine/model'; +import { t } from '../i18n'; +import { el, q, setClass, setHidden, setStyleVar, setText, setTitle } from '../ui/dom'; +import { local, setLocal } from '../ui/prefs/store'; +import type { CanvasView } from './view'; + +export const RULERS_KEY = 'formchem.showRulers'; +export const RULER_UNITS_KEY = 'formchem.rulerUnits'; +export const RULER_PX = 20; + +const MIN_MAJOR_PX = 56; +const MIN_MINOR_PX = 5; +const PT_PER: Record = { pt: 1, mm: 72 / 25.4, cm: 72 / 2.54, in: 72 }; +const UNIT_CYCLE: Array = ['doc', 'pt', 'mm', 'cm', 'in']; + +const HTML = ``; + +interface Tick { node: HTMLElement; label: Text; k: number; step: number; pos: number; shown: boolean } + +interface Axis { + horizontal: boolean; + ruler: HTMLElement; + ticks: HTMLElement; + marker: HTMLElement; + pool: Tick[]; + key: string; + major: string; + minor: string; + mid: string; + markerAt: number; +} + +export function niceStep(min: number): number { + const e = Math.floor(Math.log10(min)); + const base = 10 ** e; + for (const m of [1, 2, 5, 10]) if (m * base >= min - 1e-12) return m * base; + return 10 * base; +} + +function labelText(value: number, step: number): string { + const dec = step < 1 ? Math.min(6, Math.ceil(-Math.log10(step) - 1e-9)) : 0; + const s = value.toFixed(dec); + return /^-0(\.0+)?$/.test(s) ? s.slice(1) : s; +} + +export class Rulers { + readonly root: HTMLElement; + private readonly corner: HTMLButtonElement; + private readonly axes: [Axis, Axis]; + private readonly listeners = new Set<() => void>(); + private shown_ = false; + private override: Units | 'doc' = 'doc'; + private offClient: (() => void) | null = null; + private pointerIn = false; + + constructor(private readonly host: HTMLElement, private readonly view: CanvasView) { + this.root = el(HTML); + this.corner = q(this.root, '.fc-ruler-corner'); + const axis = (sel: string, horizontal: boolean): Axis => { + const ruler = q(this.root, sel); + return { horizontal, ruler, ticks: q(ruler, '.fc-ruler-ticks'), marker: q(ruler, '.fc-ruler-marker'), pool: [], key: '', major: '', minor: '', mid: '', markerAt: NaN }; + }; + this.axes = [axis('.fc-ruler.is-h', true), axis('.fc-ruler.is-v', false)]; + const saved = local(RULER_UNITS_KEY); + if (saved && (UNIT_CYCLE as string[]).includes(saved)) this.override = saved as Units | 'doc'; + setStyleVar(host, '--fc-ruler-size', `${RULER_PX}px`); + host.appendChild(this.root); + + this.corner.addEventListener('click', () => this.cycleUnits()); + this.root.addEventListener('wheel', (e) => { + e.preventDefault(); + view.root.dispatchEvent(new WheelEvent('wheel', e)); + }, { passive: false }); + view.on('viewport', () => this.layout()); + view.on('client', () => this.hook()); + const r = view.root; + r.addEventListener('pointermove', (e) => this.track(e), { passive: true }); + r.addEventListener('pointerleave', () => { this.pointerIn = false; this.syncMarkers(NaN, NaN); }); + this.hook(); + this.setShown(local(RULERS_KEY) === '1', false); + } + + shown(): boolean { return this.shown_; } + + toggle(): void { this.setShown(!this.shown_); } + + setShown(on: boolean, persist = true): void { + if (persist) setLocal(RULERS_KEY, on ? '1' : '0'); + if (on === this.shown_) return; + this.shown_ = on; + this.view.setInsets(on ? { top: RULER_PX, left: RULER_PX } : { top: 0, left: 0 }); + for (const a of this.axes) a.key = ''; + if (on) this.layout(); + setClass(this.host, 'has-rulers', on); + setHidden(this.root, !on); + this.emit(); + } + + units(): Units { + if (this.override !== 'doc') return this.override; + const u = this.view.client ? this.view.style().units : 'pt'; + return u in PT_PER ? u : 'pt'; + } + + onChange(fn: () => void): () => void { + this.listeners.add(fn); + return () => { this.listeners.delete(fn); }; + } + + private emit(): void { for (const fn of [...this.listeners]) fn(); } + + private hook(): void { + this.offClient?.(); + const c = this.view.client; + this.offClient = c ? c.on((e) => { if (e.type === 'tx' || e.type === 'reset') this.layout(); }) : null; + this.layout(); + } + + private cycleUnits(): void { + const at = UNIT_CYCLE.indexOf(this.override); + this.override = UNIT_CYCLE[(at + 1) % UNIT_CYCLE.length]; + setLocal(RULER_UNITS_KEY, this.override === 'doc' ? null : this.override); + this.layout(); + this.view.focus(); + } + + private layout(): void { + if (!this.shown_) return; + const v = this.view.viewport(); + const size = this.view.screenSize(); + const unit = this.units(); + setText(this.corner, unit); + setTitle(this.corner, this.override === 'doc' ? t('Ruler units follow the drawing; click to change') : t('Ruler units; click to change')); + this.layoutAxis(this.axes[0], v.x, v.zoom, size.w, unit); + this.layoutAxis(this.axes[1], v.y, v.zoom, size.h, unit); + } + + private layoutAxis(a: Axis, origin: number, zoom: number, length: number, unit: Units): void { + const key = `${origin},${zoom},${length},${unit}`; + if (key === a.key) return; + a.key = key; + const pxPerUnit = PT_PER[unit] * zoom; + const step = niceStep(MIN_MAJOR_PX / pxPerUnit); + const majorPx = step * pxPerUnit; + const minors = majorPx / 10 >= MIN_MINOR_PX ? 10 : majorPx / 5 >= MIN_MINOR_PX ? 5 : 2; + const major = `${majorPx.toFixed(3)}px`, minor = `${(majorPx / minors).toFixed(3)}px`, mid = minors === 10 ? `${(majorPx / 2).toFixed(3)}px` : major; + if (major !== a.major) { a.major = major; setStyleVar(a.ruler, '--fc-ruler-major', major); } + if (minor !== a.minor) { a.minor = minor; setStyleVar(a.ruler, '--fc-ruler-minor', minor); } + if (mid !== a.mid) { a.mid = mid; setStyleVar(a.ruler, '--fc-ruler-mid', mid); } + + const k0 = Math.floor(-origin / majorPx), k1 = Math.ceil((length - origin) / majorPx); + const count = Math.max(0, k1 - k0 + 1); + if (count > a.pool.length) this.grow(a, count + 4); + const n = a.pool.length; + const used = new Set(); + for (let k = k0; k <= k1; k++) { + const i = ((k % n) + n) % n; + used.add(i); + const tk = a.pool[i]; + const pos = Math.round((origin + k * majorPx) * 100) / 100; + if (tk.k !== k || tk.step !== step) { + tk.k = k; + tk.step = step; + const text = labelText(k * step, step); + if (tk.label.data !== text) tk.label.data = text; + } + if (tk.pos !== pos) { + tk.pos = pos; + tk.node.style.transform = a.horizontal ? `translate3d(${pos}px,0,0)` : `translate3d(0,${pos}px,0)`; + } + if (!tk.shown) { tk.shown = true; tk.node.hidden = false; } + } + a.pool.forEach((tk, i) => { if (!used.has(i) && tk.shown) { tk.shown = false; tk.node.hidden = true; } }); + } + + private grow(a: Axis, to: number): void { + const fresh: Tick[] = []; + while (a.pool.length + fresh.length < to) { + const node = el(''); + const label = document.createTextNode(''); + node.firstElementChild!.appendChild(label); + fresh.push({ node, label, k: NaN, step: NaN, pos: NaN, shown: false }); + } + a.ticks.append(...fresh.map((f) => f.node)); + a.pool.push(...fresh); + for (const tk of a.pool) tk.k = NaN; + } + + private track(e: PointerEvent): void { + if (!this.shown_) return; + this.pointerIn = true; + const r = this.view.root.getBoundingClientRect(); + this.syncMarkers(e.clientX - r.left, e.clientY - r.top); + } + + private syncMarkers(x: number, y: number): void { + const [h, v] = this.axes; + this.place(h, this.pointerIn ? x : NaN); + this.place(v, this.pointerIn ? y : NaN); + } + + private place(a: Axis, at: number): void { + const p = Number.isFinite(at) ? Math.round(at) : NaN; + if (p === a.markerAt || (Number.isNaN(p) && Number.isNaN(a.markerAt))) return; + a.markerAt = p; + setClass(a.marker, 'is-on', Number.isFinite(p)); + if (Number.isFinite(p)) a.marker.style.transform = a.horizontal ? `translate3d(${p}px,0,0)` : `translate3d(0,${p}px,0)`; + } +} diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index 15be5247..cd2a30c9 100644 --- a/frontend/src/styles/canvas-view.css +++ b/frontend/src/styles/canvas-view.css @@ -46,6 +46,35 @@ .fc-find-more .icon { transition: transform var(--transition-fast); } .fc-find.has-replace .fc-find-more .icon { transform: rotate(90deg); } +.fc-rulers { position: absolute; inset: 0; z-index: var(--z-local-4); pointer-events: none; --fc-ruler-ink: color-mix(in srgb, var(--text-muted) 75%, transparent); } +.fc-rulers[hidden] { display: none; } +.fc-ruler { position: absolute; overflow: hidden; box-sizing: border-box; background: var(--surface-1); color: var(--text-muted); pointer-events: auto; contain: strict; user-select: none; -webkit-user-select: none; touch-action: none; } +.fc-ruler.is-h { left: 0; right: 0; top: 0; height: var(--fc-ruler-size); border-bottom: 1px solid var(--line-1); cursor: row-resize; } +.fc-ruler.is-v { left: 0; top: 0; bottom: 0; width: var(--fc-ruler-size); border-right: 1px solid var(--line-1); cursor: col-resize; } +.fc-ruler-ticks { position: absolute; inset: 0; } +.fc-ruler-tick { position: absolute; left: 0; top: 0; will-change: transform; background-repeat: repeat-x; } +.fc-ruler-tick[hidden] { display: none; } +.fc-ruler.is-h .fc-ruler-tick { + width: var(--fc-ruler-major); height: 100%; + background-image: linear-gradient(to right, var(--fc-ruler-ink) 1px, transparent 1px), linear-gradient(to right, var(--fc-ruler-ink) 1px, transparent 1px), linear-gradient(to right, var(--fc-ruler-ink) 1px, transparent 1px); + background-size: var(--fc-ruler-major) 100%, var(--fc-ruler-mid) 50%, var(--fc-ruler-minor) 25%; + background-position: 0 100%; +} +.fc-ruler.is-v .fc-ruler-tick { + width: 100%; height: var(--fc-ruler-major); background-repeat: repeat-y; + background-image: linear-gradient(to bottom, var(--fc-ruler-ink) 1px, transparent 1px), linear-gradient(to bottom, var(--fc-ruler-ink) 1px, transparent 1px), linear-gradient(to bottom, var(--fc-ruler-ink) 1px, transparent 1px); + background-size: 100% var(--fc-ruler-major), 50% var(--fc-ruler-mid), 25% var(--fc-ruler-minor); + background-position: 100% 0; +} +.fc-ruler-label { position: absolute; left: 3px; top: 1px; font-size: var(--fc-9); line-height: 10px; font-variant-numeric: tabular-nums; white-space: nowrap; } +.fc-ruler.is-v .fc-ruler-label { left: 1px; top: 3px; writing-mode: vertical-rl; transform: rotate(180deg); } +.fc-ruler-marker { position: absolute; left: 0; top: 0; display: none; background: var(--accent-color); pointer-events: none; } +.fc-ruler-marker.is-on { display: block; } +.fc-ruler.is-h .fc-ruler-marker { width: 1px; height: 100%; } +.fc-ruler.is-v .fc-ruler-marker { width: 100%; height: 1px; } +.fc-ruler-corner { position: absolute; left: 0; top: 0; z-index: var(--z-local-2); display: grid; place-items: center; box-sizing: border-box; width: var(--fc-ruler-size); height: var(--fc-ruler-size); padding: 0; border: 0; border-right: 1px solid var(--line-1); border-bottom: 1px solid var(--line-1); background: var(--surface-1); color: var(--text-secondary); font: inherit; font-size: var(--fc-9); pointer-events: auto; cursor: pointer; } +.fc-ruler-corner:hover { color: var(--text-primary); background: var(--surface-raised); } + @media (prefers-reduced-motion: reduce) { .fc-canvas-paper { will-change: auto; } .fc-find-more .icon { transition: none; } From 2a85f4ce069ad3366d31ed60bc161b8f1f1b4c90 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:56:19 -0500 Subject: [PATCH 123/279] feat(canvas): drag guides out of the rulers (0.5.0) Guides belong to the window, kept per open drawing and never written to the document; they draw in the doc-space overlay so panning moves them for free, and dropping one back on a ruler removes it. --- frontend/src/canvas/rulers.ts | 126 +++++++++++++++++++++++++++- frontend/src/styles/canvas-view.css | 6 ++ 2 files changed, 130 insertions(+), 2 deletions(-) diff --git a/frontend/src/canvas/rulers.ts b/frontend/src/canvas/rulers.ts index 3334e96e..1a1b0e76 100644 --- a/frontend/src/canvas/rulers.ts +++ b/frontend/src/canvas/rulers.ts @@ -1,9 +1,16 @@ -import type { Units } from '../engine/model'; +import { newId, type Units } from '../engine/model'; import { t } from '../i18n'; import { el, q, setClass, setHidden, setStyleVar, setText, setTitle } from '../ui/dom'; import { local, setLocal } from '../ui/prefs/store'; +import { fmt } from './render/geom'; +import { Keyed, svgEl } from './render/svg'; import type { CanvasView } from './view'; +export interface Guide { id: string; axis: 'x' | 'y'; at: number } + +const GRAB_PX = 4; +const GUIDE_REACH = 1e5; + export const RULERS_KEY = 'formchem.showRulers'; export const RULER_UNITS_KEY = 'formchem.rulerUnits'; export const RULER_PX = 20; @@ -32,6 +39,7 @@ interface Axis { minor: string; mid: string; markerAt: number; + notches: Map; } export function niceStep(min: number): number { @@ -56,15 +64,27 @@ export class Rulers { private override: Units | 'doc' = 'doc'; private offClient: (() => void) | null = null; private pointerIn = false; + private readonly guides = new Map(); + private readonly guideLayer: SVGGElement; + private readonly guideNodes: Keyed; + private drag: { pointer: number; guide: Guide; ruler: HTMLElement } | null = null; constructor(private readonly host: HTMLElement, private readonly view: CanvasView) { this.root = el(HTML); this.corner = q(this.root, '.fc-ruler-corner'); const axis = (sel: string, horizontal: boolean): Axis => { const ruler = q(this.root, sel); - return { horizontal, ruler, ticks: q(ruler, '.fc-ruler-ticks'), marker: q(ruler, '.fc-ruler-marker'), pool: [], key: '', major: '', minor: '', mid: '', markerAt: NaN }; + return { horizontal, ruler, ticks: q(ruler, '.fc-ruler-ticks'), marker: q(ruler, '.fc-ruler-marker'), pool: [], key: '', major: '', minor: '', mid: '', markerAt: NaN, notches: new Map() }; }; this.axes = [axis('.fc-ruler.is-h', true), axis('.fc-ruler.is-v', false)]; + this.guideLayer = view.docLayer('fc-guides is-off'); + this.guideNodes = new Keyed(this.guideLayer, (id) => svgEl('g', { 'data-guide': id })); + for (const a of this.axes) { + a.ruler.addEventListener('pointerdown', (e) => this.down(e, a)); + a.ruler.addEventListener('pointermove', (e) => this.move(e)); + a.ruler.addEventListener('pointerup', (e) => this.up(e)); + a.ruler.addEventListener('pointercancel', (e) => this.up(e)); + } const saved = local(RULER_UNITS_KEY); if (saved && (UNIT_CYCLE as string[]).includes(saved)) this.override = saved as Units | 'doc'; setStyleVar(host, '--fc-ruler-size', `${RULER_PX}px`); @@ -96,10 +116,110 @@ export class Rulers { for (const a of this.axes) a.key = ''; if (on) this.layout(); setClass(this.host, 'has-rulers', on); + setClass(this.guideLayer, 'is-off', !on); setHidden(this.root, !on); this.emit(); } + guideCount(): number { return this.list().length; } + + clearGuides(): void { + this.list().length = 0; + this.syncGuides(); + this.emit(); + } + + private list(): Guide[] { + const key = this.view.client?.id ?? ''; + let l = this.guides.get(key); + if (!l) this.guides.set(key, (l = [])); + return l; + } + + private syncGuides(): void { + const keep = new Set(); + const [h, v] = this.axes; + for (const g of this.list()) { + keep.add(g.id); + const at = fmt(g.at); + const a = g.axis === 'x' + ? { x1: at, x2: at, y1: String(-GUIDE_REACH), y2: String(GUIDE_REACH), class: 'fc-guide' } + : { x1: String(-GUIDE_REACH), x2: String(GUIDE_REACH), y1: at, y2: at, class: 'fc-guide' }; + this.guideNodes.patch(g.id, [{ tag: 'line', a }]); + const ax = g.axis === 'x' ? h : v; + if (!ax.notches.has(g.id)) { + const node = el('
'); + ax.ruler.appendChild(node); + ax.notches.set(g.id, { node, pos: NaN }); + } + } + this.guideNodes.keep(keep); + for (const ax of this.axes) { + for (const [id, n] of ax.notches) if (!keep.has(id)) { n.node.remove(); ax.notches.delete(id); } + } + this.placeNotches(); + } + + private placeNotches(): void { + const v = this.view.viewport(); + const byId = new Map(this.list().map((g) => [g.id, g])); + for (const ax of this.axes) { + for (const [id, n] of ax.notches) { + const g = byId.get(id); + if (!g) continue; + const pos = Math.round(g.at * v.zoom + (ax.horizontal ? v.x : v.y)); + if (pos === n.pos) continue; + n.pos = pos; + n.node.style.transform = ax.horizontal ? `translate3d(${pos}px,0,0)` : `translate3d(0,${pos}px,0)`; + } + } + } + + private down(e: PointerEvent, a: Axis): void { + if (e.button !== 0 || this.drag || !this.view.client) return; + e.preventDefault(); + const r = this.view.root.getBoundingClientRect(), v = this.view.viewport(); + const s = a.horizontal ? e.clientX - r.left : e.clientY - r.top; + const pick: Guide['axis'] = a.horizontal ? 'x' : 'y'; + let g = this.list().find((x) => x.axis === pick && Math.abs(x.at * v.zoom + (pick === 'x' ? v.x : v.y) - s) <= GRAB_PX); + if (!g) { + const p = this.view.toDoc(e.clientX, e.clientY); + g = a.horizontal ? { id: newId('g'), axis: 'y', at: p[1] } : { id: newId('g'), axis: 'x', at: p[0] }; + this.list().push(g); + } + a.ruler.setPointerCapture(e.pointerId); + this.drag = { pointer: e.pointerId, guide: g, ruler: a.ruler }; + setClass(this.root, 'is-dragging', true); + this.syncGuides(); + } + + private move(e: PointerEvent): void { + const d = this.drag; + if (!d || d.pointer !== e.pointerId) { this.track(e); return; } + const p = this.view.toDoc(e.clientX, e.clientY); + d.guide.at = Math.round((d.guide.axis === 'x' ? p[0] : p[1]) * 100) / 100; + this.syncGuides(); + this.track(e); + } + + private up(e: PointerEvent): void { + const d = this.drag; + if (!d || d.pointer !== e.pointerId) return; + this.drag = null; + setClass(this.root, 'is-dragging', false); + if (d.ruler.hasPointerCapture(e.pointerId)) d.ruler.releasePointerCapture(e.pointerId); + const r = this.view.root.getBoundingClientRect(); + const s = d.guide.axis === 'x' ? e.clientX - r.left : e.clientY - r.top; + const max = d.guide.axis === 'x' ? r.width : r.height; + if (e.type === 'pointercancel' || s < RULER_PX || s > max) { + const l = this.list(); + const i = l.indexOf(d.guide); + if (i >= 0) l.splice(i, 1); + } + this.syncGuides(); + this.emit(); + } + units(): Units { if (this.override !== 'doc') return this.override; const u = this.view.client ? this.view.style().units : 'pt'; @@ -117,6 +237,7 @@ export class Rulers { this.offClient?.(); const c = this.view.client; this.offClient = c ? c.on((e) => { if (e.type === 'tx' || e.type === 'reset') this.layout(); }) : null; + this.syncGuides(); this.layout(); } @@ -137,6 +258,7 @@ export class Rulers { setTitle(this.corner, this.override === 'doc' ? t('Ruler units follow the drawing; click to change') : t('Ruler units; click to change')); this.layoutAxis(this.axes[0], v.x, v.zoom, size.w, unit); this.layoutAxis(this.axes[1], v.y, v.zoom, size.h, unit); + this.placeNotches(); } private layoutAxis(a: Axis, origin: number, zoom: number, length: number, unit: Units): void { diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index cd2a30c9..afc792f0 100644 --- a/frontend/src/styles/canvas-view.css +++ b/frontend/src/styles/canvas-view.css @@ -74,6 +74,12 @@ .fc-ruler.is-v .fc-ruler-marker { width: 100%; height: 1px; } .fc-ruler-corner { position: absolute; left: 0; top: 0; z-index: var(--z-local-2); display: grid; place-items: center; box-sizing: border-box; width: var(--fc-ruler-size); height: var(--fc-ruler-size); padding: 0; border: 0; border-right: 1px solid var(--line-1); border-bottom: 1px solid var(--line-1); background: var(--surface-1); color: var(--text-secondary); font: inherit; font-size: var(--fc-9); pointer-events: auto; cursor: pointer; } .fc-ruler-corner:hover { color: var(--text-primary); background: var(--surface-raised); } +.fc-ruler-notch { position: absolute; left: 0; top: 0; z-index: var(--z-local-2); background: var(--handle-image); } +.fc-ruler.is-h .fc-ruler-notch { top: auto; bottom: 0; width: 3px; height: 50%; margin-left: -1px; cursor: col-resize; } +.fc-ruler.is-v .fc-ruler-notch { left: auto; right: 0; width: 50%; height: 3px; margin-top: -1px; cursor: row-resize; } +.fc-rulers.is-dragging .fc-ruler, .fc-rulers.is-dragging .fc-ruler-notch { cursor: grabbing; } +.fc-guides.is-off { display: none; } +.fc-guide { stroke: var(--handle-image); stroke-width: 1; vector-effect: non-scaling-stroke; shape-rendering: crispEdges; } @media (prefers-reduced-motion: reduce) { .fc-canvas-paper { will-change: auto; } From 6275fee514aca02e46b05a6502c0940154611aa0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:56:26 -0500 Subject: [PATCH 124/279] feat(app): wire Show Rulers and Clear Guides (0.5.0) The 0.12.0 placeholder gives way to a real toggle whose state is remembered in local storage like Show Grid, and the rulers mount in the stage beside the canvas so they never resize it. --- frontend/src/app/canvas-commands.ts | 10 ++++++++++ frontend/src/app/canvas.ts | 5 ++++- frontend/src/app/commands-shell.ts | 1 - 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index 74f4406b..d71cdf1a 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -2,6 +2,7 @@ import { makeSelection, fragmentsTouched, isEmpty } from '../canvas/selection'; import { align, distribute, flipHorizontal, flipVertical, rotate90, type AlignHow } from '../canvas/tools'; import { atomsOfSelection, commitDraft, draftFor } from '../canvas/tools/common'; import { deleteSelection } from '../canvas/tools/edit'; +import type { Rulers } from '../canvas/rulers'; import { placeImage } from '../canvas/tools/image'; import { duplicateSelection } from '../canvas/tools/select'; import { translateSelection } from '../canvas/tools/transform'; @@ -22,6 +23,14 @@ export interface CanvasCommandDeps { view: CanvasView; homeOpen(): boolean; find?: FindBar; + rulers?: Rulers; +} + +function rulerCommands(rulers: Rulers): CommandDef[] { + return [ + { id: 'show-rulers', label: () => t('Show Rulers'), group: 'View', icon: 'ruler', description: 'Shows or hides rulers along the top and left canvas edges, in the drawing units (click the corner to switch units). Drag from a ruler to place a guide; drag a guide back onto a ruler to remove it. The choice is remembered.', checked: () => rulers.shown(), run: () => rulers.toggle() }, + { id: 'clear-guides', label: () => t('Clear Guides'), group: 'View', icon: 'guides', description: 'Removes every ruler guide from the active drawing in this window. Guides are never saved in the document.', when: 'Drag a guide out of a ruler first', enabled: () => rulers.guideCount() > 0, run: () => rulers.clearGuides() }, + ]; } function findCommands(bar: FindBar, open: () => boolean): CommandDef[] { @@ -233,6 +242,7 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { { id: 'insert-image', label: () => t('Image...'), group: 'Insert', icon: 'image', mutates: true, description: 'Asks the person for a PNG, JPEG, GIF, WebP or SVG picture and places it in the middle of the visible page as one undo step.', when: NEED_DRAWING, enabled: open, run: () => { void placeImage(view.context, visibleCentre(view), null); } }, tool('add-reaction-arrow', 'Add Reaction Arrow', 'arrow', 'arrow-forward', 'Reaction'), ...(deps.find ? findCommands(deps.find, open) : []), + ...(deps.rulers ? rulerCommands(deps.rulers) : []), ]; return commands.register(...defs); } diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index 506364cf..53b75800 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -1,4 +1,5 @@ import { createRenderer } from '../canvas/render'; +import { Rulers } from '../canvas/rulers'; import { EMPTY_SELECTION, fragmentSelection, fragmentsTouched, isEmpty, union } from '../canvas/selection'; import { TOOLS } from '../canvas/tools'; import type { RenderDisplay } from '../canvas/types'; @@ -44,9 +45,11 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan const rail = mountToolRail(h.stageCol, view); const open = (): boolean => !!view.client && !homeOpen(); commands.register(...rail.commands().map((c) => ({ ...c, enabled: open }))); + const rulers = new Rulers(h.stage, view); + rulers.onChange(() => commandStateChanged()); const find = mountFindBar(h.stage, view); find.onChange(() => commandStateChanged()); - registerCanvasCommands({ view, homeOpen, find }); + registerCanvasCommands({ view, homeOpen, find, rulers }); commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); registerReactionCommands({ view, homeOpen }); diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index f9f18924..02e27af6 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -173,7 +173,6 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { { id: 'select-all', label: () => t('Select All'), group: 'Edit', keys: ['Mod+A'], icon: 'selectAll', run: () => (fieldSelectAll() ? undefined : deps.selectAll()) }, { id: 'show-grid', label: () => t('Show Grid'), group: 'View', icon: 'grid', checked: () => deps.gridOn?.() ?? true, run: () => deps.showGrid() }, - later('show-rulers', 'Show Rulers', 'View', '0.12.0', 'ruler', 'Arrives in 0.12.0 with page layout'), { id: 'toggle-analysis', label: () => t('Analysis Panel'), group: 'View', icon: 'panelProps', checked: () => deps.analysisOpen(), run: () => deps.toggleAnalysis() }, { id: 'show-stoichiometry', label: () => t('Stoichiometry Panel'), group: 'View', icon: 'table', checked: () => deps.stoichOpen(), run: () => deps.toggleStoich() }, { id: 'view-terminal', label: () => t('Terminal and Claude Code'), group: 'View', keys: ['Mod+`'], icon: 'terminal', checked: () => deps.terminalOpen?.() ?? false, run: () => deps.terminal() }, From 3e815da869aef3ee6a3255e5d5426fd4ec8f92c5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 20:56:31 -0500 Subject: [PATCH 125/279] feat(menus): list Find, Replace and Clear Guides (0.5.0) Edit gains Find Next, Find Previous and Replace beside Find, and View lists Clear Guides under Show Rulers, so every new command is reachable from the menu bar. --- frontend/src/app/menus.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 64b80339..224ac58d 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -18,8 +18,8 @@ export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource }; return [ { label: 'File', items: () => ['home', 'new-document', 'open', recent(), '-', 'new-window', 'close-window', 'close-document', '-', 'save', 'save-as', 'save-copy', '-', 'import', EXPORT, 'print', '-', 'preferences'] }, - { label: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', COPY_AS, 'paste', 'duplicate', 'delete', '-', 'select-all', 'find'] }, - { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', '-', 'toggle-analysis', 'show-stoichiometry', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, + { label: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', COPY_AS, 'paste', 'duplicate', 'delete', '-', 'select-all', '-', 'find', 'find-next', 'find-previous', 'replace'] }, + { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', 'clear-guides', '-', 'toggle-analysis', 'show-stoichiometry', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, { label: 'Insert', items: ['insert-smiles', 'insert-name', 'insert-template', '-', 'insert-text', 'insert-arrow', 'insert-shape', 'insert-table', 'insert-image'] }, { label: 'Structure', items: ['clean-structure', 'layout-structure', 'check-structure', '-', 'expand-abbreviation', 'contract-abbreviation', '-', 'add-hydrogens', 'remove-hydrogens', 'show-stereo', '-', 'flip-horizontal', 'flip-vertical'] }, { label: 'Reaction', items: ['add-reaction-arrow', 'perceive-reactions', 'set-reaction-roles', '-', 'map-atoms', 'clear-mapping', '-', 'check-reaction', 'balance-reaction', '-', 'show-stoichiometry', 'stoichiometry-grid', '-', 'paste-reaction', REACTION_COPY, REACTION_EXPORT] }, From f601266200618bb9235ec446cef18a8c59ab511a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:00:49 -0500 Subject: [PATCH 126/279] fix(canvas): make every ruler corner click change the shown unit (0.5.0) Cycling through a separate follow-the-drawing step showed points twice on a points drawing; the corner now steps pt, mm, cm, in and falls back to following the drawing when it reaches the drawing's own unit. --- frontend/src/canvas/rulers.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/frontend/src/canvas/rulers.ts b/frontend/src/canvas/rulers.ts index 1a1b0e76..fe345f51 100644 --- a/frontend/src/canvas/rulers.ts +++ b/frontend/src/canvas/rulers.ts @@ -18,7 +18,7 @@ export const RULER_PX = 20; const MIN_MAJOR_PX = 56; const MIN_MINOR_PX = 5; const PT_PER: Record = { pt: 1, mm: 72 / 25.4, cm: 72 / 2.54, in: 72 }; -const UNIT_CYCLE: Array = ['doc', 'pt', 'mm', 'cm', 'in']; +const UNITS: Units[] = ['pt', 'mm', 'cm', 'in']; const HTML = ` `); panel = host; + props = mountAnalysisProperties(q(host, '.fc-ap-body')); open = readOpen(); apply(); requestAnimationFrame(() => requestAnimationFrame(() => host.classList.add('is-animated'))); @@ -64,6 +67,7 @@ export function setAnalysisOpen(on: boolean): void { open = on; saveOpen(on); apply(); + if (on) refreshSoon(); for (const l of [...listeners]) l(on); commandStateChanged(); } @@ -148,6 +152,7 @@ function combinedAnalysis(frags: DerivedFragment[], formula: string, charge: num export function refreshAnalysis(): void { const s = source; const frags = s ? pageFragments(s.doc) : []; + if (open) props?.update(s?.doc ?? null, frags); if (!s || !frags.length) { setAnalysis(null); setStatusFormula(''); From 0392fef6a903344fae4a164a68d74ccb75579716 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:15:39 -0500 Subject: [PATCH 217/279] style(ui): load the chemistry marks and chemistry UI stylesheets (0.6.0) They load with the canvas styles in the head so the marks, dialogs, popover and panels are styled at first paint. --- frontend/index.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/frontend/index.html b/frontend/index.html index 6e2e8a18..3b93a2cf 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -106,6 +106,8 @@ + + From ceaf2857c6626ea66546344c377279017ce6f422 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:16:52 -0500 Subject: [PATCH 218/279] fix(engine): read the real analysis replies for properties, stereo and checks (0.6.0) The client was written against draft shapes: properties now come from the engine's rows with their note and RDKit call as the method, Lipinski rules from key and ok, CIP labels from atoms and bonds with centre states, and a check issue's named fix is kept. --- frontend/src/engine/analysis-api.ts | 45 +++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/frontend/src/engine/analysis-api.ts b/frontend/src/engine/analysis-api.ts index af58e852..238fcee5 100644 --- a/frontend/src/engine/analysis-api.ts +++ b/frontend/src/engine/analysis-api.ts @@ -23,6 +23,7 @@ export interface CheckIssue { atoms: Id[]; bonds: Id[]; fix?: EngineTx | null; + fixCommand?: 'wedges' | 'expand'; } export interface CheckResult { issues: CheckIssue[]; counts: Record } @@ -94,15 +95,38 @@ function issueOf(v: unknown): CheckIssue | null { const text = typeof v.text === 'string' ? v.text : typeof v.message === 'string' ? v.message : ''; if (!text) return null; const sev = SEVERITIES.includes(v.severity as Severity) ? (v.severity as Severity) : v.severity === 'warn' ? 'warning' : 'info'; - return { code: typeof v.code === 'string' ? v.code : 'issue', severity: sev, text, atoms: ids(v.atoms), bonds: ids(v.bonds), fix: txOf(v.fix) }; + const out: CheckIssue = { code: typeof v.code === 'string' ? v.code : 'issue', severity: sev, text, atoms: ids(v.atoms), bonds: ids(v.bonds), fix: txOf(v.fix) }; + if (v.fix === 'wedges' || v.fix === 'expand') out.fixCommand = v.fix; + return out; } +const UNITS: Readonly> = { A2: 'ร…ยฒ', 'cm3/mol': 'cmยณ/mol' }; + +function rowsOf(rows: unknown): Rec { + const out: Rec = {}; + if (!Array.isArray(rows)) return out; + for (const row of rows) { + if (!isRec(row) || typeof row.key !== 'string') continue; + const value = typeof row.value === 'number' || typeof row.value === 'string' ? row.value : null; + const pv: PropertyValue = { value }; + const method = typeof row.method === 'string' ? row.method : ''; + const note = typeof row.note === 'string' ? row.note : ''; + if (method || note) pv.method = note && method ? `${note} (${method})` : note || method; + if (typeof row.unit === 'string' && row.unit) pv.unit = UNITS[row.unit] ?? row.unit; + if (note) pv.note = note; + out[row.key] = pv; + } + return out; +} + +const RULE_NAMES: Readonly> = { mw: 'MW', clogp: 'cLogP', hbd: 'HBD', hba: 'HBA', tpsa: 'TPSA', rotatable_bonds: 'Rotatable bonds' }; + const PROPERTY_ALIASES: Readonly> = { formula: ['formula'], mw: ['mw', 'molecular_weight'], exact_mass: ['exact_mass', 'monoisotopic_mass'], mz: ['mz'], - charge: ['charge'], + charge: ['charge', 'formal_charge'], clogp: ['clogp', 'logp', 'crippen_logp'], tpsa: ['tpsa', 'psa'], mr: ['mr', 'molar_refractivity'], @@ -132,9 +156,11 @@ export function propertiesOf(v: unknown): Properties { const r = isRec(v) ? v : {}; const methods = isRec(r.methods) ? r.methods : {}; const values: Partial> = {}; + const rows = rowsOf(r.rows); + const flat: Rec = { ...r, ...(isRec(r.values) ? r.values : {}), ...rows }; for (const [key, names] of Object.entries(PROPERTY_ALIASES) as [PropertyKey, readonly string[]][]) { for (const n of names) { - const pv = valueOf(r[n], {}); + const pv = valueOf(flat[n], {}); if (!pv) continue; const m = methods[key] ?? methods[n]; if (!pv.method && typeof m === 'string') pv.method = m; @@ -149,7 +175,11 @@ export function propertiesOf(v: unknown): Properties { const L = r.lipinski; const rules: LipinskiRule[] = []; const list = Array.isArray(L.rules) ? L.rules : []; - for (const x of list) if (isRec(x) && typeof x.rule === 'string') rules.push({ rule: x.rule, value: num(x.value), limit: num(x.limit) ?? 0, pass: x.pass !== false }); + for (const x of list) { + if (!isRec(x)) continue; + const rule = typeof x.rule === 'string' ? x.rule : typeof x.key === 'string' ? RULE_NAMES[x.key] ?? x.key : null; + if (rule) rules.push({ rule, value: num(x.value), limit: num(x.limit) ?? 0, pass: x.pass !== false && x.ok !== false }); + } const violations = num(L.violations) ?? rules.filter((x) => !x.pass).length; lipinski = { violations, rules, method: typeof L.method === 'string' ? L.method : undefined }; } @@ -159,8 +189,11 @@ export function propertiesOf(v: unknown): Properties { export function stereoOf(v: unknown): StereoInfo { const r = isRec(v) ? v : {}; const cip: Record = {}; - if (isRec(r.cip)) for (const [id, code] of Object.entries(r.cip)) if (typeof code === 'string') cip[id] = code; - return { cip, centres: ids(r.centres ?? r.centers), undefined_centres: ids(r.undefined_centres ?? r.undefined) }; + for (const src of [r.cip, r.atoms, r.bonds]) if (isRec(src)) for (const [id, code] of Object.entries(src)) if (typeof code === 'string') cip[id] = code; + const units = Array.isArray(r.centres) ? r.centres.filter(isRec) : []; + if (!units.length) return { cip, centres: ids(r.centres ?? r.centers), undefined_centres: ids(r.undefined_centres ?? r.undefined) }; + const atomOf = (u: Rec): Id[] => (typeof u.atom === 'string' ? [u.atom] : []); + return { cip, centres: units.flatMap(atomOf), undefined_centres: units.filter((u) => u.state !== 'defined').flatMap(atomOf) }; } function perFragment(res: unknown, read: (v: unknown) => T): Record { From c905a4fe03ac4f3b4167bed0ff5602bfcff3cc2d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:17:07 -0500 Subject: [PATCH 219/279] fix(app): run the engine's named fix from a structure check row (0.6.0) The engine names the repairing command (wedges or expand) instead of sending a transaction, so the Fix button never showed; it now asks that route for the issue's atoms and commits the answer as one undo step. --- frontend/src/app/chem-commands.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/frontend/src/app/chem-commands.ts b/frontend/src/app/chem-commands.ts index 17d9fce7..f2092e1d 100644 --- a/frontend/src/app/chem-commands.ts +++ b/frontend/src/app/chem-commands.ts @@ -328,11 +328,13 @@ export function checkStructure(host: ChemHost): void { const sel = selectedAtoms(host); const fids = sel.size ? [...sel.keys()] : pageFragmentIds(host); const fixes = new Map(); + const named = new Map(); const scope = sel.size ? t('The selected structures') : t('Every structure on this page'); showStructureCheck({ scopeLabel: () => scope, run: async () => { fixes.clear(); + named.clear(); const client = host.client; if (!client) return []; const rows: CheckRow[] = []; @@ -348,7 +350,8 @@ export function checkStructure(host: ChemHost): void { seen.set(base, k + 1); const key = k ? `${base}#${k}` : base; if (issue.fix?.ops.length) fixes.set(key, issue.fix); - rows.push({ key, frag: fid, severity: issue.severity, code: issue.code, text: issue.text, atoms: issue.atoms, bonds: issue.bonds, fixable: !!issue.fix?.ops.length }); + else if (issue.fixCommand) named.set(key, issue.fixCommand); + rows.push({ key, frag: fid, severity: issue.severity, code: issue.code, text: issue.text, atoms: issue.atoms, bonds: issue.bonds, fixable: fixes.has(key) || named.has(key) }); } } } catch (e) { @@ -360,9 +363,21 @@ export function checkStructure(host: ChemHost): void { select: (row) => { host.setSelection(makeSelection(row.atoms.map((a) => selectionKey(row.frag, a)), row.bonds.map((b) => selectionKey(row.frag, b)))); }, - fix: (row) => { + fix: async (row) => { + const client = host.client; const tx = fixes.get(row.key); - if (tx && host.client) host.client.commit(tx.label || t('Fix Structure'), tx.ops); + if (tx && client) { client.commit(tx.label || t('Fix Structure'), tx.ops); return; } + const cmd = named.get(row.key); + const src = client && cmd ? sourceFor(client.doc, row.frag) : null; + if (!client || !cmd || !src) return; + const atoms = row.atoms.length ? row.atoms : undefined; + try { + const res = cmd === 'wedges' ? await analysisApi.wedges(src, atoms) : await analysisApi.expand(src, atoms); + if (host.client !== client || client.doc.objects[row.frag] !== src.fragment) { toast(t('The drawing changed while the engine worked; try again.')); return; } + if (res.tx?.ops.length) client.commit(t('Fix Structure'), res.tx.ops); + } catch (e) { + toast(`${t('Fix')}: ${errText(e)}`, 'error'); + } }, }); } From 75219a96d8132e991286c67df9a7e9c41a1cb67f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:18:39 -0500 Subject: [PATCH 220/279] feat(chem): compute isotope patterns at 0.01 Da resolution with adduct m/z (0.6.0) Each element's RDKit isotope masses and abundances are raised to its count by repeated squaring and convolved, so labelled atoms, chlorine and bromine clusters and large peptides come out in milliseconds; peaks under 0.1 percent of the base peak are dropped and [M+H]+, [M+Na]+ and [M-H]- are listed. --- backend/app/services/chem/isotopes.py | 151 ++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 backend/app/services/chem/isotopes.py diff --git a/backend/app/services/chem/isotopes.py b/backend/app/services/chem/isotopes.py new file mode 100644 index 00000000..dbcfd979 --- /dev/null +++ b/backend/app/services/chem/isotopes.py @@ -0,0 +1,151 @@ +import re + +from rdkit import Chem + +from app.services.chem import ids, mass, perceive, warning + +PT = Chem.GetPeriodicTable() +PROTON = 1.007276466812 +SODIUM_ION = 22.98976928 - mass.ELECTRON_MASS +FINE = 1e-3 +KEEP = 1e-7 +THRESHOLD = 0.1 +MERGE = 0.01 +MAX_ATOMS = 20000 + +Peaks = list[tuple[float, float]] + +ADDUCTS = (("[M+H]+", PROTON, 1), ("[M+Na]+", SODIUM_ION, 1), ("[M-H]-", -PROTON, -1)) + + +def _merge(peaks: Peaks, width: float) -> Peaks: + out: Peaks = [] + for m, p in sorted(peaks): + if out and m - out[-1][0] <= width: + m0, p0 = out[-1] + total = p0 + p + out[-1] = ((m0 * p0 + m * p) / total, total) + else: + out.append((m, p)) + return out + + +def _prune(peaks: Peaks) -> Peaks: + top = max(p for _, p in peaks) + return [(m, p) for m, p in peaks if p >= top * KEEP] + + +def _convolve(a: Peaks, b: Peaks) -> Peaks: + return _prune(_merge([(ma + mb, pa * pb) for ma, pa in a for mb, pb in b], FINE)) + + +def _power(base: Peaks, n: int) -> Peaks: + out: Peaks = [(0.0, 1.0)] + while n: + if n & 1: + out = _convolve(out, base) + n >>= 1 + if n: + base = _convolve(base, base) + return out + + +def _element(z: int, iso: int) -> Peaks: + if iso: + m = PT.GetMassForIsotope(z, iso) + return [(m if m > 0 else float(iso), 1.0)] + return [(m, p) for _, m, p in mass.isotopes(z)] + + +def from_counts(counts: dict[tuple[int, int], int], charge: int = 0, threshold: float = THRESHOLD, merge: float = MERGE) -> dict: + if sum(counts.values()) > MAX_ATOMS: + raise ValueError(f"the isotope pattern is limited to {MAX_ATOMS} atoms") + dist: Peaks = [(0.0, 1.0)] + for (z, iso), n in sorted(counts.items()): + if n > 0: + dist = _convolve(dist, _power(_element(z, iso), n)) + total = sum(p for _, p in dist) + shift = charge * mass.ELECTRON_MASS + average = sum(m * p for m, p in dist) / total - shift if counts else 0.0 + merged = _merge(dist, merge) + top = max(p for _, p in merged) + z_abs = abs(charge) or 1 + peaks = [] + for m, p in merged: + rel = p / top * 100 + if rel + 1e-12 < threshold: + continue + neutral = m - shift + peaks.append({"mass": round(neutral, 4), "mz": round(neutral / z_abs, 4), "abundance": round(rel, 2), "fraction": round(p / total, 6)}) + mono = sum(n * (_element(z, iso)[0][0] if iso else PT.GetMostCommonIsotopeMass(z)) for (z, iso), n in counts.items()) - shift + adducts = [] + if charge == 0 and counts: + for name, delta, z_ion in ADDUCTS: + adducts.append({"ion": name, "charge": z_ion, "mz": round(mono + delta, 4)}) + else: + adducts.append({"ion": f"[M]{'' if z_abs == 1 else z_abs}{'+' if charge > 0 else '-'}", "charge": charge, "mz": round(mono / z_abs, 4)}) + return { + "formula": ids.hill(counts, [], charge), + "charge": charge, + "monoisotopic": round(mono, 4), + "average": round(average, 4), + "peaks": peaks, + "adducts": adducts, + "threshold": threshold, + "merge": merge, + "method": "convolution of RDKit isotope masses and abundances; peaks within 0.01 Da merged, peaks under 0.1 % of the base peak dropped", + } + + +def pattern(frag: dict, expansions: dict | None = None, threshold: float = THRESHOLD, merge: float = MERGE) -> dict: + conv = perceive.prepare(frag, expansions) + counts, labels, charge = ids.formula_counts(conv.mol) + if not counts: + raise ValueError("the structure has no atoms with an element") + out = from_counts(counts, charge, threshold, merge) + notes = [] + excluded = sorted({conv.owner[a.GetIdx()] for a in conv.mol.GetAtoms() if a.GetAtomicNum() == 0}) + if excluded or labels: + notes.append(warning("incomplete", f"{len(excluded) or len(labels)} label(s) or R-group(s) are not counted in the isotope pattern.", excluded)) + out["warnings"] = notes + return out + + +FORMULA_PART = re.compile(r"([A-Z][a-z]?)(\d*)") +HYDROGEN_ISOTOPES = {"D": 2, "T": 3} + + +def _atomic_number(symbol: str) -> int: + try: + return PT.GetAtomicNumber(symbol) + except RuntimeError: + return 0 +CHARGE_TAIL = re.compile(r"([+-])(\d*)$|(\d+)([+-])$") + + +def parse_formula(text: str) -> tuple[dict[tuple[int, int], int], int]: + body = text.strip().replace(" ", "") + charge = 0 + tail = CHARGE_TAIL.search(body) + if tail: + sign = tail.group(1) or tail.group(4) + n = int(tail.group(2) or tail.group(3) or 1) + charge = n if sign == "+" else -n + body = body[: tail.start()] + if not body: + raise ValueError("give a formula such as C13H18O2") + counts: dict[tuple[int, int], int] = {} + pos = 0 + for m in FORMULA_PART.finditer(body): + if m.start() != pos: + break + pos = m.end() + symbol = m.group(1) + iso = HYDROGEN_ISOTOPES.get(symbol, 0) + z = 1 if iso else _atomic_number(symbol) + if z <= 0: + raise ValueError(f"{symbol} is not an element") + counts[(z, iso)] = counts.get((z, iso), 0) + (int(m.group(2)) if m.group(2) else 1) + if pos != len(body): + raise ValueError(f"cannot read the formula at '{body[pos:]}'") + return counts, charge From c82cbe98e6da823af3c7aae8848cadd3ff6b7cbd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:18:39 -0500 Subject: [PATCH 221/279] feat(api): add the isotope pattern route for structures and formulas (0.6.0) POST takes a fragment or a drawing like the other analysis reads and answers per fragment; GET takes a formula so agents and scripts can ask without a drawing. --- backend/app/routers/analysis.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/analysis.py b/backend/app/routers/analysis.py index 9235c97a..e7d0f64c 100644 --- a/backend/app/routers/analysis.py +++ b/backend/app/routers/analysis.py @@ -6,7 +6,7 @@ from app.routers.chem import MAX_TEXT, _bond_length, _expansions, _fragment, _num from app.services import ops as opsmod -from app.services.chem import ENGINE, abbrev, check, convert, hydrogens, markush, props, query, search, stereo, superatom, v3000 +from app.services.chem import ENGINE, abbrev, check, convert, hydrogens, isotopes, markush, props, query, search, stereo, superatom, v3000 from app.services.store import STORE router = APIRouter() @@ -313,3 +313,30 @@ async def enumerate_markush(body: dict) -> dict: out = await run(markush.enumerate_structures, src.one, src.members, src.expansions, limit, body.get("force") is True) out["groups"] = markush.describe(src.one, src.members)["groups"] return out + + +def _threshold(value) -> float: + if value is None: + return isotopes.THRESHOLD + if not _num(value) or not 0 <= value <= 100: + raise HTTPException(422, "threshold must be a percent of the base peak from 0 to 100") + return float(value) + + +@router.get("/api/analysis/isotope-pattern") +async def isotope_pattern_of_formula(formula: str = "", threshold: float | None = None) -> dict: + if not formula.strip() or len(formula) > 2000: + raise HTTPException(422, "give a formula such as C13H18O2") + level = _threshold(threshold) + + def compute() -> dict: + counts, charge = isotopes.parse_formula(formula) + return {**isotopes.from_counts(counts, charge, level), "warnings": [], "engine": ENGINE} + return await run(compute) + + +@router.post("/api/analysis/isotope-pattern") +async def isotope_pattern(body: dict) -> dict: + src = source(body) + level = _threshold(body.get("threshold")) + return await run(_each, src, lambda f: isotopes.pattern(f, src.expansions, level)) From d1169a5630ec8835243dbf047b03af25a8d27770 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:18:57 -0500 Subject: [PATCH 222/279] feat(engine): type the analysis replies the engine sends (0.6.0) Properties, stereo reports, check issues, isotope patterns, Markush enumeration and SMARTS export now have one typed wire shape beside the document client, matching the routes as they answer. --- frontend/src/engine/client-api.ts | 58 ++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/frontend/src/engine/client-api.ts b/frontend/src/engine/client-api.ts index 9c4dfd45..84ea4dba 100644 --- a/frontend/src/engine/client-api.ts +++ b/frontend/src/engine/client-api.ts @@ -1,4 +1,4 @@ -import type { Derived, FormChemDocument, Id } from './model'; +import type { ChemWarning, Derived, FormChemDocument, Id, StereoGroup } from './model'; import type { Op, Transaction } from './ops'; export type DocEvent = @@ -28,3 +28,59 @@ export interface DocumentClient { save(path?: string): Promise; close(): Promise; } + +export interface PerFragmentReply { fragments: Record; engine: string } + +export interface PropRow { key: string; label: string; value: number | string | null; unit: string; method: string; note: string } +export interface RuleVerdict { name: string; method: string; rules: { key: string; value: number | null; limit: number; ok: boolean }[]; violations: number; pass: boolean } +export interface FragmentProps { + rows: PropRow[]; + values: Record; + lipinski: RuleVerdict; + veber: RuleVerdict; + elemental_analysis: Record; + excluded: Id[]; + engine: string; + warnings: ChemWarning[]; +} + +export interface StereoUnit { atom?: Id; bond?: Id; label: string | null; state: 'defined' | 'undefined' | 'unknown'; group?: string } +export interface StereoReport { + atoms: Record; + bonds: Record; + centres: StereoUnit[]; + double_bonds: StereoUnit[]; + axes: StereoUnit[]; + chiral: string | null; + stereo_groups: StereoGroup[]; + smiles: string; + cxsmiles: string; + warnings: ChemWarning[]; +} + +export interface CheckIssueReply { code: string; severity: 'error' | 'warning' | 'info'; text: string; atoms?: Id[]; bonds?: Id[]; fix?: 'wedges' | 'expand' } +export interface CheckReply { issues: CheckIssueReply[]; counts: { error: number; warning: number; info: number }; engine: string } + +export interface IsotopePeak { mass: number; mz: number; abundance: number; fraction: number } +export interface IsotopeAdduct { ion: string; charge: number; mz: number } +export interface IsotopePattern { + formula: string; + charge: number; + monoisotopic: number; + average: number; + peaks: IsotopePeak[]; + adducts: IsotopeAdduct[]; + threshold: number; + merge: number; + method: string; + warnings: ChemWarning[]; +} + +export interface EngineTxReply { label: string; ops: Op[] } +export interface MarkushReply { + count: number; + structures: { smiles: string; formula: string; choice: Record }[]; + truncated: boolean; + warnings: ChemWarning[]; +} +export interface SmartsReply { smarts: string; warnings: ChemWarning[]; engine: string } From 244fb5591de86f8c63369c47138fb8d9b24ac794 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:19:09 -0500 Subject: [PATCH 223/279] feat(engine): add isotope pattern, Markush enumeration and SMARTS export to the analysis client (0.6.0) The analysis panel and the new window commands reach these routes through the one module that talks to /api/analysis. --- frontend/src/engine/analysis-api.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/frontend/src/engine/analysis-api.ts b/frontend/src/engine/analysis-api.ts index 238fcee5..79278767 100644 --- a/frontend/src/engine/analysis-api.ts +++ b/frontend/src/engine/analysis-api.ts @@ -1,4 +1,5 @@ import { get, post } from '../io/api'; +import type { IsotopePattern, MarkushReply, PerFragmentReply } from './client-api'; import type { Expansion, FormChemDocument, Fragment, Id } from './model'; import type { Op } from './ops'; @@ -282,6 +283,28 @@ export const analysisApi = { return { tx: txOf(r.tx), count, kept: ids(r.kept), warnings: warningsOf(r.warnings) }; }, + async isotopePattern(src: Source, signal?: AbortSignal): Promise { + const res = await post>(`${ANALYSIS}/isotope-pattern`, src, signal); + const all = isRec(res) && isRec(res.fragments) ? res.fragments : {}; + const one = all[src.fragment.id] ?? Object.values(all)[0]; + return one && Array.isArray((one as IsotopePattern).peaks) ? (one as IsotopePattern) : null; + }, + + async markush(src: Source, limit = 1000): Promise { + const r = await post(`${ANALYSIS}/markush`, { ...src, limit }); + const structures = (Array.isArray(r.structures) ? r.structures : []).filter(isRec).filter((s) => typeof s.smiles === 'string').map((s) => ({ + smiles: s.smiles as string, + formula: typeof s.formula === 'string' ? s.formula : '', + choice: isRec(s.choice) ? (s.choice as Record) : {}, + })); + return { count: num(r.count) ?? structures.length, structures, truncated: r.truncated === true, warnings: warningsOf(r.warnings) as MarkushReply['warnings'] }; + }, + + async smarts(src: Source, atoms?: Id[]): Promise<{ smarts: string; warnings: EngineWarning[] }> { + const r = await post(`${ANALYSIS}/smarts/export`, atoms?.length ? { ...src, atoms } : src); + return { smarts: typeof r.smarts === 'string' ? r.smarts : '', warnings: warningsOf(r.warnings) }; + }, + async substructure(query: Fragment | { smarts: string }, targets: Record, opts: { maxHits?: number; chirality?: boolean } = {}, signal?: AbortSignal): Promise { const body: Rec = 'smarts' in query ? { smarts: query.smarts, fragments: targets } : { query, fragments: targets }; if (opts.maxHits) body.max_hits = opts.maxHits; From 4b5d386deae1360869c1825e177ebd86e8c4f5cd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:20:37 -0500 Subject: [PATCH 224/279] feat(app): include the isotope pattern and adduct m/z in Copy Analysis (0.6.0) The copied text now carries the same peaks and [M+H]+, [M+Na]+ and [M-H]- values the panel shows, with the method when methods are asked for. --- frontend/src/app/analysis-text.ts | 12 +++++++++++- frontend/src/app/chem-commands.ts | 7 ++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/frontend/src/app/analysis-text.ts b/frontend/src/app/analysis-text.ts index 7bfaaf4b..b1068e9e 100644 --- a/frontend/src/app/analysis-text.ts +++ b/frontend/src/app/analysis-text.ts @@ -1,4 +1,5 @@ import type { LipinskiRule, Properties, PropertyKey } from '../engine/analysis-api'; +import type { IsotopePattern } from '../engine/client-api'; import { t } from '../i18n'; export type RowKey = PropertyKey | 'elemental' | 'lipinski'; @@ -69,7 +70,15 @@ export function rowMethod(def: PropertyRowDef, p: Properties | null): string { return p?.values[def.key]?.method ?? def.method; } -export interface AnalysisTextOptions { title?: string; methods?: boolean; smiles?: string } +export function isotopeLines(p: IsotopePattern | null | undefined, methods = false): string[] { + if (!p?.peaks.length) return []; + const peaks = p.peaks.map((k) => `${k.mz.toFixed(4)} (${k.abundance.toFixed(1)}%)`).join(', '); + const lines = [methods ? `${t('Isotope pattern')}: ${peaks} [${p.method}]` : `${t('Isotope pattern')}: ${peaks}`]; + for (const a of p.adducts) lines.push(`${a.ion}: ${a.mz.toFixed(4)}`); + return lines; +} + +export interface AnalysisTextOptions { title?: string; methods?: boolean; smiles?: string; isotopes?: IsotopePattern | null } export function formatAnalysisText(p: Properties, opts: AnalysisTextOptions = {}): string { const lines: string[] = []; @@ -80,6 +89,7 @@ export function formatAnalysisText(p: Properties, opts: AnalysisTextOptions = {} if (!v) continue; lines.push(opts.methods ? `${t(def.label)}: ${v} [${rowMethod(def, p)}]` : `${t(def.label)}: ${v}`); } + lines.push(...isotopeLines(opts.isotopes, opts.methods)); for (const w of p.warnings) lines.push(`${t('Note')}: ${w.text}`); return lines.join('\n'); } diff --git a/frontend/src/app/chem-commands.ts b/frontend/src/app/chem-commands.ts index f2092e1d..2226d94f 100644 --- a/frontend/src/app/chem-commands.ts +++ b/frontend/src/app/chem-commands.ts @@ -402,13 +402,14 @@ export async function copyAnalysis(host: ChemHost, props?: Properties | null): P const sel = selectedAtoms(host); const fids = sel.size ? [...sel.keys()] : pageFragmentIds(host); let p = props ?? null; + const src = mergedSource(client.doc, fids); + if (!src) { toast(t('There is no structure to analyse.')); return; } + const isotopes = analysisApi.isotopePattern(src).catch(() => null); if (!p) { - const src = mergedSource(client.doc, fids); - if (!src) { toast(t('There is no structure to analyse.')); return; } try { p = await analysisApi.properties(src); } catch (e) { toast(`${t('Copy Analysis')}: ${errText(e)}`, 'error'); return; } } const smiles = fids.length === 1 ? client.derived?.fragments[fids[0]]?.smiles : undefined; - const ok = await copyText(formatAnalysisText(p, { title: client.doc.title, smiles, methods: true })); + const ok = await copyText(formatAnalysisText(p, { title: client.doc.title, smiles, methods: true, isotopes: await isotopes })); toast(ok ? t('Analysis copied') : t('Could not copy to the clipboard'), ok ? 'info' : 'error'); } From 0f40ba7bbe52f18c466a24c7e58c3830c6009e0b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:20:38 -0500 Subject: [PATCH 225/279] feat(ui): draw the isotope pattern as a keyed stick plot in the properties section (0.6.0) Sticks are keyed by their offset from the monoisotopic peak and patched in place, the plot and the three adduct rows have a reserved height, and old values stay dimmed while new ones load, so the panel never jumps or flashes. --- frontend/src/styles/chem-ui.css | 18 +++++ frontend/src/ui/analysis-properties.ts | 14 +++- frontend/src/ui/isotope-plot.ts | 106 +++++++++++++++++++++++++ 3 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 frontend/src/ui/isotope-plot.ts diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index a0f6e1c9..c14f6044 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -107,3 +107,21 @@ .fc-apx.is-shown .fc-apx-val { opacity: 0.5; } .fc-apx-note { margin-top: 4px; } .fc-apx-note[hidden] { display: none; } + +.fc-iso { display: grid; gap: 4px; padding-top: var(--space-2); } +.fc-iso-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); min-height: 22px; } +.fc-iso-title { color: var(--text-secondary); font-size: var(--fc-12); } +.fc-iso-mono { color: var(--text-muted); font: var(--fc-11)/1.3 var(--font-mono); font-variant-numeric: tabular-nums; } +.fc-iso-frame { height: 92px; border-radius: var(--radius-sm, 4px); background: var(--accent-tint); } +.fc-iso-plot { display: block; width: 100%; height: 92px; overflow: visible; } +.fc-iso-axis { stroke: var(--line-1); stroke-width: 1; vector-effect: non-scaling-stroke; } +.fc-iso-stick line { stroke: var(--text-secondary); stroke-width: 2; stroke-linecap: butt; vector-effect: non-scaling-stroke; transition: opacity var(--transition-fast); } +.fc-iso-stick.is-base line { stroke: var(--accent-color); } +.fc-iso-stick text { fill: var(--text-muted); font: 9px var(--font-mono); } +.fc-iso.is-empty .fc-iso-frame { opacity: 0.5; } +.fc-iso-ions { display: grid; margin: 0; } +.fc-iso-ion { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; column-gap: var(--space-3); min-height: 24px; padding: 3px 0; } +.fc-iso-ion dt { color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-mono); } +.fc-iso-ion dd { min-width: 10ch; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; user-select: text; -webkit-user-select: text; } +.fc-iso-ion.is-empty dd { color: var(--text-muted); } +.fc-apx.is-shown .fc-iso-plot, .fc-apx.is-shown .fc-iso-ion dd { opacity: 0.5; } diff --git a/frontend/src/ui/analysis-properties.ts b/frontend/src/ui/analysis-properties.ts index 6af27fa6..9d8d914a 100644 --- a/frontend/src/ui/analysis-properties.ts +++ b/frontend/src/ui/analysis-properties.ts @@ -1,9 +1,11 @@ import { formatAnalysisText, lipinskiRules, PROPERTY_ROWS, rowMethod, rowValue, type PropertyRowDef } from '../app/analysis-text'; import { analysisApi, type Properties, type Source } from '../engine/analysis-api'; +import type { IsotopePattern } from '../engine/client-api'; import type { FormChemDocument, Fragment } from '../engine/model'; import { t } from '../i18n'; import { copyButtonHtml, copyText, flashCopied } from './dialogs'; import { el, pendingClass, q, setClass, setDisabled, setHidden, setStyleVar, setText, setTitle } from './dom'; +import { mountIsotopePlot } from './isotope-plot'; import { toast } from './toast'; const DASH = 'โ€“'; @@ -45,9 +47,12 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { setStyleVar(dd, '--fc-apx-w', `${def.width}ch`); cells.set(def.key, { row, dt, dd, def }); } + const iso = mountIsotopePlot(root); + root.insertBefore(iso.root, note); host.appendChild(root); let props: Properties | null = null; + let pattern: IsotopePattern | null = null; let inputs: unknown[] = []; let timer = 0; let ctrl: AbortController | null = null; @@ -68,6 +73,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { setClass(row, 'is-fail', !!l && l.violations > 0); } } + iso.update(pattern); setDisabled(copyBtn, !props); const warn = [...new Set(props?.warnings.map((w) => w.text) ?? [])].join(' '); setText(note, warn); @@ -88,9 +94,10 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { const mine = ++ticket; pending ??= pendingClass(root, 200, 250); root.setAttribute('aria-busy', 'true'); - analysisApi.properties(src, c.signal).then((p) => { + Promise.all([analysisApi.properties(src, c.signal), analysisApi.isotopePattern(src, c.signal).catch(() => null)]).then(([p, ip]) => { if (mine !== ticket) return; props = p; + pattern = ip; paint(); settle(); }, (e: unknown) => { @@ -105,7 +112,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { paint(); copyBtn.addEventListener('click', () => { if (!props) return; - void copyText(formatAnalysisText(props, { methods: false })).then((ok) => flashCopied(copyBtn, ok, () => toast(t('Could not copy to the clipboard'), 'error'))); + void copyText(formatAnalysisText(props, { methods: false, isotopes: pattern })).then((ok) => flashCopied(copyBtn, ok, () => toast(t('Could not copy to the clipboard'), 'error'))); }); return { @@ -121,6 +128,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { ctrl?.abort(); settle(); props = null; + pattern = null; paint(); return; } @@ -128,7 +136,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { timer = window.setTimeout(() => fetchNow(src), DEBOUNCE_MS); }, current: () => props, - copyText: (methods = false) => (props ? formatAnalysisText(props, { methods }) : ''), + copyText: (methods = false) => (props ? formatAnalysisText(props, { methods, isotopes: pattern }) : ''), destroy() { window.clearTimeout(timer); ctrl?.abort(); diff --git a/frontend/src/ui/isotope-plot.ts b/frontend/src/ui/isotope-plot.ts new file mode 100644 index 00000000..504864f8 --- /dev/null +++ b/frontend/src/ui/isotope-plot.ts @@ -0,0 +1,106 @@ +import type { IsotopePattern } from '../engine/client-api'; +import { t } from '../i18n'; +import { el, q, setAttr, setClass, setText } from './dom'; + +const NS = 'http://www.w3.org/2000/svg'; +const W = 240, H = 92, TOP = 6, BASE = 70, LEFT = 6, RIGHT = 234; +const DASH = 'โ€“'; +const IONS = ['[M+H]+', '[M+Na]+', '[M-H]-'] as const; + +interface Stick { g: SVGGElement; line: SVGLineElement; label: SVGTextElement; tip: SVGTitleElement } + +export interface IsotopePlot { + readonly root: HTMLElement; + update(p: IsotopePattern | null): void; +} + +function svg(tag: K, attrs: Record): SVGElementTagNameMap[K] { + const n = document.createElementNS(NS, tag); + for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v); + return n; +} + +const fx = (n: number): string => (Math.round(n * 100) / 100).toString(); + +export function mountIsotopePlot(host: HTMLElement): IsotopePlot { + const root = el(`
+
+
+
${IONS.map((i) => `
${DASH}
`).join('')}
+
`); + setText(q(root, '.fc-iso-title'), t('Isotope pattern')); + const plot = svg('svg', { class: 'fc-iso-plot', viewBox: `0 0 ${W} ${H}`, role: 'img' }); + setAttr(plot, 'aria-label', t('Isotope pattern')); + plot.appendChild(svg('line', { class: 'fc-iso-axis', x1: String(LEFT), x2: String(RIGHT), y1: String(BASE), y2: String(BASE) })); + const sticks = svg('g', { class: 'fc-iso-sticks' }); + plot.appendChild(sticks); + q(root, '.fc-iso-frame').appendChild(plot); + const ionRows = IONS.map((_, i) => q(root, `.fc-iso-ion:nth-child(${i + 1})`)); + host.appendChild(root); + + const live = new Map(); + + const stick = (key: string): Stick => { + let s = live.get(key); + if (s) return s; + const g = svg('g', { class: 'fc-iso-stick', 'data-key': key }); + const line = svg('line', { y2: String(BASE) }); + const label = svg('text', { y: String(BASE + 13), 'text-anchor': 'middle' }); + const tip = svg('title', {}); + g.append(tip, line, label); + sticks.appendChild(g); + s = { g, line, label, tip }; + live.set(key, s); + return s; + }; + + const set = (n: Element, name: string, value: string): void => { if (n.getAttribute(name) !== value) n.setAttribute(name, value); }; + + return { + root, + update(p) { + const peaks = p?.peaks ?? []; + setClass(root, 'is-empty', !peaks.length); + setText(q(root, '.fc-iso-mono'), p ? `${t('Monoisotopic')} ${p.monoisotopic.toFixed(4)}` : ''); + const keep = new Set(); + if (peaks.length) { + const lo = Math.min(...peaks.map((k) => k.mz)), hi = Math.max(...peaks.map((k) => k.mz)); + const span = Math.max(hi - lo, 4 / Math.max(1, Math.abs(p?.charge ?? 0) || 1)); + const mid = (lo + hi) / 2; + const x0 = mid - span * 0.55, x1 = mid + span * 0.55; + const xOf = (m: number): number => LEFT + ((m - x0) / (x1 - x0)) * (RIGHT - LEFT); + let lastLabel = -Infinity; + const mono = peaks[0].mz; + for (const k of peaks) { + const base = `M+${Math.round((k.mz - mono) * Math.max(1, Math.abs(p?.charge ?? 0)))}`; + let key = base; + for (let n = 1; keep.has(key); n++) key = `${base}.${n}`; + keep.add(key); + const s = stick(key); + const x = fx(xOf(k.mz)); + set(s.line, 'x1', x); + set(s.line, 'x2', x); + set(s.line, 'y1', fx(BASE - (k.abundance / 100) * (BASE - TOP))); + set(s.label, 'x', x); + const labelled = k.abundance >= 5 && xOf(k.mz) - lastLabel >= 40; + if (labelled) lastLabel = xOf(k.mz); + setText(s.label, labelled ? k.mz.toFixed(2) : ''); + setText(s.tip, `m/z ${k.mz.toFixed(4)} ${k.abundance.toFixed(2)}%`); + setClass(s.g, 'is-base', k.abundance >= 99.995); + } + } + for (const [key, s] of live) { + if (keep.has(key)) continue; + s.g.remove(); + live.delete(key); + } + const adducts = p?.adducts ?? []; + ionRows.forEach((row, i) => { + const a = adducts[i]; + setText(q(row, 'dt'), a ? a.ion : adducts.length ? '' : IONS[i]); + setText(q(row, 'dd'), a ? a.mz.toFixed(4) : adducts.length ? '' : DASH); + setClass(row, 'is-empty', !a); + }); + }, + }; +} From 439254b819ec772ad231b38b9ab6bce597d1f7cc Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:22:01 -0500 Subject: [PATCH 226/279] feat(ui): add the R-group enumeration results dialog (0.6.0) A keyed list of the enumerated structures with formula and SMILES in a list of fixed height, built once and patched per run, with Copy SMILES. --- frontend/src/styles/chem-ui.css | 9 ++++++ frontend/src/ui/markush-dialog.ts | 53 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 frontend/src/ui/markush-dialog.ts diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index c14f6044..1289717d 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -125,3 +125,12 @@ .fc-iso-ion dd { min-width: 10ch; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; user-select: text; -webkit-user-select: text; } .fc-iso-ion.is-empty dd { color: var(--text-muted); } .fc-apx.is-shown .fc-iso-plot, .fc-apx.is-shown .fc-iso-ion dd { opacity: 0.5; } + +.fc-markush { display: grid; gap: var(--space-2); } +.fc-markush-sum { margin: 0; color: var(--text-secondary); font-size: var(--fc-12); } +.fc-markush-list { display: grid; align-content: start; height: 280px; overflow-y: auto; padding: 4px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); } +.fc-markush-row { display: grid; grid-template-columns: 4ch 12ch minmax(0, 1fr); column-gap: var(--space-3); align-items: baseline; min-height: 24px; padding: 2px 4px; font: var(--fc-12)/1.4 var(--font-mono); } +.fc-markush-n { color: var(--text-muted); text-align: right; } +.fc-markush-formula { color: var(--text-secondary); } +.fc-markush-smiles { overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; } +.fc-markush-note[hidden] { display: none; } diff --git a/frontend/src/ui/markush-dialog.ts b/frontend/src/ui/markush-dialog.ts new file mode 100644 index 00000000..0aba20d2 --- /dev/null +++ b/frontend/src/ui/markush-dialog.ts @@ -0,0 +1,53 @@ +import type { MarkushReply } from '../engine/client-api'; +import { t } from '../i18n'; +import { copyText, Dialog } from './dialogs'; +import { el, patchList, q, setHidden, setText } from './dom'; +import { toast } from './toast'; + +type Row = { n: number; smiles: string; formula: string }; + +let dlg: Dialog | null = null; +let shown: MarkushReply | null = null; + +function build(): Dialog { + const d = new Dialog(t('Enumerate R-Groups'), 560); + d.body.appendChild(el(`
+

+
+ +
`)); + d.button(t('Copy SMILES'), '', () => { + if (!shown?.structures.length) return; + void copyText(shown.structures.map((s) => s.smiles).join('\n')).then((ok) => toast(ok ? t('Copied the SMILES of every structure') : t('Could not copy to the clipboard'), ok ? 'info' : 'error')); + }); + d.button(t('Close'), 'primary', () => d.close()); + return d; +} + +export function showMarkushResults(reply: MarkushReply): void { + const d = (dlg ??= build()); + shown = reply; + const n = reply.structures.length; + const sum = `${reply.count} ${reply.count === 1 ? t('structure') : t('structures')}${reply.truncated || n < reply.count ? ` (${t('showing')} ${n})` : ''}`; + setText(q(d.body, '.fc-markush-sum'), sum); + const rows: Row[] = reply.structures.map((s, i) => ({ n: i + 1, smiles: s.smiles, formula: s.formula })); + patchList(q(d.body, '.fc-markush-list'), rows, { + key: (r) => r.smiles, + create: (r) => { + const node = el('
'); + setText(q(node, '.fc-markush-n'), String(r.n)); + setText(q(node, '.fc-markush-formula'), r.formula); + setText(q(node, '.fc-markush-smiles'), r.smiles); + return node; + }, + update: (node, r) => { + setText(q(node, '.fc-markush-n'), String(r.n)); + setText(q(node, '.fc-markush-formula'), r.formula); + }, + }); + const note = q(d.body, '.fc-markush-note'); + const warn = [...new Set(reply.warnings.map((w) => w.text))].join(' '); + setText(note, warn); + setHidden(note, !warn); + d.open(); +} From deda456710f517e1dedeb8a289b5c0fbdc15bf39 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:22:01 -0500 Subject: [PATCH 227/279] feat(app): add Enumerate R-Groups, Copy as SMARTS and Export SMARTS (0.6.0) The engine's Markush and SMARTS routes had no window command; they now sit in the Query submenu, with Copy as SMARTS also under Edit. The desktop shell has no file writer yet, so Export SMARTS copies there and says so. --- frontend/src/app/chem-commands.ts | 84 +++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 3 deletions(-) diff --git a/frontend/src/app/chem-commands.ts b/frontend/src/app/chem-commands.ts index 2226d94f..e86d65fd 100644 --- a/frontend/src/app/chem-commands.ts +++ b/frontend/src/app/chem-commands.ts @@ -15,6 +15,8 @@ import { askAbbreviation } from '../ui/abbreviation-dialog'; import { setAnalysisOpen, refreshAnalysis } from '../ui/analysis-panel'; import { askAtomList } from '../ui/atom-list-dialog'; import { copyText, promptName } from '../ui/dialogs'; +import { inTauri } from '../ui/dom'; +import { showMarkushResults } from '../ui/markush-dialog'; import type { MenuItem } from '../ui/menu'; import { pref, setPref } from '../ui/prefs/store'; import { atomQuerySubmenu, BOND_QUERY_LABELS, queryBondSubmenu, stereoGroupSubmenu, type AtomTarget, type TempCommand } from '../ui/query-menus'; @@ -52,7 +54,7 @@ export const CHEM_COMMAND_IDS: readonly string[] = [ 'add-hydrogens', 'remove-hydrogens', 'expand-abbreviation', 'contract-abbreviation', 'show-stereo', 'show-stereo-groups', 'show-query-marks', 'set-stereo-group', 'set-stereo-group-abs', 'set-stereo-group-and', 'set-stereo-group-or', 'clear-stereo-group', 'stereo-group-popover', 'set-atom-list', 'set-query-bond', ...BOND_QUERY_LABELS.map(([q]) => `set-query-bond-${q}`), 'clear-query-bond', 'define-rgroup', - 'assign-wedges', 'check-structure', 'compute-properties', 'copy-analysis', 'search-substructure', + 'assign-wedges', 'check-structure', 'compute-properties', 'copy-analysis', 'search-substructure', 'enumerate-markush', 'copy-smarts', 'export-smarts', ]; const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); @@ -456,6 +458,79 @@ export async function searchSubstructure(host: ChemHost): Promise { } } +function markushScaffold(host: ChemHost): Id | null { + const doc = host.client?.doc; + if (!doc) return null; + const hasSites = (fid: Id): boolean => { + const f = doc.objects[fid]; + return f?.kind === 'fragment' && (!!f.rgroups || Object.values(f.atoms).some((a) => a.element === 'R#')); + }; + return [...selectedAtoms(host).keys()].find(hasSites) ?? pageFragmentIds(host).find(hasSites) ?? null; +} + +export async function enumerateMarkush(host: ChemHost): Promise { + const client = host.client; + const fid = markushScaffold(host); + const src = client && fid ? sourceFor(client.doc, fid) : null; + if (!src) { toast(t('Draw a structure with R-group atoms and define its R-groups first.')); return; } + try { + showMarkushResults(await analysisApi.markush(src, 1000)); + } catch (e) { + toast(`${t('Enumerate R-Groups')}: ${errText(e)}`, 'error'); + } +} + +async function smartsOf(host: ChemHost): Promise<{ text: string; warnings: EngineWarning[] } | null> { + const client = host.client; + if (!client) return null; + const sel = selectedAtoms(host); + const scope: Targets = sel.size ? new Map([...sel].map(([fid, atoms]) => [fid, isWhole(host, fid, atoms) ? null : atoms])) : new Map(pageFragmentIds(host).map((fid) => [fid, null])); + const parts: string[] = []; + const warnings: EngineWarning[] = []; + for (const [fid, atoms] of scope) { + const src = sourceFor(client.doc, fid); + if (!src) continue; + const r = await analysisApi.smarts(src, atoms ?? undefined); + if (r.smarts) parts.push(r.smarts); + warnings.push(...r.warnings); + } + return parts.length ? { text: parts.join('.'), warnings } : null; +} + +export async function copySmarts(host: ChemHost): Promise { + try { + const out = await smartsOf(host); + if (!out) { toast(t('There is no structure to write as SMARTS.')); return; } + const ok = await copyText(out.text); + const note = out.warnings[0]?.text; + toast(ok ? `${t('Copied the SMARTS')}${note ? ` (${note})` : ''}` : t('Could not copy to the clipboard'), ok ? 'info' : 'error'); + } catch (e) { + toast(`${t('Copy as SMARTS')}: ${errText(e)}`, 'error'); + } +} + +export async function exportSmarts(host: ChemHost): Promise { + try { + const out = await smartsOf(host); + if (!out) { toast(t('There is no structure to write as SMARTS.')); return; } + if (inTauri()) { + const ok = await copyText(out.text); + toast(ok ? t('Saving SMARTS files arrives with the file formats in 0.7.0; the SMARTS was copied instead.') : t('Could not copy to the clipboard'), ok ? 'info' : 'error'); + return; + } + const name =`${(host.client?.doc.title || 'query').replace(/[\\/:*?"<>|]+/g, ' ').trim() || 'query'}.sma`; + const url = URL.createObjectURL(new Blob([`${out.text}\n`], { type: 'text/plain' })); + const a = document.createElement('a'); + a.href = url; + a.download = name; + a.click(); + window.setTimeout(() => URL.revokeObjectURL(url), 1000); + toast(`${t('Exported the SMARTS to')} ${name}`); + } catch (e) { + toast(`${t('Export SMARTS')}: ${errText(e)}`, 'error'); + } +} + export function chemContextItems(host: ChemHost, hit: Hit, temp: TempCommand[]): MenuItem[] { const commit = (label: string, ops: Op[]): void => { if (ops.length) host.client?.commit(label, ops); }; if (hit.kind === 'atom') { @@ -521,13 +596,16 @@ export function registerChemCommands(deps: ChemCommandDeps): () => void { { id: 'compute-properties', label: () => t('Compute Properties'), group: 'Analysis', icon: 'flask', description: 'Opens the analysis panel with the calculated properties of the selection or the page.', when: NEED_DRAWING, enabled: open, run: () => computeProperties() }, { id: 'copy-analysis', label: () => t('Copy Analysis'), group: 'Analysis', icon: 'copy', description: 'Copies formula, masses, elemental analysis and the calculated properties with their methods as text.', when: NEED_DRAWING, enabled: open, run: () => copyAnalysis(host) }, { id: 'search-substructure', label: () => t('Find Substructure...'), group: 'Edit', icon: 'substructure', description: 'Selects every match of the selected atoms (or of a SMARTS pattern) in the other structures on the page.', when: NEED_DRAWING, enabled: open, run: () => searchSubstructure(host) }, + { id: 'enumerate-markush', label: () => t('Enumerate R-Groups...'), group: 'Structure', icon: 'rgroup', description: 'Lists every structure the selected Markush scaffold (or the first one on the page) stands for, with formula and SMILES, up to 1000; the list can be copied.', when: NEED_DRAWING, enabled: open, run: () => enumerateMarkush(host) }, + { id: 'copy-smarts', label: () => t('Copy as SMARTS'), group: 'Edit', icon: 'copy', description: 'Copies the selected atoms (or every structure on the page) as SMARTS, with atom lists, generic atoms, query bonds and the other query features.', when: NEED_DRAWING, enabled: open, run: () => copySmarts(host) }, + { id: 'export-smarts', label: () => t('Export SMARTS...'), group: 'File', icon: 'download', description: 'Saves the selected atoms (or every structure on the page) as a SMARTS file (.sma).', when: NEED_DRAWING, enabled: open, run: () => exportSmarts(host) }, ]; return commands.register(...defs); } export const CHEM_MENU_ITEMS = { - structure: ['expand-abbreviation', 'contract-abbreviation', '-', 'add-hydrogens', 'remove-hydrogens', '-', 'assign-wedges', { label: 'Enhanced Stereo', items: ['set-stereo-group-abs', 'set-stereo-group-and', 'set-stereo-group-or', '-', 'clear-stereo-group', '-', 'stereo-group-popover'] }, { label: 'Query', items: ['set-atom-list', '-', ...BOND_QUERY_LABELS.map(([q]) => `set-query-bond-${q}`), 'clear-query-bond', '-', 'define-rgroup'] }] as MenuItem[], + structure: ['expand-abbreviation', 'contract-abbreviation', '-', 'add-hydrogens', 'remove-hydrogens', '-', 'assign-wedges', { label: 'Enhanced Stereo', items: ['set-stereo-group-abs', 'set-stereo-group-and', 'set-stereo-group-or', '-', 'clear-stereo-group', '-', 'stereo-group-popover'] }, { label: 'Query', items: ['set-atom-list', '-', ...BOND_QUERY_LABELS.map(([q]) => `set-query-bond-${q}`), 'clear-query-bond', '-', 'define-rgroup', 'enumerate-markush', '-', 'copy-smarts', 'export-smarts'] }] as MenuItem[], view: ['show-stereo', 'show-stereo-groups', 'show-query-marks'] as MenuItem[], analysis: ['compute-properties', '-', 'copy-analysis'] as MenuItem[], - edit: ['search-substructure'] as MenuItem[], + edit: ['search-substructure', 'copy-smarts'] as MenuItem[], }; From 26aad791dcda5b1fc0453d8f180603bbca6ffb5d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:23:29 -0500 Subject: [PATCH 228/279] feat(chem): build the ops that set reaction roles in a step (0.6.0) Moving an object between reactants, products, agents and conditions rewrites only the lists that change, marks the step explicit so perception keeps the roles, and drops coefficients and stoichiometry entries that no longer fit the new role. --- frontend/src/chem/reaction-roles.ts | 58 +++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 frontend/src/chem/reaction-roles.ts diff --git a/frontend/src/chem/reaction-roles.ts b/frontend/src/chem/reaction-roles.ts new file mode 100644 index 00000000..6b08e6be --- /dev/null +++ b/frontend/src/chem/reaction-roles.ts @@ -0,0 +1,58 @@ +import type { FormChemDocument, Id, ReactionStep } from '../engine/model'; +import type { Op } from '../engine/ops'; +import { stepPath } from './stoich-ops'; +import { findStep, type StepRef } from './stoich'; + +export type ReactionRole = 'reactant' | 'product' | 'agent' | 'condition' | 'none'; + +export const REACTION_ROLES: readonly ReactionRole[] = ['reactant', 'product', 'agent', 'condition', 'none']; + +type RoleList = 'reactants' | 'products' | 'agents' | 'conditions'; + +const LISTS: Readonly, RoleList>> = { reactant: 'reactants', product: 'products', agent: 'agents', condition: 'conditions' }; + +const ROLE_KINDS = new Set(['fragment', 'text', 'caption', 'group', 'image', 'shape', 'table']); + +export function canTakeRole(doc: FormChemDocument, step: ReactionStep, id: Id): boolean { + const o = doc.objects[id]; + return !!o && id !== step.arrow && ROLE_KINDS.has(o.kind); +} + +export function roleOf(step: ReactionStep, id: Id): ReactionRole { + for (const [role, list] of Object.entries(LISTS) as [Exclude, RoleList][]) if ((step[list] ?? []).includes(id)) return role; + return 'none'; +} + +const same = (a: readonly Id[], b: readonly Id[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); + +export function reactionRoleOps(doc: FormChemDocument, ref: StepRef, changes: ReadonlyMap): Op[] { + const step = findStep(doc, ref); + if (!step) return []; + const base = stepPath(ref); + const ops: Op[] = []; + const next: Record = { reactants: [...step.reactants], products: [...step.products], agents: [...step.agents], conditions: [...(step.conditions ?? [])] }; + let changed = false; + for (const [id, role] of changes) { + if (!canTakeRole(doc, step, id) || roleOf(step, id) === role) continue; + changed = true; + for (const list of Object.values(LISTS)) next[list] = next[list].filter((x) => x !== id); + if (role !== 'none') next[LISTS[role]].push(id); + } + if (!changed) return []; + for (const list of Object.values(LISTS)) { + const was = list === 'conditions' ? step.conditions : step[list]; + if (was === undefined && !next[list].length) continue; + if (!was || !same(was, next[list])) ops.push({ op: 'set', path: [...base, list], value: next[list] }); + } + if (!step.explicit) ops.push({ op: 'set', path: [...base, 'explicit'], value: true }); + const stoich = new Set([...next.reactants, ...next.agents, ...next.products]); + const reactants = new Set(next.reactants); + for (const id of Object.keys(step.coefficients ?? {})) if (!reactants.has(id) && !next.products.includes(id)) ops.push({ op: 'set', path: [...base, 'coefficients', id] }); + const data = step.stoich; + if (data) { + for (const id of Object.keys(data.components ?? {})) if (!stoich.has(id)) ops.push({ op: 'set', path: [...base, 'stoich', 'components', id] }); + if (data.limiting && !reactants.has(data.limiting)) ops.push({ op: 'set', path: [...base, 'stoich', 'limiting'] }); + if (data.product && !next.products.includes(data.product)) ops.push({ op: 'set', path: [...base, 'stoich', 'product'] }); + } + return ops; +} From 163acd4c4593fdaffa2f285272c991b2474a19bb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:23:29 -0500 Subject: [PATCH 229/279] feat(ui): add the reaction roles dialog (0.6.0) One keyed row per member of the step and per selected object, each with a role select; the dialog is built once and its rows are patched when it opens. --- frontend/src/styles/chem-ui.css | 8 ++++ frontend/src/ui/roles-dialog.ts | 69 +++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 frontend/src/ui/roles-dialog.ts diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index 1289717d..2e6aca6a 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -134,3 +134,11 @@ .fc-markush-formula { color: var(--text-secondary); } .fc-markush-smiles { overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; } .fc-markush-note[hidden] { display: none; } + +.fc-roles { display: grid; gap: var(--space-2); } +.fc-roles-step { margin: 0; } +.fc-roles-list { display: grid; align-content: start; gap: 2px; max-height: 320px; overflow-y: auto; } +.fc-roles-row { display: grid; grid-template-columns: minmax(0, 1fr) auto 140px; align-items: center; column-gap: var(--space-3); min-height: 36px; padding: 2px 6px; border-radius: var(--radius-md); } +.fc-roles-row.is-selected { background: var(--accent-tint); } +.fc-roles-name { overflow: hidden; color: var(--text-primary); font-size: var(--fc-13); text-overflow: ellipsis; white-space: nowrap; } +.fc-roles-detail { color: var(--text-muted); font: var(--fc-12)/1.3 var(--font-mono); } diff --git a/frontend/src/ui/roles-dialog.ts b/frontend/src/ui/roles-dialog.ts new file mode 100644 index 00000000..deb8d4c9 --- /dev/null +++ b/frontend/src/ui/roles-dialog.ts @@ -0,0 +1,69 @@ +import { REACTION_ROLES, type ReactionRole } from '../chem/reaction-roles'; +import type { Id } from '../engine/model'; +import { t } from '../i18n'; +import { Dialog } from './dialogs'; +import { el, escapeHtml, patchList, q, setClass, setText } from './dom'; + +export interface RoleRow { id: Id; label: string; detail: string; role: ReactionRole; selected: boolean } + +const ROLE_LABEL: Readonly> = { reactant: 'Reactant', product: 'Product', agent: 'Agent', condition: 'Condition', none: 'None' }; + +let dlg: Dialog | null = null; +let pick: ((v: Map | null) => void) | null = null; +let rows: RoleRow[] = []; + +function finish(v: Map | null): void { + const done = pick; + pick = null; + done?.(v); +} + +function build(): Dialog { + const d = new Dialog(t('Set Reaction Roles'), 480); + d.body.appendChild(el(`
+

+
+
`)); + d.button(t('Cancel'), 'ghost', () => d.close()); + d.button(t('Apply'), 'primary', () => { + const out = new Map(); + for (const row of rows) { + const sel = d.body.querySelector(`.fc-roles-row[data-key="${CSS.escape(row.id)}"] select`); + const v = sel?.value as ReactionRole | undefined; + if (v && v !== row.role) out.set(row.id, v); + } + finish(out); + d.close(); + }); + d.onClose = () => finish(null); + return d; +} + +const options = (): string => REACTION_ROLES.map((r) => ``).join(''); + +export function askReactionRoles(stepLabel: string, list: RoleRow[]): Promise | null> { + const d = (dlg ??= build()); + finish(null); + rows = list; + setText(q(d.body, '.fc-roles-step'), stepLabel); + patchList(q(d.body, '.fc-roles-list'), list, { + key: (r) => r.id, + create: () => { + const node = el(``); + return node; + }, + update: () => undefined, + }); + for (const r of list) { + const node = q(d.body, `.fc-roles-row[data-key="${CSS.escape(r.id)}"]`); + setText(q(node, '.fc-roles-name'), r.label); + setText(q(node, '.fc-roles-detail'), r.detail); + setClass(node, 'is-selected', r.selected); + q(node, 'select').value = r.role; + } + return new Promise((resolve) => { + pick = resolve; + const first = list.find((r) => r.selected) ?? list[0]; + d.open(first ? d.body.querySelector(`.fc-roles-row[data-key="${CSS.escape(first.id)}"] select`) : null); + }); +} From a199b6be3ad89ff95a55b0c63de4210d6f806c4e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:23:30 -0500 Subject: [PATCH 230/279] feat(app): set reaction roles by hand (0.6.0) Set Reaction Roles opens the roles dialog for the selected step (perceiving one first when the page has none) and commits the changes as one undo step; with role and objects it acts at once for agents. The 0.6.0 placeholder is gone. --- frontend/src/app/commands-shell.ts | 2 -- frontend/src/app/reaction-commands.ts | 41 ++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index affc8320..e7e8477c 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -119,7 +119,6 @@ const LATER: Record = { '0.3.0': 'Arrives in 0.3.0 with documents', '0.4.0': 'Arrives in 0.4.0 with the drawing canvas', '0.5.0': 'Arrives in 0.5.0 with reactions and annotations', - '0.6.0': 'Arrives in 0.6.0 with stereo and analysis', '0.7.0': 'Arrives in 0.7.0 with formats and exchange', '0.9.0': 'Arrives in 0.9.0 with names and spectra', '0.10.0': 'Arrives in 0.10.0 with 3D', @@ -186,7 +185,6 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { later('insert-name', 'Structure from Name...', 'Insert', '0.9.0'), { id: 'insert-template', label: () => t('Template...'), group: 'Insert', icon: 'template', mutates: true, description: 'Opens the template library; with id it inserts that template (fresh ids, scaled to the drawing bond length) centred in the view of the active drawing, or a new one, as one undo step. GET /api/templates lists the ids.', params: { id: { type: 'string', description: 'Template id from GET /api/templates, such as benzene or l-alanine; leave it out to open the library', example: 'benzene' } }, run: (params) => deps.insertTemplate(typeof params?.id === 'string' ? params.id : undefined) }, - later('set-reaction-roles', 'Set Reaction Roles', 'Reaction', '0.6.0', undefined, 'Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing'), { id: 'stoichiometry-grid', label: () => t('Insert Stoichiometry Table'), group: 'Reaction', icon: 'table', mutates: true, description: 'Inserts the stoichiometry grid of the selected reaction step as a table under the reaction, or refreshes the table already bound to that step, as one undo step.', when: 'Draw a reaction with an arrow first', enabled: () => deps.hasDocument(), run: () => deps.insertStoichTable() }, later('view-3d', '3D View', '3D', '0.10.0', 'model3d'), diff --git a/frontend/src/app/reaction-commands.ts b/frontend/src/app/reaction-commands.ts index b7e7184f..bfcf1d8f 100644 --- a/frontend/src/app/reaction-commands.ts +++ b/frontend/src/app/reaction-commands.ts @@ -1,14 +1,17 @@ import { fragmentsTouched, isEmpty } from '../canvas/selection'; import type { CanvasView } from '../canvas/view'; +import { quickFormula } from '../chem/formula'; +import { canTakeRole, reactionRoleOps, REACTION_ROLES, roleOf, type ReactionRole } from '../chem/reaction-roles'; import { reactionSteps, stepFor } from '../chem/stoich'; import { commands, type CommandDef } from '../commands/registry'; import type { DocumentClient } from '../engine/client-api'; -import type { Id } from '../engine/model'; +import { isFragment, type Id } from '../engine/model'; import { reactionsApi, warningText, type CheckAnswer, type ReactionFormat, type StepRef } from '../engine/reactions-api'; import { session } from '../engine/session'; import { t } from '../i18n'; import { copyText, Dialog, promptName } from '../ui/dialogs'; import { el, inTauri, setText } from '../ui/dom'; +import { askReactionRoles, type RoleRow } from '../ui/roles-dialog'; import { toast } from '../ui/toast'; export interface ReactionCommandDeps { @@ -158,6 +161,41 @@ async function exportReaction(view: CanvasView, client: DocumentClient, format: toast(`${t('Exported the reaction to')} ${name}${noteWarnings(out.warnings)}`); } +function roleRow(view: CanvasView, client: DocumentClient, id: Id, role: ReactionRole, selected: boolean): RoleRow { + const o = client.doc.objects[id]; + if (isFragment(o)) { + const formula = client.derived?.fragments[id]?.formula || quickFormula(o, client.doc.expansions); + return { id, label: o.name || formula || id, detail: o.name ? formula : '', role, selected }; + } + const runs = (o as { runs?: { t?: string }[] } | undefined)?.runs; + const text = Array.isArray(runs) ? runs.map((r) => r.t ?? '').join('').replace(/\s+/g, ' ').trim() : ''; + return { id, label: text.length > 48 ? `${text.slice(0, 47)}...` : text || t(o?.kind === 'text' || o?.kind === 'caption' ? 'Text' : 'Object'), detail: '', role, selected }; +} + +async function setRoles(view: CanvasView, client: DocumentClient, params?: Record): Promise { + const ref = await ensureStep(view, client); + const entry = ref ? reactionSteps(client.doc).find((e) => e.ref.step === ref.step) : null; + if (!ref || !entry) return; + const step = entry.step; + const picked = Array.isArray(params?.objects) ? (params.objects as unknown[]).filter((x): x is Id => typeof x === 'string') : scopeIds(view) ?? []; + const chosen = picked.filter((id) => canTakeRole(client.doc, step, id)); + let changes: Map | null; + if (typeof params?.role === 'string') { + if (!REACTION_ROLES.includes(params.role as ReactionRole)) throw new Error(`role must be one of ${REACTION_ROLES.join(', ')}`); + changes = new Map(chosen.map((id) => [id, params.role as ReactionRole])); + } else { + const members = [...step.reactants, ...step.agents, ...(step.conditions ?? []), ...step.products]; + const ids = [...new Set([...chosen, ...members])].filter((id) => canTakeRole(client.doc, step, id)); + if (!ids.length) { toast(t('Select the structures or text to give a role first.')); return; } + const want = new Set(chosen); + const stepLabel = `${t('Reaction')} ${entry.reactionIndex + 1}, ${t('step')} ${entry.index + 1}`; + changes = await askReactionRoles(stepLabel, ids.map((id) => roleRow(view, client, id, roleOf(step, id), want.has(id)))); + } + if (!changes?.size || view.client !== client) return; + const ops = reactionRoleOps(client.doc, ref, changes); + if (ops.length) client.commit(t('Set Reaction Roles'), ops); +} + async function readClipboard(): Promise { try { const text = await navigator.clipboard.readText(); @@ -184,6 +222,7 @@ export function registerReactionCommands(deps: ReactionCommandDeps): () => void }; const defs: CommandDef[] = [ { id: 'perceive-reactions', label: () => t('Perceive Reactions'), group: 'Reaction', icon: 'arrow', mutates: true, description: 'Reads the reaction arrows on the page and stores each step with its reactants, products, agents and conditions, as one undo step.', when: NEED_DRAWING, enabled: open, run: on('Could not perceive the reactions', perceive) }, + { id: 'set-reaction-roles', label: () => t('Set Reaction Roles...'), group: 'Reaction', mutates: true, description: 'Sets the role of the selected structures or text in the selected reaction step (reactant, product, agent, condition or none) and marks the step\'s roles as set by hand, as one undo step. Without role it opens a dialog listing the step\'s members and the selection.', params: { role: { type: 'string', enum: ['reactant', 'product', 'agent', 'condition', 'none'], description: 'Role to give the objects; leave it out to open the dialog' }, objects: { type: 'array', description: 'Object ids to change; default the selection' } }, when: NEED_DRAWING, enabled: open, run: (params) => { const c = view.client; if (c) return setRoles(view, c, params).catch(fail('Could not set the reaction roles')); return undefined; } }, { id: 'map-atoms', label: () => t('Map Atoms'), group: 'Reaction', mutates: true, description: 'Maps the atoms of the selected reaction step (perceiving reactions first when none is stored) and marks the bonds broken, formed and changed, as one undo step.', when: NEED_DRAWING, enabled: open, run: on('Could not map the atoms', mapAtoms) }, { id: 'clear-mapping', label: () => t('Clear Atom Mapping'), group: 'Reaction', mutates: true, description: 'Removes the atom map numbers and reacting-centre marks of the selected reaction step.', when: NEED_REACTION, enabled: hasSteps, run: on('Could not clear the mapping', clearMap) }, { id: 'check-reaction', label: () => t('Check Balance...'), group: 'Reaction', icon: 'approve', description: 'Shows the element, charge and mass balance of the selected reaction step, with a suggestion when it is not balanced.', when: NEED_DRAWING, enabled: open, run: on('Could not check the reaction', check) }, From a26831ba134c5f30d7084e178f2dbcc9e3a563c5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:24:04 -0500 Subject: [PATCH 231/279] docs(mcp): tell agents about the reaction and analysis tools (0.6.0) The instructions, guide and get_context still said every drawing tool arrives in 0.8.0, although agents can already write reactions and read properties, checks, stereo and substructure hits; only atom and bond tools remain for 0.8.0. --- backend/app/routers/mcp.py | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index a90a3640..8fe1f043 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -23,27 +23,32 @@ INSTRUCTIONS = ("FormChem is the structure drawing suite of the FormAI family, running on this computer; the person watches it in the FormChem window. " "Drawings exist: get_context lists the documents open in the window (id, title, path, unsaved changes, revision, fragments, formula). " f"Change them through run_command with the window's own commands (list_commands first; insert-smiles {{smiles}} adds a structure, clean-structure, align and the rest act on the person's selection) " - f"and through Form extensions; dedicated drawing tools for agents arrive in {DRAWING_FROM}. " + "and through Form extensions. Reaction tools work on a drawing directly: perceive_reactions and map_reaction write the reaction steps and the atom mapping (one undo step each); " + "export_reaction and reaction_stoichiometry read them. Analysis tools read a drawing: properties, check_structure, stereo (CIP labels and enhanced stereo groups) and substructure (SMARTS or a drawn query). " + f"Tools that add atoms and bonds by id arrive in {DRAWING_FROM}. " "Workflow: get_context first; list_commands and run_command reach the window's menu commands; extensions_list and extension_command reach Form extensions; " "handoff {state: ready or question, note} tells the person where your work stands in the window. Commands, extensions and a handoff change what the person sees, " "so the first one asks the person in the window to allow agents. Details: resource formchem://guide.") WORKFLOW = [ "1. get_context -> window open or not, agents allowed or not, open drawings, catalogue size, your last handoff", "2. list_commands {text} -> command ids; run_command {id} runs one in the window as the person's click would", - "3. extensions_list -> Form extensions and their commands; extension_command {id, command} runs one in the window", - "4. handoff {state: ready, note} when you are done; state question when you need the person's input", + "3. reactions: perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry; analysis: properties, check_structure, stereo, substructure", + "4. extensions_list -> Form extensions and their commands; extension_command {id, command} runs one in the window", + "5. handoff {state: ready, note} when you are done; state question when you need the person's input", ] GUIDE = f"""# FormChem agent guide FormChem is a chemical structure drawing suite and a member of the FormAI family. The engine on this computer serves this MCP server; the person works in the FormChem window and sees every change there. ## What exists in this version -FormChem {config.VERSION} draws. Drawings are documents the engine owns (docs/FORMAT.md): the person opens them in the window, draws on the canvas with the tool rail and hover keys, and the engine's chemistry (RDKit) works out SMILES, InChIKey, formula, masses and elemental analysis after every change, shown in the Analysis panel. Files in molfile, SDF, RXN, SMILES, CML and CDXML open as new drawings. +FormChem {config.VERSION} draws. Drawings are documents the engine owns (docs/FORMAT.md): the person opens them in the window, draws on the canvas with the tool rail and hover keys, and the engine's chemistry (RDKit) works out SMILES, InChIKey, formula, masses, elemental analysis and CIP labels after every change, shown in the Analysis panel with the calculated properties and the isotope pattern. Drawings hold reaction schemes with perceived or hand-set roles, stereo groups, query atoms and bonds, abbreviations and R-group definitions. Files in molfile, SDF, RXN, SMILES, CML and CDXML open as new drawings. How an agent changes a drawing today: -- run_command with the window's own commands, the same ones the menus run. Call list_commands first: it gives each id, its params and whether it is on right now. insert-smiles {{"smiles": "c1ccccc1O"}} adds a structure to the active drawing (or a new one) and selects it; new-document, open-recent {{"path"}}, save, undo, redo, select-all, delete, duplicate, flip-horizontal, flip-vertical, rotate-90, align-*, distribute-*, clean-structure, layout-structure, check-structure and the zoom commands act on the active drawing and the person's selection. Each command is one undo step. +- run_command with the window's own commands, the same ones the menus run. Call list_commands first: it gives each id, its params and whether it is on right now. insert-smiles {{"smiles": "c1ccccc1O"}} adds a structure to the active drawing (or a new one) and selects it; new-document, open-recent {{"path"}}, save, undo, redo, select-all, delete, duplicate, flip-horizontal, flip-vertical, rotate-90, align-*, distribute-*, clean-structure, layout-structure, check-structure and the zoom commands act on the active drawing and the person's selection. Chemistry commands work the same way: add-hydrogens, remove-hydrogens, expand-abbreviation, contract-abbreviation, assign-wedges, set-stereo-group-and, set-atom-list, define-rgroup, enumerate-markush, set-reaction-roles {{"role", "objects"}}, copy-smarts and compute-properties. Each command is one undo step. +- The reaction tools below write reaction steps and atom mapping straight into a drawing and read reactions and stoichiometry back. +- The analysis tools below read a drawing: properties, the structure check, CIP stereo and substructure hits. They never change it. - Form extensions, through extension_command: an extension may read the drawing and apply transactions to it. -Dedicated drawing tools for agents (adding atoms and bonds by id, reading the document directly) arrive in {DRAWING_FROM}. Until then, say plainly what you can do with the commands above. +Tools that add atoms and bonds by id and read the whole document arrive in {DRAWING_FROM}. Until then, say plainly what you can do with the commands and tools above. ## Tools - get_context: app, version, whether a window is open, whether agents are allowed, the documents open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the size of the command catalogue and your last handoff. Call it first. @@ -93,7 +98,8 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = _S = {"type": "string"} TOOLS = [ _tool("get_context", "FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), " - f"the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; dedicated drawing tools arrive in {DRAWING_FROM}.", {}, read=True), + f"the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; " + f"properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in {DRAWING_FROM}.", {}, read=True), _tool("list_commands", "The window's command catalogue, the same commands as the menus, title bar and palette: id, label, group and what it does; commands of a later version are listed as off. " "text narrows by words (all must match), group by one group; id returns one command in full.", {"text": _S, "group": _S, "id": _S, "limit": {"type": "integer", "description": "Most rows to return (default 60)"}}, read=True), @@ -260,7 +266,8 @@ async def t_get_context(a: Agent, args: dict) -> dict: lines.append("Agents: " + ("blocked by the person (Preferences)" if blocked else "allowed" if allowed else "not yet allowed (your first change asks the person in the window)")) docs = _documents() if docs: - lines.append(f"Documents: {len(docs)} open in the window (change them with run_command and the window's commands; dedicated drawing tools arrive in {DRAWING_FROM})") + lines.append(f"Documents: {len(docs)} open in the window (change them with run_command and the window's commands, write reactions with perceive_reactions and map_reaction, " + f"read them with export_reaction, reaction_stoichiometry, properties, check_structure, stereo and substructure; atom and bond tools arrive in {DRAWING_FROM})") lines.extend(_document_line(d) for d in docs) else: lines.append("Documents: none open (run_command new-document, insert-smiles {smiles} or open-recent {path} opens one)") From edb2a8d8ecbcb74635bf1bb73e04050c6c12ca29 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:24:04 -0500 Subject: [PATCH 232/279] chore(agents): regenerate the tools reference and manifest for the analysis tools (0.6.0) Written by ./formchem agents sync so the harness reference and the manifest list the four analysis tools and the new get_context text; sync --check is in step. --- .../formchem-harness/references/tools.md | 53 ++++++++++++++++++- .../formchem-harness/references/tools.md | 53 ++++++++++++++++++- agents/manifest.json | 12 ++++- 3 files changed, 112 insertions(+), 6 deletions(-) diff --git a/.agents/skills/formchem-harness/references/tools.md b/.agents/skills/formchem-harness/references/tools.md index d3fc2305..cfef0fe0 100644 --- a/.agents/skills/formchem-harness/references/tools.md +++ b/.agents/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 10 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 14 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -17,6 +17,10 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - map_reaction - export_reaction - reaction_stoichiometry +- properties +- check_structure +- stereo +- substructure - Resource | Tool | Kind | @@ -31,10 +35,14 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `map_reaction` | approval-gated | | `export_reaction` | read-only | | `reaction_stoichiometry` | read-only | +| `properties` | read-only | +| `check_structure` | read-only | +| `stereo` | read-only | +| `substructure` | read-only | ## get_context -FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; dedicated drawing tools arrive in 0.8.0. +FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in 0.8.0. Arguments: none. @@ -125,6 +133,47 @@ The stoichiometry of one reaction step worked out from the amounts the person ty | `reaction` | string | no | | | `step` | string | no | | +## properties + +Drug-like properties of the structures in an open drawing, per fragment: formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis; every value names the RDKit method behind it. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `object` | string | no | One fragment id; absent: every fragment | + +## check_structure + +Checks the structures of an open drawing: valence errors, unusual charges, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps; each issue has a code, a severity (error, warning, info) and the atom and bond ids it concerns. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `object` | string | no | One fragment id; absent: every fragment | +| `query` | boolean | no | True when the drawing is a search query, so query features are not reported | + +## stereo + +Stereochemistry of an open drawing per fragment: each stereocentre, stereogenic double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), whether it is defined, undefined or unknown, its enhanced stereo group (abs, and1, or1) and the CXSMILES that carries the groups. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `object` | string | no | One fragment id; absent: every fragment | + +## substructure + +Searches the fragments of an open drawing for a substructure given as SMARTS or as a query fragment drawn in the same drawing; returns every hit with its fragment id and the matched atom and bond ids. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `smarts` | string | no | SMARTS pattern, such as C(=O)[OH] | +| `query_object` | string | no | A fragment of the drawing to use as the query instead of smarts | +| `objects` | array of string | no | Fragment ids to search; absent: all | +| `chirality` | boolean | no | | +| `max_hits` | integer | no | Most hits to return (default 1000) | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/.claude/skills/formchem-harness/references/tools.md b/.claude/skills/formchem-harness/references/tools.md index d3fc2305..cfef0fe0 100644 --- a/.claude/skills/formchem-harness/references/tools.md +++ b/.claude/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 10 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 14 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -17,6 +17,10 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - map_reaction - export_reaction - reaction_stoichiometry +- properties +- check_structure +- stereo +- substructure - Resource | Tool | Kind | @@ -31,10 +35,14 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `map_reaction` | approval-gated | | `export_reaction` | read-only | | `reaction_stoichiometry` | read-only | +| `properties` | read-only | +| `check_structure` | read-only | +| `stereo` | read-only | +| `substructure` | read-only | ## get_context -FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; dedicated drawing tools arrive in 0.8.0. +FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in 0.8.0. Arguments: none. @@ -125,6 +133,47 @@ The stoichiometry of one reaction step worked out from the amounts the person ty | `reaction` | string | no | | | `step` | string | no | | +## properties + +Drug-like properties of the structures in an open drawing, per fragment: formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis; every value names the RDKit method behind it. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `object` | string | no | One fragment id; absent: every fragment | + +## check_structure + +Checks the structures of an open drawing: valence errors, unusual charges, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps; each issue has a code, a severity (error, warning, info) and the atom and bond ids it concerns. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `object` | string | no | One fragment id; absent: every fragment | +| `query` | boolean | no | True when the drawing is a search query, so query features are not reported | + +## stereo + +Stereochemistry of an open drawing per fragment: each stereocentre, stereogenic double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), whether it is defined, undefined or unknown, its enhanced stereo group (abs, and1, or1) and the CXSMILES that carries the groups. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `object` | string | no | One fragment id; absent: every fragment | + +## substructure + +Searches the fragments of an open drawing for a substructure given as SMARTS or as a query fragment drawn in the same drawing; returns every hit with its fragment id and the matched atom and bond ids. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Document id from get_context (optional when one drawing is open) | +| `smarts` | string | no | SMARTS pattern, such as C(=O)[OH] | +| `query_object` | string | no | A fragment of the drawing to use as the query instead of smarts | +| `objects` | array of string | no | Fragment ids to search; absent: all | +| `chirality` | boolean | no | | +| `max_hits` | integer | no | Most hits to return (default 1000) | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/agents/manifest.json b/agents/manifest.json index f00ed61c..c1ea73fa 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -13,14 +13,22 @@ "perceive_reactions", "map_reaction", "export_reaction", - "reaction_stoichiometry" + "reaction_stoichiometry", + "properties", + "check_structure", + "stereo", + "substructure" ], "read_only": [ "get_context", "list_commands", "extensions_list", "export_reaction", - "reaction_stoichiometry" + "reaction_stoichiometry", + "properties", + "check_structure", + "stereo", + "substructure" ], "approval_gated": [ "run_command", From 1c85befef84e30b8e6f416310d5a82dea615f5ea Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:26:37 -0500 Subject: [PATCH 233/279] fix(chem): stop reporting allene bonds as undefined E/Z double bonds (0.6.0) RDKit lists every bond of a cumulene as a potential stereo double bond, so an allene drew an undefined_double_bond warning on both bonds; in a cumulene only the middle bond of an odd run can be E or Z, so the other bonds are left out of the report and the warning. --- backend/app/services/chem/perceive.py | 31 ++++++++++++++++++++++++++- backend/app/services/chem/stereo.py | 3 +++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/backend/app/services/chem/perceive.py b/backend/app/services/chem/perceive.py index 6826e496..b509c15c 100644 --- a/backend/app/services/chem/perceive.py +++ b/backend/app/services/chem/perceive.py @@ -131,6 +131,34 @@ def _rings(p: Perception) -> None: p.warnings.append(warning("aromatic_outside_ring", "Aromatic bond outside a ring.", bonds=[conv.bond_id(b.GetIdx())])) +def _cumulene(mol: Chem.Mol, start: Chem.Bond) -> list[int]: + def walk(bond: Chem.Bond, atom: int) -> list[int]: + out = [] + while True: + a = mol.GetAtomWithIdx(atom) + nxt = [x for x in a.GetBonds() if x.GetIdx() != bond.GetIdx() and x.GetBondType() == Chem.BondType.DOUBLE] + if len(nxt) != 1 or a.GetDegree() != 2 or nxt[0].GetIdx() in out: + return out + bond = nxt[0] + out.append(bond.GetIdx()) + atom = bond.GetOtherAtomIdx(atom) + return walk(start, start.GetBeginAtomIdx())[::-1] + [start.GetIdx()] + walk(start, start.GetEndAtomIdx()) + + +def not_ez_bonds(mol: Chem.Mol) -> set[int]: + skip: set[int] = set() + seen: set[int] = set() + for b in mol.GetBonds(): + if b.GetIdx() in seen or b.GetBondType() != Chem.BondType.DOUBLE: + continue + chain = _cumulene(mol, b) + seen.update(chain) + if len(chain) > 1: + keep = chain[len(chain) // 2] if len(chain) % 2 else None + skip.update(i for i in chain if i != keep) + return skip + + def _cip(p: Perception) -> None: conv = p.conv mol = conv.mol @@ -154,7 +182,8 @@ def _cip(p: Perception) -> None: undefined = [conv.owner[si.centeredOn] for si in centres if si.specified == Chem.StereoSpecified.Unspecified] unknown = [conv.owner[si.centeredOn] for si in centres if si.specified == Chem.StereoSpecified.Unknown] marked = {b for w in conv.warnings if w.get("code") == "unknown_ez" for b in w.get("bonds", [])} - loose = [conv.bond_id(si.centeredOn) for si in found if si.type == Chem.StereoType.Bond_Double + cumulated = not_ez_bonds(mol) + loose = [conv.bond_id(si.centeredOn) for si in found if si.type == Chem.StereoType.Bond_Double and si.centeredOn not in cumulated and si.specified != Chem.StereoSpecified.Specified and conv.bond_id(si.centeredOn) and conv.bond_id(si.centeredOn) not in marked] if undefined: p.warnings.append(warning("undefined_stereocentre", f"{len(undefined)} stereocentre(s) without a configuration.", undefined)) diff --git a/backend/app/services/chem/stereo.py b/backend/app/services/chem/stereo.py index 22185d08..7c734aff 100644 --- a/backend/app/services/chem/stereo.py +++ b/backend/app/services/chem/stereo.py @@ -41,7 +41,10 @@ def report(frag: dict, expansions: dict | None = None) -> dict: except Exception: found = [] centres, double_bonds, axes = [], [], [] + cumulated = perceive.not_ez_bonds(mol) for si in found: + if si.type == ST.Bond_Double and si.centeredOn in cumulated: + continue if si.type == ST.Atom_Tetrahedral: i = si.centeredOn if not conv.drawn[i]: From 1e04495839ac8f9c995d5b5ef28ce41f50edab50 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:36:27 -0500 Subject: [PATCH 234/279] fix(app): expand abbreviations against the open drawing so the expansion record goes with the last use (0.6.0) Expanding sent the fragment alone, so the engine could not see other uses and left the expansion record in the document after the last abbreviation was expanded; in document mode it drops the record and checks new ids against every fragment. --- frontend/src/app/chem-commands.ts | 5 +++-- frontend/src/engine/analysis-api.ts | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/frontend/src/app/chem-commands.ts b/frontend/src/app/chem-commands.ts index e86d65fd..2ad4d2ed 100644 --- a/frontend/src/app/chem-commands.ts +++ b/frontend/src/app/chem-commands.ts @@ -199,7 +199,8 @@ export async function expandAbbreviation(host: ChemHost): Promise { const targets = abbreviationAtoms(host); if (!targets.size) { toast(t('Select an abbreviation such as Ph or OTs to expand.')); return; } const bl = host.style().bond_length; - const res = await engineEdit(host, t('Expand Abbreviation'), targets, (src, atoms) => analysisApi.expand(src, atoms, bl)); + const doc = host.client?.id; + const res = await engineEdit(host, t('Expand Abbreviation'), targets, (src, atoms) => analysisApi.expand(doc ? { doc, object: src.fragment.id } : src, atoms, bl)); if (!res) return; const keys: string[] = []; [...targets.keys()].forEach((fid, i) => { for (const list of Object.values(res[i]?.expanded ?? {})) for (const a of list) keys.push(selectionKey(fid, a)); }); @@ -374,7 +375,7 @@ export function checkStructure(host: ChemHost): void { if (!client || !cmd || !src) return; const atoms = row.atoms.length ? row.atoms : undefined; try { - const res = cmd === 'wedges' ? await analysisApi.wedges(src, atoms) : await analysisApi.expand(src, atoms); + const res = cmd === 'wedges' ? await analysisApi.wedges(src, atoms) : await analysisApi.expand({ doc: client.id, object: row.frag }, atoms); if (host.client !== client || client.doc.objects[row.frag] !== src.fragment) { toast(t('The drawing changed while the engine worked; try again.')); return; } if (res.tx?.ops.length) client.commit(t('Fix Structure'), res.tx.ops); } catch (e) { diff --git a/frontend/src/engine/analysis-api.ts b/frontend/src/engine/analysis-api.ts index 79278767..ce22b309 100644 --- a/frontend/src/engine/analysis-api.ts +++ b/frontend/src/engine/analysis-api.ts @@ -260,7 +260,7 @@ export const analysisApi = { return all[src.fragment.id] ?? Object.values(all)[0] ?? checkOf({}); }, - async expand(src: Source, atoms?: Id[], bondLength?: number): Promise<{ tx: EngineTx | null; expanded: Record; warnings: EngineWarning[] }> { + async expand(src: Source | { doc: Id; object: Id }, atoms?: Id[], bondLength?: number): Promise<{ tx: EngineTx | null; expanded: Record; warnings: EngineWarning[] }> { const body: Rec = { ...src }; if (atoms) body.atoms = atoms; if (bondLength) body.bond_length = bondLength; From 086dcc65837683aa306c1a5f067ddd743373594b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:39:56 -0500 Subject: [PATCH 235/279] fix(chem): treat a bare star atom as an attachment point, not an unknown label (0.6.0) Every R-group member drawn with a * stub showed an unknown_label warning in the derived cache and in Check Structure; FORMAT defines an unlabelled * as any atom or an attachment point, so it is now a generic atom like R or X. --- backend/app/services/chem/convert.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/app/services/chem/convert.py b/backend/app/services/chem/convert.py index 868a2b46..4c53a081 100644 --- a/backend/app/services/chem/convert.py +++ b/backend/app/services/chem/convert.py @@ -93,7 +93,7 @@ def _new_atom(a: dict, conv: Conversion) -> Chem.Atom: if label: atom.SetProp("dummyLabel", label) atom.SetProp("atomLabel", label) - if a.get("generic") or asked or label in ("R", "R'", "R''", "X", "Ar", "Alk", "Het", "Hal", "M", "G"): + if a.get("generic") or asked or label in ("R", "R'", "R''", "X", "Ar", "Alk", "Het", "Hal", "M", "G") or (el == "*" and label in (None, "", "*")): conv.generic.append(aid) else: conv.unknown.append(aid) From 19e1cd954161cf14110e2a177563f70af19f48ef Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:20 -0500 Subject: [PATCH 236/279] fix(canvas): turn a stereo or query mark within its free gap when a neighbouring label blocks it (0.6.0) After contracting ibuprofen's acid to CO2H the (S) and and1 marks sat on the CO2H label, because the mark only moved outward along one direction; it now also tries directions up to 50 degrees either side before stepping further out. --- frontend/src/canvas/render/marks-stereo.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/frontend/src/canvas/render/marks-stereo.ts b/frontend/src/canvas/render/marks-stereo.ts index f1fac46b..dbac9da1 100644 --- a/frontend/src/canvas/render/marks-stereo.ts +++ b/frontend/src/canvas/render/marks-stereo.ts @@ -103,8 +103,19 @@ export function block(at: V, d: V, gap: number, lines: Line[], style: Style): { const overlaps = (a: Box, b: Box): boolean => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; export function clearOf(at: V, d: V, gap: number, lines: Line[], style: Style, avoid: readonly Box[], L: number): NodeSpec[] { + const clear = (p: { box: Box }): boolean => !avoid.some((b) => overlaps(p.box, b)); let placed = block(at, d, gap, lines, style); - for (let i = 1; i <= 6 && avoid.some((b) => overlaps(placed.box, b)); i++) placed = block(at, d, gap + i * 0.15 * L, lines, style); + for (let i = 1; i <= 2 && !clear(placed); i++) placed = block(at, d, gap + i * 0.15 * L, lines, style); + if (clear(placed)) return placed.specs; + for (const turn of [0.44, -0.44, 0.87, -0.87]) { + const c = Math.cos(turn), s = Math.sin(turn); + const dd: V = [d[0] * c - d[1] * s, d[0] * s + d[1] * c]; + for (let i = 0; i <= 3; i++) { + const p = block(at, dd, gap + i * 0.15 * L, lines, style); + if (clear(p)) return p.specs; + } + } + for (let i = 3; i <= 6 && !clear(placed); i++) placed = block(at, d, gap + i * 0.15 * L, lines, style); return placed.specs; } From c9db35f13a99794ba0cc01799d586574d5bd7c2e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:20 -0500 Subject: [PATCH 237/279] fix(ui): show formula, masses and elemental analysis once in the analysis panel (0.6.0) The old window-side rows repeated the engine's properties section with a different formula for deuterium, so they are kept for the status bar but no longer shown. --- frontend/src/styles/chem-ui.css | 2 ++ frontend/src/ui/analysis-panel.ts | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index 2e6aca6a..79b7c0b7 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -107,6 +107,8 @@ .fc-apx.is-shown .fc-apx-val { opacity: 0.5; } .fc-apx-note { margin-top: 4px; } .fc-apx-note[hidden] { display: none; } +.fc-ap-rows[hidden] { display: none; } +.fc-ap-rows[hidden] + .fc-apx { margin-top: 0; padding-top: 0; border-top: 0; } .fc-iso { display: grid; gap: 4px; padding-top: var(--space-2); } .fc-iso-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); min-height: 22px; } diff --git a/frontend/src/ui/analysis-panel.ts b/frontend/src/ui/analysis-panel.ts index 0b456fe3..0a1fea84 100644 --- a/frontend/src/ui/analysis-panel.ts +++ b/frontend/src/ui/analysis-panel.ts @@ -50,7 +50,7 @@ export function mountAnalysisPanel(host: HTMLElement): void {
${t('Analysis')}

${t('Formula, masses and properties appear here when a structure is selected.')}

-
${rows}
+
`); panel = host; From 6c02b3a7c7d485aea1867b5dd9d7f72bf7d92767 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:50:56 -0500 Subject: [PATCH 238/279] feat(i18n): key the stereo, query, analysis and reaction role strings (0.6.0) --- frontend/src/i18n/keys/part06.json | 156 +++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/keys/part06.json diff --git a/frontend/src/i18n/keys/part06.json b/frontend/src/i18n/keys/part06.json new file mode 100644 index 00000000..79497df5 --- /dev/null +++ b/frontend/src/i18n/keys/part06.json @@ -0,0 +1,156 @@ +[ +"Hill order with charge, abbreviations expanded", +"Standard atomic weights (CIAAW conventional values)", +"Monoisotopic mass from the most abundant isotope of each element", +"Exact mass divided by the absolute charge, electron mass corrected", +"Mass percent of each element, two decimals", +"Atom contributions (Wildman and Crippen 1999)", +"Topological polar surface area, N and O fragments (Ertl 2000)", +"Molar refractivity", +"H-bond donors", +"Lipinski counting: N-H and O-H groups", +"H-bond acceptors", +"Lipinski counting: N and O atoms", +"Rotatable bonds", +"Non-ring single bonds between non-terminal heavy atoms, amide C-N excluded", +"Lipinski rule of five", +"MW at most 500, cLogP at most 5, donors at most 5, acceptors at most 10", +"HBD", +"HBA", +"Pass (0 violations)", +"Select one or more atoms first", +"Select one or more bonds first", +"No implicit hydrogens to add.", +"No explicit hydrogens to remove.", +"Select an abbreviation such as Ph or OTs to expand.", +"Select the atoms of one group in one structure to contract.", +"Select the group to contract, without the atom it is attached to.", +"Contract", +"Pick a library abbreviation or type a new label for the selected atoms.", +"Set Stereo Group", +"Clear Stereo Group", +"Set Atom List", +"Clear Atom List", +"Set Query Bond", +"Clear Bond Query", +"Select the atom that carries the R-group.", +"1 attachment point", +"Define R-Group", +"Remove R-Group Definition", +"Assign Wedges", +"The wedges already match the stereocentres.", +"The selected structures", +"Every structure on this page", +"Fix Structure", +"There is no structure to analyse.", +"Analysis copied", +"Could not copy to the clipboard", +"Find Substructure", +"SMARTS", +"Draw the structures to search on this page first.", +"first results only", +"No matches on this page.", +"Draw a structure with R-group atoms and define its R-groups first.", +"There is no structure to write as SMARTS.", +"Saving SMARTS files arrives with the file formats in 0.7.0; the SMARTS was copied instead.", +"Draws every implicit hydrogen of the selected atoms (or of every structure on the page) as an explicit H atom placed by the engine, in one undo step.", +"Removes explicit H atoms from the selection (or the page), keeping hydrogens that carry stereo, an isotope, a charge, a map number or bridge two atoms.", +"Replaces the selected abbreviation atoms (or every abbreviation on the page) by their full structure, laid out along the attachment bond.", +"Contract Abbreviation...", +"Collapses the selected group of atoms into one abbreviation atom with the label the person picks or types.", +"Shows or hides R, S, E and Z labels next to stereocentres and stereo double bonds.", +"Show Enhanced Stereo Groups", +"Shows or hides the abs, and and or group labels next to stereocentres while stereo labels are on.", +"Show Query Features", +"Shows or hides atom list, query bond and R-group marks on the canvas.", +"Puts the selected stereocentres in an enhanced stereo group: abs, and n or or n. Without n a new and or or group is made.", +"abs, and or or", +"Group number for and and or", +"Absolute (abs)", +"New AND Group", +"New OR Group", +"Stereo Group...", +"Atom List...", +"Turns the selected atoms into an atom list or not-list query picked on the periodic table.", +"Makes the selected bonds query bonds: any, single_or_double, single_or_aromatic or double_or_aromatic; leave query out to clear.", +"The query bond type", +"Define R-Group...", +"Makes the selected atom an R-group label and defines its members, occurrence, rest H and if-then condition.", +"Lets the engine choose wedge and hash bonds that express the stereocentres of the selection (or the page) unambiguously.", +"Lists valence, stereo, geometry and label problems of the selection (or the page) in a panel whose rows select the atoms.", +"Opens the analysis panel with the calculated properties of the selection or the page.", +"Copies formula, masses, elemental analysis and the calculated properties with their methods as text.", +"Find Substructure...", +"Selects every match of the selected atoms (or of a SMARTS pattern) in the other structures on the page.", +"Enumerate R-Groups...", +"Lists every structure the selected Markush scaffold (or the first one on the page) stands for, with formula and SMILES, up to 1000; the list can be copied.", +"Copy as SMARTS", +"Copies the selected atoms (or every structure on the page) as SMARTS, with atom lists, generic atoms, query bonds and the other query features.", +"Export SMARTS...", +"Saves the selected atoms (or every structure on the page) as a SMARTS file (.sma).", +"Enhanced Stereo", +"Query", +"Object", +"Select the structures or text to give a role first.", +"Set Reaction Roles...", +"Sets the role of the selected structures or text in the selected reaction step (reactant, product, agent, condition or none) and marks the step's roles as set by hand, as one undo step. Without role it opens a dialog listing the step's members and the selection.", +"Role to give the objects; leave it out to open the dialog", +"Object ids to change; default the selection", +"Could not set the reaction roles", +"rest H", +"Abbreviation", +"Label", +"Search the library", +"The abbreviation library could not be loaded. You can still type a label.", +"No abbreviation matches. The label you type is used as it is.", +"Properties", +"Atom List", +"Click elements in the table to add them.", +"Clear Query", +"Apply", +"Remove", +"No query", +"[M+Na]+", +"Isotope pattern", +"Enumerate R-Groups", +"Copy SMILES", +"Copied the SMILES of every structure", +"Si", +"Any Bond", +"Single or Double", +"Single or Aromatic", +"Double or Aromatic", +"Ring or Chain", +"In a Ring", +"In a Chain", +"Any Atom (A)", +"Any Heteroatom (Q)", +"Any Halogen (X)", +"Any Metal (M)", +"Set Bond Topology", +"Query Bond", +"Set Atom Query", +"Aromatic", +"Aliphatic", +"Unsaturated", +"Substitution as Drawn", +"Ring Bonds as Drawn", +"Clear Atom Query", +"Atom Query", +"R-Group Definition", +"R-group", +"Members", +"Draw each member as its own structure with an attachment point (*), then open this dialog again.", +"Occurrence", +"Rest H (unsubstituted positions are hydrogen)", +"If present, then", +"Remove Definition", +"Agent", +"Condition", +"Clear", +"Add the selected centres to this group", +"Check Again", +"Checking...", +"Fix", +"Select on the canvas" +] From 9651198f52265f2e7c74d22817ee739489a6cdf4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:38 -0500 Subject: [PATCH 239/279] feat(i18n): translate the stereo, query and analysis strings into Spanish (0.6.0) Adds part06 for the stereochemistry, query, R-group, structure check and analysis strings. --- frontend/src/i18n/locales/es/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/es/part06.json diff --git a/frontend/src/i18n/locales/es/part06.json b/frontend/src/i18n/locales/es/part06.json new file mode 100644 index 00000000..3cd27dab --- /dev/null +++ b/frontend/src/i18n/locales/es/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Orden de Hill con carga, abreviaturas expandidas", + "1": "Pesos atรณmicos estรกndar (valores convencionales de la CIAAW)", + "2": "Masa monoisotรณpica a partir del isรณtopo mรกs abundante de cada elemento", + "3": "Masa exacta dividida entre la carga absoluta, con correcciรณn de la masa del electrรณn", + "4": "Porcentaje en masa de cada elemento, con dos decimales", + "5": "Contribuciones atรณmicas (Wildman and Crippen 1999)", + "6": "Superficie polar topolรณgica, fragmentos de N y O (Ertl 2000)", + "7": "Refractividad molar", + "8": "Donantes de enlace de hidrรณgeno", + "9": "Recuento de Lipinski: grupos N-H y O-H", + "10": "Aceptores de enlace de hidrรณgeno", + "11": "Recuento de Lipinski: รกtomos de N y O", + "12": "Enlaces rotables", + "13": "Enlaces simples fuera de anillos entre รกtomos pesados no terminales, excluido el enlace C-N de las amidas", + "14": "Regla de los cinco de Lipinski", + "15": "MW como mรกximo 500, cLogP como mรกximo 5, donantes como mรกximo 5, aceptores como mรกximo 10", + "16": "HBD", + "17": "HBA", + "18": "Cumple (0 infracciones)", + "19": "Selecciona antes uno o mรกs รกtomos", + "20": "Selecciona antes uno o mรกs enlaces", + "21": "No hay hidrรณgenos implรญcitos que aรฑadir.", + "22": "No hay hidrรณgenos explรญcitos que quitar.", + "23": "Selecciona una abreviatura, como Ph u OTs, para expandirla.", + "24": "Selecciona los รกtomos de un grupo de una sola estructura para contraerlos.", + "25": "Selecciona el grupo que quieres contraer, sin el รกtomo al que estรก unido.", + "26": "Contraer", + "27": "Elige una abreviatura de la biblioteca o escribe una etiqueta nueva para los รกtomos seleccionados.", + "28": "Definir grupo estereoquรญmico", + "29": "Borrar grupo estereoquรญmico", + "30": "Definir lista de รกtomos", + "31": "Borrar lista de รกtomos", + "32": "Definir enlace de consulta", + "33": "Borrar consulta de enlace", + "34": "Selecciona el รกtomo que lleva el grupo R.", + "35": "1 punto de uniรณn", + "36": "Definir grupo R", + "37": "Quitar definiciรณn de grupo R", + "38": "Asignar cuรฑas", + "39": "Las cuรฑas ya coinciden con los estereocentros.", + "40": "Las estructuras seleccionadas", + "41": "Todas las estructuras de esta pรกgina", + "42": "Corregir estructura", + "43": "No hay ninguna estructura que analizar.", + "44": "Anรกlisis copiado", + "45": "No se pudo copiar en el portapapeles", + "46": "Buscar subestructura", + "47": "SMARTS", + "48": "Dibuja antes las estructuras en las que buscar en esta pรกgina.", + "49": "solo los primeros resultados", + "50": "No hay coincidencias en esta pรกgina.", + "51": "Dibuja antes una estructura con รกtomos de grupo R y define sus grupos R.", + "52": "No hay ninguna estructura que escribir como SMARTS.", + "53": "Guardar archivos SMARTS llegarรก con los formatos de archivo en la 0.7.0; se ha copiado el SMARTS en su lugar.", + "54": "Dibuja cada hidrรณgeno implรญcito de los รกtomos seleccionados (o de todas las estructuras de la pรกgina) como un รกtomo de H explรญcito colocado por el motor, en un solo paso de deshacer.", + "55": "Quita los รกtomos de H explรญcitos de la selecciรณn (o de la pรกgina), conservando los hidrรณgenos que llevan estereoquรญmica, un isรณtopo, una carga o un nรบmero de mapeo, o que forman un puente entre dos รกtomos.", + "56": "Sustituye los รกtomos de abreviatura seleccionados (o todas las abreviaturas de la pรกgina) por su estructura completa, dispuesta a lo largo del enlace de uniรณn.", + "57": "Contraer abreviatura...", + "58": "Contrae el grupo de รกtomos seleccionado en un รบnico รกtomo de abreviatura con la etiqueta que elijas o escribas.", + "59": "Muestra u oculta las etiquetas R, S, E y Z junto a los estereocentros y los dobles enlaces estereoquรญmicos.", + "60": "Mostrar grupos de estereoquรญmica mejorada", + "61": "Muestra u oculta las etiquetas de grupo abs, and y or junto a los estereocentros mientras las etiquetas de estereoquรญmica estรกn activadas.", + "62": "Mostrar caracterรญsticas de consulta", + "63": "Muestra u oculta las marcas de lista de รกtomos, enlace de consulta y grupo R en el lienzo.", + "64": "Coloca los estereocentros seleccionados en un grupo de estereoquรญmica mejorada: abs, and n u or n. Sin n se crea un grupo and u or nuevo.", + "65": "abs, and u or", + "66": "Nรบmero de grupo para and y or", + "67": "Absoluto (abs)", + "68": "Nuevo grupo AND", + "69": "Nuevo grupo OR", + "70": "Grupo estereoquรญmico...", + "71": "Lista de รกtomos...", + "72": "Convierte los รกtomos seleccionados en una consulta de lista de รกtomos o de lista de exclusiรณn elegida en la tabla periรณdica.", + "73": "Convierte los enlaces seleccionados en enlaces de consulta: any, single_or_double, single_or_aromatic o double_or_aromatic; omite query para borrar.", + "74": "El tipo de enlace de consulta", + "75": "Definir grupo R...", + "76": "Convierte el รกtomo seleccionado en una etiqueta de grupo R y define sus miembros, ocurrencia, H restante y la condiciรณn si-entonces.", + "77": "Deja que el motor elija enlaces en cuรฑa y en cuรฑa discontinua que expresen sin ambigรผedad los estereocentros de la selecciรณn (o de la pรกgina).", + "78": "Enumera los problemas de valencia, estereoquรญmica, geometrรญa y etiquetas de la selecciรณn (o de la pรกgina) en un panel cuyas filas seleccionan los รกtomos.", + "79": "Abre el panel de anรกlisis con las propiedades calculadas de la selecciรณn o de la pรกgina.", + "80": "Copia como texto la fรณrmula, las masas, el anรกlisis elemental y las propiedades calculadas con sus mรฉtodos.", + "81": "Buscar subestructura...", + "82": "Selecciona todas las coincidencias de los รกtomos seleccionados (o de un patrรณn SMARTS) en las demรกs estructuras de la pรกgina.", + "83": "Enumerar grupos R...", + "84": "Enumera todas las estructuras que representa el esqueleto de Markush seleccionado (o el primero de la pรกgina), con fรณrmula y SMILES, hasta 1000; la lista se puede copiar.", + "85": "Copiar como SMARTS", + "86": "Copia los รกtomos seleccionados (o todas las estructuras de la pรกgina) como SMARTS, con listas de รกtomos, รกtomos genรฉricos, enlaces de consulta y las demรกs caracterรญsticas de consulta.", + "87": "Exportar SMARTS...", + "88": "Guarda los รกtomos seleccionados (o todas las estructuras de la pรกgina) como un archivo SMARTS (.sma).", + "89": "Estereoquรญmica mejorada", + "90": "Consulta", + "91": "Objeto", + "92": "Selecciona antes las estructuras o el texto a los que asignar una funciรณn.", + "93": "Definir funciones en la reacciรณn...", + "94": "Define la funciรณn de las estructuras o el texto seleccionados en el paso de reacciรณn seleccionado (reactivo, producto, agente, condiciรณn o ninguna) y marca las funciones del paso como definidas a mano, en un solo paso de deshacer. Sin role abre un cuadro de diรกlogo con los miembros del paso y la selecciรณn.", + "95": "Funciรณn que asignar a los objetos; omรญtela para abrir el cuadro de diรกlogo", + "96": "Ids de los objetos que cambiar; por defecto, la selecciรณn", + "97": "No se pudieron definir las funciones de la reacciรณn", + "98": "H restante", + "99": "Abreviatura", + "100": "Etiqueta", + "101": "Buscar en la biblioteca", + "102": "No se pudo cargar la biblioteca de abreviaturas. Aun asรญ puedes escribir una etiqueta.", + "103": "Ninguna abreviatura coincide. Se usa la etiqueta que escribas tal cual.", + "104": "Propiedades", + "105": "Lista de รกtomos", + "106": "Haz clic en los elementos de la tabla para aรฑadirlos.", + "107": "Borrar consulta", + "108": "Aplicar", + "109": "Quitar", + "110": "Sin consulta", + "111": "[M+Na]+", + "112": "Patrรณn isotรณpico", + "113": "Enumerar grupos R", + "114": "Copiar SMILES", + "115": "Se copiรณ el SMILES de todas las estructuras", + "116": "Si", + "117": "Cualquier enlace", + "118": "Simple o doble", + "119": "Simple o aromรกtico", + "120": "Doble o aromรกtico", + "121": "Anillo o cadena", + "122": "En un anillo", + "123": "En una cadena", + "124": "Cualquier รกtomo (A)", + "125": "Cualquier heteroรกtomo (Q)", + "126": "Cualquier halรณgeno (X)", + "127": "Cualquier metal (M)", + "128": "Definir topologรญa del enlace", + "129": "Enlace de consulta", + "130": "Definir consulta de รกtomo", + "131": "Aromรกtico", + "132": "Alifรกtico", + "133": "Insaturado", + "134": "Sustituciรณn como se dibujรณ", + "135": "Enlaces de anillo como se dibujaron", + "136": "Borrar consulta de รกtomo", + "137": "Consulta de รกtomo", + "138": "Definiciรณn de grupo R", + "139": "Grupo R", + "140": "Miembros", + "141": "Dibuja cada miembro como una estructura propia con un punto de uniรณn (*) y vuelve a abrir este cuadro de diรกlogo.", + "142": "Ocurrencia", + "143": "H restante (las posiciones sin sustituir son hidrรณgeno)", + "144": "Si estรก presente, entonces", + "145": "Quitar definiciรณn", + "146": "Agente", + "147": "Condiciรณn", + "148": "Borrar", + "149": "Aรฑadir los centros seleccionados a este grupo", + "150": "Comprobar de nuevo", + "151": "Comprobando...", + "152": "Corregir", + "153": "Seleccionar en el lienzo" +} From 558056bed1266ff7e4486a2d5657d4ae860f82d5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:38 -0500 Subject: [PATCH 240/279] feat(i18n): translate the stereo, query and analysis strings into Spanish (Mexico) (0.6.0) Adds part06 for the stereochemistry, query, R-group, structure check and analysis strings. --- frontend/src/i18n/locales/es-MX/part06.json | 156 ++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/es-MX/part06.json diff --git a/frontend/src/i18n/locales/es-MX/part06.json b/frontend/src/i18n/locales/es-MX/part06.json new file mode 100644 index 00000000..019f1127 --- /dev/null +++ b/frontend/src/i18n/locales/es-MX/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Orden de Hill con carga, abreviaturas expandidas", + "1": "Pesos atรณmicos estรกndar (valores convencionales de la CIAAW)", + "2": "Masa monoisotรณpica a partir del isรณtopo mรกs abundante de cada elemento", + "3": "Masa exacta dividida entre la carga absoluta, con correcciรณn de la masa del electrรณn", + "4": "Porcentaje en masa de cada elemento, con dos decimales", + "5": "Contribuciones atรณmicas (Wildman and Crippen 1999)", + "6": "รrea de superficie polar topolรณgica, fragmentos de N y O (Ertl 2000)", + "7": "Refractividad molar", + "8": "Donadores de enlace de hidrรณgeno", + "9": "Conteo de Lipinski: grupos N-H y O-H", + "10": "Aceptores de enlace de hidrรณgeno", + "11": "Conteo de Lipinski: รกtomos de N y O", + "12": "Enlaces rotables", + "13": "Enlaces simples fuera de anillos entre รกtomos pesados no terminales, excluido el enlace C-N de las amidas", + "14": "Regla de los cinco de Lipinski", + "15": "MW mรกximo 500, cLogP mรกximo 5, donadores mรกximo 5, aceptores mรกximo 10", + "16": "HBD", + "17": "HBA", + "18": "Cumple (0 infracciones)", + "19": "Primero selecciona uno o mรกs รกtomos", + "20": "Primero selecciona uno o mรกs enlaces", + "21": "No hay hidrรณgenos implรญcitos que agregar.", + "22": "No hay hidrรณgenos explรญcitos que quitar.", + "23": "Selecciona una abreviatura, como Ph u OTs, para expandirla.", + "24": "Selecciona los รกtomos de un grupo de una sola estructura para contraerlos.", + "25": "Selecciona el grupo que quieres contraer, sin el รกtomo al que estรก unido.", + "26": "Contraer", + "27": "Elige una abreviatura de la biblioteca o escribe una etiqueta nueva para los รกtomos seleccionados.", + "28": "Definir grupo estereoquรญmico", + "29": "Borrar grupo estereoquรญmico", + "30": "Definir lista de รกtomos", + "31": "Borrar lista de รกtomos", + "32": "Definir enlace de consulta", + "33": "Borrar consulta de enlace", + "34": "Selecciona el รกtomo que lleva el grupo R.", + "35": "1 punto de uniรณn", + "36": "Definir grupo R", + "37": "Quitar definiciรณn de grupo R", + "38": "Asignar cuรฑas", + "39": "Las cuรฑas ya coinciden con los estereocentros.", + "40": "Las estructuras seleccionadas", + "41": "Todas las estructuras de esta pรกgina", + "42": "Corregir estructura", + "43": "No hay ninguna estructura que analizar.", + "44": "Anรกlisis copiado", + "45": "No se pudo copiar al portapapeles", + "46": "Buscar subestructura", + "47": "SMARTS", + "48": "Primero dibuja en esta pรกgina las estructuras en las que se buscarรก.", + "49": "solo los primeros resultados", + "50": "No hay coincidencias en esta pรกgina.", + "51": "Primero dibuja una estructura con รกtomos de grupo R y define sus grupos R.", + "52": "No hay ninguna estructura que escribir como SMARTS.", + "53": "Guardar archivos SMARTS llegarรก con los formatos de archivo en la 0.7.0; en su lugar se copiรณ el SMARTS.", + "54": "Dibuja cada hidrรณgeno implรญcito de los รกtomos seleccionados (o de todas las estructuras de la pรกgina) como un รกtomo de H explรญcito colocado por el motor, en un solo paso de deshacer.", + "55": "Quita los รกtomos de H explรญcitos de la selecciรณn (o de la pรกgina), conservando los hidrรณgenos que llevan estereoquรญmica, un isรณtopo, una carga o un nรบmero de mapeo, o que forman un puente entre dos รกtomos.", + "56": "Sustituye los รกtomos de abreviatura seleccionados (o todas las abreviaturas de la pรกgina) por su estructura completa, acomodada a lo largo del enlace de uniรณn.", + "57": "Contraer abreviatura...", + "58": "Contrae el grupo de รกtomos seleccionado en un solo รกtomo de abreviatura con la etiqueta que elijas o escribas.", + "59": "Muestra u oculta las etiquetas R, S, E y Z junto a los estereocentros y los dobles enlaces estereoquรญmicos.", + "60": "Mostrar grupos de estereoquรญmica mejorada", + "61": "Muestra u oculta las etiquetas de grupo abs, and y or junto a los estereocentros mientras las etiquetas de estereoquรญmica estรกn activadas.", + "62": "Mostrar caracterรญsticas de consulta", + "63": "Muestra u oculta las marcas de lista de รกtomos, enlace de consulta y grupo R en el lienzo.", + "64": "Coloca los estereocentros seleccionados en un grupo de estereoquรญmica mejorada: abs, and n u or n. Sin n se crea un grupo and u or nuevo.", + "65": "abs, and u or", + "66": "Nรบmero de grupo para and y or", + "67": "Absoluto (abs)", + "68": "Nuevo grupo AND", + "69": "Nuevo grupo OR", + "70": "Grupo estereoquรญmico...", + "71": "Lista de รกtomos...", + "72": "Convierte los รกtomos seleccionados en una consulta de lista de รกtomos o de lista de exclusiรณn elegida en la tabla periรณdica.", + "73": "Convierte los enlaces seleccionados en enlaces de consulta: any, single_or_double, single_or_aromatic o double_or_aromatic; omite query para borrar.", + "74": "El tipo de enlace de consulta", + "75": "Definir grupo R...", + "76": "Convierte el รกtomo seleccionado en una etiqueta de grupo R y define sus miembros, ocurrencia, H restante y la condiciรณn si-entonces.", + "77": "Deja que el motor elija enlaces en cuรฑa y en cuรฑa discontinua que expresen sin ambigรผedad los estereocentros de la selecciรณn (o de la pรกgina).", + "78": "Enlista los problemas de valencia, estereoquรญmica, geometrรญa y etiquetas de la selecciรณn (o de la pรกgina) en un panel cuyas filas seleccionan los รกtomos.", + "79": "Abre el panel de anรกlisis con las propiedades calculadas de la selecciรณn o de la pรกgina.", + "80": "Copia como texto la fรณrmula, las masas, el anรกlisis elemental y las propiedades calculadas con sus mรฉtodos.", + "81": "Buscar subestructura...", + "82": "Selecciona todas las coincidencias de los รกtomos seleccionados (o de un patrรณn SMARTS) en las demรกs estructuras de la pรกgina.", + "83": "Enumerar grupos R...", + "84": "Enlista todas las estructuras que representa el esqueleto de Markush seleccionado (o el primero de la pรกgina), con fรณrmula y SMILES, hasta 1000; la lista se puede copiar.", + "85": "Copiar como SMARTS", + "86": "Copia los รกtomos seleccionados (o todas las estructuras de la pรกgina) como SMARTS, con listas de รกtomos, รกtomos genรฉricos, enlaces de consulta y las demรกs caracterรญsticas de consulta.", + "87": "Exportar SMARTS...", + "88": "Guarda los รกtomos seleccionados (o todas las estructuras de la pรกgina) como un archivo SMARTS (.sma).", + "89": "Estereoquรญmica mejorada", + "90": "Consulta", + "91": "Objeto", + "92": "Primero selecciona las estructuras o el texto a los que asignarรกs una funciรณn.", + "93": "Definir funciones en la reacciรณn...", + "94": "Define la funciรณn de las estructuras o el texto seleccionados en el paso de reacciรณn seleccionado (reactivo, producto, agente, condiciรณn o ninguna) y marca las funciones del paso como definidas a mano, en un solo paso de deshacer. Sin role abre un cuadro de diรกlogo con los miembros del paso y la selecciรณn.", + "95": "Funciรณn que se asignarรก a los objetos; omรญtela para abrir el cuadro de diรกlogo", + "96": "Ids de los objetos que se cambiarรกn; por defecto, la selecciรณn", + "97": "No se pudieron definir las funciones de la reacciรณn", + "98": "H restante", + "99": "Abreviatura", + "100": "Etiqueta", + "101": "Buscar en la biblioteca", + "102": "No se pudo cargar la biblioteca de abreviaturas. Aun asรญ puedes escribir una etiqueta.", + "103": "Ninguna abreviatura coincide. Se usa tal cual la etiqueta que escribas.", + "104": "Propiedades", + "105": "Lista de รกtomos", + "106": "Haz clic en los elementos de la tabla para agregarlos.", + "107": "Borrar consulta", + "108": "Aplicar", + "109": "Quitar", + "110": "Sin consulta", + "111": "[M+Na]+", + "112": "Patrรณn isotรณpico", + "113": "Enumerar grupos R", + "114": "Copiar SMILES", + "115": "Se copiรณ el SMILES de todas las estructuras", + "116": "Si", + "117": "Cualquier enlace", + "118": "Simple o doble", + "119": "Simple o aromรกtico", + "120": "Doble o aromรกtico", + "121": "Anillo o cadena", + "122": "En un anillo", + "123": "En una cadena", + "124": "Cualquier รกtomo (A)", + "125": "Cualquier heteroรกtomo (Q)", + "126": "Cualquier halรณgeno (X)", + "127": "Cualquier metal (M)", + "128": "Definir topologรญa del enlace", + "129": "Enlace de consulta", + "130": "Definir consulta de รกtomo", + "131": "Aromรกtico", + "132": "Alifรกtico", + "133": "Insaturado", + "134": "Sustituciรณn como se dibujรณ", + "135": "Enlaces de anillo como se dibujaron", + "136": "Borrar consulta de รกtomo", + "137": "Consulta de รกtomo", + "138": "Definiciรณn de grupo R", + "139": "Grupo R", + "140": "Miembros", + "141": "Dibuja cada miembro como una estructura propia con un punto de uniรณn (*) y vuelve a abrir este cuadro de diรกlogo.", + "142": "Ocurrencia", + "143": "H restante (las posiciones sin sustituir son hidrรณgeno)", + "144": "Si estรก presente, entonces", + "145": "Quitar definiciรณn", + "146": "Agente", + "147": "Condiciรณn", + "148": "Borrar", + "149": "Agregar los centros seleccionados a este grupo", + "150": "Volver a comprobar", + "151": "Comprobando...", + "152": "Corregir", + "153": "Seleccionar en el lienzo" +} From 0e475f454382c249629deca3a04132de4220444c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:38 -0500 Subject: [PATCH 241/279] feat(i18n): translate the stereo, query and analysis strings into Portuguese (Brazil) (0.6.0) Adds part06 for the stereochemistry, query, R-group, structure check and analysis strings. --- frontend/src/i18n/locales/pt-BR/part06.json | 156 ++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/pt-BR/part06.json diff --git a/frontend/src/i18n/locales/pt-BR/part06.json b/frontend/src/i18n/locales/pt-BR/part06.json new file mode 100644 index 00000000..b63b2683 --- /dev/null +++ b/frontend/src/i18n/locales/pt-BR/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Ordem de Hill com carga, abreviaรงรตes expandidas", + "1": "Pesos atรดmicos padrรฃo (valores convencionais da CIAAW)", + "2": "Massa monoisotรณpica a partir do isรณtopo mais abundante de cada elemento", + "3": "Massa exata dividida pela carga absoluta, com correรงรฃo da massa do elรฉtron", + "4": "Porcentagem em massa de cada elemento, com duas casas decimais", + "5": "Contribuiรงรตes atรดmicas (Wildman and Crippen 1999)", + "6": "รrea de superfรญcie polar topolรณgica, fragmentos de N e O (Ertl 2000)", + "7": "Refratividade molar", + "8": "Doadores de ligaรงรฃo de hidrogรชnio", + "9": "Contagem de Lipinski: grupos N-H e O-H", + "10": "Aceptores de ligaรงรฃo de hidrogรชnio", + "11": "Contagem de Lipinski: รกtomos de N e O", + "12": "Ligaรงรตes rotacionรกveis", + "13": "Ligaรงรตes simples fora de anรฉis entre รกtomos pesados nรฃo terminais, excluรญda a ligaรงรฃo C-N das amidas", + "14": "Regra dos cinco de Lipinski", + "15": "MW no mรกximo 500, cLogP no mรกximo 5, doadores no mรกximo 5, aceptores no mรกximo 10", + "16": "HBD", + "17": "HBA", + "18": "Aprovada (0 violaรงรตes)", + "19": "Selecione antes um ou mais รกtomos", + "20": "Selecione antes uma ou mais ligaรงรตes", + "21": "Nรฃo hรก hidrogรชnios implรญcitos para adicionar.", + "22": "Nรฃo hรก hidrogรชnios explรญcitos para remover.", + "23": "Selecione uma abreviaรงรฃo, como Ph ou OTs, para expandir.", + "24": "Selecione os รกtomos de um grupo de uma รบnica estrutura para recolher.", + "25": "Selecione o grupo a recolher, sem o รกtomo ao qual ele estรก ligado.", + "26": "Recolher", + "27": "Escolha uma abreviaรงรฃo da biblioteca ou digite um novo rรณtulo para os รกtomos selecionados.", + "28": "Definir Grupo Estereoquรญmico", + "29": "Limpar Grupo Estereoquรญmico", + "30": "Definir Lista de รtomos", + "31": "Limpar Lista de รtomos", + "32": "Definir Ligaรงรฃo de Consulta", + "33": "Limpar Consulta de Ligaรงรฃo", + "34": "Selecione o รกtomo que carrega o grupo R.", + "35": "1 ponto de ligaรงรฃo", + "36": "Definir Grupo R", + "37": "Remover Definiรงรฃo de Grupo R", + "38": "Atribuir Cunhas", + "39": "As cunhas jรก correspondem aos estereocentros.", + "40": "As estruturas selecionadas", + "41": "Todas as estruturas desta pรกgina", + "42": "Corrigir Estrutura", + "43": "Nรฃo hรก nenhuma estrutura para analisar.", + "44": "Anรกlise copiada", + "45": "Nรฃo foi possรญvel copiar para a รกrea de transferรชncia", + "46": "Localizar Subestrutura", + "47": "SMARTS", + "48": "Desenhe antes as estruturas a pesquisar nesta pรกgina.", + "49": "somente os primeiros resultados", + "50": "Nenhuma correspondรชncia nesta pรกgina.", + "51": "Desenhe antes uma estrutura com รกtomos de grupo R e defina seus grupos R.", + "52": "Nรฃo hรก nenhuma estrutura para escrever como SMARTS.", + "53": "Salvar arquivos SMARTS chega com os formatos de arquivo na 0.7.0; o SMARTS foi copiado no lugar.", + "54": "Desenha cada hidrogรชnio implรญcito dos รกtomos selecionados (ou de todas as estruturas da pรกgina) como um รกtomo de H explรญcito posicionado pelo motor, em uma รบnica etapa de desfazer.", + "55": "Remove os รกtomos de H explรญcitos da seleรงรฃo (ou da pรกgina), mantendo os hidrogรชnios que carregam estereoquรญmica, um isรณtopo, uma carga ou um nรบmero de mapeamento, ou que formam uma ponte entre dois รกtomos.", + "56": "Substitui os รกtomos de abreviaรงรฃo selecionados (ou todas as abreviaรงรตes da pรกgina) por sua estrutura completa, disposta ao longo da ligaรงรฃo de conexรฃo.", + "57": "Recolher Abreviaรงรฃo...", + "58": "Recolhe o grupo de รกtomos selecionado em um รบnico รกtomo de abreviaรงรฃo com o rรณtulo que vocรช escolher ou digitar.", + "59": "Mostra ou oculta os rรณtulos R, S, E e Z ao lado dos estereocentros e das ligaรงรตes duplas estereoquรญmicas.", + "60": "Mostrar Grupos de Estereoquรญmica Aprimorada", + "61": "Mostra ou oculta os rรณtulos de grupo abs, and e or ao lado dos estereocentros enquanto os rรณtulos de estereoquรญmica estรฃo ativados.", + "62": "Mostrar Recursos de Consulta", + "63": "Mostra ou oculta as marcas de lista de รกtomos, ligaรงรฃo de consulta e grupo R na tela.", + "64": "Coloca os estereocentros selecionados em um grupo de estereoquรญmica aprimorada: abs, and n ou or n. Sem n, รฉ criado um novo grupo and ou or.", + "65": "abs, and ou or", + "66": "Nรบmero do grupo para and e or", + "67": "Absoluto (abs)", + "68": "Novo Grupo AND", + "69": "Novo Grupo OR", + "70": "Grupo Estereoquรญmico...", + "71": "Lista de รtomos...", + "72": "Transforma os รกtomos selecionados em uma consulta de lista de รกtomos ou de lista de exclusรฃo escolhida na tabela periรณdica.", + "73": "Transforma as ligaรงรตes selecionadas em ligaรงรตes de consulta: any, single_or_double, single_or_aromatic ou double_or_aromatic; omita query para limpar.", + "74": "O tipo de ligaรงรฃo de consulta", + "75": "Definir Grupo R...", + "76": "Transforma o รกtomo selecionado em um rรณtulo de grupo R e define seus membros, ocorrรชncia, H restante e a condiรงรฃo se-entรฃo.", + "77": "Permite que o motor escolha ligaรงรตes em cunha e em cunha tracejada que expressem sem ambiguidade os estereocentros da seleรงรฃo (ou da pรกgina).", + "78": "Lista os problemas de valรชncia, estereoquรญmica, geometria e rรณtulos da seleรงรฃo (ou da pรกgina) em um painel cujas linhas selecionam os รกtomos.", + "79": "Abre o painel de anรกlise com as propriedades calculadas da seleรงรฃo ou da pรกgina.", + "80": "Copia como texto a fรณrmula, as massas, a anรกlise elementar e as propriedades calculadas com seus mรฉtodos.", + "81": "Localizar Subestrutura...", + "82": "Seleciona todas as correspondรชncias dos รกtomos selecionados (ou de um padrรฃo SMARTS) nas outras estruturas da pรกgina.", + "83": "Enumerar Grupos R...", + "84": "Lista todas as estruturas que o esqueleto de Markush selecionado (ou o primeiro da pรกgina) representa, com fรณrmula e SMILES, atรฉ 1000; a lista pode ser copiada.", + "85": "Copiar como SMARTS", + "86": "Copia os รกtomos selecionados (ou todas as estruturas da pรกgina) como SMARTS, com listas de รกtomos, รกtomos genรฉricos, ligaรงรตes de consulta e os demais recursos de consulta.", + "87": "Exportar SMARTS...", + "88": "Salva os รกtomos selecionados (ou todas as estruturas da pรกgina) como um arquivo SMARTS (.sma).", + "89": "Estereoquรญmica Aprimorada", + "90": "Consulta", + "91": "Objeto", + "92": "Selecione antes as estruturas ou o texto aos quais atribuir um papel.", + "93": "Definir Papรฉis na Reaรงรฃo...", + "94": "Define o papel das estruturas ou do texto selecionados na etapa de reaรงรฃo selecionada (reagente, produto, agente, condiรงรฃo ou nenhum) e marca os papรฉis da etapa como definidos manualmente, em uma รบnica etapa de desfazer. Sem role, abre uma caixa de diรกlogo com os membros da etapa e a seleรงรฃo.", + "95": "Papel a atribuir aos objetos; omita para abrir a caixa de diรกlogo", + "96": "Ids dos objetos a alterar; por padrรฃo, a seleรงรฃo", + "97": "Nรฃo foi possรญvel definir os papรฉis da reaรงรฃo", + "98": "H restante", + "99": "Abreviaรงรฃo", + "100": "Rรณtulo", + "101": "Pesquisar na biblioteca", + "102": "Nรฃo foi possรญvel carregar a biblioteca de abreviaรงรตes. Vocรช ainda pode digitar um rรณtulo.", + "103": "Nenhuma abreviaรงรฃo corresponde. O rรณtulo digitado รฉ usado como estรก.", + "104": "Propriedades", + "105": "Lista de รtomos", + "106": "Clique nos elementos da tabela para adicionรก-los.", + "107": "Limpar Consulta", + "108": "Aplicar", + "109": "Remover", + "110": "Sem consulta", + "111": "[M+Na]+", + "112": "Padrรฃo isotรณpico", + "113": "Enumerar Grupos R", + "114": "Copiar SMILES", + "115": "SMILES de todas as estruturas copiado", + "116": "Si", + "117": "Qualquer Ligaรงรฃo", + "118": "Simples ou Dupla", + "119": "Simples ou Aromรกtica", + "120": "Dupla ou Aromรกtica", + "121": "Anel ou Cadeia", + "122": "Em um Anel", + "123": "Em uma Cadeia", + "124": "Qualquer รtomo (A)", + "125": "Qualquer Heteroรกtomo (Q)", + "126": "Qualquer Halogรชnio (X)", + "127": "Qualquer Metal (M)", + "128": "Definir Topologia da Ligaรงรฃo", + "129": "Ligaรงรฃo de Consulta", + "130": "Definir Consulta de รtomo", + "131": "Aromรกtico", + "132": "Alifรกtico", + "133": "Insaturado", + "134": "Substituiรงรฃo como Desenhada", + "135": "Ligaรงรตes de Anel como Desenhadas", + "136": "Limpar Consulta de รtomo", + "137": "Consulta de รtomo", + "138": "Definiรงรฃo de Grupo R", + "139": "Grupo R", + "140": "Membros", + "141": "Desenhe cada membro como uma estrutura prรณpria com um ponto de ligaรงรฃo (*) e abra esta caixa de diรกlogo novamente.", + "142": "Ocorrรชncia", + "143": "H restante (as posiรงรตes nรฃo substituรญdas sรฃo hidrogรชnio)", + "144": "Se presente, entรฃo", + "145": "Remover Definiรงรฃo", + "146": "Agente", + "147": "Condiรงรฃo", + "148": "Limpar", + "149": "Adicionar os centros selecionados a este grupo", + "150": "Verificar Novamente", + "151": "Verificando...", + "152": "Corrigir", + "153": "Selecionar na tela" +} From d04b4aae0318b161e6c9ceea4417018636a97d7c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:38 -0500 Subject: [PATCH 242/279] feat(i18n): translate the stereo, query and analysis strings into French (0.6.0) Adds part06 for the stereochemistry, query, R-group, structure check and analysis strings. --- frontend/src/i18n/locales/fr/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/fr/part06.json diff --git a/frontend/src/i18n/locales/fr/part06.json b/frontend/src/i18n/locales/fr/part06.json new file mode 100644 index 00000000..df67bebf --- /dev/null +++ b/frontend/src/i18n/locales/fr/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Ordre de Hill avec charge, abrรฉviations dรฉveloppรฉes", + "1": "Masses atomiques standard (valeurs conventionnelles de la CIAAW)", + "2": "Masse monoisotopique ร  partir de lโ€™isotope le plus abondant de chaque รฉlรฉment", + "3": "Masse exacte divisรฉe par la charge absolue, avec correction de la masse de lโ€™รฉlectron", + "4": "Pourcentage massique de chaque รฉlรฉment, avec deux dรฉcimales", + "5": "Contributions atomiques (Wildman and Crippen 1999)", + "6": "Surface polaire topologique, fragments N et O (Ertl 2000)", + "7": "Rรฉfractivitรฉ molaire", + "8": "Donneurs de liaison hydrogรจne", + "9": "Comptage de Lipinski : groupes N-H et O-H", + "10": "Accepteurs de liaison hydrogรจne", + "11": "Comptage de Lipinski : atomes N et O", + "12": "Liaisons rotatives", + "13": "Liaisons simples hors cycle entre atomes lourds non terminaux, liaison C-N des amides exclue", + "14": "Rรจgle de cinq de Lipinski", + "15": "MW au plus 500, cLogP au plus 5, donneurs au plus 5, accepteurs au plus 10", + "16": "HBD", + "17": "HBA", + "18": "Conforme (0 violation)", + "19": "Sรฉlectionnez dโ€™abord un ou plusieurs atomes", + "20": "Sรฉlectionnez dโ€™abord une ou plusieurs liaisons", + "21": "Aucun hydrogรจne implicite ร  ajouter.", + "22": "Aucun hydrogรจne explicite ร  retirer.", + "23": "Sรฉlectionnez une abrรฉviation, comme Ph ou OTs, ร  dรฉvelopper.", + "24": "Sรฉlectionnez les atomes dโ€™un groupe dans une seule structure pour le rรฉduire.", + "25": "Sรฉlectionnez le groupe ร  rรฉduire, sans lโ€™atome auquel il est attachรฉ.", + "26": "Rรฉduire", + "27": "Choisissez une abrรฉviation de la bibliothรจque ou saisissez une nouvelle รฉtiquette pour les atomes sรฉlectionnรฉs.", + "28": "Dรฉfinir le groupe stรฉrรฉochimique", + "29": "Effacer le groupe stรฉrรฉochimique", + "30": "Dรฉfinir la liste dโ€™atomes", + "31": "Effacer la liste dโ€™atomes", + "32": "Dรฉfinir la liaison de requรชte", + "33": "Effacer la requรชte de liaison", + "34": "Sรฉlectionnez lโ€™atome qui porte le groupe R.", + "35": "1 point dโ€™attache", + "36": "Dรฉfinir le groupe R", + "37": "Retirer la dรฉfinition du groupe R", + "38": "Attribuer les coins", + "39": "Les coins correspondent dรฉjร  aux centres stรฉrรฉogรจnes.", + "40": "Les structures sรฉlectionnรฉes", + "41": "Toutes les structures de cette page", + "42": "Corriger la structure", + "43": "Aucune structure ร  analyser.", + "44": "Analyse copiรฉe", + "45": "Impossible de copier dans le presse-papiers", + "46": "Rechercher une sous-structure", + "47": "SMARTS", + "48": "Dessinez dโ€™abord les structures ร  rechercher sur cette page.", + "49": "premiers rรฉsultats seulement", + "50": "Aucune correspondance sur cette page.", + "51": "Dessinez dโ€™abord une structure avec des atomes de groupe R et dรฉfinissez ses groupes R.", + "52": "Aucune structure ร  รฉcrire en SMARTS.", + "53": "Lโ€™enregistrement de fichiers SMARTS arrivera avec les formats de fichier dans la 0.7.0 ; le SMARTS a รฉtรฉ copiรฉ ร  la place.", + "54": "Dessine chaque hydrogรจne implicite des atomes sรฉlectionnรฉs (ou de toutes les structures de la page) comme un atome H explicite placรฉ par le moteur, en une seule รฉtape dโ€™annulation.", + "55": "Retire les atomes H explicites de la sรฉlection (ou de la page), en gardant les hydrogรจnes qui portent une stรฉrรฉochimie, un isotope, une charge ou un numรฉro de mappage, ou qui relient deux atomes.", + "56": "Remplace les atomes dโ€™abrรฉviation sรฉlectionnรฉs (ou toutes les abrรฉviations de la page) par leur structure complรจte, disposรฉe le long de la liaison dโ€™attache.", + "57": "Rรฉduire lโ€™abrรฉviation...", + "58": "Rรฉduit le groupe dโ€™atomes sรฉlectionnรฉ en un seul atome dโ€™abrรฉviation avec lโ€™รฉtiquette que vous choisissez ou saisissez.", + "59": "Affiche ou masque les รฉtiquettes R, S, E et Z ร  cรดtรฉ des centres stรฉrรฉogรจnes et des doubles liaisons stรฉrรฉochimiques.", + "60": "Afficher les groupes de stรฉrรฉochimie amรฉliorรฉe", + "61": "Affiche ou masque les รฉtiquettes de groupe abs, and et or ร  cรดtรฉ des centres stรฉrรฉogรจnes lorsque les รฉtiquettes de stรฉrรฉochimie sont affichรฉes.", + "62": "Afficher les caractรฉristiques de requรชte", + "63": "Affiche ou masque les marques de liste dโ€™atomes, de liaison de requรชte et de groupe R sur le canevas.", + "64": "Place les centres stรฉrรฉogรจnes sรฉlectionnรฉs dans un groupe de stรฉrรฉochimie amรฉliorรฉe : abs, and n ou or n. Sans n, un nouveau groupe and ou or est crรฉรฉ.", + "65": "abs, and ou or", + "66": "Numรฉro de groupe pour and et or", + "67": "Absolu (abs)", + "68": "Nouveau groupe AND", + "69": "Nouveau groupe OR", + "70": "Groupe stรฉrรฉochimique...", + "71": "Liste dโ€™atomes...", + "72": "Transforme les atomes sรฉlectionnรฉs en requรชte de liste dโ€™atomes ou de liste dโ€™exclusion choisie dans le tableau pรฉriodique.", + "73": "Transforme les liaisons sรฉlectionnรฉes en liaisons de requรชte : any, single_or_double, single_or_aromatic ou double_or_aromatic ; omettez query pour effacer.", + "74": "Le type de liaison de requรชte", + "75": "Dรฉfinir le groupe R...", + "76": "Fait de lโ€™atome sรฉlectionnรฉ une รฉtiquette de groupe R et dรฉfinit ses membres, son occurrence, le H rรฉsiduel et la condition si-alors.", + "77": "Laisse le moteur choisir des liaisons en coin plein et en coin hachurรฉ qui expriment sans ambiguรฏtรฉ les centres stรฉrรฉogรจnes de la sรฉlection (ou de la page).", + "78": "Liste les problรจmes de valence, de stรฉrรฉochimie, de gรฉomรฉtrie et dโ€™รฉtiquettes de la sรฉlection (ou de la page) dans un panneau dont les lignes sรฉlectionnent les atomes.", + "79": "Ouvre le panneau dโ€™analyse avec les propriรฉtรฉs calculรฉes de la sรฉlection ou de la page.", + "80": "Copie sous forme de texte la formule, les masses, lโ€™analyse รฉlรฉmentaire et les propriรฉtรฉs calculรฉes avec leurs mรฉthodes.", + "81": "Rechercher une sous-structure...", + "82": "Sรฉlectionne toutes les correspondances des atomes sรฉlectionnรฉs (ou dโ€™un motif SMARTS) dans les autres structures de la page.", + "83": "ร‰numรฉrer les groupes R...", + "84": "Liste toutes les structures que reprรฉsente le squelette de Markush sรฉlectionnรฉ (ou le premier de la page), avec formule et SMILES, jusquโ€™ร  1000 ; la liste peut รชtre copiรฉe.", + "85": "Copier en SMARTS", + "86": "Copie les atomes sรฉlectionnรฉs (ou toutes les structures de la page) en SMARTS, avec les listes dโ€™atomes, les atomes gรฉnรฉriques, les liaisons de requรชte et les autres caractรฉristiques de requรชte.", + "87": "Exporter en SMARTS...", + "88": "Enregistre les atomes sรฉlectionnรฉs (ou toutes les structures de la page) dans un fichier SMARTS (.sma).", + "89": "Stรฉrรฉochimie amรฉliorรฉe", + "90": "Requรชte", + "91": "Objet", + "92": "Sรฉlectionnez dโ€™abord les structures ou le texte auxquels attribuer un rรดle.", + "93": "Dรฉfinir les rรดles dans la rรฉaction...", + "94": "Dรฉfinit le rรดle des structures ou du texte sรฉlectionnรฉs dans lโ€™รฉtape de rรฉaction sรฉlectionnรฉe (rรฉactif, produit, agent, condition ou aucun) et marque les rรดles de lโ€™รฉtape comme dรฉfinis ร  la main, en une seule รฉtape dโ€™annulation. Sans role, ouvre une boรฎte de dialogue qui liste les membres de lโ€™รฉtape et la sรฉlection.", + "95": "Rรดle ร  attribuer aux objets ; omettez-le pour ouvrir la boรฎte de dialogue", + "96": "Id des objets ร  modifier ; par dรฉfaut, la sรฉlection", + "97": "Impossible de dรฉfinir les rรดles de la rรฉaction", + "98": "H rรฉsiduel", + "99": "Abrรฉviation", + "100": "ร‰tiquette", + "101": "Rechercher dans la bibliothรจque", + "102": "Impossible de charger la bibliothรจque dโ€™abrรฉviations. Vous pouvez quand mรชme saisir une รฉtiquette.", + "103": "Aucune abrรฉviation ne correspond. Lโ€™รฉtiquette saisie est utilisรฉe telle quelle.", + "104": "Propriรฉtรฉs", + "105": "Liste dโ€™atomes", + "106": "Cliquez sur les รฉlรฉments du tableau pour les ajouter.", + "107": "Effacer la requรชte", + "108": "Appliquer", + "109": "Retirer", + "110": "Aucune requรชte", + "111": "[M+Na]+", + "112": "Motif isotopique", + "113": "ร‰numรฉrer les groupes R", + "114": "Copier le SMILES", + "115": "SMILES de toutes les structures copiรฉ", + "116": "Si", + "117": "Nโ€™importe quelle liaison", + "118": "Simple ou double", + "119": "Simple ou aromatique", + "120": "Double ou aromatique", + "121": "Cycle ou chaรฎne", + "122": "Dans un cycle", + "123": "Dans une chaรฎne", + "124": "Nโ€™importe quel atome (A)", + "125": "Nโ€™importe quel hรฉtรฉroatome (Q)", + "126": "Nโ€™importe quel halogรจne (X)", + "127": "Nโ€™importe quel mรฉtal (M)", + "128": "Dรฉfinir la topologie de la liaison", + "129": "Liaison de requรชte", + "130": "Dรฉfinir la requรชte dโ€™atome", + "131": "Aromatique", + "132": "Aliphatique", + "133": "Insaturรฉ", + "134": "Substitution comme dessinรฉe", + "135": "Liaisons de cycle comme dessinรฉes", + "136": "Effacer la requรชte dโ€™atome", + "137": "Requรชte dโ€™atome", + "138": "Dรฉfinition du groupe R", + "139": "Groupe R", + "140": "Membres", + "141": "Dessinez chaque membre comme sa propre structure avec un point dโ€™attache (*), puis rouvrez cette boรฎte de dialogue.", + "142": "Occurrence", + "143": "H rรฉsiduel (les positions non substituรฉes sont de lโ€™hydrogรจne)", + "144": "Si prรฉsent, alors", + "145": "Retirer la dรฉfinition", + "146": "Agent", + "147": "Condition", + "148": "Effacer", + "149": "Ajouter les centres sรฉlectionnรฉs ร  ce groupe", + "150": "Vรฉrifier ร  nouveau", + "151": "Vรฉrification...", + "152": "Corriger", + "153": "Sรฉlectionner sur le canevas" +} From 6d591feb3eb99155675192d63a61289908134002 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:38 -0500 Subject: [PATCH 243/279] feat(i18n): translate the stereo, query and analysis strings into French (Canada) (0.6.0) Adds part06 for the stereochemistry, query, R-group, structure check and analysis strings. --- frontend/src/i18n/locales/fr-CA/part06.json | 156 ++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/fr-CA/part06.json diff --git a/frontend/src/i18n/locales/fr-CA/part06.json b/frontend/src/i18n/locales/fr-CA/part06.json new file mode 100644 index 00000000..f7ca5ca8 --- /dev/null +++ b/frontend/src/i18n/locales/fr-CA/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Ordre de Hill avec charge, abrรฉviations dรฉveloppรฉes", + "1": "Masses atomiques standard (valeurs conventionnelles de la CIAAW)", + "2": "Masse monoisotopique ร  partir de lโ€™isotope le plus abondant de chaque รฉlรฉment", + "3": "Masse exacte divisรฉe par la charge absolue, avec correction de la masse de lโ€™รฉlectron", + "4": "Pourcentage massique de chaque รฉlรฉment, avec deux dรฉcimales", + "5": "Contributions atomiques (Wildman and Crippen 1999)", + "6": "Surface polaire topologique, fragments N et O (Ertl 2000)", + "7": "Rรฉfractivitรฉ molaire", + "8": "Donneurs de liaison hydrogรจne", + "9": "Comptage de Lipinski : groupes N-H et O-H", + "10": "Accepteurs de liaison hydrogรจne", + "11": "Comptage de Lipinski : atomes N et O", + "12": "Liaisons rotatives", + "13": "Liaisons simples hors cycle entre atomes lourds non terminaux, liaison C-N des amides exclue", + "14": "Rรจgle de cinq de Lipinski", + "15": "MW au plus 500, cLogP au plus 5, donneurs au plus 5, accepteurs au plus 10", + "16": "HBD", + "17": "HBA", + "18": "Conforme (0 violation)", + "19": "Sรฉlectionnez dโ€™abord un ou plusieurs atomes", + "20": "Sรฉlectionnez dโ€™abord une ou plusieurs liaisons", + "21": "Aucun hydrogรจne implicite ร  ajouter.", + "22": "Aucun hydrogรจne explicite ร  retirer.", + "23": "Sรฉlectionnez une abrรฉviation, comme Ph ou OTs, ร  dรฉvelopper.", + "24": "Sรฉlectionnez les atomes dโ€™un groupe dans une seule structure pour le rรฉduire.", + "25": "Sรฉlectionnez le groupe ร  rรฉduire, sans lโ€™atome auquel il est attachรฉ.", + "26": "Rรฉduire", + "27": "Choisissez une abrรฉviation de la bibliothรจque ou saisissez une nouvelle รฉtiquette pour les atomes sรฉlectionnรฉs.", + "28": "Dรฉfinir le groupe stรฉrรฉochimique", + "29": "Effacer le groupe stรฉrรฉochimique", + "30": "Dรฉfinir la liste dโ€™atomes", + "31": "Effacer la liste dโ€™atomes", + "32": "Dรฉfinir la liaison de requรชte", + "33": "Effacer la requรชte de liaison", + "34": "Sรฉlectionnez lโ€™atome qui porte le groupe R.", + "35": "1 point dโ€™attache", + "36": "Dรฉfinir le groupe R", + "37": "Retirer la dรฉfinition du groupe R", + "38": "Attribuer les coins", + "39": "Les coins correspondent dรฉjร  aux centres stรฉrรฉogรจnes.", + "40": "Les structures sรฉlectionnรฉes", + "41": "Toutes les structures de cette page", + "42": "Corriger la structure", + "43": "Aucune structure ร  analyser.", + "44": "Analyse copiรฉe", + "45": "Impossible de copier dans le presse-papiers", + "46": "Rechercher une sous-structure", + "47": "SMARTS", + "48": "Dessinez dโ€™abord les structures ร  rechercher sur cette page.", + "49": "premiers rรฉsultats seulement", + "50": "Aucune correspondance sur cette page.", + "51": "Dessinez dโ€™abord une structure avec des atomes de groupe R et dรฉfinissez ses groupes R.", + "52": "Aucune structure ร  รฉcrire en SMARTS.", + "53": "Lโ€™enregistrement de fichiers SMARTS arrivera avec les formats de fichier dans la 0.7.0; le SMARTS a รฉtรฉ copiรฉ ร  la place.", + "54": "Dessine chaque hydrogรจne implicite des atomes sรฉlectionnรฉs (ou de toutes les structures de la page) comme un atome H explicite placรฉ par le moteur, en une seule รฉtape dโ€™annulation.", + "55": "Retire les atomes H explicites de la sรฉlection (ou de la page), en gardant les hydrogรจnes qui portent une stรฉrรฉochimie, un isotope, une charge ou un numรฉro de mappage, ou qui relient deux atomes.", + "56": "Remplace les atomes dโ€™abrรฉviation sรฉlectionnรฉs (ou toutes les abrรฉviations de la page) par leur structure complรจte, disposรฉe le long de la liaison dโ€™attache.", + "57": "Rรฉduire lโ€™abrรฉviation...", + "58": "Rรฉduit le groupe dโ€™atomes sรฉlectionnรฉ en un seul atome dโ€™abrรฉviation avec lโ€™รฉtiquette que vous choisissez ou saisissez.", + "59": "Affiche ou masque les รฉtiquettes R, S, E et Z ร  cรดtรฉ des centres stรฉrรฉogรจnes et des doubles liaisons stรฉrรฉochimiques.", + "60": "Afficher les groupes de stรฉrรฉochimie amรฉliorรฉe", + "61": "Affiche ou masque les รฉtiquettes de groupe abs, and et or ร  cรดtรฉ des centres stรฉrรฉogรจnes lorsque les รฉtiquettes de stรฉrรฉochimie sont affichรฉes.", + "62": "Afficher les caractรฉristiques de requรชte", + "63": "Affiche ou masque les marques de liste dโ€™atomes, de liaison de requรชte et de groupe R sur le canevas.", + "64": "Place les centres stรฉrรฉogรจnes sรฉlectionnรฉs dans un groupe de stรฉrรฉochimie amรฉliorรฉe : abs, and n ou or n. Sans n, un nouveau groupe and ou or est crรฉรฉ.", + "65": "abs, and ou or", + "66": "Numรฉro de groupe pour and et or", + "67": "Absolu (abs)", + "68": "Nouveau groupe AND", + "69": "Nouveau groupe OR", + "70": "Groupe stรฉrรฉochimique...", + "71": "Liste dโ€™atomes...", + "72": "Transforme les atomes sรฉlectionnรฉs en requรชte de liste dโ€™atomes ou de liste dโ€™exclusion choisie dans le tableau pรฉriodique.", + "73": "Transforme les liaisons sรฉlectionnรฉes en liaisons de requรชte : any, single_or_double, single_or_aromatic ou double_or_aromatic; omettez query pour effacer.", + "74": "Le type de liaison de requรชte", + "75": "Dรฉfinir le groupe R...", + "76": "Fait de lโ€™atome sรฉlectionnรฉ une รฉtiquette de groupe R et dรฉfinit ses membres, son occurrence, le H rรฉsiduel et la condition si-alors.", + "77": "Laisse le moteur choisir des liaisons en coin plein et en coin hachurรฉ qui expriment sans ambiguรฏtรฉ les centres stรฉrรฉogรจnes de la sรฉlection (ou de la page).", + "78": "Liste les problรจmes de valence, de stรฉrรฉochimie, de gรฉomรฉtrie et dโ€™รฉtiquettes de la sรฉlection (ou de la page) dans un panneau dont les lignes sรฉlectionnent les atomes.", + "79": "Ouvre le panneau dโ€™analyse avec les propriรฉtรฉs calculรฉes de la sรฉlection ou de la page.", + "80": "Copie sous forme de texte la formule, les masses, lโ€™analyse รฉlรฉmentaire et les propriรฉtรฉs calculรฉes avec leurs mรฉthodes.", + "81": "Rechercher une sous-structure...", + "82": "Sรฉlectionne toutes les correspondances des atomes sรฉlectionnรฉs (ou dโ€™un motif SMARTS) dans les autres structures de la page.", + "83": "ร‰numรฉrer les groupes R...", + "84": "Liste toutes les structures que reprรฉsente le squelette de Markush sรฉlectionnรฉ (ou le premier de la page), avec formule et SMILES, jusquโ€™ร  1000; la liste peut รชtre copiรฉe.", + "85": "Copier en SMARTS", + "86": "Copie les atomes sรฉlectionnรฉs (ou toutes les structures de la page) en SMARTS, avec les listes dโ€™atomes, les atomes gรฉnรฉriques, les liaisons de requรชte et les autres caractรฉristiques de requรชte.", + "87": "Exporter en SMARTS...", + "88": "Enregistre les atomes sรฉlectionnรฉs (ou toutes les structures de la page) dans un fichier SMARTS (.sma).", + "89": "Stรฉrรฉochimie amรฉliorรฉe", + "90": "Requรชte", + "91": "Objet", + "92": "Sรฉlectionnez dโ€™abord les structures ou le texte auxquels attribuer un rรดle.", + "93": "Dรฉfinir les rรดles dans la rรฉaction...", + "94": "Dรฉfinit le rรดle des structures ou du texte sรฉlectionnรฉs dans lโ€™รฉtape de rรฉaction sรฉlectionnรฉe (rรฉactif, produit, agent, condition ou aucun) et marque les rรดles de lโ€™รฉtape comme dรฉfinis ร  la main, en une seule รฉtape dโ€™annulation. Sans role, ouvre une boรฎte de dialogue qui liste les membres de lโ€™รฉtape et la sรฉlection.", + "95": "Rรดle ร  attribuer aux objets; omettez-le pour ouvrir la boรฎte de dialogue", + "96": "Id des objets ร  modifier; par dรฉfaut, la sรฉlection", + "97": "Impossible de dรฉfinir les rรดles de la rรฉaction", + "98": "H rรฉsiduel", + "99": "Abrรฉviation", + "100": "ร‰tiquette", + "101": "Rechercher dans la bibliothรจque", + "102": "Impossible de charger la bibliothรจque dโ€™abrรฉviations. Vous pouvez quand mรชme saisir une รฉtiquette.", + "103": "Aucune abrรฉviation ne correspond. Lโ€™รฉtiquette saisie est utilisรฉe telle quelle.", + "104": "Propriรฉtรฉs", + "105": "Liste dโ€™atomes", + "106": "Cliquez sur les รฉlรฉments du tableau pour les ajouter.", + "107": "Effacer la requรชte", + "108": "Appliquer", + "109": "Retirer", + "110": "Aucune requรชte", + "111": "[M+Na]+", + "112": "Motif isotopique", + "113": "ร‰numรฉrer les groupes R", + "114": "Copier le SMILES", + "115": "SMILES de toutes les structures copiรฉ", + "116": "Si", + "117": "Nโ€™importe quelle liaison", + "118": "Simple ou double", + "119": "Simple ou aromatique", + "120": "Double ou aromatique", + "121": "Cycle ou chaรฎne", + "122": "Dans un cycle", + "123": "Dans une chaรฎne", + "124": "Nโ€™importe quel atome (A)", + "125": "Nโ€™importe quel hรฉtรฉroatome (Q)", + "126": "Nโ€™importe quel halogรจne (X)", + "127": "Nโ€™importe quel mรฉtal (M)", + "128": "Dรฉfinir la topologie de la liaison", + "129": "Liaison de requรชte", + "130": "Dรฉfinir la requรชte dโ€™atome", + "131": "Aromatique", + "132": "Aliphatique", + "133": "Insaturรฉ", + "134": "Substitution comme dessinรฉe", + "135": "Liaisons de cycle comme dessinรฉes", + "136": "Effacer la requรชte dโ€™atome", + "137": "Requรชte dโ€™atome", + "138": "Dรฉfinition du groupe R", + "139": "Groupe R", + "140": "Membres", + "141": "Dessinez chaque membre comme sa propre structure avec un point dโ€™attache (*), puis rouvrez cette boรฎte de dialogue.", + "142": "Occurrence", + "143": "H rรฉsiduel (les positions non substituรฉes sont de lโ€™hydrogรจne)", + "144": "Si prรฉsent, alors", + "145": "Retirer la dรฉfinition", + "146": "Agent", + "147": "Condition", + "148": "Effacer", + "149": "Ajouter les centres sรฉlectionnรฉs ร  ce groupe", + "150": "Vรฉrifier ร  nouveau", + "151": "Vรฉrification...", + "152": "Corriger", + "153": "Sรฉlectionner sur le canevas" +} From 09a94b750bd3d211645a460f71d11099c885788c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:50 -0500 Subject: [PATCH 244/279] feat(i18n): translate the stereo, query and analysis strings into German (0.6.0) Adds the part06 key block for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/de/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/de/part06.json diff --git a/frontend/src/i18n/locales/de/part06.json b/frontend/src/i18n/locales/de/part06.json new file mode 100644 index 00000000..e91502a8 --- /dev/null +++ b/frontend/src/i18n/locales/de/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill-Reihenfolge mit Ladung, Abkรผrzungen aufgelรถst", + "1": "Standard-Atomgewichte (konventionelle CIAAW-Werte)", + "2": "Monoisotopische Masse aus dem hรคufigsten Isotop jedes Elements", + "3": "Exakte Masse geteilt durch die absolute Ladung, mit Korrektur um die Elektronenmasse", + "4": "Massenanteil jedes Elements in Prozent, zwei Dezimalstellen", + "5": "Atombeitrรคge (Wildman und Crippen 1999)", + "6": "Topologische polare Oberflรคche, N- und O-Fragmente (Ertl 2000)", + "7": "Molrefraktion", + "8": "H-Brรผcken-Donoren", + "9": "Zรคhlung nach Lipinski: N-H- und O-H-Gruppen", + "10": "H-Brรผcken-Akzeptoren", + "11": "Zรคhlung nach Lipinski: N- und O-Atome", + "12": "Drehbare Bindungen", + "13": "Einfachbindungen auรŸerhalb von Ringen zwischen nicht endstรคndigen Schweratomen, Amid-C-N ausgenommen", + "14": "Lipinski-Regel der Fรผnf", + "15": "MW hรถchstens 500, cLogP hรถchstens 5, Donoren hรถchstens 5, Akzeptoren hรถchstens 10", + "16": "HBD", + "17": "HBA", + "18": "Bestanden (0 VerstรถรŸe)", + "19": "Wรคhlen Sie zuerst ein oder mehrere Atome aus", + "20": "Wรคhlen Sie zuerst eine oder mehrere Bindungen aus", + "21": "Keine impliziten Wasserstoffe zum Hinzufรผgen.", + "22": "Keine expliziten Wasserstoffe zum Entfernen.", + "23": "Wรคhlen Sie eine Abkรผrzung wie Ph oder OTs zum Erweitern aus.", + "24": "Wรคhlen Sie die Atome einer Gruppe in einer Struktur zum Zusammenziehen aus.", + "25": "Wรคhlen Sie die zusammenzuziehende Gruppe ohne das Atom, an dem sie hรคngt.", + "26": "Zusammenziehen", + "27": "Wรคhlen Sie eine Abkรผrzung aus der Bibliothek oder geben Sie eine neue Beschriftung fรผr die ausgewรคhlten Atome ein.", + "28": "Stereogruppe festlegen", + "29": "Stereogruppe entfernen", + "30": "Atomliste festlegen", + "31": "Atomliste entfernen", + "32": "Query-Bindung festlegen", + "33": "Bindungs-Query entfernen", + "34": "Wรคhlen Sie das Atom aus, das den R-Rest trรคgt.", + "35": "1 Anknรผpfungspunkt", + "36": "R-Rest definieren", + "37": "R-Rest-Definition entfernen", + "38": "Keile zuweisen", + "39": "Die Keile entsprechen bereits den Stereozentren.", + "40": "Die ausgewรคhlten Strukturen", + "41": "Jede Struktur auf dieser Seite", + "42": "Struktur korrigieren", + "43": "Es gibt keine Struktur zum Analysieren.", + "44": "Analyse kopiert", + "45": "Kopieren in die Zwischenablage nicht mรถglich", + "46": "Teilstruktur suchen", + "47": "SMARTS", + "48": "Zeichnen Sie zuerst die Strukturen, in denen auf dieser Seite gesucht werden soll.", + "49": "nur die ersten Ergebnisse", + "50": "Keine Treffer auf dieser Seite.", + "51": "Zeichnen Sie zuerst eine Struktur mit R-Rest-Atomen und definieren Sie deren R-Reste.", + "52": "Es gibt keine Struktur, die als SMARTS geschrieben werden kann.", + "53": "Das Speichern von SMARTS-Dateien kommt mit den Dateiformaten in 0.7.0; stattdessen wurde das SMARTS kopiert.", + "54": "Zeichnet jeden impliziten Wasserstoff der ausgewรคhlten Atome (oder jeder Struktur auf der Seite) als explizites, von der Engine platziertes H-Atom, in einem Rรผckgรคngig-Schritt.", + "55": "Entfernt explizite H-Atome aus der Auswahl (oder der Seite) und behรคlt Wasserstoffe, die Stereochemie, ein Isotop, eine Ladung oder eine Mapping-Nummer tragen oder zwei Atome รผberbrรผcken.", + "56": "Ersetzt die ausgewรคhlten Abkรผrzungsatome (oder jede Abkรผrzung auf der Seite) durch ihre vollstรคndige Struktur, entlang der Anknรผpfungsbindung ausgelegt.", + "57": "Abkรผrzung zusammenziehen...", + "58": "Fasst die ausgewรคhlte Atomgruppe zu einem Abkรผrzungsatom zusammen, mit der Beschriftung, die der Benutzer wรคhlt oder eingibt.", + "59": "Blendet R-, S-, E- und Z-Beschriftungen neben Stereozentren und stereoisomeren Doppelbindungen ein oder aus.", + "60": "Erweiterte Stereogruppen anzeigen", + "61": "Blendet die Gruppenbeschriftungen abs, and und or neben Stereozentren ein oder aus, solange Stereobeschriftungen eingeblendet sind.", + "62": "Query-Merkmale anzeigen", + "63": "Blendet Atomlisten-, Query-Bindungs- und R-Rest-Markierungen auf der Zeichenflรคche ein oder aus.", + "64": "Legt die ausgewรคhlten Stereozentren in eine erweiterte Stereogruppe: abs, and n oder or n. Ohne n wird eine neue and- oder or-Gruppe angelegt.", + "65": "abs, and oder or", + "66": "Gruppennummer fรผr and und or", + "67": "Absolut (abs)", + "68": "Neue AND-Gruppe", + "69": "Neue OR-Gruppe", + "70": "Stereogruppe...", + "71": "Atomliste...", + "72": "Macht die ausgewรคhlten Atome zu einer Atomliste oder Nicht-Liste, die im Periodensystem ausgewรคhlt wird.", + "73": "Macht die ausgewรคhlten Bindungen zu Query-Bindungen: any, single_or_double, single_or_aromatic oder double_or_aromatic; query weglassen, um sie zu entfernen.", + "74": "Der Typ der Query-Bindung", + "75": "R-Rest definieren...", + "76": "Macht das ausgewรคhlte Atom zu einer R-Rest-Beschriftung und legt seine Mitglieder, Hรคufigkeit, Rest-H und die Wenn-dann-Bedingung fest.", + "77": "Lรคsst die Engine Keil- und gestrichelte Bindungen wรคhlen, die die Stereozentren der Auswahl (oder der Seite) eindeutig ausdrรผcken.", + "78": "Listet Valenz-, Stereo-, Geometrie- und Beschriftungsprobleme der Auswahl (oder der Seite) in einem Bereich auf, dessen Zeilen die Atome auswรคhlen.", + "79": "ร–ffnet den Analysebereich mit den berechneten Eigenschaften der Auswahl oder der Seite.", + "80": "Kopiert Summenformel, Massen, Elementaranalyse und die berechneten Eigenschaften mit ihren Methoden als Text.", + "81": "Teilstruktur suchen...", + "82": "Wรคhlt jeden Treffer der ausgewรคhlten Atome (oder eines SMARTS-Musters) in den anderen Strukturen auf der Seite aus.", + "83": "R-Reste aufzรคhlen...", + "84": "Listet jede Struktur auf, fรผr die das ausgewรคhlte Markush-Grundgerรผst (oder das erste auf der Seite) steht, mit Summenformel und SMILES, bis zu 1000; die Liste lรคsst sich kopieren.", + "85": "Als SMARTS kopieren", + "86": "Kopiert die ausgewรคhlten Atome (oder jede Struktur auf der Seite) als SMARTS, mit Atomlisten, generischen Atomen, Query-Bindungen und den รผbrigen Query-Merkmalen.", + "87": "SMARTS exportieren...", + "88": "Speichert die ausgewรคhlten Atome (oder jede Struktur auf der Seite) als SMARTS-Datei (.sma).", + "89": "Erweiterte Stereochemie", + "90": "Query", + "91": "Objekt", + "92": "Wรคhlen Sie zuerst die Strukturen oder den Text aus, denen eine Rolle zugewiesen werden soll.", + "93": "Reaktionsrollen festlegen...", + "94": "Legt die Rolle der ausgewรคhlten Strukturen oder des Texts im ausgewรคhlten Reaktionsschritt fest (Edukt, Produkt, Reagenz, Bedingung oder keine) und markiert die Rollen des Schritts als von Hand gesetzt, in einem Rรผckgรคngig-Schritt. Ohne role รถffnet sich ein Dialog mit den Mitgliedern des Schritts und der Auswahl.", + "95": "Rolle fรผr die Objekte; weglassen, um den Dialog zu รถffnen", + "96": "IDs der zu รคndernden Objekte; standardmรครŸig die Auswahl", + "97": "Die Reaktionsrollen konnten nicht festgelegt werden", + "98": "Rest-H", + "99": "Abkรผrzung", + "100": "Beschriftung", + "101": "Bibliothek durchsuchen", + "102": "Die Abkรผrzungsbibliothek konnte nicht geladen werden. Sie kรถnnen weiterhin eine Beschriftung eingeben.", + "103": "Keine Abkรผrzung passt. Die eingegebene Beschriftung wird unverรคndert verwendet.", + "104": "Eigenschaften", + "105": "Atomliste", + "106": "Klicken Sie in der Tabelle auf Elemente, um sie hinzuzufรผgen.", + "107": "Query entfernen", + "108": "Anwenden", + "109": "Entfernen", + "110": "Keine Query", + "111": "[M+Na]+", + "112": "Isotopenmuster", + "113": "R-Reste aufzรคhlen", + "114": "SMILES kopieren", + "115": "SMILES jeder Struktur kopiert", + "116": "Si", + "117": "Beliebige Bindung", + "118": "Einfach oder doppelt", + "119": "Einfach oder aromatisch", + "120": "Doppelt oder aromatisch", + "121": "Ring oder Kette", + "122": "In einem Ring", + "123": "In einer Kette", + "124": "Beliebiges Atom (A)", + "125": "Beliebiges Heteroatom (Q)", + "126": "Beliebiges Halogen (X)", + "127": "Beliebiges Metall (M)", + "128": "Bindungstopologie festlegen", + "129": "Query-Bindung", + "130": "Atom-Query festlegen", + "131": "Aromatisch", + "132": "Aliphatisch", + "133": "Ungesรคttigt", + "134": "Substitution wie gezeichnet", + "135": "Ringbindungen wie gezeichnet", + "136": "Atom-Query entfernen", + "137": "Atom-Query", + "138": "R-Rest-Definition", + "139": "R-Rest", + "140": "Mitglieder", + "141": "Zeichnen Sie jedes Mitglied als eigene Struktur mit einem Anknรผpfungspunkt (*) und รถffnen Sie dann diesen Dialog erneut.", + "142": "Hรคufigkeit", + "143": "Rest-H (nicht substituierte Positionen sind Wasserstoff)", + "144": "Wenn vorhanden, dann", + "145": "Definition entfernen", + "146": "Reagenz", + "147": "Bedingung", + "148": "Leeren", + "149": "Die ausgewรคhlten Zentren zu dieser Gruppe hinzufรผgen", + "150": "Erneut prรผfen", + "151": "Prรผfung lรคuft...", + "152": "Korrigieren", + "153": "Auf der Zeichenflรคche auswรคhlen" +} From d585e7c4a13fab271887734fe48df6115815aa6e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:50 -0500 Subject: [PATCH 245/279] feat(i18n): translate the stereo, query and analysis strings into Italian (0.6.0) Adds the part06 key block for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/it/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/it/part06.json diff --git a/frontend/src/i18n/locales/it/part06.json b/frontend/src/i18n/locales/it/part06.json new file mode 100644 index 00000000..958808a6 --- /dev/null +++ b/frontend/src/i18n/locales/it/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Ordine di Hill con carica, abbreviazioni espanse", + "1": "Pesi atomici standard (valori convenzionali CIAAW)", + "2": "Massa monoisotopica dall'isotopo piรน abbondante di ogni elemento", + "3": "Massa esatta divisa per la carica assoluta, con correzione per la massa dell'elettrone", + "4": "Percentuale in massa di ogni elemento, due decimali", + "5": "Contributi atomici (Wildman e Crippen 1999)", + "6": "Area superficiale polare topologica, frammenti N e O (Ertl 2000)", + "7": "Rifrazione molare", + "8": "Donatori di legami a idrogeno", + "9": "Conteggio di Lipinski: gruppi N-H e O-H", + "10": "Accettori di legami a idrogeno", + "11": "Conteggio di Lipinski: atomi N e O", + "12": "Legami ruotabili", + "13": "Legami singoli non ciclici tra atomi pesanti non terminali, escluso il C-N delle ammidi", + "14": "Regola del cinque di Lipinski", + "15": "MW al massimo 500, cLogP al massimo 5, donatori al massimo 5, accettori al massimo 10", + "16": "HBD", + "17": "HBA", + "18": "Superato (0 violazioni)", + "19": "Seleziona prima uno o piรน atomi", + "20": "Seleziona prima uno o piรน legami", + "21": "Nessun idrogeno implicito da aggiungere.", + "22": "Nessun idrogeno esplicito da rimuovere.", + "23": "Seleziona un'abbreviazione come Ph o OTs da espandere.", + "24": "Seleziona gli atomi di un gruppo in una struttura da comprimere.", + "25": "Seleziona il gruppo da comprimere, senza l'atomo a cui รจ legato.", + "26": "Comprimi", + "27": "Scegli un'abbreviazione dalla libreria o digita una nuova etichetta per gli atomi selezionati.", + "28": "Imposta gruppo stereo", + "29": "Cancella gruppo stereo", + "30": "Imposta lista di atomi", + "31": "Cancella lista di atomi", + "32": "Imposta legame query", + "33": "Cancella query del legame", + "34": "Seleziona l'atomo che porta il gruppo R.", + "35": "1 punto di attacco", + "36": "Definisci gruppo R", + "37": "Rimuovi definizione del gruppo R", + "38": "Assegna cunei", + "39": "I cunei corrispondono giร  agli stereocentri.", + "40": "Le strutture selezionate", + "41": "Ogni struttura di questa pagina", + "42": "Correggi struttura", + "43": "Non c'รจ nessuna struttura da analizzare.", + "44": "Analisi copiata", + "45": "Impossibile copiare negli appunti", + "46": "Trova sottostruttura", + "47": "SMARTS", + "48": "Disegna prima le strutture in cui cercare in questa pagina.", + "49": "solo i primi risultati", + "50": "Nessuna corrispondenza in questa pagina.", + "51": "Disegna prima una struttura con atomi di gruppo R e definisci i suoi gruppi R.", + "52": "Non c'รจ nessuna struttura da scrivere come SMARTS.", + "53": "Il salvataggio dei file SMARTS arriva con i formati di file nella 0.7.0; รจ stato copiato lo SMARTS.", + "54": "Disegna ogni idrogeno implicito degli atomi selezionati (o di ogni struttura della pagina) come atomo H esplicito posizionato dal motore, in un solo passaggio di annullamento.", + "55": "Rimuove gli atomi H espliciti dalla selezione (o dalla pagina), mantenendo gli idrogeni che portano stereochimica, un isotopo, una carica, un numero di mappatura o che ponticellano due atomi.", + "56": "Sostituisce gli atomi di abbreviazione selezionati (o ogni abbreviazione della pagina) con la loro struttura completa, disposta lungo il legame di attacco.", + "57": "Comprimi abbreviazione...", + "58": "Riduce il gruppo di atomi selezionato a un solo atomo di abbreviazione con l'etichetta scelta o digitata dall'utente.", + "59": "Mostra o nasconde le etichette R, S, E e Z accanto agli stereocentri e ai doppi legami stereo.", + "60": "Mostra gruppi stereo avanzati", + "61": "Mostra o nasconde le etichette di gruppo abs, and e or accanto agli stereocentri quando le etichette stereo sono attive.", + "62": "Mostra caratteristiche query", + "63": "Mostra o nasconde sull'area di disegno i segni di lista di atomi, legame query e gruppo R.", + "64": "Mette gli stereocentri selezionati in un gruppo stereo avanzato: abs, and n o or n. Senza n viene creato un nuovo gruppo and o or.", + "65": "abs, and o or", + "66": "Numero del gruppo per and e or", + "67": "Assoluto (abs)", + "68": "Nuovo gruppo AND", + "69": "Nuovo gruppo OR", + "70": "Gruppo stereo...", + "71": "Lista di atomi...", + "72": "Trasforma gli atomi selezionati in una query a lista di atomi o a lista di esclusione scelta nella tavola periodica.", + "73": "Trasforma i legami selezionati in legami query: any, single_or_double, single_or_aromatic o double_or_aromatic; ometti query per cancellare.", + "74": "Il tipo di legame query", + "75": "Definisci gruppo R...", + "76": "Trasforma l'atomo selezionato in un'etichetta di gruppo R e ne definisce membri, occorrenza, H residuo e condizione se-allora.", + "77": "Lascia che il motore scelga legami a cuneo e tratteggiati che esprimano senza ambiguitร  gli stereocentri della selezione (o della pagina).", + "78": "Elenca problemi di valenza, stereochimica, geometria ed etichette della selezione (o della pagina) in un pannello le cui righe selezionano gli atomi.", + "79": "Apre il pannello di analisi con le proprietร  calcolate della selezione o della pagina.", + "80": "Copia come testo formula, masse, analisi elementare e proprietร  calcolate con i relativi metodi.", + "81": "Trova sottostruttura...", + "82": "Seleziona ogni corrispondenza degli atomi selezionati (o di un pattern SMARTS) nelle altre strutture della pagina.", + "83": "Enumera gruppi R...", + "84": "Elenca ogni struttura rappresentata dallo scheletro Markush selezionato (o dal primo della pagina), con formula e SMILES, fino a 1000; l'elenco si puรฒ copiare.", + "85": "Copia come SMARTS", + "86": "Copia gli atomi selezionati (o ogni struttura della pagina) come SMARTS, con liste di atomi, atomi generici, legami query e le altre caratteristiche query.", + "87": "Esporta SMARTS...", + "88": "Salva gli atomi selezionati (o ogni struttura della pagina) come file SMARTS (.sma).", + "89": "Stereochimica avanzata", + "90": "Query", + "91": "Oggetto", + "92": "Seleziona prima le strutture o il testo a cui dare un ruolo.", + "93": "Imposta ruoli di reazione...", + "94": "Imposta il ruolo delle strutture o del testo selezionati nel passaggio di reazione selezionato (reagente, prodotto, agente, condizione o nessuno) e segna i ruoli del passaggio come impostati a mano, in un solo passaggio di annullamento. Senza role apre una finestra con i membri del passaggio e la selezione.", + "95": "Ruolo da dare agli oggetti; omettilo per aprire la finestra", + "96": "Id degli oggetti da modificare; per impostazione predefinita la selezione", + "97": "Impossibile impostare i ruoli di reazione", + "98": "H residuo", + "99": "Abbreviazione", + "100": "Etichetta", + "101": "Cerca nella libreria", + "102": "Impossibile caricare la libreria delle abbreviazioni. Puoi comunque digitare un'etichetta.", + "103": "Nessuna abbreviazione corrisponde. L'etichetta digitata viene usata cosรฌ com'รจ.", + "104": "Proprietร ", + "105": "Lista di atomi", + "106": "Clicca gli elementi nella tabella per aggiungerli.", + "107": "Cancella query", + "108": "Applica", + "109": "Rimuovi", + "110": "Nessuna query", + "111": "[M+Na]+", + "112": "Pattern isotopico", + "113": "Enumera gruppi R", + "114": "Copia SMILES", + "115": "SMILES di ogni struttura copiati", + "116": "Si", + "117": "Qualsiasi legame", + "118": "Singolo o doppio", + "119": "Singolo o aromatico", + "120": "Doppio o aromatico", + "121": "Anello o catena", + "122": "In un anello", + "123": "In una catena", + "124": "Qualsiasi atomo (A)", + "125": "Qualsiasi eteroatomo (Q)", + "126": "Qualsiasi alogeno (X)", + "127": "Qualsiasi metallo (M)", + "128": "Imposta topologia del legame", + "129": "Legame query", + "130": "Imposta query dell'atomo", + "131": "Aromatico", + "132": "Alifatico", + "133": "Insaturo", + "134": "Sostituzione come disegnata", + "135": "Legami dell'anello come disegnati", + "136": "Cancella query dell'atomo", + "137": "Query dell'atomo", + "138": "Definizione del gruppo R", + "139": "Gruppo R", + "140": "Membri", + "141": "Disegna ogni membro come struttura a sรฉ con un punto di attacco (*), poi riapri questa finestra.", + "142": "Occorrenza", + "143": "H residuo (le posizioni non sostituite sono idrogeno)", + "144": "Se presente, allora", + "145": "Rimuovi definizione", + "146": "Agente", + "147": "Condizione", + "148": "Cancella", + "149": "Aggiungi i centri selezionati a questo gruppo", + "150": "Ricontrolla", + "151": "Verifica in corso...", + "152": "Correggi", + "153": "Seleziona sull'area di disegno" +} From 3b5b0635f121d179d113ad283e97ac6ed0a84411 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:50 -0500 Subject: [PATCH 246/279] feat(i18n): translate the stereo, query and analysis strings into Dutch (0.6.0) Adds the part06 key block for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/nl/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/nl/part06.json diff --git a/frontend/src/i18n/locales/nl/part06.json b/frontend/src/i18n/locales/nl/part06.json new file mode 100644 index 00000000..0eb20c65 --- /dev/null +++ b/frontend/src/i18n/locales/nl/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill-volgorde met lading, afkortingen uitgeschreven", + "1": "Standaard atoomgewichten (conventionele CIAAW-waarden)", + "2": "Monoisotopische massa van de meest voorkomende isotoop van elk element", + "3": "Exacte massa gedeeld door de absolute lading, gecorrigeerd voor de elektronmassa", + "4": "Massapercentage van elk element, twee decimalen", + "5": "Atoombijdragen (Wildman en Crippen 1999)", + "6": "Topologisch polair oppervlak, N- en O-fragmenten (Ertl 2000)", + "7": "Molaire refractie", + "8": "Waterstofbrugdonoren", + "9": "Telling volgens Lipinski: N-H- en O-H-groepen", + "10": "Waterstofbrugacceptoren", + "11": "Telling volgens Lipinski: N- en O-atomen", + "12": "Roteerbare bindingen", + "13": "Enkelvoudige bindingen buiten ringen tussen niet-terminale zware atomen, amide-C-N uitgezonderd", + "14": "Vijfregel van Lipinski", + "15": "MW hooguit 500, cLogP hooguit 5, donoren hooguit 5, acceptoren hooguit 10", + "16": "HBD", + "17": "HBA", + "18": "Geslaagd (0 schendingen)", + "19": "Selecteer eerst een of meer atomen", + "20": "Selecteer eerst een of meer bindingen", + "21": "Geen impliciete waterstofatomen om toe te voegen.", + "22": "Geen expliciete waterstofatomen om te verwijderen.", + "23": "Selecteer een afkorting zoals Ph of OTs om uit te schrijven.", + "24": "Selecteer de atomen van รฉรฉn groep in รฉรฉn structuur om samen te trekken.", + "25": "Selecteer de groep die moet worden samengetrokken, zonder het atoom waaraan ze vastzit.", + "26": "Samentrekken", + "27": "Kies een afkorting uit de bibliotheek of typ een nieuw label voor de geselecteerde atomen.", + "28": "Stereogroep instellen", + "29": "Stereogroep wissen", + "30": "Atoomlijst instellen", + "31": "Atoomlijst wissen", + "32": "Querybinding instellen", + "33": "Bindingsquery wissen", + "34": "Selecteer het atoom dat de R-groep draagt.", + "35": "1 aanhechtingspunt", + "36": "R-groep definiรซren", + "37": "R-groepdefinitie verwijderen", + "38": "Wiggen toewijzen", + "39": "De wiggen komen al overeen met de stereocentra.", + "40": "De geselecteerde structuren", + "41": "Elke structuur op deze pagina", + "42": "Structuur herstellen", + "43": "Er is geen structuur om te analyseren.", + "44": "Analyse gekopieerd", + "45": "Kopiรซren naar het klembord is niet gelukt", + "46": "Substructuur zoeken", + "47": "SMARTS", + "48": "Teken eerst de structuren waarin op deze pagina moet worden gezocht.", + "49": "alleen de eerste resultaten", + "50": "Geen treffers op deze pagina.", + "51": "Teken eerst een structuur met R-groepatomen en definieer de bijbehorende R-groepen.", + "52": "Er is geen structuur om als SMARTS te schrijven.", + "53": "Het opslaan van SMARTS-bestanden komt met de bestandsindelingen in 0.7.0; de SMARTS is in plaats daarvan gekopieerd.", + "54": "Tekent elk impliciet waterstofatoom van de geselecteerde atomen (of van elke structuur op de pagina) als expliciet H-atoom dat door de engine wordt geplaatst, in รฉรฉn ongedaanmakingsstap.", + "55": "Verwijdert expliciete H-atomen uit de selectie (of de pagina), maar behoudt waterstofatomen met stereochemie, een isotoop, een lading of een mappingnummer, of die twee atomen overbruggen.", + "56": "Vervangt de geselecteerde afkortingsatomen (of elke afkorting op de pagina) door hun volledige structuur, uitgelegd langs de aanhechtingsbinding.", + "57": "Afkorting samentrekken...", + "58": "Trekt de geselecteerde atoomgroep samen tot รฉรฉn afkortingsatoom met het label dat de gebruiker kiest of typt.", + "59": "Toont of verbergt R-, S-, E- en Z-labels naast stereocentra en stereodubbelbindingen.", + "60": "Uitgebreide stereogroepen tonen", + "61": "Toont of verbergt de groepslabels abs, and en or naast stereocentra zolang stereolabels aan staan.", + "62": "Querykenmerken tonen", + "63": "Toont of verbergt markeringen voor atoomlijsten, querybindingen en R-groepen op het tekengebied.", + "64": "Plaatst de geselecteerde stereocentra in een uitgebreide stereogroep: abs, and n of or n. Zonder n wordt een nieuwe and- of or-groep gemaakt.", + "65": "abs, and of or", + "66": "Groepsnummer voor and en or", + "67": "Absoluut (abs)", + "68": "Nieuwe AND-groep", + "69": "Nieuwe OR-groep", + "70": "Stereogroep...", + "71": "Atoomlijst...", + "72": "Maakt van de geselecteerde atomen een atoomlijst- of niet-lijstquery die in het periodiek systeem wordt gekozen.", + "73": "Maakt van de geselecteerde bindingen querybindingen: any, single_or_double, single_or_aromatic of double_or_aromatic; laat query weg om te wissen.", + "74": "Het type querybinding", + "75": "R-groep definiรซren...", + "76": "Maakt van het geselecteerde atoom een R-groeplabel en definieert de leden, het voorkomen, rest-H en de als-dan-voorwaarde.", + "77": "Laat de engine wig- en gestippelde bindingen kiezen die de stereocentra van de selectie (of de pagina) ondubbelzinnig weergeven.", + "78": "Toont valentie-, stereo-, geometrie- en labelproblemen van de selectie (of de pagina) in een paneel waarvan de rijen de atomen selecteren.", + "79": "Opent het analysepaneel met de berekende eigenschappen van de selectie of de pagina.", + "80": "Kopieert molecuulformule, massa's, elementanalyse en de berekende eigenschappen met hun methoden als tekst.", + "81": "Substructuur zoeken...", + "82": "Selecteert elke treffer van de geselecteerde atomen (of van een SMARTS-patroon) in de andere structuren op de pagina.", + "83": "R-groepen opsommen...", + "84": "Toont elke structuur waarvoor het geselecteerde Markush-skelet (of het eerste op de pagina) staat, met molecuulformule en SMILES, tot 1000; de lijst kan worden gekopieerd.", + "85": "Kopiรซren als SMARTS", + "86": "Kopieert de geselecteerde atomen (of elke structuur op de pagina) als SMARTS, met atoomlijsten, generieke atomen, querybindingen en de overige querykenmerken.", + "87": "SMARTS exporteren...", + "88": "Slaat de geselecteerde atomen (of elke structuur op de pagina) op als SMARTS-bestand (.sma).", + "89": "Uitgebreide stereochemie", + "90": "Query", + "91": "Object", + "92": "Selecteer eerst de structuren of tekst waaraan een rol moet worden gegeven.", + "93": "Reactierollen instellen...", + "94": "Stelt de rol in van de geselecteerde structuren of tekst in de geselecteerde reactiestap (reactant, product, agens, omstandigheid of geen) en markeert de rollen van de stap als handmatig ingesteld, in รฉรฉn ongedaanmakingsstap. Zonder role opent het een dialoog met de leden van de stap en de selectie.", + "95": "Rol die aan de objecten wordt gegeven; laat weg om de dialoog te openen", + "96": "Id's van de te wijzigen objecten; standaard de selectie", + "97": "Kon de reactierollen niet instellen", + "98": "rest-H", + "99": "Afkorting", + "100": "Label", + "101": "Zoeken in de bibliotheek", + "102": "De afkortingenbibliotheek kon niet worden geladen. U kunt nog steeds een label typen.", + "103": "Geen afkorting komt overeen. Het getypte label wordt gebruikt zoals het is.", + "104": "Eigenschappen", + "105": "Atoomlijst", + "106": "Klik op elementen in de tabel om ze toe te voegen.", + "107": "Query wissen", + "108": "Toepassen", + "109": "Verwijderen", + "110": "Geen query", + "111": "[M+Na]+", + "112": "Isotopenpatroon", + "113": "R-groepen opsommen", + "114": "SMILES kopiรซren", + "115": "SMILES van elke structuur gekopieerd", + "116": "Si", + "117": "Elke binding", + "118": "Enkel of dubbel", + "119": "Enkel of aromatisch", + "120": "Dubbel of aromatisch", + "121": "Ring of keten", + "122": "In een ring", + "123": "In een keten", + "124": "Elk atoom (A)", + "125": "Elk heteroatoom (Q)", + "126": "Elk halogeen (X)", + "127": "Elk metaal (M)", + "128": "Bindingstopologie instellen", + "129": "Querybinding", + "130": "Atoomquery instellen", + "131": "Aromatisch", + "132": "Alifatisch", + "133": "Onverzadigd", + "134": "Substitutie zoals getekend", + "135": "Ringbindingen zoals getekend", + "136": "Atoomquery wissen", + "137": "Atoomquery", + "138": "R-groepdefinitie", + "139": "R-groep", + "140": "Leden", + "141": "Teken elk lid als eigen structuur met een aanhechtingspunt (*) en open deze dialoog daarna opnieuw.", + "142": "Voorkomen", + "143": "Rest-H (niet-gesubstitueerde posities zijn waterstof)", + "144": "Indien aanwezig, dan", + "145": "Definitie verwijderen", + "146": "Agens", + "147": "Omstandigheid", + "148": "Wissen", + "149": "De geselecteerde centra aan deze groep toevoegen", + "150": "Opnieuw controleren", + "151": "Controleren...", + "152": "Herstellen", + "153": "Selecteren op het tekengebied" +} From a3099fac784d02338fc5f3df898a931d68d48b43 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:50 -0500 Subject: [PATCH 247/279] feat(i18n): translate the stereo, query and analysis strings into Danish (0.6.0) Adds the part06 key block for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/da/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/da/part06.json diff --git a/frontend/src/i18n/locales/da/part06.json b/frontend/src/i18n/locales/da/part06.json new file mode 100644 index 00000000..79b4d245 --- /dev/null +++ b/frontend/src/i18n/locales/da/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill-rรฆkkefรธlge med ladning, forkortelser udvidet", + "1": "Standardatomvรฆgte (konventionelle CIAAW-vรฆrdier)", + "2": "Monoisotopisk masse ud fra den mest almindelige isotop af hvert grundstof", + "3": "Nรธjagtig masse divideret med den absolutte ladning, korrigeret for elektronmassen", + "4": "Masseprocent af hvert grundstof, to decimaler", + "5": "Atombidrag (Wildman og Crippen 1999)", + "6": "Topologisk polรฆrt overfladeareal, N- og O-fragmenter (Ertl 2000)", + "7": "Molรฆr refraktion", + "8": "Hydrogenbindingsdonorer", + "9": "Lipinski-optรฆlling: N-H- og O-H-grupper", + "10": "Hydrogenbindingsacceptorer", + "11": "Lipinski-optรฆlling: N- og O-atomer", + "12": "Roterbare bindinger", + "13": "Enkeltbindinger uden for ringe mellem ikke-terminale tunge atomer, amid-C-N undtaget", + "14": "Lipinskis femregel", + "15": "MW hรธjst 500, cLogP hรธjst 5, donorer hรธjst 5, acceptorer hรธjst 10", + "16": "HBD", + "17": "HBA", + "18": "Bestรฅet (0 overtrรฆdelser)", + "19": "Markรฉr fรธrst et eller flere atomer", + "20": "Markรฉr fรธrst en eller flere bindinger", + "21": "Ingen implicitte hydrogener at tilfรธje.", + "22": "Ingen eksplicitte hydrogener at fjerne.", + "23": "Markรฉr en forkortelse som Ph eller OTs for at udvide den.", + "24": "Markรฉr atomerne i รฉn gruppe i รฉn struktur for at sammentrรฆkke dem.", + "25": "Markรฉr den gruppe, der skal sammentrรฆkkes, uden det atom, den sidder pรฅ.", + "26": "Sammentrรฆk", + "27": "Vรฆlg en forkortelse fra biblioteket, eller skriv en ny etiket til de markerede atomer.", + "28": "Angiv stereogruppe", + "29": "Ryd stereogruppe", + "30": "Angiv atomliste", + "31": "Ryd atomliste", + "32": "Angiv forespรธrgselsbinding", + "33": "Ryd bindingsforespรธrgsel", + "34": "Markรฉr det atom, der bรฆrer R-gruppen.", + "35": "1 bindingspunkt", + "36": "Definรฉr R-gruppe", + "37": "Fjern R-gruppedefinition", + "38": "Tildel kiler", + "39": "Kilerne passer allerede til stereocentrene.", + "40": "De markerede strukturer", + "41": "Hver struktur pรฅ denne side", + "42": "Ret struktur", + "43": "Der er ingen struktur at analysere.", + "44": "Analyse kopieret", + "45": "Kunne ikke kopiere til udklipsholderen", + "46": "Find substruktur", + "47": "SMARTS", + "48": "Tegn fรธrst de strukturer, der skal sรธges i pรฅ denne side.", + "49": "kun de fรธrste resultater", + "50": "Ingen match pรฅ denne side.", + "51": "Tegn fรธrst en struktur med R-gruppeatomer, og definรฉr dens R-grupper.", + "52": "Der er ingen struktur at skrive som SMARTS.", + "53": "Lagring af SMARTS-filer kommer med filformaterne i 0.7.0; SMARTS blev kopieret i stedet.", + "54": "Tegner hvert implicit hydrogen pรฅ de markerede atomer (eller pรฅ hver struktur pรฅ siden) som et eksplicit H-atom placeret af motoren, i รฉt fortryd-trin.", + "55": "Fjerner eksplicitte H-atomer fra markeringen (eller siden), men beholder hydrogener, der bรฆrer stereokemi, en isotop, en ladning eller et kortlรฆgningsnummer, eller som brobinder to atomer.", + "56": "Erstatter de markerede forkortelsesatomer (eller hver forkortelse pรฅ siden) med deres fulde struktur, lagt ud langs bindingspunktets binding.", + "57": "Sammentrรฆk forkortelse...", + "58": "Samler den markerede atomgruppe i รฉt forkortelsesatom med den etiket, brugeren vรฆlger eller skriver.", + "59": "Viser eller skjuler R-, S-, E- og Z-etiketter ved stereocentre og stereodobbeltbindinger.", + "60": "Vis udvidede stereogrupper", + "61": "Viser eller skjuler gruppeetiketterne abs, and og or ved stereocentre, mens stereoetiketter er slรฅet til.", + "62": "Vis forespรธrgselsegenskaber", + "63": "Viser eller skjuler markeringer for atomlister, forespรธrgselsbindinger og R-grupper pรฅ lรฆrredet.", + "64": "Placerer de markerede stereocentre i en udvidet stereogruppe: abs, and n eller or n. Uden n oprettes en ny and- eller or-gruppe.", + "65": "abs, and eller or", + "66": "Gruppenummer for and og or", + "67": "Absolut (abs)", + "68": "Ny AND-gruppe", + "69": "Ny OR-gruppe", + "70": "Stereogruppe...", + "71": "Atomliste...", + "72": "Gรธr de markerede atomer til en atomliste- eller ikke-liste-forespรธrgsel valgt i det periodiske system.", + "73": "Gรธr de markerede bindinger til forespรธrgselsbindinger: any, single_or_double, single_or_aromatic eller double_or_aromatic; udelad query for at rydde.", + "74": "Forespรธrgselsbindingens type", + "75": "Definรฉr R-gruppe...", + "76": "Gรธr det markerede atom til en R-gruppeetiket og definerer dens medlemmer, forekomst, rest-H og hvis-sรฅ-betingelse.", + "77": "Lader motoren vรฆlge kile- og stiplede bindinger, der entydigt udtrykker stereocentrene i markeringen (eller siden).", + "78": "Viser problemer med valens, stereokemi, geometri og etiketter i markeringen (eller siden) i et panel, hvis rรฆkker markerer atomerne.", + "79": "ร…bner analysepanelet med de beregnede egenskaber for markeringen eller siden.", + "80": "Kopierer formel, masser, grundstofanalyse og de beregnede egenskaber med deres metoder som tekst.", + "81": "Find substruktur...", + "82": "Markerer hvert match af de markerede atomer (eller af et SMARTS-mรธnster) i de andre strukturer pรฅ siden.", + "83": "Opregn R-grupper...", + "84": "Viser hver struktur, som det markerede Markush-skelet (eller det fรธrste pรฅ siden) stรฅr for, med formel og SMILES, op til 1000; listen kan kopieres.", + "85": "Kopiรฉr som SMARTS", + "86": "Kopierer de markerede atomer (eller hver struktur pรฅ siden) som SMARTS med atomlister, generiske atomer, forespรธrgselsbindinger og de รธvrige forespรธrgselsegenskaber.", + "87": "Eksportรฉr SMARTS...", + "88": "Gemmer de markerede atomer (eller hver struktur pรฅ siden) som en SMARTS-fil (.sma).", + "89": "Udvidet stereokemi", + "90": "Forespรธrgsel", + "91": "Objekt", + "92": "Markรฉr fรธrst de strukturer eller den tekst, der skal have en rolle.", + "93": "Angiv reaktionsroller...", + "94": "Angiver rollen for de markerede strukturer eller tekst i det markerede reaktionstrin (reaktant, produkt, agens, betingelse eller ingen) og markerer trinnets roller som angivet manuelt, i รฉt fortryd-trin. Uden role รฅbnes en dialog med trinnets medlemmer og markeringen.", + "95": "Rolle, objekterne skal have; udelad for at รฅbne dialogen", + "96": "Id'er pรฅ de objekter, der skal รฆndres; som standard markeringen", + "97": "Reaktionsrollerne kunne ikke angives", + "98": "rest-H", + "99": "Forkortelse", + "100": "Etiket", + "101": "Sรธg i biblioteket", + "102": "Forkortelsesbiblioteket kunne ikke indlรฆses. Du kan stadig skrive en etiket.", + "103": "Ingen forkortelse matcher. Den etiket, du skriver, bruges, som den er.", + "104": "Egenskaber", + "105": "Atomliste", + "106": "Klik pรฅ grundstoffer i tabellen for at tilfรธje dem.", + "107": "Ryd forespรธrgsel", + "108": "Anvend", + "109": "Fjern", + "110": "Ingen forespรธrgsel", + "111": "[M+Na]+", + "112": "Isotopmรธnster", + "113": "Opregn R-grupper", + "114": "Kopiรฉr SMILES", + "115": "SMILES for hver struktur kopieret", + "116": "Si", + "117": "Vilkรฅrlig binding", + "118": "Enkelt eller dobbelt", + "119": "Enkelt eller aromatisk", + "120": "Dobbelt eller aromatisk", + "121": "Ring eller kรฆde", + "122": "I en ring", + "123": "I en kรฆde", + "124": "Vilkรฅrligt atom (A)", + "125": "Vilkรฅrligt heteroatom (Q)", + "126": "Vilkรฅrligt halogen (X)", + "127": "Vilkรฅrligt metal (M)", + "128": "Angiv bindingstopologi", + "129": "Forespรธrgselsbinding", + "130": "Angiv atomforespรธrgsel", + "131": "Aromatisk", + "132": "Alifatisk", + "133": "Umรฆttet", + "134": "Substitution som tegnet", + "135": "Ringbindinger som tegnet", + "136": "Ryd atomforespรธrgsel", + "137": "Atomforespรธrgsel", + "138": "R-gruppedefinition", + "139": "R-gruppe", + "140": "Medlemmer", + "141": "Tegn hvert medlem som sin egen struktur med et bindingspunkt (*), og รฅbn derefter denne dialog igen.", + "142": "Forekomst", + "143": "Rest-H (usubstituerede positioner er hydrogen)", + "144": "Hvis til stede, sรฅ", + "145": "Fjern definition", + "146": "Agens", + "147": "Betingelse", + "148": "Ryd", + "149": "Fรธj de markerede centre til denne gruppe", + "150": "Kontrollรฉr igen", + "151": "Kontrollerer...", + "152": "Ret", + "153": "Markรฉr pรฅ lรฆrredet" +} From 17a1cbed5861d84d72abd5fe4014b844020a6f60 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:50 -0500 Subject: [PATCH 248/279] feat(i18n): translate the stereo, query and analysis strings into Finnish (0.6.0) Adds the part06 key block for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/fi/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/fi/part06.json diff --git a/frontend/src/i18n/locales/fi/part06.json b/frontend/src/i18n/locales/fi/part06.json new file mode 100644 index 00000000..46ebe9f9 --- /dev/null +++ b/frontend/src/i18n/locales/fi/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hillin jรคrjestys varauksineen, lyhenteet avattuina", + "1": "Standardiatomipainot (CIAAW:n sovinnaiset arvot)", + "2": "Monoisotooppinen massa kunkin alkuaineen yleisimmรคstรค isotoopista", + "3": "Tarkka massa jaettuna varauksen itseisarvolla, elektronin massa korjattuna", + "4": "Kunkin alkuaineen massaprosentti, kaksi desimaalia", + "5": "Atomien osuudet (Wildman ja Crippen 1999)", + "6": "Topologinen polaarinen pinta-ala, N- ja O-fragmentit (Ertl 2000)", + "7": "Moolirefraktio", + "8": "Vetysidosluovuttajat", + "9": "Lipinskin laskenta: N-H- ja O-H-ryhmรคt", + "10": "Vetysidosvastaanottajat", + "11": "Lipinskin laskenta: N- ja O-atomit", + "12": "Pyรถrivรคt sidokset", + "13": "Renkaiden ulkopuoliset yksinkertaiset sidokset pรครคtyasemassa olemattomien raskaiden atomien vรคlillรค, amidin C-N pois lukien", + "14": "Lipinskin viiden sรครคntรถ", + "15": "MW enintรครคn 500, cLogP enintรครคn 5, luovuttajia enintรครคn 5, vastaanottajia enintรครคn 10", + "16": "HBD", + "17": "HBA", + "18": "Hyvรคksytty (0 rikkomusta)", + "19": "Valitse ensin yksi tai useampi atomi", + "20": "Valitse ensin yksi tai useampi sidos", + "21": "Ei lisรคttรคviรค implisiittisiรค vetyjรค.", + "22": "Ei poistettavia eksplisiittisiรค vetyjรค.", + "23": "Valitse avattava lyhenne, kuten Ph tai OTs.", + "24": "Valitse yhden rakenteen yhden ryhmรคn atomit tiivistettรคvรคksi.", + "25": "Valitse tiivistettรคvรค ryhmรค ilman atomia, johon se on kiinnittynyt.", + "26": "Tiivistรค", + "27": "Valitse kirjaston lyhenne tai kirjoita valituille atomeille uusi nimiรถ.", + "28": "Aseta stereoryhmรค", + "29": "Tyhjennรค stereoryhmรค", + "30": "Aseta atomiluettelo", + "31": "Tyhjennรค atomiluettelo", + "32": "Aseta kyselysidos", + "33": "Tyhjennรค sidoskysely", + "34": "Valitse atomi, joka kantaa R-ryhmรครค.", + "35": "1 kiinnityskohta", + "36": "Mรครคritรค R-ryhmรค", + "37": "Poista R-ryhmรคn mรครคritys", + "38": "Mรครคritรค kiilat", + "39": "Kiilat vastaavat jo stereokeskuksia.", + "40": "Valitut rakenteet", + "41": "Jokainen tรคmรคn sivun rakenne", + "42": "Korjaa rakenne", + "43": "Analysoitavaa rakennetta ei ole.", + "44": "Analyysi kopioitu", + "45": "Leikepรถydรคlle kopiointi ei onnistunut", + "46": "Hae osarakennetta", + "47": "SMARTS", + "48": "Piirrรค ensin rakenteet, joista haetaan tรคltรค sivulta.", + "49": "vain ensimmรคiset tulokset", + "50": "Ei osumia tรคllรค sivulla.", + "51": "Piirrรค ensin rakenne, jossa on R-ryhmรคatomeja, ja mรครคritรค sen R-ryhmรคt.", + "52": "SMARTS-muotoon kirjoitettavaa rakennetta ei ole.", + "53": "SMARTS-tiedostojen tallennus tulee tiedostomuotojen mukana versiossa 0.7.0; SMARTS kopioitiin sen sijaan.", + "54": "Piirtรครค valittujen atomien (tai sivun jokaisen rakenteen) jokaisen implisiittisen vedyn eksplisiittisenรค H-atomina, jonka moottori sijoittaa, yhtenรค kumoamisvaiheena.", + "55": "Poistaa eksplisiittiset H-atomit valinnasta (tai sivulta) mutta sรคilyttรครค vedyt, joilla on stereokemiaa, isotooppi, varaus tai kartoitusnumero tai jotka siltaavat kaksi atomia.", + "56": "Korvaa valitut lyhenneatomit (tai sivun jokaisen lyhenteen) tรคydellรค rakenteellaan, joka asetellaan kiinnityssidoksen suuntaan.", + "57": "Tiivistรค lyhenteeksi...", + "58": "Tiivistรครค valitun atomiryhmรคn yhdeksi lyhenneatomiksi kรคyttรคjรคn valitsemalla tai kirjoittamalla nimiรถllรค.", + "59": "Nรคyttรครค tai piilottaa R-, S-, E- ja Z-nimiรถt stereokeskusten ja stereodoppelisidosten vieressรค.", + "60": "Nรคytรค laajennetut stereoryhmรคt", + "61": "Nรคyttรครค tai piilottaa ryhmรคnimiรถt abs, and ja or stereokeskusten vieressรค, kun stereonimiรถt ovat nรคkyvissรค.", + "62": "Nรคytรค kyselyominaisuudet", + "63": "Nรคyttรครค tai piilottaa atomiluettelon, kyselysidoksen ja R-ryhmรคn merkinnรคt piirtoalueella.", + "64": "Asettaa valitut stereokeskukset laajennettuun stereoryhmรครคn: abs, and n tai or n. Ilman n luodaan uusi and- tai or-ryhmรค.", + "65": "abs, and tai or", + "66": "Ryhmรคn numero ryhmille and ja or", + "67": "Absoluuttinen (abs)", + "68": "Uusi AND-ryhmรค", + "69": "Uusi OR-ryhmรค", + "70": "Stereoryhmรค...", + "71": "Atomiluettelo...", + "72": "Muuttaa valitut atomit jaksollisesta jรคrjestelmรคstรค valittavaksi atomiluettelo- tai ei-luettelokyselyksi.", + "73": "Muuttaa valitut sidokset kyselysidoksiksi: any, single_or_double, single_or_aromatic tai double_or_aromatic; jรคtรค query pois tyhjentรครคksesi.", + "74": "Kyselysidoksen tyyppi", + "75": "Mรครคritรค R-ryhmรค...", + "76": "Muuttaa valitun atomin R-ryhmรคnimiรถksi ja mรครคrittรครค sen jรคsenet, esiintymiskerrat, jรครคnnรถs-H:n ja jos-niin-ehdon.", + "77": "Antaa moottorin valita kiila- ja katkoviivasidokset, jotka ilmaisevat valinnan (tai sivun) stereokeskukset yksiselitteisesti.", + "78": "Luettelee valinnan (tai sivun) valenssi-, stereo-, geometria- ja nimiรถongelmat paneelissa, jonka rivit valitsevat atomit.", + "79": "Avaa analyysipaneelin, jossa on valinnan tai sivun lasketut ominaisuudet.", + "80": "Kopioi kaavan, massat, alkuaineanalyysin ja lasketut ominaisuudet menetelmineen tekstinรค.", + "81": "Hae osarakennetta...", + "82": "Valitsee valittujen atomien (tai SMARTS-mallin) jokaisen osuman sivun muissa rakenteissa.", + "83": "Luettele R-ryhmรคt...", + "84": "Luettelee jokaisen rakenteen, jota valittu Markush-runko (tai sivun ensimmรคinen) edustaa, kaavoineen ja SMILES-merkkijonoineen, enintรครคn 1000; luettelon voi kopioida.", + "85": "Kopioi SMARTS-muodossa", + "86": "Kopioi valitut atomit (tai sivun jokaisen rakenteen) SMARTS-muodossa atomiluetteloineen, yleisatomeineen, kyselysidoksineen ja muine kyselyominaisuuksineen.", + "87": "Vie SMARTS...", + "88": "Tallentaa valitut atomit (tai sivun jokaisen rakenteen) SMARTS-tiedostona (.sma).", + "89": "Laajennettu stereokemia", + "90": "Kysely", + "91": "Objekti", + "92": "Valitse ensin rakenteet tai teksti, joille annetaan rooli.", + "93": "Aseta reaktioroolit...", + "94": "Asettaa valittujen rakenteiden tai tekstin roolin valitussa reaktiovaiheessa (lรคhtรถaine, tuote, aine, olosuhde tai ei mikรครคn) ja merkitsee vaiheen roolit kรคsin asetetuiksi yhtenรค kumoamisvaiheena. Ilman role avautuu valintaikkuna, jossa on vaiheen jรคsenet ja valinta.", + "95": "Objekteille annettava rooli; jรคtรค pois avataksesi valintaikkunan", + "96": "Muutettavien objektien tunnukset; oletuksena valinta", + "97": "Reaktiorooleja ei voitu asettaa", + "98": "jรครคnnรถs-H", + "99": "Lyhenne", + "100": "Nimiรถ", + "101": "Hae kirjastosta", + "102": "Lyhennekirjastoa ei voitu ladata. Voit silti kirjoittaa nimiรถn.", + "103": "Mikรครคn lyhenne ei vastaa. Kirjoittamaasi nimiรถtรค kรคytetรครคn sellaisenaan.", + "104": "Ominaisuudet", + "105": "Atomiluettelo", + "106": "Lisรครค alkuaineita napsauttamalla niitรค taulukossa.", + "107": "Tyhjennรค kysely", + "108": "Kรคytรค", + "109": "Poista", + "110": "Ei kyselyรค", + "111": "[M+Na]+", + "112": "Isotooppikuvio", + "113": "Luettele R-ryhmรคt", + "114": "Kopioi SMILES", + "115": "Jokaisen rakenteen SMILES kopioitu", + "116": "Si", + "117": "Mikรค tahansa sidos", + "118": "Yksinkertainen tai kaksois", + "119": "Yksinkertainen tai aromaattinen", + "120": "Kaksois tai aromaattinen", + "121": "Rengas tai ketju", + "122": "Renkaassa", + "123": "Ketjussa", + "124": "Mikรค tahansa atomi (A)", + "125": "Mikรค tahansa heteroatomi (Q)", + "126": "Mikรค tahansa halogeeni (X)", + "127": "Mikรค tahansa metalli (M)", + "128": "Aseta sidoksen topologia", + "129": "Kyselysidos", + "130": "Aseta atomikysely", + "131": "Aromaattinen", + "132": "Alifaattinen", + "133": "Tyydyttymรคtรถn", + "134": "Substituutio piirretyn mukaan", + "135": "Rengassidokset piirretyn mukaan", + "136": "Tyhjennรค atomikysely", + "137": "Atomikysely", + "138": "R-ryhmรคn mรครคritys", + "139": "R-ryhmรค", + "140": "Jรคsenet", + "141": "Piirrรค jokainen jรคsen omaksi rakenteekseen, jossa on kiinnityskohta (*), ja avaa sitten tรคmรค valintaikkuna uudelleen.", + "142": "Esiintymiskerrat", + "143": "Jรครคnnรถs-H (substituoimattomat paikat ovat vetyรค)", + "144": "Jos lรคsnรค, niin", + "145": "Poista mรครคritys", + "146": "Aine", + "147": "Olosuhde", + "148": "Tyhjennรค", + "149": "Lisรครค valitut keskukset tรคhรคn ryhmรครคn", + "150": "Tarkista uudelleen", + "151": "Tarkistetaan...", + "152": "Korjaa", + "153": "Valitse piirtoalueelta" +} From 4a93eb4d30031e527e764e0ffd2adf331ec4b0ff Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:40 -0500 Subject: [PATCH 249/279] =?UTF-8?q?feat(i18n):=20translate=20the=20stereo,?= =?UTF-8?q?=20query=20and=20analysis=20strings=20into=20Norwegian=20Bokm?= =?UTF-8?q?=C3=A5l=20(0.6.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the part06 strings for Norwegian Bokmรฅl so the 0.6.0 stereochemistry, query and analysis UI is localised. --- frontend/src/i18n/locales/nb/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/nb/part06.json diff --git a/frontend/src/i18n/locales/nb/part06.json b/frontend/src/i18n/locales/nb/part06.json new file mode 100644 index 00000000..95d2e414 --- /dev/null +++ b/frontend/src/i18n/locales/nb/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill-rekkefรธlge med ladning, forkortelser utvidet", + "1": "Standard atomvekter (konvensjonelle CIAAW-verdier)", + "2": "Monoisotopmasse fra den mest tallrike isotopen av hvert grunnstoff", + "3": "Eksakt masse delt pรฅ absoluttverdien av ladningen, korrigert for elektronmassen", + "4": "Masseprosent av hvert grunnstoff, to desimaler", + "5": "Atombidrag (Wildman and Crippen 1999)", + "6": "Topologisk polart overflateareal, N- og O-fragmenter (Ertl 2000)", + "7": "Molar refraksjon", + "8": "Hydrogenbindingsdonorer", + "9": "Lipinski-telling: N-H- og O-H-grupper", + "10": "Hydrogenbindingsakseptorer", + "11": "Lipinski-telling: N- og O-atomer", + "12": "Roterbare bindinger", + "13": "Enkeltbindinger utenfor ring mellom tunge atomer som ikke er terminale, amid-C-N unntatt", + "14": "Lipinskis femregel", + "15": "MW hรธyst 500, cLogP hรธyst 5, donorer hรธyst 5, akseptorer hรธyst 10", + "16": "HBD", + "17": "HBA", + "18": "Bestรฅtt (0 brudd)", + "19": "Velg ett eller flere atomer fรธrst", + "20": "Velg รฉn eller flere bindinger fรธrst", + "21": "Ingen implisitte hydrogenatomer รฅ legge til.", + "22": "Ingen eksplisitte hydrogenatomer รฅ fjerne.", + "23": "Velg en forkortelse som Ph eller OTs for รฅ utvide den.", + "24": "Velg atomene i รฉn gruppe i รฉn struktur for รฅ trekke den sammen.", + "25": "Velg gruppen som skal trekkes sammen, uten atomet den er festet til.", + "26": "Trekk sammen", + "27": "Velg en forkortelse fra biblioteket eller skriv en ny etikett for de valgte atomene.", + "28": "Angi stereogruppe", + "29": "Fjern stereogruppe", + "30": "Angi atomliste", + "31": "Fjern atomliste", + "32": "Angi spรธrringsbinding", + "33": "Fjern bindingsspรธrring", + "34": "Velg atomet som bรฆrer R-gruppen.", + "35": "1 festepunkt", + "36": "Definer R-gruppe", + "37": "Fjern R-gruppedefinisjon", + "38": "Tildel kiler", + "39": "Kilene stemmer allerede med stereosentrene.", + "40": "De valgte strukturene", + "41": "Alle strukturer pรฅ denne siden", + "42": "Rett opp struktur", + "43": "Det finnes ingen struktur รฅ analysere.", + "44": "Analysen er kopiert", + "45": "Kunne ikke kopiere til utklippstavlen", + "46": "Finn delstruktur", + "47": "SMARTS", + "48": "Tegn strukturene det skal sรธkes etter pรฅ denne siden fรธrst.", + "49": "bare de fรธrste treffene", + "50": "Ingen treff pรฅ denne siden.", + "51": "Tegn fรธrst en struktur med R-gruppeatomer og definer R-gruppene dens.", + "52": "Det finnes ingen struktur รฅ skrive som SMARTS.", + "53": "Lagring av SMARTS-filer kommer med filformatene i 0.7.0; SMARTS ble kopiert i stedet.", + "54": "Tegner hvert implisitt hydrogenatom pรฅ de valgte atomene (eller i alle strukturer pรฅ siden) som et eksplisitt H-atom plassert av motoren, i ett angretrinn.", + "55": "Fjerner eksplisitte H-atomer fra utvalget (eller siden), men beholder hydrogenatomer som bรฆrer stereo, en isotop, en ladning, et kartleggingsnummer eller binder to atomer sammen.", + "56": "Erstatter de valgte forkortelsesatomene (eller alle forkortelser pรฅ siden) med den fullstendige strukturen, lagt ut langs festebindingen.", + "57": "Trekk sammen forkortelse...", + "58": "Trekker den valgte atomgruppen sammen til ett forkortelsesatom med etiketten brukeren velger eller skriver.", + "59": "Viser eller skjuler R-, S-, E- og Z-etiketter ved siden av stereosentre og stereodobbeltbindinger.", + "60": "Vis utvidede stereogrupper", + "61": "Viser eller skjuler etikettene abs, and og or for gruppene ved siden av stereosentre mens stereoetiketter er pรฅ.", + "62": "Vis spรธrringsegenskaper", + "63": "Viser eller skjuler merker for atomlister, spรธrringsbindinger og R-grupper pรฅ lerretet.", + "64": "Legger de valgte stereosentrene i en utvidet stereogruppe: abs, and n eller or n. Uten n lages en ny and- eller or-gruppe.", + "65": "abs, and eller or", + "66": "Gruppenummer for and og or", + "67": "Absolutt (abs)", + "68": "Ny AND-gruppe", + "69": "Ny OR-gruppe", + "70": "Stereogruppe...", + "71": "Atomliste...", + "72": "Gjรธr de valgte atomene om til en atomliste eller en ikke-liste som velges i periodesystemet.", + "73": "Gjรธr de valgte bindingene til spรธrringsbindinger: any, single_or_double, single_or_aromatic eller double_or_aromatic; utelat query for รฅ fjerne.", + "74": "Typen spรธrringsbinding", + "75": "Definer R-gruppe...", + "76": "Gjรธr det valgte atomet til en R-gruppeetikett og definerer medlemmene, forekomsten, rest H og hvis-sรฅ-betingelsen.", + "77": "La motoren velge kile- og stiplede bindinger som uttrykker stereosentrene i utvalget (eller siden) entydig.", + "78": "Viser problemer med valens, stereo, geometri og etiketter i utvalget (eller siden) i et panel der radene velger atomene.", + "79": "ร…pner analysepanelet med de beregnede egenskapene til utvalget eller siden.", + "80": "Kopierer formel, masser, elementanalyse og de beregnede egenskapene med metodene som tekst.", + "81": "Finn delstruktur...", + "82": "Velger alle treff for de valgte atomene (eller et SMARTS-mรธnster) i de andre strukturene pรฅ siden.", + "83": "Tell opp R-grupper...", + "84": "Viser alle strukturer den valgte Markush-skjelettstrukturen (eller den fรธrste pรฅ siden) stรฅr for, med formel og SMILES, opptil 1000; listen kan kopieres.", + "85": "Kopier som SMARTS", + "86": "Kopierer de valgte atomene (eller alle strukturer pรฅ siden) som SMARTS, med atomlister, generiske atomer, spรธrringsbindinger og de andre spรธrringsegenskapene.", + "87": "Eksporter SMARTS...", + "88": "Lagrer de valgte atomene (eller alle strukturer pรฅ siden) som en SMARTS-fil (.sma).", + "89": "Utvidet stereo", + "90": "Spรธrring", + "91": "Objekt", + "92": "Velg strukturene eller teksten som skal fรฅ en rolle fรธrst.", + "93": "Angi reaksjonsroller...", + "94": "Angir rollen til de valgte strukturene eller teksten i det valgte reaksjonstrinnet (reaktant, produkt, agens, betingelse eller ingen) og markerer trinnets roller som satt for hรฅnd, i ett angretrinn. Uten role รฅpnes en dialog som viser trinnets medlemmer og utvalget.", + "95": "Rollen objektene skal fรฅ; utelat den for รฅ รฅpne dialogen", + "96": "Objekt-id-er som skal endres; standard er utvalget", + "97": "Kunne ikke angi reaksjonsrollene", + "98": "rest H", + "99": "Forkortelse", + "100": "Etikett", + "101": "Sรธk i biblioteket", + "102": "Forkortelsesbiblioteket kunne ikke lastes. Du kan fortsatt skrive en etikett.", + "103": "Ingen forkortelse passer. Etiketten du skriver brukes som den er.", + "104": "Egenskaper", + "105": "Atomliste", + "106": "Klikk pรฅ grunnstoffer i tabellen for รฅ legge dem til.", + "107": "Fjern spรธrring", + "108": "Bruk", + "109": "Fjern", + "110": "Ingen spรธrring", + "111": "[M+Na]+", + "112": "Isotopmรธnster", + "113": "Tell opp R-grupper", + "114": "Kopier SMILES", + "115": "SMILES for alle strukturer er kopiert", + "116": "Si", + "117": "Vilkรฅrlig binding", + "118": "Enkelt eller dobbelt", + "119": "Enkelt eller aromatisk", + "120": "Dobbelt eller aromatisk", + "121": "Ring eller kjede", + "122": "I en ring", + "123": "I en kjede", + "124": "Vilkรฅrlig atom (A)", + "125": "Vilkรฅrlig heteroatom (Q)", + "126": "Vilkรฅrlig halogen (X)", + "127": "Vilkรฅrlig metall (M)", + "128": "Angi bindingstopologi", + "129": "Spรธrringsbinding", + "130": "Angi atomspรธrring", + "131": "Aromatisk", + "132": "Alifatisk", + "133": "Umettet", + "134": "Substitusjon som tegnet", + "135": "Ringbindinger som tegnet", + "136": "Fjern atomspรธrring", + "137": "Atomspรธrring", + "138": "R-gruppedefinisjon", + "139": "R-gruppe", + "140": "Medlemmer", + "141": "Tegn hvert medlem som en egen struktur med et festepunkt (*), og รฅpne deretter denne dialogen igjen.", + "142": "Forekomst", + "143": "Rest H (usubstituerte posisjoner er hydrogen)", + "144": "Hvis til stede, sรฅ", + "145": "Fjern definisjon", + "146": "Agens", + "147": "Betingelse", + "148": "Tรธm", + "149": "Legg de valgte sentrene til denne gruppen", + "150": "Kontroller pรฅ nytt", + "151": "Kontrollerer...", + "152": "Rett opp", + "153": "Velg pรฅ lerretet" +} From 45d020848c798a00add08a1aee0c971590afe8a0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:40 -0500 Subject: [PATCH 250/279] feat(i18n): translate the stereo, query and analysis strings into Swedish (0.6.0) Adds the part06 strings for Swedish so the 0.6.0 stereochemistry, query and analysis UI is localised. --- frontend/src/i18n/locales/sv/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/sv/part06.json diff --git a/frontend/src/i18n/locales/sv/part06.json b/frontend/src/i18n/locales/sv/part06.json new file mode 100644 index 00000000..7f15f79b --- /dev/null +++ b/frontend/src/i18n/locales/sv/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill-ordning med laddning, fรถrkortningar expanderade", + "1": "Standardatomvikter (konventionella CIAAW-vรคrden)", + "2": "Monoisotopisk massa frรฅn den vanligaste isotopen av varje grundรคmne", + "3": "Exakt massa delad med laddningens absolutbelopp, korrigerad fรถr elektronmassan", + "4": "Massprocent av varje grundรคmne, tvรฅ decimaler", + "5": "Atombidrag (Wildman and Crippen 1999)", + "6": "Topologisk polรคr ytarea, N- och O-fragment (Ertl 2000)", + "7": "Molรคr refraktivitet", + "8": "Vรคtebindningsdonatorer", + "9": "Lipinski-rรคkning: N-H- och O-H-grupper", + "10": "Vรคtebindningsacceptorer", + "11": "Lipinski-rรคkning: N- och O-atomer", + "12": "Roterbara bindningar", + "13": "Enkelbindningar utanfรถr ring mellan icke-terminala tunga atomer, amid-C-N undantaget", + "14": "Lipinskis femregel", + "15": "MW hรถgst 500, cLogP hรถgst 5, donatorer hรถgst 5, acceptorer hรถgst 10", + "16": "HBD", + "17": "HBA", + "18": "Godkรคnd (0 รถvertrรคdelser)", + "19": "Markera fรถrst en eller flera atomer", + "20": "Markera fรถrst en eller flera bindningar", + "21": "Inga implicita vรคteatomer att lรคgga till.", + "22": "Inga explicita vรคteatomer att ta bort.", + "23": "Markera en fรถrkortning som Ph eller OTs fรถr att expandera den.", + "24": "Markera atomerna i en grupp i en struktur fรถr att dra ihop dem.", + "25": "Markera gruppen som ska dras ihop, utan atomen den sitter pรฅ.", + "26": "Dra ihop", + "27": "Vรคlj en fรถrkortning frรฅn biblioteket eller skriv en ny etikett fรถr de markerade atomerna.", + "28": "Ange stereogrupp", + "29": "Rensa stereogrupp", + "30": "Ange atomlista", + "31": "Rensa atomlista", + "32": "Ange frรฅgebindning", + "33": "Rensa bindningsfrรฅga", + "34": "Markera atomen som bรคr R-gruppen.", + "35": "1 fรคstpunkt", + "36": "Definiera R-grupp", + "37": "Ta bort R-gruppsdefinition", + "38": "Tilldela kilar", + "39": "Kilarna stรคmmer redan med stereocentra.", + "40": "De markerade strukturerna", + "41": "Varje struktur pรฅ den hรคr sidan", + "42": "Rรคtta struktur", + "43": "Det finns ingen struktur att analysera.", + "44": "Analysen kopierades", + "45": "Det gick inte att kopiera till urklipp", + "46": "Sรถk delstruktur", + "47": "SMARTS", + "48": "Rita fรถrst strukturerna att sรถka efter pรฅ den hรคr sidan.", + "49": "endast de fรถrsta trรคffarna", + "50": "Inga trรคffar pรฅ den hรคr sidan.", + "51": "Rita fรถrst en struktur med R-gruppsatomer och definiera dess R-grupper.", + "52": "Det finns ingen struktur att skriva som SMARTS.", + "53": "Att spara SMARTS-filer kommer med filformaten i 0.7.0; SMARTS kopierades i stรคllet.", + "54": "Ritar varje implicit vรคteatom pรฅ de markerade atomerna (eller i alla strukturer pรฅ sidan) som en explicit H-atom placerad av motorn, i ett รฅngra-steg.", + "55": "Tar bort explicita H-atomer frรฅn markeringen (eller sidan), men behรฅller vรคteatomer som bรคr stereo, en isotop, en laddning, ett mappningsnummer eller binder tvรฅ atomer.", + "56": "Ersรคtter de markerade fรถrkortningsatomerna (eller alla fรถrkortningar pรฅ sidan) med sin fullstรคndiga struktur, utlagd lรคngs fรคstbindningen.", + "57": "Dra ihop fรถrkortning...", + "58": "Drar ihop den markerade atomgruppen till en fรถrkortningsatom med den etikett som anvรคndaren vรคljer eller skriver.", + "59": "Visar eller dรถljer R-, S-, E- och Z-etiketter intill stereocentra och stereodubbelbindningar.", + "60": "Visa utรถkade stereogrupper", + "61": "Visar eller dรถljer etiketterna abs, and och or fรถr grupper intill stereocentra medan stereoetiketter รคr pรฅ.", + "62": "Visa frรฅgeegenskaper", + "63": "Visar eller dรถljer markeringar fรถr atomlistor, frรฅgebindningar och R-grupper pรฅ ritytan.", + "64": "Lรคgger de markerade stereocentra i en utรถkad stereogrupp: abs, and n eller or n. Utan n skapas en ny and- eller or-grupp.", + "65": "abs, and eller or", + "66": "Gruppnummer fรถr and och or", + "67": "Absolut (abs)", + "68": "Ny AND-grupp", + "69": "Ny OR-grupp", + "70": "Stereogrupp...", + "71": "Atomlista...", + "72": "Gรถr de markerade atomerna till en atomlista eller en icke-lista som vรคljs i periodiska systemet.", + "73": "Gรถr de markerade bindningarna till frรฅgebindningar: any, single_or_double, single_or_aromatic eller double_or_aromatic; utelรคmna query fรถr att rensa.", + "74": "Typen av frรฅgebindning", + "75": "Definiera R-grupp...", + "76": "Gรถr den markerade atomen till en R-gruppsetikett och definierar dess medlemmar, fรถrekomst, rest H och om-sรฅ-villkor.", + "77": "Lรฅter motorn vรคlja kil- och streckade bindningar som entydigt uttrycker stereocentra i markeringen (eller sidan).", + "78": "Listar problem med valens, stereo, geometri och etiketter i markeringen (eller sidan) i en panel vars rader markerar atomerna.", + "79": "ร–ppnar analyspanelen med de berรคknade egenskaperna fรถr markeringen eller sidan.", + "80": "Kopierar formel, massor, elementaranalys och de berรคknade egenskaperna med sina metoder som text.", + "81": "Sรถk delstruktur...", + "82": "Markerar varje trรคff fรถr de markerade atomerna (eller ett SMARTS-mรถnster) i de andra strukturerna pรฅ sidan.", + "83": "Rรคkna upp R-grupper...", + "84": "Listar varje struktur som den markerade Markush-grundstrukturen (eller den fรถrsta pรฅ sidan) stรฅr fรถr, med formel och SMILES, upp till 1000; listan kan kopieras.", + "85": "Kopiera som SMARTS", + "86": "Kopierar de markerade atomerna (eller alla strukturer pรฅ sidan) som SMARTS, med atomlistor, generiska atomer, frรฅgebindningar och รถvriga frรฅgeegenskaper.", + "87": "Exportera SMARTS...", + "88": "Sparar de markerade atomerna (eller alla strukturer pรฅ sidan) som en SMARTS-fil (.sma).", + "89": "Utรถkad stereo", + "90": "Frรฅga", + "91": "Objekt", + "92": "Markera fรถrst strukturerna eller texten som ska fรฅ en roll.", + "93": "Ange reaktionsroller...", + "94": "Anger rollen fรถr de markerade strukturerna eller texten i det markerade reaktionssteget (reaktant, produkt, agens, villkor eller ingen) och markerar stegets roller som instรคllda fรถr hand, i ett รฅngra-steg. Utan role รถppnas en dialogruta som listar stegets medlemmar och markeringen.", + "95": "Roll att ge objekten; utelรคmna fรถr att รถppna dialogrutan", + "96": "Objekt-id:n att รคndra; standard รคr markeringen", + "97": "Det gick inte att ange reaktionsrollerna", + "98": "rest H", + "99": "Fรถrkortning", + "100": "Etikett", + "101": "Sรถk i biblioteket", + "102": "Fรถrkortningsbiblioteket kunde inte lรคsas in. Du kan fortfarande skriva en etikett.", + "103": "Ingen fรถrkortning matchar. Etiketten du skriver anvรคnds som den รคr.", + "104": "Egenskaper", + "105": "Atomlista", + "106": "Klicka pรฅ grundรคmnen i tabellen fรถr att lรคgga till dem.", + "107": "Rensa frรฅga", + "108": "Verkstรคll", + "109": "Ta bort", + "110": "Ingen frรฅga", + "111": "[M+Na]+", + "112": "Isotopmรถnster", + "113": "Rรคkna upp R-grupper", + "114": "Kopiera SMILES", + "115": "SMILES fรถr varje struktur kopierades", + "116": "Si", + "117": "Valfri bindning", + "118": "Enkel eller dubbel", + "119": "Enkel eller aromatisk", + "120": "Dubbel eller aromatisk", + "121": "Ring eller kedja", + "122": "I en ring", + "123": "I en kedja", + "124": "Valfri atom (A)", + "125": "Valfri heteroatom (Q)", + "126": "Valfri halogen (X)", + "127": "Valfri metall (M)", + "128": "Ange bindningstopologi", + "129": "Frรฅgebindning", + "130": "Ange atomfrรฅga", + "131": "Aromatisk", + "132": "Alifatisk", + "133": "Omรคttad", + "134": "Substitution som ritad", + "135": "Ringbindningar som ritade", + "136": "Rensa atomfrรฅga", + "137": "Atomfrรฅga", + "138": "R-gruppsdefinition", + "139": "R-grupp", + "140": "Medlemmar", + "141": "Rita varje medlem som en egen struktur med en fรคstpunkt (*) och รถppna sedan den hรคr dialogrutan igen.", + "142": "Fรถrekomst", + "143": "Rest H (osubstituerade positioner รคr vรคte)", + "144": "Om nรคrvarande, dรฅ", + "145": "Ta bort definition", + "146": "Agens", + "147": "Villkor", + "148": "Rensa", + "149": "Lรคgg till de markerade centrumen i den hรคr gruppen", + "150": "Kontrollera igen", + "151": "Kontrollerar...", + "152": "Rรคtta", + "153": "Markera pรฅ ritytan" +} From 717598f0f4f6d52c75a8b3df0a0c194d711fcfcf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:40 -0500 Subject: [PATCH 251/279] feat(i18n): translate the stereo, query and analysis strings into Russian (0.6.0) Adds the part06 strings for Russian so the 0.6.0 stereochemistry, query and analysis UI is localised. --- frontend/src/i18n/locales/ru/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/ru/part06.json diff --git a/frontend/src/i18n/locales/ru/part06.json b/frontend/src/i18n/locales/ru/part06.json new file mode 100644 index 00000000..61333d7d --- /dev/null +++ b/frontend/src/i18n/locales/ru/part06.json @@ -0,0 +1,156 @@ +{ + "0": "ะŸะพั€ัะดะพะบ ะฅะธะปะปะฐ ั ะทะฐั€ัะดะพะผ, ัะพะบั€ะฐั‰ะตะฝะธั ั€ะฐัะบั€ั‹ั‚ั‹", + "1": "ะกั‚ะฐะฝะดะฐั€ั‚ะฝั‹ะต ะฐั‚ะพะผะฝั‹ะต ะผะฐััั‹ (ัƒัะปะพะฒะฝั‹ะต ะทะฝะฐั‡ะตะฝะธั CIAAW)", + "2": "ะœะพะฝะพะธะทะพั‚ะพะฟะฝะฐั ะผะฐััะฐ ะฟะพ ัะฐะผะพะผัƒ ั€ะฐัะฟั€ะพัั‚ั€ะฐะฝั‘ะฝะฝะพะผัƒ ะธะทะพั‚ะพะฟัƒ ะบะฐะถะดะพะณะพ ัะปะตะผะตะฝั‚ะฐ", + "3": "ะขะพั‡ะฝะฐั ะผะฐััะฐ, ะดะตะปั‘ะฝะฝะฐั ะฝะฐ ะฐะฑัะพะปัŽั‚ะฝัƒัŽ ะฒะตะปะธั‡ะธะฝัƒ ะทะฐั€ัะดะฐ, ั ะฟะพะฟั€ะฐะฒะบะพะน ะฝะฐ ะผะฐัััƒ ัะปะตะบั‚ั€ะพะฝะฐ", + "4": "ะœะฐััะพะฒะฐั ะดะพะปั ะบะฐะถะดะพะณะพ ัะปะตะผะตะฝั‚ะฐ ะฒ ะฟั€ะพั†ะตะฝั‚ะฐั…, ะดะฒะฐ ะทะฝะฐะบะฐ ะฟะพัะปะต ะทะฐะฟัั‚ะพะน", + "5": "ะ’ะบะปะฐะดั‹ ะฐั‚ะพะผะพะฒ (Wildman and Crippen 1999)", + "6": "ะขะพะฟะพะปะพะณะธั‡ะตัะบะฐั ะฟะพะปัั€ะฝะฐั ะฟะปะพั‰ะฐะดัŒ ะฟะพะฒะตั€ั…ะฝะพัั‚ะธ, ั„ั€ะฐะณะผะตะฝั‚ั‹ N ะธ O (Ertl 2000)", + "7": "ะœะพะปัั€ะฝะฐั ั€ะตั„ั€ะฐะบั†ะธั", + "8": "ะ”ะพะฝะพั€ั‹ ะฒะพะดะพั€ะพะดะฝะพะน ัะฒัะทะธ", + "9": "ะŸะพะดัั‡ั‘ั‚ ะฟะพ ะ›ะธะฟะธะฝัะบะธ: ะณั€ัƒะฟะฟั‹ N-H ะธ O-H", + "10": "ะะบั†ะตะฟั‚ะพั€ั‹ ะฒะพะดะพั€ะพะดะฝะพะน ัะฒัะทะธ", + "11": "ะŸะพะดัั‡ั‘ั‚ ะฟะพ ะ›ะธะฟะธะฝัะบะธ: ะฐั‚ะพะผั‹ N ะธ O", + "12": "ะ’ั€ะฐั‰ะฐะตะผั‹ะต ัะฒัะทะธ", + "13": "ะžะดะธะฝะฐั€ะฝั‹ะต ัะฒัะทะธ ะฒะฝะต ั†ะธะบะปะฐ ะผะตะถะดัƒ ะฝะตั‚ะตั€ะผะธะฝะฐะปัŒะฝั‹ะผะธ ั‚ัะถั‘ะปั‹ะผะธ ะฐั‚ะพะผะฐะผะธ, ะฐะผะธะดะฝะฐั ัะฒัะทัŒ C-N ะธัะบะปัŽั‡ะตะฝะฐ", + "14": "ะŸั€ะฐะฒะธะปะพ ะฟัั‚ะธ ะ›ะธะฟะธะฝัะบะธ", + "15": "MW ะฝะต ะฑะพะปะตะต 500, cLogP ะฝะต ะฑะพะปะตะต 5, ะดะพะฝะพั€ะพะฒ ะฝะต ะฑะพะปะตะต 5, ะฐะบั†ะตะฟั‚ะพั€ะพะฒ ะฝะต ะฑะพะปะตะต 10", + "16": "HBD", + "17": "HBA", + "18": "ะŸั€ะพะนะดะตะฝะพ (0 ะฝะฐั€ัƒัˆะตะฝะธะน)", + "19": "ะกะฝะฐั‡ะฐะปะฐ ะฒั‹ะฑะตั€ะธั‚ะต ะพะดะธะฝ ะธะปะธ ะฝะตัะบะพะปัŒะบะพ ะฐั‚ะพะผะพะฒ", + "20": "ะกะฝะฐั‡ะฐะปะฐ ะฒั‹ะฑะตั€ะธั‚ะต ะพะดะฝัƒ ะธะปะธ ะฝะตัะบะพะปัŒะบะพ ัะฒัะทะตะน", + "21": "ะะตั‚ ะฝะตัะฒะฝั‹ั… ะฐั‚ะพะผะพะฒ ะฒะพะดะพั€ะพะดะฐ ะดะปั ะดะพะฑะฐะฒะปะตะฝะธั.", + "22": "ะะตั‚ ัะฒะฝั‹ั… ะฐั‚ะพะผะพะฒ ะฒะพะดะพั€ะพะดะฐ ะดะปั ัƒะดะฐะปะตะฝะธั.", + "23": "ะ’ั‹ะฑะตั€ะธั‚ะต ัะพะบั€ะฐั‰ะตะฝะธะต, ะฝะฐะฟั€ะธะผะตั€ Ph ะธะปะธ OTs, ั‡ั‚ะพะฑั‹ ั€ะฐัะบั€ั‹ั‚ัŒ ะตะณะพ.", + "24": "ะ’ั‹ะฑะตั€ะธั‚ะต ะฐั‚ะพะผั‹ ะพะดะฝะพะน ะณั€ัƒะฟะฟั‹ ะฒ ะพะดะฝะพะน ัั‚ั€ัƒะบั‚ัƒั€ะต, ั‡ั‚ะพะฑั‹ ัะฒะตั€ะฝัƒั‚ัŒ ะตั‘.", + "25": "ะ’ั‹ะฑะตั€ะธั‚ะต ะณั€ัƒะฟะฟัƒ ะดะปั ัะฒะพั€ะฐั‡ะธะฒะฐะฝะธั, ะฑะตะท ะฐั‚ะพะผะฐ, ะบ ะบะพั‚ะพั€ะพะผัƒ ะพะฝะฐ ะฟั€ะธัะพะตะดะธะฝะตะฝะฐ.", + "26": "ะกะฒะตั€ะฝัƒั‚ัŒ", + "27": "ะ’ั‹ะฑะตั€ะธั‚ะต ัะพะบั€ะฐั‰ะตะฝะธะต ะธะท ะฑะธะฑะปะธะพั‚ะตะบะธ ะธะปะธ ะฒะฒะตะดะธั‚ะต ะฝะพะฒัƒัŽ ะผะตั‚ะบัƒ ะดะปั ะฒั‹ะฑั€ะฐะฝะฝั‹ั… ะฐั‚ะพะผะพะฒ.", + "28": "ะ—ะฐะดะฐั‚ัŒ ัั‚ะตั€ะตะพะณั€ัƒะฟะฟัƒ", + "29": "ะžั‡ะธัั‚ะธั‚ัŒ ัั‚ะตั€ะตะพะณั€ัƒะฟะฟัƒ", + "30": "ะ—ะฐะดะฐั‚ัŒ ัะฟะธัะพะบ ะฐั‚ะพะผะพะฒ", + "31": "ะžั‡ะธัั‚ะธั‚ัŒ ัะฟะธัะพะบ ะฐั‚ะพะผะพะฒ", + "32": "ะ—ะฐะดะฐั‚ัŒ ัะฒัะทัŒ-ะทะฐะฟั€ะพั", + "33": "ะžั‡ะธัั‚ะธั‚ัŒ ะทะฐะฟั€ะพั ัะฒัะทะธ", + "34": "ะ’ั‹ะฑะตั€ะธั‚ะต ะฐั‚ะพะผ, ะฝะตััƒั‰ะธะน R-ะณั€ัƒะฟะฟัƒ.", + "35": "1 ั‚ะพั‡ะบะฐ ะฟั€ะธัะพะตะดะธะฝะตะฝะธั", + "36": "ะžะฟั€ะตะดะตะปะธั‚ัŒ R-ะณั€ัƒะฟะฟัƒ", + "37": "ะฃะดะฐะปะธั‚ัŒ ะพะฟั€ะตะดะตะปะตะฝะธะต R-ะณั€ัƒะฟะฟั‹", + "38": "ะะฐะทะฝะฐั‡ะธั‚ัŒ ะบะปะธะฝัŒั", + "39": "ะšะปะธะฝัŒั ัƒะถะต ัะพะพั‚ะฒะตั‚ัั‚ะฒัƒัŽั‚ ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ะฐะผ.", + "40": "ะ’ั‹ะฑั€ะฐะฝะฝั‹ะต ัั‚ั€ัƒะบั‚ัƒั€ั‹", + "41": "ะ’ัะต ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะฝะฐ ัั‚ะพะน ัั‚ั€ะฐะฝะธั†ะต", + "42": "ะ˜ัะฟั€ะฐะฒะธั‚ัŒ ัั‚ั€ัƒะบั‚ัƒั€ัƒ", + "43": "ะะตั‚ ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะดะปั ะฐะฝะฐะปะธะทะฐ.", + "44": "ะะฝะฐะปะธะท ัะบะพะฟะธั€ะพะฒะฐะฝ", + "45": "ะะต ัƒะดะฐะปะพััŒ ัะบะพะฟะธั€ะพะฒะฐั‚ัŒ ะฒ ะฑัƒั„ะตั€ ะพะฑะผะตะฝะฐ", + "46": "ะะฐะนั‚ะธ ะฟะพะดัั‚ั€ัƒะบั‚ัƒั€ัƒ", + "47": "SMARTS", + "48": "ะกะฝะฐั‡ะฐะปะฐ ะฝะฐั€ะธััƒะนั‚ะต ะฝะฐ ัั‚ะพะน ัั‚ั€ะฐะฝะธั†ะต ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะดะปั ะฟะพะธัะบะฐ.", + "49": "ั‚ะพะปัŒะบะพ ะฟะตั€ะฒั‹ะต ั€ะตะทัƒะปัŒั‚ะฐั‚ั‹", + "50": "ะะฐ ัั‚ะพะน ัั‚ั€ะฐะฝะธั†ะต ะฝะตั‚ ัะพะฒะฟะฐะดะตะฝะธะน.", + "51": "ะกะฝะฐั‡ะฐะปะฐ ะฝะฐั€ะธััƒะนั‚ะต ัั‚ั€ัƒะบั‚ัƒั€ัƒ ั ะฐั‚ะพะผะฐะผะธ R-ะณั€ัƒะฟะฟ ะธ ะพะฟั€ะตะดะตะปะธั‚ะต ะตั‘ R-ะณั€ัƒะฟะฟั‹.", + "52": "ะะตั‚ ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะดะปั ะทะฐะฟะธัะธ ะฒ ะฒะธะดะต SMARTS.", + "53": "ะกะพั…ั€ะฐะฝะตะฝะธะต ั„ะฐะนะปะพะฒ SMARTS ะฟะพัะฒะธั‚ัั ะฒะผะตัั‚ะต ั ั„ะพั€ะผะฐั‚ะฐะผะธ ั„ะฐะนะปะพะฒ ะฒ 0.7.0; ะฒะผะตัั‚ะพ ัั‚ะพะณะพ SMARTS ัะบะพะฟะธั€ะพะฒะฐะฝ.", + "54": "ะ ะธััƒะตั‚ ะบะฐะถะดั‹ะน ะฝะตัะฒะฝั‹ะน ะฐั‚ะพะผ ะฒะพะดะพั€ะพะดะฐ ะฒั‹ะฑั€ะฐะฝะฝั‹ั… ะฐั‚ะพะผะพะฒ (ะธะปะธ ะฒัะตั… ัั‚ั€ัƒะบั‚ัƒั€ ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต) ะบะฐะบ ัะฒะฝั‹ะน ะฐั‚ะพะผ H, ั€ะฐะทะผะตั‰ั‘ะฝะฝั‹ะน ะดะฒะธะถะบะพะผ, ะพะดะฝะธะผ ัˆะฐะณะพะผ ะพั‚ะผะตะฝั‹.", + "55": "ะฃะดะฐะปัะตั‚ ัะฒะฝั‹ะต ะฐั‚ะพะผั‹ H ะธะท ะฒั‹ะดะตะปะตะฝะธั (ะธะปะธ ัั‚ั€ะฐะฝะธั†ั‹), ัะพั…ั€ะฐะฝัั ะฐั‚ะพะผั‹ ะฒะพะดะพั€ะพะดะฐ ัะพ ัั‚ะตั€ะตะพะบะพะฝั„ะธะณัƒั€ะฐั†ะธะตะน, ะธะทะพั‚ะพะฟะพะผ, ะทะฐั€ัะดะพะผ, ะฝะพะผะตั€ะพะผ ะพั‚ะพะฑั€ะฐะถะตะฝะธั ะธะปะธ ะผะพัั‚ะธะบะพะฒั‹ะต ะผะตะถะดัƒ ะดะฒัƒะผั ะฐั‚ะพะผะฐะผะธ.", + "56": "ะ—ะฐะผะตะฝัะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ะฐั‚ะพะผั‹-ัะพะบั€ะฐั‰ะตะฝะธั (ะธะปะธ ะฒัะต ัะพะบั€ะฐั‰ะตะฝะธั ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต) ะธั… ะฟะพะปะฝะพะน ัั‚ั€ัƒะบั‚ัƒั€ะพะน, ัƒะปะพะถะตะฝะฝะพะน ะฒะดะพะปัŒ ัะฒัะทะธ ะฟั€ะธัะพะตะดะธะฝะตะฝะธั.", + "57": "ะกะฒะตั€ะฝัƒั‚ัŒ ัะพะบั€ะฐั‰ะตะฝะธะต...", + "58": "ะกะฒะพั€ะฐั‡ะธะฒะฐะตั‚ ะฒั‹ะฑั€ะฐะฝะฝัƒัŽ ะณั€ัƒะฟะฟัƒ ะฐั‚ะพะผะพะฒ ะฒ ะพะดะธะฝ ะฐั‚ะพะผ-ัะพะบั€ะฐั‰ะตะฝะธะต ั ะผะตั‚ะบะพะน, ะบะพั‚ะพั€ัƒัŽ ะฟะพะปัŒะทะพะฒะฐั‚ะตะปัŒ ะฒั‹ะฑะธั€ะฐะตั‚ ะธะปะธ ะฒะฒะพะดะธั‚.", + "59": "ะŸะพะบะฐะทั‹ะฒะฐะตั‚ ะธะปะธ ัะบั€ั‹ะฒะฐะตั‚ ะผะตั‚ะบะธ R, S, E ะธ Z ั€ัะดะพะผ ัะพ ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ะฐะผะธ ะธ ัั‚ะตั€ะตะพะดะฒะพะนะฝั‹ะผะธ ัะฒัะทัะผะธ.", + "60": "ะŸะพะบะฐะทั‹ะฒะฐั‚ัŒ ั€ะฐััˆะธั€ะตะฝะฝั‹ะต ัั‚ะตั€ะตะพะณั€ัƒะฟะฟั‹", + "61": "ะŸะพะบะฐะทั‹ะฒะฐะตั‚ ะธะปะธ ัะบั€ั‹ะฒะฐะตั‚ ะผะตั‚ะบะธ ะณั€ัƒะฟะฟ abs, and ะธ or ั€ัะดะพะผ ัะพ ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ะฐะผะธ, ะฟะพะบะฐ ัั‚ะตั€ะตะพะผะตั‚ะบะธ ะฒะบะปัŽั‡ะตะฝั‹.", + "62": "ะŸะพะบะฐะทั‹ะฒะฐั‚ัŒ ะฟั€ะธะทะฝะฐะบะธ ะทะฐะฟั€ะพัะพะฒ", + "63": "ะŸะพะบะฐะทั‹ะฒะฐะตั‚ ะธะปะธ ัะบั€ั‹ะฒะฐะตั‚ ะฝะฐ ั…ะพะปัั‚ะต ะพั‚ะผะตั‚ะบะธ ัะฟะธัะบะพะฒ ะฐั‚ะพะผะพะฒ, ัะฒัะทะตะน-ะทะฐะฟั€ะพัะพะฒ ะธ R-ะณั€ัƒะฟะฟ.", + "64": "ะŸะพะผะตั‰ะฐะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ั‹ ะฒ ั€ะฐััˆะธั€ะตะฝะฝัƒัŽ ัั‚ะตั€ะตะพะณั€ัƒะฟะฟัƒ: abs, and n ะธะปะธ or n. ะ‘ะตะท n ัะพะทะดะฐั‘ั‚ัั ะฝะพะฒะฐั ะณั€ัƒะฟะฟะฐ and ะธะปะธ or.", + "65": "abs, and ะธะปะธ or", + "66": "ะะพะผะตั€ ะณั€ัƒะฟะฟั‹ ะดะปั and ะธ or", + "67": "ะะฑัะพะปัŽั‚ะฝะฐั (abs)", + "68": "ะะพะฒะฐั ะณั€ัƒะฟะฟะฐ AND", + "69": "ะะพะฒะฐั ะณั€ัƒะฟะฟะฐ OR", + "70": "ะกั‚ะตั€ะตะพะณั€ัƒะฟะฟะฐ...", + "71": "ะกะฟะธัะพะบ ะฐั‚ะพะผะพะฒ...", + "72": "ะŸั€ะตะฒั€ะฐั‰ะฐะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ะฐั‚ะพะผั‹ ะฒ ะทะฐะฟั€ะพั ัะพ ัะฟะธัะบะพะผ ะฐั‚ะพะผะพะฒ ะธะปะธ ั ะธัะบะปัŽั‡ะฐัŽั‰ะธะผ ัะฟะธัะบะพะผ, ะฒั‹ะฑะธั€ะฐะตะผั‹ะผ ะฒ ะฟะตั€ะธะพะดะธั‡ะตัะบะพะน ั‚ะฐะฑะปะธั†ะต.", + "73": "ะŸั€ะตะฒั€ะฐั‰ะฐะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ัะฒัะทะธ ะฒ ัะฒัะทะธ-ะทะฐะฟั€ะพัั‹: any, single_or_double, single_or_aromatic ะธะปะธ double_or_aromatic; ะฑะตะท query ะทะฐะฟั€ะพั ัะฝะธะผะฐะตั‚ัั.", + "74": "ะขะธะฟ ัะฒัะทะธ-ะทะฐะฟั€ะพัะฐ", + "75": "ะžะฟั€ะตะดะตะปะธั‚ัŒ R-ะณั€ัƒะฟะฟัƒ...", + "76": "ะŸั€ะตะฒั€ะฐั‰ะฐะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะน ะฐั‚ะพะผ ะฒ ะผะตั‚ะบัƒ R-ะณั€ัƒะฟะฟั‹ ะธ ะพะฟั€ะตะดะตะปัะตั‚ ะตั‘ ั‡ะปะตะฝั‹, ั‡ะธัะปะพ ะฒั…ะพะถะดะตะฝะธะน, ะพัั‚ะฐั‚ะพั‡ะฝั‹ะน H ะธ ัƒัะปะพะฒะธะต ยซะตัะปะธ, ั‚ะพยป.", + "77": "ะŸะพะทะฒะพะปัะตั‚ ะดะฒะธะถะบัƒ ะฒั‹ะฑั€ะฐั‚ัŒ ะบะปะธะฝะพะฒะธะดะฝั‹ะต ะธ ัˆั‚ั€ะธั…ะพะฒั‹ะต ัะฒัะทะธ, ะพะดะฝะพะทะฝะฐั‡ะฝะพ ะฒั‹ั€ะฐะถะฐัŽั‰ะธะต ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ั‹ ะฒั‹ะดะตะปะตะฝะธั (ะธะปะธ ัั‚ั€ะฐะฝะธั†ั‹).", + "78": "ะŸะตั€ะตั‡ะธัะปัะตั‚ ะฟั€ะพะฑะปะตะผั‹ ะฒะฐะปะตะฝั‚ะฝะพัั‚ะธ, ัั‚ะตั€ะตะพั…ะธะผะธะธ, ะณะตะพะผะตั‚ั€ะธะธ ะธ ะผะตั‚ะพะบ ะฒ ะฒั‹ะดะตะปะตะฝะธะธ (ะธะปะธ ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต) ะฒ ะฟะฐะฝะตะปะธ, ัั‚ั€ะพะบะธ ะบะพั‚ะพั€ะพะน ะฒั‹ะฑะธั€ะฐัŽั‚ ะฐั‚ะพะผั‹.", + "79": "ะžั‚ะบั€ั‹ะฒะฐะตั‚ ะฟะฐะฝะตะปัŒ ะฐะฝะฐะปะธะทะฐ ั ั€ะฐัั‡ั‘ั‚ะฝั‹ะผะธ ัะฒะพะนัั‚ะฒะฐะผะธ ะฒั‹ะดะตะปะตะฝะธั ะธะปะธ ัั‚ั€ะฐะฝะธั†ั‹.", + "80": "ะšะพะฟะธั€ัƒะตั‚ ั„ะพั€ะผัƒะปัƒ, ะผะฐััั‹, ัะปะตะผะตะฝั‚ะฝั‹ะน ะฐะฝะฐะปะธะท ะธ ั€ะฐัั‡ั‘ั‚ะฝั‹ะต ัะฒะพะนัั‚ะฒะฐ ั ะธั… ะผะตั‚ะพะดะฐะผะธ ะฒ ะฒะธะดะต ั‚ะตะบัั‚ะฐ.", + "81": "ะะฐะนั‚ะธ ะฟะพะดัั‚ั€ัƒะบั‚ัƒั€ัƒ...", + "82": "ะ’ั‹ะดะตะปัะตั‚ ะบะฐะถะดะพะต ัะพะฒะฟะฐะดะตะฝะธะต ะฒั‹ะฑั€ะฐะฝะฝั‹ั… ะฐั‚ะพะผะพะฒ (ะธะปะธ ัˆะฐะฑะปะพะฝะฐ SMARTS) ะฒ ะดั€ัƒะณะธั… ัั‚ั€ัƒะบั‚ัƒั€ะฐั… ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต.", + "83": "ะŸะตั€ะตั‡ะธัะปะธั‚ัŒ R-ะณั€ัƒะฟะฟั‹...", + "84": "ะŸะตั€ะตั‡ะธัะปัะตั‚ ะบะฐะถะดัƒัŽ ัั‚ั€ัƒะบั‚ัƒั€ัƒ, ะบะพั‚ะพั€ัƒัŽ ะฟั€ะตะดัั‚ะฐะฒะปัะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะน ัะบะฐั„ั„ะพะปะด ะœะฐั€ะบัƒัˆะฐ (ะธะปะธ ะฟะตั€ะฒั‹ะน ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต), ั ั„ะพั€ะผัƒะปะพะน ะธ SMILES, ะดะพ 1000; ัะฟะธัะพะบ ะผะพะถะฝะพ ัะบะพะฟะธั€ะพะฒะฐั‚ัŒ.", + "85": "ะšะพะฟะธั€ะพะฒะฐั‚ัŒ ะบะฐะบ SMARTS", + "86": "ะšะพะฟะธั€ัƒะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ะฐั‚ะพะผั‹ (ะธะปะธ ะฒัะต ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต) ะบะฐะบ SMARTS, ัะพ ัะฟะธัะบะฐะผะธ ะฐั‚ะพะผะพะฒ, ะพะฑะพะฑั‰ั‘ะฝะฝั‹ะผะธ ะฐั‚ะพะผะฐะผะธ, ัะฒัะทัะผะธ-ะทะฐะฟั€ะพัะฐะผะธ ะธ ะดั€ัƒะณะธะผะธ ะฟั€ะธะทะฝะฐะบะฐะผะธ ะทะฐะฟั€ะพัะพะฒ.", + "87": "ะญะบัะฟะพั€ั‚ SMARTS...", + "88": "ะกะพั…ั€ะฐะฝัะตั‚ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ะฐั‚ะพะผั‹ (ะธะปะธ ะฒัะต ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะฝะฐ ัั‚ั€ะฐะฝะธั†ะต) ะบะฐะบ ั„ะฐะนะป SMARTS (.sma).", + "89": "ะ ะฐััˆะธั€ะตะฝะฝะฐั ัั‚ะตั€ะตะพั…ะธะผะธั", + "90": "ะ—ะฐะฟั€ะพั", + "91": "ะžะฑัŠะตะบั‚", + "92": "ะกะฝะฐั‡ะฐะปะฐ ะฒั‹ะฑะตั€ะธั‚ะต ัั‚ั€ัƒะบั‚ัƒั€ั‹ ะธะปะธ ั‚ะตะบัั‚, ะบะพั‚ะพั€ั‹ะผ ะฝัƒะถะฝะพ ะฝะฐะทะฝะฐั‡ะธั‚ัŒ ั€ะพะปัŒ.", + "93": "ะ—ะฐะดะฐั‚ัŒ ั€ะพะปะธ ะฒ ั€ะตะฐะบั†ะธะธ...", + "94": "ะ—ะฐะดะฐั‘ั‚ ั€ะพะปัŒ ะฒั‹ะฑั€ะฐะฝะฝั‹ั… ัั‚ั€ัƒะบั‚ัƒั€ ะธะปะธ ั‚ะตะบัั‚ะฐ ะฒ ะฒั‹ะฑั€ะฐะฝะฝะพะน ัั‚ะฐะดะธะธ ั€ะตะฐะบั†ะธะธ (ั€ะตะฐะณะตะฝั‚, ะฟั€ะพะดัƒะบั‚, ะฐะณะตะฝั‚, ัƒัะปะพะฒะธะต ะธะปะธ ะฝะตั‚) ะธ ะฟะพะผะตั‡ะฐะตั‚ ั€ะพะปะธ ัั‚ะฐะดะธะธ ะบะฐะบ ะทะฐะดะฐะฝะฝั‹ะต ะฒั€ัƒั‡ะฝัƒัŽ, ะพะดะฝะธะผ ัˆะฐะณะพะผ ะพั‚ะผะตะฝั‹. ะ‘ะตะท role ะพั‚ะบั€ั‹ะฒะฐะตั‚ ะดะธะฐะปะพะณ ัะพ ัะฟะธัะบะพะผ ัƒั‡ะฐัั‚ะฝะธะบะพะฒ ัั‚ะฐะดะธะธ ะธ ะฒั‹ะดะตะปะตะฝะธะตะผ.", + "95": "ะ ะพะปัŒ ะดะปั ะพะฑัŠะตะบั‚ะพะฒ; ะพะฟัƒัั‚ะธั‚ะต, ั‡ั‚ะพะฑั‹ ะพั‚ะบั€ั‹ั‚ัŒ ะดะธะฐะปะพะณ", + "96": "id ะพะฑัŠะตะบั‚ะพะฒ ะดะปั ะธะทะผะตะฝะตะฝะธั; ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ ะฒั‹ะดะตะปะตะฝะธะต", + "97": "ะะต ัƒะดะฐะปะพััŒ ะทะฐะดะฐั‚ัŒ ั€ะพะปะธ ะฒ ั€ะตะฐะบั†ะธะธ", + "98": "ะพัั‚ะฐั‚ะพั‡ะฝั‹ะน H", + "99": "ะกะพะบั€ะฐั‰ะตะฝะธะต", + "100": "ะœะตั‚ะบะฐ", + "101": "ะŸะพะธัะบ ะฟะพ ะฑะธะฑะปะธะพั‚ะตะบะต", + "102": "ะะต ัƒะดะฐะปะพััŒ ะทะฐะณั€ัƒะทะธั‚ัŒ ะฑะธะฑะปะธะพั‚ะตะบัƒ ัะพะบั€ะฐั‰ะตะฝะธะน. ะœะตั‚ะบัƒ ะฟะพ-ะฟั€ะตะถะฝะตะผัƒ ะผะพะถะฝะพ ะฒะฒะตัั‚ะธ.", + "103": "ะะตั‚ ะฟะพะดั…ะพะดัั‰ะธั… ัะพะบั€ะฐั‰ะตะฝะธะน. ะ’ะฒะตะดั‘ะฝะฝะฐั ะผะตั‚ะบะฐ ะธัะฟะพะปัŒะทัƒะตั‚ัั ะบะฐะบ ะตัั‚ัŒ.", + "104": "ะกะฒะพะนัั‚ะฒะฐ", + "105": "ะกะฟะธัะพะบ ะฐั‚ะพะผะพะฒ", + "106": "ะฉั‘ะปะบะฐะนั‚ะต ัะปะตะผะตะฝั‚ั‹ ะฒ ั‚ะฐะฑะปะธั†ะต, ั‡ั‚ะพะฑั‹ ะดะพะฑะฐะฒะธั‚ัŒ ะธั….", + "107": "ะžั‡ะธัั‚ะธั‚ัŒ ะทะฐะฟั€ะพั", + "108": "ะŸั€ะธะผะตะฝะธั‚ัŒ", + "109": "ะฃะดะฐะปะธั‚ัŒ", + "110": "ะะตั‚ ะทะฐะฟั€ะพัะฐ", + "111": "[M+Na]+", + "112": "ะ˜ะทะพั‚ะพะฟะฝะพะต ั€ะฐัะฟั€ะตะดะตะปะตะฝะธะต", + "113": "ะŸะตั€ะตั‡ะธัะปะธั‚ัŒ R-ะณั€ัƒะฟะฟั‹", + "114": "ะšะพะฟะธั€ะพะฒะฐั‚ัŒ SMILES", + "115": "SMILES ะฒัะตั… ัั‚ั€ัƒะบั‚ัƒั€ ัะบะพะฟะธั€ะพะฒะฐะฝั‹", + "116": "Si", + "117": "ะ›ัŽะฑะฐั ัะฒัะทัŒ", + "118": "ะžะดะธะฝะฐั€ะฝะฐั ะธะปะธ ะดะฒะพะนะฝะฐั", + "119": "ะžะดะธะฝะฐั€ะฝะฐั ะธะปะธ ะฐั€ะพะผะฐั‚ะธั‡ะตัะบะฐั", + "120": "ะ”ะฒะพะนะฝะฐั ะธะปะธ ะฐั€ะพะผะฐั‚ะธั‡ะตัะบะฐั", + "121": "ะฆะธะบะป ะธะปะธ ั†ะตะฟัŒ", + "122": "ะ’ ั†ะธะบะปะต", + "123": "ะ’ ั†ะตะฟะธ", + "124": "ะ›ัŽะฑะพะน ะฐั‚ะพะผ (A)", + "125": "ะ›ัŽะฑะพะน ะณะตั‚ะตั€ะพะฐั‚ะพะผ (Q)", + "126": "ะ›ัŽะฑะพะน ะณะฐะปะพะณะตะฝ (X)", + "127": "ะ›ัŽะฑะพะน ะผะตั‚ะฐะปะป (M)", + "128": "ะ—ะฐะดะฐั‚ัŒ ั‚ะพะฟะพะปะพะณะธัŽ ัะฒัะทะธ", + "129": "ะกะฒัะทัŒ-ะทะฐะฟั€ะพั", + "130": "ะ—ะฐะดะฐั‚ัŒ ะทะฐะฟั€ะพั ะฐั‚ะพะผะฐ", + "131": "ะั€ะพะผะฐั‚ะธั‡ะตัะบะธะน", + "132": "ะะปะธั„ะฐั‚ะธั‡ะตัะบะธะน", + "133": "ะะตะฝะฐัั‹ั‰ะตะฝะฝั‹ะน", + "134": "ะ—ะฐะผะตั‰ะตะฝะธะต ะบะฐะบ ะฝะฐั€ะธัะพะฒะฐะฝะพ", + "135": "ะฆะธะบะปะธั‡ะตัะบะธะต ัะฒัะทะธ ะบะฐะบ ะฝะฐั€ะธัะพะฒะฐะฝะพ", + "136": "ะžั‡ะธัั‚ะธั‚ัŒ ะทะฐะฟั€ะพั ะฐั‚ะพะผะฐ", + "137": "ะ—ะฐะฟั€ะพั ะฐั‚ะพะผะฐ", + "138": "ะžะฟั€ะตะดะตะปะตะฝะธะต R-ะณั€ัƒะฟะฟั‹", + "139": "R-ะณั€ัƒะฟะฟะฐ", + "140": "ะงะปะตะฝั‹", + "141": "ะะฐั€ะธััƒะนั‚ะต ะบะฐะถะดะพะณะพ ั‡ะปะตะฝะฐ ะพั‚ะดะตะปัŒะฝะพะน ัั‚ั€ัƒะบั‚ัƒั€ะพะน ั ั‚ะพั‡ะบะพะน ะฟั€ะธัะพะตะดะธะฝะตะฝะธั (*), ะทะฐั‚ะตะผ ัะฝะพะฒะฐ ะพั‚ะบั€ะพะนั‚ะต ัั‚ะพั‚ ะดะธะฐะปะพะณ.", + "142": "ะงะธัะปะพ ะฒั…ะพะถะดะตะฝะธะน", + "143": "ะžัั‚ะฐั‚ะพั‡ะฝั‹ะน H (ะฝะตะทะฐะผะตั‰ั‘ะฝะฝั‹ะต ะฟะพะปะพะถะตะฝะธั ะทะฐะฝะธะผะฐะตั‚ ะฒะพะดะพั€ะพะด)", + "144": "ะ•ัะปะธ ะฟั€ะธััƒั‚ัั‚ะฒัƒะตั‚, ั‚ะพ", + "145": "ะฃะดะฐะปะธั‚ัŒ ะพะฟั€ะตะดะตะปะตะฝะธะต", + "146": "ะะณะตะฝั‚", + "147": "ะฃัะปะพะฒะธะต", + "148": "ะžั‡ะธัั‚ะธั‚ัŒ", + "149": "ะ”ะพะฑะฐะฒะธั‚ัŒ ะฒั‹ะฑั€ะฐะฝะฝั‹ะต ั†ะตะฝั‚ั€ั‹ ะฒ ัั‚ัƒ ะณั€ัƒะฟะฟัƒ", + "150": "ะŸั€ะพะฒะตั€ะธั‚ัŒ ัะฝะพะฒะฐ", + "151": "ะŸั€ะพะฒะตั€ะบะฐ...", + "152": "ะ˜ัะฟั€ะฐะฒะธั‚ัŒ", + "153": "ะ’ั‹ะฑั€ะฐั‚ัŒ ะฝะฐ ั…ะพะปัั‚ะต" +} From aa4b39312609a2b3f1835d2f5dc6f6383b85a0c0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:40 -0500 Subject: [PATCH 252/279] feat(i18n): translate the stereo, query and analysis strings into Polish (0.6.0) Adds the part06 strings for Polish so the 0.6.0 stereochemistry, query and analysis UI is localised. --- frontend/src/i18n/locales/pl/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/pl/part06.json diff --git a/frontend/src/i18n/locales/pl/part06.json b/frontend/src/i18n/locales/pl/part06.json new file mode 100644 index 00000000..2e1b86bc --- /dev/null +++ b/frontend/src/i18n/locales/pl/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Kolejnoล›ฤ‡ Hilla z ล‚adunkiem, skrรณty rozwiniฤ™te", + "1": "Standardowe masy atomowe (wartoล›ci konwencjonalne CIAAW)", + "2": "Masa monoizotopowa z najpowszechniejszego izotopu kaลผdego pierwiastka", + "3": "Masa dokล‚adna podzielona przez wartoล›ฤ‡ bezwzglฤ™dnฤ… ล‚adunku, z poprawkฤ… na masฤ™ elektronu", + "4": "Procent masowy kaลผdego pierwiastka, dwa miejsca po przecinku", + "5": "Udziaล‚y atomรณw (Wildman and Crippen 1999)", + "6": "Topologiczna polarna powierzchnia, fragmenty N i O (Ertl 2000)", + "7": "Refrakcja molowa", + "8": "Donory wiฤ…zania wodorowego", + "9": "Liczenie wedล‚ug Lipinskiego: grupy N-H i O-H", + "10": "Akceptory wiฤ…zania wodorowego", + "11": "Liczenie wedล‚ug Lipinskiego: atomy N i O", + "12": "Wiฤ…zania rotowalne", + "13": "Wiฤ…zania pojedyncze poza pierล›cieniem miฤ™dzy nieterminalnymi ciฤ™ลผkimi atomami, z wyล‚ฤ…czeniem wiฤ…zania C-N amidu", + "14": "Reguล‚a piฤ™ciu Lipinskiego", + "15": "MW najwyลผej 500, cLogP najwyลผej 5, donorรณw najwyลผej 5, akceptorรณw najwyลผej 10", + "16": "HBD", + "17": "HBA", + "18": "Zaliczono (0 naruszeล„)", + "19": "Najpierw zaznacz jeden lub wiฤ™cej atomรณw", + "20": "Najpierw zaznacz jedno lub wiฤ™cej wiฤ…zaล„", + "21": "Brak niejawnych atomรณw wodoru do dodania.", + "22": "Brak jawnych atomรณw wodoru do usuniฤ™cia.", + "23": "Zaznacz skrรณt, na przykล‚ad Ph lub OTs, aby go rozwinฤ…ฤ‡.", + "24": "Zaznacz atomy jednej grupy w jednej strukturze, aby jฤ… zwinฤ…ฤ‡.", + "25": "Zaznacz grupฤ™ do zwiniฤ™cia, bez atomu, do ktรณrego jest przyล‚ฤ…czona.", + "26": "Zwiล„", + "27": "Wybierz skrรณt z biblioteki lub wpisz nowฤ… etykietฤ™ dla zaznaczonych atomรณw.", + "28": "Ustaw grupฤ™ stereo", + "29": "Wyczyล›ฤ‡ grupฤ™ stereo", + "30": "Ustaw listฤ™ atomรณw", + "31": "Wyczyล›ฤ‡ listฤ™ atomรณw", + "32": "Ustaw wiฤ…zanie zapytania", + "33": "Wyczyล›ฤ‡ zapytanie wiฤ…zania", + "34": "Zaznacz atom niosฤ…cy grupฤ™ R.", + "35": "1 punkt przyล‚ฤ…czenia", + "36": "Zdefiniuj grupฤ™ R", + "37": "Usuล„ definicjฤ™ grupy R", + "38": "Przypisz kliny", + "39": "Kliny juลผ odpowiadajฤ… centrom stereogenicznym.", + "40": "Zaznaczone struktury", + "41": "Kaลผda struktura na tej stronie", + "42": "Napraw strukturฤ™", + "43": "Brak struktury do analizy.", + "44": "Skopiowano analizฤ™", + "45": "Nie udaล‚o siฤ™ skopiowaฤ‡ do schowka", + "46": "Znajdลบ podstrukturฤ™", + "47": "SMARTS", + "48": "Najpierw narysuj na tej stronie struktury do wyszukania.", + "49": "tylko pierwsze wyniki", + "50": "Brak dopasowaล„ na tej stronie.", + "51": "Najpierw narysuj strukturฤ™ z atomami grup R i zdefiniuj jej grupy R.", + "52": "Brak struktury do zapisania jako SMARTS.", + "53": "Zapis plikรณw SMARTS pojawi siฤ™ wraz z formatami plikรณw w wersji 0.7.0; zamiast tego skopiowano SMARTS.", + "54": "Rysuje kaลผdy niejawny atom wodoru zaznaczonych atomรณw (lub wszystkich struktur na stronie) jako jawny atom H umieszczony przez silnik, w jednym kroku cofania.", + "55": "Usuwa jawne atomy H z zaznaczenia (lub strony), zachowujฤ…c atomy wodoru niosฤ…ce stereochemiฤ™, izotop, ล‚adunek, numer mapowania lub ล‚ฤ…czฤ…ce dwa atomy.", + "56": "Zastฤ™puje zaznaczone atomy skrรณtรณw (lub wszystkie skrรณty na stronie) ich peล‚nฤ… strukturฤ…, uล‚oลผonฤ… wzdล‚uลผ wiฤ…zania przyล‚ฤ…czenia.", + "57": "Zwiล„ skrรณt...", + "58": "Zwija zaznaczonฤ… grupฤ™ atomรณw do jednego atomu skrรณtu z etykietฤ… wybranฤ… lub wpisanฤ… przez uลผytkownika.", + "59": "Pokazuje lub ukrywa etykiety R, S, E i Z obok centrรณw stereogenicznych i stereowiฤ…zaล„ podwรณjnych.", + "60": "Pokaลผ rozszerzone grupy stereo", + "61": "Pokazuje lub ukrywa etykiety grup abs, and i or obok centrรณw stereogenicznych, gdy etykiety stereo sฤ… wล‚ฤ…czone.", + "62": "Pokaลผ cechy zapytania", + "63": "Pokazuje lub ukrywa na kanwie znaczniki list atomรณw, wiฤ…zaล„ zapytania i grup R.", + "64": "Umieszcza zaznaczone centra stereogeniczne w rozszerzonej grupie stereo: abs, and n lub or n. Bez n powstaje nowa grupa and lub or.", + "65": "abs, and lub or", + "66": "Numer grupy dla and i or", + "67": "Absolutna (abs)", + "68": "Nowa grupa AND", + "69": "Nowa grupa OR", + "70": "Grupa stereo...", + "71": "Lista atomรณw...", + "72": "Zamienia zaznaczone atomy na zapytanie z listฤ… atomรณw lub listฤ… wykluczajฤ…cฤ…, wybieranฤ… w ukล‚adzie okresowym.", + "73": "Zamienia zaznaczone wiฤ…zania na wiฤ…zania zapytania: any, single_or_double, single_or_aromatic lub double_or_aromatic; pomiล„ query, aby wyczyล›ciฤ‡.", + "74": "Typ wiฤ…zania zapytania", + "75": "Zdefiniuj grupฤ™ R...", + "76": "Zamienia zaznaczony atom na etykietฤ™ grupy R i definiuje jej czล‚onkรณw, krotnoล›ฤ‡ wystฤ™powania, resztฤ™ H i warunek jeล›li-to.", + "77": "Pozwala silnikowi wybraฤ‡ wiฤ…zania klinowe i kreskowane, ktรณre jednoznacznie wyraลผajฤ… centra stereogeniczne zaznaczenia (lub strony).", + "78": "Wyล›wietla problemy z walencyjnoล›ciฤ…, stereochemiฤ…, geometriฤ… i etykietami w zaznaczeniu (lub na stronie) w panelu, ktรณrego wiersze zaznaczajฤ… atomy.", + "79": "Otwiera panel analizy z obliczonymi wล‚aล›ciwoล›ciami zaznaczenia lub strony.", + "80": "Kopiuje wzรณr, masy, analizฤ™ elementarnฤ… i obliczone wล‚aล›ciwoล›ci wraz z ich metodami jako tekst.", + "81": "Znajdลบ podstrukturฤ™...", + "82": "Zaznacza kaลผde dopasowanie zaznaczonych atomรณw (lub wzorca SMARTS) w pozostaล‚ych strukturach na stronie.", + "83": "Wylicz grupy R...", + "84": "Wyล›wietla kaลผdฤ… strukturฤ™, ktรณrฤ… reprezentuje zaznaczony szkielet Markusha (lub pierwszy na stronie), z wzorem i SMILES, do 1000; listฤ™ moลผna skopiowaฤ‡.", + "85": "Kopiuj jako SMARTS", + "86": "Kopiuje zaznaczone atomy (lub wszystkie struktury na stronie) jako SMARTS, z listami atomรณw, atomami ogรณlnymi, wiฤ…zaniami zapytania i innymi cechami zapytania.", + "87": "Eksportuj SMARTS...", + "88": "Zapisuje zaznaczone atomy (lub wszystkie struktury na stronie) jako plik SMARTS (.sma).", + "89": "Rozszerzona stereochemia", + "90": "Zapytanie", + "91": "Obiekt", + "92": "Najpierw zaznacz struktury lub tekst, ktรณrym nadaฤ‡ rolฤ™.", + "93": "Ustaw role w reakcji...", + "94": "Ustawia rolฤ™ zaznaczonych struktur lub tekstu w wybranym etapie reakcji (substrat, produkt, czynnik, warunek lub brak) i oznacza role etapu jako ustawione rฤ™cznie, w jednym kroku cofania. Bez role otwiera okno z listฤ… uczestnikรณw etapu i zaznaczeniem.", + "95": "Rola nadawana obiektom; pomiล„, aby otworzyฤ‡ okno", + "96": "Id obiektรณw do zmiany; domyล›lnie zaznaczenie", + "97": "Nie udaล‚o siฤ™ ustawiฤ‡ rรณl w reakcji", + "98": "reszta H", + "99": "Skrรณt", + "100": "Etykieta", + "101": "Przeszukaj bibliotekฤ™", + "102": "Nie udaล‚o siฤ™ wczytaฤ‡ biblioteki skrรณtรณw. Nadal moลผesz wpisaฤ‡ etykietฤ™.", + "103": "ลปaden skrรณt nie pasuje. Wpisana etykieta jest uลผywana bez zmian.", + "104": "Wล‚aล›ciwoล›ci", + "105": "Lista atomรณw", + "106": "Klikaj pierwiastki w tabeli, aby je dodaฤ‡.", + "107": "Wyczyล›ฤ‡ zapytanie", + "108": "Zastosuj", + "109": "Usuล„", + "110": "Brak zapytania", + "111": "[M+Na]+", + "112": "Rozkล‚ad izotopowy", + "113": "Wylicz grupy R", + "114": "Kopiuj SMILES", + "115": "Skopiowano SMILES kaลผdej struktury", + "116": "Si", + "117": "Dowolne wiฤ…zanie", + "118": "Pojedyncze lub podwรณjne", + "119": "Pojedyncze lub aromatyczne", + "120": "Podwรณjne lub aromatyczne", + "121": "Pierล›cieล„ lub ล‚aล„cuch", + "122": "W pierล›cieniu", + "123": "W ล‚aล„cuchu", + "124": "Dowolny atom (A)", + "125": "Dowolny heteroatom (Q)", + "126": "Dowolny halogen (X)", + "127": "Dowolny metal (M)", + "128": "Ustaw topologiฤ™ wiฤ…zania", + "129": "Wiฤ…zanie zapytania", + "130": "Ustaw zapytanie atomu", + "131": "Aromatyczny", + "132": "Alifatyczny", + "133": "Nienasycony", + "134": "Podstawienie jak narysowano", + "135": "Wiฤ…zania pierล›cienia jak narysowano", + "136": "Wyczyล›ฤ‡ zapytanie atomu", + "137": "Zapytanie atomu", + "138": "Definicja grupy R", + "139": "Grupa R", + "140": "Czล‚onkowie", + "141": "Narysuj kaลผdego czล‚onka jako osobnฤ… strukturฤ™ z punktem przyล‚ฤ…czenia (*), a nastฤ™pnie otwรณrz to okno ponownie.", + "142": "Krotnoล›ฤ‡ wystฤ™powania", + "143": "Reszta H (niepodstawione pozycje to wodรณr)", + "144": "Jeล›li obecna, to", + "145": "Usuล„ definicjฤ™", + "146": "Czynnik", + "147": "Warunek", + "148": "Wyczyล›ฤ‡", + "149": "Dodaj zaznaczone centra do tej grupy", + "150": "Sprawdลบ ponownie", + "151": "Sprawdzanie...", + "152": "Napraw", + "153": "Zaznacz na kanwie" +} From 7f3c2b7e23e656fd238c11ee1e85695b22495601 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:40 -0500 Subject: [PATCH 253/279] feat(i18n): translate the stereo, query and analysis strings into Czech (0.6.0) Adds the part06 strings for Czech so the 0.6.0 stereochemistry, query and analysis UI is localised. --- frontend/src/i18n/locales/cs/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/cs/part06.json diff --git a/frontend/src/i18n/locales/cs/part06.json b/frontend/src/i18n/locales/cs/part06.json new file mode 100644 index 00000000..29b6bd52 --- /dev/null +++ b/frontend/src/i18n/locales/cs/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hillovo poล™adรญ s nรกbojem, zkratky rozvinuty", + "1": "Standardnรญ atomovรฉ hmotnosti (konvenฤnรญ hodnoty CIAAW)", + "2": "Monoizotopovรก hmotnost z nejhojnฤ›jลกรญho izotopu kaลพdรฉho prvku", + "3": "Pล™esnรก hmotnost dฤ›lenรก absolutnรญ hodnotou nรกboje, s korekcรญ na hmotnost elektronu", + "4": "Hmotnostnรญ procento kaลพdรฉho prvku, dvฤ› desetinnรก mรญsta", + "5": "Pล™รญspฤ›vky atomลฏ (Wildman and Crippen 1999)", + "6": "Topologickรฝ polรกrnรญ povrch, fragmenty N a O (Ertl 2000)", + "7": "Molรกrnรญ refrakce", + "8": "Donory vodรญkovรฉ vazby", + "9": "Poฤรญtรกnรญ podle Lipinskรฉho: skupiny N-H a O-H", + "10": "Akceptory vodรญkovรฉ vazby", + "11": "Poฤรญtรกnรญ podle Lipinskรฉho: atomy N a O", + "12": "Rotovatelnรฉ vazby", + "13": "Jednoduchรฉ vazby mimo kruh mezi neterminรกlnรญmi tฤ›ลพkรฝmi atomy, vazba C-N amidu vylouฤena", + "14": "Lipinskรฉho pravidlo pฤ›ti", + "15": "MW nejvรฝลกe 500, cLogP nejvรฝลกe 5, donorลฏ nejvรฝลกe 5, akceptorลฏ nejvรฝลกe 10", + "16": "HBD", + "17": "HBA", + "18": "Splnฤ›no (0 poruลกenรญ)", + "19": "Nejprve vyberte jeden nebo vรญce atomลฏ", + "20": "Nejprve vyberte jednu nebo vรญce vazeb", + "21": "ลฝรกdnรฉ implicitnรญ atomy vodรญku k pล™idรกnรญ.", + "22": "ลฝรกdnรฉ explicitnรญ atomy vodรญku k odebrรกnรญ.", + "23": "Vyberte zkratku, napล™รญklad Ph nebo OTs, a rozvinete ji.", + "24": "Vyberte atomy jednรฉ skupiny v jednรฉ struktuล™e, abyste ji sbalili.", + "25": "Vyberte skupinu ke sbalenรญ, bez atomu, na kterรฝ je navรกzรกna.", + "26": "Sbalit", + "27": "Vyberte zkratku z knihovny nebo zadejte novรฝ popisek pro vybranรฉ atomy.", + "28": "Nastavit stereoskupinu", + "29": "Vymazat stereoskupinu", + "30": "Nastavit seznam atomลฏ", + "31": "Vymazat seznam atomลฏ", + "32": "Nastavit dotazovou vazbu", + "33": "Vymazat dotaz vazby", + "34": "Vyberte atom, kterรฝ nese R-skupinu.", + "35": "1 bod pล™ipojenรญ", + "36": "Definovat R-skupinu", + "37": "Odebrat definici R-skupiny", + "38": "Pล™iล™adit klรญny", + "39": "Klรญny jiลพ odpovรญdajรญ stereocentrลฏm.", + "40": "Vybranรฉ struktury", + "41": "Kaลพdรก struktura na tรฉto strรกnce", + "42": "Opravit strukturu", + "43": "Nenรญ co analyzovat, chybรญ struktura.", + "44": "Analรฝza zkopรญrovรกna", + "45": "Kopรญrovรกnรญ do schrรกnky se nepodaล™ilo", + "46": "Najรญt podstrukturu", + "47": "SMARTS", + "48": "Nejprve nakreslete na tรฉto strรกnce struktury, kterรฉ se majรญ hledat.", + "49": "pouze prvnรญ vรฝsledky", + "50": "Na tรฉto strรกnce nejsou ลพรกdnรฉ shody.", + "51": "Nejprve nakreslete strukturu s atomy R-skupin a definujte jejรญ R-skupiny.", + "52": "Nenรญ ลพรกdnรก struktura k zรกpisu jako SMARTS.", + "53": "Uklรกdรกnรญ souborลฏ SMARTS pล™ijde s formรกty souborลฏ ve verzi 0.7.0; mรญsto toho byl SMARTS zkopรญrovรกn.", + "54": "Nakreslรญ kaลพdรฝ implicitnรญ atom vodรญku vybranรฝch atomลฏ (nebo vลกech struktur na strรกnce) jako explicitnรญ atom H umรญstฤ›nรฝ enginem v jednom kroku zpฤ›t.", + "55": "Odebere explicitnรญ atomy H z vรฝbฤ›ru (nebo strรกnky), ale ponechรก atomy vodรญku, kterรฉ nesou stereo, izotop, nรกboj, mapovacรญ ฤรญslo nebo spojujรญ dva atomy.", + "56": "Nahradรญ vybranรฉ atomy zkratek (nebo vลกechny zkratky na strรกnce) jejich รบplnou strukturou, rozloลพenou podรฉl pล™ipojovacรญ vazby.", + "57": "Sbalit zkratku...", + "58": "Sbalรญ vybranou skupinu atomลฏ do jednoho atomu zkratky s popiskem, kterรฝ uลพivatel vybere nebo zadรก.", + "59": "Zobrazรญ nebo skryje popisky R, S, E a Z vedle stereocenter a stereo dvojnรฝch vazeb.", + "60": "Zobrazit rozลกรญล™enรฉ stereoskupiny", + "61": "Zobrazรญ nebo skryje popisky skupin abs, and a or vedle stereocenter, dokud jsou stereopopisky zapnutรฉ.", + "62": "Zobrazit dotazovรฉ vlastnosti", + "63": "Zobrazรญ nebo skryje na plรกtnฤ› znaฤky seznamลฏ atomลฏ, dotazovรฝch vazeb a R-skupin.", + "64": "Zaล™adรญ vybranรก stereocentra do rozลกรญล™enรฉ stereoskupiny: abs, and n nebo or n. Bez n vznikne novรก skupina and nebo or.", + "65": "abs, and nebo or", + "66": "ฤŒรญslo skupiny pro and a or", + "67": "Absolutnรญ (abs)", + "68": "Novรก skupina AND", + "69": "Novรก skupina OR", + "70": "Stereoskupina...", + "71": "Seznam atomลฏ...", + "72": "Zmฤ›nรญ vybranรฉ atomy na dotaz se seznamem atomลฏ nebo s vyluฤujรญcรญm seznamem, vybranรฝm v periodickรฉ tabulce.", + "73": "Zmฤ›nรญ vybranรฉ vazby na dotazovรฉ vazby: any, single_or_double, single_or_aromatic nebo double_or_aromatic; vynechejte query pro vymazรกnรญ.", + "74": "Typ dotazovรฉ vazby", + "75": "Definovat R-skupinu...", + "76": "Zmฤ›nรญ vybranรฝ atom na popisek R-skupiny a definuje jejรญ ฤleny, vรฝskyt, zbytek H a podmรญnku pokud-pak.", + "77": "Nechรก engine zvolit klรญnovรฉ a ฤรกrkovanรฉ vazby, kterรฉ jednoznaฤnฤ› vyjadล™ujรญ stereocentra vรฝbฤ›ru (nebo strรกnky).", + "78": "Vypรญลกe problรฉmy s valencรญ, stereem, geometriรญ a popisky ve vรฝbฤ›ru (nebo na strรกnce) v panelu, jehoลพ ล™รกdky vybรญrajรญ atomy.", + "79": "Otevล™e panel analรฝzy s vypoฤtenรฝmi vlastnostmi vรฝbฤ›ru nebo strรกnky.", + "80": "Zkopรญruje vzorec, hmotnosti, elementรกrnรญ analรฝzu a vypoฤtenรฉ vlastnosti s jejich metodami jako text.", + "81": "Najรญt podstrukturu...", + "82": "Vybere kaลพdou shodu vybranรฝch atomลฏ (nebo vzoru SMARTS) v ostatnรญch strukturรกch na strรกnce.", + "83": "Vyjmenovat R-skupiny...", + "84": "Vypรญลกe kaลพdou strukturu, kterou pล™edstavuje vybranรก Markushova kostra (nebo prvnรญ na strรกnce), se vzorcem a SMILES, nejvรฝลกe 1000; seznam lze zkopรญrovat.", + "85": "Kopรญrovat jako SMARTS", + "86": "Zkopรญruje vybranรฉ atomy (nebo vลกechny struktury na strรกnce) jako SMARTS se seznamy atomลฏ, obecnรฝmi atomy, dotazovรฝmi vazbami a dalลกรญmi dotazovรฝmi vlastnostmi.", + "87": "Exportovat SMARTS...", + "88": "Uloลพรญ vybranรฉ atomy (nebo vลกechny struktury na strรกnce) jako soubor SMARTS (.sma).", + "89": "Rozลกรญล™enรฉ stereo", + "90": "Dotaz", + "91": "Objekt", + "92": "Nejprve vyberte struktury nebo text, kterรฝm chcete pล™iล™adit roli.", + "93": "Nastavit role v reakci...", + "94": "Nastavรญ roli vybranรฝch struktur nebo textu ve vybranรฉm kroku reakce (reaktant, produkt, ฤinidlo, podmรญnka nebo ลพรกdnรก) a oznaฤรญ role kroku jako nastavenรฉ ruฤnฤ›, v jednom kroku zpฤ›t. Bez role otevล™e dialog se seznamem ฤlenลฏ kroku a vรฝbฤ›rem.", + "95": "Role, kterou objekty dostanou; vynechejte pro otevล™enรญ dialogu", + "96": "Id objektลฏ ke zmฤ›nฤ›; vรฝchozรญ je vรฝbฤ›r", + "97": "Role v reakci se nepodaล™ilo nastavit", + "98": "zbytek H", + "99": "Zkratka", + "100": "Popisek", + "101": "Hledat v knihovnฤ›", + "102": "Knihovnu zkratek se nepodaล™ilo naฤรญst. Popisek mลฏลพete stรกle zadat.", + "103": "ลฝรกdnรก zkratka neodpovรญdรก. Zadanรฝ popisek se pouลพije tak, jak je.", + "104": "Vlastnosti", + "105": "Seznam atomลฏ", + "106": "Kliknutรญm na prvky v tabulce je pล™idรกte.", + "107": "Vymazat dotaz", + "108": "Pouลพรญt", + "109": "Odebrat", + "110": "ลฝรกdnรฝ dotaz", + "111": "[M+Na]+", + "112": "Izotopovรฝ vzor", + "113": "Vyjmenovat R-skupiny", + "114": "Kopรญrovat SMILES", + "115": "SMILES kaลพdรฉ struktury zkopรญrovรกn", + "116": "Si", + "117": "Libovolnรก vazba", + "118": "Jednoduchรก nebo dvojnรก", + "119": "Jednoduchรก nebo aromatickรก", + "120": "Dvojnรก nebo aromatickรก", + "121": "Kruh nebo ล™etฤ›zec", + "122": "V kruhu", + "123": "V ล™etฤ›zci", + "124": "Libovolnรฝ atom (A)", + "125": "Libovolnรฝ heteroatom (Q)", + "126": "Libovolnรฝ halogen (X)", + "127": "Libovolnรฝ kov (M)", + "128": "Nastavit topologii vazby", + "129": "Dotazovรก vazba", + "130": "Nastavit dotaz atomu", + "131": "Aromatickรฝ", + "132": "Alifatickรฝ", + "133": "Nenasycenรฝ", + "134": "Substituce jak je nakreslena", + "135": "Kruhovรฉ vazby jak jsou nakresleny", + "136": "Vymazat dotaz atomu", + "137": "Dotaz atomu", + "138": "Definice R-skupiny", + "139": "R-skupina", + "140": "ฤŒleny", + "141": "Nakreslete kaลพdรฉho ฤlena jako samostatnou strukturu s bodem pล™ipojenรญ (*) a pak tento dialog otevล™ete znovu.", + "142": "Vรฝskyt", + "143": "Zbytek H (nesubstituovanรฉ pozice jsou vodรญk)", + "144": "Je-li pล™รญtomna, pak", + "145": "Odebrat definici", + "146": "ฤŒinidlo", + "147": "Podmรญnka", + "148": "Vymazat", + "149": "Pล™idat vybranรก centra do tรฉto skupiny", + "150": "Zkontrolovat znovu", + "151": "Kontroluje se...", + "152": "Opravit", + "153": "Vybrat na plรกtnฤ›" +} From 94fa07390a31280a427827503e7fe0526fed7270 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:44 -0500 Subject: [PATCH 254/279] feat(i18n): translate the stereo, query and analysis strings into Hungarian (0.6.0) Adds part06 for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/hu/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/hu/part06.json diff --git a/frontend/src/i18n/locales/hu/part06.json b/frontend/src/i18n/locales/hu/part06.json new file mode 100644 index 00000000..0636c82e --- /dev/null +++ b/frontend/src/i18n/locales/hu/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill-sorrend a tรถltรฉssel, a rรถvidรญtรฉsek kibontva", + "1": "Standard atomtรถmegek (CIAAW hagyomรกnyos รฉrtรฉkek)", + "2": "Monoizotopos tรถmeg az egyes elemek leggyakoribb izotรณpjรกbรณl", + "3": "A pontos tรถmeg osztva a tรถltรฉs abszolรบt รฉrtรฉkรฉvel, az elektrontรถmeggel korrigรกlva", + "4": "Az egyes elemek tรถmegszรกzalรฉka, kรฉt tizedesjeggyel", + "5": "Atomhozzรกjรกrulรกsok (Wildman รฉs Crippen 1999)", + "6": "Topolรณgiai polรกris felรผlet, N- รฉs O-fragmensek (Ertl 2000)", + "7": "Molรกris refrakciรณ", + "8": "Hidrogรฉnkรถtรฉs-donorok", + "9": "Lipinski-szรกmolรกs: N-H รฉs O-H csoportok", + "10": "Hidrogรฉnkรถtรฉs-akceptorok", + "11": "Lipinski-szรกmolรกs: N- รฉs O-atomok", + "12": "Forgathatรณ kรถtรฉsek", + "13": "Gyลฑrลฑn kรญvรผli egyszeres kรถtรฉsek nem vรฉgรกllรกsรบ nehรฉzatomok kรถzรถtt, az amid C-N kรถtรฉs kivรฉtelรฉvel", + "14": "Lipinski-fรฉle รถtรถs szabรกly", + "15": "MW legfeljebb 500, cLogP legfeljebb 5, donorok legfeljebb 5, akceptorok legfeljebb 10", + "16": "HBD", + "17": "HBA", + "18": "Megfelel (0 szabรกlysรฉrtรฉs)", + "19": "Elล‘bb jelรถljรถn ki egy vagy tรถbb atomot", + "20": "Elล‘bb jelรถljรถn ki egy vagy tรถbb kรถtรฉst", + "21": "Nincs hozzรกadhatรณ implicit hidrogรฉn.", + "22": "Nincs eltรกvolรญthatรณ explicit hidrogรฉn.", + "23": "Jelรถljรถn ki egy rรถvidรญtรฉst, pรฉldรกul Ph vagy OTs, a kibontรกshoz.", + "24": "Jelรถlje ki egyetlen szerkezet egy csoportjรกnak atomjait az รถsszevonรกshoz.", + "25": "Jelรถlje ki az รถsszevonandรณ csoportot, a hozzรก kapcsolรณdรณ atom nรฉlkรผl.", + "26": "ร–sszevonรกs", + "27": "Vรกlasszon egy kรถnyvtรกri rรถvidรญtรฉst, vagy รญrjon be รบj feliratot a kijelรถlt atomokhoz.", + "28": "Sztereocsoport beรกllรญtรกsa", + "29": "Sztereocsoport tรถrlรฉse", + "30": "Atomlista beรกllรญtรกsa", + "31": "Atomlista tรถrlรฉse", + "32": "Lekรฉrdezรฉsi kรถtรฉs beรกllรญtรกsa", + "33": "Kรถtรฉslekรฉrdezรฉs tรถrlรฉse", + "34": "Jelรถlje ki az R-csoportot hordozรณ atomot.", + "35": "1 kapcsolรณdรกsi pont", + "36": "R-csoport meghatรกrozรกsa", + "37": "R-csoport-meghatรกrozรกs eltรกvolรญtรกsa", + "38": "ร‰kek kiosztรกsa", + "39": "Az รฉkek mรกr megfelelnek a sztereocentrumoknak.", + "40": "A kijelรถlt szerkezetek", + "41": "Az oldal รถsszes szerkezete", + "42": "Szerkezet javรญtรกsa", + "43": "Nincs elemezhetล‘ szerkezet.", + "44": "Az elemzรฉs a vรกgรณlapra mรกsolva", + "45": "Nem sikerรผlt a vรกgรณlapra mรกsolni", + "46": "Rรฉszszerkezet keresรฉse", + "47": "SMARTS", + "48": "Elล‘bb rajzolja meg az oldalon keresendล‘ szerkezeteket.", + "49": "csak az elsล‘ talรกlatok", + "50": "Nincs talรกlat ezen az oldalon.", + "51": "Elล‘bb rajzoljon egy R-csoport-atomokat tartalmazรณ szerkezetet, รฉs hatรกrozza meg az R-csoportjait.", + "52": "Nincs SMARTS-kรฉnt leรญrhatรณ szerkezet.", + "53": "A SMARTS-fรกjlok mentรฉse a fรกjlformรกtumokkal รฉrkezik a 0.7.0 verziรณban; helyette a SMARTS a vรกgรณlapra kerรผlt.", + "54": "A kijelรถlt atomok (vagy az oldal รถsszes szerkezetรฉnek) minden implicit hidrogรฉnjรฉt explicit H-atomkรฉnt rajzolja meg, a motor รกltal elhelyezve, egyetlen visszavonรกsi lรฉpรฉskรฉnt.", + "55": "Eltรกvolรญtja az explicit H-atomokat a kijelรถlรฉsbล‘l (vagy az oldalrรณl), megtartva azokat a hidrogรฉneket, amelyek sztereรณt, izotรณpot, tรถltรฉst, lekรฉpezรฉsi szรกmot hordoznak, vagy kรฉt atomot รกthidalnak.", + "56": "A kijelรถlt rรถvidรญtรฉsatomokat (vagy az oldal รถsszes rรถvidรญtรฉsรฉt) a teljes szerkezetรผkre cserรฉli, a kapcsolรณdรณ kรถtรฉs mentรฉn elrendezve.", + "57": "Rรถvidรญtรฉs รถsszevonรกsa...", + "58": "A kijelรถlt atomcsoportot egyetlen rรถvidรญtรฉsatommรก vonja รถssze azzal a felirattal, amelyet a felhasznรกlรณ kivรกlaszt vagy beรญr.", + "59": "Megjelenรญti vagy elrejti az R, S, E รฉs Z feliratokat a sztereocentrumok รฉs a sztereo kettล‘s kรถtรฉsek mellett.", + "60": "Kiterjesztett sztereocsoportok megjelenรญtรฉse", + "61": "Megjelenรญti vagy elrejti az abs, and รฉs or csoportfeliratokat a sztereocentrumok mellett, amรญg a sztereofeliratok be vannak kapcsolva.", + "62": "Lekรฉrdezรฉsi jellemzล‘k megjelenรญtรฉse", + "63": "Megjelenรญti vagy elrejti az atomlista, a lekรฉrdezรฉsi kรถtรฉs รฉs az R-csoport jelรถlรฉseit a vรกsznon.", + "64": "A kijelรถlt sztereocentrumokat kiterjesztett sztereocsoportba teszi: abs, and n vagy or n. Az n nรฉlkรผl รบj and vagy or csoport jรถn lรฉtre.", + "65": "abs, and vagy or", + "66": "A csoport szรกma az and รฉs or csoportokhoz", + "67": "Abszolรบt (abs)", + "68": "รšj AND csoport", + "69": "รšj OR csoport", + "70": "Sztereocsoport...", + "71": "Atomlista...", + "72": "A kijelรถlt atomokat a periรณdusos rendszerben vรกlasztott atomlista- vagy nem-lista lekรฉrdezรฉssรฉ alakรญtja.", + "73": "A kijelรถlt kรถtรฉseket lekรฉrdezรฉsi kรถtรฉsekkรฉ alakรญtja: any, single_or_double, single_or_aromatic vagy double_or_aromatic; a query elhagyรกsรกval tรถrรถl.", + "74": "A lekรฉrdezรฉsi kรถtรฉs tรญpusa", + "75": "R-csoport meghatรกrozรกsa...", + "76": "A kijelรถlt atomot R-csoport-jelรถlล‘vรฉ alakรญtja, รฉs meghatรกrozza a tagjait, az elล‘fordulรกst, a maradรฉk H-t รฉs a ha-akkor feltรฉtelt.", + "77": "Lehetล‘vรฉ teszi, hogy a motor olyan รฉk- รฉs szaggatott kรถtรฉseket vรกlasszon, amelyek egyรฉrtelmลฑen kifejezik a kijelรถlรฉs (vagy az oldal) sztereocentrumait.", + "78": "Felsorolja a kijelรถlรฉs (vagy az oldal) vegyรฉrtรฉk-, sztereรณ-, geometria- รฉs feliratproblรฉmรกit egy panelen, amelynek sorai kijelรถlik az atomokat.", + "79": "Megnyitja az elemzล‘panelt a kijelรถlรฉs vagy az oldal szรกmรญtott tulajdonsรกgaival.", + "80": "Szรถvegkรฉnt mรกsolja a kรฉpletet, a tรถmegeket, az elemanalรญzist รฉs a szรกmรญtott tulajdonsรกgokat a mรณdszereikkel egyรผtt.", + "81": "Rรฉszszerkezet keresรฉse...", + "82": "Kijelรถli a kijelรถlt atomok (vagy egy SMARTS-minta) minden talรกlatรกt az oldal tรถbbi szerkezetรฉben.", + "83": "R-csoportok felsorolรกsa...", + "84": "Felsorolja az รถsszes szerkezetet, amelyet a kijelรถlt Markush-vรกzszerkezet (vagy az oldal elsล‘) kรฉpvisel, kรฉplettel รฉs SMILES-szel, legfeljebb 1000-ig; a lista mรกsolhatรณ.", + "85": "Mรกsolรกs SMARTS-kรฉnt", + "86": "A kijelรถlt atomokat (vagy az oldal รถsszes szerkezetรฉt) SMARTS-kรฉnt mรกsolja, az atomlistรกkkal, รกltalรกnos atomokkal, lekรฉrdezรฉsi kรถtรฉsekkel รฉs a tรถbbi lekรฉrdezรฉsi jellemzล‘vel egyรผtt.", + "87": "SMARTS exportรกlรกsa...", + "88": "A kijelรถlt atomokat (vagy az oldal รถsszes szerkezetรฉt) SMARTS-fรกjlkรฉnt menti (.sma).", + "89": "Kiterjesztett sztereรณ", + "90": "Lekรฉrdezรฉs", + "91": "Objektum", + "92": "Elล‘bb jelรถlje ki a szerepet kapรณ szerkezeteket vagy szรถveget.", + "93": "Reakciรณszerepek beรกllรญtรกsa...", + "94": "Beรกllรญtja a kijelรถlt szerkezetek vagy szรถveg szerepรฉt a kijelรถlt reakciรณlรฉpรฉsben (reaktรกns, termรฉk, รกgens, kรถrรผlmรฉny vagy nincs), รฉs a lรฉpรฉs szerepeit kรฉzzel beรกllรญtottnak jelรถli, egyetlen visszavonรกsi lรฉpรฉskรฉnt. A role nรฉlkรผl megnyit egy pรกrbeszรฉdablakot, amely felsorolja a lรฉpรฉs tagjait รฉs a kijelรถlรฉst.", + "95": "Az objektumoknak adandรณ szerep; elhagyva megnyรญlik a pรกrbeszรฉdablak", + "96": "A mรณdosรญtandรณ objektumok azonosรญtรณi; alapรฉrtelmezรฉs a kijelรถlรฉs", + "97": "Nem sikerรผlt beรกllรญtani a reakciรณszerepeket", + "98": "maradรฉk H", + "99": "Rรถvidรญtรฉs", + "100": "Felirat", + "101": "Keresรฉs a kรถnyvtรกrban", + "102": "A rรถvidรญtรฉskรถnyvtรกrat nem sikerรผlt betรถlteni. Tovรกbbra is beรญrhat feliratot.", + "103": "Nincs egyezล‘ rรถvidรญtรฉs. A beรญrt feliratot vรกltoztatรกs nรฉlkรผl hasznรกljuk.", + "104": "Tulajdonsรกgok", + "105": "Atomlista", + "106": "Kattintson az elemekre a tรกblรกzatban a hozzรกadรกsukhoz.", + "107": "Lekรฉrdezรฉs tรถrlรฉse", + "108": "Alkalmaz", + "109": "Eltรกvolรญtรกs", + "110": "Nincs lekรฉrdezรฉs", + "111": "[M+Na]+", + "112": "Izotรณpmintรกzat", + "113": "R-csoportok felsorolรกsa", + "114": "SMILES mรกsolรกsa", + "115": "Minden szerkezet SMILES-e mรกsolva", + "116": "Si", + "117": "Bรกrmilyen kรถtรฉs", + "118": "Egyszeres vagy kettล‘s", + "119": "Egyszeres vagy aromรกs", + "120": "Kettล‘s vagy aromรกs", + "121": "Gyลฑrลฑ vagy lรกnc", + "122": "Gyลฑrลฑben", + "123": "Lรกncban", + "124": "Bรกrmilyen atom (A)", + "125": "Bรกrmilyen heteroatom (Q)", + "126": "Bรกrmilyen halogรฉn (X)", + "127": "Bรกrmilyen fรฉm (M)", + "128": "Kรถtรฉstopolรณgia beรกllรญtรกsa", + "129": "Lekรฉrdezรฉsi kรถtรฉs", + "130": "Atomlekรฉrdezรฉs beรกllรญtรกsa", + "131": "Aromรกs", + "132": "Alifรกs", + "133": "Telรญtetlen", + "134": "Szubsztitรบciรณ a rajz szerint", + "135": "Gyลฑrลฑkรถtรฉsek a rajz szerint", + "136": "Atomlekรฉrdezรฉs tรถrlรฉse", + "137": "Atomlekรฉrdezรฉs", + "138": "R-csoport-meghatรกrozรกs", + "139": "R-csoport", + "140": "Tagok", + "141": "Rajzolja meg az egyes tagokat kรผlรถn szerkezetkรฉnt egy kapcsolรณdรกsi ponttal (*), majd nyissa meg รบjra ezt a pรกrbeszรฉdablakot.", + "142": "Elล‘fordulรกs", + "143": "Maradรฉk H (a nem szubsztituรกlt helyeken hidrogรฉn รกll)", + "144": "Ha jelen van, akkor", + "145": "Meghatรกrozรกs eltรกvolรญtรกsa", + "146": "รgens", + "147": "Kรถrรผlmรฉny", + "148": "Tรถrlรฉs", + "149": "A kijelรถlt centrumok hozzรกadรกsa ehhez a csoporthoz", + "150": "Ellenล‘rzรฉs รบjra", + "151": "Ellenล‘rzรฉs...", + "152": "Javรญtรกs", + "153": "Kijelรถlรฉs a vรกsznon" +} From 06be98922d9a3d2bad19751f1a701df1a3569957 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:44 -0500 Subject: [PATCH 255/279] feat(i18n): translate the stereo, query and analysis strings into Ukrainian (0.6.0) Adds part06 for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/uk/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/uk/part06.json diff --git a/frontend/src/i18n/locales/uk/part06.json b/frontend/src/i18n/locales/uk/part06.json new file mode 100644 index 00000000..012d2015 --- /dev/null +++ b/frontend/src/i18n/locales/uk/part06.json @@ -0,0 +1,156 @@ +{ + "0": "ะŸะพั€ัะดะพะบ ะ“ั–ะปะปะฐ ั–ะท ะทะฐั€ัะดะพะผ, ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ะธ ั€ะพะทะณะพั€ะฝัƒั‚ะพ", + "1": "ะกั‚ะฐะฝะดะฐั€ั‚ะฝั– ะฐั‚ะพะผะฝั– ะผะฐัะธ (ั‚ั€ะฐะดะธั†ั–ะนะฝั– ะทะฝะฐั‡ะตะฝะฝั CIAAW)", + "2": "ะœะพะฝะพั–ะทะพั‚ะพะฟะฝะฐ ะผะฐัะฐ ะทะฐ ะฝะฐะนะฟะพัˆะธั€ะตะฝั–ัˆะธะผ ั–ะทะพั‚ะพะฟะพะผ ะบะพะถะฝะพะณะพ ะตะปะตะผะตะฝั‚ะฐ", + "3": "ะขะพั‡ะฝะฐ ะผะฐัะฐ, ะฟะพะดั–ะปะตะฝะฐ ะฝะฐ ะฐะฑัะพะปัŽั‚ะฝะธะน ะทะฐั€ัะด, ะท ะฟะพะฟั€ะฐะฒะบะพัŽ ะฝะฐ ะผะฐััƒ ะตะปะตะบั‚ั€ะพะฝะฐ", + "4": "ะœะฐัะพะฒะฐ ั‡ะฐัั‚ะบะฐ ะบะพะถะฝะพะณะพ ะตะปะตะผะตะฝั‚ะฐ ัƒ ะฒั–ะดัะพั‚ะบะฐั…, ะดะฒะฐ ะทะฝะฐะบะธ ะฟั–ัะปั ะบะพะผะธ", + "5": "ะ’ะฝะตัะบะธ ะฐั‚ะพะผั–ะฒ (Wildman ั– Crippen 1999)", + "6": "ะขะพะฟะพะปะพะณั–ั‡ะฝะฐ ะฟะพะปัั€ะฝะฐ ะฟะพะฒะตั€ั…ะฝั, ั„ั€ะฐะณะผะตะฝั‚ะธ N ั‚ะฐ O (Ertl 2000)", + "7": "ะœะพะปัั€ะฝะฐ ั€ะตั„ั€ะฐะบั†ั–ั", + "8": "ะ”ะพะฝะพั€ะธ ะฒะพะดะฝะตะฒะพะณะพ ะทะฒโ€™ัะทะบัƒ", + "9": "ะŸั–ะดั€ะฐั…ัƒะฝะพะบ ะทะฐ ะ›ั–ะฟั–ะฝัะบั–: ะณั€ัƒะฟะธ N-H ั‚ะฐ O-H", + "10": "ะะบั†ะตะฟั‚ะพั€ะธ ะฒะพะดะฝะตะฒะพะณะพ ะทะฒโ€™ัะทะบัƒ", + "11": "ะŸั–ะดั€ะฐั…ัƒะฝะพะบ ะทะฐ ะ›ั–ะฟั–ะฝัะบั–: ะฐั‚ะพะผะธ N ั‚ะฐ O", + "12": "ะžะฑะตั€ั‚ะพะฒั– ะทะฒโ€™ัะทะบะธ", + "13": "ะะตั†ะธะบะปั–ั‡ะฝั– ะพะดะธะฝะฐั€ะฝั– ะทะฒโ€™ัะทะบะธ ะผั–ะถ ะฝะตั‚ะตั€ะผั–ะฝะฐะปัŒะฝะธะผะธ ะฒะฐะถะบะธะผะธ ะฐั‚ะพะผะฐะผะธ, ะฐะผั–ะดะฝะธะน ะทะฒโ€™ัะทะพะบ C-N ะฒะธะบะปัŽั‡ะตะฝะพ", + "14": "ะŸั€ะฐะฒะธะปะพ ะฟโ€™ัั‚ะธ ะ›ั–ะฟั–ะฝัะบั–", + "15": "MW ะฝะต ะฑั–ะปัŒัˆะต 500, cLogP ะฝะต ะฑั–ะปัŒัˆะต 5, ะดะพะฝะพั€ั–ะฒ ะฝะต ะฑั–ะปัŒัˆะต 5, ะฐะบั†ะตะฟั‚ะพั€ั–ะฒ ะฝะต ะฑั–ะปัŒัˆะต 10", + "16": "HBD", + "17": "HBA", + "18": "ะ’ั–ะดะฟะพะฒั–ะดะฐั” (0 ะฟะพั€ัƒัˆะตะฝัŒ)", + "19": "ะกะฟะตั€ัˆัƒ ะฒะธะดั–ะปั–ั‚ัŒ ะพะดะธะฝ ะฐะฑะพ ะบั–ะปัŒะบะฐ ะฐั‚ะพะผั–ะฒ", + "20": "ะกะฟะตั€ัˆัƒ ะฒะธะดั–ะปั–ั‚ัŒ ะพะดะธะฝ ะฐะฑะพ ะบั–ะปัŒะบะฐ ะทะฒโ€™ัะทะบั–ะฒ", + "21": "ะะตะผะฐั” ะฝะตัะฒะฝะธั… ะฐั‚ะพะผั–ะฒ ะฒะพะดะฝัŽ ะดะปั ะดะพะดะฐะฒะฐะฝะฝั.", + "22": "ะะตะผะฐั” ัะฒะฝะธั… ะฐั‚ะพะผั–ะฒ ะฒะพะดะฝัŽ ะดะปั ะฒะธะดะฐะปะตะฝะฝั.", + "23": "ะ’ะธะดั–ะปั–ั‚ัŒ ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ัƒ, ะฝะฐะฟั€ะธะบะปะฐะด Ph ะฐะฑะพ OTs, ั‰ะพะฑ ั€ะพะทะณะพั€ะฝัƒั‚ะธ ั—ั—.", + "24": "ะ’ะธะดั–ะปั–ั‚ัŒ ะฐั‚ะพะผะธ ะพะดะฝั–ั”ั— ะณั€ัƒะฟะธ ะฒ ะพะดะฝั–ะน ัั‚ั€ัƒะบั‚ัƒั€ั–, ั‰ะพะฑ ะทะณะพั€ะฝัƒั‚ะธ ั—ั….", + "25": "ะ’ะธะดั–ะปั–ั‚ัŒ ะณั€ัƒะฟัƒ ะดะปั ะทะณะพั€ั‚ะฐะฝะฝั ะฑะตะท ะฐั‚ะพะผะฐ, ะดะพ ัะบะพะณะพ ะฒะพะฝะฐ ะฟั€ะธั”ะดะฝะฐะฝะฐ.", + "26": "ะ—ะณะพั€ะฝัƒั‚ะธ", + "27": "ะ’ะธะฑะตั€ั–ั‚ัŒ ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ัƒ ะท ะฑั–ะฑะปั–ะพั‚ะตะบะธ ะฐะฑะพ ะฒะฒะตะดั–ั‚ัŒ ะฝะพะฒัƒ ะผั–ั‚ะบัƒ ะดะปั ะฒะธะดั–ะปะตะฝะธั… ะฐั‚ะพะผั–ะฒ.", + "28": "ะ—ะฐะดะฐั‚ะธ ัั‚ะตั€ะตะพะณั€ัƒะฟัƒ", + "29": "ะžั‡ะธัั‚ะธั‚ะธ ัั‚ะตั€ะตะพะณั€ัƒะฟัƒ", + "30": "ะ—ะฐะดะฐั‚ะธ ัะฟะธัะพะบ ะฐั‚ะพะผั–ะฒ", + "31": "ะžั‡ะธัั‚ะธั‚ะธ ัะฟะธัะพะบ ะฐั‚ะพะผั–ะฒ", + "32": "ะ—ะฐะดะฐั‚ะธ ะทะฐะฟะธั‚ะฝะธะน ะทะฒโ€™ัะทะพะบ", + "33": "ะžั‡ะธัั‚ะธั‚ะธ ะทะฐะฟะธั‚ ะทะฒโ€™ัะทะบัƒ", + "34": "ะ’ะธะดั–ะปั–ั‚ัŒ ะฐั‚ะพะผ, ั‰ะพ ะฝะตัะต R-ะณั€ัƒะฟัƒ.", + "35": "1 ั‚ะพั‡ะบะฐ ะฟั€ะธั”ะดะฝะฐะฝะฝั", + "36": "ะ’ะธะทะฝะฐั‡ะธั‚ะธ R-ะณั€ัƒะฟัƒ", + "37": "ะ’ะธะดะฐะปะธั‚ะธ ะฒะธะทะฝะฐั‡ะตะฝะฝั R-ะณั€ัƒะฟะธ", + "38": "ะŸั€ะธะทะฝะฐั‡ะธั‚ะธ ะบะปะธะฝะธ", + "39": "ะšะปะธะฝะธ ะฒะถะต ะฒั–ะดะฟะพะฒั–ะดะฐัŽั‚ัŒ ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ะฐะผ.", + "40": "ะ’ะธะดั–ะปะตะฝั– ัั‚ั€ัƒะบั‚ัƒั€ะธ", + "41": "ะฃัั– ัั‚ั€ัƒะบั‚ัƒั€ะธ ะฝะฐ ั†ั–ะน ัั‚ะพั€ั–ะฝั†ั–", + "42": "ะ’ะธะฟั€ะฐะฒะธั‚ะธ ัั‚ั€ัƒะบั‚ัƒั€ัƒ", + "43": "ะะตะผะฐั” ัั‚ั€ัƒะบั‚ัƒั€ะธ ะดะปั ะฐะฝะฐะปั–ะทัƒ.", + "44": "ะะฝะฐะปั–ะท ัะบะพะฟั–ะนะพะฒะฐะฝะพ", + "45": "ะะต ะฒะดะฐะปะพัั ัะบะพะฟั–ัŽะฒะฐั‚ะธ ะฒ ะฑัƒั„ะตั€ ะพะฑะผั–ะฝัƒ", + "46": "ะ—ะฝะฐะนั‚ะธ ะฟั–ะดัั‚ั€ัƒะบั‚ัƒั€ัƒ", + "47": "SMARTS", + "48": "ะกะฟะตั€ัˆัƒ ะฝะฐะผะฐะปัŽะนั‚ะต ัั‚ั€ัƒะบั‚ัƒั€ะธ ะดะปั ะฟะพัˆัƒะบัƒ ะฝะฐ ั†ั–ะน ัั‚ะพั€ั–ะฝั†ั–.", + "49": "ะปะธัˆะต ะฟะตั€ัˆั– ั€ะตะทัƒะปัŒั‚ะฐั‚ะธ", + "50": "ะะฐ ั†ั–ะน ัั‚ะพั€ั–ะฝั†ั– ะทะฑั–ะณั–ะฒ ะฝะตะผะฐั”.", + "51": "ะกะฟะตั€ัˆัƒ ะฝะฐะผะฐะปัŽะนั‚ะต ัั‚ั€ัƒะบั‚ัƒั€ัƒ ะท ะฐั‚ะพะผะฐะผะธ R-ะณั€ัƒะฟ ั– ะฒะธะทะฝะฐั‡ั‚ะต ั—ั— R-ะณั€ัƒะฟะธ.", + "52": "ะะตะผะฐั” ัั‚ั€ัƒะบั‚ัƒั€ะธ, ัะบัƒ ะผะพะถะฝะฐ ะทะฐะฟะธัะฐั‚ะธ ัะบ SMARTS.", + "53": "ะ—ะฑะตั€ะตะถะตะฝะฝั ั„ะฐะนะปั–ะฒ SMARTS ะทโ€™ัะฒะธั‚ัŒัั ั€ะฐะทะพะผ ั–ะท ั„ะฐะนะปะพะฒะธะผะธ ั„ะพั€ะผะฐั‚ะฐะผะธ ัƒ ะฒะตั€ัั–ั— 0.7.0; ะฝะฐั‚ะพะผั–ัั‚ัŒ SMARTS ัะบะพะฟั–ะนะพะฒะฐะฝะพ.", + "54": "ะœะฐะปัŽั” ะบะพะถะตะฝ ะฝะตัะฒะฝะธะน ะฒะพะดะตะฝัŒ ะฒะธะดั–ะปะตะฝะธั… ะฐั‚ะพะผั–ะฒ (ะฐะฑะพ ะฒัั–ั… ัั‚ั€ัƒะบั‚ัƒั€ ัั‚ะพั€ั–ะฝะบะธ) ัะบ ัะฒะฝะธะน ะฐั‚ะพะผ H, ั€ะพะทะผั–ั‰ะตะฝะธะน ั€ัƒัˆั–ั”ะผ, ะพะดะฝะธะผ ะบั€ะพะบะพะผ ัะบะฐััƒะฒะฐะฝะฝั.", + "55": "ะ’ะธะดะฐะปัั” ัะฒะฝั– ะฐั‚ะพะผะธ H ะท ะฒะธะดั–ะปะตะฝะฝั (ะฐะฑะพ ะทั– ัั‚ะพั€ั–ะฝะบะธ), ะทะฑะตั€ั–ะณะฐัŽั‡ะธ ะฒะพะดะฝั–, ั‰ะพ ะฝะตััƒั‚ัŒ ัั‚ะตั€ะตะพั–ะฝั„ะพั€ะผะฐั†ั–ัŽ, ั–ะทะพั‚ะพะฟ, ะทะฐั€ัะด, ะฝะพะผะตั€ ะฒั–ะดะพะฑั€ะฐะถะตะฝะฝั ะฐะฑะพ ัะฟะพะปัƒั‡ะฐัŽั‚ัŒ ะดะฒะฐ ะฐั‚ะพะผะธ.", + "56": "ะ—ะฐะผั–ะฝัŽั” ะฒะธะดั–ะปะตะฝั– ะฐั‚ะพะผะธ-ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ะธ (ะฐะฑะพ ะฒัั– ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ะธ ัั‚ะพั€ั–ะฝะบะธ) ั—ั…ะฝัŒะพัŽ ะฟะพะฒะฝะพัŽ ัั‚ั€ัƒะบั‚ัƒั€ะพัŽ, ั€ะพะทั‚ะฐัˆะพะฒะฐะฝะพัŽ ะฒะทะดะพะฒะถ ะทะฒโ€™ัะทะบัƒ ะฟั€ะธั”ะดะฝะฐะฝะฝั.", + "57": "ะ—ะณะพั€ะฝัƒั‚ะธ ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ัƒ...", + "58": "ะ—ะณะพั€ั‚ะฐั” ะฒะธะดั–ะปะตะฝัƒ ะณั€ัƒะฟัƒ ะฐั‚ะพะผั–ะฒ ะฒ ะพะดะธะฝ ะฐั‚ะพะผ-ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€ัƒ ะท ะผั–ั‚ะบะพัŽ, ัะบัƒ ะบะพั€ะธัั‚ัƒะฒะฐั‡ ะฒะธะฑะธั€ะฐั” ะฐะฑะพ ะฒะฒะพะดะธั‚ัŒ.", + "59": "ะŸะพะบะฐะทัƒั” ะฐะฑะพ ะฟั€ะธั…ะพะฒัƒั” ะฟะพะทะฝะฐั‡ะบะธ R, S, E ั‚ะฐ Z ะฑั–ะปั ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ั–ะฒ ั– ัั‚ะตั€ะตะพะดะฒะพะทะฒโ€™ัะทะบั–ะฒ.", + "60": "ะŸะพะบะฐะทัƒะฒะฐั‚ะธ ั€ะพะทัˆะธั€ะตะฝั– ัั‚ะตั€ะตะพะณั€ัƒะฟะธ", + "61": "ะŸะพะบะฐะทัƒั” ะฐะฑะพ ะฟั€ะธั…ะพะฒัƒั” ะฟะพะทะฝะฐั‡ะบะธ ะณั€ัƒะฟ abs, and ั‚ะฐ or ะฑั–ะปั ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ั–ะฒ, ะฟะพะบะธ ัั‚ะตั€ะตะพะฟะพะทะฝะฐั‡ะบะธ ะฒะฒั–ะผะบะฝะตะฝะพ.", + "62": "ะŸะพะบะฐะทัƒะฒะฐั‚ะธ ะทะฐะฟะธั‚ะฝั– ะพะทะฝะฐะบะธ", + "63": "ะŸะพะบะฐะทัƒั” ะฐะฑะพ ะฟั€ะธั…ะพะฒัƒั” ะฝะฐ ะฟะพะปะพั‚ะฝั– ะฟะพะทะฝะฐั‡ะบะธ ัะฟะธัะบัƒ ะฐั‚ะพะผั–ะฒ, ะทะฐะฟะธั‚ะฝะพะณะพ ะทะฒโ€™ัะทะบัƒ ั‚ะฐ R-ะณั€ัƒะฟะธ.", + "64": "ะŸะพะผั–ั‰ะฐั” ะฒะธะดั–ะปะตะฝั– ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ะธ ะฒ ั€ะพะทัˆะธั€ะตะฝัƒ ัั‚ะตั€ะตะพะณั€ัƒะฟัƒ: abs, and n ะฐะฑะพ or n. ะ‘ะตะท n ัั‚ะฒะพั€ัŽั”ั‚ัŒัั ะฝะพะฒะฐ ะณั€ัƒะฟะฐ and ะฐะฑะพ or.", + "65": "abs, and ะฐะฑะพ or", + "66": "ะะพะผะตั€ ะณั€ัƒะฟะธ ะดะปั and ั‚ะฐ or", + "67": "ะะฑัะพะปัŽั‚ะฝะฐ (abs)", + "68": "ะะพะฒะฐ ะณั€ัƒะฟะฐ AND", + "69": "ะะพะฒะฐ ะณั€ัƒะฟะฐ OR", + "70": "ะกั‚ะตั€ะตะพะณั€ัƒะฟะฐ...", + "71": "ะกะฟะธัะพะบ ะฐั‚ะพะผั–ะฒ...", + "72": "ะŸะตั€ะตั‚ะฒะพั€ัŽั” ะฒะธะดั–ะปะตะฝั– ะฐั‚ะพะผะธ ะฝะฐ ะทะฐะฟะธั‚ ะทั– ัะฟะธัะบะพะผ ะฐั‚ะพะผั–ะฒ ะฐะฑะพ ะทั– ัะฟะธัะบะพะผ-ะทะฐะฟะตั€ะตั‡ะตะฝะฝัะผ, ะฒะธะฑั€ะฐะฝะธะผ ัƒ ะฟะตั€ั–ะพะดะธั‡ะฝั–ะน ั‚ะฐะฑะปะธั†ั–.", + "73": "ะ ะพะฑะธั‚ัŒ ะฒะธะดั–ะปะตะฝั– ะทะฒโ€™ัะทะบะธ ะทะฐะฟะธั‚ะฝะธะผะธ: any, single_or_double, single_or_aromatic ะฐะฑะพ double_or_aromatic; ะฑะตะท query ะทะฐะฟะธั‚ ะพั‡ะธั‰ะฐั”ั‚ัŒัั.", + "74": "ะขะธะฟ ะทะฐะฟะธั‚ะฝะพะณะพ ะทะฒโ€™ัะทะบัƒ", + "75": "ะ’ะธะทะฝะฐั‡ะธั‚ะธ R-ะณั€ัƒะฟัƒ...", + "76": "ะ ะพะฑะธั‚ัŒ ะฒะธะดั–ะปะตะฝะธะน ะฐั‚ะพะผ ะผั–ั‚ะบะพัŽ R-ะณั€ัƒะฟะธ ั‚ะฐ ะฒะธะทะฝะฐั‡ะฐั” ั—ั— ั‡ะปะตะฝะธ, ะฒั…ะพะดะถะตะฝะฝั, ั€ะตัˆั‚ัƒ H ั– ัƒะผะพะฒัƒ ยซัะบั‰ะพ, ั‚ะพยป.", + "77": "ะ”ะฐั” ะทะผะพะณัƒ ั€ัƒัˆั–ั”ะฒั– ะฒะธะฑั€ะฐั‚ะธ ะบะปะธะฝะพะฟะพะดั–ะฑะฝั– ั‚ะฐ ัˆั‚ั€ะธั…ะพะฒั– ะทะฒโ€™ัะทะบะธ, ั‰ะพ ะพะดะฝะพะทะฝะฐั‡ะฝะพ ะฒะธั€ะฐะถะฐัŽั‚ัŒ ัั‚ะตั€ะตะพั†ะตะฝั‚ั€ะธ ะฒะธะดั–ะปะตะฝะฝั (ะฐะฑะพ ัั‚ะพั€ั–ะฝะบะธ).", + "78": "ะŸะตั€ะตะปั–ั‡ัƒั” ะฟั€ะพะฑะปะตะผะธ ะฒะฐะปะตะฝั‚ะฝะพัั‚ั–, ัั‚ะตั€ะตะพั…ั–ะผั–ั—, ะณะตะพะผะตั‚ั€ั–ั— ั‚ะฐ ะผั–ั‚ะพะบ ะดะปั ะฒะธะดั–ะปะตะฝะฝั (ะฐะฑะพ ัั‚ะพั€ั–ะฝะบะธ) ะฝะฐ ะฟะฐะฝะตะปั–, ั€ัะดะบะธ ัะบะพั— ะฒะธะดั–ะปััŽั‚ัŒ ะฐั‚ะพะผะธ.", + "79": "ะ’ั–ะดะบั€ะธะฒะฐั” ะฟะฐะฝะตะปัŒ ะฐะฝะฐะปั–ะทัƒ ะท ั€ะพะทั€ะฐั…ะพะฒะฐะฝะธะผะธ ะฒะปะฐัั‚ะธะฒะพัั‚ัะผะธ ะฒะธะดั–ะปะตะฝะฝั ะฐะฑะพ ัั‚ะพั€ั–ะฝะบะธ.", + "80": "ะšะพะฟั–ัŽั” ั„ะพั€ะผัƒะปัƒ, ะผะฐัะธ, ะตะปะตะผะตะฝั‚ะฝะธะน ะฐะฝะฐะปั–ะท ั– ั€ะพะทั€ะฐั…ะพะฒะฐะฝั– ะฒะปะฐัั‚ะธะฒะพัั‚ั– ะท ั—ั…ะฝั–ะผะธ ะผะตั‚ะพะดะฐะผะธ ัะบ ั‚ะตะบัั‚.", + "81": "ะ—ะฝะฐะนั‚ะธ ะฟั–ะดัั‚ั€ัƒะบั‚ัƒั€ัƒ...", + "82": "ะ’ะธะดั–ะปัั” ะบะพะถะตะฝ ะทะฑั–ะณ ะฒะธะดั–ะปะตะฝะธั… ะฐั‚ะพะผั–ะฒ (ะฐะฑะพ ัˆะฐะฑะปะพะฝัƒ SMARTS) ะฒ ั–ะฝัˆะธั… ัั‚ั€ัƒะบั‚ัƒั€ะฐั… ัั‚ะพั€ั–ะฝะบะธ.", + "83": "ะŸะตั€ะตะปั–ั‡ะธั‚ะธ R-ะณั€ัƒะฟะธ...", + "84": "ะŸะตั€ะตะปั–ั‡ัƒั” ะบะพะถะฝัƒ ัั‚ั€ัƒะบั‚ัƒั€ัƒ, ัะบัƒ ะฟะพะดะฐั” ะฒะธะดั–ะปะตะฝะธะน ัะบะฐั„ะพะปะด ะœะฐั€ะบัƒัˆะฐ (ะฐะฑะพ ะฟะตั€ัˆะธะน ะฝะฐ ัั‚ะพั€ั–ะฝั†ั–), ะท ั„ะพั€ะผัƒะปะพัŽ ั‚ะฐ SMILES, ะดะพ 1000; ัะฟะธัะพะบ ะผะพะถะฝะฐ ัะบะพะฟั–ัŽะฒะฐั‚ะธ.", + "85": "ะšะพะฟั–ัŽะฒะฐั‚ะธ ัะบ SMARTS", + "86": "ะšะพะฟั–ัŽั” ะฒะธะดั–ะปะตะฝั– ะฐั‚ะพะผะธ (ะฐะฑะพ ะฒัั– ัั‚ั€ัƒะบั‚ัƒั€ะธ ัั‚ะพั€ั–ะฝะบะธ) ัะบ SMARTS ั€ะฐะทะพะผ ะทั– ัะฟะธัะบะฐะผะธ ะฐั‚ะพะผั–ะฒ, ัƒะทะฐะณะฐะปัŒะฝะตะฝะธะผะธ ะฐั‚ะพะผะฐะผะธ, ะทะฐะฟะธั‚ะฝะธะผะธ ะทะฒโ€™ัะทะบะฐะผะธ ั‚ะฐ ั–ะฝัˆะธะผะธ ะทะฐะฟะธั‚ะฝะธะผะธ ะพะทะฝะฐะบะฐะผะธ.", + "87": "ะ•ะบัะฟะพั€ั‚ัƒะฒะฐั‚ะธ SMARTS...", + "88": "ะ—ะฑะตั€ั–ะณะฐั” ะฒะธะดั–ะปะตะฝั– ะฐั‚ะพะผะธ (ะฐะฑะพ ะฒัั– ัั‚ั€ัƒะบั‚ัƒั€ะธ ัั‚ะพั€ั–ะฝะบะธ) ัะบ ั„ะฐะนะป SMARTS (.sma).", + "89": "ะ ะพะทัˆะธั€ะตะฝะฐ ัั‚ะตั€ะตะพั…ั–ะผั–ั", + "90": "ะ—ะฐะฟะธั‚", + "91": "ะžะฑโ€™ั”ะบั‚", + "92": "ะกะฟะตั€ัˆัƒ ะฒะธะดั–ะปั–ั‚ัŒ ัั‚ั€ัƒะบั‚ัƒั€ะธ ะฐะฑะพ ั‚ะตะบัั‚, ัะบะธะผ ัะปั–ะด ะฟั€ะธะทะฝะฐั‡ะธั‚ะธ ั€ะพะปัŒ.", + "93": "ะ—ะฐะดะฐั‚ะธ ั€ะพะปั– ั€ะตะฐะบั†ั–ั—...", + "94": "ะ—ะฐะดะฐั” ั€ะพะปัŒ ะฒะธะดั–ะปะตะฝะธั… ัั‚ั€ัƒะบั‚ัƒั€ ะฐะฑะพ ั‚ะตะบัั‚ัƒ ัƒ ะฒะธะดั–ะปะตะฝะพะผัƒ ะบั€ะพั†ั– ั€ะตะฐะบั†ั–ั— (ั€ะตะฐะณะตะฝั‚, ะฟั€ะพะดัƒะบั‚, ะฐะณะตะฝั‚, ัƒะผะพะฒะฐ ะฐะฑะพ ะถะพะดะฝะพั—) ั– ะฟะพะทะฝะฐั‡ะฐั” ั€ะพะปั– ะบั€ะพะบัƒ ัะบ ะทะฐะดะฐะฝั– ะฒั€ัƒั‡ะฝัƒ, ะพะดะฝะธะผ ะบั€ะพะบะพะผ ัะบะฐััƒะฒะฐะฝะฝั. ะ‘ะตะท role ะฒั–ะดะบั€ะธะฒะฐั” ะดั–ะฐะปะพะณ ะทั– ัะฟะธัะบะพะผ ัƒั‡ะฐัะฝะธะบั–ะฒ ะบั€ะพะบัƒ ั‚ะฐ ะฒะธะดั–ะปะตะฝะฝัะผ.", + "95": "ะ ะพะปัŒ ะดะปั ะพะฑโ€™ั”ะบั‚ั–ะฒ; ะฟั€ะพะฟัƒัั‚ั–ั‚ัŒ, ั‰ะพะฑ ะฒั–ะดะบั€ะธั‚ะธ ะดั–ะฐะปะพะณ", + "96": "ะ†ะดะตะฝั‚ะธั„ั–ะบะฐั‚ะพั€ะธ ะพะฑโ€™ั”ะบั‚ั–ะฒ ะดะปั ะทะผั–ะฝะธ; ั‚ะธะฟะพะฒะพ ะฒะธะดั–ะปะตะฝะฝั", + "97": "ะะต ะฒะดะฐะปะพัั ะทะฐะดะฐั‚ะธ ั€ะพะปั– ั€ะตะฐะบั†ั–ั—", + "98": "ั€ะตัˆั‚ะฐ H", + "99": "ะะฑั€ะตะฒั–ะฐั‚ัƒั€ะฐ", + "100": "ะœั–ั‚ะบะฐ", + "101": "ะŸะพัˆัƒะบ ัƒ ะฑั–ะฑะปั–ะพั‚ะตั†ั–", + "102": "ะะต ะฒะดะฐะปะพัั ะทะฐะฒะฐะฝั‚ะฐะถะธั‚ะธ ะฑั–ะฑะปั–ะพั‚ะตะบัƒ ะฐะฑั€ะตะฒั–ะฐั‚ัƒั€. ะœั–ั‚ะบัƒ ะฒัะต ะพะดะฝะพ ะผะพะถะฝะฐ ะฒะฒะตัั‚ะธ.", + "103": "ะะฑั€ะตะฒั–ะฐั‚ัƒั€, ั‰ะพ ะทะฑั–ะณะฐัŽั‚ัŒัั, ะฝะตะผะฐั”. ะ’ะฒะตะดะตะฝะฐ ะผั–ั‚ะบะฐ ะฒะธะบะพั€ะธัั‚ะพะฒัƒั”ั‚ัŒัั ัะบ ั”.", + "104": "ะ’ะปะฐัั‚ะธะฒะพัั‚ั–", + "105": "ะกะฟะธัะพะบ ะฐั‚ะพะผั–ะฒ", + "106": "ะšะปะฐั†ะฐะนั‚ะต ะตะปะตะผะตะฝั‚ะธ ะฒ ั‚ะฐะฑะปะธั†ั–, ั‰ะพะฑ ะดะพะดะฐั‚ะธ ั—ั….", + "107": "ะžั‡ะธัั‚ะธั‚ะธ ะทะฐะฟะธั‚", + "108": "ะ—ะฐัั‚ะพััƒะฒะฐั‚ะธ", + "109": "ะ’ะธะดะฐะปะธั‚ะธ", + "110": "ะ‘ะตะท ะทะฐะฟะธั‚ัƒ", + "111": "[M+Na]+", + "112": "ะ†ะทะพั‚ะพะฟะฝะธะน ั€ะพะทะฟะพะดั–ะป", + "113": "ะŸะตั€ะตะปั–ั‡ะธั‚ะธ R-ะณั€ัƒะฟะธ", + "114": "ะšะพะฟั–ัŽะฒะฐั‚ะธ SMILES", + "115": "SMILES ะบะพะถะฝะพั— ัั‚ั€ัƒะบั‚ัƒั€ะธ ัะบะพะฟั–ะนะพะฒะฐะฝะพ", + "116": "Si", + "117": "ะ‘ัƒะดัŒ-ัะบะธะน ะทะฒโ€™ัะทะพะบ", + "118": "ะžะดะธะฝะฐั€ะฝะธะน ะฐะฑะพ ะฟะพะดะฒั–ะนะฝะธะน", + "119": "ะžะดะธะฝะฐั€ะฝะธะน ะฐะฑะพ ะฐั€ะพะผะฐั‚ะธั‡ะฝะธะน", + "120": "ะŸะพะดะฒั–ะนะฝะธะน ะฐะฑะพ ะฐั€ะพะผะฐั‚ะธั‡ะฝะธะน", + "121": "ะฆะธะบะป ะฐะฑะพ ะปะฐะฝั†ัŽะณ", + "122": "ะฃ ั†ะธะบะปั–", + "123": "ะฃ ะปะฐะฝั†ัŽะณัƒ", + "124": "ะ‘ัƒะดัŒ-ัะบะธะน ะฐั‚ะพะผ (A)", + "125": "ะ‘ัƒะดัŒ-ัะบะธะน ะณะตั‚ะตั€ะพะฐั‚ะพะผ (Q)", + "126": "ะ‘ัƒะดัŒ-ัะบะธะน ะณะฐะปะพะณะตะฝ (X)", + "127": "ะ‘ัƒะดัŒ-ัะบะธะน ะผะตั‚ะฐะป (M)", + "128": "ะ—ะฐะดะฐั‚ะธ ั‚ะพะฟะพะปะพะณั–ัŽ ะทะฒโ€™ัะทะบัƒ", + "129": "ะ—ะฐะฟะธั‚ะฝะธะน ะทะฒโ€™ัะทะพะบ", + "130": "ะ—ะฐะดะฐั‚ะธ ะทะฐะฟะธั‚ ะฐั‚ะพะผะฐ", + "131": "ะั€ะพะผะฐั‚ะธั‡ะฝะธะน", + "132": "ะะปั–ั„ะฐั‚ะธั‡ะฝะธะน", + "133": "ะะตะฝะฐัะธั‡ะตะฝะธะน", + "134": "ะ—ะฐะผั–ั‰ะตะฝะฝั ัะบ ะฝะฐะผะฐะปัŒะพะฒะฐะฝะพ", + "135": "ะฆะธะบะปั–ั‡ะฝั– ะทะฒโ€™ัะทะบะธ ัะบ ะฝะฐะผะฐะปัŒะพะฒะฐะฝะพ", + "136": "ะžั‡ะธัั‚ะธั‚ะธ ะทะฐะฟะธั‚ ะฐั‚ะพะผะฐ", + "137": "ะ—ะฐะฟะธั‚ ะฐั‚ะพะผะฐ", + "138": "ะ’ะธะทะฝะฐั‡ะตะฝะฝั R-ะณั€ัƒะฟะธ", + "139": "R-ะณั€ัƒะฟะฐ", + "140": "ะงะปะตะฝะธ", + "141": "ะะฐะผะฐะปัŽะนั‚ะต ะบะพะถะฝะพะณะพ ั‡ะปะตะฝะฐ ัะบ ะพะบั€ะตะผัƒ ัั‚ั€ัƒะบั‚ัƒั€ัƒ ะท ั‚ะพั‡ะบะพัŽ ะฟั€ะธั”ะดะฝะฐะฝะฝั (*), ะฟะพั‚ั–ะผ ะทะฝะพะฒัƒ ะฒั–ะดะบั€ะธะนั‚ะต ั†ะตะน ะดั–ะฐะปะพะณ.", + "142": "ะ’ั…ะพะดะถะตะฝะฝั", + "143": "ะ ะตัˆั‚ะฐ H (ะฝะตะทะฐะผั–ั‰ะตะฝั– ะฟะพะปะพะถะตะฝะฝั ะทะฐะนะผะฐั” ะฒะพะดะตะฝัŒ)", + "144": "ะฏะบั‰ะพ ั”, ั‚ะพ", + "145": "ะ’ะธะดะฐะปะธั‚ะธ ะฒะธะทะฝะฐั‡ะตะฝะฝั", + "146": "ะะณะตะฝั‚", + "147": "ะฃะผะพะฒะฐ", + "148": "ะžั‡ะธัั‚ะธั‚ะธ", + "149": "ะ”ะพะดะฐั‚ะธ ะฒะธะดั–ะปะตะฝั– ั†ะตะฝั‚ั€ะธ ะดะพ ั†ั–ั”ั— ะณั€ัƒะฟะธ", + "150": "ะŸะตั€ะตะฒั–ั€ะธั‚ะธ ั‰ะต ั€ะฐะท", + "151": "ะŸะตั€ะตะฒั–ั€ะบะฐ...", + "152": "ะ’ะธะฟั€ะฐะฒะธั‚ะธ", + "153": "ะ’ะธะดั–ะปะธั‚ะธ ะฝะฐ ะฟะพะปะพั‚ะฝั–" +} From b4b44ec66fe3c4d5331379ad0dda5fd42ab07ee1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:44 -0500 Subject: [PATCH 256/279] feat(i18n): translate the stereo, query and analysis strings into Turkish (0.6.0) Adds part06 for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/tr/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/tr/part06.json diff --git a/frontend/src/i18n/locales/tr/part06.json b/frontend/src/i18n/locales/tr/part06.json new file mode 100644 index 00000000..b33f90d2 --- /dev/null +++ b/frontend/src/i18n/locales/tr/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Hill sฤฑrasฤฑ, yรผkle birlikte, kฤฑsaltmalar aรงฤฑlmฤฑลŸ", + "1": "Standart atom aฤŸฤฑrlฤฑklarฤฑ (CIAAW geleneksel deฤŸerleri)", + "2": "Her elementin en bol izotopundan monoizotopik kรผtle", + "3": "Tam kรผtle, mutlak yรผke bรถlรผnmรผลŸ, elektron kรผtlesi dรผzeltmeli", + "4": "Her elementin kรผtle yรผzdesi, iki ondalฤฑk basamak", + "5": "Atom katkฤฑlarฤฑ (Wildman ve Crippen 1999)", + "6": "Topolojik polar yรผzey alanฤฑ, N ve O parรงalarฤฑ (Ertl 2000)", + "7": "Molar kฤฑrฤฑlma", + "8": "Hidrojen baฤŸฤฑ vericileri", + "9": "Lipinski sayฤฑmฤฑ: N-H ve O-H gruplarฤฑ", + "10": "Hidrojen baฤŸฤฑ alฤฑcฤฑlarฤฑ", + "11": "Lipinski sayฤฑmฤฑ: N ve O atomlarฤฑ", + "12": "Dรถnebilen baฤŸlar", + "13": "Uรง olmayan aฤŸฤฑr atomlar arasฤฑndaki halka dฤฑลŸฤฑ tekli baฤŸlar, amit C-N hariรง", + "14": "Lipinski beลŸli kuralฤฑ", + "15": "MW en รงok 500, cLogP en รงok 5, vericiler en รงok 5, alฤฑcฤฑlar en รงok 10", + "16": "HBD", + "17": "HBA", + "18": "Geรงti (0 ihlal)", + "19": "ร–nce bir veya daha fazla atom seรงin", + "20": "ร–nce bir veya daha fazla baฤŸ seรงin", + "21": "Eklenecek รถrtรผk hidrojen yok.", + "22": "Kaldฤฑrฤฑlacak aรงฤฑk hidrojen yok.", + "23": "Aรงmak iรงin Ph veya OTs gibi bir kฤฑsaltma seรงin.", + "24": "Daraltmak iรงin tek bir yapฤฑdaki bir grubun atomlarฤฑnฤฑ seรงin.", + "25": "Daraltฤฑlacak grubu, baฤŸlฤฑ olduฤŸu atom olmadan seรงin.", + "26": "Daralt", + "27": "Kitaplฤฑktan bir kฤฑsaltma seรงin veya seรงili atomlar iรงin yeni bir etiket yazฤฑn.", + "28": "Stereo Grubu Ayarla", + "29": "Stereo Grubunu Temizle", + "30": "Atom Listesi Ayarla", + "31": "Atom Listesini Temizle", + "32": "Sorgu BaฤŸฤฑ Ayarla", + "33": "BaฤŸ Sorgusunu Temizle", + "34": "R grubunu taลŸฤฑyan atomu seรงin.", + "35": "1 baฤŸlanma noktasฤฑ", + "36": "R Grubu Tanฤฑmla", + "37": "R Grubu Tanฤฑmฤฑnฤฑ Kaldฤฑr", + "38": "Kamalarฤฑ Ata", + "39": "Kamalar zaten stereomerkezlerle uyumlu.", + "40": "Seรงili yapฤฑlar", + "41": "Bu sayfadaki her yapฤฑ", + "42": "Yapฤฑyฤฑ Dรผzelt", + "43": "ร‡รถzรผmlenecek yapฤฑ yok.", + "44": "ร‡รถzรผmleme kopyalandฤฑ", + "45": "Panoya kopyalanamadฤฑ", + "46": "Alt Yapฤฑ Bul", + "47": "SMARTS", + "48": "ร–nce bu sayfada aranacak yapฤฑlarฤฑ รงizin.", + "49": "yalnฤฑzca ilk sonuรงlar", + "50": "Bu sayfada eลŸleลŸme yok.", + "51": "ร–nce R grubu atomlarฤฑ olan bir yapฤฑ รงizin ve R gruplarฤฑnฤฑ tanฤฑmlayฤฑn.", + "52": "SMARTS olarak yazฤฑlacak yapฤฑ yok.", + "53": "SMARTS dosyalarฤฑnฤฑ kaydetme, dosya biรงimleriyle birlikte 0.7.0 sรผrรผmรผnde gelecek; bunun yerine SMARTS kopyalandฤฑ.", + "54": "Seรงili atomlarฤฑn (veya sayfadaki her yapฤฑnฤฑn) tรผm รถrtรผk hidrojenlerini, motorun yerleลŸtirdiฤŸi aรงฤฑk H atomlarฤฑ olarak, tek bir geri alma adฤฑmฤฑnda รงizer.", + "55": "Seรงimden (veya sayfadan) aรงฤฑk H atomlarฤฑnฤฑ kaldฤฑrฤฑr; stereo, izotop, yรผk, eลŸleme numarasฤฑ taลŸฤฑyan veya iki atomu kรถprรผleyen hidrojenleri korur.", + "56": "Seรงili kฤฑsaltma atomlarฤฑnฤฑ (veya sayfadaki her kฤฑsaltmayฤฑ) baฤŸlanma baฤŸฤฑ boyunca yerleลŸtirilmiลŸ tam yapฤฑlarฤฑyla deฤŸiลŸtirir.", + "57": "Kฤฑsaltmayฤฑ Daralt...", + "58": "Seรงili atom grubunu, kullanฤฑcฤฑnฤฑn seรงtiฤŸi veya yazdฤฑฤŸฤฑ etiketle tek bir kฤฑsaltma atomuna daraltฤฑr.", + "59": "Stereomerkezlerin ve stereo รงift baฤŸlarฤฑn yanฤฑndaki R, S, E ve Z etiketlerini gรถsterir veya gizler.", + "60": "GeliลŸmiลŸ Stereo Gruplarฤฑnฤฑ Gรถster", + "61": "Stereo etiketleri aรงฤฑkken stereomerkezlerin yanฤฑndaki abs, and ve or grup etiketlerini gรถsterir veya gizler.", + "62": "Sorgu ร–zelliklerini Gรถster", + "63": "Tuval รผzerinde atom listesi, sorgu baฤŸฤฑ ve R grubu iลŸaretlerini gรถsterir veya gizler.", + "64": "Seรงili stereomerkezleri geliลŸmiลŸ bir stereo grubuna koyar: abs, and n veya or n. n olmadan yeni bir and veya or grubu oluลŸturulur.", + "65": "abs, and veya or", + "66": "and ve or iรงin grup numarasฤฑ", + "67": "Mutlak (abs)", + "68": "Yeni AND Grubu", + "69": "Yeni OR Grubu", + "70": "Stereo Grubu...", + "71": "Atom Listesi...", + "72": "Seรงili atomlarฤฑ, periyodik tabloda seรงilen bir atom listesi veya hariรง liste sorgusuna dรถnรผลŸtรผrรผr.", + "73": "Seรงili baฤŸlarฤฑ sorgu baฤŸlarฤฑna dรถnรผลŸtรผrรผr: any, single_or_double, single_or_aromatic veya double_or_aromatic; query verilmezse temizlenir.", + "74": "Sorgu baฤŸฤฑ tรผrรผ", + "75": "R Grubu Tanฤฑmla...", + "76": "Seรงili atomu bir R grubu etiketi yapar ve รผyelerini, oluลŸum sayฤฑsฤฑnฤฑ, kalan H'yi ve eฤŸer-ise koลŸulunu tanฤฑmlar.", + "77": "Motorun, seรงimin (veya sayfanฤฑn) stereomerkezlerini belirsizlik bฤฑrakmadan ifade eden kama ve kesikli baฤŸlarฤฑ seรงmesini saฤŸlar.", + "78": "Seรงimin (veya sayfanฤฑn) deฤŸerlik, stereo, geometri ve etiket sorunlarฤฑnฤฑ, satฤฑrlarฤฑ atomlarฤฑ seรงen bir panelde listeler.", + "79": "Seรงimin veya sayfanฤฑn hesaplanan รถzellikleriyle รงรถzรผmleme panelini aรงar.", + "80": "Formรผlรผ, kรผtleleri, elemental analizi ve hesaplanan รถzellikleri yรถntemleriyle birlikte metin olarak kopyalar.", + "81": "Alt Yapฤฑ Bul...", + "82": "Seรงili atomlarฤฑn (veya bir SMARTS deseninin) sayfadaki diฤŸer yapฤฑlarda bulunan her eลŸleลŸmesini seรงer.", + "83": "R Gruplarฤฑnฤฑ Sฤฑrala...", + "84": "Seรงili Markush iskeletinin (veya sayfadaki ilkinin) temsil ettiฤŸi her yapฤฑyฤฑ formรผl ve SMILES ile 1000'e kadar listeler; liste kopyalanabilir.", + "85": "SMARTS Olarak Kopyala", + "86": "Seรงili atomlarฤฑ (veya sayfadaki her yapฤฑyฤฑ) atom listeleri, genel atomlar, sorgu baฤŸlarฤฑ ve diฤŸer sorgu รถzellikleriyle birlikte SMARTS olarak kopyalar.", + "87": "SMARTS DฤฑลŸa Aktar...", + "88": "Seรงili atomlarฤฑ (veya sayfadaki her yapฤฑyฤฑ) bir SMARTS dosyasฤฑ (.sma) olarak kaydeder.", + "89": "GeliลŸmiลŸ Stereo", + "90": "Sorgu", + "91": "Nesne", + "92": "ร–nce rol verilecek yapฤฑlarฤฑ veya metni seรงin.", + "93": "Tepkime Rollerini Ayarla...", + "94": "Seรงili yapฤฑlarฤฑn veya metnin seรงili tepkime adฤฑmฤฑndaki rolรผnรผ (reaktan, รผrรผn, ajan, koลŸul veya hiรงbiri) ayarlar ve adฤฑmฤฑn rollerini elle ayarlanmฤฑลŸ olarak iลŸaretler, tek bir geri alma adฤฑmฤฑnda. role olmadan, adฤฑmฤฑn รผyelerini ve seรงimi listeleyen bir pencere aรงar.", + "95": "Nesnelere verilecek rol; pencereyi aรงmak iรงin boลŸ bฤฑrakฤฑn", + "96": "DeฤŸiลŸtirilecek nesne kimlikleri; varsayฤฑlan seรงim", + "97": "Tepkime rolleri ayarlanamadฤฑ", + "98": "kalan H", + "99": "Kฤฑsaltma", + "100": "Etiket", + "101": "Kitaplฤฑkta ara", + "102": "Kฤฑsaltma kitaplฤฑฤŸฤฑ yรผklenemedi. Yine de bir etiket yazabilirsiniz.", + "103": "EลŸleลŸen kฤฑsaltma yok. YazdฤฑฤŸฤฑnฤฑz etiket olduฤŸu gibi kullanฤฑlฤฑr.", + "104": "ร–zellikler", + "105": "Atom Listesi", + "106": "Eklemek iรงin tablodaki elementlere tฤฑklayฤฑn.", + "107": "Sorguyu Temizle", + "108": "Uygula", + "109": "Kaldฤฑr", + "110": "Sorgu yok", + "111": "[M+Na]+", + "112": "ฤฐzotop deseni", + "113": "R Gruplarฤฑnฤฑ Sฤฑrala", + "114": "SMILES Kopyala", + "115": "Her yapฤฑnฤฑn SMILES'ฤฑ kopyalandฤฑ", + "116": "Si", + "117": "Herhangi Bir BaฤŸ", + "118": "Tekli veya ร‡ift", + "119": "Tekli veya Aromatik", + "120": "ร‡ift veya Aromatik", + "121": "Halka veya Zincir", + "122": "Halkada", + "123": "Zincirde", + "124": "Herhangi Bir Atom (A)", + "125": "Herhangi Bir Heteroatom (Q)", + "126": "Herhangi Bir Halojen (X)", + "127": "Herhangi Bir Metal (M)", + "128": "BaฤŸ Topolojisini Ayarla", + "129": "Sorgu BaฤŸฤฑ", + "130": "Atom Sorgusunu Ayarla", + "131": "Aromatik", + "132": "Alifatik", + "133": "DoymamฤฑลŸ", + "134": "ร‡izildiฤŸi Gibi Sรผbstitรผsyon", + "135": "ร‡izildiฤŸi Gibi Halka BaฤŸlarฤฑ", + "136": "Atom Sorgusunu Temizle", + "137": "Atom Sorgusu", + "138": "R Grubu Tanฤฑmฤฑ", + "139": "R grubu", + "140": "รœyeler", + "141": "Her รผyeyi bir baฤŸlanma noktasฤฑ (*) olan ayrฤฑ bir yapฤฑ olarak รงizin, ardฤฑndan bu pencereyi yeniden aรงฤฑn.", + "142": "OluลŸum", + "143": "Kalan H (sรผbstitรผe edilmemiลŸ konumlar hidrojendir)", + "144": "Varsa, o zaman", + "145": "Tanฤฑmฤฑ Kaldฤฑr", + "146": "Ajan", + "147": "KoลŸul", + "148": "Temizle", + "149": "Seรงili merkezleri bu gruba ekle", + "150": "Yeniden Denetle", + "151": "Denetleniyor...", + "152": "Dรผzelt", + "153": "Tuval รผzerinde seรง" +} From 18440aa0b7ba8c239b9c0902cfdb8e2b56c0ffbe Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:44 -0500 Subject: [PATCH 257/279] feat(i18n): translate the stereo, query and analysis strings into Indonesian (0.6.0) Adds part06 for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/id/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/id/part06.json diff --git a/frontend/src/i18n/locales/id/part06.json b/frontend/src/i18n/locales/id/part06.json new file mode 100644 index 00000000..1f2505eb --- /dev/null +++ b/frontend/src/i18n/locales/id/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Urutan Hill dengan muatan, singkatan diperluas", + "1": "Bobot atom standar (nilai konvensional CIAAW)", + "2": "Massa monoisotopik dari isotop paling melimpah pada setiap unsur", + "3": "Massa eksak dibagi muatan absolut, dikoreksi massa elektron", + "4": "Persen massa setiap unsur, dua desimal", + "5": "Kontribusi atom (Wildman dan Crippen 1999)", + "6": "Luas permukaan polar topologis, fragmen N dan O (Ertl 2000)", + "7": "Refraksi molar", + "8": "Donor ikatan hidrogen", + "9": "Penghitungan Lipinski: gugus N-H dan O-H", + "10": "Akseptor ikatan hidrogen", + "11": "Penghitungan Lipinski: atom N dan O", + "12": "Ikatan yang dapat berputar", + "13": "Ikatan tunggal non-cincin antara atom berat non-terminal, C-N amida dikecualikan", + "14": "Aturan lima Lipinski", + "15": "MW paling banyak 500, cLogP paling banyak 5, donor paling banyak 5, akseptor paling banyak 10", + "16": "HBD", + "17": "HBA", + "18": "Lolos (0 pelanggaran)", + "19": "Pilih satu atom atau lebih terlebih dahulu", + "20": "Pilih satu ikatan atau lebih terlebih dahulu", + "21": "Tidak ada hidrogen implisit untuk ditambahkan.", + "22": "Tidak ada hidrogen eksplisit untuk dihapus.", + "23": "Pilih singkatan seperti Ph atau OTs untuk diperluas.", + "24": "Pilih atom satu gugus dalam satu struktur untuk diringkas.", + "25": "Pilih gugus yang akan diringkas, tanpa atom tempat gugus itu terikat.", + "26": "Ringkas", + "27": "Pilih singkatan dari pustaka atau ketik label baru untuk atom yang dipilih.", + "28": "Atur Grup Stereo", + "29": "Hapus Grup Stereo", + "30": "Atur Daftar Atom", + "31": "Hapus Daftar Atom", + "32": "Atur Ikatan Kueri", + "33": "Hapus Kueri Ikatan", + "34": "Pilih atom yang membawa gugus R.", + "35": "1 titik pengikatan", + "36": "Definisikan Gugus R", + "37": "Hapus Definisi Gugus R", + "38": "Tetapkan Baji", + "39": "Baji sudah sesuai dengan pusat stereo.", + "40": "Struktur yang dipilih", + "41": "Setiap struktur di halaman ini", + "42": "Perbaiki Struktur", + "43": "Tidak ada struktur untuk dianalisis.", + "44": "Analisis disalin", + "45": "Tidak dapat menyalin ke papan klip", + "46": "Cari Substruktur", + "47": "SMARTS", + "48": "Gambar dahulu struktur yang akan dicari di halaman ini.", + "49": "hanya hasil pertama", + "50": "Tidak ada kecocokan di halaman ini.", + "51": "Gambar dahulu struktur dengan atom gugus R dan definisikan gugus R-nya.", + "52": "Tidak ada struktur untuk ditulis sebagai SMARTS.", + "53": "Penyimpanan berkas SMARTS hadir bersama format berkas pada 0.7.0; sebagai gantinya SMARTS disalin.", + "54": "Menggambar setiap hidrogen implisit dari atom yang dipilih (atau dari setiap struktur di halaman) sebagai atom H eksplisit yang ditempatkan oleh mesin, dalam satu langkah urungkan.", + "55": "Menghapus atom H eksplisit dari pilihan (atau halaman), mempertahankan hidrogen yang membawa stereo, isotop, muatan, nomor pemetaan, atau yang menjembatani dua atom.", + "56": "Mengganti atom singkatan yang dipilih (atau setiap singkatan di halaman) dengan struktur lengkapnya, ditata sepanjang ikatan pengikatan.", + "57": "Ringkas Singkatan...", + "58": "Meringkas gugus atom yang dipilih menjadi satu atom singkatan dengan label yang dipilih atau diketik pengguna.", + "59": "Menampilkan atau menyembunyikan label R, S, E, dan Z di samping pusat stereo dan ikatan rangkap stereo.", + "60": "Tampilkan Grup Stereo Tingkat Lanjut", + "61": "Menampilkan atau menyembunyikan label grup abs, and, dan or di samping pusat stereo selama label stereo aktif.", + "62": "Tampilkan Fitur Kueri", + "63": "Menampilkan atau menyembunyikan tanda daftar atom, ikatan kueri, dan gugus R di kanvas.", + "64": "Menempatkan pusat stereo yang dipilih dalam grup stereo tingkat lanjut: abs, and n, atau or n. Tanpa n, dibuat grup and atau or baru.", + "65": "abs, and, atau or", + "66": "Nomor grup untuk and dan or", + "67": "Absolut (abs)", + "68": "Grup AND Baru", + "69": "Grup OR Baru", + "70": "Grup Stereo...", + "71": "Daftar Atom...", + "72": "Mengubah atom yang dipilih menjadi kueri daftar atom atau daftar-bukan yang dipilih pada tabel periodik.", + "73": "Menjadikan ikatan yang dipilih ikatan kueri: any, single_or_double, single_or_aromatic, atau double_or_aromatic; hilangkan query untuk menghapus.", + "74": "Tipe ikatan kueri", + "75": "Definisikan Gugus R...", + "76": "Menjadikan atom yang dipilih label gugus R dan mendefinisikan anggotanya, kemunculan, H sisa, dan kondisi jika-maka.", + "77": "Membiarkan mesin memilih ikatan baji dan putus-putus yang menyatakan pusat stereo dari pilihan (atau halaman) tanpa ambiguitas.", + "78": "Mencantumkan masalah valensi, stereo, geometri, dan label dari pilihan (atau halaman) dalam panel yang barisnya memilih atom.", + "79": "Membuka panel analisis dengan sifat terhitung dari pilihan atau halaman.", + "80": "Menyalin rumus, massa, analisis unsur, dan sifat terhitung beserta metodenya sebagai teks.", + "81": "Cari Substruktur...", + "82": "Memilih setiap kecocokan atom yang dipilih (atau pola SMARTS) di struktur lain pada halaman.", + "83": "Daftarkan Gugus R...", + "84": "Mencantumkan setiap struktur yang diwakili kerangka Markush yang dipilih (atau yang pertama di halaman), dengan rumus dan SMILES, hingga 1000; daftarnya dapat disalin.", + "85": "Salin sebagai SMARTS", + "86": "Menyalin atom yang dipilih (atau setiap struktur di halaman) sebagai SMARTS, lengkap dengan daftar atom, atom generik, ikatan kueri, dan fitur kueri lainnya.", + "87": "Ekspor SMARTS...", + "88": "Menyimpan atom yang dipilih (atau setiap struktur di halaman) sebagai berkas SMARTS (.sma).", + "89": "Stereo Tingkat Lanjut", + "90": "Kueri", + "91": "Objek", + "92": "Pilih dahulu struktur atau teks yang akan diberi peran.", + "93": "Atur Peran Reaksi...", + "94": "Mengatur peran struktur atau teks yang dipilih pada langkah reaksi yang dipilih (reaktan, produk, agen, kondisi, atau tidak ada) dan menandai peran langkah itu sebagai diatur manual, dalam satu langkah urungkan. Tanpa role, membuka dialog yang mencantumkan anggota langkah dan pilihan.", + "95": "Peran yang diberikan ke objek; kosongkan untuk membuka dialog", + "96": "ID objek yang diubah; bawaan adalah pilihan", + "97": "Tidak dapat mengatur peran reaksi", + "98": "H sisa", + "99": "Singkatan", + "100": "Label", + "101": "Cari di pustaka", + "102": "Pustaka singkatan tidak dapat dimuat. Anda tetap dapat mengetik label.", + "103": "Tidak ada singkatan yang cocok. Label yang Anda ketik dipakai apa adanya.", + "104": "Sifat", + "105": "Daftar Atom", + "106": "Klik unsur di tabel untuk menambahkannya.", + "107": "Hapus Kueri", + "108": "Terapkan", + "109": "Hapus", + "110": "Tanpa kueri", + "111": "[M+Na]+", + "112": "Pola isotop", + "113": "Daftarkan Gugus R", + "114": "Salin SMILES", + "115": "SMILES setiap struktur disalin", + "116": "Si", + "117": "Ikatan Apa Pun", + "118": "Tunggal atau Rangkap Dua", + "119": "Tunggal atau Aromatik", + "120": "Rangkap Dua atau Aromatik", + "121": "Cincin atau Rantai", + "122": "Dalam Cincin", + "123": "Dalam Rantai", + "124": "Atom Apa Pun (A)", + "125": "Heteroatom Apa Pun (Q)", + "126": "Halogen Apa Pun (X)", + "127": "Logam Apa Pun (M)", + "128": "Atur Topologi Ikatan", + "129": "Ikatan Kueri", + "130": "Atur Kueri Atom", + "131": "Aromatik", + "132": "Alifatik", + "133": "Tak Jenuh", + "134": "Substitusi Sesuai Gambar", + "135": "Ikatan Cincin Sesuai Gambar", + "136": "Hapus Kueri Atom", + "137": "Kueri Atom", + "138": "Definisi Gugus R", + "139": "Gugus R", + "140": "Anggota", + "141": "Gambar setiap anggota sebagai struktur tersendiri dengan titik pengikatan (*), lalu buka dialog ini lagi.", + "142": "Kemunculan", + "143": "H sisa (posisi tanpa substitusi adalah hidrogen)", + "144": "Jika ada, maka", + "145": "Hapus Definisi", + "146": "Agen", + "147": "Kondisi", + "148": "Hapus", + "149": "Tambahkan pusat yang dipilih ke grup ini", + "150": "Periksa Lagi", + "151": "Memeriksa...", + "152": "Perbaiki", + "153": "Pilih di kanvas" +} From 934c144bc57118d59400ad98f7c406460a17e154 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:44 -0500 Subject: [PATCH 258/279] feat(i18n): translate the stereo, query and analysis strings into Vietnamese (0.6.0) Adds part06 for the new stereochemistry, query, R-group and analysis strings. --- frontend/src/i18n/locales/vi/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/vi/part06.json diff --git a/frontend/src/i18n/locales/vi/part06.json b/frontend/src/i18n/locales/vi/part06.json new file mode 100644 index 00000000..a975c79a --- /dev/null +++ b/frontend/src/i18n/locales/vi/part06.json @@ -0,0 +1,156 @@ +{ + "0": "Thแปฉ tแปฑ Hill kรจm ฤ‘iแป‡n tรญch, chแปฏ viแบฟt tแบฏt ฤ‘ฦฐแปฃc mแปŸ rแป™ng", + "1": "Khแป‘i lฦฐแปฃng nguyรชn tแปญ chuแบฉn (giรก trแป‹ quy ฦฐแป›c cแปงa CIAAW)", + "2": "Khแป‘i lฦฐแปฃng ฤ‘ฦกn ฤ‘แป“ng vแป‹ tแปซ ฤ‘แป“ng vแป‹ phong phรบ nhแบฅt cแปงa mแป—i nguyรชn tแป‘", + "3": "Khแป‘i lฦฐแปฃng chรญnh xรกc chia cho ฤ‘iแป‡n tรญch tuyแป‡t ฤ‘แป‘i, ฤ‘รฃ hiแป‡u chแป‰nh khแป‘i lฦฐแปฃng electron", + "4": "Phแบงn trฤƒm khแป‘i lฦฐแปฃng cแปงa mแป—i nguyรชn tแป‘, hai chแปฏ sแป‘ thแบญp phรขn", + "5": "ฤรณng gรณp cแปงa nguyรชn tแปญ (Wildman vร  Crippen 1999)", + "6": "Diแป‡n tรญch bแป mแบทt phรขn cแปฑc tรด-pรด, mแบฃnh N vร  O (Ertl 2000)", + "7": "ฤแป™ khรบc xแบก mol", + "8": "Chแบฅt cho liรชn kแบฟt hydro", + "9": "Cรกch ฤ‘แบฟm cแปงa Lipinski: nhรณm N-H vร  O-H", + "10": "Chแบฅt nhแบญn liรชn kแบฟt hydro", + "11": "Cรกch ฤ‘แบฟm cแปงa Lipinski: nguyรชn tแปญ N vร  O", + "12": "Liรชn kแบฟt quay ฤ‘ฦฐแปฃc", + "13": "Liรชn kแบฟt ฤ‘ฦกn ngoร i vรฒng giแปฏa cรกc nguyรชn tแปญ nแบทng khรดng แปŸ ฤ‘แบงu mแบกch, trแปซ C-N cแปงa amit", + "14": "Quy tแบฏc nฤƒm cแปงa Lipinski", + "15": "MW tแป‘i ฤ‘a 500, cLogP tแป‘i ฤ‘a 5, chแบฅt cho tแป‘i ฤ‘a 5, chแบฅt nhแบญn tแป‘i ฤ‘a 10", + "16": "HBD", + "17": "HBA", + "18": "ฤแบกt (0 vi phแบกm)", + "19": "Hรฃy chแปn mแป™t hoแบทc nhiแปu nguyรชn tแปญ trฦฐแป›c", + "20": "Hรฃy chแปn mแป™t hoแบทc nhiแปu liรชn kแบฟt trฦฐแป›c", + "21": "Khรดng cรณ hydro ngแบงm ฤ‘แป‹nh nร o ฤ‘แปƒ thรชm.", + "22": "Khรดng cรณ hydro tฦฐแปng minh nร o ฤ‘แปƒ xรณa.", + "23": "Chแปn mแป™t chแปฏ viแบฟt tแบฏt nhฦฐ Ph hoแบทc OTs ฤ‘แปƒ mแปŸ rแป™ng.", + "24": "Chแปn cรกc nguyรชn tแปญ cแปงa mแป™t nhรณm trong mแป™t cแบฅu trรบc ฤ‘แปƒ thu gแปn.", + "25": "Chแปn nhรณm cแบงn thu gแปn, khรดng gแป“m nguyรชn tแปญ mร  nรณ gแบฏn vร o.", + "26": "Thu gแปn", + "27": "Chแปn mแป™t chแปฏ viแบฟt tแบฏt trong thฦฐ viแป‡n hoแบทc nhแบญp nhรฃn mแป›i cho cรกc nguyรชn tแปญ ฤ‘รฃ chแปn.", + "28": "ฤแบทt nhรณm lแบญp thแปƒ", + "29": "Xรณa nhรณm lแบญp thแปƒ", + "30": "ฤแบทt danh sรกch nguyรชn tแปญ", + "31": "Xรณa danh sรกch nguyรชn tแปญ", + "32": "ฤแบทt liรชn kแบฟt truy vแบฅn", + "33": "Xรณa truy vแบฅn liรชn kแบฟt", + "34": "Chแปn nguyรชn tแปญ mang nhรณm R.", + "35": "1 ฤ‘iแปƒm gแบฏn", + "36": "ฤแป‹nh nghฤฉa nhรณm R", + "37": "Xรณa ฤ‘แป‹nh nghฤฉa nhรณm R", + "38": "Gรกn nรฉt nรชm", + "39": "Cรกc nรฉt nรชm ฤ‘รฃ khแป›p vแป›i cรกc tรขm lแบญp thแปƒ.", + "40": "Cรกc cแบฅu trรบc ฤ‘รฃ chแปn", + "41": "Mแปi cแบฅu trรบc trรชn trang nร y", + "42": "Sแปญa cแบฅu trรบc", + "43": "Khรดng cรณ cแบฅu trรบc nร o ฤ‘แปƒ phรขn tรญch.", + "44": "ฤรฃ sao chรฉp kแบฟt quแบฃ phรขn tรญch", + "45": "Khรดng thแปƒ sao chรฉp vร o bแบฃng nhแป› tแบกm", + "46": "Tรฌm cแบฅu trรบc con", + "47": "SMARTS", + "48": "Hรฃy vแบฝ cรกc cแบฅu trรบc cแบงn tรฌm trรชn trang nร y trฦฐแป›c.", + "49": "chแป‰ cรกc kแบฟt quแบฃ ฤ‘แบงu tiรชn", + "50": "Khรดng cรณ kแบฟt quแบฃ khแป›p trรชn trang nร y.", + "51": "Hรฃy vแบฝ mแป™t cแบฅu trรบc cรณ nguyรชn tแปญ nhรณm R vร  ฤ‘แป‹nh nghฤฉa cรกc nhรณm R cแปงa nรณ trฦฐแป›c.", + "52": "Khรดng cรณ cแบฅu trรบc nร o ฤ‘แปƒ ghi thร nh SMARTS.", + "53": "Chแปฉc nฤƒng lฦฐu tแป‡p SMARTS sแบฝ cรณ cรนng cรกc ฤ‘แป‹nh dแบกng tแป‡p แปŸ phiรชn bแบฃn 0.7.0; thay vร o ฤ‘รณ SMARTS ฤ‘รฃ ฤ‘ฦฐแปฃc sao chรฉp.", + "54": "Vแบฝ mแปi hydro ngแบงm ฤ‘แป‹nh cแปงa cรกc nguyรชn tแปญ ฤ‘รฃ chแปn (hoแบทc cแปงa mแปi cแบฅu trรบc trรชn trang) thร nh nguyรชn tแปญ H tฦฐแปng minh do bแป™ mรกy ฤ‘แบทt vแป‹ trรญ, trong mแป™t bฦฐแป›c hoร n tรกc.", + "55": "Xรณa cรกc nguyรชn tแปญ H tฦฐแปng minh khแปi vรนng chแปn (hoแบทc trang), giแปฏ lแบกi cรกc hydro mang thรดng tin lแบญp thแปƒ, ฤ‘แป“ng vแป‹, ฤ‘iแป‡n tรญch, sแป‘ รกnh xแบก hoแบทc bแบฏc cแบงu giแปฏa hai nguyรชn tแปญ.", + "56": "Thay cรกc nguyรชn tแปญ viแบฟt tแบฏt ฤ‘รฃ chแปn (hoแบทc mแปi chแปฏ viแบฟt tแบฏt trรชn trang) bแบฑng cแบฅu trรบc ฤ‘แบงy ฤ‘แปง, bแป‘ trรญ dแปc theo liรชn kแบฟt gแบฏn.", + "57": "Thu gแปn chแปฏ viแบฟt tแบฏt...", + "58": "Thu gแปn nhรณm nguyรชn tแปญ ฤ‘รฃ chแปn thร nh mแป™t nguyรชn tแปญ viแบฟt tแบฏt vแป›i nhรฃn do ngฦฐแปi dรนng chแปn hoแบทc nhแบญp.", + "59": "Hiแป‡n hoแบทc แบฉn cรกc nhรฃn R, S, E vร  Z bรชn cแบกnh cรกc tรขm lแบญp thแปƒ vร  liรชn kแบฟt ฤ‘รดi lแบญp thแปƒ.", + "60": "Hiแป‡n cรกc nhรณm lแบญp thแปƒ nรขng cao", + "61": "Hiแป‡n hoแบทc แบฉn cรกc nhรฃn nhรณm abs, and vร  or bรชn cแบกnh cรกc tรขm lแบญp thแปƒ khi nhรฃn lแบญp thแปƒ ฤ‘ang bแบญt.", + "62": "Hiแป‡n cรกc ฤ‘แบทc ฤ‘iแปƒm truy vแบฅn", + "63": "Hiแป‡n hoแบทc แบฉn cรกc dแบฅu danh sรกch nguyรชn tแปญ, liรชn kแบฟt truy vแบฅn vร  nhรณm R trรชn canvas.", + "64": "ฤฦฐa cรกc tรขm lแบญp thแปƒ ฤ‘รฃ chแปn vร o mแป™t nhรณm lแบญp thแปƒ nรขng cao: abs, and n hoแบทc or n. Khรดng cรณ n thรฌ tแบกo nhรณm and hoแบทc or mแป›i.", + "65": "abs, and hoแบทc or", + "66": "Sแป‘ nhรณm cho and vร  or", + "67": "Tuyแป‡t ฤ‘แป‘i (abs)", + "68": "Nhรณm AND mแป›i", + "69": "Nhรณm OR mแป›i", + "70": "Nhรณm lแบญp thแปƒ...", + "71": "Danh sรกch nguyรชn tแปญ...", + "72": "Biแบฟn cรกc nguyรชn tแปญ ฤ‘รฃ chแปn thร nh truy vแบฅn danh sรกch nguyรชn tแปญ hoแบทc danh sรกch loแบกi trแปซ, chแปn trรชn bแบฃng tuแบงn hoร n.", + "73": "Biแบฟn cรกc liรชn kแบฟt ฤ‘รฃ chแปn thร nh liรชn kแบฟt truy vแบฅn: any, single_or_double, single_or_aromatic hoแบทc double_or_aromatic; bแป query ฤ‘แปƒ xรณa.", + "74": "Loแบกi liรชn kแบฟt truy vแบฅn", + "75": "ฤแป‹nh nghฤฉa nhรณm R...", + "76": "Biแบฟn nguyรชn tแปญ ฤ‘รฃ chแปn thร nh nhรฃn nhรณm R vร  ฤ‘แป‹nh nghฤฉa cรกc thร nh viรชn, sแป‘ lแบงn xuแบฅt hiแป‡n, H cรฒn lแบกi vร  ฤ‘iแปu kiแป‡n nแบฟu-thรฌ cแปงa nรณ.", + "77": "ฤแปƒ bแป™ mรกy chแปn cรกc liรชn kแบฟt nรฉt nรชm vร  nรฉt ฤ‘แปฉt biแปƒu diแป…n rรต rร ng cรกc tรขm lแบญp thแปƒ cแปงa vรนng chแปn (hoแบทc trang).", + "78": "Liแป‡t kรช cรกc vแบฅn ฤ‘แป vแป hรณa trแป‹, lแบญp thแปƒ, hรฌnh hแปc vร  nhรฃn cแปงa vรนng chแปn (hoแบทc trang) trong mแป™t bแบฃng mร  cรกc hร ng chแปn nguyรชn tแปญ.", + "79": "MแปŸ bแบฃng phรขn tรญch vแป›i cรกc tรญnh chแบฅt tรญnh toรกn cแปงa vรนng chแปn hoแบทc trang.", + "80": "Sao chรฉp cรดng thแปฉc, khแป‘i lฦฐแปฃng, phรขn tรญch nguyรชn tแป‘ vร  cรกc tรญnh chแบฅt tรญnh toรกn cรนng phฦฐฦกng phรกp cแปงa chรบng dฦฐแป›i dแบกng vฤƒn bแบฃn.", + "81": "Tรฌm cแบฅu trรบc con...", + "82": "Chแปn mแปi kแบฟt quแบฃ khแป›p cแปงa cรกc nguyรชn tแปญ ฤ‘รฃ chแปn (hoแบทc cแปงa mแป™t mแบซu SMARTS) trong cรกc cแบฅu trรบc khรกc trรชn trang.", + "83": "Liแป‡t kรช nhรณm R...", + "84": "Liแป‡t kรช mแปi cแบฅu trรบc mร  khung Markush ฤ‘รฃ chแปn (hoแบทc khung ฤ‘แบงu tiรชn trรชn trang) ฤ‘แบกi diแป‡n, kรจm cรดng thแปฉc vร  SMILES, tแป‘i ฤ‘a 1000; cรณ thแปƒ sao chรฉp danh sรกch.", + "85": "Sao chรฉp dฦฐแป›i dแบกng SMARTS", + "86": "Sao chรฉp cรกc nguyรชn tแปญ ฤ‘รฃ chแปn (hoแบทc mแปi cแบฅu trรบc trรชn trang) dฦฐแป›i dแบกng SMARTS, kรจm danh sรกch nguyรชn tแปญ, nguyรชn tแปญ tแป•ng quรกt, liรชn kแบฟt truy vแบฅn vร  cรกc ฤ‘แบทc ฤ‘iแปƒm truy vแบฅn khรกc.", + "87": "Xuแบฅt SMARTS...", + "88": "Lฦฐu cรกc nguyรชn tแปญ ฤ‘รฃ chแปn (hoแบทc mแปi cแบฅu trรบc trรชn trang) thร nh tแป‡p SMARTS (.sma).", + "89": "Lแบญp thแปƒ nรขng cao", + "90": "Truy vแบฅn", + "91": "ฤแป‘i tฦฐแปฃng", + "92": "Hรฃy chแปn cรกc cแบฅu trรบc hoแบทc vฤƒn bแบฃn cแบงn gรกn vai trรฒ trฦฐแป›c.", + "93": "ฤแบทt vai trรฒ phแบฃn แปฉng...", + "94": "ฤแบทt vai trรฒ cแปงa cรกc cแบฅu trรบc hoแบทc vฤƒn bแบฃn ฤ‘รฃ chแปn trong bฦฐแป›c phแบฃn แปฉng ฤ‘รฃ chแปn (chแบฅt phแบฃn แปฉng, sแบฃn phแบฉm, tรกc nhรขn, ฤ‘iแปu kiแป‡n hoแบทc khรดng cรณ) vร  ฤ‘รกnh dแบฅu cรกc vai trรฒ cแปงa bฦฐแป›c lร  ฤ‘แบทt thแปง cรดng, trong mแป™t bฦฐแป›c hoร n tรกc. Nแบฟu khรดng cรณ role, mแปŸ hแป™p thoแบกi liแป‡t kรช cรกc thร nh viรชn cแปงa bฦฐแป›c vร  vรนng chแปn.", + "95": "Vai trรฒ gรกn cho cรกc ฤ‘แป‘i tฦฐแปฃng; bแป trแป‘ng ฤ‘แปƒ mแปŸ hแป™p thoแบกi", + "96": "Mรฃ ฤ‘แป‘i tฦฐแปฃng cแบงn ฤ‘แป•i; mแบทc ฤ‘แป‹nh lร  vรนng chแปn", + "97": "Khรดng thแปƒ ฤ‘แบทt vai trรฒ phแบฃn แปฉng", + "98": "H cรฒn lแบกi", + "99": "Chแปฏ viแบฟt tแบฏt", + "100": "Nhรฃn", + "101": "Tรฌm trong thฦฐ viแป‡n", + "102": "Khรดng thแปƒ tแบฃi thฦฐ viแป‡n chแปฏ viแบฟt tแบฏt. Bแบกn vแบซn cรณ thแปƒ nhแบญp nhรฃn.", + "103": "Khรดng cรณ chแปฏ viแบฟt tแบฏt nร o khแป›p. Nhรฃn bแบกn nhแบญp ฤ‘ฦฐแปฃc dรนng nguyรชn nhฦฐ vแบญy.", + "104": "Tรญnh chแบฅt", + "105": "Danh sรกch nguyรชn tแปญ", + "106": "Nhแบฅp vร o cรกc nguyรชn tแป‘ trong bแบฃng ฤ‘แปƒ thรชm chรบng.", + "107": "Xรณa truy vแบฅn", + "108": "รp dแปฅng", + "109": "Xรณa bแป", + "110": "Khรดng cรณ truy vแบฅn", + "111": "[M+Na]+", + "112": "Mแบซu ฤ‘แป“ng vแป‹", + "113": "Liแป‡t kรช nhรณm R", + "114": "Sao chรฉp SMILES", + "115": "ฤรฃ sao chรฉp SMILES cแปงa mแปi cแบฅu trรบc", + "116": "Si", + "117": "Liรชn kแบฟt bแบฅt kแปณ", + "118": "ฤฦกn hoแบทc ฤ‘รดi", + "119": "ฤฦกn hoแบทc thฦกm", + "120": "ฤรดi hoแบทc thฦกm", + "121": "Vรฒng hoแบทc mแบกch", + "122": "Trong vรฒng", + "123": "Trong mแบกch", + "124": "Nguyรชn tแปญ bแบฅt kแปณ (A)", + "125": "Dแป‹ nguyรชn tแปญ bแบฅt kแปณ (Q)", + "126": "Halogen bแบฅt kแปณ (X)", + "127": "Kim loแบกi bแบฅt kแปณ (M)", + "128": "ฤแบทt tรด-pรด liรชn kแบฟt", + "129": "Liรชn kแบฟt truy vแบฅn", + "130": "ฤแบทt truy vแบฅn nguyรชn tแปญ", + "131": "Thฦกm", + "132": "Mแบกch hแปŸ", + "133": "Khรดng no", + "134": "Thแบฟ nhฦฐ ฤ‘รฃ vแบฝ", + "135": "Liรชn kแบฟt vรฒng nhฦฐ ฤ‘รฃ vแบฝ", + "136": "Xรณa truy vแบฅn nguyรชn tแปญ", + "137": "Truy vแบฅn nguyรชn tแปญ", + "138": "ฤแป‹nh nghฤฉa nhรณm R", + "139": "Nhรณm R", + "140": "Thร nh viรชn", + "141": "Vแบฝ tแปซng thร nh viรชn thร nh mแป™t cแบฅu trรบc riรชng cรณ ฤ‘iแปƒm gแบฏn (*), rแป“i mแปŸ lแบกi hแป™p thoแบกi nร y.", + "142": "Sแป‘ lแบงn xuแบฅt hiแป‡n", + "143": "H cรฒn lแบกi (cรกc vแป‹ trรญ khรดng ฤ‘ฦฐแปฃc thแบฟ lร  hydro)", + "144": "Nแบฟu cรณ, thรฌ", + "145": "Xรณa ฤ‘แป‹nh nghฤฉa", + "146": "Tรกc nhรขn", + "147": "ฤiแปu kiแป‡n", + "148": "Xรณa", + "149": "Thรชm cรกc tรขm ฤ‘รฃ chแปn vร o nhรณm nร y", + "150": "Kiแปƒm tra lแบกi", + "151": "ฤang kiแปƒm tra...", + "152": "Sแปญa", + "153": "Chแปn trรชn canvas" +} From 7ce4a5ffd089470190d42afce5d37c0fe7373b1f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:32 -0500 Subject: [PATCH 259/279] feat(i18n): translate the stereo, query and analysis strings into Simplified Chinese (0.6.0) Adds the 154 strings of part06 for zh-Hans. --- frontend/src/i18n/locales/zh-Hans/part06.json | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/zh-Hans/part06.json diff --git a/frontend/src/i18n/locales/zh-Hans/part06.json b/frontend/src/i18n/locales/zh-Hans/part06.json new file mode 100644 index 00000000..ed51fe68 --- /dev/null +++ b/frontend/src/i18n/locales/zh-Hans/part06.json @@ -0,0 +1,156 @@ +{ + "0": "ๅธฆ็”ต่ท็š„ Hill ้กบๅบ๏ผŒ็ผฉๅ†™ๅทฒๅฑ•ๅผ€", + "1": "ๆ ‡ๅ‡†ๅŽŸๅญ้‡๏ผˆCIAAW ๅธธ่ง„ๅ€ผ๏ผ‰", + "2": "ๆŒ‰ๅ„ๅ…ƒ็ด ไธฐๅบฆๆœ€้ซ˜็š„ๅŒไฝ็ด ่ฎก็ฎ—็š„ๅ•ๅŒไฝ็ด ่ดจ้‡", + "3": "็ฒพ็กฎ่ดจ้‡้™คไปฅ็”ต่ท็ปๅฏนๅ€ผ๏ผŒๅทฒๆ กๆญฃ็”ตๅญ่ดจ้‡", + "4": "ๅ„ๅ…ƒ็ด ็š„่ดจ้‡็™พๅˆ†ๆฏ”๏ผŒไฟ็•™ไธคไฝๅฐๆ•ฐ", + "5": "ๅŽŸๅญ่ดก็Œฎ๏ผˆWildman and Crippen 1999๏ผ‰", + "6": "ๆ‹“ๆ‰‘ๆžๆ€ง่กจ้ข็งฏ๏ผŒN ๅ’Œ O ็‰‡ๆฎต๏ผˆErtl 2000๏ผ‰", + "7": "ๆ‘ฉๅฐ”ๆŠ˜ๅฐ„็އ", + "8": "ๆฐข้”ฎไพ›ไฝ“", + "9": "Lipinski ่ฎกๆ•ฐ๏ผšN-H ๅ’Œ O-H ๅŸบๅ›ข", + "10": "ๆฐข้”ฎๅ—ไฝ“", + "11": "Lipinski ่ฎกๆ•ฐ๏ผšN ๅ’Œ O ๅŽŸๅญ", + "12": "ๅฏๆ—‹่ฝฌ้”ฎ", + "13": "้žๆœซ็ซฏ้‡ๅŽŸๅญไน‹้—ด็š„้ž็Žฏๅ•้”ฎ๏ผŒไธๅซ้…ฐ่ƒบ C-N ้”ฎ", + "14": "Lipinski ไบ”่ง„ๅˆ™", + "15": "MW ไธ่ถ…่ฟ‡ 500๏ผŒcLogP ไธ่ถ…่ฟ‡ 5๏ผŒไพ›ไฝ“ไธ่ถ…่ฟ‡ 5๏ผŒๅ—ไฝ“ไธ่ถ…่ฟ‡ 10", + "16": "HBD", + "17": "HBA", + "18": "้€š่ฟ‡๏ผˆ0 ้กน่ฟๅ๏ผ‰", + "19": "่ฏทๅ…ˆ้€‰ๆ‹ฉไธ€ไธชๆˆ–ๅคšไธชๅŽŸๅญ", + "20": "่ฏทๅ…ˆ้€‰ๆ‹ฉไธ€ไธชๆˆ–ๅคšไธช้”ฎ", + "21": "ๆฒกๆœ‰ๅฏๆทปๅŠ ็š„้šๅผๆฐขใ€‚", + "22": "ๆฒกๆœ‰ๅฏ็งป้™ค็š„ๆ˜พๅผๆฐขใ€‚", + "23": "่ฏท้€‰ๆ‹ฉ Ph ๆˆ– OTs ็ญ‰็ผฉๅ†™ไปฅๅฑ•ๅผ€ใ€‚", + "24": "่ฏท้€‰ๆ‹ฉๆŸไธ€็ป“ๆž„ไธญไธ€ไธชๅŸบๅ›ข็š„ๅŽŸๅญไปฅๆ”ถ็ผฉใ€‚", + "25": "่ฏท้€‰ๆ‹ฉ่ฆๆ”ถ็ผฉ็š„ๅŸบๅ›ข๏ผŒไธๅŒ…ๆ‹ฌไธŽๅ…ถ็›ธ่ฟž็š„ๅŽŸๅญใ€‚", + "26": "ๆ”ถ็ผฉ", + "27": "ไธบๆ‰€้€‰ๅŽŸๅญ้€‰ๅ–ๅบ“ไธญ็š„็ผฉๅ†™๏ผŒๆˆ–่พ“ๅ…ฅๆ–ฐ็š„ๆ ‡็ญพใ€‚", + "28": "่ฎพ็ฝฎ็ซ‹ไฝ“็ป„", + "29": "ๆธ…้™ค็ซ‹ไฝ“็ป„", + "30": "่ฎพ็ฝฎๅŽŸๅญๅˆ—่กจ", + "31": "ๆธ…้™คๅŽŸๅญๅˆ—่กจ", + "32": "่ฎพ็ฝฎๆŸฅ่ฏข้”ฎ", + "33": "ๆธ…้™ค้”ฎๆŸฅ่ฏข", + "34": "่ฏท้€‰ๆ‹ฉๅธฆๆœ‰ R ๅŸบๅ›ข็š„ๅŽŸๅญใ€‚", + "35": "1 ไธช่ฟžๆŽฅ็‚น", + "36": "ๅฎšไน‰ R ๅŸบๅ›ข", + "37": "็งป้™ค R ๅŸบๅ›ขๅฎšไน‰", + "38": "ๆŒ‡ๅฎšๆฅ”ๅฝข้”ฎ", + "39": "ๆฅ”ๅฝข้”ฎๅทฒไธŽ็ซ‹ไฝ“ไธญๅฟƒไธ€่‡ดใ€‚", + "40": "ๆ‰€้€‰็ป“ๆž„", + "41": "ๆญค้กต้ขไธŠ็š„ๆฏไธช็ป“ๆž„", + "42": "ไฟฎๅค็ป“ๆž„", + "43": "ๆฒกๆœ‰ๅฏๅˆ†ๆž็š„็ป“ๆž„ใ€‚", + "44": "ๅˆ†ๆž็ป“ๆžœๅทฒๅคๅˆถ", + "45": "ๆ— ๆณ•ๅคๅˆถๅˆฐๅ‰ช่ดดๆฟ", + "46": "ๆŸฅๆ‰พๅญ็ป“ๆž„", + "47": "SMARTS", + "48": "่ฏทๅ…ˆ็ป˜ๅˆถ่ฆๅœจๆญค้กต้ขไธŠๆœ็ดข็š„็ป“ๆž„ใ€‚", + "49": "ไป…ๆ˜พ็คบๅ‰ๅ‡ ้กน็ป“ๆžœ", + "50": "ๆญค้กต้ขไธŠๆฒกๆœ‰ๅŒน้…้กนใ€‚", + "51": "่ฏทๅ…ˆ็ป˜ๅˆถๅธฆๆœ‰ R ๅŸบๅ›ขๅŽŸๅญ็š„็ป“ๆž„ๅนถๅฎšไน‰ๅ…ถ R ๅŸบๅ›ขใ€‚", + "52": "ๆฒกๆœ‰ๅฏๅ†™ๆˆ SMARTS ็š„็ป“ๆž„ใ€‚", + "53": "ไฟๅญ˜ SMARTS ๆ–‡ไปถๅฐ†้š 0.7.0 ไธญ็š„ๆ–‡ไปถๆ ผๅผไธ€ๅŒๆŽจๅ‡บ๏ผ›ๅทฒๆ”นไธบๅคๅˆถ SMARTSใ€‚", + "54": "ๅฐ†ๆ‰€้€‰ๅŽŸๅญ๏ผˆๆˆ–้กต้ขไธŠๆฏไธช็ป“ๆž„๏ผ‰็š„ๆฏไธช้šๅผๆฐข็ป˜ๅˆถไธบ็”ฑๅผ•ๆ“Žๆ”พ็ฝฎ็š„ๆ˜พๅผ H ๅŽŸๅญ๏ผŒไฝœไธบไธ€ไธชๆ’ค้”€ๆญฅ้ชคใ€‚", + "55": "ไปŽๆ‰€้€‰ๅ†…ๅฎน๏ผˆๆˆ–้กต้ข๏ผ‰ไธญ็งป้™คๆ˜พๅผ H ๅŽŸๅญ๏ผŒไฝ†ไฟ็•™ๅธฆๆœ‰็ซ‹ไฝ“ไฟกๆฏใ€ๅŒไฝ็ด ใ€็”ต่ทใ€ๆ˜ ๅฐ„็ผ–ๅทๆˆ–ๆกฅๆŽฅไธคไธชๅŽŸๅญ็š„ๆฐขใ€‚", + "56": "ๅฐ†ๆ‰€้€‰็ผฉๅ†™ๅŽŸๅญ๏ผˆๆˆ–้กต้ขไธŠ็š„ๆฏไธช็ผฉๅ†™๏ผ‰ๆ›ฟๆขไธบๅ…ถๅฎŒๆ•ด็ป“ๆž„๏ผŒๅนถๆฒฟ่ฟžๆŽฅ้”ฎๆŽ’ๅธƒใ€‚", + "57": "ๆ”ถ็ผฉ็ผฉๅ†™...", + "58": "ๅฐ†ๆ‰€้€‰ๅŽŸๅญๅŸบๅ›ขๆ”ถ็ผฉไธบไธ€ไธช็ผฉๅ†™ๅŽŸๅญ๏ผŒๆ ‡็ญพ็”ฑ็”จๆˆท้€‰ๅ–ๆˆ–่พ“ๅ…ฅใ€‚", + "59": "ๆ˜พ็คบๆˆ–้š่—็ซ‹ไฝ“ไธญๅฟƒๅ’Œ็ซ‹ไฝ“ๅŒ้”ฎๆ—็š„ Rใ€Sใ€Eใ€Z ๆ ‡่ฎฐใ€‚", + "60": "ๆ˜พ็คบๅขžๅผบ็ซ‹ไฝ“็ป„", + "61": "ๅœจ็ซ‹ไฝ“ๆ ‡่ฎฐๅผ€ๅฏๆ—ถ๏ผŒๆ˜พ็คบๆˆ–้š่—็ซ‹ไฝ“ไธญๅฟƒๆ—็š„ absใ€and ๅ’Œ or ็ป„ๆ ‡่ฎฐใ€‚", + "62": "ๆ˜พ็คบๆŸฅ่ฏข็‰นๅพ", + "63": "ๆ˜พ็คบๆˆ–้š่—็”ปๅธƒไธŠ็š„ๅŽŸๅญๅˆ—่กจใ€ๆŸฅ่ฏข้”ฎๅ’Œ R ๅŸบๅ›ขๆ ‡่ฎฐใ€‚", + "64": "ๅฐ†ๆ‰€้€‰็ซ‹ไฝ“ไธญๅฟƒๆ”พๅ…ฅๅขžๅผบ็ซ‹ไฝ“็ป„๏ผšabsใ€and n ๆˆ– or nใ€‚ไธๅธฆ n ๆ—ถไผšๆ–ฐๅปบ and ๆˆ– or ็ป„ใ€‚", + "65": "absใ€and ๆˆ– or", + "66": "and ๅ’Œ or ็š„็ป„็ผ–ๅท", + "67": "็ปๅฏน๏ผˆabs๏ผ‰", + "68": "ๆ–ฐๅปบ AND ็ป„", + "69": "ๆ–ฐๅปบ OR ็ป„", + "70": "็ซ‹ไฝ“็ป„...", + "71": "ๅŽŸๅญๅˆ—่กจ...", + "72": "ๅฐ†ๆ‰€้€‰ๅŽŸๅญๅ˜ไธบๅœจๅ…ƒ็ด ๅ‘จๆœŸ่กจไธŠ้€‰ๅ–็š„ๅŽŸๅญๅˆ—่กจๆˆ–้žๅˆ—่กจๆŸฅ่ฏขใ€‚", + "73": "ๅฐ†ๆ‰€้€‰้”ฎ่ฎพไธบๆŸฅ่ฏข้”ฎ๏ผšanyใ€single_or_doubleใ€single_or_aromatic ๆˆ– double_or_aromatic๏ผ›็œ็•ฅ query ๅˆ™ๆธ…้™คใ€‚", + "74": "ๆŸฅ่ฏข้”ฎ็ฑปๅž‹", + "75": "ๅฎšไน‰ R ๅŸบๅ›ข...", + "76": "ๅฐ†ๆ‰€้€‰ๅŽŸๅญ่ฎพไธบ R ๅŸบๅ›ขๆ ‡็ญพ๏ผŒๅนถๅฎšไน‰ๅ…ถๆˆๅ‘˜ใ€ๅ‡บ็Žฐๆฌกๆ•ฐใ€ๅ…ถไฝ™ H ๅ’Œ if-then ๆกไปถใ€‚", + "77": "่ฎฉๅผ•ๆ“Ž้€‰ๆ‹ฉ่ƒฝๆ˜Ž็กฎ่กจ็คบๆ‰€้€‰ๅ†…ๅฎน๏ผˆๆˆ–้กต้ข๏ผ‰็ซ‹ไฝ“ไธญๅฟƒ็š„ๆฅ”ๅฝข้”ฎๅ’Œ่™š็บฟ้”ฎใ€‚", + "78": "ๅœจ้ขๆฟไธญๅˆ—ๅ‡บๆ‰€้€‰ๅ†…ๅฎน๏ผˆๆˆ–้กต้ข๏ผ‰็š„ไปทๆ€ใ€็ซ‹ไฝ“ใ€ๅ‡ ไฝ•ๅ’Œๆ ‡็ญพ้—ฎ้ข˜๏ผŒ็‚นๅ‡ป่กŒๅณๅฏ้€‰ไธญ็›ธๅบ”ๅŽŸๅญใ€‚", + "79": "ๆ‰“ๅผ€ๅˆ†ๆž้ขๆฟ๏ผŒๆ˜พ็คบๆ‰€้€‰ๅ†…ๅฎนๆˆ–้กต้ข็š„่ฎก็ฎ—ๆ€ง่ดจใ€‚", + "80": "ๅฐ†ๅˆ†ๅญๅผใ€่ดจ้‡ใ€ๅ…ƒ็ด ๅˆ†ๆžๅ’Œ่ฎก็ฎ—ๆ€ง่ดจๅŠๅ…ถๆ–นๆณ•ไปฅๆ–‡ๆœฌๅฝขๅผๅคๅˆถใ€‚", + "81": "ๆŸฅๆ‰พๅญ็ป“ๆž„...", + "82": "ๅœจ้กต้ขไธŠ็š„ๅ…ถไป–็ป“ๆž„ไธญ๏ผŒ้€‰ไธญๆ‰€้€‰ๅŽŸๅญ๏ผˆๆˆ– SMARTS ๆจกๅผ๏ผ‰็š„ๆฏไธชๅŒน้…้กนใ€‚", + "83": "ๆžšไธพ R ๅŸบๅ›ข...", + "84": "ๅˆ—ๅ‡บๆ‰€้€‰ Markush ๆฏๆ ธ๏ผˆๆˆ–้กต้ขไธŠ็ฌฌไธ€ไธช๏ผ‰ๆ‰€ไปฃ่กจ็š„ๆฏไธช็ป“ๆž„๏ผŒๅซๅˆ†ๅญๅผๅ’Œ SMILES๏ผŒๆœ€ๅคš 1000 ไธช๏ผ›ๅˆ—่กจๅฏๅคๅˆถใ€‚", + "85": "ๅคๅˆถไธบ SMARTS", + "86": "ๅฐ†ๆ‰€้€‰ๅŽŸๅญ๏ผˆๆˆ–้กต้ขไธŠๆฏไธช็ป“ๆž„๏ผ‰ๅคๅˆถไธบ SMARTS๏ผŒๅŒ…ๅซๅŽŸๅญๅˆ—่กจใ€้€š็”จๅŽŸๅญใ€ๆŸฅ่ฏข้”ฎๅŠๅ…ถไป–ๆŸฅ่ฏข็‰นๅพใ€‚", + "87": "ๅฏผๅ‡บ SMARTS...", + "88": "ๅฐ†ๆ‰€้€‰ๅŽŸๅญ๏ผˆๆˆ–้กต้ขไธŠๆฏไธช็ป“ๆž„๏ผ‰ไฟๅญ˜ไธบ SMARTS ๆ–‡ไปถ๏ผˆ.sma๏ผ‰ใ€‚", + "89": "ๅขžๅผบ็ซ‹ไฝ“", + "90": "ๆŸฅ่ฏข", + "91": "ๅฏน่ฑก", + "92": "่ฏทๅ…ˆ้€‰ๆ‹ฉ่ฆๆŒ‡ๅฎš่ง’่‰ฒ็š„็ป“ๆž„ๆˆ–ๆ–‡ๆœฌใ€‚", + "93": "่ฎพ็ฝฎๅๅบ”่ง’่‰ฒ...", + "94": "่ฎพ็ฝฎๆ‰€้€‰ๅๅบ”ๆญฅ้ชคไธญๆ‰€้€‰็ป“ๆž„ๆˆ–ๆ–‡ๆœฌ็š„่ง’่‰ฒ๏ผˆๅๅบ”็‰ฉใ€ไบง็‰ฉใ€่ฏ•ๅ‰‚ใ€ๆกไปถๆˆ–ๆ— ๏ผ‰๏ผŒๅนถๅฐ†่ฏฅๆญฅ้ชค็š„่ง’่‰ฒๆ ‡่ฎฐไธบๆ‰‹ๅŠจ่ฎพ็ฝฎ๏ผŒไฝœไธบไธ€ไธชๆ’ค้”€ๆญฅ้ชคใ€‚ไธๅธฆ role ๆ—ถไผšๆ‰“ๅผ€ๅฏน่ฏๆก†๏ผŒๅˆ—ๅ‡บ่ฏฅๆญฅ้ชค็š„ๆˆๅ‘˜ๅ’Œๆ‰€้€‰ๅ†…ๅฎนใ€‚", + "95": "่ฆ่ต‹ไบˆๅฏน่ฑก็š„่ง’่‰ฒ๏ผ›็œ็•ฅๅˆ™ๆ‰“ๅผ€ๅฏน่ฏๆก†", + "96": "่ฆๆ›ดๆ”น็š„ๅฏน่ฑก id๏ผ›้ป˜่ฎคไธบๆ‰€้€‰ๅ†…ๅฎน", + "97": "ๆ— ๆณ•่ฎพ็ฝฎๅๅบ”่ง’่‰ฒ", + "98": "ๅ…ถไฝ™ H", + "99": "็ผฉๅ†™", + "100": "ๆ ‡็ญพ", + "101": "ๆœ็ดขๅบ“", + "102": "ๆ— ๆณ•ๅŠ ่ฝฝ็ผฉๅ†™ๅบ“ใ€‚ๆ‚จไปๅฏ่พ“ๅ…ฅๆ ‡็ญพใ€‚", + "103": "ๆฒกๆœ‰ๅŒน้…็š„็ผฉๅ†™ใ€‚ๅฐ†ๆŒ‰ๅŽŸๆ ทไฝฟ็”จๆ‚จ่พ“ๅ…ฅ็š„ๆ ‡็ญพใ€‚", + "104": "ๆ€ง่ดจ", + "105": "ๅŽŸๅญๅˆ—่กจ", + "106": "็‚นๅ‡ป่กจไธญ็š„ๅ…ƒ็ด ๅณๅฏๆทปๅŠ ใ€‚", + "107": "ๆธ…้™คๆŸฅ่ฏข", + "108": "ๅบ”็”จ", + "109": "็งป้™ค", + "110": "ๆ— ๆŸฅ่ฏข", + "111": "[M+Na]+", + "112": "ๅŒไฝ็ด ๅˆ†ๅธƒ", + "113": "ๆžšไธพ R ๅŸบๅ›ข", + "114": "ๅคๅˆถ SMILES", + "115": "ๅทฒๅคๅˆถๆฏไธช็ป“ๆž„็š„ SMILES", + "116": "Si", + "117": "ไปปๆ„้”ฎ", + "118": "ๅ•้”ฎๆˆ–ๅŒ้”ฎ", + "119": "ๅ•้”ฎๆˆ–่Šณ้ฆ™้”ฎ", + "120": "ๅŒ้”ฎๆˆ–่Šณ้ฆ™้”ฎ", + "121": "็Žฏๆˆ–้“พ", + "122": "ๅœจ็Žฏไธญ", + "123": "ๅœจ้“พไธญ", + "124": "ไปปๆ„ๅŽŸๅญ๏ผˆA๏ผ‰", + "125": "ไปปๆ„ๆ‚ๅŽŸๅญ๏ผˆQ๏ผ‰", + "126": "ไปปๆ„ๅค็ด ๏ผˆX๏ผ‰", + "127": "ไปปๆ„้‡‘ๅฑž๏ผˆM๏ผ‰", + "128": "่ฎพ็ฝฎ้”ฎๆ‹“ๆ‰‘", + "129": "ๆŸฅ่ฏข้”ฎ", + "130": "่ฎพ็ฝฎๅŽŸๅญๆŸฅ่ฏข", + "131": "่Šณ้ฆ™", + "132": "่„‚่‚ช", + "133": "ไธ้ฅฑๅ’Œ", + "134": "ๆŒ‰ๆ‰€็ป˜ๅ–ไปฃ", + "135": "ๆŒ‰ๆ‰€็ป˜็Žฏ้”ฎ", + "136": "ๆธ…้™คๅŽŸๅญๆŸฅ่ฏข", + "137": "ๅŽŸๅญๆŸฅ่ฏข", + "138": "R ๅŸบๅ›ขๅฎšไน‰", + "139": "R ๅŸบๅ›ข", + "140": "ๆˆๅ‘˜", + "141": "ๅฐ†ๆฏไธชๆˆๅ‘˜็ป˜ๅˆถไธบๅธฆ่ฟžๆŽฅ็‚น๏ผˆ*๏ผ‰็š„็‹ฌ็ซ‹็ป“ๆž„๏ผŒ็„ถๅŽๅ†ๆฌกๆ‰“ๅผ€ๆญคๅฏน่ฏๆก†ใ€‚", + "142": "ๅ‡บ็Žฐๆฌกๆ•ฐ", + "143": "ๅ…ถไฝ™ H๏ผˆๆœชๅ–ไปฃ็š„ไฝ็ฝฎไธบๆฐข๏ผ‰", + "144": "่‹ฅๅญ˜ๅœจ๏ผŒๅˆ™", + "145": "็งป้™คๅฎšไน‰", + "146": "่ฏ•ๅ‰‚", + "147": "ๆกไปถ", + "148": "ๆธ…้™ค", + "149": "ๅฐ†ๆ‰€้€‰็ซ‹ไฝ“ไธญๅฟƒๅŠ ๅ…ฅๆญค็ป„", + "150": "้‡ๆ–ฐๆฃ€ๆŸฅ", + "151": "ๆญฃๅœจๆฃ€ๆŸฅ...", + "152": "ไฟฎๅค", + "153": "ๅœจ็”ปๅธƒไธŠ้€‰ไธญ" +} From d5160202237d419d906be8bdf05d578238b1dd46 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:32 -0500 Subject: [PATCH 260/279] feat(i18n): translate the stereo, query and analysis strings into Traditional Chinese (0.6.0) Adds the 154 strings of part06 for zh-Hant. --- frontend/src/i18n/locales/zh-Hant/part06.json | 156 ++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/zh-Hant/part06.json diff --git a/frontend/src/i18n/locales/zh-Hant/part06.json b/frontend/src/i18n/locales/zh-Hant/part06.json new file mode 100644 index 00000000..1798f295 --- /dev/null +++ b/frontend/src/i18n/locales/zh-Hant/part06.json @@ -0,0 +1,156 @@ +{ + "0": "ๅธถ้›ป่ท็š„ Hill ้ †ๅบ๏ผŒ็ธฎๅฏซๅทฒๅฑ•้–‹", + "1": "ๆจ™ๆบ–ๅŽŸๅญ้‡๏ผˆCIAAW ๅธธ่ฆๅ€ผ๏ผ‰", + "2": "ไพๅ„ๅ…ƒ็ด ่ฑๅบฆๆœ€้ซ˜็š„ๅŒไฝ็ด ่จˆ็ฎ—็š„ๅ–ฎไธ€ๅŒไฝ็ด ่ณช้‡", + "3": "็ฒพ็ขบ่ณช้‡้™คไปฅ้›ป่ท็ต•ๅฐๅ€ผ๏ผŒๅทฒๆ กๆญฃ้›ปๅญ่ณช้‡", + "4": "ๅ„ๅ…ƒ็ด ็š„่ณช้‡็™พๅˆ†ๆฏ”๏ผŒไฟ็•™ๅ…ฉไฝๅฐๆ•ธ", + "5": "ๅŽŸๅญ่ฒข็ป๏ผˆWildman and Crippen 1999๏ผ‰", + "6": "ๆ‹“ๆ’ฒๆฅตๆ€ง่กจ้ข็ฉ๏ผŒN ๅ’Œ O ็‰‡ๆฎต๏ผˆErtl 2000๏ผ‰", + "7": "่Žซ่€ณๆŠ˜ๅฐ„็އ", + "8": "ๆฐซ้ตไบˆ้ซ”", + "9": "Lipinski ่จˆๆ•ธ๏ผšN-H ๅ’Œ O-H ๅŸบๅœ˜", + "10": "ๆฐซ้ตๅ—้ซ”", + "11": "Lipinski ่จˆๆ•ธ๏ผšN ๅ’Œ O ๅŽŸๅญ", + "12": "ๅฏๆ—‹่ฝ‰้ต", + "13": "้žๆœซ็ซฏ้‡ๅŽŸๅญไน‹้–“็š„้ž็’ฐๅ–ฎ้ต๏ผŒไธๅซ้†ฏ่ƒบ C-N ้ต", + "14": "Lipinski ไบ”่ฆๅ‰‡", + "15": "MW ไธ่ถ…้Ž 500๏ผŒcLogP ไธ่ถ…้Ž 5๏ผŒไบˆ้ซ”ไธ่ถ…้Ž 5๏ผŒๅ—้ซ”ไธ่ถ…้Ž 10", + "16": "HBD", + "17": "HBA", + "18": "้€š้Ž๏ผˆ0 ้ …้•ๅ๏ผ‰", + "19": "่ซ‹ๅ…ˆ้ธๅ–ไธ€ๅ€‹ๆˆ–ๅคšๅ€‹ๅŽŸๅญ", + "20": "่ซ‹ๅ…ˆ้ธๅ–ไธ€ๅ€‹ๆˆ–ๅคšๅ€‹้ต", + "21": "ๆฒ’ๆœ‰ๅฏๅŠ ๅ…ฅ็š„้šฑๅผๆฐซใ€‚", + "22": "ๆฒ’ๆœ‰ๅฏ็งป้™ค็š„้กฏๅผๆฐซใ€‚", + "23": "่ซ‹้ธๅ– Ph ๆˆ– OTs ็ญ‰็ธฎๅฏซไปฅๅฑ•้–‹ใ€‚", + "24": "่ซ‹้ธๅ–ๆŸไธ€็ตๆง‹ไธญไธ€ๅ€‹ๅŸบๅœ˜็š„ๅŽŸๅญไปฅๆ”ถๅˆใ€‚", + "25": "่ซ‹้ธๅ–่ฆๆ”ถๅˆ็š„ๅŸบๅœ˜๏ผŒไธๅŒ…ๆ‹ฌ่ˆ‡ๅ…ถ็›ธ้€ฃ็š„ๅŽŸๅญใ€‚", + "26": "ๆ”ถๅˆ", + "27": "็‚บๆ‰€้ธๅŽŸๅญๆŒ‘้ธ่ณ‡ๆ–™ๅบซไธญ็š„็ธฎๅฏซ๏ผŒๆˆ–่ผธๅ…ฅๆ–ฐ็š„ๆจ™็ฑคใ€‚", + "28": "่จญๅฎš็ซ‹้ซ”็พค็ต„", + "29": "ๆธ…้™ค็ซ‹้ซ”็พค็ต„", + "30": "่จญๅฎšๅŽŸๅญๆธ…ๅ–ฎ", + "31": "ๆธ…้™คๅŽŸๅญๆธ…ๅ–ฎ", + "32": "่จญๅฎšๆŸฅ่ฉข้ต", + "33": "ๆธ…้™ค้ตๆŸฅ่ฉข", + "34": "่ซ‹้ธๅ–ๅธถๆœ‰ R ๅŸบๅœ˜็š„ๅŽŸๅญใ€‚", + "35": "1 ๅ€‹้€ฃๆŽฅ้ปž", + "36": "ๅฎš็พฉ R ๅŸบๅœ˜", + "37": "็งป้™ค R ๅŸบๅœ˜ๅฎš็พฉ", + "38": "ๆŒ‡ๅฎšๆฅ”ๅฝข้ต", + "39": "ๆฅ”ๅฝข้ตๅทฒ่ˆ‡็ซ‹้ซ”ไธญๅฟƒไธ€่‡ดใ€‚", + "40": "ๆ‰€้ธ็ตๆง‹", + "41": "ๆญค้ ้ขไธŠ็š„ๆฏๅ€‹็ตๆง‹", + "42": "ไฟฎๅพฉ็ตๆง‹", + "43": "ๆฒ’ๆœ‰ๅฏๅˆ†ๆž็š„็ตๆง‹ใ€‚", + "44": "ๅˆ†ๆž็ตๆžœๅทฒ่ค‡่ฃฝ", + "45": "็„กๆณ•่ค‡่ฃฝๅˆฐๅ‰ช่ฒผ็ฐฟ", + "46": "ๅฐ‹ๆ‰พๅญ็ตๆง‹", + "47": "SMARTS", + "48": "่ซ‹ๅ…ˆ็นช่ฃฝ่ฆๅœจๆญค้ ้ขไธŠๆœๅฐ‹็š„็ตๆง‹ใ€‚", + "49": "ๅƒ…้กฏ็คบๅ‰ๅนพ้ …็ตๆžœ", + "50": "ๆญค้ ้ขไธŠๆฒ’ๆœ‰็ฌฆๅˆ้ …ใ€‚", + "51": "่ซ‹ๅ…ˆ็นช่ฃฝๅธถๆœ‰ R ๅŸบๅœ˜ๅŽŸๅญ็š„็ตๆง‹ไธฆๅฎš็พฉๅ…ถ R ๅŸบๅœ˜ใ€‚", + "52": "ๆฒ’ๆœ‰ๅฏๅฏซๆˆ SMARTS ็š„็ตๆง‹ใ€‚", + "53": "ๅ„ฒๅญ˜ SMARTS ๆช”ๆกˆๅฐ‡้šจ 0.7.0 ไธญ็š„ๆช”ๆกˆๆ ผๅผไธ€ๅŒๆŽจๅ‡บ๏ผ›ๅทฒๆ”น็‚บ่ค‡่ฃฝ SMARTSใ€‚", + "54": "ๅฐ‡ๆ‰€้ธๅŽŸๅญ๏ผˆๆˆ–้ ้ขไธŠๆฏๅ€‹็ตๆง‹๏ผ‰็š„ๆฏๅ€‹้šฑๅผๆฐซ็นช่ฃฝ็‚บ็”ฑๅผ•ๆ“Žๆ”พ็ฝฎ็š„้กฏๅผ H ๅŽŸๅญ๏ผŒไฝœ็‚บไธ€ๅ€‹ๅพฉๅŽŸๆญฅ้ฉŸใ€‚", + "55": "ๅพžๆ‰€้ธๅ…งๅฎน๏ผˆๆˆ–้ ้ข๏ผ‰ไธญ็งป้™ค้กฏๅผ H ๅŽŸๅญ๏ผŒไฝ†ไฟ็•™ๅธถๆœ‰็ซ‹้ซ”่ณ‡่จŠใ€ๅŒไฝ็ด ใ€้›ป่ทใ€ๅฐๆ‡‰็ทจ่™Ÿๆˆ–ๆฉ‹ๆŽฅๅ…ฉๅ€‹ๅŽŸๅญ็š„ๆฐซใ€‚", + "56": "ๅฐ‡ๆ‰€้ธ็ธฎๅฏซๅŽŸๅญ๏ผˆๆˆ–้ ้ขไธŠ็š„ๆฏๅ€‹็ธฎๅฏซ๏ผ‰ๅ–ไปฃ็‚บๅ…ถๅฎŒๆ•ด็ตๆง‹๏ผŒไธฆๆฒฟ้€ฃๆŽฅ้ตๆŽ’ๅธƒใ€‚", + "57": "ๆ”ถๅˆ็ธฎๅฏซ...", + "58": "ๅฐ‡ๆ‰€้ธๅŽŸๅญๅŸบๅœ˜ๆ”ถๅˆ็‚บไธ€ๅ€‹็ธฎๅฏซๅŽŸๅญ๏ผŒๆจ™็ฑค็”ฑไฝฟ็”จ่€…ๆŒ‘้ธๆˆ–่ผธๅ…ฅใ€‚", + "59": "้กฏ็คบๆˆ–้šฑ่—็ซ‹้ซ”ไธญๅฟƒๅ’Œ็ซ‹้ซ”้›™้ตๆ—็š„ Rใ€Sใ€Eใ€Z ๆจ™่จ˜ใ€‚", + "60": "้กฏ็คบๅขžๅผท็ซ‹้ซ”็พค็ต„", + "61": "ๅœจ็ซ‹้ซ”ๆจ™่จ˜้–‹ๅ•Ÿๆ™‚๏ผŒ้กฏ็คบๆˆ–้šฑ่—็ซ‹้ซ”ไธญๅฟƒๆ—็š„ absใ€and ๅ’Œ or ็พค็ต„ๆจ™่จ˜ใ€‚", + "62": "้กฏ็คบๆŸฅ่ฉข็‰นๅพต", + "63": "้กฏ็คบๆˆ–้šฑ่—็•ซๅธƒไธŠ็š„ๅŽŸๅญๆธ…ๅ–ฎใ€ๆŸฅ่ฉข้ตๅ’Œ R ๅŸบๅœ˜ๆจ™่จ˜ใ€‚", + "64": "ๅฐ‡ๆ‰€้ธ็ซ‹้ซ”ไธญๅฟƒๆ”พๅ…ฅๅขžๅผท็ซ‹้ซ”็พค็ต„๏ผšabsใ€and n ๆˆ– or nใ€‚ไธๅธถ n ๆ™‚ๆœƒๅปบ็ซ‹ๆ–ฐ็š„ and ๆˆ– or ็พค็ต„ใ€‚", + "65": "absใ€and ๆˆ– or", + "66": "and ๅ’Œ or ็š„็พค็ต„็ทจ่™Ÿ", + "67": "็ต•ๅฐ๏ผˆabs๏ผ‰", + "68": "ๆ–ฐๅขž AND ็พค็ต„", + "69": "ๆ–ฐๅขž OR ็พค็ต„", + "70": "็ซ‹้ซ”็พค็ต„...", + "71": "ๅŽŸๅญๆธ…ๅ–ฎ...", + "72": "ๅฐ‡ๆ‰€้ธๅŽŸๅญ่ฎŠ็‚บๅœจๅ…ƒ็ด ้€ฑๆœŸ่กจไธŠๆŒ‘้ธ็š„ๅŽŸๅญๆธ…ๅ–ฎๆˆ–้žๆธ…ๅ–ฎๆŸฅ่ฉขใ€‚", + "73": "ๅฐ‡ๆ‰€้ธ้ต่จญ็‚บๆŸฅ่ฉข้ต๏ผšanyใ€single_or_doubleใ€single_or_aromatic ๆˆ– double_or_aromatic๏ผ›็œ็•ฅ query ๅ‰‡ๆธ…้™คใ€‚", + "74": "ๆŸฅ่ฉข้ต้กžๅž‹", + "75": "ๅฎš็พฉ R ๅŸบๅœ˜...", + "76": "ๅฐ‡ๆ‰€้ธๅŽŸๅญ่จญ็‚บ R ๅŸบๅœ˜ๆจ™็ฑค๏ผŒไธฆๅฎš็พฉๅ…ถๆˆๅ“กใ€ๅ‡บ็พๆฌกๆ•ธใ€ๅ…ถ้ค˜ H ๅ’Œ if-then ๆขไปถใ€‚", + "77": "่ฎ“ๅผ•ๆ“Ž้ธๆ“‡่ƒฝๆ˜Ž็ขบ่กจ็คบๆ‰€้ธๅ…งๅฎน๏ผˆๆˆ–้ ้ข๏ผ‰็ซ‹้ซ”ไธญๅฟƒ็š„ๆฅ”ๅฝข้ตๅ’Œ่™›็ทš้ตใ€‚", + "78": "ๅœจ้ขๆฟไธญๅˆ—ๅ‡บๆ‰€้ธๅ…งๅฎน๏ผˆๆˆ–้ ้ข๏ผ‰็š„ๅƒนๆ…‹ใ€็ซ‹้ซ”ใ€ๅนพไฝ•ๅ’Œๆจ™็ฑคๅ•้กŒ๏ผŒ้ปžๆ“Šๅˆ—ๅณๅฏ้ธๅ–็›ธๆ‡‰ๅŽŸๅญใ€‚", + "79": "้–‹ๅ•Ÿๅˆ†ๆž้ขๆฟ๏ผŒ้กฏ็คบๆ‰€้ธๅ…งๅฎนๆˆ–้ ้ข็š„่จˆ็ฎ—ๆ€ง่ณชใ€‚", + "80": "ๅฐ‡ๅˆ†ๅญๅผใ€่ณช้‡ใ€ๅ…ƒ็ด ๅˆ†ๆžๅ’Œ่จˆ็ฎ—ๆ€ง่ณชๅŠๅ…ถๆ–นๆณ•ไปฅๆ–‡ๅญ—ๅฝขๅผ่ค‡่ฃฝใ€‚", + "81": "ๅฐ‹ๆ‰พๅญ็ตๆง‹...", + "82": "ๅœจ้ ้ขไธŠ็š„ๅ…ถไป–็ตๆง‹ไธญ๏ผŒ้ธๅ–ๆ‰€้ธๅŽŸๅญ๏ผˆๆˆ– SMARTS ๆจกๅผ๏ผ‰็š„ๆฏๅ€‹็ฌฆๅˆ้ …ใ€‚", + "83": "ๅˆ—่ˆ‰ R ๅŸบๅœ˜...", + "84": "ๅˆ—ๅ‡บๆ‰€้ธ Markush ๆฏๆ ธ๏ผˆๆˆ–้ ้ขไธŠ็ฌฌไธ€ๅ€‹๏ผ‰ๆ‰€ไปฃ่กจ็š„ๆฏๅ€‹็ตๆง‹๏ผŒๅซๅˆ†ๅญๅผๅ’Œ SMILES๏ผŒๆœ€ๅคš 1000 ๅ€‹๏ผ›ๆธ…ๅ–ฎๅฏ่ค‡่ฃฝใ€‚", + "85": "่ค‡่ฃฝ็‚บ SMARTS", + "86": "ๅฐ‡ๆ‰€้ธๅŽŸๅญ๏ผˆๆˆ–้ ้ขไธŠๆฏๅ€‹็ตๆง‹๏ผ‰่ค‡่ฃฝ็‚บ SMARTS๏ผŒๅŒ…ๅซๅŽŸๅญๆธ…ๅ–ฎใ€้€š็”จๅŽŸๅญใ€ๆŸฅ่ฉข้ตๅŠๅ…ถไป–ๆŸฅ่ฉข็‰นๅพตใ€‚", + "87": "ๅŒฏๅ‡บ SMARTS...", + "88": "ๅฐ‡ๆ‰€้ธๅŽŸๅญ๏ผˆๆˆ–้ ้ขไธŠๆฏๅ€‹็ตๆง‹๏ผ‰ๅ„ฒๅญ˜็‚บ SMARTS ๆช”ๆกˆ๏ผˆ.sma๏ผ‰ใ€‚", + "89": "ๅขžๅผท็ซ‹้ซ”", + "90": "ๆŸฅ่ฉข", + "91": "็‰ฉไปถ", + "92": "่ซ‹ๅ…ˆ้ธๅ–่ฆๆŒ‡ๅฎš่ง’่‰ฒ็š„็ตๆง‹ๆˆ–ๆ–‡ๅญ—ใ€‚", + "93": "่จญๅฎšๅๆ‡‰่ง’่‰ฒ...", + "94": "่จญๅฎšๆ‰€้ธๅๆ‡‰ๆญฅ้ฉŸไธญๆ‰€้ธ็ตๆง‹ๆˆ–ๆ–‡ๅญ—็š„่ง’่‰ฒ๏ผˆๅๆ‡‰็‰ฉใ€็”ข็‰ฉใ€่ฉฆๅŠ‘ใ€ๆขไปถๆˆ–็„ก๏ผ‰๏ผŒไธฆๅฐ‡่ฉฒๆญฅ้ฉŸ็š„่ง’่‰ฒๆจ™่จ˜็‚บๆ‰‹ๅ‹•่จญๅฎš๏ผŒไฝœ็‚บไธ€ๅ€‹ๅพฉๅŽŸๆญฅ้ฉŸใ€‚ไธๅธถ role ๆ™‚ๆœƒ้–‹ๅ•Ÿๅฐ่ฉฑๆ–นๅกŠ๏ผŒๅˆ—ๅ‡บ่ฉฒๆญฅ้ฉŸ็š„ๆˆๅ“กๅ’Œๆ‰€้ธๅ…งๅฎนใ€‚", + "95": "่ฆ่ณฆไบˆ็‰ฉไปถ็š„่ง’่‰ฒ๏ผ›็œ็•ฅๅ‰‡้–‹ๅ•Ÿๅฐ่ฉฑๆ–นๅกŠ", + "96": "่ฆ่ฎŠๆ›ด็š„็‰ฉไปถ id๏ผ›้ ่จญ็‚บๆ‰€้ธๅ…งๅฎน", + "97": "็„กๆณ•่จญๅฎšๅๆ‡‰่ง’่‰ฒ", + "98": "ๅ…ถ้ค˜ H", + "99": "็ธฎๅฏซ", + "100": "ๆจ™็ฑค", + "101": "ๆœๅฐ‹่ณ‡ๆ–™ๅบซ", + "102": "็„กๆณ•่ผ‰ๅ…ฅ็ธฎๅฏซ่ณ‡ๆ–™ๅบซใ€‚ๆ‚จไปๅฏ่ผธๅ…ฅๆจ™็ฑคใ€‚", + "103": "ๆฒ’ๆœ‰็ฌฆๅˆ็š„็ธฎๅฏซใ€‚ๅฐ‡็…งๅŽŸๆจฃไฝฟ็”จๆ‚จ่ผธๅ…ฅ็š„ๆจ™็ฑคใ€‚", + "104": "ๆ€ง่ณช", + "105": "ๅŽŸๅญๆธ…ๅ–ฎ", + "106": "้ปžๆ“Š่กจไธญ็š„ๅ…ƒ็ด ๅณๅฏๅŠ ๅ…ฅใ€‚", + "107": "ๆธ…้™คๆŸฅ่ฉข", + "108": "ๅฅ—็”จ", + "109": "็งป้™ค", + "110": "็„กๆŸฅ่ฉข", + "111": "[M+Na]+", + "112": "ๅŒไฝ็ด ๅˆ†ๅธƒ", + "113": "ๅˆ—่ˆ‰ R ๅŸบๅœ˜", + "114": "่ค‡่ฃฝ SMILES", + "115": "ๅทฒ่ค‡่ฃฝๆฏๅ€‹็ตๆง‹็š„ SMILES", + "116": "Si", + "117": "ไปปๆ„้ต", + "118": "ๅ–ฎ้ตๆˆ–้›™้ต", + "119": "ๅ–ฎ้ตๆˆ–่Šณ้ฆ™้ต", + "120": "้›™้ตๆˆ–่Šณ้ฆ™้ต", + "121": "็’ฐๆˆ–้ˆ", + "122": "ๅœจ็’ฐไธญ", + "123": "ๅœจ้ˆไธญ", + "124": "ไปปๆ„ๅŽŸๅญ๏ผˆA๏ผ‰", + "125": "ไปปๆ„้›œๅŽŸๅญ๏ผˆQ๏ผ‰", + "126": "ไปปๆ„้นต็ด ๏ผˆX๏ผ‰", + "127": "ไปปๆ„้‡‘ๅฑฌ๏ผˆM๏ผ‰", + "128": "่จญๅฎš้ตๆ‹“ๆ’ฒ", + "129": "ๆŸฅ่ฉข้ต", + "130": "่จญๅฎšๅŽŸๅญๆŸฅ่ฉข", + "131": "่Šณ้ฆ™", + "132": "่„‚่‚ช", + "133": "ไธ้ฃฝๅ’Œ", + "134": "ไพๆ‰€็นชๅ–ไปฃ", + "135": "ไพๆ‰€็นช็’ฐ้ต", + "136": "ๆธ…้™คๅŽŸๅญๆŸฅ่ฉข", + "137": "ๅŽŸๅญๆŸฅ่ฉข", + "138": "R ๅŸบๅœ˜ๅฎš็พฉ", + "139": "R ๅŸบๅœ˜", + "140": "ๆˆๅ“ก", + "141": "ๅฐ‡ๆฏๅ€‹ๆˆๅ“ก็นช่ฃฝ็‚บๅธถ้€ฃๆŽฅ้ปž๏ผˆ*๏ผ‰็š„็จ็ซ‹็ตๆง‹๏ผŒ็„ถๅพŒๅ†ๆฌก้–‹ๅ•Ÿๆญคๅฐ่ฉฑๆ–นๅกŠใ€‚", + "142": "ๅ‡บ็พๆฌกๆ•ธ", + "143": "ๅ…ถ้ค˜ H๏ผˆๆœชๅ–ไปฃ็š„ไฝ็ฝฎ็‚บๆฐซ๏ผ‰", + "144": "่‹ฅๅญ˜ๅœจ๏ผŒๅ‰‡", + "145": "็งป้™คๅฎš็พฉ", + "146": "่ฉฆๅŠ‘", + "147": "ๆขไปถ", + "148": "ๆธ…้™ค", + "149": "ๅฐ‡ๆ‰€้ธ็ซ‹้ซ”ไธญๅฟƒๅŠ ๅ…ฅๆญค็พค็ต„", + "150": "้‡ๆ–ฐๆชขๆŸฅ", + "151": "ๆญฃๅœจๆชขๆŸฅ...", + "152": "ไฟฎๅพฉ", + "153": "ๅœจ็•ซๅธƒไธŠ้ธๅ–" +} From 9206be274dc1074a9622dae369ad8930f88be79d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:32 -0500 Subject: [PATCH 261/279] feat(i18n): translate the stereo, query and analysis strings into Japanese (0.6.0) Adds the 154 strings of part06 for ja. --- frontend/src/i18n/locales/ja/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/ja/part06.json diff --git a/frontend/src/i18n/locales/ja/part06.json b/frontend/src/i18n/locales/ja/part06.json new file mode 100644 index 00000000..422965c2 --- /dev/null +++ b/frontend/src/i18n/locales/ja/part06.json @@ -0,0 +1,156 @@ +{ + "0": "้›ป่ทใคใใฎ Hill ้ †ใ€็•ฅๅทใฏๅฑ•้–‹ๆธˆใฟ", + "1": "ๆจ™ๆบ–ๅŽŸๅญ้‡(CIAAW ใฎๆ…ฃ็”จๅ€ค)", + "2": "ๅ„ๅ…ƒ็ด ใฎๆœ€ใ‚‚ๅญ˜ๅœจๆฏ”ใฎ้ซ˜ใ„ๅŒไฝไฝ“ใซใ‚ˆใ‚‹ๅ˜ไธ€ๅŒไฝไฝ“่ณช้‡", + "3": "็ฒพๅฏ†่ณช้‡ใ‚’้›ป่ทใฎ็ตถๅฏพๅ€คใงๅ‰ฒใฃใŸๅ€ค(้›ปๅญ่ณช้‡่ฃœๆญฃๆธˆใฟ)", + "4": "ๅ„ๅ…ƒ็ด ใฎ่ณช้‡ใƒ‘ใƒผใ‚ปใƒณใƒˆ(ๅฐๆ•ฐ็‚นไปฅไธ‹ 2 ๆก)", + "5": "ๅŽŸๅญใฎๅฏ„ไธŽ(Wildman and Crippen 1999)", + "6": "ใƒˆใƒใƒญใ‚ธใ‚ซใƒซๆฅตๆ€ง่กจ้ข็ฉใ€N ใจ O ใฎใƒ•ใƒฉใ‚ฐใƒกใƒณใƒˆ(Ertl 2000)", + "7": "ใƒขใƒซๅฑˆๆŠ˜", + "8": "ๆฐด็ด ็ตๅˆไพ›ไธŽไฝ“", + "9": "Lipinski ใฎใ‚ซใ‚ฆใƒณใƒˆ:N-H ๅŸบใจ O-H ๅŸบ", + "10": "ๆฐด็ด ็ตๅˆๅ—ๅฎนไฝ“", + "11": "Lipinski ใฎใ‚ซใ‚ฆใƒณใƒˆ:N ๅŽŸๅญใจ O ๅŽŸๅญ", + "12": "ๅ›ž่ปขๅฏ่ƒฝ็ตๅˆ", + "13": "ๆœซ็ซฏใงใชใ„้‡ๅŽŸๅญ้–“ใฎ้ž็’ฐ็Šถๅ˜็ตๅˆ(ใ‚ขใƒŸใƒ‰ใฎ C-N ใฏ้™คใ)", + "14": "Lipinski ใฎ 5 ใฎๆณ•ๅ‰‡", + "15": "MW ใฏ 500 ไปฅไธ‹ใ€cLogP ใฏ 5 ไปฅไธ‹ใ€ไพ›ไธŽไฝ“ใฏ 5 ไปฅไธ‹ใ€ๅ—ๅฎนไฝ“ใฏ 10 ไปฅไธ‹", + "16": "HBD", + "17": "HBA", + "18": "ๅˆๆ ผ(้•ๅ 0 ไปถ)", + "19": "ๅ…ˆใซ 1 ใคไปฅไธŠใฎๅŽŸๅญใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„", + "20": "ๅ…ˆใซ 1 ใคไปฅไธŠใฎ็ตๅˆใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„", + "21": "่ฟฝๅŠ ใงใใ‚‹ๆš—้ป™ใฎๆฐด็ด ใฏใ‚ใ‚Šใพใ›ใ‚“ใ€‚", + "22": "ๅ‰Š้™คใงใใ‚‹ๆ˜Ž็คบ็š„ใชๆฐด็ด ใฏใ‚ใ‚Šใพใ›ใ‚“ใ€‚", + "23": "ๅฑ•้–‹ใ™ใ‚‹ Ph ใ‚„ OTs ใชใฉใฎ็•ฅๅทใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„ใ€‚", + "24": "็ธฎ็ด„ใ™ใ‚‹ใ€1 ใคใฎๆง‹้€ ๅ†…ใฎ 1 ใคใฎๅŸบใฎๅŽŸๅญใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„ใ€‚", + "25": "็ธฎ็ด„ใ™ใ‚‹ๅŸบใ‚’ใ€็ตๅˆๅ…ˆใฎๅŽŸๅญใ‚’ๅซใ‚ใšใซ้ธๆŠžใ—ใฆใใ ใ•ใ„ใ€‚", + "26": "็ธฎ็ด„", + "27": "้ธๆŠžใ—ใŸๅŽŸๅญใซใƒฉใ‚คใƒ–ใƒฉใƒชใฎ็•ฅๅทใ‚’้ธใถใ‹ใ€ๆ–ฐใ—ใ„ใƒฉใƒ™ใƒซใ‚’ๅ…ฅๅŠ›ใ—ใฆใใ ใ•ใ„ใ€‚", + "28": "็ซ‹ไฝ“ใ‚ฐใƒซใƒผใƒ—ใ‚’่จญๅฎš", + "29": "็ซ‹ไฝ“ใ‚ฐใƒซใƒผใƒ—ใ‚’่งฃ้™ค", + "30": "ๅŽŸๅญใƒชใ‚นใƒˆใ‚’่จญๅฎš", + "31": "ๅŽŸๅญใƒชใ‚นใƒˆใ‚’่งฃ้™ค", + "32": "ใ‚ฏใ‚จใƒช็ตๅˆใ‚’่จญๅฎš", + "33": "็ตๅˆใ‚ฏใ‚จใƒชใ‚’่งฃ้™ค", + "34": "R ๅŸบใ‚’ใ‚‚ใคๅŽŸๅญใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„ใ€‚", + "35": "็ตๅˆ็‚น 1 ใค", + "36": "R ๅŸบใ‚’ๅฎš็พฉ", + "37": "R ๅŸบใฎๅฎš็พฉใ‚’ๅ‰Š้™ค", + "38": "ใใ•ใณใ‚’ๅ‰ฒใ‚Šๅฝ“ใฆ", + "39": "ใใ•ใณใฏใ™ใงใซ็ซ‹ไฝ“ไธญๅฟƒใจไธ€่‡ดใ—ใฆใ„ใพใ™ใ€‚", + "40": "้ธๆŠžใ—ใŸๆง‹้€ ", + "41": "ใ“ใฎใƒšใƒผใ‚ธใฎใ™ในใฆใฎๆง‹้€ ", + "42": "ๆง‹้€ ใ‚’ไฟฎๆญฃ", + "43": "่งฃๆžใ™ใ‚‹ๆง‹้€ ใŒใ‚ใ‚Šใพใ›ใ‚“ใ€‚", + "44": "่งฃๆž็ตๆžœใ‚’ใ‚ณใƒ”ใƒผใ—ใพใ—ใŸ", + "45": "ใ‚ฏใƒชใƒƒใƒ—ใƒœใƒผใƒ‰ใซใ‚ณใƒ”ใƒผใงใใพใ›ใ‚“ใงใ—ใŸ", + "46": "้ƒจๅˆ†ๆง‹้€ ใ‚’ๆคœ็ดข", + "47": "SMARTS", + "48": "ๅ…ˆใซใ“ใฎใƒšใƒผใ‚ธใงๆคœ็ดขใ™ใ‚‹ๆง‹้€ ใ‚’ๆใ„ใฆใใ ใ•ใ„ใ€‚", + "49": "ๆœ€ๅˆใฎ็ตๆžœใฎใฟ", + "50": "ใ“ใฎใƒšใƒผใ‚ธใซไธ€่‡ดใ™ใ‚‹ใ‚‚ใฎใฏใ‚ใ‚Šใพใ›ใ‚“ใ€‚", + "51": "ๅ…ˆใซ R ๅŸบใฎๅŽŸๅญใ‚’ใ‚‚ใคๆง‹้€ ใ‚’ๆใใ€ใใฎ R ๅŸบใ‚’ๅฎš็พฉใ—ใฆใใ ใ•ใ„ใ€‚", + "52": "SMARTS ใจใ—ใฆๆ›ธใๅ‡บใ™ๆง‹้€ ใŒใ‚ใ‚Šใพใ›ใ‚“ใ€‚", + "53": "SMARTS ใƒ•ใ‚กใ‚คใƒซใฎไฟๅญ˜ใฏ 0.7.0 ใฎใƒ•ใ‚กใ‚คใƒซๅฝขๅผใจใจใ‚‚ใซๆไพ›ใ•ใ‚Œใพใ™ใ€‚ไปฃใ‚ใ‚Šใซ SMARTS ใ‚’ใ‚ณใƒ”ใƒผใ—ใพใ—ใŸใ€‚", + "54": "้ธๆŠžใ—ใŸๅŽŸๅญ(ใพใŸใฏใƒšใƒผใ‚ธไธŠใฎใ™ในใฆใฎๆง‹้€ )ใฎๆš—้ป™ใฎๆฐด็ด ใ‚’ใ™ในใฆใ€ใ‚จใƒณใ‚ธใƒณใŒ้…็ฝฎใ™ใ‚‹ๆ˜Ž็คบ็š„ใช H ๅŽŸๅญใจใ—ใฆๆใใ€ๅ–ใ‚Šๆถˆใ— 1 ๅ›žๅˆ†ใจใ—ใฆ้ฉ็”จใ—ใพใ™ใ€‚", + "55": "้ธๆŠž็ฏ„ๅ›ฒ(ใพใŸใฏใƒšใƒผใ‚ธ)ใ‹ใ‚‰ๆ˜Ž็คบ็š„ใช H ๅŽŸๅญใ‚’ๅ‰Š้™คใ—ใพใ™ใ€‚ใŸใ ใ—ใ€็ซ‹ไฝ“ใ€ๅŒไฝไฝ“ใ€้›ป่ทใ€ใƒžใƒƒใƒ—็•ชๅทใ‚’ใ‚‚ใคๆฐด็ด ใ‚„ใ€2 ใคใฎๅŽŸๅญใ‚’ๆฉ‹ใ‹ใ‘ใ—ใฆใ„ใ‚‹ๆฐด็ด ใฏๆฎ‹ใ—ใพใ™ใ€‚", + "56": "้ธๆŠžใ—ใŸ็•ฅๅทใฎๅŽŸๅญ(ใพใŸใฏใƒšใƒผใ‚ธไธŠใฎใ™ในใฆใฎ็•ฅๅท)ใ‚’ๅฎŒๅ…จใชๆง‹้€ ใซ็ฝฎใๆ›ใˆใ€็ตๅˆใซๆฒฟใฃใฆ้…็ฝฎใ—ใพใ™ใ€‚", + "57": "็•ฅๅทใซ็ธฎ็ด„...", + "58": "้ธๆŠžใ—ใŸๅŽŸๅญใฎๅŸบใ‚’ใ€ใƒฆใƒผใ‚ถใƒผใŒ้ธใถใ‹ๅ…ฅๅŠ›ใ—ใŸใƒฉใƒ™ใƒซใ‚’ใ‚‚ใค 1 ใคใฎ็•ฅๅทๅŽŸๅญใซใพใจใ‚ใพใ™ใ€‚", + "59": "็ซ‹ไฝ“ไธญๅฟƒใจ็ซ‹ไฝ“ไบŒ้‡็ตๅˆใฎๆจชใซ Rใ€Sใ€Eใ€Z ใฎใƒฉใƒ™ใƒซใ‚’่กจ็คบใพใŸใฏ้ž่กจ็คบใซใ—ใพใ™ใ€‚", + "60": "ๆ‹กๅผต็ซ‹ไฝ“ใ‚ฐใƒซใƒผใƒ—ใ‚’่กจ็คบ", + "61": "็ซ‹ไฝ“ใƒฉใƒ™ใƒซใŒใ‚ชใƒณใฎใจใใ€็ซ‹ไฝ“ไธญๅฟƒใฎๆจชใซ absใ€andใ€or ใฎใ‚ฐใƒซใƒผใƒ—ใƒฉใƒ™ใƒซใ‚’่กจ็คบใพใŸใฏ้ž่กจ็คบใซใ—ใพใ™ใ€‚", + "62": "ใ‚ฏใ‚จใƒชๆฉŸ่ƒฝใ‚’่กจ็คบ", + "63": "ใ‚ญใƒฃใƒณใƒใ‚นไธŠใฎๅŽŸๅญใƒชใ‚นใƒˆใ€ใ‚ฏใ‚จใƒช็ตๅˆใ€R ๅŸบใฎๅฐใ‚’่กจ็คบใพใŸใฏ้ž่กจ็คบใซใ—ใพใ™ใ€‚", + "64": "้ธๆŠžใ—ใŸ็ซ‹ไฝ“ไธญๅฟƒใ‚’ๆ‹กๅผต็ซ‹ไฝ“ใ‚ฐใƒซใƒผใƒ—(absใ€and nใ€or n)ใซๅ…ฅใ‚Œใพใ™ใ€‚n ใ‚’็œใใจใ€ๆ–ฐใ—ใ„ and ใพใŸใฏ or ใ‚ฐใƒซใƒผใƒ—ใ‚’ไฝœๆˆใ—ใพใ™ใ€‚", + "65": "absใ€andใ€or", + "66": "and ใจ or ใฎใ‚ฐใƒซใƒผใƒ—็•ชๅท", + "67": "็ตถๅฏพ(abs)", + "68": "ๆ–ฐใ—ใ„ AND ใ‚ฐใƒซใƒผใƒ—", + "69": "ๆ–ฐใ—ใ„ OR ใ‚ฐใƒซใƒผใƒ—", + "70": "็ซ‹ไฝ“ใ‚ฐใƒซใƒผใƒ—...", + "71": "ๅŽŸๅญใƒชใ‚นใƒˆ...", + "72": "้ธๆŠžใ—ใŸๅŽŸๅญใ‚’ใ€ๅ‘จๆœŸ่กจใง้ธใ‚“ใ ๅŽŸๅญใƒชใ‚นใƒˆใพใŸใฏ้žใƒชใ‚นใƒˆใฎใ‚ฏใ‚จใƒชใซใ—ใพใ™ใ€‚", + "73": "้ธๆŠžใ—ใŸ็ตๅˆใ‚’ใ‚ฏใ‚จใƒช็ตๅˆใซใ—ใพใ™:anyใ€single_or_doubleใ€single_or_aromaticใ€double_or_aromaticใ€‚query ใ‚’็œใใจ่งฃ้™คใ—ใพใ™ใ€‚", + "74": "ใ‚ฏใ‚จใƒช็ตๅˆใฎ็จฎ้กž", + "75": "R ๅŸบใ‚’ๅฎš็พฉ...", + "76": "้ธๆŠžใ—ใŸๅŽŸๅญใ‚’ R ๅŸบใƒฉใƒ™ใƒซใซใ—ใ€ใใฎใƒกใƒณใƒใƒผใ€ๅ‡บ็พๆ•ฐใ€ๆฎ‹ใ‚Šใฎ Hใ€if-then ๆกไปถใ‚’ๅฎš็พฉใ—ใพใ™ใ€‚", + "77": "้ธๆŠž็ฏ„ๅ›ฒ(ใพใŸใฏใƒšใƒผใ‚ธ)ใฎ็ซ‹ไฝ“ไธญๅฟƒใ‚’ๆ›–ๆ˜งใ•ใชใ่กจใ›ใ‚‹ใ‚ˆใ†ใ€ใ‚จใƒณใ‚ธใƒณใŒใใ•ใณ็ตๅˆใจ็ ด็ทš็ตๅˆใ‚’้ธใณใพใ™ใ€‚", + "78": "้ธๆŠž็ฏ„ๅ›ฒ(ใพใŸใฏใƒšใƒผใ‚ธ)ใฎๅŽŸๅญไพกใ€็ซ‹ไฝ“ใ€ใ‚ธใ‚ชใƒกใƒˆใƒชใ€ใƒฉใƒ™ใƒซใฎๅ•้กŒใ‚’ใƒ‘ใƒใƒซใซไธ€่ฆง่กจ็คบใ—ใพใ™ใ€‚่กŒใ‚’้ธใถใจ่ฉฒๅฝ“ใ™ใ‚‹ๅŽŸๅญใŒ้ธๆŠžใ•ใ‚Œใพใ™ใ€‚", + "79": "้ธๆŠž็ฏ„ๅ›ฒใพใŸใฏใƒšใƒผใ‚ธใฎ่จˆ็ฎ—ใ•ใ‚ŒใŸๆ€ง่ณชใ‚’่งฃๆžใƒ‘ใƒใƒซใซ่กจ็คบใ—ใพใ™ใ€‚", + "80": "ๅˆ†ๅญๅผใ€่ณช้‡ใ€ๅ…ƒ็ด ๅˆ†ๆžใ€่จˆ็ฎ—ใ•ใ‚ŒใŸๆ€ง่ณชใจใใฎ็ฎ—ๅ‡บๆ–นๆณ•ใ‚’ใƒ†ใ‚ญใ‚นใƒˆใจใ—ใฆใ‚ณใƒ”ใƒผใ—ใพใ™ใ€‚", + "81": "้ƒจๅˆ†ๆง‹้€ ใ‚’ๆคœ็ดข...", + "82": "ใƒšใƒผใ‚ธไธŠใฎไป–ใฎๆง‹้€ ใ‹ใ‚‰ใ€้ธๆŠžใ—ใŸๅŽŸๅญ(ใพใŸใฏ SMARTS ใƒ‘ใ‚ฟใƒผใƒณ)ใซไธ€่‡ดใ™ใ‚‹ใ‚‚ใฎใ‚’ใ™ในใฆ้ธๆŠžใ—ใพใ™ใ€‚", + "83": "R ๅŸบใ‚’ๅˆ—ๆŒ™...", + "84": "้ธๆŠžใ—ใŸ Markush ้ชจๆ ผ(ใพใŸใฏใƒšใƒผใ‚ธๆœ€ๅˆใฎใ‚‚ใฎ)ใŒ่กจใ™ใ™ในใฆใฎๆง‹้€ ใ‚’ใ€ๅˆ†ๅญๅผใจ SMILES ใจใจใ‚‚ใซๆœ€ๅคง 1000 ไปถใพใงไธ€่ฆง่กจ็คบใ—ใพใ™ใ€‚ไธ€่ฆงใฏใ‚ณใƒ”ใƒผใงใใพใ™ใ€‚", + "85": "SMARTS ใจใ—ใฆใ‚ณใƒ”ใƒผ", + "86": "้ธๆŠžใ—ใŸๅŽŸๅญ(ใพใŸใฏใƒšใƒผใ‚ธไธŠใฎใ™ในใฆใฎๆง‹้€ )ใ‚’ใ€ๅŽŸๅญใƒชใ‚นใƒˆใ€ๆฑŽ็”จๅŽŸๅญใ€ใ‚ฏใ‚จใƒช็ตๅˆใชใฉใฎใ‚ฏใ‚จใƒชๆฉŸ่ƒฝใ‚’ๅซใ‚ใฆ SMARTS ใจใ—ใฆใ‚ณใƒ”ใƒผใ—ใพใ™ใ€‚", + "87": "SMARTS ใ‚’ๆ›ธใๅ‡บใ—...", + "88": "้ธๆŠžใ—ใŸๅŽŸๅญ(ใพใŸใฏใƒšใƒผใ‚ธไธŠใฎใ™ในใฆใฎๆง‹้€ )ใ‚’ SMARTS ใƒ•ใ‚กใ‚คใƒซ(.sma)ใจใ—ใฆไฟๅญ˜ใ—ใพใ™ใ€‚", + "89": "ๆ‹กๅผต็ซ‹ไฝ“", + "90": "ใ‚ฏใ‚จใƒช", + "91": "ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆ", + "92": "ๅ…ˆใซๅฝนๅ‰ฒใ‚’ไธŽใˆใ‚‹ๆง‹้€ ใพใŸใฏใƒ†ใ‚ญใ‚นใƒˆใ‚’้ธๆŠžใ—ใฆใใ ใ•ใ„ใ€‚", + "93": "ๅๅฟœใฎๅฝนๅ‰ฒใ‚’่จญๅฎš...", + "94": "้ธๆŠžใ—ใŸๅๅฟœใ‚นใƒ†ใƒƒใƒ—ๅ†…ใฎใ€้ธๆŠžใ—ใŸๆง‹้€ ใพใŸใฏใƒ†ใ‚ญใ‚นใƒˆใฎๅฝนๅ‰ฒ(ๅๅฟœ็‰ฉใ€็”Ÿๆˆ็‰ฉใ€ใ‚จใƒผใ‚ธใ‚งใƒณใƒˆใ€ๆกไปถใ€ใชใ—)ใ‚’่จญๅฎšใ—ใ€ใใฎใ‚นใƒ†ใƒƒใƒ—ใฎๅฝนๅ‰ฒใ‚’ๆ‰‹ๅ‹•่จญๅฎšๆธˆใฟใจใ—ใฆ่จ˜้Œฒใ—ใพใ™ใ€‚ๅ–ใ‚Šๆถˆใ— 1 ๅ›žๅˆ†ใงใ™ใ€‚role ใ‚’็œใใจใ€ใ‚นใƒ†ใƒƒใƒ—ใฎใƒกใƒณใƒใƒผใจ้ธๆŠž็ฏ„ๅ›ฒใ‚’ไธ€่ฆงใ™ใ‚‹ใƒ€ใ‚คใ‚ขใƒญใ‚ฐใ‚’้–‹ใใพใ™ใ€‚", + "95": "ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใซไธŽใˆใ‚‹ๅฝนๅ‰ฒใ€‚็œ็•ฅใ™ใ‚‹ใจใƒ€ใ‚คใ‚ขใƒญใ‚ฐใ‚’้–‹ใใพใ™", + "96": "ๅค‰ๆ›ดใ™ใ‚‹ใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใฎ idใ€‚ๆ—ขๅฎšใฏ้ธๆŠž็ฏ„ๅ›ฒ", + "97": "ๅๅฟœใฎๅฝนๅ‰ฒใ‚’่จญๅฎšใงใใพใ›ใ‚“ใงใ—ใŸ", + "98": "ๆฎ‹ใ‚Šใฎ H", + "99": "็•ฅๅท", + "100": "ใƒฉใƒ™ใƒซ", + "101": "ใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’ๆคœ็ดข", + "102": "็•ฅๅทใƒฉใ‚คใƒ–ใƒฉใƒชใ‚’่ชญใฟ่พผใ‚ใพใ›ใ‚“ใงใ—ใŸใ€‚ใƒฉใƒ™ใƒซใฏๅ…ฅๅŠ›ใงใใพใ™ใ€‚", + "103": "ไธ€่‡ดใ™ใ‚‹็•ฅๅทใŒใ‚ใ‚Šใพใ›ใ‚“ใ€‚ๅ…ฅๅŠ›ใ—ใŸใƒฉใƒ™ใƒซใŒใใฎใพใพไฝฟใ‚ใ‚Œใพใ™ใ€‚", + "104": "ๆ€ง่ณช", + "105": "ๅŽŸๅญใƒชใ‚นใƒˆ", + "106": "่กจใฎๅ…ƒ็ด ใ‚’ใ‚ฏใƒชใƒƒใ‚ฏใ—ใฆ่ฟฝๅŠ ใ—ใพใ™ใ€‚", + "107": "ใ‚ฏใ‚จใƒชใ‚’่งฃ้™ค", + "108": "้ฉ็”จ", + "109": "ๅ‰Š้™ค", + "110": "ใ‚ฏใ‚จใƒชใชใ—", + "111": "[M+Na]+", + "112": "ๅŒไฝไฝ“ใƒ‘ใ‚ฟใƒผใƒณ", + "113": "R ๅŸบใ‚’ๅˆ—ๆŒ™", + "114": "SMILES ใ‚’ใ‚ณใƒ”ใƒผ", + "115": "ใ™ในใฆใฎๆง‹้€ ใฎ SMILES ใ‚’ใ‚ณใƒ”ใƒผใ—ใพใ—ใŸ", + "116": "Si", + "117": "ไปปๆ„ใฎ็ตๅˆ", + "118": "ๅ˜็ตๅˆใพใŸใฏไบŒ้‡็ตๅˆ", + "119": "ๅ˜็ตๅˆใพใŸใฏ่Šณ้ฆ™ๆ—็ตๅˆ", + "120": "ไบŒ้‡็ตๅˆใพใŸใฏ่Šณ้ฆ™ๆ—็ตๅˆ", + "121": "็’ฐใพใŸใฏ้Ž–", + "122": "็’ฐๅ†…", + "123": "้Ž–ๅ†…", + "124": "ไปปๆ„ใฎๅŽŸๅญ(A)", + "125": "ไปปๆ„ใฎใƒ˜ใƒ†ใƒญๅŽŸๅญ(Q)", + "126": "ไปปๆ„ใฎใƒใƒญใ‚ฒใƒณ(X)", + "127": "ไปปๆ„ใฎ้‡‘ๅฑž(M)", + "128": "็ตๅˆใฎใƒˆใƒใƒญใ‚ธใƒผใ‚’่จญๅฎš", + "129": "ใ‚ฏใ‚จใƒช็ตๅˆ", + "130": "ๅŽŸๅญใ‚ฏใ‚จใƒชใ‚’่จญๅฎš", + "131": "่Šณ้ฆ™ๆ—", + "132": "่„‚่‚ชๆ—", + "133": "ไธ้ฃฝๅ’Œ", + "134": "ๆใ„ใŸใจใŠใ‚Šใฎ็ฝฎๆ›", + "135": "ๆใ„ใŸใจใŠใ‚Šใฎ็’ฐ็ตๅˆ", + "136": "ๅŽŸๅญใ‚ฏใ‚จใƒชใ‚’่งฃ้™ค", + "137": "ๅŽŸๅญใ‚ฏใ‚จใƒช", + "138": "R ๅŸบใฎๅฎš็พฉ", + "139": "R ๅŸบ", + "140": "ใƒกใƒณใƒใƒผ", + "141": "ๅ„ใƒกใƒณใƒใƒผใ‚’็ตๅˆ็‚น(*)ใคใใฎๅ€‹ๅˆฅใฎๆง‹้€ ใจใ—ใฆๆใ„ใฆใ‹ใ‚‰ใ€ใ“ใฎใƒ€ใ‚คใ‚ขใƒญใ‚ฐใ‚’ใ‚‚ใ†ไธ€ๅบฆ้–‹ใ„ใฆใใ ใ•ใ„ใ€‚", + "142": "ๅ‡บ็พๆ•ฐ", + "143": "ๆฎ‹ใ‚Šใฎ H(็ฝฎๆ›ใ•ใ‚Œใฆใ„ใชใ„ไฝ็ฝฎใฏๆฐด็ด )", + "144": "ๅญ˜ๅœจใ™ใ‚‹ๅ ดๅˆใ€ๆฌกใ‚’้ฉ็”จ", + "145": "ๅฎš็พฉใ‚’ๅ‰Š้™ค", + "146": "ใ‚จใƒผใ‚ธใ‚งใƒณใƒˆ", + "147": "ๆกไปถ", + "148": "ๆถˆๅŽป", + "149": "้ธๆŠžใ—ใŸไธญๅฟƒใ‚’ใ“ใฎใ‚ฐใƒซใƒผใƒ—ใซ่ฟฝๅŠ ", + "150": "ๅ†ใƒใ‚งใƒƒใ‚ฏ", + "151": "ใƒใ‚งใƒƒใ‚ฏไธญ...", + "152": "ไฟฎๆญฃ", + "153": "ใ‚ญใƒฃใƒณใƒใ‚นไธŠใง้ธๆŠž" +} From 741119e76d8436020b42e072c5380220431e9e14 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:32 -0500 Subject: [PATCH 262/279] feat(i18n): translate the stereo, query and analysis strings into Korean (0.6.0) Adds the 154 strings of part06 for ko. --- frontend/src/i18n/locales/ko/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/ko/part06.json diff --git a/frontend/src/i18n/locales/ko/part06.json b/frontend/src/i18n/locales/ko/part06.json new file mode 100644 index 00000000..82f1aa9d --- /dev/null +++ b/frontend/src/i18n/locales/ko/part06.json @@ -0,0 +1,156 @@ +{ + "0": "์ „ํ•˜๋ฅผ ํฌํ•จํ•œ Hill ์ˆœ์„œ, ์•ฝ์–ด๋Š” ํŽผ์ณ์ง„ ์ƒํƒœ", + "1": "ํ‘œ์ค€ ์›์ž๋Ÿ‰(CIAAW ๊ด€๋ก€๊ฐ’)", + "2": "๊ฐ ์›์†Œ์—์„œ ๊ฐ€์žฅ ํ’๋ถ€ํ•œ ๋™์œ„์›์†Œ๋กœ ๊ณ„์‚ฐํ•œ ๋‹จ์ผ๋™์œ„์›์†Œ ์งˆ๋Ÿ‰", + "3": "์ •๋ฐ€ ์งˆ๋Ÿ‰์„ ์ „ํ•˜์˜ ์ ˆ๋Œ“๊ฐ’์œผ๋กœ ๋‚˜๋ˆˆ ๊ฐ’(์ „์ž ์งˆ๋Ÿ‰ ๋ณด์ •)", + "4": "๊ฐ ์›์†Œ์˜ ์งˆ๋Ÿ‰ ๋ฐฑ๋ถ„์œจ(์†Œ์ˆ˜์  ๋‘˜์งธ ์ž๋ฆฌ)", + "5": "์›์ž ๊ธฐ์—ฌ๋„(Wildman and Crippen 1999)", + "6": "์œ„์ƒ ๊ทน์„ฑ ํ‘œ๋ฉด์ , N ๋ฐ O ์กฐ๊ฐ(Ertl 2000)", + "7": "๋ชฐ ๊ตด์ ˆ๋ฅ ", + "8": "์ˆ˜์†Œ ๊ฒฐํ•ฉ ์ฃผ๊ฐœ", + "9": "Lipinski ๊ณ„์ˆ˜: N-H ๋ฐ O-H ๊ธฐ", + "10": "์ˆ˜์†Œ ๊ฒฐํ•ฉ ๋ฐ›๊ฐœ", + "11": "Lipinski ๊ณ„์ˆ˜: N ๋ฐ O ์›์ž", + "12": "ํšŒ์ „ ๊ฐ€๋Šฅ ๊ฒฐํ•ฉ", + "13": "๋ง๋‹จ์ด ์•„๋‹Œ ๋ฌด๊ฑฐ์šด ์›์ž ์‚ฌ์ด์˜ ๋น„๊ณ ๋ฆฌ ๋‹จ์ผ ๊ฒฐํ•ฉ(์•„๋งˆ์ด๋“œ C-N ์ œ์™ธ)", + "14": "Lipinski 5์˜ ๋ฒ•์น™", + "15": "MW 500 ์ดํ•˜, cLogP 5 ์ดํ•˜, ์ฃผ๊ฐœ 5 ์ดํ•˜, ๋ฐ›๊ฐœ 10 ์ดํ•˜", + "16": "HBD", + "17": "HBA", + "18": "ํ†ต๊ณผ(์œ„๋ฐ˜ 0๊ฑด)", + "19": "๋จผ์ € ์›์ž๋ฅผ ํ•˜๋‚˜ ์ด์ƒ ์„ ํƒํ•˜์„ธ์š”", + "20": "๋จผ์ € ๊ฒฐํ•ฉ์„ ํ•˜๋‚˜ ์ด์ƒ ์„ ํƒํ•˜์„ธ์š”", + "21": "์ถ”๊ฐ€ํ•  ์•”์‹œ์  ์ˆ˜์†Œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", + "22": "์ œ๊ฑฐํ•  ๋ช…์‹œ์  ์ˆ˜์†Œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", + "23": "ํŽผ์น  Ph ๋˜๋Š” OTs ๊ฐ™์€ ์•ฝ์–ด๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", + "24": "์ค„์ผ ํ•œ ๊ตฌ์กฐ์˜ ํ•œ ๊ธฐ์— ์†ํ•œ ์›์ž๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", + "25": "์ค„์ผ ๊ธฐ๋ฅผ ์„ ํƒํ•˜๋˜, ๊ทธ๊ฒƒ์ด ๋ถ™์–ด ์žˆ๋Š” ์›์ž๋Š” ์ œ์™ธํ•˜์„ธ์š”.", + "26": "์ค„์ด๊ธฐ", + "27": "์„ ํƒํ•œ ์›์ž์— ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ ์•ฝ์–ด๋ฅผ ๊ณ ๋ฅด๊ฑฐ๋‚˜ ์ƒˆ ๋ ˆ์ด๋ธ”์„ ์ž…๋ ฅํ•˜์„ธ์š”.", + "28": "์ž…์ฒด ๊ทธ๋ฃน ์„ค์ •", + "29": "์ž…์ฒด ๊ทธ๋ฃน ์ง€์šฐ๊ธฐ", + "30": "์›์ž ๋ชฉ๋ก ์„ค์ •", + "31": "์›์ž ๋ชฉ๋ก ์ง€์šฐ๊ธฐ", + "32": "์ฟผ๋ฆฌ ๊ฒฐํ•ฉ ์„ค์ •", + "33": "๊ฒฐํ•ฉ ์ฟผ๋ฆฌ ์ง€์šฐ๊ธฐ", + "34": "R ๊ธฐ๋ฅผ ๊ฐ€์ง„ ์›์ž๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", + "35": "์—ฐ๊ฒฐ์  1๊ฐœ", + "36": "R ๊ธฐ ์ •์˜", + "37": "R ๊ธฐ ์ •์˜ ์ œ๊ฑฐ", + "38": "์๊ธฐ ์ง€์ •", + "39": "์๊ธฐ๊ฐ€ ์ด๋ฏธ ์ž…์ฒด ์ค‘์‹ฌ๊ณผ ์ผ์น˜ํ•ฉ๋‹ˆ๋‹ค.", + "40": "์„ ํƒํ•œ ๊ตฌ์กฐ", + "41": "์ด ํŽ˜์ด์ง€์˜ ๋ชจ๋“  ๊ตฌ์กฐ", + "42": "๊ตฌ์กฐ ์ˆ˜์ •", + "43": "๋ถ„์„ํ•  ๊ตฌ์กฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", + "44": "๋ถ„์„ ๊ฒฐ๊ณผ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค", + "45": "ํด๋ฆฝ๋ณด๋“œ์— ๋ณต์‚ฌํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค", + "46": "๋ถ€๋ถ„ ๊ตฌ์กฐ ์ฐพ๊ธฐ", + "47": "SMARTS", + "48": "๋จผ์ € ์ด ํŽ˜์ด์ง€์—์„œ ๊ฒ€์ƒ‰ํ•  ๊ตฌ์กฐ๋ฅผ ๊ทธ๋ฆฌ์„ธ์š”.", + "49": "์ฒ˜์Œ ๊ฒฐ๊ณผ๋งŒ", + "50": "์ด ํŽ˜์ด์ง€์— ์ผ์น˜ํ•˜๋Š” ํ•ญ๋ชฉ์ด ์—†์Šต๋‹ˆ๋‹ค.", + "51": "๋จผ์ € R ๊ธฐ ์›์ž๊ฐ€ ์žˆ๋Š” ๊ตฌ์กฐ๋ฅผ ๊ทธ๋ฆฌ๊ณ  R ๊ธฐ๋ฅผ ์ •์˜ํ•˜์„ธ์š”.", + "52": "SMARTS๋กœ ์“ธ ๊ตฌ์กฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", + "53": "SMARTS ํŒŒ์ผ ์ €์žฅ์€ 0.7.0์˜ ํŒŒ์ผ ํ˜•์‹๊ณผ ํ•จ๊ป˜ ์ œ๊ณต๋ฉ๋‹ˆ๋‹ค. ๋Œ€์‹  SMARTS๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค.", + "54": "์„ ํƒํ•œ ์›์ž(๋˜๋Š” ํŽ˜์ด์ง€์˜ ๋ชจ๋“  ๊ตฌ์กฐ)์˜ ์•”์‹œ์  ์ˆ˜์†Œ๋ฅผ ๋ชจ๋‘ ์—”์ง„์ด ๋ฐฐ์น˜ํ•˜๋Š” ๋ช…์‹œ์  H ์›์ž๋กœ ๊ทธ๋ฆฌ๋ฉฐ, ์‹คํ–‰ ์ทจ์†Œ ํ•œ ๋ฒˆ์œผ๋กœ ๋˜๋Œ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.", + "55": "์„ ํƒ ์˜์—ญ(๋˜๋Š” ํŽ˜์ด์ง€)์—์„œ ๋ช…์‹œ์  H ์›์ž๋ฅผ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค. ์ž…์ฒด, ๋™์œ„์›์†Œ, ์ „ํ•˜, ๋งต ๋ฒˆํ˜ธ๊ฐ€ ์žˆ๊ฑฐ๋‚˜ ๋‘ ์›์ž๋ฅผ ์ž‡๋Š” ์ˆ˜์†Œ๋Š” ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค.", + "56": "์„ ํƒํ•œ ์•ฝ์–ด ์›์ž(๋˜๋Š” ํŽ˜์ด์ง€์˜ ๋ชจ๋“  ์•ฝ์–ด)๋ฅผ ์ „์ฒด ๊ตฌ์กฐ๋กœ ๋ฐ”๊พธ๊ณ  ์—ฐ๊ฒฐ ๊ฒฐํ•ฉ์„ ๋”ฐ๋ผ ๋ฐฐ์น˜ํ•ฉ๋‹ˆ๋‹ค.", + "57": "์•ฝ์–ด๋กœ ์ค„์ด๊ธฐ...", + "58": "์„ ํƒํ•œ ์›์ž ๊ธฐ๋ฅผ ์‚ฌ์šฉ์ž๊ฐ€ ๊ณ ๋ฅด๊ฑฐ๋‚˜ ์ž…๋ ฅํ•œ ๋ ˆ์ด๋ธ”์ด ๋ถ™์€ ์•ฝ์–ด ์›์ž ํ•˜๋‚˜๋กœ ํ•ฉ์นฉ๋‹ˆ๋‹ค.", + "59": "์ž…์ฒด ์ค‘์‹ฌ๊ณผ ์ž…์ฒด ์ด์ค‘ ๊ฒฐํ•ฉ ์˜†์˜ R, S, E, Z ๋ ˆ์ด๋ธ”์„ ํ‘œ์‹œํ•˜๊ฑฐ๋‚˜ ์ˆจ๊น๋‹ˆ๋‹ค.", + "60": "ํ–ฅ์ƒ๋œ ์ž…์ฒด ๊ทธ๋ฃน ํ‘œ์‹œ", + "61": "์ž…์ฒด ๋ ˆ์ด๋ธ”์ด ์ผœ์ ธ ์žˆ์„ ๋•Œ ์ž…์ฒด ์ค‘์‹ฌ ์˜†์˜ abs, and, or ๊ทธ๋ฃน ๋ ˆ์ด๋ธ”์„ ํ‘œ์‹œํ•˜๊ฑฐ๋‚˜ ์ˆจ๊น๋‹ˆ๋‹ค.", + "62": "์ฟผ๋ฆฌ ๊ธฐ๋Šฅ ํ‘œ์‹œ", + "63": "์บ”๋ฒ„์Šค์˜ ์›์ž ๋ชฉ๋ก, ์ฟผ๋ฆฌ ๊ฒฐํ•ฉ, R ๊ธฐ ํ‘œ์‹œ๋ฅผ ๋ณด์ด๊ฑฐ๋‚˜ ์ˆจ๊น๋‹ˆ๋‹ค.", + "64": "์„ ํƒํ•œ ์ž…์ฒด ์ค‘์‹ฌ์„ ํ–ฅ์ƒ๋œ ์ž…์ฒด ๊ทธ๋ฃน(abs, and n ๋˜๋Š” or n)์— ๋„ฃ์Šต๋‹ˆ๋‹ค. n์„ ์ƒ๋žตํ•˜๋ฉด ์ƒˆ and ๋˜๋Š” or ๊ทธ๋ฃน์ด ๋งŒ๋“ค์–ด์ง‘๋‹ˆ๋‹ค.", + "65": "abs, and ๋˜๋Š” or", + "66": "and ๋ฐ or์˜ ๊ทธ๋ฃน ๋ฒˆํ˜ธ", + "67": "์ ˆ๋Œ€(abs)", + "68": "์ƒˆ AND ๊ทธ๋ฃน", + "69": "์ƒˆ OR ๊ทธ๋ฃน", + "70": "์ž…์ฒด ๊ทธ๋ฃน...", + "71": "์›์ž ๋ชฉ๋ก...", + "72": "์„ ํƒํ•œ ์›์ž๋ฅผ ์ฃผ๊ธฐ์œจํ‘œ์—์„œ ๊ณ ๋ฅธ ์›์ž ๋ชฉ๋ก ๋˜๋Š” ๋น„๋ชฉ๋ก ์ฟผ๋ฆฌ๋กœ ๋ฐ”๊ฟ‰๋‹ˆ๋‹ค.", + "73": "์„ ํƒํ•œ ๊ฒฐํ•ฉ์„ ์ฟผ๋ฆฌ ๊ฒฐํ•ฉ์œผ๋กœ ๋งŒ๋“ญ๋‹ˆ๋‹ค: any, single_or_double, single_or_aromatic ๋˜๋Š” double_or_aromatic. query๋ฅผ ์ƒ๋žตํ•˜๋ฉด ์ง€์›๋‹ˆ๋‹ค.", + "74": "์ฟผ๋ฆฌ ๊ฒฐํ•ฉ ์œ ํ˜•", + "75": "R ๊ธฐ ์ •์˜...", + "76": "์„ ํƒํ•œ ์›์ž๋ฅผ R ๊ธฐ ๋ ˆ์ด๋ธ”๋กœ ๋งŒ๋“ค๊ณ  ๊ตฌ์„ฑ์›, ์ถœํ˜„ ํšŸ์ˆ˜, ๋‚˜๋จธ์ง€ H, if-then ์กฐ๊ฑด์„ ์ •์˜ํ•ฉ๋‹ˆ๋‹ค.", + "77": "์„ ํƒ ์˜์—ญ(๋˜๋Š” ํŽ˜์ด์ง€)์˜ ์ž…์ฒด ์ค‘์‹ฌ์„ ๋ชจํ˜ธํ•˜์ง€ ์•Š๊ฒŒ ๋‚˜ํƒ€๋‚ด๋Š” ์๊ธฐ ๊ฒฐํ•ฉ๊ณผ ์ ์„  ๊ฒฐํ•ฉ์„ ์—”์ง„์ด ๊ณ ๋ฅด๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค.", + "78": "์„ ํƒ ์˜์—ญ(๋˜๋Š” ํŽ˜์ด์ง€)์˜ ์›์ž๊ฐ€, ์ž…์ฒด, ๊ธฐํ•˜, ๋ ˆ์ด๋ธ” ๋ฌธ์ œ๋ฅผ ํŒจ๋„์— ๋‚˜์—ดํ•˜๋ฉฐ, ํ–‰์„ ๋ˆ„๋ฅด๋ฉด ํ•ด๋‹น ์›์ž๊ฐ€ ์„ ํƒ๋ฉ๋‹ˆ๋‹ค.", + "79": "์„ ํƒ ์˜์—ญ ๋˜๋Š” ํŽ˜์ด์ง€์˜ ๊ณ„์‚ฐ๋œ ์„ฑ์งˆ์ด ๋‹ด๊ธด ๋ถ„์„ ํŒจ๋„์„ ์—ฝ๋‹ˆ๋‹ค.", + "80": "๋ถ„์ž์‹, ์งˆ๋Ÿ‰, ์›์†Œ ๋ถ„์„, ๊ณ„์‚ฐ๋œ ์„ฑ์งˆ๊ณผ ๊ทธ ๋ฐฉ๋ฒ•์„ ํ…์ŠคํŠธ๋กœ ๋ณต์‚ฌํ•ฉ๋‹ˆ๋‹ค.", + "81": "๋ถ€๋ถ„ ๊ตฌ์กฐ ์ฐพ๊ธฐ...", + "82": "ํŽ˜์ด์ง€์˜ ๋‹ค๋ฅธ ๊ตฌ์กฐ์—์„œ ์„ ํƒํ•œ ์›์ž(๋˜๋Š” SMARTS ํŒจํ„ด)์™€ ์ผ์น˜ํ•˜๋Š” ๋ถ€๋ถ„์„ ๋ชจ๋‘ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค.", + "83": "R ๊ธฐ ์—ด๊ฑฐ...", + "84": "์„ ํƒํ•œ Markush ๊ณจ๊ฒฉ(๋˜๋Š” ํŽ˜์ด์ง€์˜ ์ฒซ ๋ฒˆ์งธ ๊ณจ๊ฒฉ)์ด ๋‚˜ํƒ€๋‚ด๋Š” ๋ชจ๋“  ๊ตฌ์กฐ๋ฅผ ๋ถ„์ž์‹ ๋ฐ SMILES์™€ ํ•จ๊ป˜ ์ตœ๋Œ€ 1000๊ฐœ๊นŒ์ง€ ๋‚˜์—ดํ•ฉ๋‹ˆ๋‹ค. ๋ชฉ๋ก์€ ๋ณต์‚ฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.", + "85": "SMARTS๋กœ ๋ณต์‚ฌ", + "86": "์„ ํƒํ•œ ์›์ž(๋˜๋Š” ํŽ˜์ด์ง€์˜ ๋ชจ๋“  ๊ตฌ์กฐ)๋ฅผ ์›์ž ๋ชฉ๋ก, ์ผ๋ฐ˜ ์›์ž, ์ฟผ๋ฆฌ ๊ฒฐํ•ฉ ๋ฐ ๊ธฐํƒ€ ์ฟผ๋ฆฌ ๊ธฐ๋Šฅ๊ณผ ํ•จ๊ป˜ SMARTS๋กœ ๋ณต์‚ฌํ•ฉ๋‹ˆ๋‹ค.", + "87": "SMARTS ๋‚ด๋ณด๋‚ด๊ธฐ...", + "88": "์„ ํƒํ•œ ์›์ž(๋˜๋Š” ํŽ˜์ด์ง€์˜ ๋ชจ๋“  ๊ตฌ์กฐ)๋ฅผ SMARTS ํŒŒ์ผ(.sma)๋กœ ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.", + "89": "ํ–ฅ์ƒ๋œ ์ž…์ฒด", + "90": "์ฟผ๋ฆฌ", + "91": "๊ฐœ์ฒด", + "92": "๋จผ์ € ์—ญํ• ์„ ์ง€์ •ํ•  ๊ตฌ์กฐ ๋˜๋Š” ํ…์ŠคํŠธ๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", + "93": "๋ฐ˜์‘ ์—ญํ•  ์„ค์ •...", + "94": "์„ ํƒํ•œ ๋ฐ˜์‘ ๋‹จ๊ณ„์—์„œ ์„ ํƒํ•œ ๊ตฌ์กฐ ๋˜๋Š” ํ…์ŠคํŠธ์˜ ์—ญํ• (๋ฐ˜์‘๋ฌผ, ์ƒ์„ฑ๋ฌผ, ์—์ด์ „ํŠธ, ์กฐ๊ฑด ๋˜๋Š” ์—†์Œ)์„ ์„ค์ •ํ•˜๊ณ , ๊ทธ ๋‹จ๊ณ„์˜ ์—ญํ• ์„ ์ˆ˜๋™์œผ๋กœ ์„ค์ •ํ•œ ๊ฒƒ์œผ๋กœ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค. ์‹คํ–‰ ์ทจ์†Œ ํ•œ ๋ฒˆ์œผ๋กœ ๋˜๋Œ๋ฆด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. role์„ ์ƒ๋žตํ•˜๋ฉด ๋‹จ๊ณ„์˜ ๊ตฌ์„ฑ์›๊ณผ ์„ ํƒ ํ•ญ๋ชฉ์„ ๋‚˜์—ดํ•˜๋Š” ๋Œ€ํ™”์ƒ์ž๊ฐ€ ์—ด๋ฆฝ๋‹ˆ๋‹ค.", + "95": "๊ฐœ์ฒด์— ์ง€์ •ํ•  ์—ญํ• . ์ƒ๋žตํ•˜๋ฉด ๋Œ€ํ™”์ƒ์ž๊ฐ€ ์—ด๋ฆฝ๋‹ˆ๋‹ค", + "96": "๋ณ€๊ฒฝํ•  ๊ฐœ์ฒด id. ๊ธฐ๋ณธ๊ฐ’์€ ์„ ํƒ ํ•ญ๋ชฉ", + "97": "๋ฐ˜์‘ ์—ญํ• ์„ ์„ค์ •ํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค", + "98": "๋‚˜๋จธ์ง€ H", + "99": "์•ฝ์–ด", + "100": "๋ ˆ์ด๋ธ”", + "101": "๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๊ฒ€์ƒ‰", + "102": "์•ฝ์–ด ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋ ˆ์ด๋ธ”์€ ์ง์ ‘ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.", + "103": "์ผ์น˜ํ•˜๋Š” ์•ฝ์–ด๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. ์ž…๋ ฅํ•œ ๋ ˆ์ด๋ธ”์ด ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.", + "104": "์„ฑ์งˆ", + "105": "์›์ž ๋ชฉ๋ก", + "106": "ํ‘œ์˜ ์›์†Œ๋ฅผ ํด๋ฆญํ•˜์—ฌ ์ถ”๊ฐ€ํ•˜์„ธ์š”.", + "107": "์ฟผ๋ฆฌ ์ง€์šฐ๊ธฐ", + "108": "์ ์šฉ", + "109": "์ œ๊ฑฐ", + "110": "์ฟผ๋ฆฌ ์—†์Œ", + "111": "[M+Na]+", + "112": "๋™์œ„์›์†Œ ํŒจํ„ด", + "113": "R ๊ธฐ ์—ด๊ฑฐ", + "114": "SMILES ๋ณต์‚ฌ", + "115": "๋ชจ๋“  ๊ตฌ์กฐ์˜ SMILES๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค", + "116": "Si", + "117": "๋ชจ๋“  ๊ฒฐํ•ฉ", + "118": "๋‹จ์ผ ๋˜๋Š” ์ด์ค‘", + "119": "๋‹จ์ผ ๋˜๋Š” ๋ฐฉํ–ฅ์กฑ", + "120": "์ด์ค‘ ๋˜๋Š” ๋ฐฉํ–ฅ์กฑ", + "121": "๊ณ ๋ฆฌ ๋˜๋Š” ์‚ฌ์Šฌ", + "122": "๊ณ ๋ฆฌ ์•ˆ", + "123": "์‚ฌ์Šฌ ์•ˆ", + "124": "๋ชจ๋“  ์›์ž(A)", + "125": "๋ชจ๋“  ํ—คํ…Œ๋กœ์›์ž(Q)", + "126": "๋ชจ๋“  ํ• ๋กœ์  (X)", + "127": "๋ชจ๋“  ๊ธˆ์†(M)", + "128": "๊ฒฐํ•ฉ ์œ„์ƒ ์„ค์ •", + "129": "์ฟผ๋ฆฌ ๊ฒฐํ•ฉ", + "130": "์›์ž ์ฟผ๋ฆฌ ์„ค์ •", + "131": "๋ฐฉํ–ฅ์กฑ", + "132": "์ง€๋ฐฉ์กฑ", + "133": "๋ถˆํฌํ™”", + "134": "๊ทธ๋ฆฐ ๋Œ€๋กœ์˜ ์น˜ํ™˜", + "135": "๊ทธ๋ฆฐ ๋Œ€๋กœ์˜ ๊ณ ๋ฆฌ ๊ฒฐํ•ฉ", + "136": "์›์ž ์ฟผ๋ฆฌ ์ง€์šฐ๊ธฐ", + "137": "์›์ž ์ฟผ๋ฆฌ", + "138": "R ๊ธฐ ์ •์˜", + "139": "R ๊ธฐ", + "140": "๊ตฌ์„ฑ์›", + "141": "๊ฐ ๊ตฌ์„ฑ์›์„ ์—ฐ๊ฒฐ์ (*)์ด ์žˆ๋Š” ๋ณ„๋„์˜ ๊ตฌ์กฐ๋กœ ๊ทธ๋ฆฐ ๋‹ค์Œ ์ด ๋Œ€ํ™”์ƒ์ž๋ฅผ ๋‹ค์‹œ ์—ฌ์„ธ์š”.", + "142": "์ถœํ˜„ ํšŸ์ˆ˜", + "143": "๋‚˜๋จธ์ง€ H(์น˜ํ™˜๋˜์ง€ ์•Š์€ ์œ„์น˜๋Š” ์ˆ˜์†Œ)", + "144": "์žˆ์œผ๋ฉด ๋‹ค์Œ ์ ์šฉ", + "145": "์ •์˜ ์ œ๊ฑฐ", + "146": "์—์ด์ „ํŠธ", + "147": "์กฐ๊ฑด", + "148": "์ง€์šฐ๊ธฐ", + "149": "์„ ํƒํ•œ ์ค‘์‹ฌ์„ ์ด ๊ทธ๋ฃน์— ์ถ”๊ฐ€", + "150": "๋‹ค์‹œ ํ™•์ธ", + "151": "ํ™•์ธํ•˜๋Š” ์ค‘...", + "152": "์ˆ˜์ •", + "153": "์บ”๋ฒ„์Šค์—์„œ ์„ ํƒ" +} From fe7e800bfa2b12933d537946bf936693e8d7a54d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:32 -0500 Subject: [PATCH 263/279] feat(i18n): translate the stereo, query and analysis strings into Thai (0.6.0) Adds the 154 strings of part06 for th. --- frontend/src/i18n/locales/th/part06.json | 156 +++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 frontend/src/i18n/locales/th/part06.json diff --git a/frontend/src/i18n/locales/th/part06.json b/frontend/src/i18n/locales/th/part06.json new file mode 100644 index 00000000..635b9eab --- /dev/null +++ b/frontend/src/i18n/locales/th/part06.json @@ -0,0 +1,156 @@ +{ + "0": "เธฅเธณเธ”เธฑเธš Hill เธžเธฃเน‰เธญเธกเธ›เธฃเธฐเธˆเธธ เธ•เธฑเธงเธขเนˆเธญเธ–เธนเธเธ‚เธขเธฒเธขเนเธฅเน‰เธง", + "1": "เธ™เน‰เธณเธซเธ™เธฑเธเธญเธฐเธ•เธญเธกเธกเธฒเธ•เธฃเธเธฒเธ™ (เธ„เนˆเธฒเธ•เธฒเธกเธ‚เน‰เธญเธ•เธเธฅเธ‡เธ‚เธญเธ‡ CIAAW)", + "2": "เธกเธงเธฅเน‚เธกเน‚เธ™เน„เธญเน‚เธ‹เน‚เธ—เธ›เธˆเธฒเธเน„เธญเน‚เธ‹เน‚เธ—เธ›เธ—เธตเนˆเธžเธšเธกเธฒเธเธ—เธตเนˆเธชเธธเธ”เธ‚เธญเธ‡เนเธ•เนˆเธฅเธฐเธ˜เธฒเธ•เธธ", + "3": "เธกเธงเธฅเนเธกเนˆเธ™เธ•เธฃเธ‡เธซเธฒเธฃเธ”เน‰เธงเธขเธ„เนˆเธฒเธชเธฑเธกเธšเธนเธฃเธ“เนŒเธ‚เธญเธ‡เธ›เธฃเธฐเธˆเธธ เนเธเน‰เธ„เนˆเธฒเธกเธงเธฅเธญเธดเน€เธฅเน‡เธเธ•เธฃเธญเธ™เนเธฅเน‰เธง", + "4": "เธฃเน‰เธญเธขเธฅเธฐเน‚เธ”เธขเธกเธงเธฅเธ‚เธญเธ‡เนเธ•เนˆเธฅเธฐเธ˜เธฒเธ•เธธ เธ—เธจเธ™เธดเธขเธกเธชเธญเธ‡เธ•เธณเนเธซเธ™เนˆเธ‡", + "5": "เธเธฒเธฃเธกเธตเธชเนˆเธงเธ™เธฃเนˆเธงเธกเธ‚เธญเธ‡เธญเธฐเธ•เธญเธก (Wildman and Crippen 1999)", + "6": "เธžเธทเน‰เธ™เธ—เธตเนˆเธœเธดเธงเธ‚เธฑเน‰เธงเน€เธŠเธดเธ‡เธ—เธญเธžเธญเน‚เธฅเธขเธต เธชเนˆเธงเธ™ N เนเธฅเธฐ O (Ertl 2000)", + "7": "เน‚เธกเธฅเธฒเธฃเนŒเธฃเธตเนเธŸเธฃเธเธŠเธฑเธ™", + "8": "เธ•เธฑเธงเนƒเธซเน‰เธžเธฑเธ™เธ˜เธฐเน„เธฎเน‚เธ”เธฃเน€เธˆเธ™", + "9": "เธเธฒเธฃเธ™เธฑเธšเนเธšเธš Lipinski: เธซเธกเธนเนˆ N-H เนเธฅเธฐ O-H", + "10": "เธ•เธฑเธงเธฃเธฑเธšเธžเธฑเธ™เธ˜เธฐเน„เธฎเน‚เธ”เธฃเน€เธˆเธ™", + "11": "เธเธฒเธฃเธ™เธฑเธšเนเธšเธš Lipinski: เธญเธฐเธ•เธญเธก N เนเธฅเธฐ O", + "12": "เธžเธฑเธ™เธ˜เธฐเธ—เธตเนˆเธซเธกเธธเธ™เน„เธ”เน‰", + "13": "เธžเธฑเธ™เธ˜เธฐเน€เธ”เธตเนˆเธขเธงเธ™เธญเธเธงเธ‡เธฃเธฐเธซเธงเนˆเธฒเธ‡เธญเธฐเธ•เธญเธกเธซเธ™เธฑเธเธ—เธตเนˆเน„เธกเนˆเนƒเธŠเนˆเธ›เธฅเธฒเธขเธชเธธเธ” เน„เธกเนˆเธฃเธงเธก C-N เธ‚เธญเธ‡เน€เธญเน„เธกเธ”เนŒ", + "14": "เธเธŽเธซเน‰เธฒเธ‚เธญเธ‡ Lipinski", + "15": "MW เน„เธกเนˆเน€เธเธดเธ™ 500, cLogP เน„เธกเนˆเน€เธเธดเธ™ 5, เธ•เธฑเธงเนƒเธซเน‰เน„เธกเนˆเน€เธเธดเธ™ 5, เธ•เธฑเธงเธฃเธฑเธšเน„เธกเนˆเน€เธเธดเธ™ 10", + "16": "HBD", + "17": "HBA", + "18": "เธœเนˆเธฒเธ™ (เธฅเธฐเน€เธกเธดเธ” 0 เธ‚เน‰เธญ)", + "19": "เน€เธฅเธทเธญเธเธญเธฐเธ•เธญเธกเธญเธขเนˆเธฒเธ‡เธ™เน‰เธญเธขเธซเธ™เธถเนˆเธ‡เธญเธฐเธ•เธญเธกเธเนˆเธญเธ™", + "20": "เน€เธฅเธทเธญเธเธžเธฑเธ™เธ˜เธฐเธญเธขเนˆเธฒเธ‡เธ™เน‰เธญเธขเธซเธ™เธถเนˆเธ‡เธžเธฑเธ™เธ˜เธฐเธเนˆเธญเธ™", + "21": "เน„เธกเนˆเธกเธตเน„เธฎเน‚เธ”เธฃเน€เธˆเธ™เน‚เธ”เธขเธ™เธฑเธขเนƒเธซเน‰เน€เธžเธดเนˆเธก", + "22": "เน„เธกเนˆเธกเธตเน„เธฎเน‚เธ”เธฃเน€เธˆเธ™เนเธšเธšเธŠเธฑเธ”เนเธˆเน‰เธ‡เนƒเธซเน‰เน€เธญเธฒเธญเธญเธ", + "23": "เน€เธฅเธทเธญเธเธ•เธฑเธงเธขเนˆเธญ เน€เธŠเนˆเธ™ Ph เธซเธฃเธทเธญ OTs เน€เธžเธทเนˆเธญเธ‚เธขเธฒเธข", + "24": "เน€เธฅเธทเธญเธเธญเธฐเธ•เธญเธกเธ‚เธญเธ‡เธซเธกเธนเนˆเธซเธ™เธถเนˆเธ‡เนƒเธ™เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธซเธ™เธถเนˆเธ‡เน€เธžเธทเนˆเธญเธขเนˆเธญ", + "25": "เน€เธฅเธทเธญเธเธซเธกเธนเนˆเธ—เธตเนˆเธˆเธฐเธขเนˆเธญ เน‚เธ”เธขเน„เธกเนˆเธฃเธงเธกเธญเธฐเธ•เธญเธกเธ—เธตเนˆเธซเธกเธนเนˆเธ™เธฑเน‰เธ™เธ•เนˆเธญเธญเธขเธนเนˆ", + "26": "เธขเนˆเธญ", + "27": "เน€เธฅเธทเธญเธเธ•เธฑเธงเธขเนˆเธญเธˆเธฒเธเธ„เธฅเธฑเธ‡ เธซเธฃเธทเธญเธžเธดเธกเธžเนŒเธ›เน‰เธฒเธขเธเธณเธเธฑเธšเนƒเธซเธกเนˆเนƒเธซเน‰เธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธ", + "28": "เธเธณเธซเธ™เธ”เธเธฅเธธเนˆเธกเธชเน€เธ•เธญเธฃเธดเน‚เธญ", + "29": "เธฅเน‰เธฒเธ‡เธเธฅเธธเนˆเธกเธชเน€เธ•เธญเธฃเธดเน‚เธญ", + "30": "เธเธณเธซเธ™เธ”เธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธก", + "31": "เธฅเน‰เธฒเธ‡เธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธก", + "32": "เธเธณเธซเธ™เธ”เธžเธฑเธ™เธ˜เธฐเน€เธ„เธตเธขเธงเธฃเธต", + "33": "เธฅเน‰เธฒเธ‡เน€เธ„เธตเธขเธงเธฃเธตเธ‚เธญเธ‡เธžเธฑเธ™เธ˜เธฐ", + "34": "เน€เธฅเธทเธญเธเธญเธฐเธ•เธญเธกเธ—เธตเนˆเธกเธตเธซเธกเธนเนˆ R", + "35": "เธˆเธธเธ”เธ•เนˆเธญ 1 เธˆเธธเธ”", + "36": "เธเธณเธซเธ™เธ”เธซเธกเธนเนˆ R", + "37": "เธฅเธšเธ™เธดเธขเธฒเธกเธซเธกเธนเนˆ R", + "38": "เธเธณเธซเธ™เธ”เธžเธฑเธ™เธ˜เธฐเธฅเธดเนˆเธก", + "39": "เธžเธฑเธ™เธ˜เธฐเธฅเธดเนˆเธกเธ•เธฃเธ‡เธเธฑเธšเธจเธนเธ™เธขเนŒเธชเน€เธ•เธญเธฃเธดเน‚เธญเนเธฅเน‰เธง", + "40": "เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธ—เธตเนˆเน€เธฅเธทเธญเธ", + "41": "เธ—เธธเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนƒเธ™เธซเธ™เน‰เธฒเธ™เธตเน‰", + "42": "เนเธเน‰เน„เธ‚เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡", + "43": "เน„เธกเนˆเธกเธตเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนƒเธซเน‰เธงเธดเน€เธ„เธฃเธฒเธฐเธซเนŒ", + "44": "เธ„เธฑเธ”เธฅเธญเธเธœเธฅเธเธฒเธฃเธงเธดเน€เธ„เธฃเธฒเธฐเธซเนŒเนเธฅเน‰เธง", + "45": "เธ„เธฑเธ”เธฅเธญเธเน„เธ›เธขเธฑเธ‡เธ„เธฅเธดเธ›เธšเธญเธฃเนŒเธ”เน„เธกเนˆเน„เธ”เน‰", + "46": "เธ„เน‰เธ™เธซเธฒเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธขเนˆเธญเธข", + "47": "SMARTS", + "48": "เธงเธฒเธ”เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธ—เธตเนˆเธˆเธฐเธ„เน‰เธ™เธซเธฒเนƒเธ™เธซเธ™เน‰เธฒเธ™เธตเน‰เธเนˆเธญเธ™", + "49": "เน€เธ‰เธžเธฒเธฐเธœเธฅเธฅเธฑเธžเธ˜เนŒเนเธฃเธ เน†", + "50": "เน„เธกเนˆเธกเธตเธฃเธฒเธขเธเธฒเธฃเธ—เธตเนˆเธ•เธฃเธ‡เธเธฑเธ™เนƒเธ™เธซเธ™เน‰เธฒเธ™เธตเน‰", + "51": "เธงเธฒเธ”เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธ—เธตเนˆเธกเธตเธญเธฐเธ•เธญเธกเธซเธกเธนเนˆ R เนเธฅเน‰เธงเธเธณเธซเธ™เธ”เธซเธกเธนเนˆ R เธ‚เธญเธ‡เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธ™เธฑเน‰เธ™เธเนˆเธญเธ™", + "52": "เน„เธกเนˆเธกเธตเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนƒเธซเน‰เน€เธ‚เธตเธขเธ™เน€เธ›เน‡เธ™ SMARTS", + "53": "เธเธฒเธฃเธšเธฑเธ™เธ—เธถเธเน„เธŸเธฅเนŒ SMARTS เธˆเธฐเธกเธฒเธžเธฃเน‰เธญเธกเธฃเธนเธ›เนเธšเธšเน„เธŸเธฅเนŒเนƒเธ™ 0.7.0 เธˆเธถเธ‡เธ„เธฑเธ”เธฅเธญเธ SMARTS เนเธ—เธ™", + "54": "เธงเธฒเธ”เน„เธฎเน‚เธ”เธฃเน€เธˆเธ™เน‚เธ”เธขเธ™เธฑเธขเธ—เธธเธเธ•เธฑเธงเธ‚เธญเธ‡เธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ‚เธญเธ‡เธ—เธธเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนƒเธ™เธซเธ™เน‰เธฒ) เน€เธ›เน‡เธ™เธญเธฐเธ•เธญเธก H เนเธšเธšเธŠเธฑเธ”เนเธˆเน‰เธ‡เธ—เธตเนˆเน€เธญเธ™เธˆเธดเธ™เธงเธฒเธ‡เนƒเธซเน‰ เนƒเธ™เธเธฒเธฃเน€เธฅเธดเธเธ—เธณเธซเธ™เธถเนˆเธ‡เธ‚เธฑเน‰เธ™เธ•เธญเธ™", + "55": "เน€เธญเธฒเธญเธฐเธ•เธญเธก H เนเธšเธšเธŠเธฑเธ”เนเธˆเน‰เธ‡เธญเธญเธเธˆเธฒเธเธชเนˆเธงเธ™เธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ—เธฑเน‰เธ‡เธซเธ™เน‰เธฒ) เน‚เธ”เธขเธ„เธ‡เน„เธฎเน‚เธ”เธฃเน€เธˆเธ™เธ—เธตเนˆเธกเธตเธชเน€เธ•เธญเธฃเธดเน‚เธญ เน„เธญเน‚เธ‹เน‚เธ—เธ› เธ›เธฃเธฐเธˆเธธ เธซเธกเธฒเธขเน€เธฅเธ‚เนเธกเธ› เธซเธฃเธทเธญเน€เธŠเธทเนˆเธญเธกเธญเธฐเธ•เธญเธกเธชเธญเธ‡เธญเธฐเธ•เธญเธกเน„เธงเน‰", + "56": "เนเธ—เธ™เธ—เธตเนˆเธญเธฐเธ•เธญเธกเธ•เธฑเธงเธขเนˆเธญเธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ—เธธเธเธ•เธฑเธงเธขเนˆเธญเนƒเธ™เธซเธ™เน‰เธฒ) เธ”เน‰เธงเธขเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เน€เธ•เน‡เธก เน‚เธ”เธขเธˆเธฑเธ”เธงเธฒเธ‡เธ•เธฒเธกเธžเธฑเธ™เธ˜เธฐเธ—เธตเนˆเธ•เนˆเธญเธญเธขเธนเนˆ", + "57": "เธขเนˆเธญเน€เธ›เน‡เธ™เธ•เธฑเธงเธขเนˆเธญ...", + "58": "เธขเธธเธšเธซเธกเธนเนˆเธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธเนƒเธซเน‰เน€เธ›เน‡เธ™เธญเธฐเธ•เธญเธกเธ•เธฑเธงเธขเนˆเธญเธซเธ™เธถเนˆเธ‡เธ•เธฑเธงเธžเธฃเน‰เธญเธกเธ›เน‰เธฒเธขเธเธณเธเธฑเธšเธ—เธตเนˆเธœเธนเน‰เนƒเธŠเน‰เน€เธฅเธทเธญเธเธซเธฃเธทเธญเธžเธดเธกเธžเนŒ", + "59": "เนเธชเธ”เธ‡เธซเธฃเธทเธญเธ‹เนˆเธญเธ™เธ›เน‰เธฒเธข R, S, E เนเธฅเธฐ Z เธ‚เน‰เธฒเธ‡เธจเธนเธ™เธขเนŒเธชเน€เธ•เธญเธฃเธดเน‚เธญเนเธฅเธฐเธžเธฑเธ™เธ˜เธฐเธ„เธนเนˆเธชเน€เธ•เธญเธฃเธดเน‚เธญ", + "60": "เนเธชเธ”เธ‡เธเธฅเธธเนˆเธกเธชเน€เธ•เธญเธฃเธดเน‚เธญเนเธšเธšเธ‚เธขเธฒเธข", + "61": "เนเธชเธ”เธ‡เธซเธฃเธทเธญเธ‹เนˆเธญเธ™เธ›เน‰เธฒเธขเธเธฅเธธเนˆเธก abs, and เนเธฅเธฐ or เธ‚เน‰เธฒเธ‡เธจเธนเธ™เธขเนŒเธชเน€เธ•เธญเธฃเธดเน‚เธญ เธ‚เธ“เธฐเธ—เธตเนˆเธ›เน‰เธฒเธขเธชเน€เธ•เธญเธฃเธดเน‚เธญเน€เธ›เธดเธ”เธญเธขเธนเนˆ", + "62": "เนเธชเธ”เธ‡เธ„เธธเธ“เธชเธกเธšเธฑเธ•เธดเน€เธ„เธตเธขเธงเธฃเธต", + "63": "เนเธชเธ”เธ‡เธซเธฃเธทเธญเธ‹เนˆเธญเธ™เน€เธ„เธฃเธทเนˆเธญเธ‡เธซเธกเธฒเธขเธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธก เธžเธฑเธ™เธ˜เธฐเน€เธ„เธตเธขเธงเธฃเธต เนเธฅเธฐเธซเธกเธนเนˆ R เธšเธ™เธœเธทเธ™เธœเน‰เธฒเนƒเธš", + "64": "เนƒเธชเนˆเธจเธนเธ™เธขเนŒเธชเน€เธ•เธญเธฃเธดเน‚เธญเธ—เธตเนˆเน€เธฅเธทเธญเธเนƒเธ™เธเธฅเธธเนˆเธกเธชเน€เธ•เธญเธฃเธดเน‚เธญเนเธšเธšเธ‚เธขเธฒเธข: abs, and n เธซเธฃเธทเธญ or n เธซเธฒเธเน„เธกเนˆเธฃเธฐเธšเธธ n เธˆเธฐเธชเธฃเน‰เธฒเธ‡เธเธฅเธธเนˆเธก and เธซเธฃเธทเธญ or เนƒเธซเธกเนˆ", + "65": "abs, and เธซเธฃเธทเธญ or", + "66": "เธซเธกเธฒเธขเน€เธฅเธ‚เธเธฅเธธเนˆเธกเธชเธณเธซเธฃเธฑเธš and เนเธฅเธฐ or", + "67": "เธชเธฑเธกเธšเธนเธฃเธ“เนŒ (abs)", + "68": "เธเธฅเธธเนˆเธก AND เนƒเธซเธกเนˆ", + "69": "เธเธฅเธธเนˆเธก OR เนƒเธซเธกเนˆ", + "70": "เธเธฅเธธเนˆเธกเธชเน€เธ•เธญเธฃเธดเน‚เธญ...", + "71": "เธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธก...", + "72": "เน€เธ›เธฅเธตเนˆเธขเธ™เธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธเนƒเธซเน‰เน€เธ›เน‡เธ™เน€เธ„เธตเธขเธงเธฃเธตเนเธšเธšเธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธกเธซเธฃเธทเธญเนเธšเธšเน„เธกเนˆเนƒเธŠเนˆเธฃเธฒเธขเธเธฒเธฃ เธ—เธตเนˆเน€เธฅเธทเธญเธเธˆเธฒเธเธ•เธฒเธฃเธฒเธ‡เธ˜เธฒเธ•เธธ", + "73": "เธ—เธณเนƒเธซเน‰เธžเธฑเธ™เธ˜เธฐเธ—เธตเนˆเน€เธฅเธทเธญเธเน€เธ›เน‡เธ™เธžเธฑเธ™เธ˜เธฐเน€เธ„เธตเธขเธงเธฃเธต: any, single_or_double, single_or_aromatic เธซเธฃเธทเธญ double_or_aromatic เธซเธฒเธเน„เธกเนˆเธฃเธฐเธšเธธ query เธˆเธฐเธฅเน‰เธฒเธ‡เธ„เนˆเธฒ", + "74": "เธŠเธ™เธดเธ”เธ‚เธญเธ‡เธžเธฑเธ™เธ˜เธฐเน€เธ„เธตเธขเธงเธฃเธต", + "75": "เธเธณเธซเธ™เธ”เธซเธกเธนเนˆ R...", + "76": "เธ—เธณเนƒเธซเน‰เธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธเน€เธ›เน‡เธ™เธ›เน‰เธฒเธขเธเธณเธเธฑเธšเธซเธกเธนเนˆ R เนเธฅเธฐเธเธณเธซเธ™เธ”เธชเธกเธฒเธŠเธดเธ เธˆเธณเธ™เธงเธ™เธ„เธฃเธฑเน‰เธ‡เธ—เธตเนˆเธ›เธฃเธฒเธเธ H เธชเนˆเธงเธ™เธ—เธตเนˆเน€เธซเธฅเธทเธญ เนเธฅเธฐเน€เธ‡เธทเนˆเธญเธ™เน„เธ‚ if-then", + "77": "เนƒเธซเน‰เน€เธญเธ™เธˆเธดเธ™เน€เธฅเธทเธญเธเธžเธฑเธ™เธ˜เธฐเธฅเธดเนˆเธกเนเธฅเธฐเธžเธฑเธ™เธ˜เธฐเธ›เธฃเธฐเธ—เธตเนˆเธฃเธฐเธšเธธเธจเธนเธ™เธขเนŒเธชเน€เธ•เธญเธฃเธดเน‚เธญเธ‚เธญเธ‡เธชเนˆเธงเธ™เธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ—เธฑเน‰เธ‡เธซเธ™เน‰เธฒ) เน„เธ”เน‰เธญเธขเนˆเธฒเธ‡เน„เธกเนˆเธเธณเธเธงเธก", + "78": "เนเธชเธ”เธ‡เธฃเธฒเธขเธเธฒเธฃเธ›เธฑเธเธซเธฒเน€เธฃเธทเนˆเธญเธ‡เน€เธงเน€เธฅเธ™เธ‹เนŒ เธชเน€เธ•เธญเธฃเธดเน‚เธญ เน€เธฃเธ‚เธฒเธ„เธ“เธดเธ• เนเธฅเธฐเธ›เน‰เธฒเธขเธเธณเธเธฑเธšเธ‚เธญเธ‡เธชเนˆเธงเธ™เธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ—เธฑเน‰เธ‡เธซเธ™เน‰เธฒ) เนƒเธ™เนเธœเธ‡เธ—เธตเนˆเธ„เธฅเธดเธเนเธ–เธงเน€เธžเธทเนˆเธญเน€เธฅเธทเธญเธเธญเธฐเธ•เธญเธกเน„เธ”เน‰", + "79": "เน€เธ›เธดเธ”เนเธœเธ‡เธเธฒเธฃเธงเธดเน€เธ„เธฃเธฒเธฐเธซเนŒเธžเธฃเน‰เธญเธกเธชเธกเธšเธฑเธ•เธดเธ—เธตเนˆเธ„เธณเธ™เธงเธ“เน„เธ”เน‰เธ‚เธญเธ‡เธชเนˆเธงเธ™เธ—เธตเนˆเน€เธฅเธทเธญเธเธซเธฃเธทเธญเธ—เธฑเน‰เธ‡เธซเธ™เน‰เธฒ", + "80": "เธ„เธฑเธ”เธฅเธญเธเธชเธนเธ•เธฃ เธกเธงเธฅ เธเธฒเธฃเธงเธดเน€เธ„เธฃเธฒเธฐเธซเนŒเธ˜เธฒเธ•เธธ เนเธฅเธฐเธชเธกเธšเธฑเธ•เธดเธ—เธตเนˆเธ„เธณเธ™เธงเธ“เน„เธ”เน‰เธžเธฃเน‰เธญเธกเธงเธดเธ˜เธตเธ„เธณเธ™เธงเธ“เน€เธ›เน‡เธ™เธ‚เน‰เธญเธ„เธงเธฒเธก", + "81": "เธ„เน‰เธ™เธซเธฒเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธขเนˆเธญเธข...", + "82": "เน€เธฅเธทเธญเธเธ—เธธเธเธฃเธฒเธขเธเธฒเธฃเธ—เธตเนˆเธ•เธฃเธ‡เธเธฑเธšเธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธฃเธนเธ›เนเธšเธš SMARTS) เนƒเธ™เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธญเธทเนˆเธ™เนƒเธ™เธซเธ™เน‰เธฒ", + "83": "เนเธˆเธเนเธˆเธ‡เธซเธกเธนเนˆ R...", + "84": "เนเธชเธ”เธ‡เธฃเธฒเธขเธเธฒเธฃเธ—เธธเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธ—เธตเนˆเน‚เธ„เธฃเธ‡เธฃเนˆเธฒเธ‡ Markush เธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเน‚เธ„เธฃเธ‡เธฃเนˆเธฒเธ‡เนเธฃเธเนƒเธ™เธซเธ™เน‰เธฒ) เนเธ—เธ™เธญเธขเธนเนˆ เธžเธฃเน‰เธญเธกเธชเธนเธ•เธฃเนเธฅเธฐ SMILES เธชเธนเธ‡เธชเธธเธ” 1000 เธฃเธฒเธขเธเธฒเธฃ เนเธฅเธฐเธ„เธฑเธ”เธฅเธญเธเธฃเธฒเธขเธเธฒเธฃเน„เธ”เน‰", + "85": "เธ„เธฑเธ”เธฅเธญเธเน€เธ›เน‡เธ™ SMARTS", + "86": "เธ„เธฑเธ”เธฅเธญเธเธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ—เธธเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนƒเธ™เธซเธ™เน‰เธฒ) เน€เธ›เน‡เธ™ SMARTS เธžเธฃเน‰เธญเธกเธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธก เธญเธฐเธ•เธญเธกเธ—เธฑเนˆเธงเน„เธ› เธžเธฑเธ™เธ˜เธฐเน€เธ„เธตเธขเธงเธฃเธต เนเธฅเธฐเธ„เธธเธ“เธชเธกเธšเธฑเธ•เธดเน€เธ„เธตเธขเธงเธฃเธตเธญเธทเนˆเธ™ เน†", + "87": "เธชเนˆเธ‡เธญเธญเธ SMARTS...", + "88": "เธšเธฑเธ™เธ—เธถเธเธญเธฐเธ•เธญเธกเธ—เธตเนˆเน€เธฅเธทเธญเธ (เธซเธฃเธทเธญเธ—เธธเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนƒเธ™เธซเธ™เน‰เธฒ) เน€เธ›เน‡เธ™เน„เธŸเธฅเนŒ SMARTS (.sma)", + "89": "เธชเน€เธ•เธญเธฃเธดเน‚เธญเนเธšเธšเธ‚เธขเธฒเธข", + "90": "เน€เธ„เธตเธขเธงเธฃเธต", + "91": "เธงเธฑเธ•เธ–เธธ", + "92": "เน€เธฅเธทเธญเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธซเธฃเธทเธญเธ‚เน‰เธญเธ„เธงเธฒเธกเธ—เธตเนˆเธˆเธฐเธเธณเธซเธ™เธ”เธšเธ—เธšเธฒเธ—เธเนˆเธญเธ™", + "93": "เธเธณเธซเธ™เธ”เธšเธ—เธšเธฒเธ—เนƒเธ™เธ›เธเธดเธเธดเธฃเธดเธขเธฒ...", + "94": "เธเธณเธซเธ™เธ”เธšเธ—เธšเธฒเธ—เธ‚เธญเธ‡เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เธซเธฃเธทเธญเธ‚เน‰เธญเธ„เธงเธฒเธกเธ—เธตเนˆเน€เธฅเธทเธญเธเนƒเธ™เธ‚เธฑเน‰เธ™เธ•เธญเธ™เธ›เธเธดเธเธดเธฃเธดเธขเธฒเธ—เธตเนˆเน€เธฅเธทเธญเธ (เธชเธฒเธฃเธ•เธฑเน‰เธ‡เธ•เน‰เธ™ เธœเธฅเธดเธ•เธ เธฑเธ“เธ‘เนŒ เธ•เธฑเธงเนเธ—เธ™ เน€เธ‡เธทเนˆเธญเธ™เน„เธ‚ เธซเธฃเธทเธญเน„เธกเนˆเธกเธต) เนเธฅเธฐเธ—เธณเน€เธ„เธฃเธทเนˆเธญเธ‡เธซเธกเธฒเธขเธงเนˆเธฒเธšเธ—เธšเธฒเธ—เธ‚เธญเธ‡เธ‚เธฑเน‰เธ™เธ•เธญเธ™เธ™เธฑเน‰เธ™เธเธณเธซเธ™เธ”เธ”เน‰เธงเธขเธกเธทเธญ เนƒเธ™เธเธฒเธฃเน€เธฅเธดเธเธ—เธณเธซเธ™เธถเนˆเธ‡เธ‚เธฑเน‰เธ™เธ•เธญเธ™ เธซเธฒเธเน„เธกเนˆเธฃเธฐเธšเธธ role เธˆเธฐเน€เธ›เธดเธ”เธเธฅเนˆเธญเธ‡เน‚เธ•เน‰เธ•เธญเธšเธ—เธตเนˆเนเธชเธ”เธ‡เธชเธกเธฒเธŠเธดเธเธ‚เธญเธ‡เธ‚เธฑเน‰เธ™เธ•เธญเธ™เนเธฅเธฐเธชเนˆเธงเธ™เธ—เธตเนˆเน€เธฅเธทเธญเธ", + "95": "เธšเธ—เธšเธฒเธ—เธ—เธตเนˆเธˆเธฐเนƒเธซเน‰เธงเธฑเธ•เธ–เธธ เธซเธฒเธเน„เธกเนˆเธฃเธฐเธšเธธเธˆเธฐเน€เธ›เธดเธ”เธเธฅเนˆเธญเธ‡เน‚เธ•เน‰เธ•เธญเธš", + "96": "id เธ‚เธญเธ‡เธงเธฑเธ•เธ–เธธเธ—เธตเนˆเธˆเธฐเน€เธ›เธฅเธตเนˆเธขเธ™ เธ„เนˆเธฒเน€เธฃเธดเนˆเธกเธ•เน‰เธ™เธ„เธทเธญเธชเนˆเธงเธ™เธ—เธตเนˆเน€เธฅเธทเธญเธ", + "97": "เธเธณเธซเธ™เธ”เธšเธ—เธšเธฒเธ—เนƒเธ™เธ›เธเธดเธเธดเธฃเธดเธขเธฒเน„เธกเนˆเน„เธ”เน‰", + "98": "H เธชเนˆเธงเธ™เธ—เธตเนˆเน€เธซเธฅเธทเธญ", + "99": "เธ•เธฑเธงเธขเนˆเธญ", + "100": "เธ›เน‰เธฒเธขเธเธณเธเธฑเธš", + "101": "เธ„เน‰เธ™เธซเธฒเนƒเธ™เธ„เธฅเธฑเธ‡", + "102": "เน‚เธซเธฅเธ”เธ„เธฅเธฑเธ‡เธ•เธฑเธงเธขเนˆเธญเน„เธกเนˆเน„เธ”เน‰ เธ„เธธเธ“เธขเธฑเธ‡เธžเธดเธกเธžเนŒเธ›เน‰เธฒเธขเธเธณเธเธฑเธšเน€เธญเธ‡เน„เธ”เน‰", + "103": "เน„เธกเนˆเธกเธตเธ•เธฑเธงเธขเนˆเธญเธ—เธตเนˆเธ•เธฃเธ‡เธเธฑเธ™ เธฃเธฐเธšเธšเธˆเธฐเนƒเธŠเน‰เธ›เน‰เธฒเธขเธเธณเธเธฑเธšเธ—เธตเนˆเธ„เธธเธ“เธžเธดเธกเธžเนŒเธ•เธฒเธกเธ—เธตเนˆเน€เธ›เน‡เธ™เธญเธขเธนเนˆ", + "104": "เธชเธกเธšเธฑเธ•เธด", + "105": "เธฃเธฒเธขเธเธฒเธฃเธญเธฐเธ•เธญเธก", + "106": "เธ„เธฅเธดเธเธ˜เธฒเธ•เธธเนƒเธ™เธ•เธฒเธฃเธฒเธ‡เน€เธžเธทเนˆเธญเน€เธžเธดเนˆเธก", + "107": "เธฅเน‰เธฒเธ‡เน€เธ„เธตเธขเธงเธฃเธต", + "108": "เนƒเธŠเน‰", + "109": "เธฅเธš", + "110": "เน„เธกเนˆเธกเธตเน€เธ„เธตเธขเธงเธฃเธต", + "111": "[M+Na]+", + "112": "เธฃเธนเธ›เนเธšเธšเน„เธญเน‚เธ‹เน‚เธ—เธ›", + "113": "เนเธˆเธเนเธˆเธ‡เธซเธกเธนเนˆ R", + "114": "เธ„เธฑเธ”เธฅเธญเธ SMILES", + "115": "เธ„เธฑเธ”เธฅเธญเธ SMILES เธ‚เธญเธ‡เธ—เธธเธเน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนเธฅเน‰เธง", + "116": "Si", + "117": "เธžเธฑเธ™เธ˜เธฐเนƒเธ”เธเน‡เน„เธ”เน‰", + "118": "เน€เธ”เธตเนˆเธขเธงเธซเธฃเธทเธญเธ„เธนเนˆ", + "119": "เน€เธ”เธตเนˆเธขเธงเธซเธฃเธทเธญเธญเธฐเน‚เธฃเธกเธฒเธ•เธดเธ", + "120": "เธ„เธนเนˆเธซเธฃเธทเธญเธญเธฐเน‚เธฃเธกเธฒเธ•เธดเธ", + "121": "เธงเธ‡เธซเธฃเธทเธญเน‚เธ‹เนˆ", + "122": "เนƒเธ™เธงเธ‡", + "123": "เนƒเธ™เน‚เธ‹เนˆ", + "124": "เธญเธฐเธ•เธญเธกเนƒเธ”เธเน‡เน„เธ”เน‰ (A)", + "125": "เน€เธฎเน€เธ—เธญเน‚เธฃเธญเธฐเธ•เธญเธกเนƒเธ”เธเน‡เน„เธ”เน‰ (Q)", + "126": "เธฎเธฒเน‚เธฅเน€เธˆเธ™เนƒเธ”เธเน‡เน„เธ”เน‰ (X)", + "127": "เน‚เธฅเธซเธฐเนƒเธ”เธเน‡เน„เธ”เน‰ (M)", + "128": "เธเธณเธซเธ™เธ”เธ—เธญเธžเธญเน‚เธฅเธขเธตเธ‚เธญเธ‡เธžเธฑเธ™เธ˜เธฐ", + "129": "เธžเธฑเธ™เธ˜เธฐเน€เธ„เธตเธขเธงเธฃเธต", + "130": "เธเธณเธซเธ™เธ”เน€เธ„เธตเธขเธงเธฃเธตเธ‚เธญเธ‡เธญเธฐเธ•เธญเธก", + "131": "เธญเธฐเน‚เธฃเธกเธฒเธ•เธดเธ", + "132": "เธญเธฐเธฅเธดเธŸเธฒเธ•เธดเธ", + "133": "เน„เธกเนˆเธญเธดเนˆเธกเธ•เธฑเธง", + "134": "เธเธฒเธฃเนเธ—เธ™เธ—เธตเนˆเธ•เธฒเธกเธ—เธตเนˆเธงเธฒเธ”", + "135": "เธžเธฑเธ™เธ˜เธฐเนƒเธ™เธงเธ‡เธ•เธฒเธกเธ—เธตเนˆเธงเธฒเธ”", + "136": "เธฅเน‰เธฒเธ‡เน€เธ„เธตเธขเธงเธฃเธตเธ‚เธญเธ‡เธญเธฐเธ•เธญเธก", + "137": "เน€เธ„เธตเธขเธงเธฃเธตเธ‚เธญเธ‡เธญเธฐเธ•เธญเธก", + "138": "เธ™เธดเธขเธฒเธกเธซเธกเธนเนˆ R", + "139": "เธซเธกเธนเนˆ R", + "140": "เธชเธกเธฒเธŠเธดเธ", + "141": "เธงเธฒเธ”เธชเธกเธฒเธŠเธดเธเนเธ•เนˆเธฅเธฐเธ•เธฑเธงเน€เธ›เน‡เธ™เน‚เธ„เธฃเธ‡เธชเธฃเน‰เธฒเธ‡เนเธขเธเธ—เธตเนˆเธกเธตเธˆเธธเธ”เธ•เนˆเธญ (*) เนเธฅเน‰เธงเน€เธ›เธดเธ”เธเธฅเนˆเธญเธ‡เน‚เธ•เน‰เธ•เธญเธšเธ™เธตเน‰เธญเธตเธเธ„เธฃเธฑเน‰เธ‡", + "142": "เธˆเธณเธ™เธงเธ™เธ„เธฃเธฑเน‰เธ‡เธ—เธตเนˆเธ›เธฃเธฒเธเธ", + "143": "H เธชเนˆเธงเธ™เธ—เธตเนˆเน€เธซเธฅเธทเธญ (เธ•เธณเนเธซเธ™เนˆเธ‡เธ—เธตเนˆเน„เธกเนˆเธ–เธนเธเนเธ—เธ™เธ—เธตเนˆเน€เธ›เน‡เธ™เน„เธฎเน‚เธ”เธฃเน€เธˆเธ™)", + "144": "เธ–เน‰เธฒเธกเธต เนƒเธซเน‰", + "145": "เธฅเธšเธ™เธดเธขเธฒเธก", + "146": "เธ•เธฑเธงเนเธ—เธ™", + "147": "เน€เธ‡เธทเนˆเธญเธ™เน„เธ‚", + "148": "เธฅเน‰เธฒเธ‡", + "149": "เน€เธžเธดเนˆเธกเธจเธนเธ™เธขเนŒเธ—เธตเนˆเน€เธฅเธทเธญเธเนƒเธ™เธเธฅเธธเนˆเธกเธ™เธตเน‰", + "150": "เธ•เธฃเธงเธˆเธชเธญเธšเธญเธตเธเธ„เธฃเธฑเน‰เธ‡", + "151": "เธเธณเธฅเธฑเธ‡เธ•เธฃเธงเธˆเธชเธญเธš...", + "152": "เนเธเน‰เน„เธ‚", + "153": "เน€เธฅเธทเธญเธเธšเธ™เธœเธทเธ™เธœเน‰เธฒเนƒเธš" +} From 3c26f7cabebf8600dbf3ba86a6a2c2a35b9ba609 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:54:12 -0500 Subject: [PATCH 264/279] docs(changelog): add the 0.6.0 entry for stereo, queries and analysis (0.6.0) Records what phase 6 brings, what moved in the menus, the desktop build and salt valence fixes, and the gaps left for later versions. --- CHANGELOG.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97018112..41a7b083 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,63 @@ Versions follow `v*.*.*` with dots. Dates are US Eastern. +## 0.6.0 ยท 2026-12-03 + +Stereo, queries and analysis: FormChem now reads and edits stereochemistry in depth, draws query structures and R-groups, and computes properties, structure checks and isotope patterns with the method behind every number. + +### New + +- (R) and (S), (r) and (s), and (E) and (Z) labels are worked out by the engine with the new CIP rules, including pseudo-asymmetric centres and isotopes such as a CHD centre. View > Show Stereochemistry draws them under the atom or beside the bond. +- Enhanced stereo groups: Structure > Enhanced Stereo puts the selected centres into an absolute, AND or OR group, and Stereo Group... opens a small popover with the group number and the groups already in the drawing. View > Show Enhanced Stereo Groups labels them abs, and1 or or2, in colour if you like. The chiral flag (absolute, relative or racemic) shows under the structure. +- Structure > Assign Wedges redraws the wedges and hashes of the stereocentres the way the chemistry reads them, with one wedge per centre placed on a bond outside the ring where possible. +- Abbreviations: a library of 106 (alkyl, aryl, protecting groups, silyl and sulfonyl groups, functional groups). Contract Abbreviation... turns the selected group into a label such as CO2H or OTs, picked from the library or typed, and Expand Abbreviation puts the atoms back where they were, with their old ids. Your own abbreviations go in `abbreviations.json` in the FormChem data folder. +- Add Explicit Hydrogens and Remove Explicit Hydrogens, spread into the open space around each atom. Hydrogens that carry stereo, an isotope, a charge or a map number are kept. +- Query structures: Atom List... picks elements from a periodic table, as "any of these" or "none of these". The Query menu and the atom and bond right-click menus set any atom (A), any heteroatom (Q), any halogen (X), any metal (M), aromatic or aliphatic, unsaturated, substitution and ring bonds as drawn, and query bonds (any, single or double, single or aromatic, double or aromatic, in a ring or in a chain). Query features are drawn as small purple tags (View > Show Query Features). +- R-groups and Markush structures: Define R-Group... turns an atom into R1, R2 and so on, with its members, occurrence (such as 1, 1-3 or >0), rest H and an if-then condition. Enumerate R-Groups... lists every structure the definition stands for, with its SMILES and formula, and copies them. +- Edit > Find Substructure... finds a SMARTS pattern, or the atoms you selected, in every structure on the page and selects the matches. Copy as SMARTS and Export SMARTS write the selection or a query structure as SMARTS. +- The Analysis panel has a Properties section: formula, molecular weight, exact mass, m/z, elemental analysis, cLogP, TPSA, molar refractivity, H-bond donors and acceptors, rotatable bonds and the Lipinski rule of five. Hover a row to see the method behind it, such as Crippen's cLogP with its typical error. Agents also get rings, fraction Csp3, stereocentres and the Veber rules. +- The isotope pattern of the selection is drawn as a stick plot in the Analysis panel, with the monoisotopic mass and the m/z of [M+H]+, [M+Na]+ and [M-H]-. Copy Analysis puts every value with its method and the peaks on the clipboard. +- Check Structure opens a panel that lists errors, warnings and notes with a code for each (valence, unusual charges, misplaced or ambiguous wedges, undefined stereocentres and double bonds, overlapping atoms, crossing bonds, unusual bond lengths, uncommon isotopes, R-group gaps and more). Click a row to select its atoms; Fix repairs wedges or expands an abbreviation as one undo step; Check Again keeps the list in place. +- Reaction > Set Reaction Roles... lists the members of the selected step and the selected structures and text, each with a role (reactant, product, agent, condition or none). Apply changes the roles as one undo step and marks them as set by hand, so Perceive Reactions keeps them. +- Molfiles in V3000 carry query atoms and bonds, enhanced stereo groups and R-group definitions in and out. +- Agents get four analysis tools: `properties`, `check_structure`, `stereo` and `substructure`. The new chemistry commands (hydrogens, abbreviations, wedges, stereo groups, atom lists, R-groups, reaction roles, SMARTS) also run through `run_command`. + +### Improved + +- The stereo and query marks find the free side of an atom and turn aside when a neighbouring label is in the way. +- Every new menu item, dialog, panel and message is translated into all 25 languages. + +### Changed + +- The Structure menu now holds the abbreviation, hydrogen, wedge, Enhanced Stereo and Query commands. Show Stereochemistry moved to the View menu, and Compute Properties and Copy Analysis are in the Analysis menu. +- Check Structure is a panel that stays open while you work instead of a dialog. +- The Analysis panel's formula, masses and elemental analysis now come from the engine, with their methods; they are worked out only while the panel is open. +- A molfile whose chiral flag is 0 opens with its stereocentres absolute, as most drawing programs and databases mean it, rather than as a racemate. + +### Fixed + +- The desktop build stopped with "the Tauri CLI did not install", because the window's packages never listed the Tauri CLI. It is now pinned at 2.12.6, matching the Tauri crate 2.12, and the message says what to check. +- `./build_app` left the template library out of the engine it froze, so Insert > Template was empty in a desktop app built that way. +- Sodium and other metal cations in salts, such as Na+, were reported as valence errors. +- Query atoms (A, Q, X, M and atom lists) and a bare `*` attachment point were reported as unknown labels. +- The Analysis panel's formula counted deuterium as hydrogen. + +### Known issues + +- Allene axial chirality and atropisomers (such as a hindered biaryl) are not perceived, so they get no label. +- Link nodes and variable attachment (a substituent on any position of a ring) are not built yet. +- A SMARTS pattern with aromatic atoms brought in as a drawing shows its ring with single bonds, although it matches aromatic rings. +- In the desktop app Export SMARTS copies the SMARTS to the clipboard instead of saving a file, until the file formats arrive in 0.7.0. +- The macOS native menu with the new Structure and View items was not run in this build. +- Enumerate R-Groups can count more structures than it lists, because the count is taken before duplicates and if-then conditions are removed. + +### Under the hood + +- Enhanced stereo groups and the chiral flag go into RDKit with the structure, so SMILES, CXSMILES and the derived cache carry them. +- The engine has new analysis routes under `/api/analysis` (properties, CIP, structure check, stereo groups, wedges, abbreviations, hydrogens, SMARTS, substructure search, V3000 query molfiles, Markush enumeration and the isotope pattern). Each command that changes the drawing returns one transaction for the window to commit as one undo step. They are documented in `docs/ANALYSIS.md`. +- The canvas draws stereo, enhanced group and query marks through one keyed layer, so a change patches only its own marks. +- The drawing format gains SMARTS atom queries, R-group attachment atoms, the expansion's library source and the chemistry of the chiral flag. + ## 0.5.0 ยท 2026-12-03 Reactions and annotations: draw a scheme with arrows, plus signs and conditions, and FormChem reads it as a reaction, maps its atoms, checks its balance and works out the amounts. From bfad448827622b950fe5433ecd0b056dbe9542a0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:56:12 -0500 Subject: [PATCH 265/279] docs(hashout): log the 0.6.0 analysis services, router, tools and build fixes in the backend log (0.6.0) Entries 78 to 98 keep the reasons phase 6 left in its notes: stereo groups, the chiral flag 0 deviation, queries and V3000, Markush attachment order, the isotope algorithm, and why build_app failed on a fresh Mac. --- backend/HASHOUT_LOG.md | 111 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 109 insertions(+), 2 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 954b29a4..ef31529a 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # backend HASHOUT_LOG -Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.5.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, and from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.6.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, and from 0.6.0 the analysis services (stereo and enhanced stereo, wedges, abbreviations, hydrogens, queries and SMARTS, V3000 query molfiles, Markush, properties, the structure check, the isotope pattern), the analysis router and tools, and the desktop build fixes, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -11,7 +11,7 @@ backend/app/core/ config.py (ports, data dirs, settings store), local startup.py, runtime.py, ids.py backend/app/routers/ system (health, version, capabilities, settings, notices, window key and ticket), live (WebSocket), library, commands, terminal, chat, extensions, mcp, documents (0.3.0, media 0.5.0), chem (0.3.0), - reactions (0.5.0), templates (0.5.0) + reactions (0.5.0), templates (0.5.0), analysis (0.6.0) backend/app/core/files.py safe file names and free names for saves and imports (0.3.0) backend/app/services/ hub.py (client and agent table), bridge.py (window tools over the live channel), library.py, terminal.py, consent.py, claude_code.py, agent_programs.py, agent_lookup.py (vendored), @@ -21,9 +21,11 @@ backend/app/services/ hub.py (client and agent table), bridge.py (window templates.py (the template library, 0.5.0) backend/app/services/chem/ abbrev, convert, perceive, ids, mass, layout, io, derive (RDKit and Indigo, 0.3.0) geometry, reactions, rxnio, scheme, mapping, balance, stoich (reactions, 0.5.0) + stereo, superatom, hydrogens, query, search, v3000, markush, props, check, isotopes (analysis, 0.6.0) backend/app/data/templates/ 206 original templates in nine category files (0.5.0) docs/FORMAT.md the document format, the single source for both languages (0.3.0) docs/REACTIONS.md reaction perception, mapping, balance, stoichiometry and their routes (0.5.0) +docs/ANALYSIS.md stereo, queries, R-groups, properties, the structure check, the isotope pattern and their routes (0.6.0) docs/TEMPLATES.md the template file format and API (0.5.0) backend/requirements*.txt pins for the engine and for the desktop freeze formchem, formchem.bat one dispatcher for install, boot, serve, build, desktop, doctor, clean @@ -110,6 +112,27 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log 75. Four reaction tools on the MCP server ยท routers/mcp.py 76. Wiring the phase 5 routers and the frozen engine ยท app/main.py, setup/freeze_backend, setup/freeze_backend.bat 77. The generated tools reference carries a contents list ยท setup/agents.py tools_text +78. Stereo groups and the chiral flag go into RDKit with the molecule ยท services/chem/convert.py, services/chem/derive.py +79. A molfile chiral flag of 0 reads as absolute ยท services/chem/convert.py from_mol +80. The stereo report, and the stereo the engine does not perceive ยท services/chem/stereo.py report, services/chem/perceive.py +81. Wedges are placed by RDKit for the configuration wanted ยท services/chem/stereo.py rewedge +82. The abbreviation library is data, with the person's file on top ยท services/chem/abbrev.py +83. Contract and expand keep atom ids ยท services/chem/superatom.py, routers/analysis.py _ids_of +84. Explicit hydrogens go into the widest gaps and keep the configuration ยท services/chem/hydrogens.py +85. A query is one RDKit query molecule built from SMARTS primitives ยท services/chem/query.py query_mol +86. SMARTS in and out ยท services/chem/query.py to_smarts, from_smarts +87. Substructure hits come back as ids ยท services/chem/search.py +88. FormChem writes V3000 query molfiles and reads R-group blocks itself ยท services/chem/v3000.py +89. Markush enumeration and the attachment fallback order ยท services/chem/markush.py +90. Every property names its method ยท services/chem/props.py +91. The structure check has codes, severities and named fixes ยท services/chem/check.py +92. Metal cations are not valence errors ยท services/chem/perceive.py _valence +93. Query atoms and bare stars are generics, not unknown labels ยท services/chem/convert.py _query_label, services/chem/v3000.py +94. The isotope pattern is a convolution merged at 0.01 Da ยท services/chem/isotopes.py +95. The analysis router: a fragment or a document in, one transaction out ยท routers/analysis.py, app/main.py +96. Four analysis tools on the MCP server ยท routers/mcp.py +97. build_app names package.json when the Tauri CLI is missing ยท build_app +98. build_app bundles the template library when it freezes the engine ยท build_app ## 1. Ports and the data folder are FormChem's own ยท _v0.1.0 (app/core/config.py) @@ -418,3 +441,87 @@ The reactions and templates routers were written on their own branches and never ## 77. The generated tools reference carries a contents list ยท _v0.5.0 (setup/agents.py tools_text) With ten tools, `.claude/skills/formchem-harness/references/tools.md` grew past 100 lines and the god-tier-skill-creator validator warned D4 (a reference file of 100 lines or more needs a `## Contents` section). The file is generated, so a hand edit would be undone by the next sync and fail `sync --check`; `tools_text` now writes `## Contents` after the opening paragraphs, listing the kinds table, every tool section from the TOOLS list and the resource, so the list follows the server as tools are added. Both packs validate with zero FAIL and zero WARN afterwards. + +## 78. Stereo groups and the chiral flag go into RDKit with the molecule ยท _v0.6.0 (services/chem/convert.py _read_groups, apply_groups, groups_from_mol; services/chem/derive.py content_key) + +`to_mol` reads `stereo_groups` and `chiral` while it builds the molecule (`_read_groups`), and `apply_groups` turns them into RDKit StereoGroups only after stereo perception, so only real centres are grouped; an atom that is not a centre is dropped from its group and reported as `stereo_group_not_centre`, an atom in two groups as `stereo_group_overlap`. An `and` or `or` group without `n` takes the next free number. `chiral` follows FORMAT: `relative` puts the ungrouped centres into one OR group, `racemic` into one AND group, `absolute` (or absent) leaves them absolute. `from_mol` reads groups back from CXSMILES and V3000 collections (`groups_from_mol`). Because the groups now change CXSMILES, `derive.content_key` includes `FRAGMENT_FIELDS` (`chiral`, `stereo_groups`); without it a regroup kept the cached CXSMILES of the old grouping. RDKit canonicalises enhanced stereo: an OR (or AND) group of one centre writes the same CXSMILES for R and S (`C[C@H](N)C(=O)O |o1:1|` both ways), which is right, since or1 means either enantiomer. + +## 79. A molfile chiral flag of 0 reads as absolute ยท _v0.6.0 (services/chem/convert.py from_mol) + +The clean-room spec says a molfile with the chiral flag at 0 holds one AND group (a racemate). PubChem and most drawing programs write 0 for single enantiomers, so following the spec would turn nearly every imported enantiomer racemic. FormChem reads flag 0 as RDKit does: absolute, no groups and no `chiral` field. Flag 1 sets `chiral: "absolute"`. This is a deliberate deviation from the spec. No import warning says so, because the import warnings belong to `io.py`, which this phase did not change. + +## 80. The stereo report, and the stereo the engine does not perceive ยท _v0.6.0 (services/chem/stereo.py report, group_labels; services/chem/perceive.py _cip, not_ez_bonds) + +`stereo.report` returns centres, double bonds and axes with their CIP labels from the new labeller (`CIPLabeler`, the same as derived `cip`), a `state` from `FindPotentialStereo` (`defined`, `undefined`, or `unknown` for a wavy or crossed mark), and the group label per defined centre (`abs`, `and`, `or`; ungrouped centres are `abs`). Perception adds two warnings: `stereo_unknown` (a centre on a wavy bond) and `undefined_double_bond` (a stereogenic double bond that is neither specified nor marked crossed or wavy, usually a substituent drawn on the bond's line). `not_ez_bonds` walks cumulated double bonds and keeps only the middle bond of an odd chain, because an allene's two bonds were reported as undefined E/Z double bonds. Not perceived: allene axial chirality (RDKit's SMILES reader drops the extended tetrahedral mark, and 2025.09 has no allene CIP) and atropisomers from a drawing (RDKit perceives them only with the non-legacy stereo perception from molblocks; the engine runs legacy perception, and a wedge at a biaryl axis gives only `misplaced_wedge`). The 14 supported cases of the AC5.3 table (alanine, glyceraldehyde, carvone, ibuprofen, threonine, tartaric acids, 2-butenes, both pentane-2,3,4-triols with r and s, a CHD centre, CHFClBr) were all right through the route and the window. + +## 81. Wedges are placed by RDKit for the configuration wanted ยท _v0.6.0 (services/chem/stereo.py rewedge, _from_3d, _aim) + +The parity comes from the drawing, from 3D coordinates (`AssignStereochemistryFrom3D` on an added conformer; abbreviations must be expanded first), or from wanted R or S labels (`_aim` flips the chiral tag and relabels with the new CIP labeller, up to four rounds, because labels can depend on each other). The wedge and hash marks on the chosen centres are cleared and RDKit's `WedgeMolBonds` picks bonds on the 2D conformer: it prefers bonds outside rings, bonds to H and to terminal atoms, one wedge per centre. A wedge whose narrow end must move swaps `a` and `b` in the same transaction. Hollow wedges stay hollow, and wavy and crossed bonds are never touched. The result is perceived again; a centre that still disagrees gives `wedge_mismatch`, a label no flip reaches gives `cip_unreachable`. + +## 82. The abbreviation library is data, with the person's file on top ยท _v0.6.0 (services/chem/abbrev.py library, user_entries, match, PREFERRED) + +The built-in table grew from 75 to 106 entries in six categories (alkyl, aryl, protecting group, silyl, sulfonyl, functional), each an attachment SMILES with one `*`. `abbreviations.json` in the data folder adds the person's own, as a list of `{label, smiles, reversed?, category?, prefer?}` or a map of label to the same or to a SMILES string; the SMILES needs exactly one `*` with one bond. User entries win over built-ins, and `"prefer": "abbreviation"` makes a label that is an element symbol read as the abbreviation. The file is re-read when its mtime changes (one stat per lookup), and bad entries are listed in `user_errors` rather than failing the library. A substituent is matched by canonical SMILES with `*` at the attachment and stereo removed; when several labels match, `PREFERRED` picks Pr over nPr, Bu over nBu, Ac over COMe, TBS over TBDMS, CO2H over COOH and Ms over SO2Me. Ac, Pr and Np collide with element symbols (`ELEMENT_COLLISIONS`), so the check reports `label_collides` for them. + +## 83. Contract and expand keep atom ids ยท _v0.6.0 (services/chem/superatom.py contract, expand; routers/analysis.py _ids_of) + +Contract keeps the selected atoms with their ids inside the expansion (coordinates relative to the first attachment atom, the outgoing bond along +x, as FORMAT says), deletes them from the fragment, adds one `*` atom with `label` and `expansion` at the first attachment atom's position and re-points the crossing bonds to it, keeping the bond ids. A wedge that started inside is dropped (`stereo_dropped`), and stereo group entries for removed atoms go too. More than one attachment bond needs a typed label. Expand rotates the stored atoms so +x points from the abbreviation atom to its first neighbour, tries both mirror images and keeps the one with fewer clashes (0.6 bond lengths) against the other atoms; a library label with no expansion record is expanded from the template laid out by `convert.from_mol` at the fragment's median bond length. The abbreviation atom's bonds attach to `attach` in order of its bonds by z then id; extra bonds join the last attachment point with `abbreviation_bonds`. `_ids_of` first counted the ids stored inside expansions as taken, so expand renamed every restored atom; expansion-internal ids are not live document ids, so only expansion keys count now and `superatom.expand` still renames on a real clash. Contract then expand of ibuprofen's CO2H gives back the same three ids at the same coordinates (0.000 pt), and in document mode the expansion record is deleted when no other atom uses it. + +## 84. Explicit hydrogens go into the widest gaps and keep the configuration ยท _v0.6.0 (services/chem/hydrogens.py add_hydrogens, remove_hydrogens, directions) + +Hydrogens are placed at 0.8 bond lengths (`H_LENGTH`), each new one into the gap with the largest share left (`directions`), so a terminal CH3 fans out at 90 degree steps and a CH2 in a chain gets its two H on the open side. Atoms whose label is element-like (OH, NH2) lose the label and the pinned `hydrogens`. If a centre's CIP label would change, its new H bond becomes a hash (or wedge) with the narrow end on the centre; when that cannot hold it, the reply warns `stereo_changed`. Removal keeps an H with an isotope, charge, map number, query, label, radical, any stereo mark or a bond order other than 1, and one that holds a centre's configuration, found by comparing CIP labels before and after, up to three rounds (`hydrogens_kept`). Adding and removing are each one transaction across every fragment asked for. + +## 85. A query is one RDKit query molecule built from SMARTS primitives ยท _v0.6.0 (services/chem/query.py query_mol, atom_smarts, bond_smarts) + +Every atom and bond becomes a SMARTS primitive and the molecule is built from them atom by atom, so search, SMARTS export and the check read one representation. Plain atoms match by element only (no charge, H count or aromaticity constraint unless the atom asks), bonds by drawn order, aromatic bonds as `:`. A list is `[#6,#7]`, a not-list `[!#6&!#7]`, A `!#1`, AH `*`, Q `!#6&!#1`, QH `!#6`, X the halogens, M every element outside a fixed non-metal set (the metalloids B, Si, Ge, As, Sb and Te count as non-metals); `ring_bonds` is `x` (4 means 4 or more), `subst` is `D` (6 or more), "as drawn" (-2) uses the drawing's own count, `unsat` is `$(*=,#,:*)`, `h_min` n is `!H0` to `!H(n-1)`, topology is `@` or `!@`, and the bond queries map through `BOND_QUERY_SMARTS`. Explicit H atoms in a query fold into H counts (`MergeQueryHs`). Chiral tags are copied, so `chirality: true` tells L- from D-alanine. + +## 86. SMARTS in and out ยท _v0.6.0 (services/chem/query.py to_smarts, from_smarts, parse_atom_smarts) + +Export writes the query molecule's SMARTS for a fragment or a subset of its atoms; R-group atoms become `*` (`smarts_rgroups`), stereo groups are not expressed (`smarts_stereo_groups`), abbreviations are expanded first, and "as drawn" counts become the drawn number. Import parses each atom's own SMARTS into the query fields where a primitive maps (element, aromatic, list and not-list, the generic classes, `D`, `x`, `!H`, the unsaturation recursion) and keeps anything else (other recursive SMARTS, `R`, exact `H`, valence and so on) whole in `query.smarts`, with `element` from the SMARTS where it names one (`smarts_opaque`). That field is why FORMAT gained `AtomQuery.smarts`: without it an imported pattern lost meaning on the way in. An implicit SMARTS bond becomes order 1 with `single_or_aromatic` (its SMARTS meaning), so an aromatic ring from SMARTS draws as single bonds although it matches aromatic rings; setting order 1.5 when both ends are aromatic would fix the drawing. Layout is `from_mol` on the parsed molecule at the drawing's bond length. + +## 87. Substructure hits come back as ids ยท _v0.6.0 (services/chem/search.py query_from, substructure) + +The pattern is SMARTS or a drawn query fragment (`query_mol`); targets are a document's fragments (minus the query fragment) or fragments sent with the call. Matches use RDKit's substructure search with `useChirality` from the `chirality` flag, and each hit is reported as the target's atom and bond ids plus a map from query atom id (or SMARTS atom index as a string) to target atom id, so the window selects hits without any index bookkeeping. `max_hits` defaults to 1000 (`MAX_HITS`) and is capped at 100000; `truncated` says when the list stopped. + +## 88. FormChem writes V3000 query molfiles and reads R-group blocks itself ยท _v0.6.0 (services/chem/v3000.py write, read, _decorate, _read_ctab) + +RDKit writes the CTAB and the stereo collections; FormChem then rewrites the atom type (`[C,N]`, `NOT[C,N]`, `A`, `AH`, `Q`, `QH`, `X`, `XH`, `M`, `MH`), appends RBCNT, SUBST, UNSAT, HCOUNT (h_min n as HCOUNT=n, as RDKit reads it), bond types 5 to 8 and TOPO, and inserts RGROUP blocks (RLOGIC with if-then, rest H and occurrence; one CTAB per member with ATTCHPT=1) before M END. `NOT[...]` without a space is the form both RDKit and Indigo read: the spaced form breaks Indigo's reader and a bare spaced form breaks RDKit's. RDKit's molblock reader cannot read RGROUP blocks at all, so `read` splits the blocks itself, gives each CTAB to RDKit with the query types replaced by placeholders, and puts the query fields back by atom and bond order; members come back as their own fragments laid out in rows under the scaffold, with `data.attach` on their attachment atoms. Indigo was used by hand to cross-check the output, not in code. One `v3000_query_lossy` warning names every atom a field could not carry. + +## 89. Markush enumeration and the attachment fallback order ยท _v0.6.0 (services/chem/markush.py describe, member_attachments, _stub_link, enumerate_structures) + +`member_attachments(member, declared)` finds where a member attaches, in FORMAT's order: the definition's `attach` entry for that member, then atoms whose `data.attach` is 1 or 2 (what V3000 import writes), then attachment stubs (a `"*"` atom with no label, no `generic` and exactly one bond, in id order), then the member's first atom. A stub stands for the R-group atom, so `_stub_link` resolves it to its neighbour, which bonds to the scaffold, and the stub is left out of the structure; a declared stub resolves the same way. Occurrence accepts `1`, `1-3`, `>0`, `<3` and comma lists; with `rest_h` false only "every site substituted" is enumerated; `if_then` n requires group n filled whenever this one is. Structures are joined with RDKit `molzip` on atom map numbers and deduplicated by canonical SMILES. `count` is the combinatorial total before if-then filtering and deduplication, so it can exceed the listed structures with `truncated` false. Over 100000 (`HARD_LIMIT`) refuses without `force`, and listing stops at `limit` (default 1000) with `enumeration_truncated`. + +## 90. Every property names its method ยท _v0.6.0 (services/chem/props.py compute, ROWS, LIPINSKI, VEBER) + +Each row carries `method` (the RDKit call, such as `Crippen.MolLogP`, `rdMolDescriptors.CalcTPSA`, `rdMolDescriptors.CalcNumLipinskiHBD`) and `note` (the method in words, such as "Wildman and Crippen 1999 atom contributions; typical error 0.5 to 0.7 log units"), because a number without its method is not citable. Properties are computed on the identifier molecule (abbreviations expanded, private props and explicit H removed, re-sanitised for ring info); labels and R-groups become dummy atoms and are named in an `incomplete` warning. TPSA counts N and O only (`tpsa`, Ertl's default), with S and P in `tpsa_sp`; both the Lipinski counts and RDKit's refined donor and acceptor counts are given. Lipinski passes with at most one violation, as the rule of five is usually applied; Veber is rotatable bonds at most 10 and TPSA at most 140. Rounding: mw 2, exact mass 4, cLogP, MR and TPSA 2, fraction Csp3 3 decimals. A value RDKit could not compute is null with `property_failed`. Acceptance values: ibuprofen cLogP 3.07, TPSA 37.3, MW 206.28; aspirin TPSA 63.6, HBD 1, HBA 4. + +## 91. The structure check has codes, severities and named fixes ยท _v0.6.0 (services/chem/check.py check, SEVERITY, FIX, SKIP) + +The check starts from the derived warnings and valence errors and adds `unusual_charge` (|charge| of 3 or more on a non-metal, carbon at 2 or more, a charged noble gas, F+, an anionic group 1 or 2 metal), `wedge_between_centres`, `ring_double_bond_stereo` (a crossed double bond in a ring under 8), `uncommon_isotope` (a known nuclide with no natural abundance, except the common labels in `COMMON_LABELS`), `crossing_bonds` (skipped over 1500 bonds), `query_feature` (unless the call says the drawing is a query), `label_collides`, and the R-group gaps (`rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `rgroup_unused`, `rgroup_attachment_guessed`). Each code has one severity (`SEVERITY`: error, warning or info) and issues are sorted errors first. A fixable issue names the analysis command that repairs it in `fix` (`wedges` for the wedge codes, `expand` for abbreviation codes) instead of carrying a transaction, so the fix is computed against the drawing as it is when the person clicks. Derived-only noise (`query_ignored`, the InChI remarks) is left out (`SKIP`), and atoms with `ignore_warnings` drop the issues that name only them. + +## 92. Metal cations are not valence errors ยท _v0.6.0 (services/chem/perceive.py _valence) + +RDKit 2025.09 reports `HasValenceViolation` for a bare Na+, so every salt drawn as Na+ and an anion showed a valence error (it predates this phase). For a charged atom the isoelectronic allowed list alone now decides; RDKit's flag still counts for neutral atoms. + +## 93. Query atoms and bare stars are generics, not unknown labels ยท _v0.6.0 (services/chem/convert.py _query_label, _new_atom; services/chem/v3000.py) + +An any-atom carrying an atom list or a generic query class was reported as `unknown_label`, and so was a bare `*`, which FORMAT defines as any atom or an attachment point (every R-group member drawn with a stub showed it). Both now count as generics like R or Hal, shown literally in the formula as `[N,O]` or Q. The V3000 writer had listed one lossy warning per aromatic atom and an unknown-label warning per list atom; it now names all lossy atoms in one warning and stays quiet about atoms that are queries by design. + +## 94. The isotope pattern is a convolution merged at 0.01 Da ยท _v0.6.0 (services/chem/isotopes.py from_counts, pattern, parse_formula; routers/analysis.py isotope routes) + +Per element, the isotope masses and abundances come from RDKit's periodic table (through `mass.isotopes`), raised to the element count by repeated squaring (`_power`) and convolved element by element (`_convolve`). During convolution peaks within 0.001 Da (`FINE`) are merged and those under 1e-7 of the top (`KEEP`) are pruned, which keeps a 5.7 kDa peptide formula to 7 ms. The result is merged within 0.01 Da (`MERGE`, unit resolution with fine structure folded) and cut under 0.1 percent of the base peak (`THRESHOLD`, adjustable 0 to 100 on the route). Atoms with an isotope set count as one fixed mass. A charge removes the electron mass and divides m/z by |z|. Adducts for a neutral species are [M+H]+ (proton 1.007276), [M+Na]+ (Na minus an electron) and [M-H]-; an ion gets only [M]z with its sign. The formula route reads D and T and a charge suffix such as `+` or `2-`, and limits a pattern to 20000 atoms. Checked: CH2Cl2 M+2 63.92 percent, C6H5Br M+2 97.45, C60 M+1 64.9, ibuprofen 206.1307 (100), 207.1341 (14.34), 208.1367 (1.36). The older `mass.isotope_pattern` (entry 50) is unchanged and still feeds `/api/chem/properties`; the Analysis panel's plot reads the new routes. + +## 95. The analysis router: a fragment or a document in, one transaction out ยท _v0.6.0 (routers/analysis.py source, finish, run; app/main.py) + +Every POST takes its structure either stateless (`fragment`, optional `expansions` and `members`) or from an open document (`doc` with `object` or `objects`), in which case expansions and R-group members come from the document and new ids are checked against every id in it. Commands that change the drawing return `tx: {label, ops}` with paths from the document root, for the window to commit as one undo step after checking the fragments did not change while it waited; with `doc` and `apply: true` the engine applies it itself (origin `user`) and adds `applied: {tx, rev}`, and `apply` without `doc` is a 422. Errors match the chem router because the validators are reused (`chem._fragment`, `_expansions`, `_bond_length`, `_num`, `MAX_TEXT`): 422 with a sentence for the person, 404 for an unknown doc or object, 409 when the document refuses, 413 over 20 MB; in a per-fragment read a failing fragment gives `{error}` in its slot instead of failing the call. Routes are async and run chemistry in a worker thread (`asyncio.to_thread`) so `apply` can await the store. The router carries full `/api/analysis/...` paths, so main.py includes it after `reactions` with no prefix. + +## 96. Four analysis tools on the MCP server ยท _v0.6.0 (routers/mcp.py t_properties, t_check_structure, t_stereo, t_substructure, _analysis_source) + +`properties`, `check_structure`, `stereo` and `substructure` are read-only and outside `MUTATING`, so they never ask the person; `doc` may be left out when exactly one drawing is open. They reuse the analysis router's source rules through `_analysis_source`, which imports the router lazily so mcp.py does not load RDKit at import. Each answers text lines for the agent plus `structuredContent` with the same JSON as the route. `substructure` without a pattern is an `isError` that names `smarts` or `query_object`. `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` description now name the reaction and analysis tools and the chemistry commands, which closes the gap noted in entry 75; only the atom and bond tools remain for `DRAWING_FROM` (0.8.0). The server has fourteen tools; `./formchem agents sync` regenerated the tools reference and the manifest. + +## 97. build_app names package.json when the Tauri CLI is missing ยท _v0.6.0 (build_app) + +`frontend/package.json` never listed `@tauri-apps/cli` (frontend log 1 recorded that the build scripts would call the CLI themselves), so on a fresh checkout `npm ci` installed no `tauri` binary and `./build_app` stopped on the owner's Mac with "the Tauri CLI did not install; run ./build_app --reinstall", which a reinstall could never fix. The CLI is now a pinned dev dependency (frontend log 133), and the message says the CLI is not in `frontend/node_modules` and to check that package.json lists `@tauri-apps/cli` in devDependencies before `--reinstall`. The check after it is unchanged: the CLI's major.minor must equal the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.6 against 2.12.7 passes), and each `@tauri-apps/plugin-*` package must share major.minor with its `tauri-plugin-*` crate. `setup/install_desktop` and `desktop_check` needed no change; they already ran `npm install` and compared versions. + +## 98. build_app bundles the template library when it freezes the engine ยท _v0.6.0 (build_app freeze) + +Entry 76 added `backend/app/data/templates` as `templates` data to `setup/freeze_backend` and its `.bat` twin, but `build_app` runs PyInstaller itself and missed it, so a desktop app built with `./build_app` had an empty template library (`templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen). It now passes the same `--add-data`. `build_app.bat` goes through `setup/desktop_build.bat` and `freeze_backend.bat`, so Windows already had it. Not run here: pyinstaller and the Tauri bundle; the owner's run on macOS arm64 with Python 3.14 is the check. From c562b06d96bcae987edaa44523d80fd24195c773 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:57:45 -0500 Subject: [PATCH 266/279] docs(hashout): log the 0.6.0 window modules, marks, commands, dialogs and the Tauri CLI pin in the frontend log (0.6.0) Entries 133 to 148 keep the reasons behind the analysis client, the keyed marks layer, window-side query edits, the check panel, the properties section, reaction roles and the CLI pin rule. --- frontend/HASHOUT_LOG.md | 96 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 2 deletions(-) diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 3898befb..c258b54f 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # frontend HASHOUT_LOG -Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.5.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.6.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands, and from 0.6.0 the analysis client, the chemistry marks layer, the stereo, query, R-group and abbreviation commands and dialogs, the structure check panel, the properties section with the isotope plot, Set Reaction Roles, and the Tauri CLI pin. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -27,9 +27,17 @@ src/app/ also object-commands.ts (z-order, group, align) and src/ui/ also stoich-panel.ts, template-dialog.ts, template-thumb.ts, home-templates.ts src/app/ also documents.ts (DocumentActions), canvas.ts (mountCanvas), canvas-commands.ts src/ui/ also tool-rail.ts +src/engine/analysis-api.ts the only caller of /api/analysis (0.6.0) +src/canvas/render/ also marks-layer.ts, marks-stereo.ts, marks-query.ts (stereo and query marks, 0.6.0); + canvas/marks-options.ts holds their view toggles +src/app/ also chem-commands.ts, chem-edits.ts, analysis-text.ts (0.6.0) +src/chem/reaction-roles.ts the ops behind Set Reaction Roles (0.6.0) +src/ui/ also periodic-grid.ts, atom-list-dialog.ts, rgroup-dialog.ts, abbreviation-dialog.ts, stereo-popover.ts, + query-menus.ts, structure-check.ts, analysis-properties.ts, isotope-plot.ts, markush-dialog.ts, + roles-dialog.ts (0.6.0) public/fonts/ Arimo and Tinos (SIL OFL 1.1) with their licences src/styles/ tokens.css (the only z-index source), base.css, shell.css, canvas.css, canvas-view.css, tool-rail.css, - stoich.css, templates.css + stoich.css, templates.css, chem-marks.css, chem-ui.css public/ favicon.svg, manifest.webmanifest, splash.html index.html pre-paint script: theme, overlay title bar, native menus, dock reservation src-tauri/src/ main.rs (windows, chrome), traffic_lights.rs, reveal.rs, engine_start.rs @@ -171,6 +179,22 @@ assets/ formchem_mark.svg, icon_src/build.py, icon set 130. A drawing draws as soon as it becomes active ยท canvas/view.ts setClient 131. The derived reactions slot in the window model ยท engine/model.ts 132. Strings of 0.5.0 are not keyed yet ยท i18n/keys +133. The Tauri CLI is a pinned dev dependency ยท package.json, package-lock.json +134. One client for the analysis routes, read defensively ยท engine/analysis-api.ts +135. The analysis replies are typed in the contract ยท engine/client-api.ts, engine/model.ts, canvas/types.ts +136. Stereo and query marks are one keyed layer ยท canvas/render/marks-layer.ts, marks-stereo.ts, marks-query.ts, renderer.ts +137. Marks take the widest free gap and turn aside from labels ยท canvas/render/marks-stereo.ts, marks-query.ts +138. The mark toggles go through the display state ยท canvas/marks-options.ts, canvas/types.ts, app/canvas.ts +139. Query, stereo group and R-group edits are made in the window ยท app/chem-edits.ts +140. The chemistry commands, their menus and the canvas menu ยท app/chem-commands.ts, app/menus.ts, app/commands-shell.ts, canvas/context.ts +141. Engine commands commit the reply's transaction once ยท app/chem-commands.ts +142. The query and stereo dialogs are built once ยท ui/periodic-grid.ts, atom-list-dialog.ts, rgroup-dialog.ts, abbreviation-dialog.ts, stereo-popover.ts, query-menus.ts, markush-dialog.ts +143. The structure check is a keyed panel with named fixes ยท ui/structure-check.ts, app/canvas-commands.ts +144. The properties section shows each method ยท ui/analysis-properties.ts, app/analysis-text.ts, ui/analysis-panel.ts +145. The isotope plot is keyed by offset from the monoisotopic peak ยท ui/isotope-plot.ts +146. Set Reaction Roles rewrites only the lists that changed ยท chem/reaction-roles.ts, ui/roles-dialog.ts, app/reaction-commands.ts +147. SMARTS export copies in the desktop shell ยท app/chem-commands.ts exportSmarts +148. Icons, stylesheets and strings of 0.6.0 ยท ui/icons.ts, styles/chem-marks.css, styles/chem-ui.css, index.html, i18n/keys/part06.json ## 1. Dependencies are the template's, nothing more ยท _v0.1.0 (package.json) @@ -700,6 +724,70 @@ reactions-api.ts is a typed client for every reaction route and sends the live c About a hundred new strings (tool labels, rail groups, panel headings, Reaction command labels and toasts, template dialog text) go through `t()` but have no key in i18n/keys, and a few are plain literals still to wrap: the drawn grid's column headers and role words in canvas/render/table.ts (`STOICH_COLUMNS`), the disabled reasons of the reaction commands, and the undo labels the tools and the engine write. `./formchem i18n scan` finds the first group. The drawn grid's words are written into the document, so translating them is a product decision (journal output is usually English). Unit words and template names are `translate="no"`. +## 133. The Tauri CLI is a pinned dev dependency ยท _v0.6.0 (package.json, package-lock.json) + +Entry 1 left `@tauri-apps/cli` out on the idea that the build scripts call the CLI themselves. They call `frontend/node_modules/.bin/tauri`, which only exists when package.json lists the CLI, so `./build_app` on a fresh Mac stopped at "the Tauri CLI did not install" (backend log 97). The CLI is now `devDependencies["@tauri-apps/cli"] = "2.12.6"`, pinned exactly like the rest. The rule for every future bump: the CLI's major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7 today), because Tauri refuses to build across minor versions; build_app and `desktop_check` enforce it. package-lock.json gained the CLI and its per-platform binary packages (218 lines); the CLI ships under Apache-2.0 or MIT, like @tauri-apps/api, and is a build tool, not part of the bundle. + +## 134. One client for the analysis routes, read defensively ยท _v0.6.0 (engine/analysis-api.ts) + +`analysisApi` is the only module that calls `/api/analysis/*` (abbreviations, properties, cip, stereo groups, wedges, check, expand, contract, hydrogens, substructure, isotope pattern, Markush, SMARTS export), and `sourceFor(doc, fid)` builds the request (the fragment, the document's expansions and the R-group member fragments). The window and the engine were written in parallel, so the replies are read through small readers (`propertiesOf`, `stereoOf`, `checkOf`, `txOf`, `warningsOf`) that accept the draft and the final shapes; at integration they were reconciled against the live routes: properties from `rows` (the method tooltip is "note (RDKit call)", units `A2` and `cm3/mol` shown as ร…ยฒ and cmยณ/mol) with `values` as fallback, stereo from `atoms` plus `bonds`, and an issue's `fix` kept as the command name (`fixCommand`). A shape change in the router is fixed here and nowhere else. + +## 135. The analysis replies are typed in the contract ยท _v0.6.0 (engine/client-api.ts, engine/model.ts, canvas/types.ts) + +client-api.ts gained the wire types of the analysis replies (`PerFragmentReply`, `PropRow`, `RuleVerdict`, `FragmentProps`, `StereoUnit`, `StereoReport`, `CheckIssueReply`, `CheckReply`, `IsotopePeak`, `IsotopeAdduct`, `IsotopePattern`, `EngineTxReply`, `MarkushReply`, `SmartsReply`). model.ts gained `AtomQuery.smarts` (an opaque SMARTS atom query, written by SMARTS import) and `RGroupDef.attach` (member fragment id to its attachment atom ids), following FORMAT, and the engine's model.py the same `RGroupDef`. `RenderDisplay` gained optional `enhancedStereo`, `queryMarks` and `groupColours` (entry 138). The model already had `stereo_groups`, `chiral`, `rgroups`, bond `query` and `topology` and `Expansion.source` from 0.3.0, so no other contract change was needed. + +## 136. Stereo and query marks are one keyed layer ยท _v0.6.0 (canvas/render/marks-layer.ts ChemMarks, marks-stereo.ts, marks-query.ts, renderer.ts syncStereo) + +`ChemMarks` replaces the CIP-only stereo layer (canvas/render/stereo.ts is deleted). It owns one `Keyed` group in the stereo layer and caches each fragment's mark specs by the fragment record, its `cip`, style, colour, the options and the font epoch (and the objects map when the fragment has R-groups, because member labels depend on other fragments). A change re-specs only the fragments whose inputs changed and patches only marks whose spec key changed; an unchanged fragment costs a list comparison. `stereoMarkSpecs` draws (R)/(S) under the label, E/Z beside the bond, the group label (abs, and1, or2) as a second line and the chiral flag under the structure; `queryMarkSpecs` draws haloed tags for atom queries (`[C,N,O]`, `not [Cl,Br]`, A, Q, X, M, rb2, s*, u, H1, arom or aliph), bond queries (S/D, S/A, D/A, any, ring, chain), the R-group summary under the scaffold, `R1 =` beside each member and wavy attachment marks, in `QUERY_COLOUR` purple. Marks carry explicit fill attributes, not CSS colours, so an SVG export later carries them. `syncStereo` still runs after `syncFragment`, so label boxes are current; the cache does not key on boxes. + +## 137. Marks take the widest free gap and turn aside from labels ยท _v0.6.0 (canvas/render/marks-stereo.ts, canvas/render/marks-query.ts) + +A mark goes into the widest angular gap around its atom after the slots `atom.ts` already takes (charge, radical, lone pairs, map number), then steps outward until it clears every neighbouring label box. After contracting ibuprofen's acid to CO2H, the (S) and and1 marks landed on the CO2H label, because stepping outward along a crowded gap never left the label's side; marks now first turn up to 50 degrees within the free gap, then step out. A query tag and a stereo mark on the same atom take different gaps, and on a very crowded atom a tag can still touch a bond (its halo keeps it legible). + +## 138. The mark toggles go through the display state ยท _v0.6.0 (canvas/marks-options.ts, canvas/types.ts RenderDisplay, app/canvas.ts display) + +Show Enhanced Stereo Groups, group colours and Show Query Features are per-window view choices stored in localStorage `formchem.marks` (`marksView`, `setMarksView`, `onMarksView`, event `fc:marks-options`), not document data. A toggle must reach the renderer through `setDisplay`, which ignores a display whose values did not change, so the three flags are fields of `RenderDisplay` and `app/canvas.ts display()` fills them; `onMarksView` calls `view.setDisplay(display())`. The renderer falls back to `marksView()` when the display lacks them. Show Stereochemistry is still the style's `stereo_labels`; `cip_enhanced` turns the group labels on regardless of the toggle. + +## 139. Query, stereo group and R-group edits are made in the window ยท _v0.6.0 (app/chem-edits.ts) + +Atom lists and not-lists, generic atom queries and their flags, query bonds and topology, stereo groups (set, join, clear), the chiral flag, R-group definitions and R# atoms are plain field edits FORMAT fully defines, so pure op builders make them in the window as one transaction with no engine round trip (`atomQueryOps`, `atomListOps`, `bondQueryOps`, `bondTopologyOps`, `stereoGroupOps`, `clearStereoGroupOps`, `chiralFlagOps`, `rgroupOps`, `rgroupAtomOps`). They emit only sets that change something. Stereo group ops never leave an empty and/or group; an `abs` group without atoms means every other centre (FORMAT's example), so assigning atoms to abs only removes them from and/or groups. `setAtomList` sets the element to the first list member for an include list, so the drawing and the SMILES show a sensible member (a known oddity: [S, N] on an O draws SH); a not-list keeps the element. Defining an R-group on an ordinary atom converts it to `R#` with the lowest free number in the document and drops its label and query in the same transaction. + +## 140. The chemistry commands, their menus and the canvas menu ยท _v0.6.0 (app/chem-commands.ts registerChemCommands, CHEM_MENU_ITEMS, chemContextItems; app/menus.ts; app/commands-shell.ts; canvas/context.ts) + +`registerChemCommands({host, homeOpen})` registers 25 commands plus the per-kind query bond ids (`set-query-bond-any` and the rest). Their ids were later() placeholders in commands-shell.ts (expand-abbreviation, contract-abbreviation, add-hydrogens, remove-hydrogens, show-stereo, compute-properties, copy-analysis, and set-reaction-roles for entry 146); registering both throws `duplicate command`, so the placeholders and the unused `'0.6.0'` LATER text were removed. `CHEM_MENU_ITEMS` places them: Edit gets Find Substructure and Copy as SMARTS; View the three Show toggles (Show Stereochemistry moved there from Structure); Structure gets the abbreviation and hydrogen commands, Assign Wedges and the Enhanced Stereo and Query submenus between Lay Out and Check Structure; Analysis gets Compute Properties and Copy Analysis. The macOS native menu is built from the same `buildMenus` definitions. `chemContextItems(host, hit, temp)` adds the Atom Query, Enhanced Stereo, Query Bond and R-group items to the atom and bond right-click menus, and a multi-atom selection gets Contract Abbreviation; temporary ids use the prefix `canvas-menu:chem-`. `CanvasMenuHost` was widened with `page()`, `style()`, `toClient()` and `focus()` so the view passes as a `ChemHost` without a cast. Find Substructure with atoms of one fragment selected uses them (and the bonds among them) as the query and searches the other fragments; with nothing selected it asks for SMARTS. + +## 141. Engine commands commit the reply's transaction once ยท _v0.6.0 (app/chem-commands.ts) + +Hydrogens, expand, contract, wedges and the check's fixes ask the engine, which answers `tx.ops`. The window collects the ops of every fragment asked, then, before committing, checks that the client is the same and that every fragment record it sent is still the current one; if the person drew meanwhile, it commits nothing and says "The drawing changed while the engine worked; try again." Otherwise it commits all the ops as one transaction, so one command is one undo step across several fragments, and shows the first engine warning as a toast. Expand is sent in document mode (the document id and the fragment), because the window sent the fragment alone at first and the engine then could neither delete the expansion record after its last use nor check new ids against the other fragments. Properties for several fragments are asked as one merged fragment (ids are unique in a document), so masses and counts sum the engine's way. + +## 142. The query and stereo dialogs are built once ยท _v0.6.0 (ui/periodic-grid.ts, ui/atom-list-dialog.ts, ui/rgroup-dialog.ts, ui/abbreviation-dialog.ts, ui/stereo-popover.ts, ui/query-menus.ts, ui/markush-dialog.ts) + +`createPeriodicGrid(onPick)` builds 118 buttons by period and group with the f-block rows once, moves with the arrow keys and patches only the pressed state (`set(selected)`). `askAtomList` resolves `{list, not}` (an empty list clears) or null; `askRGroup` resolves `{n, def}` (def null removes) and validates occurrence (`1`, `1-3`, `>0`, comma lists) before Apply. `askAbbreviation` reserves its library list at nine rows and shows placeholder rows only after 200 ms, so the dialog's height is the same loading and loaded (278 px measured). `openStereoPopover` is non-modal, in `#overlay-root` at `--z-menu`, with an abs/and/or segment, a group number stepper and the existing groups as chips; it closes on Escape, an outside pointerdown and window blur. `query-menus.ts` builds the canvas menu's submenus in its temporary-command shape, with checked states read from the live fragment. The Markush dialog is a keyed list of fixed height with Copy SMILES. + +## 143. The structure check is a keyed panel with named fixes ยท _v0.6.0 (ui/structure-check.ts showStructureCheck; app/canvas-commands.ts) + +The 0.4.0 check (entry 104) was a modal dialog that rebuilt its body on every open; `showStructureCheck({run, select, fix, scopeLabel})` is a non-modal panel with issue rows keyed by fragment, code and ids, grouped by severity. A click selects the atoms and bonds and leaves the panel open; Check Again re-runs and patches the rows (zero element mutations when nothing changed, the row node reused). The engine names the repairing command (`fix: "wedges"` or `"expand"`) instead of sending a transaction, so a Fix button calls that route for the issue's atoms and commits its reply as one "Fix Structure" step; reading a tx there first meant Fix never showed. When `/api/analysis/check` answers 404 or 405 the panel falls back to the derived cache's valence errors and warnings. canvas-commands.ts lost the old `check-structure` def, `problemRows`, `checkDialog` and `checkStructure`. + +## 144. The properties section shows each method ยท _v0.6.0 (ui/analysis-properties.ts mountAnalysisProperties, app/analysis-text.ts PROPERTY_ROWS, formatAnalysisText; ui/analysis-panel.ts) + +`mountAnalysisProperties(host)` is mounted once under the Analysis panel body and returns `{update, current, copyText, destroy}`. Updates are debounced 120 ms, stale requests are aborted, the last values stay in place and are dimmed only after 200 ms (`pendingClass`), and every value cell has a reserved width from `PROPERTY_ROWS`, so the section never jumps (574 px tall across selection changes). Each row's tooltip carries the method. The panel refreshes the section only while it is open (opening triggers a refresh), so a closed panel costs no engine calls. The five 0.4.0 window-side rows are kept for the status bar formula but hidden, because the section repeats them and the window's formula counted D as H. `formatAnalysisText` builds the Copy Analysis text with methods, the Lipinski verdict (derived from MW, cLogP, HBD and HBA when the engine sends no rule list) and the isotope lines. + +## 145. The isotope plot is keyed by offset from the monoisotopic peak ยท _v0.6.0 (ui/isotope-plot.ts mountIsotopePlot) + +The plot is one SVG of reserved size (240 by 92) built once. Sticks are keyed by their nominal offset from the monoisotopic peak (M, M+1, M+2), so a new selection with the same number of peaks patches heights and labels instead of replacing nodes; the base peak is in the accent colour, m/z labels are thinned so they never overlap, and each stick has a title tooltip with mass and abundance. Under it sit the monoisotopic mass and three fixed adduct rows ([M+H]+, [M+Na]+, [M-H]-), and old values dim while a request is out. The m/z row of the properties stays a dash for neutral species; the adduct rows carry the useful values. + +## 146. Set Reaction Roles rewrites only the lists that changed ยท _v0.6.0 (chem/reaction-roles.ts reactionRoleOps, canTakeRole; ui/roles-dialog.ts askReactionRoles; app/reaction-commands.ts setRoles) + +The command finds the step touching the selection (perceiving first when the page has none) and lists one keyed row per step member and selected object with a role select. Fragments, text, captions, groups, images, shapes and tables can take a role; the step's arrow cannot. `reactionRoleOps` moves each changed id out of every role list and into its new one, sets only the lists that differ, sets `explicit: true` so perception keeps the roles, and in the same transaction drops `coefficients` entries no longer on either side and `stoich` components, `limiting` and `product` that no longer fit, so the grid never points at a non-member. With `{role, objects}` the command acts without the dialog, which is how agents use it through `run_command`. Undo restores the old lists and `explicit: false`. + +## 147. SMARTS export copies in the desktop shell ยท _v0.6.0 (app/chem-commands.ts exportSmarts) + +In a browser Export SMARTS downloads a `.sma` Blob. The desktop window has no file writer (the reaction export asks the engine to write the file, frontend entry 128), and the engine has no SMARTS export route that writes, so in Tauri it copies the SMARTS and says that saving arrives with the file formats in 0.7.0. + +## 148. Icons, stylesheets and strings of 0.6.0 ยท _v0.6.0 (ui/icons.ts, styles/chem-marks.css, styles/chem-ui.css, index.html, i18n/keys/part06.json) + +Twelve glyphs in the shared 24 box were added: stereoCentre, stereoGroup, hydrogenAdd, hydrogenRemove, expandAbbr, contractAbbr, atomList, queryBond, rgroup, assignWedges, substructure and periodicTable (the last unused so far). chem-marks.css and chem-ui.css load after canvas-view.css and take every z-index from tokens. part06.json keys 154 strings (commands, submenus, dialogs, panels, toasts, undo labels and the property method sentences); plural forms are still built as a number plus a word, as elsewhere in the app. + ## Not verified at 0.4.0 The lasso tool in the real window (its band path is the marquee's), touch pinch and Safari gesture events, the Tauri webview (dialogs, native accelerators, `contenteditable="plaintext-only"` in older WebKit), light themes, the rotate handle on dark pages, extensions against a real package, and socket drop with resync during an edit. The title field collapses to a sliver at 1280 px wide because the menu bar takes the room; it predates this work. @@ -707,3 +795,7 @@ The lasso tool in the real window (its band path is the marquee's), touch pinch ## Not verified at 0.5.0 The macOS native menu with the new Reaction submenus and the desktop export path (no Tauri build here), the frozen sidecar carrying the template data, the rail at window heights under 900 px, rotated-box resizing by handles, bracket tilt for crossing bonds that are not perpendicular, table cell editing, TLC spot dragging, orbital phase and fill choices, and the arrow head-size handles (none of the last five are built). Everything else in entries 108 to 131 was exercised in the built window served by the engine under 4x CPU throttling, with a MutationObserver over the app for the zero-flash rule. + +## Not verified at 0.6.0 + +The macOS native menu with the new Structure, View and Analysis items, Export SMARTS in the desktop shell, and `./build_app` with the pinned CLI through to the bundle step (no Tauri here; the owner's macOS arm64 run with Python 3.14 is the check). The isotope plot with very large molecules in the window (the route was timed, the plot was not). A `data.attach` member atom that is not a stub gets its wavy mark on its first bond; only stubs and declared `attach` ids were drawn and checked. Everything else in entries 134 to 148 was exercised in the built window served by the engine under 4x CPU throttling, through menus, dialogs and canvas clicks, with state read back from the engine and a MutationObserver showing no shell or canvas container removed. From 6a2541877b408db573ab28f211600224f32d2f12 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:00:18 -0500 Subject: [PATCH 267/279] docs(analysis): document stereo, queries, Markush, properties, the check and the isotope pattern (0.6.0) The analysis routes and tools had no reference beside the format; this page gives their request and answer shapes, the check codes, the property methods and the known limits. --- docs/ANALYSIS.md | 227 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 docs/ANALYSIS.md diff --git a/docs/ANALYSIS.md b/docs/ANALYSIS.md new file mode 100644 index 00000000..3a5f049e --- /dev/null +++ b/docs/ANALYSIS.md @@ -0,0 +1,227 @@ +# FormChem analysis + +How the engine handles stereochemistry, enhanced stereo, abbreviations, explicit hydrogens, query structures, R-groups and Markush structures, calculated properties, the structure check and the isotope pattern, built from 0.6.0. What a drawing stores (`stereo_groups`, `chiral`, `rgroups`, `Atom.query`, `Bond.query` and `topology`, `expansions`) is defined in [FORMAT.md](FORMAT.md), which wins over this page; this page describes the services behind the Structure, Query and Analysis commands and the agent tools, and their HTTP routes. + +## Contents + +- Where the code lives +- Stereochemistry +- Enhanced stereo +- Wedges +- Abbreviations +- Explicit hydrogens +- Queries +- R-groups and Markush structures +- Properties +- Structure check +- Isotope pattern +- HTTP API +- Agent tools +- The window +- Known limits + +## Where the code lives + +The engine code is in `backend/app/services/chem/`: `stereo.py` (stereo report, stereo groups, wedges), `convert.py` (stereo groups and the chiral flag into RDKit), `perceive.py` (CIP and stereo warnings), `abbrev.py` (the abbreviation library), `superatom.py` (contract and expand), `hydrogens.py`, `query.py` (query molecules and SMARTS), `search.py` (substructure search), `v3000.py` (query molfiles with R-group blocks), `markush.py`, `props.py`, `check.py` and `isotopes.py`. The routes are in `backend/app/routers/analysis.py`, the agent tools in `backend/app/routers/mcp.py`. The engine uses RDKit only; the reasons for each choice are in `backend/HASHOUT_LOG.md` entries 78 to 96. + +## Stereochemistry + +Stereo comes from the drawing: wedges, hashes and the 2D geometry of double bonds. CIP labels come from RDKit's new CIP labeller, so pseudo-asymmetric centres get `r` and `s`, and isotopes rank (a CHD centre is a stereocentre). Each unit has a `state`: + +| State | Meaning | +| --- | --- | +| `defined` | a wedge or the geometry fixes the configuration | +| `undefined` | a stereocentre with no wedge, or a stereogenic double bond whose substituent lies on the bond's line | +| `unknown` | marked unknown on purpose with a wavy bond (or a crossed double bond) | + +Labels: `R`, `S`, `r`, `s` on centres, `E`, `Z` on double bonds, `M`, `P` on axes when RDKit perceives them. Not perceived: allene axial chirality and atropisomers drawn as a hindered biaryl (see Known limits). The derived cache carries the same labels in `cip` after every change. + +## Enhanced stereo + +A fragment's `stereo_groups` are `abs`, `and` (a mixture of both configurations of the group, a racemate when it holds every centre) and `or` (one configuration, not known which), each `and` and `or` group with a number `n`. An `and` or `or` group without `n` takes the next free number. Only real stereocentres stay in a group: other atoms are dropped with `stereo_group_not_centre`, and an atom in two groups gives `stereo_group_overlap`. + +The fragment's `chiral` flag: + +| `chiral` | Chemistry | +| --- | --- | +| absent or `absolute` | every centre not in a group is absolute; `absolute` also sets the molfile chiral flag to 1 | +| `relative` | the centres in no group form one OR group with the next free number | +| `racemic` | the centres in no group form one AND group with the next free number | + +The groups go into RDKit with the structure, so CXSMILES carries them (`C[C@H](N)[C@H](C)O |&1:1,3|`) and regrouping recomputes the derived cache. An OR or AND group of one centre writes the same CXSMILES for R and S, because it means either enantiomer. A V2000 or V3000 molfile with the chiral flag at 0 opens absolute, as RDKit reads it, because most programs and databases write 0 for single enantiomers. + +## Wedges + +Assign Wedges (`POST /api/analysis/wedges`) rewrites the wedge and hash marks of the chosen centres (all defined centres when none are named). The configuration comes from the drawing, from wanted labels (`cip: {atom: "R"}`, reached by flipping and relabelling, up to four rounds), or from 3D coordinates (`coords3d`). RDKit's `WedgeMolBonds` picks one bond per centre, preferring bonds outside rings, bonds to hydrogen and to terminal atoms; a wedge whose narrow end must move swaps its `a` and `b`. Hollow wedges stay hollow, wavy and crossed bonds are never touched. Warnings: `cip_unreachable` (a wanted label no flip reaches), `wedge_mismatch` (a centre that still disagrees after the rewrite). + +## Abbreviations + +The built-in library has 106 abbreviations in six categories: alkyl (17), aryl (7), protecting group (30), silyl (10), sulfonyl (14) and functional (28). Each is a SMILES with `*` at the attachment. The person's own go in `abbreviations.json` in the FormChem data folder, as a list of `{label, smiles, reversed?, category?, prefer?}` or a map of label to the same or to a SMILES string; the SMILES needs exactly one `*` with one bond. User entries win over built-ins, and `"prefer": "abbreviation"` makes a label that is also an element symbol read as the abbreviation. The file is re-read when it changes; bad entries are listed in `user_errors`. + +Contract (`POST /api/analysis/contract`) turns a connected selection into one abbreviation atom. Without a label the substituent is matched against the library by canonical SMILES with stereo removed (preferring Pr, Bu, Ac, TBS, CO2H and Ms over their synonyms); more than one attachment bond needs a label. The selected atoms keep their ids inside the new expansion record, the crossing bonds keep theirs and point at the new atom, and a wedge that started inside is dropped (`stereo_dropped`). A typed label that differs from the library's match gives `label_mismatch`. + +Expand (`POST /api/analysis/expand`) puts the stored atoms back, rotated so the attachment bond points at the neighbour and mirrored when that clashes less with the rest of the structure. A library label with no expansion record is expanded from its template at the fragment's bond length. Contract then expand returns every atom to the same place with the same id. In document mode the expansion record is deleted after its last use. + +## Explicit hydrogens + +Add (`POST /api/analysis/add-h`) places hydrogens at 0.8 bond lengths, each into the widest free gap around its atom. An element-like label (OH, NH2) is replaced by the atom and its hydrogens. When a centre's configuration would change, the new H bond becomes a hash or wedge with its narrow end on the centre; otherwise the reply warns `stereo_changed`. Remove (`POST /api/analysis/remove-h`) keeps a hydrogen with an isotope, charge, map number, query, label, radical, stereo mark or a bond order other than 1, and one that holds a centre's configuration (`hydrogens_kept`). + +## Queries + +A drawing is a query when its atoms or bonds carry query features (FORMAT, `Atom.query`, `Bond.query`, `Bond.topology`). The engine builds one RDKit query molecule from SMARTS primitives, used by substructure search, SMARTS export and the V3000 writer: + +| Feature | SMARTS | +| --- | --- | +| a plain atom | its element only (no charge, H count or aromaticity unless asked) | +| `list` | `[#6,#7]` | +| `list` with `not` | `[!#6&!#7]` | +| `generic` A, AH, Q, QH | `!#1`, `*`, `!#6&!#1`, `!#6` | +| `generic` X, M | the halogens; every element outside the non-metals (B, Si, Ge, As, Sb and Te count as non-metals) | +| `ring_bonds` n | `x` (4 means 4 or more) | +| `subst` n | `D` (6 or more); -2 is the drawing's own count | +| `unsat` | `$(*=,#,:*)` | +| `h_min` n | `!H0` to `!H(n-1)` | +| `aromatic` | `a` or `A` | +| `smarts` | the stored SMARTS, as it is | +| bond `query` | `~` any, `-,=`, `-,:`, `=,:` | +| bond `topology` | `@` ring, `!@` chain | + +Explicit hydrogens in a query fold into H counts. Chiral tags are kept, so a search with `chirality: true` tells L-alanine from D-alanine. + +SMARTS export (`POST /api/analysis/smarts/export`) writes this molecule's SMARTS; R-group atoms become `*` (`smarts_rgroups`), stereo groups cannot be expressed (`smarts_stereo_groups`), abbreviations are expanded (`abbreviations_expanded`). SMARTS import (`POST /api/analysis/smarts/import`) draws a pattern as a query fragment: primitives that map become query fields, anything else (other recursive SMARTS, `R`, exact `H`, valence) stays whole in `query.smarts` (`smarts_opaque`), and an implicit SMARTS bond becomes `single_or_aromatic` (`smarts_bond_simplified`). + +Query molfiles: `POST /api/analysis/molfile` writes V3000 with query atom types (`[C,N]`, `NOT[C,N]`, `A`, `AH`, `Q`, `QH`, `X`, `XH`, `M`, `MH`), RBCNT, SUBST, UNSAT, HCOUNT, query bond types 5 to 8, TOPO, the stereo collections and RGROUP blocks. `POST /api/analysis/molfile/import` reads them back, R-group blocks included, which RDKit's own reader cannot. A field V3000 cannot carry gives one `v3000_query_lossy` warning naming the atoms. + +## R-groups and Markush structures + +An `R#` atom with `rgroup` n refers to the fragment's `rgroups["n"]`: its `members` (fragments drawn on the page), `occurrence` (`1`, `1-3`, `>0`, `<3`, or comma lists), `rest_h` (unfilled sites are hydrogen) and `if_then` (group n must be filled whenever this one is). A member attaches, in this order, at the atoms its definition's `attach` names, else at its atoms with `data.attach` 1 or 2, else at its attachment stubs (a `*` atom with no label and one bond, which stands for the R atom: its neighbour bonds to the scaffold), else at its first atom. + +`POST /api/analysis/markush` enumerates the structures: members are joined to the scaffold, duplicates removed by canonical SMILES, and each structure listed with its SMILES, formula and the member chosen at each site. `count` is the combinatorial total before if-then filtering and deduplication. Over 100000 needs `force`; the list stops at `limit` (default 1000) with `enumeration_truncated`. + +## Properties + +`POST /api/analysis/properties` gives, per fragment, display `rows` with a `method` (the RDKit call) and a `note` (the method in words), the raw `values`, the Lipinski and Veber verdicts and the elemental analysis. Values are computed on the structure with abbreviations expanded and explicit hydrogens folded in; labels and R-groups count as dummy atoms (`incomplete`). + +| Key | Label | Method | Unit, rounding | +| --- | --- | --- | --- | +| `formula` | Formula | Hill order, FormChem's writer | | +| `mw` | Molecular weight | standard atomic weights | g/mol, 2 | +| `exact_mass` | Exact mass | most abundant isotope of each element | Da, 4 | +| `clogp` | cLogP | `Crippen.MolLogP` (Wildman and Crippen 1999; typical error 0.5 to 0.7 log units) | 2 | +| `mr` | Molar refractivity | `Crippen.MolMR` | cm3/mol, 2 | +| `tpsa` | TPSA | `rdMolDescriptors.CalcTPSA`, N and O only (Ertl) | A2, 2 | +| `tpsa_sp` | TPSA with S and P | `rdMolDescriptors.CalcTPSA` with S and P | A2, 2 | +| `hbd`, `hba` | H-bond donors, acceptors | `rdMolDescriptors.CalcNumLipinskiHBD`, `CalcNumLipinskiHBA` | | +| `hbd_refined`, `hba_refined` | refined donors, acceptors | `rdMolDescriptors.CalcNumHBD`, `CalcNumHBA` | | +| `rotatable_bonds` | Rotatable bonds | `rdMolDescriptors.CalcNumRotatableBonds` | | +| `heavy_atoms` | Heavy atoms | `Mol.GetNumHeavyAtoms` | | +| `rings`, `aromatic_rings` | Rings, aromatic rings | `rdMolDescriptors.CalcNumRings`, `CalcNumAromaticRings` | | +| `fraction_csp3` | Fraction Csp3 | `rdMolDescriptors.CalcFractionCSP3` | 3 | +| `formal_charge` | Formal charge | `Chem.GetFormalCharge` | | +| `stereocentres`, `undefined_stereocentres` | Stereocentres | `Chem.FindPotentialStereo` | | +| `pieces` | Pieces | `Chem.GetMolFrags` | | + +Lipinski: MW at most 500, cLogP at most 5, donors at most 5, acceptors at most 10; it passes with at most one violation. Veber: rotatable bonds at most 10 and TPSA at most 140. A value RDKit cannot compute is null with `property_failed`. Reference values: ibuprofen C13H18O2, MW 206.28, exact mass 206.1307, cLogP 3.07, TPSA 37.3, HBD 1, HBA 2, 4 rotatable bonds, Fsp3 0.462; aspirin TPSA 63.6, HBD 1, HBA 4, MW 180.16. + +## Structure check + +`POST /api/analysis/check` returns, per fragment, `issues` sorted errors first and `counts` by severity. An issue is `{code, severity, text, atoms?, bonds?, fix?}`; `fix` names the analysis route that repairs it (`wedges` or `expand`), which the window calls for the issue's atoms. Atoms with `ignore_warnings` drop the issues that name only them. With `query: true` (the drawing is a search query) `query_feature` is not reported. + +| Severity | Codes | +| --- | --- | +| error | `valence`, `bad_bond`, `engine_error`, `bad_expansion` | +| warning | `hypervalent`, `unknown_label`, `misplaced_wedge`, `ambiguous_wedge`, `conflicting_wedges`, `wedge_between_centres`, `ring_double_bond_stereo`, `stereo_ignored`, `undefined_double_bond`, `unusual_charge`, `unknown_isotope`, `abbreviation_bonds`, `abbreviation_valence`, `overlapping_atoms`, `short_bond`, `long_bond`, `aromatic_outside_ring`, `cannot_kekulise`, `unsupported_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre`, `rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `cip_failed` | +| info | `undefined_stereocentre`, `stereo_unknown`, `unknown_ez`, `charge_imbalance`, `query_feature`, `uncommon_isotope`, `crossing_bonds`, `label_collides`, `rgroup_unused`, `rgroup_attachment_guessed` | + +Rules beyond the derived warnings: `unusual_charge` is a charge of 3 or more on a non-metal, carbon at 2 or more, a charged noble gas, F+ or an anionic group 1 or 2 metal; `uncommon_isotope` is a known nuclide with no natural abundance, except the common labels 2H, 3H, 11C, 13C, 14C, 15N, 17O, 18O, 18F, 32P, 33P, 35S, 123I, 125I and 131I; `crossing_bonds` is skipped above 1500 bonds; `label_collides` flags Ac, Pr and Np drawn on their element. Metal cations such as Na+ are judged by their charge-shifted valence list, so salts are not valence errors. + +## Isotope pattern + +The pattern is exact: for each element, its isotope masses and abundances (from RDKit) are raised to the element's count by repeated squaring and the elements are convolved, merging peaks within 0.001 Da and pruning those under 1e-7 of the top as it goes. The result is merged within 0.01 Da and peaks under 0.1 percent of the base peak are dropped (`threshold`, 0 to 100, changes that). An atom with an isotope set counts as one fixed mass; a charge removes the electron mass and divides m/z by |z|. A neutral species gets the adducts [M+H]+ (proton 1.007276), [M+Na]+ and [M-H]-; an ion gets only [M] with its charge. Up to 20000 atoms. + +| Formula | Peaks (relative abundance) | +| --- | --- | +| CH2Cl2 | 83.9534 (100), 84.9568 (1.10), 85.9504 (63.92), 86.9538 (0.71), and smaller | +| C6H5Br | 155.9575 (100), 156.9608 (6.55), 157.9554 (97.45), 158.9588 (6.37) | +| C13H18O2 (ibuprofen) | 206.1307 (100), 207.1341 (14.34), 208.1367 (1.36); [M+H]+ 207.1380, [M+Na]+ 229.1199, [M-H]- 205.1234 | + +A pattern is `{formula, charge, monoisotopic, average, peaks: [{mass, mz, abundance, fraction}], adducts: [{ion, charge, mz}], threshold, merge, method, warnings}`; `abundance` is percent of the base peak and `fraction` the share of the whole. + +## HTTP API + +Every POST needs the window key (`x-formchem-window-key`), like every route of the engine that is not a plain read. A POST takes its structure one of two ways: + +- stateless: `fragment` (a FORMAT fragment), optional `expansions` (the document's map) and optional `members` (fragment id to fragment, the R-group members); +- from an open document: `doc` (a document id open in the engine) and `object` (one fragment id) or `objects` (a list; absent means every fragment, for the reads). Expansions and members then come from the document, and new ids are checked against every id in it. + +A route that changes the drawing answers `tx: {label, ops}`: FORMAT ops with paths from the document root, for the window to commit as one transaction (one undo step). With `doc` and `apply: true` the engine applies it at once (origin `user`) and adds `applied: {tx, rev}` (`null` when there was nothing to change); `apply` without `doc` is a 422. Errors: 422 `{detail}` with a sentence for the person (such as "no abbreviation in the library matches this selection; give a label"), 404 for an unknown `doc` or `object`, 409 `{detail: {message, errors}}` when the document refuses the transaction, 413 for text over 20 MB. In the per-fragment reads a fragment that fails gives `{error: "Type: message"}` in its slot. + +| Route | Body | Answer | +| --- | --- | --- | +| `GET /api/analysis/abbreviations` | | `{abbreviations: [{label, reversed, smiles, category, source}], user_file, user_errors}` | +| `POST /api/analysis/properties` | source | `{fragments: {fid: Props}, engine}` | +| `POST /api/analysis/cip` | source | `{fragments: {fid: Stereo}, engine}` | +| `POST /api/analysis/check` | source, `query?` | `{fragments: {fid: {issues, counts: {error, warning, info}, engine}}, engine}` | +| `POST /api/analysis/stereo-groups` | one fragment; `set?: {kind: "abs", "and" or "or", atoms, n?}`; `chiral?: "absolute", "relative", "racemic" or null` | `{groups, chiral, cxsmiles, warnings, tx?}`, a preview of the result; `tx` only when `set` or `chiral` was given | +| `POST /api/analysis/wedges` | one fragment; `atoms?`, `cip?: {atom: "R" or "S"}`, `coords3d?: {atom: [x, y, z]}` | `{tx, changed: [bond ids], cip: {atom: label}, warnings}` | +| `POST /api/analysis/expand` | one fragment; `atoms?`, `bond_length?` | `{tx, expanded: {abbreviation atom: [new atom ids]}, warnings}` | +| `POST /api/analysis/contract` | one fragment; `atoms`, `label?` | `{tx, atom, expansion, label, warnings}` | +| `POST /api/analysis/add-h` | one fragment; `atoms?` | `{tx, added: {heavy atom: [H ids]}, warnings}` | +| `POST /api/analysis/remove-h` | one fragment; `atoms?` | `{tx, removed: [H ids], kept: [H ids], warnings}` | +| `POST /api/analysis/smarts/export` | one fragment; `atoms?` | `{smarts, warnings, engine}` | +| `POST /api/analysis/smarts/import` | `{text, bond_length?, origin?: [x, y]}` | `{format: "smarts", fragments: [fragment], warnings}` | +| `POST /api/analysis/substructure` | `smarts`, or `query` (a fragment), or with `doc` `query_object`; targets `doc` with `objects?`, or `fragments: {fid: fragment}` with `expansions?`; `max_hits?` (1 to 100000, default 1000), `chirality?` | `{hits: [{object, atoms, bonds, map: {query atom: target atom}}], count, by_object: {fid: n}, truncated, smarts, warnings}` | +| `POST /api/analysis/molfile` | one fragment (with `rgroups` and members for a Markush scaffold) | `{to: "molfile3000", text, warnings, engine}` | +| `POST /api/analysis/molfile/import` | `{text, bond_length?, origin?}` | `{format: "molfile3000", fragments: [scaffold, member...], warnings}` | +| `POST /api/analysis/markush` | one fragment with R# atoms and `rgroups`; `limit?` (1 to 100000, default 1000), `force?` | `{count, structures: [{smiles, formula, choice: {"1": [member id or "H" per site]}}], truncated, groups: [{n, sites, members: [{object, attach, stubs}], occurrence, rest_h, if_then}], warnings}` | +| `POST /api/analysis/isotope-pattern` | source, `threshold?` | `{fragments: {fid: pattern}, engine}` | +| `GET /api/analysis/isotope-pattern` | `?formula=C6H5Br&threshold=` (D and T accepted, a charge suffix such as `+` or `2-`) | one pattern with `warnings` and `engine` | + +Props (one fragment): + +```json +{ "rows": [ { "key": "clogp", "label": "cLogP", "value": 3.07, "unit": "", "method": "Crippen.MolLogP", + "note": "Wildman and Crippen 1999 atom contributions; typical error 0.5 to 0.7 log units" } ], + "values": { "formula": "C13H18O2", "mw": 206.28, "exact_mass": 206.1307, "clogp": 3.07, "tpsa": 37.3, "hbd": 1, "hba": 2 }, + "lipinski": { "name": "Lipinski", "method": "...", "rules": [ { "key": "mw", "value": 206.28, "limit": 500.0, "ok": true } ], "violations": 0, "pass": true }, + "veber": { "name": "Veber", "method": "...", "rules": [], "violations": 0, "pass": true }, + "elemental_analysis": { "C": 75.69, "H": 8.8, "O": 15.51 }, "excluded": [], "engine": "rdkit 2025.09.3", "warnings": [] } +``` + +Stereo (one fragment): + +```json +{ "atoms": { "a...": "S" }, "bonds": { "b...": "E" }, + "centres": [ { "atom": "a...", "label": "S", "state": "defined", "group": "and1" } ], + "double_bonds": [ { "bond": "b...", "label": "E", "state": "defined" } ], + "axes": [], "chiral": null, "stereo_groups": [ { "kind": "and", "n": 1, "atoms": ["a...", "a..."] } ], + "smiles": "...", "cxsmiles": "C[C@H](N)[C@H](C)O |&1:1,3|", "warnings": [] } +``` + +`group` appears on defined centres only (`abs`, `and`, `or`); `stereo_groups` are the groups as RDKit kept them, in FORMAT shape. + +## Agent tools + +The MCP server has four read-only analysis tools (`backend/app/routers/mcp.py`); they never ask the person. `doc` may be left out when exactly one drawing is open. Each answers text lines plus `structuredContent` with the same JSON as the route. + +| Tool | What it returns | +| --- | --- | +| `properties {doc?, object?}` | the Props of each fragment, with methods | +| `check_structure {doc?, object?, query?}` | the issues of each fragment | +| `stereo {doc?, object?}` | the Stereo report of each fragment | +| `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | the hits with object, atom and bond ids | + +Changing commands reach agents through `run_command`: `add-hydrogens`, `remove-hydrogens`, `expand-abbreviation`, `contract-abbreviation`, `assign-wedges`, `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group`, `set-atom-list`, the `set-query-bond-` commands, `define-rgroup`, `enumerate-markush`, `copy-smarts` and `compute-properties`. Each that changes the drawing is one undo step. + +## The window + +`frontend/src/engine/analysis-api.ts` is the only caller of these routes. The window makes the plain field edits itself (atom lists and generic queries, query bonds and topology, stereo groups, the chiral flag, R-group definitions), and asks the engine for everything that needs RDKit (hydrogens, expand, contract, wedges, the check, properties, search, the abbreviation library, Markush, SMARTS), committing the reply's `tx` as one transaction only when the fragments did not change while it waited. The Analysis panel's properties section and isotope plot are refreshed only while the panel is open. The canvas draws stereo, enhanced group and query marks from the derived `cip` and the fragment's fields. + +## Known limits + +- Allene axial chirality is not perceived (RDKit 2025.09 has no allene CIP), and atropisomers drawn as a hindered biaryl get no axis: the engine runs RDKit's legacy stereo perception, and a wedge at the axis gives only `misplaced_wedge`. +- Link nodes, variable attachment (position variation), multicentre bonds and V3000 polymer brackets are not built. +- SMARTS import keeps implicit bonds between aromatic atoms at order 1 (query `single_or_aromatic`), so the ring is drawn with single bonds although it matches aromatic rings. +- `count` in the Markush answer is taken before if-then filtering and deduplication. +- A molfile with the chiral flag at 0 is read as absolute without an import warning. +- "As drawn" query counts are written to V3000 as `-2` and to SMARTS as the drawn number. From 1c2f5cafbb00625db794c96427d1f4c9c69d4679 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:00:23 -0500 Subject: [PATCH 268/279] docs(changelog): note that the desktop app now builds on macOS with the pinned CLI (0.6.0) The owner ran ./build_app on macOS arm64 with Python 3.14 after the pin and the app built; the entry says so and nothing more. --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41a7b083..8483ff03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ Stereo, queries and analysis: FormChem now reads and edits stereochemistry in de ### Fixed -- The desktop build stopped with "the Tauri CLI did not install", because the window's packages never listed the Tauri CLI. It is now pinned at 2.12.6, matching the Tauri crate 2.12, and the message says what to check. +- The desktop build stopped with "the Tauri CLI did not install", because the window's packages never listed the Tauri CLI. It is now pinned at 2.12.6, matching the Tauri crate 2.12, and the message says what to check. With the pin, `./build_app` built the desktop app on macOS (Apple silicon, Python 3.14). - `./build_app` left the template library out of the engine it froze, so Insert > Template was empty in a desktop app built that way. - Sodium and other metal cations in salts, such as Na+, were reported as valence errors. - Query atoms (A, Q, X, M and atom lists) and a bare `*` attachment point were reported as unknown labels. From fb556529ac3c77291c8b86238ca4c91480485712 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:00:30 -0500 Subject: [PATCH 269/279] docs(hashout): record the owner's macOS desktop build in both logs (0.6.0) The build fix entries said the build was unverified; the owner's arm64 run built the app, while running it was not reported on. --- backend/HASHOUT_LOG.md | 2 +- frontend/HASHOUT_LOG.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index ef31529a..7dc23de5 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -524,4 +524,4 @@ Every POST takes its structure either stateless (`fragment`, optional `expansion ## 98. build_app bundles the template library when it freezes the engine ยท _v0.6.0 (build_app freeze) -Entry 76 added `backend/app/data/templates` as `templates` data to `setup/freeze_backend` and its `.bat` twin, but `build_app` runs PyInstaller itself and missed it, so a desktop app built with `./build_app` had an empty template library (`templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen). It now passes the same `--add-data`. `build_app.bat` goes through `setup/desktop_build.bat` and `freeze_backend.bat`, so Windows already had it. Not run here: pyinstaller and the Tauri bundle; the owner's run on macOS arm64 with Python 3.14 is the check. +Entry 76 added `backend/app/data/templates` as `templates` data to `setup/freeze_backend` and its `.bat` twin, but `build_app` runs PyInstaller itself and missed it, so a desktop app built with `./build_app` had an empty template library (`templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen). It now passes the same `--add-data`. `build_app.bat` goes through `setup/desktop_build.bat` and `freeze_backend.bat`, so Windows already had it. Not run here (no pyinstaller or Tauri on this machine). The owner ran `./build_app` on macOS arm64 (Python 3.14.6, Node 24.16, Rust 1.97.1) after the CLI pin, and the desktop app built; the frozen engine at runtime (the template library in particular) and the native macOS menu were not reported on. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index c258b54f..5910c7e5 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -798,4 +798,4 @@ The macOS native menu with the new Reaction submenus and the desktop export path ## Not verified at 0.6.0 -The macOS native menu with the new Structure, View and Analysis items, Export SMARTS in the desktop shell, and `./build_app` with the pinned CLI through to the bundle step (no Tauri here; the owner's macOS arm64 run with Python 3.14 is the check). The isotope plot with very large molecules in the window (the route was timed, the plot was not). A `data.attach` member atom that is not a stub gets its wavy mark on its first bond; only stubs and declared `attach` ids were drawn and checked. Everything else in entries 134 to 148 was exercised in the built window served by the engine under 4x CPU throttling, through menus, dialogs and canvas clicks, with state read back from the engine and a MutationObserver showing no shell or canvas container removed. +The macOS native menu with the new Structure, View and Analysis items and Export SMARTS in the desktop shell (no Tauri here). With the pinned CLI the owner's `./build_app` on macOS arm64 (Python 3.14.6, Node 24.16, Rust 1.97.1) built the desktop app; nothing was reported about running it. The isotope plot with very large molecules in the window (the route was timed, the plot was not). A `data.attach` member atom that is not a stub gets its wavy mark on its first bond; only stubs and declared `attach` ids were drawn and checked. Everything else in entries 134 to 148 was exercised in the built window served by the engine under 4x CPU throttling, through menus, dialogs and canvas clicks, with state read back from the engine and a MutationObserver showing no shell or canvas container removed. From 97d3ad8d8e9cbfe7800a37b2a66719f1f7b0156e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:00:43 -0500 Subject: [PATCH 270/279] docs(reactions): describe Set Reaction Roles and its transaction (0.6.0) Roles set by hand arrived in 0.6.0; the page now says which objects can take a role, what the one transaction rewrites and how agents run it. --- docs/REACTIONS.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/REACTIONS.md b/docs/REACTIONS.md index cceb9028..d1729f71 100644 --- a/docs/REACTIONS.md +++ b/docs/REACTIONS.md @@ -36,6 +36,10 @@ Steps whose products are the reactants of another step chain into one reaction, Running perception again keeps reaction and step ids (matched by arrow), keeps `coefficients` and `stoich` for the ids still in the step, and writes nothing when the result equals what is stored. A step with `explicit: true` (set by the person, an agent, or read from a reaction file) is kept as it is, even when its arrow is gone; the summary reports it as stale. The whole change is one transaction labelled "Perceive reactions". +### Setting roles by hand + +From 0.6.0 Reaction > Set Reaction Roles... changes roles where perception read them wrongly, such as water drawn after the arrow that should be an agent. It acts on the step touching the selection (perceiving first when the page has no step) and lists one row per step member and per selected object, each with a role: reactant, product, agent, condition or none. Fragments, text, captions, groups, images, shapes and tables can take a role; the step's own arrow cannot. Apply is one transaction labelled "Set Reaction Roles", built in the window (`frontend/src/chem/reaction-roles.ts`, `reactionRoleOps`): each changed object moves out of every role list and into its new one, only the lists that differ are set, `explicit` becomes true so later perception keeps the step, and `coefficients` entries for objects no longer reactants or products, and `stoich` components, `limiting` and `product` that no longer fit, are removed in the same transaction. Undo restores the lists and `explicit`. Agents run it without the dialog: `run_command {id: "set-reaction-roles", params: {role: "agent", objects: ["o..."]}}` (`objects` defaults to the selection). + ## Atom mapping Mapping numbers reactant atoms onto product atoms (`Atom.map`) with Indigo's automapper and marks bonds of the step's fragments with `reacting` (`broken`, `formed`, `order`). Modes: @@ -115,7 +119,7 @@ The check's parts: `species` is `[{id, role, coefficient, formula, mw, charge}]` A stoichiometry row is `{id, role, label, formula, mw, mw_source, coefficient, purity_pct, density_g_ml, conc_m, equiv_entered, equiv, mmol, mass_mg, volume_ml, source, actual_mg, limiting, yield_pct}`, where `source` is `mass`, `volume`, `solution` or `equiv` and a product's `mmol` and `mass_mg` are theoretical. `limiting_source` is `entered` or `computed`; `yield` is `{product, theoretical_mmol, theoretical_mg, isolated_mg, percent}`. -Transaction labels: "Perceive reactions", "Map atoms", "Clear mapping", "Insert reaction", "Balance reaction" and "Stoichiometry grid". Amounts, coefficients and hand-set roles are written by the window with ordinary transactions on the step's path (`["pages", {"id": p}, "reactions", {"id": r}, "steps", {"id": s}, "stoich"]` and `... "coefficients"`); setting roles by hand sets `explicit: true` and the role lists in one transaction. +Transaction labels: "Perceive reactions", "Map atoms", "Clear mapping", "Insert reaction", "Balance reaction" and "Stoichiometry grid". Amounts, coefficients and hand-set roles are written by the window with ordinary transactions on the step's path (`["pages", {"id": p}, "reactions", {"id": r}, "steps", {"id": s}, "stoich"]` and `... "coefficients"`); setting roles by hand ("Set Reaction Roles") sets `explicit: true` and the role lists in one transaction. ## Agent tools @@ -130,7 +134,7 @@ The MCP server has four reaction tools (`backend/app/routers/mcp.py`); each take ## The window -The Reaction menu calls these routes: Perceive Reactions, Map Atoms (which perceives first when the page has no step), Clear Atom Mapping, Check Balance (a dialog with the suggestion and a Balance button), Balance Reaction, Stoichiometry Panel and Insert Stoichiometry Table, Insert Reaction from Clipboard, Copy Reaction As SMILES or RXN, and Export Reaction. A command acts on the step whose arrow or roles touch the selection, else the first step on the page. The Stoichiometry panel computes in the window by the rules above and asks the engine only for molecular weights it lacks. +The Reaction menu calls these routes: Perceive Reactions, Set Reaction Roles (window-side, see Perception), Map Atoms (which perceives first when the page has no step), Clear Atom Mapping, Check Balance (a dialog with the suggestion and a Balance button), Balance Reaction, Stoichiometry Panel and Insert Stoichiometry Table, Insert Reaction from Clipboard, Copy Reaction As SMILES or RXN, and Export Reaction. A command acts on the step whose arrow or roles touch the selection, else the first step on the page. The Stoichiometry panel computes in the window by the rules above and asks the engine only for molecular weights it lacks. ## Known limits From 5caf8f48f7476c4581ad8b4c8148076785c9778c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:01:17 -0500 Subject: [PATCH 271/279] docs(wiki): add the Stereo and Queries page (0.6.0) Explains stereo labels, enhanced stereo, abbreviations, query atoms and bonds, substructure search and R-groups for the person drawing, linked from the sidebar and Home. --- .docs/wiki/Home.md | 1 + .docs/wiki/Stereo-and-Queries.md | 71 ++++++++++++++++++++++++++++++++ .docs/wiki/_Sidebar.md | 1 + 3 files changed, 73 insertions(+) create mode 100644 .docs/wiki/Stereo-and-Queries.md diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index fa5105db..8385651e 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -10,6 +10,7 @@ FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, wi | [Drawing](Drawing) | The tools, the hover keys, drawing with the keyboard alone, and styles | | [Annotations](Annotations) | Arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures, captions, arranging and grouping, templates, Find and rulers | | [Reactions](Reactions) | Reaction schemes, roles, atom mapping, balance, stoichiometry, RXN and reaction SMILES | +| [Stereo and Queries](Stereo-and-Queries) | CIP labels, enhanced stereo groups, wedges, abbreviations, query atoms and bonds, substructure search, SMARTS, R-groups and Markush structures | | [Agents](Agents) | The MCP server, agent configs, skills and consent | | [Terminal](Terminal) | The terminal and agent dock | | [Extensions](Extensions) | Form extensions in FormChem | diff --git a/.docs/wiki/Stereo-and-Queries.md b/.docs/wiki/Stereo-and-Queries.md new file mode 100644 index 00000000..32ce51f4 --- /dev/null +++ b/.docs/wiki/Stereo-and-Queries.md @@ -0,0 +1,71 @@ +# Stereo and Queries + +From 0.6.0 FormChem reads and edits stereochemistry in depth and draws query structures: atom lists, generic atoms, query bonds, R-groups and Markush structures. Every command here is one undo step. The engine side, with every route, is [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md). + +## Stereo labels + +Draw stereocentres with wedges and hashes (bond tool `B`, or hover a bond and press `W` or `H`). View > Show Stereochemistry draws the labels the engine works out with the CIP rules: + +| Label | Where it shows | +| --- | --- | +| (R), (S) | under the centre's label or position | +| (r), (s) | pseudo-asymmetric centres, such as C3 of pentane-2,3,4-triol | +| (E), (Z) | beside a stereogenic double bond | + +A centre without a wedge, or a double bond with a substituent on its line, is undefined and gets no label; a wavy bond marks it unknown on purpose. Isotopes count, so a CHD centre is a stereocentre. Allene axial chirality and atropisomers (a hindered biaryl) are not perceived in this version. + +Structure > Assign Wedges redraws the wedges of the selected centres (or every defined centre) the way the chemistry reads them: one wedge per centre, on a bond outside a ring where possible, with its narrow end on the centre. Use it after a clean-up or an import that left wedges in awkward places. + +## Enhanced stereo + +Enhanced stereo says what is known about a mixture: + +| Group | Means | Shown as | +| --- | --- | --- | +| abs | this configuration, as drawn | abs | +| AND n | both configurations of these centres are present (a racemate when the group holds every centre) | and1, and2 | +| OR n | one configuration, not known which | or1, or2 | + +Select stereocentres and use Structure > Enhanced Stereo: Absolute (abs), New AND Group, New OR Group or Clear Stereo Group. Stereo Group... opens a small popover with the kind, the group number and the groups already in the drawing as chips: click a chip to join it. The same items are on the atom right-click menu. View > Show Enhanced Stereo Groups draws the group labels under the CIP labels, in a colour per group when group colours are on. + +The structure's chiral flag (absolute, relative or racemic) shows under it. Relative puts every centre that is in no group into one OR group, racemic into one AND group. A molfile with its chiral flag at 0 opens with its centres absolute, as most programs mean it. + +## Abbreviations + +Select a group of atoms (for example the CO2H of a carboxylic acid, without the carbon it hangs on) and choose Structure > Contract Abbreviation.... The dialog searches the library of 106 abbreviations (Me to TBS, Ts, Boc, Fmoc, CO2Et and the rest) and proposes the match; type a new label to use your own. Expand Abbreviation on a selected label such as OTs or Ph (or with nothing selected, on every abbreviation on the page) draws its atoms back, laid out along the attachment bond on the side with more room; after a contract, expand returns the same atoms to the same place. Your own abbreviations go in `abbreviations.json` in the FormChem data folder: a list of `{"label": "PMB", "smiles": "*Cc1ccc(OC)cc1"}` entries, the `*` marking the attachment. + +Structure > Add Explicit Hydrogens draws the implicit hydrogens as atoms (of the selection, or everything), and Remove Explicit Hydrogens folds them back. Hydrogens that carry stereo, an isotope, a charge or a map number are kept. + +## Query atoms and bonds + +A query structure describes what to search for. Right-click an atom for Atom Query, or use Structure > Query: + +| Feature | Tag on the canvas | Means | +| --- | --- | --- | +| Atom List... | `[C,N,O]` or `not [Cl,Br]` | any of these elements, or none of them (pick from the periodic table) | +| Any Atom (A) | A | any atom except hydrogen | +| Any Heteroatom (Q) | Q | any atom except carbon and hydrogen | +| Any Halogen (X) | X | F, Cl, Br, I or At | +| Any Metal (M) | M | any metal | +| Aromatic, Aliphatic | arom, aliph | the atom must or must not be aromatic | +| Unsaturated | u | the atom has a double, triple or aromatic bond | +| Substitution as Drawn | s* | exactly as many heavy neighbours as drawn | +| Ring Bonds as Drawn | rb2 | exactly as many ring bonds as drawn | + +The hover keys `A`, `Q`, `X` and `M` set the generic atoms directly. Right-click a bond for Query Bond: Any Bond, Single or Double (S/D), Single or Aromatic (S/A), Double or Aromatic (D/A), In a Ring, In a Chain, or Clear Bond Query; the hover key `0` sets any bond. Query features are drawn as small purple tags; View > Show Query Features hides or shows them. Check Structure notes query features in a drawing that is not meant as a query. + +## Find Substructure and SMARTS + +Edit > Find Substructure... searches every structure on the page and selects the matches. With atoms of one structure selected, those atoms (and the bonds among them) are the query; with nothing selected it asks for a SMARTS pattern such as `C(=O)[OH]`. The toast says how many matches in how many structures. + +Copy as SMARTS (Edit or Structure > Query) copies the selected atoms, or every structure on the page, as SMARTS with its query features; Export SMARTS... saves a `.sma` file (in the desktop app it copies instead, until 0.7.0). + +## R-groups and Markush structures + +1. Draw the scaffold and each substituent as its own structure. Mark where a substituent attaches with an attachment point: a `*` atom with one bond. +2. Select the scaffold atom that varies and choose Structure > Query > Define R-Group... (or right-click it). The atom becomes R1 (the next free number). +3. In the dialog, pick the members, the occurrence (`1`, a range such as `1-3`, or `>0`), whether unfilled positions are hydrogen (Rest H), and an if-then condition (R1 only when R2 is present). + +The canvas writes `R1 =` beside each member, a wavy mark at its attachment and a summary line under the scaffold. Structure > Query > Enumerate R-Groups... lists every structure the definition stands for, with its SMILES and formula; Copy SMILES copies them all. Molfiles in V3000 carry the R-group definitions in and out. + +Not built yet: link nodes and variable attachment (a substituent on any position of a ring). diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index a12b29a5..c76c94e6 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -5,6 +5,7 @@ - [Drawing](Drawing) - [Annotations](Annotations) - [Reactions](Reactions) +- [Stereo and Queries](Stereo-and-Queries) - [Agents](Agents) - [Terminal](Terminal) - [Extensions](Extensions) From b756d57b8376db0c822bb2979da0ace226890b9c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:01:54 -0500 Subject: [PATCH 272/279] docs(wiki): add the Analysis page and bring Home to 0.6.0 (0.6.0) Describes the properties section with its methods, the isotope plot, Copy Analysis and the Check Structure panel, linked from the sidebar and Home, whose status line now names 0.6.0. --- .docs/wiki/Analysis.md | 43 ++++++++++++++++++++++++++++++++++++++++++ .docs/wiki/Home.md | 3 ++- .docs/wiki/_Sidebar.md | 1 + 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 .docs/wiki/Analysis.md diff --git a/.docs/wiki/Analysis.md b/.docs/wiki/Analysis.md new file mode 100644 index 00000000..ebe59b82 --- /dev/null +++ b/.docs/wiki/Analysis.md @@ -0,0 +1,43 @@ +# Analysis + +From 0.6.0 the Analysis panel computes drug-like properties and the isotope pattern with the method behind every number, and Check Structure lists problems with a code for each. The engine side, with every route, is [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md). + +## The Analysis panel + +Open it with Analysis > Show Analysis. It follows the selection, or the whole page when nothing is selected, and is worked out only while it is open. + +| Row | Method (the row's tooltip) | +| --- | --- | +| Formula | Hill order with charge, abbreviations expanded | +| Molecular weight | standard atomic weights (CIAAW conventional values) | +| Exact mass | monoisotopic mass from the most abundant isotope of each element | +| m/z | exact mass over the charge, electron mass corrected (charged species only) | +| Elemental analysis | mass percent of each element | +| cLogP | Wildman and Crippen 1999 atom contributions (typical error 0.5 to 0.7 log units) | +| tPSA | topological polar surface area from N and O (Ertl 2000), in ร…ยฒ | +| Molar refractivity | Wildman and Crippen atom contributions, in cmยณ/mol | +| H-bond donors, acceptors | Lipinski counting (N-H and O-H; N and O) | +| Rotatable bonds | non-ring single bonds between non-terminal heavy atoms | +| Lipinski rule of five | MW at most 500, cLogP at most 5, donors at most 5, acceptors at most 10; passes with at most one violation | + +Hover a row to read its method. Values stay in place while new ones load, so the panel never jumps. For ibuprofen the panel reads C13H18O2, 206.28, 206.1307, cLogP 3.07, tPSA 37.30 and a Lipinski pass. + +Under the rows, the isotope pattern is drawn as sticks with the base peak in the accent colour; hover a stick for its mass and abundance. Below it are the monoisotopic mass and the m/z of [M+H]+, [M+Na]+ and [M-H]- (an ion shows its own m/z instead). The pattern is exact, merged at 0.01 Da and cut at 0.1 percent of the base peak: dichloromethane shows M+2 at about 64 percent of M, bromobenzene M+2 at about 97 percent. + +Analysis > Copy Analysis (or the panel's Copy button) puts every value with its method, the peaks and the adducts on the clipboard as text. Analysis > Compute Properties opens the panel on the selection. + +## Check Structure + +Structure > Check Structure opens a panel that stays open while you work. It lists errors, warnings and notes for the selected structures, or every structure on the page: + +| Kind | Examples | +| --- | --- | +| Errors | valence errors, bonds that cannot be read, a broken abbreviation | +| Warnings | unusual charges, misplaced, ambiguous or conflicting wedges, a wedge between two centres, undefined double bonds, overlapping atoms, very short or long bonds, unknown labels or isotopes, aromatic bonds outside a ring, stereo groups on atoms that are not centres, R-group gaps | +| Notes | undefined stereocentres, wavy-bond centres, charge imbalance, query features, uncommon isotopes, crossing bonds, labels such as Ac or Pr that are also element symbols | + +Click a row to select its atoms and bonds on the canvas. Rows with Fix repair the problem as one undo step: wedge problems are redrawn by Assign Wedges, abbreviation problems expanded. Check Again runs the check once more and keeps the list in place. Metal cations in salts, such as Na+, are not valence errors. An atom with "ignore warnings" set drops the issues that concern only it. + +## For agents + +The MCP tools `properties`, `check_structure`, `stereo` and `substructure` give agents the same numbers, issues, CIP labels and matches as JSON with atom and bond ids, without asking the person, because they only read. `properties` adds rings, aromatic rings, fraction Csp3, stereocentres, refined donor and acceptor counts, TPSA with S and P, and the Veber rules. See [Agents](Agents). diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index 8385651e..d7371c97 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,7 +2,7 @@ FormChem is the chemical structure drawing suite of the FormAI family: local-first, no account, on macOS, Windows and Linux. It runs in the browser or as a Tauri desktop app, with a local engine that holds every document, and an MCP server so Claude Code, Codex, Cursor or Antigravity can work in the same window you see. -FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, and 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers. +FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers, and 0.6.0 stereo, queries and analysis: CIP labels and enhanced stereo, abbreviations, query structures and R-groups, calculated properties with their methods, the structure check and the isotope pattern. | Page | What it covers | | --- | --- | @@ -11,6 +11,7 @@ FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, wi | [Annotations](Annotations) | Arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures, captions, arranging and grouping, templates, Find and rulers | | [Reactions](Reactions) | Reaction schemes, roles, atom mapping, balance, stoichiometry, RXN and reaction SMILES | | [Stereo and Queries](Stereo-and-Queries) | CIP labels, enhanced stereo groups, wedges, abbreviations, query atoms and bonds, substructure search, SMARTS, R-groups and Markush structures | +| [Analysis](Analysis) | Calculated properties with their methods, the isotope pattern, Copy Analysis and Check Structure | | [Agents](Agents) | The MCP server, agent configs, skills and consent | | [Terminal](Terminal) | The terminal and agent dock | | [Extensions](Extensions) | Form extensions in FormChem | diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index c76c94e6..b36e1ab9 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -6,6 +6,7 @@ - [Annotations](Annotations) - [Reactions](Reactions) - [Stereo and Queries](Stereo-and-Queries) +- [Analysis](Analysis) - [Agents](Agents) - [Terminal](Terminal) - [Extensions](Extensions) From 41c678bb19789ac169fe8e977b3c31c5842dd150 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:02:21 -0500 Subject: [PATCH 273/279] docs(wiki): bring Drawing, Reactions and Project Format to 0.6.0 (0.6.0) The menus, view toggles, hand-set reaction roles and the new fragment, atom, R-group and expansion fields were missing from the tour pages. --- .docs/wiki/Drawing.md | 4 ++-- .docs/wiki/Project-Format.md | 8 ++++++-- .docs/wiki/Reactions.md | 6 +++++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.docs/wiki/Drawing.md b/.docs/wiki/Drawing.md index 07cb9e4e..1c17ae0e 100644 --- a/.docs/wiki/Drawing.md +++ b/.docs/wiki/Drawing.md @@ -19,7 +19,7 @@ Press a tool's key with the pointer away from atoms and bonds, or click it on th | `Z` | Zoom | Zoom | Click to zoom in at the point, `Alt`-click to zoom out. `Ctrl` with the wheel zooms anywhere; View has Zoom In (`Ctrl+=`), Zoom Out (`Ctrl+-`), Zoom to Fit (`Ctrl+0`) and Actual Size (`Ctrl+1`). | | `W` `P` `K` `G` `O` | Arrows, Symbols, Brackets, Shapes, Orbitals | and Table, TLC, Image, Caption (in Text) | The annotation tools of 0.5.0; see [Annotations](Annotations). Reaction arrows and plus signs make a scheme FormChem can read; see [Reactions](Reactions). | -Right-click an atom, a bond or the paper for its context menu. Structure has Clean Up Structure, Lay Out Structure, Check Structure and the flips; Arrange has the stacking order, align, distribute, Rotate 90 Degrees, Group and Ungroup; Edit has Duplicate (`Ctrl+D`), Delete, Select All (`Ctrl+A`) and Find. With the selection tool, a selected arrow, line or box shows handles to reshape it. +Right-click an atom, a bond or the paper for its context menu; from 0.6.0 the atom and bond menus also hold Atom Query, Enhanced Stereo, Query Bond and Define R-Group, and a selection of several atoms Contract Abbreviation. Structure has Clean Up Structure, Lay Out Structure, the abbreviation and explicit hydrogen commands, Assign Wedges, the Enhanced Stereo and Query submenus, Check Structure, Compute Properties and the flips (see [Stereo and Queries](Stereo-and-Queries) and [Analysis](Analysis)); Arrange has the stacking order, align, distribute, Rotate 90 Degrees, Group and Ungroup; Edit has Duplicate (`Ctrl+D`), Delete, Select All (`Ctrl+A`), Find, Find Substructure and Copy as SMARTS. With the selection tool, a selected arrow, line or box shows handles to reshape it. ## Hover keys @@ -73,4 +73,4 @@ Structures can also come in without drawing: Insert > Structure from SMILES, Ins ## Styles -New drawings start from the default style chosen in Preferences > Drawing (Journal standard (1996), Journal variant B, Large screen or New document) with the bond length, line width, bold width and label size set there on top; choosing a style fills those numbers in from it. Preferences > Drawing and Chemistry also switch element colours, carbon labels, aromatic circles, valence warnings and stereo labels for the view. +New drawings start from the default style chosen in Preferences > Drawing (Journal standard (1996), Journal variant B, Large screen or New document) with the bond length, line width, bold width and label size set there on top; choosing a style fills those numbers in from it. Preferences > Drawing and Chemistry also switch element colours, carbon labels, aromatic circles, valence warnings and stereo labels for the view. The View menu has Show Stereochemistry (CIP labels), Show Enhanced Stereo Groups (abs, and1, or1 under the labels) and Show Query Features (the purple query tags); the last two are choices of this window, not of the drawing. diff --git a/.docs/wiki/Project-Format.md b/.docs/wiki/Project-Format.md index d74320ed..e61a18a7 100644 --- a/.docs/wiki/Project-Format.md +++ b/.docs/wiki/Project-Format.md @@ -23,11 +23,15 @@ The engine writes the package to a temporary file in the same folder and renames - From 0.5.0 the other object kinds are drawn: `arrow` (15 types, heads at either end, a signed `bend`, and `anchors` that tie an end to an atom, a lone pair, a bond or the space between two atoms), `plus`, `bracket`, `shape`, `line`, `table`, `tlc`, `orbital`, `image` and `caption`. A `group` lists its `children` back to front; members are in no page `order`. - A `caption` has a `target` (the structure it belongs to) and an `offset` from the target's bottom centre; its `x`, `y` are a cache kept in step whenever the target or the caption moves. Compound numbers are `number: {auto: true, value: "1"}`. - `page.reactions` lists reactions and their steps: the arrow, the reactant, product, agent and condition object ids, `explicit` (roles set by hand or by a file, kept by perception), optional `coefficients`, and optional `stoich`, the amounts you typed in the Stoichiometry panel (`scale_mmol`, `limiting`, `product`, `isolated_mg`, and per component `equiv`, `mass_mg`, `volume_ml`, `density_g_ml`, `conc_m`, `purity_pct`, `mw`). Moles, masses implied by equivalents, the limiting reagent and yields are worked out, never stored. A `table` with `stoich: {reaction, step}` is a stoichiometry grid. Atom map numbers are `map` on atoms and reacting marks `reacting` on bonds. +- From 0.6.0 a fragment may carry `stereo_groups` (enhanced stereo: `{kind: "abs"}`, `{kind: "and", n: 1, atoms: [...]}`, `{kind: "or", n: 2, atoms: [...]}`) and `chiral` (`absolute`, `relative` or `racemic`). For the chemistry, `relative` puts every stereocentre in no group into one OR group and `racemic` into one AND group, each with the next free number; `absolute` also sets the molfile chiral flag. +- An atom's `query` holds its query features: `list` and `not`, `generic` (A, AH, Q, QH, X, XH, M, MH), `ring_bonds`, `subst`, `unsat`, `h_min`, `aromatic`, and from 0.6.0 `smarts`, the SMARTS text of an atom query the other fields cannot express (SMARTS import writes it; it wins over the other fields). A bond's `query` is `any`, `single_or_double`, `single_or_aromatic` or `double_or_aromatic`, and `topology` is `ring` or `chain`. +- `rgroups` on a scaffold fragment define its R-groups by number: `members` (fragment ids), `occurrence`, `rest_h`, `if_then`, and `attach`, a map of member fragment id to its attachment atom ids. A member without an `attach` entry attaches at its atoms with `data.attach` 1 or 2, else at its `*` stubs (no label, one bond, standing for the R atom), else at its first atom. +- `expansions` hold what an abbreviation atom stands for (its atoms, bonds, attachment atoms and reversed label); `source` is `builtin` when the expansion came from the shipped library and `user` otherwise. - `media` maps a media id to `{name, mime, bytes, w, h, sha256}`; an `image` object names the id. The bytes go into the package as `media/[id].[ext]`, and only ids listed in `media` are written. ## What is not in the file -The engine's chemistry (canonical SMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors, warnings, and from 0.5.0 the balance check of every reaction step) is a derived cache. It is rebuilt when a drawing opens and broadcast after every change, keyed by fragment id and document revision, and never saved. Undo history is kept per open drawing by the engine and is not saved either. +The engine's chemistry (canonical SMILES, InChI and InChIKey, formula, masses, elemental analysis, implicit hydrogens, valence errors, warnings, from 0.5.0 the balance check of every reaction step, and CIP labels that follow the stereo groups and the chiral flag) is a derived cache. It is rebuilt when a drawing opens and broadcast after every change, keyed by fragment id and document revision, and never saved. Undo history is kept per open drawing by the engine and is not saved either. ## Changes are transactions @@ -35,4 +39,4 @@ Every change is a transaction: a list of `set`, `ins`, `del` and `move` ops on J ## Other formats -Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length; RXN files and CML or CDXML files with a reaction open as drawn schemes with their roles set. A reaction step exports as reaction SMILES or RXN (V2000 or V3000) from 0.5.0 ([Reactions](Reactions)); exporting whole drawings to the other formats arrives in 0.7.0. Templates use the document format too ([`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md)). +Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length; RXN files and CML or CDXML files with a reaction open as drawn schemes with their roles set. A reaction step exports as reaction SMILES or RXN (V2000 or V3000) from 0.5.0 ([Reactions](Reactions)); exporting whole drawings to the other formats arrives in 0.7.0. From 0.6.0 the engine also writes and reads V3000 molfiles with query features, enhanced stereo and R-group blocks, and SMARTS for query structures ([Stereo and Queries](Stereo-and-Queries)); a molfile with its chiral flag at 0 opens with its centres absolute. Templates use the document format too ([`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md)). diff --git a/.docs/wiki/Reactions.md b/.docs/wiki/Reactions.md index 4606bded..a0d981df 100644 --- a/.docs/wiki/Reactions.md +++ b/.docs/wiki/Reactions.md @@ -24,7 +24,11 @@ Reaction > Perceive Reactions reads every reaction arrow on the page and stores The nearest structure on each side takes the role; the next one joins it only across a plus sign or a gap under one bond length. Captions never take a role. Resonance, electron-pushing, fishhook, plain, fragmentation and dissociation arrows are not reaction steps; a retrosynthetic arrow reads from right to left. -Running it again keeps the same reaction ids, your amounts and coefficients, and changes nothing when nothing moved. Steps read from a reaction file keep the roles the file gave. Set Reaction Roles, to choose roles by hand, arrives in 0.6.0. +Running it again keeps the same reaction ids, your amounts and coefficients, and changes nothing when nothing moved. Steps read from a reaction file keep the roles the file gave, and so do steps whose roles you set by hand. + +## Set Reaction Roles + +When perception reads a role wrongly (water drawn after the arrow that should count as a reagent, a catalyst structure on the line), select the structures or text and choose Reaction > Set Reaction Roles.... The dialog lists the step's members and the selected objects, one row each with a role: Reactant, Product, Agent, Condition or None. Apply changes them as one undo step and marks the step's roles as set by hand, so Perceive Reactions keeps them from then on. Coefficients and stoichiometry amounts of an object that left its side are removed in the same step. Structures, text, captions, groups, pictures, shapes and tables can take a role; the arrow cannot. The command works on the step touching the selection, and perceives the page first when it has no step. Agents run it without the dialog: `run_command {id: "set-reaction-roles", params: {role: "agent", objects: [...]}}`. ## Map Atoms From 50420ebb7a23165f22020406837fc7b206121b62 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:02:45 -0500 Subject: [PATCH 274/279] docs(wiki): list the fourteen MCP tools and the chemistry commands for agents (0.6.0) The page still counted ten tools; it now describes properties, check_structure, stereo and substructure, the get_context line as the server writes it, and the stereo, query and role commands agents run. --- .docs/wiki/Agents.md | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index f7e499fd..8c29b749 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -15,7 +15,7 @@ FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at ## Tools -Ten tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` (working, ready or question, with a note), and from 0.5.0 four reaction tools: +Fourteen tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` (working, ready or question, with a note), from 0.5.0 four reaction tools and from 0.6.0 four analysis tools: | Tool | Kind | What it does | | --- | --- | --- | @@ -23,15 +23,19 @@ Ten tools: `get_context` (version, window, agent access, the open drawings, cata | `map_reaction {doc?, reaction?, step?, mode?}` | changes the drawing | maps reactant atoms to product atoms and marks bonds broken, formed and changed (`mode`: `discard`, `keep`, `alter`, or `clear` to remove) | | `export_reaction {doc?, reaction?, step?, format?}` | reads | a step as reaction SMILES (`smiles`) or RXN (`rxn`, `rxnv3000`) with its map numbers | | `reaction_stoichiometry {doc?, reaction?, step?}` | reads | moles, equivalents, masses, volumes, the limiting reagent and yields from the amounts in the step, with the balance check | +| `properties {doc?, object?}` | reads | per fragment: formula, MW, exact mass, cLogP, molar refractivity, TPSA (also with S and P), donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis, each with the RDKit method behind it | +| `check_structure {doc?, object?, query?}` | reads | the structure check: issues with a code, a severity (error, warning, info), the atom and bond ids, and the fix the window can run; `query: true` leaves out query-feature notes | +| `stereo {doc?, object?}` | reads | each stereocentre, double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), defined, undefined or unknown, its enhanced stereo group and the CXSMILES | +| `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | reads | every hit of a SMARTS pattern, or of a fragment of the drawing drawn as the query, with its fragment id and the matched atom and bond ids | -`doc` may be left out when one drawing is open; `reaction` and `step` default to the first. `get_context`, `list_commands`, `extensions_list`, `export_reaction` and `reaction_stoichiometry` read; `run_command`, `extension_command`, `perceive_reactions`, `map_reaction` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run. +`doc` may be left out when one drawing is open; `reaction` and `step` default to the first, and `object` (absent) means every fragment. `get_context`, `list_commands`, `extensions_list`, `export_reaction`, `reaction_stoichiometry` and the four analysis tools read; `run_command`, `extension_command`, `perceive_reactions`, `map_reaction` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run. ## Working on drawings `get_context` lists every drawing open in the window, oldest first, as text and in `structuredContent.documents`: ``` -Documents: 1 open in the window (change them with run_command and the window's commands; dedicated drawing tools arrive in 0.8.0) +Documents: 1 open in the window (change them with run_command and the window's commands, write reactions with perceive_reactions and map_reaction, read them with export_reaction, reaction_stoichiometry, properties, check_structure, stereo and substructure; atom and bond tools arrive in 0.8.0) - d4n2k8q0z "Untitled" (unsaved changes) ยท rev 1 ยท 1 fragment ยท C6H6O ยท not saved yet ``` @@ -47,10 +51,13 @@ An agent changes drawings with the window's own commands, so every change is one | Arrange the selection | `select-all`, then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h`, `distribute-v`, `bring-front`, `send-back`, `group`, `ungroup` | | Insert a template | `run_command {id: "insert-template", params: {id: "benzene"}}`: one undo step, centred in view at the drawing's bond length; `GET /api/templates` lists the ids | | Reactions | `perceive-reactions`, `map-atoms`, `clear-mapping`, `balance-reaction` through `run_command`, or the four reaction tools above, which also return the results; `check-reaction` and the Stoichiometry panel (`show-stoichiometry`) open for the person | -| Check | `check-structure` opens a dialog for the person; formula and masses are in the Analysis panel (`show-analysis`) | +| Reaction roles | `set-reaction-roles {role, objects}` gives objects a role in the selected step (reactant, product, agent, condition or none) without the dialog | +| Stereo, hydrogens, abbreviations | `assign-wedges`, `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group`, `add-hydrogens`, `remove-hydrogens`, `expand-abbreviation`, `contract-abbreviation` on the selection; read the result back with `stereo` | +| Queries and R-groups | `set-atom-list`, the `set-query-bond-` commands, `define-rgroup`, `enumerate-markush`, `copy-smarts`; search with the `substructure` tool | +| Check and properties | the `check_structure` and `properties` tools return the issues and values; `check-structure` and `compute-properties` open the panels for the person | | Undo, save | `undo`, `redo`, `save` (a drawing without a file asks the person for a name) | -Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Beyond the reaction tools, dedicated drawing tools for agents (atoms and bonds by id, reading structures back, rendering, conversion) arrive in 0.8.0. The engine's HTTP routes for reactions, templates and media are listed in [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md), [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md) and [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md). +Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Beyond the reaction and analysis tools, dedicated drawing tools for agents (atoms and bonds by id, reading whole structures back, rendering, conversion) arrive in 0.8.0. The engine's HTTP routes for reactions, analysis, templates and media are listed in [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md), [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md), [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md) and [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md). ## Consent From 6e9ba0c0f19efdfd18a9d8bc338189c1dfbbc1a4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:03:00 -0500 Subject: [PATCH 275/279] docs(wiki): describe what build_app checks and the Tauri CLI pin rule (0.6.0) The desktop page did not say how a local build is checked; it now lists build_app's steps, the CLI to crate major.minor rule behind the 0.6.0 build fix, and that the owner's macOS build succeeded. --- .docs/wiki/Desktop.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/.docs/wiki/Desktop.md b/.docs/wiki/Desktop.md index a96a783e..c273566f 100644 --- a/.docs/wiki/Desktop.md +++ b/.docs/wiki/Desktop.md @@ -20,3 +20,23 @@ The desktop app is a thin Tauri 2 shell around the same window, with the engine - Signing identities are held by formcompiler; local builds are unsigned. Run it from source with `./formchem desktop dev`; `./formchem desktop build` makes a local bundle. Released builds come only from formcompiler (see [Releasing](Releasing)). + +## Building on this machine + +`./build_app` (or `build_app.bat` on Windows) builds the desktop app from a fresh checkout in one step and writes everything it does to `build_app.log`. In order it checks and prepares: + +| Step | What it checks or does | +| --- | --- | +| System | macOS: the Xcode Command Line Tools; Linux: WebKitGTK 4.1 and the build packages | +| Python | 3.12 or newer (it tries `python3.14`, `python3.13`, `python3.12`, then `python3`); an older venv is recreated | +| Node.js | 20.19 or newer | +| Rust | rustc and cargo from the same install (rustup expected), building for this machine's architecture | +| Notices | `THIRD-PARTY-NOTICES.txt` must exist (`python3 setup/notices.py` after `./formchem install`) | +| Engine packages | `backend/requirements*.txt` into `backend/venv`, reinstalled when the files or Python change | +| Window packages | `npm ci` in `frontend/`, rerun when `package-lock.json` or Node change | +| Tauri CLI | `frontend/node_modules/.bin/tauri` must exist, and its major.minor must equal the `tauri` crate's in `src-tauri/Cargo.lock`; each `@tauri-apps/plugin-*` package must share major.minor with its `tauri-plugin-*` crate | +| Build | the window (`npm run build`), the engine frozen by PyInstaller with the window, the notices and the template library, a `--selfcheck` of the frozen engine, then the Tauri bundle (`.app` and `.dmg` on macOS, `.deb`, `.rpm` or AppImage on Linux) | + +**The Tauri CLI pin.** `@tauri-apps/cli` is a dev dependency in `frontend/package.json`, pinned at 2.12.6 because the `tauri` crate in `Cargo.lock` is 2.12.7: the CLI's major.minor must always equal the crate's, so a crate update to 2.13 needs the CLI at 2.13 in the same change. Before 0.6.0 package.json did not list the CLI at all and the build stopped with "the Tauri CLI did not install"; the message now names package.json. With the pin, the owner's `./build_app` on macOS (Apple silicon, Python 3.14) built the app. `./formchem desktop check` runs the same version comparison without building. + +`--reinstall` reinstalls both package sets, `--clean` removes earlier build output, `--bundles` picks the bundle kinds and `--config` merges an extra Tauri config (formcompiler's contract mode). From db8844f1ad36ecb11637c0602020fb93b992ecfa Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:03:19 -0500 Subject: [PATCH 276/279] docs(readme): add the stereo, query and structure check features and fourteen MCP tools (0.6.0) The feature grid and agent paragraph stopped at 0.5.0 and still listed stereochemistry as coming next; the badge is left to the release commit. --- README.md | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index fde7821f..374807bb 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ ## Features -FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms and works out the amounts. +FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms, works out the amounts, labels stereochemistry and computes properties with the method behind each number.

Arrange and style

Duplicate, delete, flip, rotate, align and distribute the selection; Drawing preferences set the default style and its bond length, widths and label size; element colours, carbon labels and stereo labels on request.

MCP server

Six tools over HTTP and stdio: agents see the open drawings with their formulas, insert structures from SMILES and run the same commands as the menus.

Reactions

Perceive Reactions reads reactants, products, reagents and conditions around each arrow, multi-step schemes included. Atom mapping with reacting bonds, balance checks with suggested coefficients, and reaction SMILES and RXN in and out.

Annotations

Fifteen arrow types and anchored electron-pushing arrows, plus signs, brackets, shapes, lines, tables, TLC plates, orbitals, pictures and attached captions, with handles, stacking order and groups.

Stoichiometry and templates

A stoichiometry panel for moles, equivalents, the limiting reagent and yields, insertable as a table, and 206 original templates from rings to glassware. Find and rulers with guides.

MCP server

Ten tools over HTTP and stdio: agents see the open drawings with their formulas, run the same commands as the menus, and perceive, map, export and measure reactions.

The family shell

Home, Preferences, twelve menus with full keyboard use, Find a Command, the terminal and agent dock, Help and updates, in 26 interface languages.

Form extensions

Extensions installed by FormPortal run in a sandboxed frame from the Extensions menu and panel, and ask before they read or change a drawing.
@@ -38,7 +38,7 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th - + @@ -47,7 +47,12 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th - + + + + + + @@ -55,7 +60,6 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th ### Coming next -- Stereochemistry, query structures and analysis - Reading and writing the common chemical file formats - Names, predicted spectra and spectrum viewing - 3D models of molecules @@ -63,7 +67,7 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th ## Built for agents -The engine's MCP server drives the same command catalogue as the window through `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus four reaction tools: `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`. Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0. +The engine's MCP server drives the same command catalogue as the window through `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus four reaction tools (`perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`) and four analysis tools (`properties`, `check_structure`, `stereo`, `substructure`). Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0. ```sh ./formchem agents install # writes .mcp.json, .codex/config.toml, .cursor/mcp.json and Antigravity's ~/.gemini/config/mcp_config.json, installs the skills @@ -100,7 +104,7 @@ cd formchem `./formchem desktop dev` opens the desktop window instead. On Windows use `formchem.bat install` and `formchem.bat`. The engine listens on `127.0.0.1:8220` (MCP at `/mcp`); `FORMCHEM_DATA_DIR` moves the data folder from `~/formchem`. > [!IMPORTANT] -> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures and reactions; export, stereo tools and 3D come in later versions. Nothing is built or released for download yet. +> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures and reactions, with stereochemistry, query structures and calculated properties; file export, names, spectra and 3D come in later versions. Nothing is built or released for download yet. **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Report security issues privately as [`SECURITY.md`](SECURITY.md) describes. @@ -108,7 +112,7 @@ cd formchem | Path | What it is | |---|---| -| `backend/` | FastAPI engine: documents, chemistry and reactions, templates, live channel, terminal dock, extensions, MCP | +| `backend/` | FastAPI engine: documents, chemistry, reactions and analysis, templates, live channel, terminal dock, extensions, MCP | | `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, shell, menus, Home, Preferences, dock | | `setup/` | Install, boot, build, freeze and agent setup scripts | | `src-tauri/` | Desktop shell and the engine sidecar | From 22aea0aab971a72e7bf167c2db7ff5419722ed2a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:05:59 -0500 Subject: [PATCH 277/279] docs(skills): teach the harness the analysis tools, chemistry commands and reaction roles (0.6.0) Adds the structure-analysis sub-skill for properties, check_structure, stereo and substructure, brings the router, catalogue and evaluations to fourteen tools, and mirrors the pack with agents sync. --- .agents/skills/formchem-harness/EVALS.json | 44 +++++++++++- .agents/skills/formchem-harness/SKILL.md | 24 ++++--- .../extension-drawings/SUB-SKILL.md | 2 +- .../sub-skills/handoff/SUB-SKILL.md | 4 +- .../sub-skills/reactions/SUB-SKILL.md | 6 +- .../session-and-connection/SUB-SKILL.md | 2 +- .../structure-analysis/SUB-SKILL.md | 69 +++++++++++++++++++ .../sub-skills/visual-qa/SUB-SKILL.md | 2 +- .../sub-skills/window-commands/SUB-SKILL.md | 7 +- .../references/command-catalogue.md | 31 +++++++-- .claude/skills/formchem-harness/EVALS.json | 44 +++++++++++- .claude/skills/formchem-harness/SKILL.md | 24 ++++--- .../extension-drawings/SUB-SKILL.md | 2 +- .../sub-skills/handoff/SUB-SKILL.md | 4 +- .../sub-skills/reactions/SUB-SKILL.md | 6 +- .../session-and-connection/SUB-SKILL.md | 2 +- .../structure-analysis/SUB-SKILL.md | 69 +++++++++++++++++++ .../sub-skills/visual-qa/SUB-SKILL.md | 2 +- .../sub-skills/window-commands/SUB-SKILL.md | 7 +- .../references/command-catalogue.md | 31 +++++++-- agents/manifest.json | 1 + 21 files changed, 329 insertions(+), 54 deletions(-) create mode 100644 .agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md create mode 100644 .claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md diff --git a/.agents/skills/formchem-harness/EVALS.json b/.agents/skills/formchem-harness/EVALS.json index fb9b9f39..079543e0 100644 --- a/.agents/skills/formchem-harness/EVALS.json +++ b/.agents/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.5.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.5.0 has drawings and four reaction tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water).", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.6.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.6.0 has drawings, four reaction tools and four read-only analysis tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction and analysis tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 17 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O.", "evals": [ { "id": 1, @@ -161,10 +161,52 @@ "Quotes the theoretical yield with its unit only when the answer gives one, never computing it from its own molecular weights", "When no amounts are typed, posts a question handoff asking the person to type a mass, volume, equivalents or scale in the Stoichiometry panel, and says no tool can type them" ] + }, + { + "id": 15, + "name": "druglike-properties-with-methods", + "prompt": "Is the structure in my FormChem drawing drug-like? Give me cLogP and TPSA.", + "files": [], + "expected_behavior": [ + "Calls get_context, then the properties tool (not compute-properties through run_command)", + "Quotes cLogP 3.07 and TPSA 37.3 with their units and the methods the tool names (Crippen.MolLogP, rdMolDescriptors.CalcTPSA), and the Lipinski and Veber verdicts as the tool gives them", + "Does not compute any value with its own chemistry and present it as FormChem's", + "Posts no approval-gated call for this read-only question" + ] + }, + { + "id": 16, + "name": "racemic-and-group", + "prompt": "In FormChem, mark the stereocentre of my ibuprofen as racemic and tell me what the CXSMILES becomes.", + "files": [], + "expected_behavior": [ + "Calls stereo first to find the centre and its current label S", + "Says the command acts on the canvas selection and either asks the person to select the centre or explains what select-all would include, then runs set-stereo-group-and once", + "Calls stereo again and quotes the new CXSMILES with its &1 group exactly as returned", + "Ends with a ready handoff saying the change is one undo step" + ] + }, + { + "id": 17, + "name": "find-carboxylic-acids", + "prompt": "Which structures in my FormChem drawing have a carboxylic acid?", + "files": [], + "expected_behavior": [ + "Calls substructure with a SMARTS such as C(=O)[OH] (or [CX3](=O)[OX2H1])", + "Reports the hit count and the fragment ids from the answer, naming the structures by what get_context or the tools say", + "Does not run search-substructure through run_command to get the answer, since its result is a selection the agent cannot read" + ] } ], "trigger_evals": [ {"query": "what can FormChem do at the moment", "should_trigger": true}, + {"query": "what is the cLogP and TPSA of the molecule in my FormChem drawing?", "should_trigger": true}, + {"query": "is the stereocentre in my formchem drawing R or S?", "should_trigger": true}, + {"query": "run a structure check on my FormChem drawing and list the warnings", "should_trigger": true}, + {"query": "find every carboxylic acid in my formchem drawing with SMARTS", "should_trigger": true}, + {"query": "make water an agent instead of a product in my FormChem reaction", "should_trigger": true}, + {"query": "add enhanced stereo group support to formchem's backend/app/services/chem/stereo.py", "should_trigger": false}, + {"query": "compute the Lipinski properties of this SMILES with an RDKit script", "should_trigger": false}, {"query": "map the atoms of the reaction in my formchem drawing", "should_trigger": true}, {"query": "export the drawn reaction in FormChem as an RXN file", "should_trigger": true}, {"query": "what is the limiting reagent in my formchem scheme?", "should_trigger": true}, diff --git a/.agents/skills/formchem-harness/SKILL.md b/.agents/skills/formchem-harness/SKILL.md index c366af8b..5c7d6f83 100644 --- a/.agents/skills/formchem-harness/SKILL.md +++ b/.agents/skills/formchem-harness/SKILL.md @@ -1,25 +1,25 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, clean up, undo, zoom, run a menu command or extension, read or change the open fchem drawing through an extension, check valence, perceive a reaction scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry or yield, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) are available. Covers connecting on 127.0.0.1:8220, approval, the command catalogue, extension drawings, handoff, and what waits for the 0.8.0 drawing tools. Not for changing FormChem's source (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, undo, run a menu command or extension, read the open fchem drawing, perceive or map a reaction, export reaction SMILES or RXN, read stoichiometry, set reaction roles, get cLogP, TPSA or Lipinski, check a structure, read R/S labels and stereo groups, find a substructure by SMARTS, add hydrogens, contract an abbreviation, define an R-group, or asks what FormChem can do, and FormChem is named or its tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry, properties, check_structure, stereo, substructure) are available. Covers 127.0.0.1:8220, approval, handoff and what waits for 0.8.0. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.5.0" + version: "0.6.0" --- # FormChem harness FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it. -## What exists today (0.5.0) +## What exists today (0.6.0) -FormChem 0.5.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 adds reactions and annotations: arrows, plus signs, brackets, shapes, tables, TLC plates, orbitals, pictures and captions, reaction perception, atom mapping, balance, the Stoichiometry panel, a template library of 206, Find and rulers. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. +FormChem 0.6.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 added reactions and annotations (arrows, brackets, shapes, tables, TLC plates, captions, reaction perception, atom mapping, balance, the Stoichiometry panel, 206 templates, Find and rulers). 0.6.0 adds stereo, queries and analysis: CIP labels and enhanced stereo groups, Assign Wedges, abbreviations, explicit hydrogens, atom lists and query bonds, R-groups and Markush enumeration, substructure search and SMARTS, calculated properties with their methods, the isotope pattern, the Check Structure panel and Set Reaction Roles. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. -The MCP server has ten tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, and the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. +The MCP server has fourteen tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. -**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out, check structure and zoom (`window-commands`). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, and read its stoichiometry and balance (`reactions`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). +**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out and zoom (`window-commands`), plus the chemistry commands (wedges, stereo groups, hydrogens, abbreviations, query features, R-groups). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry and balance, and set roles with `set-reaction-roles {role, objects}` (`reactions`). Through the analysis tools: properties with their methods, the structure check, CIP labels and stereo groups, and substructure hits by id (`structure-analysis`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). -**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading SMILES or InChIKey of a structure back through MCP (the formula in `get_context` and the reaction tools' answers are all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. +**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading the whole structure or its InChIKey back through MCP (the formula in `get_context`, the SMILES and CXSMILES in `stereo` and the other tools' answers are all), no rendering, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) @@ -39,7 +39,8 @@ formchem-harness/ sub-skills/ session-and-connection/ connecting, get_context, the approval question, errors window-commands/ drawing work through run_command; references/command-catalogue.md - reactions/ the four reaction tools and the Reaction menu commands + reactions/ the four reaction tools, the Reaction menu commands and Set Reaction Roles + structure-analysis/ the four analysis tools and the stereo, hydrogen, abbreviation and query commands extension-drawings/ reading and changing the drawing through a Form extension handoff/ handoff states, notes, clearing, what the person sees visual-qa/ checking what the person sees without a render tool @@ -54,8 +55,9 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` | | "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` | | Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` | -| The reaction in the drawing: its steps, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | -| Read atoms, bonds, SMILES, InChIKey or valence errors from the open drawing, change it by id, check a structure | `extension-drawings` (and `window-commands` when no extension fits) | +| The reaction in the drawing: its steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | +| Properties (cLogP, TPSA, Lipinski), a structure check, R or S, stereo groups, a substructure or SMARTS match, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` | +| Read atoms, bonds, InChIKey or valence errors from the open drawing, change it by id | `extension-drawings` (and `window-commands` when no extension fits) | | Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` | | Tell the person you are done, ask them something, clear your note | `handoff` | | Check what the person sees, did the command work, which commands are on | `visual-qa` | @@ -78,6 +80,8 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path | | "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it | | An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns | +| "Give smarts, or query_object" or "is not a fragment of this drawing" | `substructure` has no pattern, or the query fragment id is wrong | Pass a SMARTS or a fragment id from the tools' answers | +| A fragment slot holding `error` in an analysis answer | The engine could not read that fragment; the others are fine | Report it for that fragment and go on with the rest | ## Done means diff --git a/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md index 86da271d..98f99df2 100644 --- a/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md @@ -17,7 +17,7 @@ Use an extension as the agent's hands on the drawing until FormChem has its own ## What an extension sees - `document.read {what: "all"}`: a head (`id`, `title`, `rev`, `dirty`, `path`, `page`, `writable`, `mode`, `format`, `format_version`), the whole `document`, and `derived` when the engine's cache matches `rev`. `what` may also be `page`, `selection` or `json`. -- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). This is the honest way to check a structure before `check-structure` arrives in 0.6.0. +- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). From 0.6.0 the `check_structure` tool returns the full structure check by code and id (`structure-analysis`); the derived cache stays the way to read InChIKey and valence errors inside an extension. - With no drawing open: `writable: false`, `page: null`. Check both before offering a change. ## What an extension can change diff --git a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md index a462491b..0775514f 100644 --- a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md @@ -31,9 +31,9 @@ A handoff with a state changes what the person sees, so the first one from an ou - A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?" - No emoji, no markdown, no links the person cannot click. -## In 0.5.0 +## In 0.6.0 -A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). +A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed", "Assigned wedges in Ibuprofen; the centre reads S". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). ## Procedure diff --git a/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md index 608eb305..90c83d04 100644 --- a/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: reactions -description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, and saying plainly what only the person can do (typing amounts, Set Reaction Roles before 0.6.0). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." +description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." --- # Reactions @@ -39,7 +39,7 @@ Answer reaction questions from what FormChem computes, not from the agent's own ## Rules -- Roles come from geometry: there is no command to set them by hand before 0.6.0 (Set Reaction Roles is off with that reason). A step read from an RXN file or set by hand keeps its roles. +- Roles come from geometry unless set by hand. `run_command {id: "set-reaction-roles", params: {role, objects}}` gives the listed object ids (fragments, text, captions, groups, images, shapes or tables; never the arrow) the role `reactant`, `product`, `agent`, `condition` or `none` in the step touching the selection, as one undo step, and marks the step as set by hand so `perceive_reactions` keeps it. Without `role` it opens a dialog for the person. Read the result back with `perceive_reactions` (it lists the step as set by hand). A step read from an RXN file keeps its roles too. - Reagents drawn above the arrow are not counted in the balance; a step whose atoms come from such a reagent reads as unbalanced. Say that instead of "the reaction is wrong". - Mapping the second of two chained steps replaces the map numbers of the structure they share. Warn before mapping a second step when the first is already mapped. - Coefficients are dropped from reaction SMILES and RXN (`coefficient_dropped`); text conditions are dropped from reaction SMILES (`conditions_dropped`). Pass the warnings on. @@ -56,4 +56,4 @@ Reaction and step ids, the quoted answers, and a ready or question handoff. ## Owned resources -None of its own. `references/tools.md` at the pack root holds the generated arguments of all ten tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. +None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. diff --git a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index 9bf19f2d..f0f9e6e5 100644 --- a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -42,5 +42,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the ten tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. +- [ ] The plan uses only the fourteen tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. - [ ] No change was attempted after a refusal. diff --git a/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md new file mode 100644 index 00000000..ae33befa --- /dev/null +++ b/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md @@ -0,0 +1,69 @@ +--- +name: structure-analysis +description: "Reads and edits the chemistry of an open FormChem drawing through the four MCP analysis tools (properties, check_structure, stereo, substructure) and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem." +--- + +# Structure analysis + +## Purpose + +Answer chemistry questions about the drawing with FormChem's own numbers, quoted with the method behind them, and make the stereo, hydrogen, abbreviation and query edits as undo steps the person sees. Hands back fragment, atom and bond ids, the tool answers quoted exactly, and a handoff naming any change. + +## Preconditions + +`get_context` has been called (`session-and-connection`) and lists the drawing. The analysis tools only read, so they never ask the person; the chemistry commands change the drawing and ask the first time, like any `run_command`. + +## The four analysis tools + +| Goal | Call | What comes back | +| --- | --- | --- | +| Properties | `properties {doc?, object?}` | per fragment: formula, MW, exact mass, cLogP, MR, TPSA (and with S and P), donors and acceptors (Lipinski and refined counts), rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts, elemental analysis; each row with `method` (the RDKit call) and `note` | +| Structure check | `check_structure {doc?, object?, query?}` | issues `{code, severity, text, atoms, bonds, fix}` sorted errors first; `query: true` when the drawing is a search query | +| Stereo | `stereo {doc?, object?}` | centres, double bonds and axes with label, `state` (defined, undefined, unknown) and group (`abs`, `and1`, `or1`), the stereo groups, the chiral flag and CXSMILES | +| Substructure | `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | hits with the fragment id, matched atom and bond ids and the query-to-target map; `count`, `truncated` | + +`doc` may be left out when one drawing is open; `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`). + +## Chemistry commands (run_command) + +They act on the person's selection, or on the page when nothing is selected; the agent selects only with `select-all` or by inserting. Check `list_commands {id}` for params and the off reason first. + +| Command | Does | +| --- | --- | +| `assign-wedges` | redraws wedges and hashes of the stereocentres so they read unambiguously | +| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | puts the selected centres into an abs, new AND or new OR group, or out of any | +| `add-hydrogens`, `remove-hydrogens` | draws implicit H as atoms or folds them back; H that hold stereo, an isotope, a charge or a map number stay | +| `expand-abbreviation`, `contract-abbreviation` | expands a selected label (or every one); contract opens a dialog for the person's label | +| `set-atom-list`, the `set-query-bond-` commands, `clear-query-bond` | atom lists (a dialog) and query bonds on the selection | +| `define-rgroup`, `enumerate-markush` | R-group definition and enumeration open dialogs for the person | +| `copy-smarts`, `compute-properties`, `check-structure`, `search-substructure` | copy SMARTS to the person's clipboard, or open the panels; the tools above return the same data to the agent | + +## Procedure + +1. **Context.** `get_context`; name the drawing and pick fragment ids from the tool answers, never by guess. +2. **Read with the tool, not the command.** For values, issues, labels or matches call the analysis tool; the command opens a panel the agent cannot read. +3. **Quote with the method.** Report each value as the tool printed it, with its unit and method ("cLogP 3.07, Crippen.MolLogP; typical error 0.5 to 0.7 log units"). Never compute a property, a CIP label or a SMARTS match with your own chemistry and present it as FormChem's. +4. **Stereo states matter.** An `undefined` centre has no label because nothing fixes it; say so instead of guessing R or S. Allene axial chirality and drawn atropisomers are not perceived in this version. +5. **Change through commands, then read back.** After `assign-wedges`, a stereo group or `add-hydrogens`, call `stereo` or `check_structure` again and report what changed, with Undo as the way back. +6. **Hand off** with what changed or what the person should look at (`handoff`). + +## Rules + +- A check issue with `fix` (`wedges` or `expand`) is repaired by the person's Fix button or by `assign-wedges` or `expand-abbreviation` on the selection; say which. +- A structure check on a query drawing without `query: true` reports `query_feature` notes; they are expected, not errors. +- Metal cations such as Na+ in a salt are not valence errors; do not report them as such. +- Export SMARTS in the desktop app copies instead of saving until 0.7.0; dialogs (atom list, R-group, abbreviation label) belong to the person. + +## Gate + +- [ ] Every number, label and issue reported came from a tool answer in this session, with its unit and method where given. +- [ ] Every changing command was found in `list_commands` first and reported with its undo step. +- [ ] Undefined or unperceived stereo was named as such, never filled in. + +## Hands back + +Fragment, atom and bond ids, the quoted answers, and a ready or question handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue. diff --git a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md index 7715e05c..f4d176cd 100644 --- a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md @@ -7,7 +7,7 @@ description: "Checks what the person sees in FormChem when the agent cannot see ## Purpose -Never claim a visible result you did not confirm. In 0.5.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found), and ask the person for the rest. +Never claim a visible result you did not confirm. In 0.6.0 an agent still has no picture of the window and no render tool (it arrives in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found; `stereo`, `check_structure` and `properties` read the chemistry after a command), and ask the person for the rest. ## What you can confirm today diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index 6c6a2355..6dc92811 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: window-commands -description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." +description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." --- # Window commands @@ -33,8 +33,9 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure | | Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected | | Save | `save`; a drawing never saved before asks the person for a name, so say so in the handoff | -| Check the structure | `check-structure` opens a dialog for the person listing valence errors and warnings; the agent does not get the rows back. Say the dialog is open for them, or read valence errors through an extension (`extension-drawings`) | -| Show the formula or masses | `get_context` gives the formula of each open drawing; `show-analysis` or `toggle-analysis` opens the Analysis panel (masses, m/z, elemental analysis) for the person, whose values the agent cannot read through commands | +| Check the structure | The `check_structure` tool returns the issues with codes and ids (`structure-analysis`); `check-structure` opens the Check Structure panel for the person | +| Show the formula, masses or properties | `get_context` gives the formula of each open drawing and the `properties` tool every value with its method (`structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person | +| Stereo, hydrogens, abbreviations, query features, R-groups | Load `structure-analysis` for the commands and the tools that read the result | ## Rules diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index cb2d4371..7f9e876c 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,6 +1,6 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.5.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.6.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents @@ -9,6 +9,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.5. - Changing the drawing - Templates, objects and arrangement - Reactions +- Stereo, queries and analysis - The canvas and the view - Registered but off until a later version - What no command does yet @@ -44,7 +45,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.5. | `distribute-h`, `distribute-v` | | spread the selected objects evenly | | `clean-structure` | | tidies bond lengths and angles through the engine's layout service, keeping place and stereochemistry; selected atoms, or every structure on the page when nothing is selected. It refuses when the drawing changed during the call | | `layout-structure` | | computes fresh 2D coordinates for the structures the selection touches, or every structure on the page | -| `check-structure` | | opens a dialog for the person listing valence errors and chemistry warnings with links that select the atoms; the agent gets only "ran in the window" | +| `check-structure` | | opens the Check Structure panel for the person (rows that select atoms, Fix, Check Again); the agent gets only "ran in the window", and reads the issues with the `check_structure` tool | | `insert-text` | | switches the person's canvas to the text tool | `delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` and `insert-template` select what they added). Each changing command is one undo step. @@ -73,10 +74,30 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.5. | `copy-reaction-smiles`, `copy-reaction-rxn` | put the step on the person's clipboard; `export_reaction` gives the agent the text | | `export-reaction-smiles`, `export-reaction-rxn` | save the step to a file the person chooses | | `paste-reaction` | lays out reaction SMILES or RXN from the person's clipboard as a drawn scheme | -| `set-reaction-roles` | off: "Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing" | +| `set-reaction-roles` | params `role` (`reactant`, `product`, `agent`, `condition`, `none`) and `objects` (ids; default the selection): sets their role in the step and marks it as set by hand, one undo step; without `role` it opens the roles dialog for the person | The step is the one whose arrow or structures are selected, else the first on the page. +## Stereo, queries and analysis + +From 0.6.0. They act on the selection, or the page when nothing is selected, and each changing one is one undo step. The analysis tools (`properties`, `check_structure`, `stereo`, `substructure`) return what the panels show; see `structure-analysis`. + +| Command | What it does | +| --- | --- | +| `assign-wedges` | asks the engine for wedges and hashes that express the stereocentres unambiguously | +| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | put the selected centres into abs, a new AND group or a new OR group, or out of every group | +| `set-stereo-group`, `stereo-group-popover` | the Enhanced Stereo submenu and its popover, for the person | +| `add-hydrogens`, `remove-hydrogens` | explicit hydrogens drawn or folded back; some stay (stereo, isotope, charge, map number) | +| `expand-abbreviation` | expands the selected abbreviation atoms, or every abbreviation on the page | +| `contract-abbreviation` | opens the abbreviation dialog for the person's label | +| `set-atom-list` | opens the periodic table dialog for the person | +| `set-query-bond-any`, `set-query-bond-single_or_double`, `set-query-bond-single_or_aromatic`, `set-query-bond-double_or_aromatic`, `clear-query-bond` | query bonds on the selected bonds (list_commands gives the exact ids) | +| `define-rgroup`, `enumerate-markush` | open the R-group and enumeration dialogs for the person | +| `search-substructure` | selects matches of the selected atoms, or asks the person for SMARTS | +| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file (the desktop app copies instead until 0.7.0) | +| `compute-properties`, `copy-analysis` | open the Analysis panel on the selection; copy its values with methods to the person's clipboard | +| `show-stereo`, `show-stereo-groups`, `show-query-marks` | toggle the CIP labels, the enhanced stereo group labels and the query tags on the canvas | + ## The canvas and the view | Command | What it does | @@ -92,8 +113,8 @@ The step is the one whose arrow or structures are selected, else the first on th ## Registered but off until a later version -`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `set-reaction-roles`, `add-hydrogens` and `remove-hydrogens` (0.6.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. +`import`, `print`, `copy-smiles`, `copy-molfile`, `copy-inchi`, `copy-svg` and the whole-drawing `export-png`, `export-svg`, `export-pdf`, `export-cdxml`, `export-mol`, `export-smiles` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `demos` (0.13.0). The reaction copy and export commands and `copy-smarts` and `export-smarts` already work. Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. ## What no command does yet -Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. +Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, filling the person's dialogs (atom list, R-group, abbreviation label), reading the whole structure back beyond what `get_context` and the analysis tools give (the formula, SMILES and CXSMILES in `stereo`, properties, issues and substructure hits), rendering an image or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. diff --git a/.claude/skills/formchem-harness/EVALS.json b/.claude/skills/formchem-harness/EVALS.json index fb9b9f39..079543e0 100644 --- a/.claude/skills/formchem-harness/EVALS.json +++ b/.claude/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.5.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.5.0 has drawings and four reaction tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water).", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.6.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.6.0 has drawings, four reaction tools and four read-only analysis tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction and analysis tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 17 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O.", "evals": [ { "id": 1, @@ -161,10 +161,52 @@ "Quotes the theoretical yield with its unit only when the answer gives one, never computing it from its own molecular weights", "When no amounts are typed, posts a question handoff asking the person to type a mass, volume, equivalents or scale in the Stoichiometry panel, and says no tool can type them" ] + }, + { + "id": 15, + "name": "druglike-properties-with-methods", + "prompt": "Is the structure in my FormChem drawing drug-like? Give me cLogP and TPSA.", + "files": [], + "expected_behavior": [ + "Calls get_context, then the properties tool (not compute-properties through run_command)", + "Quotes cLogP 3.07 and TPSA 37.3 with their units and the methods the tool names (Crippen.MolLogP, rdMolDescriptors.CalcTPSA), and the Lipinski and Veber verdicts as the tool gives them", + "Does not compute any value with its own chemistry and present it as FormChem's", + "Posts no approval-gated call for this read-only question" + ] + }, + { + "id": 16, + "name": "racemic-and-group", + "prompt": "In FormChem, mark the stereocentre of my ibuprofen as racemic and tell me what the CXSMILES becomes.", + "files": [], + "expected_behavior": [ + "Calls stereo first to find the centre and its current label S", + "Says the command acts on the canvas selection and either asks the person to select the centre or explains what select-all would include, then runs set-stereo-group-and once", + "Calls stereo again and quotes the new CXSMILES with its &1 group exactly as returned", + "Ends with a ready handoff saying the change is one undo step" + ] + }, + { + "id": 17, + "name": "find-carboxylic-acids", + "prompt": "Which structures in my FormChem drawing have a carboxylic acid?", + "files": [], + "expected_behavior": [ + "Calls substructure with a SMARTS such as C(=O)[OH] (or [CX3](=O)[OX2H1])", + "Reports the hit count and the fragment ids from the answer, naming the structures by what get_context or the tools say", + "Does not run search-substructure through run_command to get the answer, since its result is a selection the agent cannot read" + ] } ], "trigger_evals": [ {"query": "what can FormChem do at the moment", "should_trigger": true}, + {"query": "what is the cLogP and TPSA of the molecule in my FormChem drawing?", "should_trigger": true}, + {"query": "is the stereocentre in my formchem drawing R or S?", "should_trigger": true}, + {"query": "run a structure check on my FormChem drawing and list the warnings", "should_trigger": true}, + {"query": "find every carboxylic acid in my formchem drawing with SMARTS", "should_trigger": true}, + {"query": "make water an agent instead of a product in my FormChem reaction", "should_trigger": true}, + {"query": "add enhanced stereo group support to formchem's backend/app/services/chem/stereo.py", "should_trigger": false}, + {"query": "compute the Lipinski properties of this SMILES with an RDKit script", "should_trigger": false}, {"query": "map the atoms of the reaction in my formchem drawing", "should_trigger": true}, {"query": "export the drawn reaction in FormChem as an RXN file", "should_trigger": true}, {"query": "what is the limiting reagent in my formchem scheme?", "should_trigger": true}, diff --git a/.claude/skills/formchem-harness/SKILL.md b/.claude/skills/formchem-harness/SKILL.md index c366af8b..5c7d6f83 100644 --- a/.claude/skills/formchem-harness/SKILL.md +++ b/.claude/skills/formchem-harness/SKILL.md @@ -1,25 +1,25 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, clean up, undo, zoom, run a menu command or extension, read or change the open fchem drawing through an extension, check valence, perceive a reaction scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry or yield, leave a note in the window, or asks what FormChem can do, and FormChem is named or the formchem tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) are available. Covers connecting on 127.0.0.1:8220, approval, the command catalogue, extension drawings, handoff, and what waits for the 0.8.0 drawing tools. Not for changing FormChem's source (use formchem-skillset), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, undo, run a menu command or extension, read the open fchem drawing, perceive or map a reaction, export reaction SMILES or RXN, read stoichiometry, set reaction roles, get cLogP, TPSA or Lipinski, check a structure, read R/S labels and stereo groups, find a substructure by SMARTS, add hydrogens, contract an abbreviation, define an R-group, or asks what FormChem can do, and FormChem is named or its tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry, properties, check_structure, stereo, substructure) are available. Covers 127.0.0.1:8220, approval, handoff and what waits for 0.8.0. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.5.0" + version: "0.6.0" --- # FormChem harness FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it. -## What exists today (0.5.0) +## What exists today (0.6.0) -FormChem 0.5.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 adds reactions and annotations: arrows, plus signs, brackets, shapes, tables, TLC plates, orbitals, pictures and captions, reaction perception, atom mapping, balance, the Stoichiometry panel, a template library of 206, Find and rulers. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. +FormChem 0.6.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 added reactions and annotations (arrows, brackets, shapes, tables, TLC plates, captions, reaction perception, atom mapping, balance, the Stoichiometry panel, 206 templates, Find and rulers). 0.6.0 adds stereo, queries and analysis: CIP labels and enhanced stereo groups, Assign Wedges, abbreviations, explicit hydrogens, atom lists and query bonds, R-groups and Markush enumeration, substructure search and SMARTS, calculated properties with their methods, the isotope pattern, the Check Structure panel and Set Reaction Roles. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. -The MCP server has ten tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, and the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. +The MCP server has fourteen tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. -**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out, check structure and zoom (`window-commands`). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, and read its stoichiometry and balance (`reactions`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). +**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out and zoom (`window-commands`), plus the chemistry commands (wedges, stereo groups, hydrogens, abbreviations, query features, R-groups). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry and balance, and set roles with `set-reaction-roles {role, objects}` (`reactions`). Through the analysis tools: properties with their methods, the structure check, CIP labels and stereo groups, and substructure hits by id (`structure-analysis`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). -**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading SMILES or InChIKey of a structure back through MCP (the formula in `get_context` and the reaction tools' answers are all), no rendering, no validation results for the agent, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. +**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading the whole structure or its InChIKey back through MCP (the formula in `get_context`, the SMILES and CXSMILES in `stereo` and the other tools' answers are all), no rendering, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) @@ -39,7 +39,8 @@ formchem-harness/ sub-skills/ session-and-connection/ connecting, get_context, the approval question, errors window-commands/ drawing work through run_command; references/command-catalogue.md - reactions/ the four reaction tools and the Reaction menu commands + reactions/ the four reaction tools, the Reaction menu commands and Set Reaction Roles + structure-analysis/ the four analysis tools and the stereo, hydrogen, abbreviation and query commands extension-drawings/ reading and changing the drawing through a Form extension handoff/ handoff states, notes, clearing, what the person sees visual-qa/ checking what the person sees without a render tool @@ -54,8 +55,9 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` | | "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` | | Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` | -| The reaction in the drawing: its steps, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | -| Read atoms, bonds, SMILES, InChIKey or valence errors from the open drawing, change it by id, check a structure | `extension-drawings` (and `window-commands` when no extension fits) | +| The reaction in the drawing: its steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | +| Properties (cLogP, TPSA, Lipinski), a structure check, R or S, stereo groups, a substructure or SMARTS match, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` | +| Read atoms, bonds, InChIKey or valence errors from the open drawing, change it by id | `extension-drawings` (and `window-commands` when no extension fits) | | Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` | | Tell the person you are done, ask them something, clear your note | `handoff` | | Check what the person sees, did the command work, which commands are on | `visual-qa` | @@ -78,6 +80,8 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path | | "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it | | An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns | +| "Give smarts, or query_object" or "is not a fragment of this drawing" | `substructure` has no pattern, or the query fragment id is wrong | Pass a SMARTS or a fragment id from the tools' answers | +| A fragment slot holding `error` in an analysis answer | The engine could not read that fragment; the others are fine | Report it for that fragment and go on with the rest | ## Done means diff --git a/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md index 86da271d..98f99df2 100644 --- a/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md @@ -17,7 +17,7 @@ Use an extension as the agent's hands on the drawing until FormChem has its own ## What an extension sees - `document.read {what: "all"}`: a head (`id`, `title`, `rev`, `dirty`, `path`, `page`, `writable`, `mode`, `format`, `format_version`), the whole `document`, and `derived` when the engine's cache matches `rev`. `what` may also be `page`, `selection` or `json`. -- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). This is the honest way to check a structure before `check-structure` arrives in 0.6.0. +- `derived.fragments[fid]`: `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `implicit_h`, `valence_errors` (`{atom, valence, allowed}`), `aromatic_rings`, `warnings` (`{code, atoms, bonds, text}`). From 0.6.0 the `check_structure` tool returns the full structure check by code and id (`structure-analysis`); the derived cache stays the way to read InChIKey and valence errors inside an extension. - With no drawing open: `writable: false`, `page: null`. Check both before offering a change. ## What an extension can change diff --git a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md index a462491b..0775514f 100644 --- a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md @@ -31,9 +31,9 @@ A handoff with a state changes what the person sees, so the first one from an ou - A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?" - No emoji, no markdown, no links the person cannot click. -## In 0.5.0 +## In 0.6.0 -A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). +A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed", "Assigned wedges in Ibuprofen; the centre reads S". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). ## Procedure diff --git a/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md index 608eb305..90c83d04 100644 --- a/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: reactions -description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, and saying plainly what only the person can do (typing amounts, Set Reaction Roles before 0.6.0). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." +description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." --- # Reactions @@ -39,7 +39,7 @@ Answer reaction questions from what FormChem computes, not from the agent's own ## Rules -- Roles come from geometry: there is no command to set them by hand before 0.6.0 (Set Reaction Roles is off with that reason). A step read from an RXN file or set by hand keeps its roles. +- Roles come from geometry unless set by hand. `run_command {id: "set-reaction-roles", params: {role, objects}}` gives the listed object ids (fragments, text, captions, groups, images, shapes or tables; never the arrow) the role `reactant`, `product`, `agent`, `condition` or `none` in the step touching the selection, as one undo step, and marks the step as set by hand so `perceive_reactions` keeps it. Without `role` it opens a dialog for the person. Read the result back with `perceive_reactions` (it lists the step as set by hand). A step read from an RXN file keeps its roles too. - Reagents drawn above the arrow are not counted in the balance; a step whose atoms come from such a reagent reads as unbalanced. Say that instead of "the reaction is wrong". - Mapping the second of two chained steps replaces the map numbers of the structure they share. Warn before mapping a second step when the first is already mapped. - Coefficients are dropped from reaction SMILES and RXN (`coefficient_dropped`); text conditions are dropped from reaction SMILES (`conditions_dropped`). Pass the warnings on. @@ -56,4 +56,4 @@ Reaction and step ids, the quoted answers, and a ready or question handoff. ## Owned resources -None of its own. `references/tools.md` at the pack root holds the generated arguments of all ten tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. +None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. diff --git a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index 9bf19f2d..f0f9e6e5 100644 --- a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -42,5 +42,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the ten tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. +- [ ] The plan uses only the fourteen tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. - [ ] No change was attempted after a refusal. diff --git a/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md new file mode 100644 index 00000000..ae33befa --- /dev/null +++ b/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md @@ -0,0 +1,69 @@ +--- +name: structure-analysis +description: "Reads and edits the chemistry of an open FormChem drawing through the four MCP analysis tools (properties, check_structure, stereo, substructure) and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem." +--- + +# Structure analysis + +## Purpose + +Answer chemistry questions about the drawing with FormChem's own numbers, quoted with the method behind them, and make the stereo, hydrogen, abbreviation and query edits as undo steps the person sees. Hands back fragment, atom and bond ids, the tool answers quoted exactly, and a handoff naming any change. + +## Preconditions + +`get_context` has been called (`session-and-connection`) and lists the drawing. The analysis tools only read, so they never ask the person; the chemistry commands change the drawing and ask the first time, like any `run_command`. + +## The four analysis tools + +| Goal | Call | What comes back | +| --- | --- | --- | +| Properties | `properties {doc?, object?}` | per fragment: formula, MW, exact mass, cLogP, MR, TPSA (and with S and P), donors and acceptors (Lipinski and refined counts), rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts, elemental analysis; each row with `method` (the RDKit call) and `note` | +| Structure check | `check_structure {doc?, object?, query?}` | issues `{code, severity, text, atoms, bonds, fix}` sorted errors first; `query: true` when the drawing is a search query | +| Stereo | `stereo {doc?, object?}` | centres, double bonds and axes with label, `state` (defined, undefined, unknown) and group (`abs`, `and1`, `or1`), the stereo groups, the chiral flag and CXSMILES | +| Substructure | `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | hits with the fragment id, matched atom and bond ids and the query-to-target map; `count`, `truncated` | + +`doc` may be left out when one drawing is open; `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`). + +## Chemistry commands (run_command) + +They act on the person's selection, or on the page when nothing is selected; the agent selects only with `select-all` or by inserting. Check `list_commands {id}` for params and the off reason first. + +| Command | Does | +| --- | --- | +| `assign-wedges` | redraws wedges and hashes of the stereocentres so they read unambiguously | +| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | puts the selected centres into an abs, new AND or new OR group, or out of any | +| `add-hydrogens`, `remove-hydrogens` | draws implicit H as atoms or folds them back; H that hold stereo, an isotope, a charge or a map number stay | +| `expand-abbreviation`, `contract-abbreviation` | expands a selected label (or every one); contract opens a dialog for the person's label | +| `set-atom-list`, the `set-query-bond-` commands, `clear-query-bond` | atom lists (a dialog) and query bonds on the selection | +| `define-rgroup`, `enumerate-markush` | R-group definition and enumeration open dialogs for the person | +| `copy-smarts`, `compute-properties`, `check-structure`, `search-substructure` | copy SMARTS to the person's clipboard, or open the panels; the tools above return the same data to the agent | + +## Procedure + +1. **Context.** `get_context`; name the drawing and pick fragment ids from the tool answers, never by guess. +2. **Read with the tool, not the command.** For values, issues, labels or matches call the analysis tool; the command opens a panel the agent cannot read. +3. **Quote with the method.** Report each value as the tool printed it, with its unit and method ("cLogP 3.07, Crippen.MolLogP; typical error 0.5 to 0.7 log units"). Never compute a property, a CIP label or a SMARTS match with your own chemistry and present it as FormChem's. +4. **Stereo states matter.** An `undefined` centre has no label because nothing fixes it; say so instead of guessing R or S. Allene axial chirality and drawn atropisomers are not perceived in this version. +5. **Change through commands, then read back.** After `assign-wedges`, a stereo group or `add-hydrogens`, call `stereo` or `check_structure` again and report what changed, with Undo as the way back. +6. **Hand off** with what changed or what the person should look at (`handoff`). + +## Rules + +- A check issue with `fix` (`wedges` or `expand`) is repaired by the person's Fix button or by `assign-wedges` or `expand-abbreviation` on the selection; say which. +- A structure check on a query drawing without `query: true` reports `query_feature` notes; they are expected, not errors. +- Metal cations such as Na+ in a salt are not valence errors; do not report them as such. +- Export SMARTS in the desktop app copies instead of saving until 0.7.0; dialogs (atom list, R-group, abbreviation label) belong to the person. + +## Gate + +- [ ] Every number, label and issue reported came from a tool answer in this session, with its unit and method where given. +- [ ] Every changing command was found in `list_commands` first and reported with its undo step. +- [ ] Undefined or unperceived stereo was named as such, never filled in. + +## Hands back + +Fragment, atom and bond ids, the quoted answers, and a ready or question handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue. diff --git a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md index 7715e05c..f4d176cd 100644 --- a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md @@ -7,7 +7,7 @@ description: "Checks what the person sees in FormChem when the agent cannot see ## Purpose -Never claim a visible result you did not confirm. In 0.5.0 an agent still has no picture of the window and no render or validation tool (they arrive in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found), and ask the person for the rest. +Never claim a visible result you did not confirm. In 0.6.0 an agent still has no picture of the window and no render tool (it arrives in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found; `stereo`, `check_structure` and `properties` read the chemistry after a command), and ask the person for the rest. ## What you can confirm today diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index 6c6a2355..6dc92811 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: window-commands -description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." +description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." --- # Window commands @@ -33,8 +33,9 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure | | Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected | | Save | `save`; a drawing never saved before asks the person for a name, so say so in the handoff | -| Check the structure | `check-structure` opens a dialog for the person listing valence errors and warnings; the agent does not get the rows back. Say the dialog is open for them, or read valence errors through an extension (`extension-drawings`) | -| Show the formula or masses | `get_context` gives the formula of each open drawing; `show-analysis` or `toggle-analysis` opens the Analysis panel (masses, m/z, elemental analysis) for the person, whose values the agent cannot read through commands | +| Check the structure | The `check_structure` tool returns the issues with codes and ids (`structure-analysis`); `check-structure` opens the Check Structure panel for the person | +| Show the formula, masses or properties | `get_context` gives the formula of each open drawing and the `properties` tool every value with its method (`structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person | +| Stereo, hydrogens, abbreviations, query features, R-groups | Load `structure-analysis` for the commands and the tools that read the result | ## Rules diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index cb2d4371..7f9e876c 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,6 +1,6 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.5.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.6.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents @@ -9,6 +9,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.5. - Changing the drawing - Templates, objects and arrangement - Reactions +- Stereo, queries and analysis - The canvas and the view - Registered but off until a later version - What no command does yet @@ -44,7 +45,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.5. | `distribute-h`, `distribute-v` | | spread the selected objects evenly | | `clean-structure` | | tidies bond lengths and angles through the engine's layout service, keeping place and stereochemistry; selected atoms, or every structure on the page when nothing is selected. It refuses when the drawing changed during the call | | `layout-structure` | | computes fresh 2D coordinates for the structures the selection touches, or every structure on the page | -| `check-structure` | | opens a dialog for the person listing valence errors and chemistry warnings with links that select the atoms; the agent gets only "ran in the window" | +| `check-structure` | | opens the Check Structure panel for the person (rows that select atoms, Fix, Check Again); the agent gets only "ran in the window", and reads the issues with the `check_structure` tool | | `insert-text` | | switches the person's canvas to the text tool | `delete`, `duplicate`, the flips, `rotate-90`, align and distribute act on the canvas selection and are `off now` with "Select something on the canvas first" while nothing is selected. The agent sets the selection only with `select-all` or by inserting (`insert-smiles` and `insert-template` select what they added). Each changing command is one undo step. @@ -73,10 +74,30 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.5. | `copy-reaction-smiles`, `copy-reaction-rxn` | put the step on the person's clipboard; `export_reaction` gives the agent the text | | `export-reaction-smiles`, `export-reaction-rxn` | save the step to a file the person chooses | | `paste-reaction` | lays out reaction SMILES or RXN from the person's clipboard as a drawn scheme | -| `set-reaction-roles` | off: "Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing" | +| `set-reaction-roles` | params `role` (`reactant`, `product`, `agent`, `condition`, `none`) and `objects` (ids; default the selection): sets their role in the step and marks it as set by hand, one undo step; without `role` it opens the roles dialog for the person | The step is the one whose arrow or structures are selected, else the first on the page. +## Stereo, queries and analysis + +From 0.6.0. They act on the selection, or the page when nothing is selected, and each changing one is one undo step. The analysis tools (`properties`, `check_structure`, `stereo`, `substructure`) return what the panels show; see `structure-analysis`. + +| Command | What it does | +| --- | --- | +| `assign-wedges` | asks the engine for wedges and hashes that express the stereocentres unambiguously | +| `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group` | put the selected centres into abs, a new AND group or a new OR group, or out of every group | +| `set-stereo-group`, `stereo-group-popover` | the Enhanced Stereo submenu and its popover, for the person | +| `add-hydrogens`, `remove-hydrogens` | explicit hydrogens drawn or folded back; some stay (stereo, isotope, charge, map number) | +| `expand-abbreviation` | expands the selected abbreviation atoms, or every abbreviation on the page | +| `contract-abbreviation` | opens the abbreviation dialog for the person's label | +| `set-atom-list` | opens the periodic table dialog for the person | +| `set-query-bond-any`, `set-query-bond-single_or_double`, `set-query-bond-single_or_aromatic`, `set-query-bond-double_or_aromatic`, `clear-query-bond` | query bonds on the selected bonds (list_commands gives the exact ids) | +| `define-rgroup`, `enumerate-markush` | open the R-group and enumeration dialogs for the person | +| `search-substructure` | selects matches of the selected atoms, or asks the person for SMARTS | +| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file (the desktop app copies instead until 0.7.0) | +| `compute-properties`, `copy-analysis` | open the Analysis panel on the selection; copy its values with methods to the person's clipboard | +| `show-stereo`, `show-stereo-groups`, `show-query-marks` | toggle the CIP labels, the enhanced stereo group labels and the query tags on the canvas | + ## The canvas and the view | Command | What it does | @@ -92,8 +113,8 @@ The step is the one whose arrow or structures are selected, else the first on th ## Registered but off until a later version -`expand-abbreviation`, `contract-abbreviation`, `show-stereo`, `compute-properties`, `copy-analysis` (0.6.0); every `copy-*` and `export-*`, `import`, `print` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `set-reaction-roles`, `add-hydrogens` and `remove-hydrogens` (0.6.0). Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. +`import`, `print`, `copy-smiles`, `copy-molfile`, `copy-inchi`, `copy-svg` and the whole-drawing `export-png`, `export-svg`, `export-pdf`, `export-cdxml`, `export-mol`, `export-smiles` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `demos` (0.13.0). The reaction copy and export commands and `copy-smarts` and `export-smarts` already work. Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. ## What no command does yet -Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, reading the structure back beyond the formula `get_context` lists (SMILES, InChIKey, masses, valence errors), rendering an image, validating a structure or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. +Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, filling the person's dialogs (atom list, R-group, abbreviation label), reading the whole structure back beyond what `get_context` and the analysis tools give (the formula, SMILES and CXSMILES in `stereo`, properties, issues and substructure hits), rendering an image or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. diff --git a/agents/manifest.json b/agents/manifest.json index c1ea73fa..02ffd08c 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -50,6 +50,7 @@ "handoff", "reactions", "session-and-connection", + "structure-analysis", "visual-qa", "window-commands" ] From 8b66f9f5b0f10d5c4de09349c84d4a82420b4967 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:08:42 -0500 Subject: [PATCH 278/279] docs(skills): add the stereo and queries specialist and the Tauri CLI pin rule to the skillset (0.6.0) The skillset routed nothing to the 0.6.0 analysis layer and did not know why the desktop build failed; it now maps the services, routes, codes, window modules and the CLI to crate version rule, mirrored with agents sync. --- .agents/skills/formchem-skillset/EVALS.json | 28 ++++++++- .agents/skills/formchem-skillset/SKILL.md | 22 ++++--- .../sub-skills/agents/SUB-SKILL.md | 8 +-- .../sub-skills/canvas/SUB-SKILL.md | 1 + .../sub-skills/chemistry-engine/SUB-SKILL.md | 3 +- .../references/warning-codes.md | 7 ++- .../sub-skills/desktop/SUB-SKILL.md | 8 ++- .../sub-skills/reactions/SUB-SKILL.md | 3 +- .../stereo-and-queries/SUB-SKILL.md | 53 ++++++++++++++++ .../references/routes-and-codes.md | 60 +++++++++++++++++++ .claude/skills/formchem-skillset/EVALS.json | 28 ++++++++- .claude/skills/formchem-skillset/SKILL.md | 22 ++++--- .../sub-skills/agents/SUB-SKILL.md | 8 +-- .../sub-skills/canvas/SUB-SKILL.md | 1 + .../sub-skills/chemistry-engine/SUB-SKILL.md | 3 +- .../references/warning-codes.md | 7 ++- .../sub-skills/desktop/SUB-SKILL.md | 8 ++- .../sub-skills/reactions/SUB-SKILL.md | 3 +- .../stereo-and-queries/SUB-SKILL.md | 53 ++++++++++++++++ .../references/routes-and-codes.md | 60 +++++++++++++++++++ agents/manifest.json | 1 + 21 files changed, 353 insertions(+), 34 deletions(-) create mode 100644 .agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md create mode 100644 .agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md create mode 100644 .claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md create mode 100644 .claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md diff --git a/.agents/skills/formchem-skillset/EVALS.json b/.agents/skills/formchem-skillset/EVALS.json index 2f23d933..46a20dac 100644 --- a/.agents/skills/formchem-skillset/EVALS.json +++ b/.agents/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.5.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.6.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -134,10 +134,36 @@ "Checks that the arrow kind's deps list the anchored fragments so the renderer re-lays it out when they change", "Verifies with a MutationObserver that one move changes only the atom's nodes and the anchored arrow, without rebuilding the layer" ] + }, + { + "id": 13, + "name": "new-check-code", + "prompt": "Add a FormChem structure check that warns when a carbon carries a +3 charge drawn as a label, with a fix that does nothing new.", + "files": [], + "expected_behavior": [ + "Loads stereo-and-queries and opens its references/routes-and-codes.md before editing", + "Adds the code in backend/app/services/chem/check.py with a SEVERITY entry and no fix (FIX only names existing analysis routes such as wedges or expand)", + "Adds the row to routes-and-codes.md and docs/ANALYSIS.md and a backend HASHOUT entry, and does not put a transaction in the issue" + ] + }, + { + "id": 14, + "name": "tauri-cli-bump", + "prompt": "The tauri crate in Cargo.lock moved to 2.13.1; update FormChem so ./build_app still builds.", + "files": [], + "expected_behavior": [ + "Loads desktop and states the rule that @tauri-apps/cli major.minor must equal the tauri crate's", + "Sets @tauri-apps/cli in frontend/package.json to a 2.13 release in the same change as package-lock.json, checking the @tauri-apps/plugin-* packages against their tauri-plugin-* crates", + "Runs ./formchem desktop check (not a full tauri build on a small machine) and records the bump in the HASHOUT log" + ] } ], "trigger_evals": [ {"query": "add an MCP tool to formchem", "should_trigger": true}, + {"query": "formchem shows (S) on the wrong side of the stereocentre after contracting CO2H", "should_trigger": true}, + {"query": "fix formchem's SMARTS export for atom lists in services/chem/query.py", "should_trigger": true}, + {"query": "formchem build_app stops with the Tauri CLI did not install", "should_trigger": true}, + {"query": "what is the cLogP of the structure in my FormChem drawing?", "should_trigger": false}, {"query": "formchem's perceive reactions picks the wrong reactants for a vertical arrow", "should_trigger": true}, {"query": "add a new glassware template to the formchem template library", "should_trigger": true}, {"query": "the curved arrow in formchem's renderer draws its head on the wrong side", "should_trigger": true}, diff --git a/.agents/skills/formchem-skillset/SKILL.md b/.agents/skills/formchem-skillset/SKILL.md index 406293cc..bc0400e8 100644 --- a/.agents/skills/formchem-skillset/SKILL.md +++ b/.agents/skills/formchem-skillset/SKILL.md @@ -1,17 +1,17 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem package, imports), the engine store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings), reactions (perception, Indigo atom mapping, balance, stoichiometry, RXN), the SVG canvas renderer patching on every edit, drawing tools (one undo step per drag), hover hotkeys, hit testing, arrows, brackets, shapes, tables, TLC, captions, groups, templates, media, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, the fchem package), the engine store, the RDKit service (SMILES, InChIKey, masses, layout, warnings, CIP and enhanced stereo, wedges, abbreviations, queries, SMARTS, R-groups, properties, the structure check, isotope patterns), reactions (perception, Indigo mapping, balance, stoichiometry, RXN, roles), the SVG canvas renderer and marks, drawing tools, hover hotkeys, hit testing, arrows, shapes, captions, templates, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell and desktop build, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck, and not for standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.5.0" + version: "0.6.0" --- # FormChem skillset Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine as a sidecar. -**Where FormChem is (0.5.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 adds reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. Stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.6.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 adds stereo, queries and analysis: enhanced stereo groups and the chiral flag in RDKit, the CIP report, wedge assignment, abbreviations and explicit hydrogens, query atoms and bonds, SMARTS, substructure search, V3000 query molfiles, R-groups and Markush enumeration, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the keyed marks layer, the chemistry commands and dialogs, Set Reaction Roles, and the Tauri CLI pin for the desktop build. Exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. ## Subsystem map @@ -25,6 +25,7 @@ Route every change to FormChem's code through this file. It maps the subsystems | Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | | Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | | Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | +| Stereo, queries and analysis: stereo groups, CIP report, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, V3000 queries, Markush, properties, the structure check, the isotope pattern, their routes, tools, commands, marks and panels | `backend/app/services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `frontend/src/engine/analysis-api.ts`, `app/chem-edits.ts`, `app/chem-commands.ts`, `canvas/render/marks-*.ts`, the 0.6.0 dialogs in `ui/`, `docs/ANALYSIS.md` | `stereo-and-queries` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | @@ -42,7 +43,9 @@ engine/model.ts, engine/ops.ts -> nothing (pure, DOM free; the contract) chem/ -> engine/model.ts only (pure, no t(), no DOM) engine/client.ts, session.ts -> model, ops, client-api, io/api, io/live canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings); - render/table.ts also chem/stoich.ts, the one window stoichiometry source + render/table.ts also chem/stoich.ts, the one window stoichiometry source; + render/marks-layer.ts also canvas/marks-options.ts (view toggles only) +engine/analysis-api.ts -> io/api, model, ops; the only caller of /api/analysis canvas/tools -> canvas/types.ts, engine/model, engine/ops, canvas/geom.ts canvas/view.ts, ui/tool-rail -> canvas/types.ts, hit.ts, selection.ts, ui/dom, ui/icons, i18n io/ -> registry only for the catalogue mirror @@ -52,7 +55,8 @@ backend services/model.py, ops.py -> nothing (pure; the contract) services/store.py -> model, ops, package, history, importers, hub; chem.derive imported lazily services/chem/ -> rdkit, indigo, model (never the store or routers) backend routers -> core, services (hub, bridge, library, store, chem, terminal, formext_host) -mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub +mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub; + routers/analysis imported lazily by the analysis tools window-only abilities -> reach the engine as window tools over /api/live (bridge.window_call) desktop shell -> frozen engine (formchem_engine.py) -> serves frontend/dist ``` @@ -85,13 +89,14 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | Drawing on the canvas: how a bond, label or wedge renders, a drawing tool, a hover hotkey, snapping, hit testing, selection, zoom and pan, the tool rail, canvas right-click menus | `canvas` | | An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `annotations`, with `canvas` for the laws it builds on | | Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | +| A CIP label, stereo group, wedge, abbreviation, explicit hydrogen, atom list, query bond, SMARTS, substructure hit, R-group, property, check issue or isotope peak; an `/api/analysis` route, an analysis MCP tool, a stereo or query mark | `stereo-and-queries`, with `chemistry-engine` for the converter and `agents` for a tool | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | | A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | | Terminal tabs, Claude Code, Codex, Cursor or Antigravity tabs, the consent dialog, chat | `dock` | | The extensions pane, an extension API call, FormPortal or form.ext integration | `extensions` | | A new MCP tool, the commands catalogue, `./formchem agents`, skills, the manifest | `agents` | -| Desktop build, sidecar, updater, Tauri commands, title bar overlay | `desktop` | +| Desktop build, `build_app`, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | | A release, version sites, CHANGELOG, NOTICE, CI | `release` | | Any chemistry feature, a file format, a name for a command or panel | `clean-room` first | | Use FormChem: insert a structure, run a menu command, hand off in the window | Not this pack: `formchem-harness` | @@ -103,9 +108,10 @@ formchem-skillset/ SKILL.md this router, the subsystem map and the laws in short references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) - sub-skills/ engine, document-format, chemistry-engine, reactions, canvas, annotations, window-shell, - menus, dock, extensions, agents, desktop, release, clean-room + sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, canvas, annotations, + window-shell, menus, dock, extensions, agents, desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from + stereo-and-queries/references/routes-and-codes.md the /api/analysis routes, check codes and service warning codes canvas/references/hover-keys.md the hover key map with the code that implements it ``` diff --git a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index da1bcc14..b0021068 100644 --- a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -30,11 +30,11 @@ Give agents a small, honest tool surface that only describes what FormChem can d 4. Describe only what works now. A tool for a later phase lands in that phase. 5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. -## What agents can reach in 0.5.0 +## What agents can reach in 0.6.0 -- Ten tools: the six of the shell plus `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`); the `reactions` specialist owns them. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present. -- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). -- `mcp.py` describes the shell as of 0.4.0 (a sentence naming the reaction tools in `INSTRUCTIONS` and `get_context` is still to add): `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. +- Fourteen tools: the six of the shell; `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`), owned by `reactions`; and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure` (outside `MUTATING`, never asking), which reuse the analysis router's source rules through `_analysis_source` with a lazy import so mcp.py does not load RDKit at import, owned by `stereo-and-queries`. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, edit ops, `convert`) land in 0.8.0; do not add them early or describe them as present. +- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands, `set-reaction-roles {role, objects}` and the 0.6.0 chemistry commands such as `assign-wedges`, `set-stereo-group-and`, `add-hydrogens` and `expand-abbreviation`) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). +- `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` text name the reaction tools, the analysis tools and the chemistry commands; `DRAWING_FROM = "0.8.0"` names when the atom and bond tools arrive. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. - `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing. - A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window. diff --git a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md index 17fe7f64..20e43a6d 100644 --- a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md @@ -21,6 +21,7 @@ Let the person draw at the speed of thought while the document stays the only tr | `canvas/hit.ts`, `selection.ts` | Hit testing and region selection on model geometry; selection sets and helpers | | `canvas/text-editor.ts`, `canvas/context.ts` | The in-place label and text editor; right-click menus for atom, bond, selection and background (`deleteSelectionOps`) | | `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups | +| Stereo and query marks (0.6.0) | `render/marks-layer.ts` (`ChemMarks`, one keyed layer cached per fragment; replaced `render/stereo.ts`), `marks-stereo.ts`, `marks-query.ts` and `canvas/marks-options.ts` belong to the `stereo-and-queries` specialist; the view toggles reach the renderer through `RenderDisplay.enhancedStereo`, `queryMarks` and `groupColours` | | Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text | | `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper | | `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key | diff --git a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index df7f56d9..12b5a79d 100644 --- a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -20,7 +20,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `chem/mass.py` | `average_mass`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `isotope_pattern`, `properties(conv)` | | `chem/layout.py` | `compute_coords(frag, ids, bond_length, fixed)` (CoordGen, RDKit fallback), `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move) | | `chem/io.py` | `detect`, `read_text`, `read_file` (`ParseResult` with fragments, warnings, reaction), `export`, `to_molfile`, `to_smiles`; SDF, RXN, reaction SMILES, CML, cdxml and cdx (Indigo), InChI; at most 1000 records per call | -| `chem/abbrev.py` | 75 built-in abbreviations with attachment SMILES; `resolve`, `element_like`, `reversed_label` | +| `chem/abbrev.py` | 106 built-in abbreviations in six categories plus the person's `abbreviations.json`; `resolve`, `element_like`, `reversed_label`, `library`, `match` | | `chem/derive.py` | `derive_fragment(frag, expansions, rev)`, `derive_document(doc, rev, only)`, `content_key`, an LRU cache of 2048 fragments | | `backend/app/routers/chem.py` | `POST /api/chem/parse`, `/derive`, `/layout`, `/convert`, `/properties`; 422 for bad input, 413 over 20 MB of text, at most 5000 atoms | | `backend/app/services/store.py` | `schedule_derive` and `_derive_loop`: after each transaction, derive in a thread on a deep copy and broadcast `{t: "derived", doc, rev, derived}` | @@ -28,6 +28,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `frontend/src/canvas/render/valence.ts`, `render/rings.ts` | The renderer's own fast implicit-H table and ring perception, used while drawing | | `references/warning-codes.md` | Every warning code, the module that raises it and when. Open before adding or interpreting a warning | | Reaction modules (0.5.0) | `chem/geometry.py`, `reactions.py`, `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py`, `scheme.py`, `derive.reaction_checks` and `routers/reactions.py` belong to the `reactions` specialist; they reuse `convert.to_mol` and the rules here | +| Analysis modules (0.6.0) | `chem/stereo.py`, `superatom.py`, `hydrogens.py`, `query.py`, `search.py`, `v3000.py`, `markush.py`, `props.py`, `check.py`, `isotopes.py` and `routers/analysis.py` belong to the `stereo-and-queries` specialist. Here they changed `convert.py` (stereo groups and the chiral flag after perception, query atoms and bare `*` as generics), `perceive.py` (`stereo_unknown`, `undefined_double_bond`, cumulenes skipped, charged atoms judged by the allowed list so Na+ is no valence error) and `derive.content_key` (`FRAGMENT_FIELDS`) | ## Rules diff --git a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md index 5ab65a8b..58dfb4eb 100644 --- a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md +++ b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md @@ -36,7 +36,7 @@ These appear in `derived.fragments[fid].warnings` after every transaction. | `charge_imbalance` | perceive.py | The pieces of one fragment carry a net charge | | `engine_error` | derive.py | Any exception inside the engine for this fragment; values are empty | -Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged. +Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged. From 0.6.0 a charged atom is judged by its charge-shifted allowed list alone (RDKit 2025.09 flags a bare Na+), and `unknown_label` no longer fires for query atoms (lists, A, Q, X, M) or a bare `*`, which count as generics. ## Stereo warnings @@ -47,6 +47,11 @@ Valence errors are not warnings: they are the separate `valence_errors` list (`{ | `conflicting_wedges` | convert.py | Wedges on one centre imply opposite configurations | | `misplaced_wedge` | convert.py | The narrow end of a wedge (atom `a`) is not a stereocentre | | `unknown_ez` | convert.py | A double bond drawn crossed (`either`) or next to a wavy bond | +| `stereo_unknown` | perceive.py | A stereocentre on a wavy bond (marked unknown on purpose) (0.6.0) | +| `undefined_double_bond` | perceive.py | A stereogenic double bond that is neither specified nor marked crossed or wavy, usually a substituent on the bond's line; cumulated bonds are skipped (0.6.0) | +| `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` | convert.py | A malformed `stereo_groups` entry, an atom in two groups, or a grouped atom that is not a stereocentre (dropped from the group) (0.6.0) | + +The 0.6.0 analysis services (wedges, contract and expand, hydrogens, SMARTS, V3000, Markush, properties) and the structure check codes belong to the `stereo-and-queries` specialist, which lists them. ## Identifier warnings diff --git a/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md index 73aa0d56..0bd95c76 100644 --- a/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md @@ -31,8 +31,14 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t - Releases are built by formcompiler from `tauri.conf.json`; do not hand-build release artifacts. - Do not run cargo build, tauri build or pyinstaller on a shared or small machine unless the task says so. +## The Tauri CLI pin + +`@tauri-apps/cli` is a pinned dev dependency in `frontend/package.json` (2.12.6). The rule: its major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7), and each `@tauri-apps/plugin-*` package shares major.minor with its `tauri-plugin-*` crate; bump them together in one change, with `package-lock.json`. Tauri refuses to build across minor versions. Until 0.6.0 package.json did not list the CLI, so `npm ci` installed no `tauri` binary and `./build_app` stopped with "the Tauri CLI did not install"; with the pin, the owner's `./build_app` on macOS arm64 (Python 3.14) built the app. + +`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck`, and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it. + ## Gate -- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable). +- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable, CLI and crate share major.minor). - [ ] The desktop dev run opens the window without a white flash and the engine answers `/api/health` on its port. - [ ] Quitting the app ends the engine process on every platform touched. diff --git a/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md index f75ad6fe..361ff088 100644 --- a/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md @@ -30,11 +30,12 @@ Read `docs/FORMAT.md` (Reactions on a page, the table `stoich` rule, the derived | `frontend/src/ui/stoich-panel.ts`, `styles/stoich.css` | the panel in row 2 of `.fc-workspace` | | `frontend/src/canvas/render/table.ts` | draws a `stoich` table live from `computeStoich` | | `frontend/src/engine/reactions-api.ts`, `app/reaction-commands.ts` | the typed route client and the Reaction menu commands | +| `frontend/src/chem/reaction-roles.ts`, `ui/roles-dialog.ts` | Set Reaction Roles (0.6.0): `reactionRoleOps` moves changed ids between role lists, sets `explicit: true` and drops coefficients and `stoich` entries that no longer fit, in one transaction; `canTakeRole` (fragments, text, captions, groups, images, shapes, tables, never the arrow); the keyed roles dialog. Window-side, no engine route | ## Laws - **One reading of stoichiometry.** The engine's `stoich.py` and the window's `chem/stoich.ts` follow the same precedence: `scale_mmol` is the reference when present, else the limiting reagent's typed amount over its equiv, else the first amount; typed amounts beat typed equivalents. Never add a third computation; the renderer's own copy was deleted for disagreeing. Only typed values are stored, and the window's write rules (mass, volume or equiv replaces the other two; scale and the limiting reagent's amount replace each other) keep the two readings equal. -- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true`; re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md. +- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true` (set by Set Reaction Roles, an agent's `set-reaction-roles {role, objects}`, or a reaction file); re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md. - **Routes are transactions.** A changing route builds ops on a copy and applies them with `STORE.apply`, returning `{changed, tx, rev}` and broadcasting the tx with the caller's `client`; no change means `changed: false` and no undo step. Agents go through `_apply` with origin `agent`. - **Map numbers are atom data.** `Atom.map` and `Bond.reacting` are the only places mapping lives, so chained steps share the numbers of a shared structure. - **Exchange keeps what the format can carry.** Kekulise RXN, keep reaction SMILES aromatic, put conditions on RXN line 4, report what is dropped as a warning code. diff --git a/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md new file mode 100644 index 00000000..cb3ba469 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md @@ -0,0 +1,53 @@ +--- +name: stereo-and-queries +description: "FormChem's 0.6.0 stereo, query and analysis layer: enhanced stereo groups and the chiral flag into RDKit, the CIP stereo report, wedge assignment, the abbreviation library with contract and expand, explicit hydrogens, query atoms and bonds as one SMARTS-built query molecule, SMARTS in and out, substructure search, V3000 query molfiles with R-group blocks, Markush enumeration, properties with method labels, the structure check codes, the isotope pattern, the /api/analysis router, the four analysis MCP tools, and the window side (analysis-api.ts, chem-edits, chem-commands, the keyed marks layer, the dialogs, the check panel, the properties section and isotope plot). Use when a CIP label, stereo group, wedge, abbreviation, query, SMARTS, R-group, property, check issue or isotope peak is wrong, or a route, command, mark or check code is added." +--- + +# Stereo and queries + +## Purpose + +Keep the chemistry of 0.6.0 in one shape: the engine (RDKit) computes and proposes, the window commits one transaction per command, and every number carries its method. The doc is `docs/ANALYSIS.md`; the reasons are in `backend/HASHOUT_LOG.md` 78 to 98 and `frontend/HASHOUT_LOG.md` 133 to 148. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/services/chem/convert.py` | `_read_groups`, `apply_groups` (stereo groups and `chiral` into RDKit after perception), `groups_from_mol`, `_query_label` (query atoms and bare `*` are generics) | +| `chem/stereo.py` | `report` (centres, double bonds, axes, state, group label, CXSMILES), `regroup`, `groups_tx`, `preview`, `rewedge` (from the drawing, wanted CIP or 3D) | +| `chem/perceive.py` | `stereo_unknown`, `undefined_double_bond`, `not_ez_bonds` (cumulenes), the charged-atom valence rule | +| `chem/abbrev.py`, `chem/superatom.py` | 106 built-ins plus `abbreviations.json`; `match`, `PREFERRED`; `contract` and `expand` keeping ids | +| `chem/hydrogens.py` | `add_hydrogens`, `remove_hydrogens` | +| `chem/query.py`, `chem/search.py` | `query_mol`, `to_smarts`, `from_smarts`, `parse_atom_smarts`; `substructure` | +| `chem/v3000.py`, `chem/markush.py` | query molfile `write` and `read` (FormChem's own RGROUP reader); `member_attachments`, `enumerate_structures` | +| `chem/props.py`, `chem/check.py`, `chem/isotopes.py` | `compute` with `method` and `note`; `check` with `SEVERITY`, `FIX`, `SKIP`; `from_counts`, `pattern`, `parse_formula` | +| `backend/app/routers/analysis.py` | every `/api/analysis` route; `source` (stateless or `doc`), `finish` (`apply`), `_ids_of` | +| `backend/app/routers/mcp.py` | `t_properties`, `t_check_structure`, `t_stereo`, `t_substructure`, `_analysis_source` (lazy router import) | +| `frontend/src/engine/analysis-api.ts` | the only caller of `/api/analysis`; `sourceFor`, defensive readers | +| `frontend/src/app/chem-edits.ts`, `app/chem-commands.ts` | window-side op builders; `registerChemCommands`, `CHEM_MENU_ITEMS`, `chemContextItems` | +| `frontend/src/canvas/render/marks-layer.ts`, `marks-stereo.ts`, `marks-query.ts`, `canvas/marks-options.ts` | `ChemMarks` keyed layer and its view toggles | +| `frontend/src/ui/` | `periodic-grid`, `atom-list-dialog`, `rgroup-dialog`, `abbreviation-dialog`, `stereo-popover`, `query-menus`, `structure-check`, `analysis-properties`, `isotope-plot`, `markush-dialog` | +| `references/routes-and-codes.md` | the routes with their bodies and answers, the check codes by severity, the warning codes of each service. Open before adding a route, a code or a reader | + +## Rules + +- **Plain fields in the window, RDKit in the engine.** Atom lists, generic queries, query bonds and topology, stereo groups, the chiral flag and R-group definitions are field edits FORMAT defines: build them in `chem-edits.ts` and commit at once. Anything that needs perception (hydrogens, contract, expand, wedges, the check, properties, search, Markush, SMARTS) is an engine route that answers `tx: {label, ops}`. +- **One transaction per command.** The window commits the engine's ops once, across fragments, and only if every fragment record it sent is still current; otherwise it says the drawing changed. A route with `doc` and `apply: true` applies on the engine side instead. Never commit per fragment. +- **Groups go in after perception.** `apply_groups` runs after stereo perception so only real centres are grouped; anything that changes `stereo_groups` or `chiral` must stay in `derive.FRAGMENT_FIELDS` or cached CXSMILES goes stale. +- **Chiral flag 0 reads absolute.** A deliberate deviation from the clean-room spec (most files write 0 for enantiomers); do not "fix" it without the owner. +- **Ids survive contract and expand.** Expansion-internal ids are not live document ids (`_ids_of`); expand restores them unless they clash. +- **Every property names its method.** A new property row has `method` (the RDKit call) and `note` (in words), and the window's `PROPERTY_ROWS` gets a reserved width. +- **A fix is a command name.** A check issue names its repairing route in `fix`, never a transaction; add the code to `SEVERITY` (and `FIX` if repairable) and to the window's row text. +- **Marks are keyed.** New marks are specs in `marks-stereo.ts` or `marks-query.ts`, cached per fragment by `ChemMarks`; explicit fills, no CSS colours; never rebuild the layer. +- **Agents read through tools, change through commands.** Analysis tools stay read-only and outside `MUTATING`; a changing chemistry command is a window command agents reach with `run_command`. + +## Known gaps (do not paper over) + +Allene axial chirality and drawn atropisomers are not perceived; link nodes and variable attachment are not built; SMARTS import draws aromatic rings as single bonds (fix: order 1.5 when both ends are aromatic); Markush `count` is before dedup and if-then; Export SMARTS copies in the desktop shell until 0.7.0. + +## Gate + +- [ ] `backend/venv/bin/python -m compileall -q backend/app` is clean; `cd frontend && npx tsc --noEmit` is clean. +- [ ] A scratch script outside the repo checks the AC5.3 CIP table (L-alanine S, meso-tartaric R and S, pentane-2,3,4-triol S, r, R) and ibuprofen properties (cLogP 3.07, TPSA 37.3) and isotopes (CH2Cl2 M+2 63.92, C6H5Br M+2 97.45). +- [ ] Contract then expand gives back the same atom ids and coordinates; each command added exactly one undo step. +- [ ] Under 4x CPU throttling a mark toggle or a property refresh patches nodes only (MutationObserver), and the properties section keeps its height. diff --git a/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md new file mode 100644 index 00000000..a90f8fb6 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md @@ -0,0 +1,60 @@ +# Analysis routes and codes + +The `/api/analysis` routes of `backend/app/routers/analysis.py`, the structure check codes of `chem/check.py` and the warning codes of each 0.6.0 service, as of 0.6.0. `docs/ANALYSIS.md` has the full answer shapes; when this page and the code differ, the code wins and this page is the bug. + +## Contents + +- Request rules +- Routes +- Check codes by severity +- Service warning codes + +## Request rules + +- Source, stateless: `fragment`, optional `expansions`, optional `members` (fragment id to fragment). From a document: `doc` plus `object` or `objects`; expansions and members come from the document. +- Changing routes answer `tx: {label, ops}` (paths from the document root). `doc` with `apply: true` applies it (origin `user`) and adds `applied: {tx, rev}` or `applied: null`. +- Errors: 422 `{detail}` sentence, 404 unknown doc or object, 409 `{detail: {message, errors}}`, 413 over 20 MB. A per-fragment read puts `{error}` in a failing fragment's slot. +- Validators are chem.py's (`_fragment`, `_expansions`, `_bond_length`, `_num`, `MAX_TEXT`); reuse them for a new route so messages match. + +## Routes + +| Route | Changes | Key answer fields | +| --- | --- | --- | +| `GET abbreviations` | no | `abbreviations [{label, reversed, smiles, category, source}]`, `user_file`, `user_errors` | +| `POST properties` | no | `fragments {fid: {rows, values, lipinski, veber, elemental_analysis, excluded, engine, warnings}}` | +| `POST cip` | no | `fragments {fid: {atoms, bonds, centres, double_bonds, axes, chiral, stereo_groups, smiles, cxsmiles, warnings}}` | +| `POST check` (`query?`) | no | `fragments {fid: {issues, counts, engine}}` | +| `POST stereo-groups` (`set?`, `chiral?`) | tx when asked | `groups`, `chiral`, `cxsmiles`, `warnings` | +| `POST wedges` (`atoms?`, `cip?`, `coords3d?`) | tx | `changed`, `cip`, `warnings` | +| `POST expand` (`atoms?`, `bond_length?`) | tx | `expanded {abbreviation atom: [ids]}` | +| `POST contract` (`atoms`, `label?`) | tx | `atom`, `expansion`, `label` | +| `POST add-h`, `POST remove-h` (`atoms?`) | tx | `added`; `removed`, `kept` | +| `POST smarts/export` (`atoms?`) | no | `smarts` | +| `POST smarts/import` (`text`) | no | `fragments [fragment]` | +| `POST substructure` | no | `hits [{object, atoms, bonds, map}]`, `count`, `by_object`, `truncated`, `smarts` | +| `POST molfile`, `POST molfile/import` | no | `text`; `fragments [scaffold, member...]` | +| `POST markush` (`limit?`, `force?`) | no | `count`, `structures [{smiles, formula, choice}]`, `truncated`, `groups` | +| `POST isotope-pattern` (`threshold?`), `GET isotope-pattern?formula=` | no | `formula`, `monoisotopic`, `average`, `peaks [{mass, mz, abundance, fraction}]`, `adducts [{ion, charge, mz}]` | + +## Check codes by severity + +| Severity | Codes | +| --- | --- | +| error | `valence`, `bad_bond`, `engine_error`, `bad_expansion` | +| warning | `hypervalent`, `unknown_label`, `misplaced_wedge`, `ambiguous_wedge`, `conflicting_wedges`, `wedge_between_centres`, `ring_double_bond_stereo`, `stereo_ignored`, `undefined_double_bond`, `unusual_charge`, `unknown_isotope`, `abbreviation_bonds`, `abbreviation_valence`, `overlapping_atoms`, `short_bond`, `long_bond`, `aromatic_outside_ring`, `cannot_kekulise`, `unsupported_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre`, `rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `cip_failed` | +| info | `undefined_stereocentre`, `stereo_unknown`, `unknown_ez`, `charge_imbalance`, `query_feature`, `uncommon_isotope`, `crossing_bonds`, `label_collides`, `rgroup_unused`, `rgroup_attachment_guessed` | + +`fix: "wedges"` for the wedge codes, `fix: "expand"` for the abbreviation codes. `SKIP` drops `query_ignored` and the InChI remarks. + +## Service warning codes + +| Service | Codes | +| --- | --- | +| derive and perceive | `stereo_unknown`, `undefined_double_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` | +| wedges | `cip_unreachable`, `wedge_mismatch` | +| contract, expand | `label_mismatch`, `stereo_dropped`, `abbreviation_bonds` | +| hydrogens | `stereo_changed`, `hydrogens_kept` | +| SMARTS | `smarts_rgroups`, `smarts_stereo_groups`, `abbreviations_expanded`, `smarts_any_atom`, `bad_smarts`, `smarts_opaque`, `smarts_chirality`, `smarts_bond_simplified` | +| V3000 | `v3000_query_lossy` | +| Markush | `enumeration_truncated` | +| properties, isotopes | `property_failed`, `incomplete` | diff --git a/.claude/skills/formchem-skillset/EVALS.json b/.claude/skills/formchem-skillset/EVALS.json index 2f23d933..46a20dac 100644 --- a/.claude/skills/formchem-skillset/EVALS.json +++ b/.claude/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.5.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.6.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -134,10 +134,36 @@ "Checks that the arrow kind's deps list the anchored fragments so the renderer re-lays it out when they change", "Verifies with a MutationObserver that one move changes only the atom's nodes and the anchored arrow, without rebuilding the layer" ] + }, + { + "id": 13, + "name": "new-check-code", + "prompt": "Add a FormChem structure check that warns when a carbon carries a +3 charge drawn as a label, with a fix that does nothing new.", + "files": [], + "expected_behavior": [ + "Loads stereo-and-queries and opens its references/routes-and-codes.md before editing", + "Adds the code in backend/app/services/chem/check.py with a SEVERITY entry and no fix (FIX only names existing analysis routes such as wedges or expand)", + "Adds the row to routes-and-codes.md and docs/ANALYSIS.md and a backend HASHOUT entry, and does not put a transaction in the issue" + ] + }, + { + "id": 14, + "name": "tauri-cli-bump", + "prompt": "The tauri crate in Cargo.lock moved to 2.13.1; update FormChem so ./build_app still builds.", + "files": [], + "expected_behavior": [ + "Loads desktop and states the rule that @tauri-apps/cli major.minor must equal the tauri crate's", + "Sets @tauri-apps/cli in frontend/package.json to a 2.13 release in the same change as package-lock.json, checking the @tauri-apps/plugin-* packages against their tauri-plugin-* crates", + "Runs ./formchem desktop check (not a full tauri build on a small machine) and records the bump in the HASHOUT log" + ] } ], "trigger_evals": [ {"query": "add an MCP tool to formchem", "should_trigger": true}, + {"query": "formchem shows (S) on the wrong side of the stereocentre after contracting CO2H", "should_trigger": true}, + {"query": "fix formchem's SMARTS export for atom lists in services/chem/query.py", "should_trigger": true}, + {"query": "formchem build_app stops with the Tauri CLI did not install", "should_trigger": true}, + {"query": "what is the cLogP of the structure in my FormChem drawing?", "should_trigger": false}, {"query": "formchem's perceive reactions picks the wrong reactants for a vertical arrow", "should_trigger": true}, {"query": "add a new glassware template to the formchem template library", "should_trigger": true}, {"query": "the curved arrow in formchem's renderer draws its head on the wrong side", "should_trigger": true}, diff --git a/.claude/skills/formchem-skillset/SKILL.md b/.claude/skills/formchem-skillset/SKILL.md index 406293cc..bc0400e8 100644 --- a/.claude/skills/formchem-skillset/SKILL.md +++ b/.claude/skills/formchem-skillset/SKILL.md @@ -1,17 +1,17 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, validation, the fchem package, imports), the engine store, the RDKit service (SMILES, InChIKey, formula, masses, layout, warnings), reactions (perception, Indigo atom mapping, balance, stoichiometry, RXN), the SVG canvas renderer patching on every edit, drawing tools (one undo step per drag), hover hotkeys, hit testing, arrows, brackets, shapes, tables, TLC, captions, groups, templates, media, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck or FormVis, and not for standalone RDKit scripts." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, the fchem package), the engine store, the RDKit service (SMILES, InChIKey, masses, layout, warnings, CIP and enhanced stereo, wedges, abbreviations, queries, SMARTS, R-groups, properties, the structure check, isotope patterns), reactions (perception, Indigo mapping, balance, stoichiometry, RXN, roles), the SVG canvas renderer and marks, drawing tools, hover hotkeys, hit testing, arrows, shapes, captions, templates, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell and desktop build, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck, and not for standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.5.0" + version: "0.6.0" --- # FormChem skillset Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine as a sidecar. -**Where FormChem is (0.5.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 adds reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. Stereo labels, abbreviations and structure checks (0.6.0), exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.6.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 adds stereo, queries and analysis: enhanced stereo groups and the chiral flag in RDKit, the CIP report, wedge assignment, abbreviations and explicit hydrogens, query atoms and bonds, SMARTS, substructure search, V3000 query molfiles, R-groups and Markush enumeration, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the keyed marks layer, the chemistry commands and dialogs, Set Reaction Roles, and the Tauri CLI pin for the desktop build. Exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. ## Subsystem map @@ -25,6 +25,7 @@ Route every change to FormChem's code through this file. It maps the subsystems | Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | | Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | | Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | +| Stereo, queries and analysis: stereo groups, CIP report, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, V3000 queries, Markush, properties, the structure check, the isotope pattern, their routes, tools, commands, marks and panels | `backend/app/services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `frontend/src/engine/analysis-api.ts`, `app/chem-edits.ts`, `app/chem-commands.ts`, `canvas/render/marks-*.ts`, the 0.6.0 dialogs in `ui/`, `docs/ANALYSIS.md` | `stereo-and-queries` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | @@ -42,7 +43,9 @@ engine/model.ts, engine/ops.ts -> nothing (pure, DOM free; the contract) chem/ -> engine/model.ts only (pure, no t(), no DOM) engine/client.ts, session.ts -> model, ops, client-api, io/api, io/live canvas/render -> canvas/types.ts, engine/model, engine/ops (its own geom, valence, rings); - render/table.ts also chem/stoich.ts, the one window stoichiometry source + render/table.ts also chem/stoich.ts, the one window stoichiometry source; + render/marks-layer.ts also canvas/marks-options.ts (view toggles only) +engine/analysis-api.ts -> io/api, model, ops; the only caller of /api/analysis canvas/tools -> canvas/types.ts, engine/model, engine/ops, canvas/geom.ts canvas/view.ts, ui/tool-rail -> canvas/types.ts, hit.ts, selection.ts, ui/dom, ui/icons, i18n io/ -> registry only for the catalogue mirror @@ -52,7 +55,8 @@ backend services/model.py, ops.py -> nothing (pure; the contract) services/store.py -> model, ops, package, history, importers, hub; chem.derive imported lazily services/chem/ -> rdkit, indigo, model (never the store or routers) backend routers -> core, services (hub, bridge, library, store, chem, terminal, formext_host) -mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub +mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub; + routers/analysis imported lazily by the analysis tools window-only abilities -> reach the engine as window tools over /api/live (bridge.window_call) desktop shell -> frozen engine (formchem_engine.py) -> serves frontend/dist ``` @@ -85,13 +89,14 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | Drawing on the canvas: how a bond, label or wedge renders, a drawing tool, a hover hotkey, snapping, hit testing, selection, zoom and pan, the tool rail, canvas right-click menus | `canvas` | | An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `annotations`, with `canvas` for the laws it builds on | | Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | +| A CIP label, stereo group, wedge, abbreviation, explicit hydrogen, atom list, query bond, SMARTS, substructure hit, R-group, property, check issue or isotope peak; an `/api/analysis` route, an analysis MCP tool, a stereo or query mark | `stereo-and-queries`, with `chemistry-engine` for the converter and `agents` for a tool | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | | A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | | Terminal tabs, Claude Code, Codex, Cursor or Antigravity tabs, the consent dialog, chat | `dock` | | The extensions pane, an extension API call, FormPortal or form.ext integration | `extensions` | | A new MCP tool, the commands catalogue, `./formchem agents`, skills, the manifest | `agents` | -| Desktop build, sidecar, updater, Tauri commands, title bar overlay | `desktop` | +| Desktop build, `build_app`, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | | A release, version sites, CHANGELOG, NOTICE, CI | `release` | | Any chemistry feature, a file format, a name for a command or panel | `clean-room` first | | Use FormChem: insert a structure, run a menu command, hand off in the window | Not this pack: `formchem-harness` | @@ -103,9 +108,10 @@ formchem-skillset/ SKILL.md this router, the subsystem map and the laws in short references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) - sub-skills/ engine, document-format, chemistry-engine, reactions, canvas, annotations, window-shell, - menus, dock, extensions, agents, desktop, release, clean-room + sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, canvas, annotations, + window-shell, menus, dock, extensions, agents, desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from + stereo-and-queries/references/routes-and-codes.md the /api/analysis routes, check codes and service warning codes canvas/references/hover-keys.md the hover key map with the code that implements it ``` diff --git a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index da1bcc14..b0021068 100644 --- a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -30,11 +30,11 @@ Give agents a small, honest tool surface that only describes what FormChem can d 4. Describe only what works now. A tool for a later phase lands in that phase. 5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. -## What agents can reach in 0.5.0 +## What agents can reach in 0.6.0 -- Ten tools: the six of the shell plus `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`); the `reactions` specialist owns them. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, `validate`, edit ops, `compute_properties`, `convert`) land in 0.8.0; do not add them early or describe them as present. -- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). -- `mcp.py` describes the shell as of 0.4.0 (a sentence naming the reaction tools in `INSTRUCTIONS` and `get_context` is still to add): `DRAWING_FROM = "0.8.0"` names when the direct drawing tools arrive, and `INSTRUCTIONS`, `GUIDE` and the `get_context` description say drawings exist and change through `run_command` and extensions. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. +- Fourteen tools: the six of the shell; `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`), owned by `reactions`; and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure` (outside `MUTATING`, never asking), which reuse the analysis router's source rules through `_analysis_source` with a lazy import so mcp.py does not load RDKit at import, owned by `stereo-and-queries`. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, edit ops, `convert`) land in 0.8.0; do not add them early or describe them as present. +- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands, `set-reaction-roles {role, objects}` and the 0.6.0 chemistry commands such as `assign-wedges`, `set-stereo-group-and`, `add-hydrogens` and `expand-abbreviation`) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). +- `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` text name the reaction tools, the analysis tools and the chemistry commands; `DRAWING_FROM = "0.8.0"` names when the atom and bond tools arrive. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. - `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing. - A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window. diff --git a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md index 17fe7f64..20e43a6d 100644 --- a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md @@ -21,6 +21,7 @@ Let the person draw at the speed of thought while the document stays the only tr | `canvas/hit.ts`, `selection.ts` | Hit testing and region selection on model geometry; selection sets and helpers | | `canvas/text-editor.ts`, `canvas/context.ts` | The in-place label and text editor; right-click menus for atom, bond, selection and background (`deleteSelectionOps`) | | `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups | +| Stereo and query marks (0.6.0) | `render/marks-layer.ts` (`ChemMarks`, one keyed layer cached per fragment; replaced `render/stereo.ts`), `marks-stereo.ts`, `marks-query.ts` and `canvas/marks-options.ts` belong to the `stereo-and-queries` specialist; the view toggles reach the renderer through `RenderDisplay.enhancedStereo`, `queryMarks` and `groupColours` | | Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text | | `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper | | `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key | diff --git a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index df7f56d9..12b5a79d 100644 --- a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -20,7 +20,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `chem/mass.py` | `average_mass`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `isotope_pattern`, `properties(conv)` | | `chem/layout.py` | `compute_coords(frag, ids, bond_length, fixed)` (CoordGen, RDKit fallback), `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move) | | `chem/io.py` | `detect`, `read_text`, `read_file` (`ParseResult` with fragments, warnings, reaction), `export`, `to_molfile`, `to_smiles`; SDF, RXN, reaction SMILES, CML, cdxml and cdx (Indigo), InChI; at most 1000 records per call | -| `chem/abbrev.py` | 75 built-in abbreviations with attachment SMILES; `resolve`, `element_like`, `reversed_label` | +| `chem/abbrev.py` | 106 built-in abbreviations in six categories plus the person's `abbreviations.json`; `resolve`, `element_like`, `reversed_label`, `library`, `match` | | `chem/derive.py` | `derive_fragment(frag, expansions, rev)`, `derive_document(doc, rev, only)`, `content_key`, an LRU cache of 2048 fragments | | `backend/app/routers/chem.py` | `POST /api/chem/parse`, `/derive`, `/layout`, `/convert`, `/properties`; 422 for bad input, 413 over 20 MB of text, at most 5000 atoms | | `backend/app/services/store.py` | `schedule_derive` and `_derive_loop`: after each transaction, derive in a thread on a deep copy and broadcast `{t: "derived", doc, rev, derived}` | @@ -28,6 +28,7 @@ Compute everything chemical in one place, from the drawing as the person drew it | `frontend/src/canvas/render/valence.ts`, `render/rings.ts` | The renderer's own fast implicit-H table and ring perception, used while drawing | | `references/warning-codes.md` | Every warning code, the module that raises it and when. Open before adding or interpreting a warning | | Reaction modules (0.5.0) | `chem/geometry.py`, `reactions.py`, `mapping.py`, `balance.py`, `stoich.py`, `rxnio.py`, `scheme.py`, `derive.reaction_checks` and `routers/reactions.py` belong to the `reactions` specialist; they reuse `convert.to_mol` and the rules here | +| Analysis modules (0.6.0) | `chem/stereo.py`, `superatom.py`, `hydrogens.py`, `query.py`, `search.py`, `v3000.py`, `markush.py`, `props.py`, `check.py`, `isotopes.py` and `routers/analysis.py` belong to the `stereo-and-queries` specialist. Here they changed `convert.py` (stereo groups and the chiral flag after perception, query atoms and bare `*` as generics), `perceive.py` (`stereo_unknown`, `undefined_double_bond`, cumulenes skipped, charged atoms judged by the allowed list so Na+ is no valence error) and `derive.content_key` (`FRAGMENT_FIELDS`) | ## Rules diff --git a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md index 5ab65a8b..58dfb4eb 100644 --- a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md +++ b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/references/warning-codes.md @@ -36,7 +36,7 @@ These appear in `derived.fragments[fid].warnings` after every transaction. | `charge_imbalance` | perceive.py | The pieces of one fragment carry a net charge | | `engine_error` | derive.py | Any exception inside the engine for this fragment; values are empty | -Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged. +Valence errors are not warnings: they are the separate `valence_errors` list (`{atom, valence, allowed}`), and `allowed` is empty for metals, which are never flagged. From 0.6.0 a charged atom is judged by its charge-shifted allowed list alone (RDKit 2025.09 flags a bare Na+), and `unknown_label` no longer fires for query atoms (lists, A, Q, X, M) or a bare `*`, which count as generics. ## Stereo warnings @@ -47,6 +47,11 @@ Valence errors are not warnings: they are the separate `valence_errors` list (`{ | `conflicting_wedges` | convert.py | Wedges on one centre imply opposite configurations | | `misplaced_wedge` | convert.py | The narrow end of a wedge (atom `a`) is not a stereocentre | | `unknown_ez` | convert.py | A double bond drawn crossed (`either`) or next to a wavy bond | +| `stereo_unknown` | perceive.py | A stereocentre on a wavy bond (marked unknown on purpose) (0.6.0) | +| `undefined_double_bond` | perceive.py | A stereogenic double bond that is neither specified nor marked crossed or wavy, usually a substituent on the bond's line; cumulated bonds are skipped (0.6.0) | +| `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` | convert.py | A malformed `stereo_groups` entry, an atom in two groups, or a grouped atom that is not a stereocentre (dropped from the group) (0.6.0) | + +The 0.6.0 analysis services (wedges, contract and expand, hydrogens, SMARTS, V3000, Markush, properties) and the structure check codes belong to the `stereo-and-queries` specialist, which lists them. ## Identifier warnings diff --git a/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md index 73aa0d56..0bd95c76 100644 --- a/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md @@ -31,8 +31,14 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t - Releases are built by formcompiler from `tauri.conf.json`; do not hand-build release artifacts. - Do not run cargo build, tauri build or pyinstaller on a shared or small machine unless the task says so. +## The Tauri CLI pin + +`@tauri-apps/cli` is a pinned dev dependency in `frontend/package.json` (2.12.6). The rule: its major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7), and each `@tauri-apps/plugin-*` package shares major.minor with its `tauri-plugin-*` crate; bump them together in one change, with `package-lock.json`. Tauri refuses to build across minor versions. Until 0.6.0 package.json did not list the CLI, so `npm ci` installed no `tauri` binary and `./build_app` stopped with "the Tauri CLI did not install"; with the pin, the owner's `./build_app` on macOS arm64 (Python 3.14) built the app. + +`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck`, and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it. + ## Gate -- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable). +- [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable, CLI and crate share major.minor). - [ ] The desktop dev run opens the window without a white flash and the engine answers `/api/health` on its port. - [ ] Quitting the app ends the engine process on every platform touched. diff --git a/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md index f75ad6fe..361ff088 100644 --- a/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md @@ -30,11 +30,12 @@ Read `docs/FORMAT.md` (Reactions on a page, the table `stoich` rule, the derived | `frontend/src/ui/stoich-panel.ts`, `styles/stoich.css` | the panel in row 2 of `.fc-workspace` | | `frontend/src/canvas/render/table.ts` | draws a `stoich` table live from `computeStoich` | | `frontend/src/engine/reactions-api.ts`, `app/reaction-commands.ts` | the typed route client and the Reaction menu commands | +| `frontend/src/chem/reaction-roles.ts`, `ui/roles-dialog.ts` | Set Reaction Roles (0.6.0): `reactionRoleOps` moves changed ids between role lists, sets `explicit: true` and drops coefficients and `stoich` entries that no longer fit, in one transaction; `canTakeRole` (fragments, text, captions, groups, images, shapes, tables, never the arrow); the keyed roles dialog. Window-side, no engine route | ## Laws - **One reading of stoichiometry.** The engine's `stoich.py` and the window's `chem/stoich.ts` follow the same precedence: `scale_mmol` is the reference when present, else the limiting reagent's typed amount over its equiv, else the first amount; typed amounts beat typed equivalents. Never add a third computation; the renderer's own copy was deleted for disagreeing. Only typed values are stored, and the window's write rules (mass, volume or equiv replaces the other two; scale and the limiting reagent's amount replace each other) keep the two readings equal. -- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true`; re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md. +- **Roles from geometry, kept when explicit.** Perception never touches a step with `explicit: true` (set by Set Reaction Roles, an agent's `set-reaction-roles {role, objects}`, or a reaction file); re-running keeps ids and writes nothing when equal. A change to a distance constant is a contract change in FORMAT.md. - **Routes are transactions.** A changing route builds ops on a copy and applies them with `STORE.apply`, returning `{changed, tx, rev}` and broadcasting the tx with the caller's `client`; no change means `changed: false` and no undo step. Agents go through `_apply` with origin `agent`. - **Map numbers are atom data.** `Atom.map` and `Bond.reacting` are the only places mapping lives, so chained steps share the numbers of a shared structure. - **Exchange keeps what the format can carry.** Kekulise RXN, keep reaction SMILES aromatic, put conditions on RXN line 4, report what is dropped as a warning code. diff --git a/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md new file mode 100644 index 00000000..cb3ba469 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/SUB-SKILL.md @@ -0,0 +1,53 @@ +--- +name: stereo-and-queries +description: "FormChem's 0.6.0 stereo, query and analysis layer: enhanced stereo groups and the chiral flag into RDKit, the CIP stereo report, wedge assignment, the abbreviation library with contract and expand, explicit hydrogens, query atoms and bonds as one SMARTS-built query molecule, SMARTS in and out, substructure search, V3000 query molfiles with R-group blocks, Markush enumeration, properties with method labels, the structure check codes, the isotope pattern, the /api/analysis router, the four analysis MCP tools, and the window side (analysis-api.ts, chem-edits, chem-commands, the keyed marks layer, the dialogs, the check panel, the properties section and isotope plot). Use when a CIP label, stereo group, wedge, abbreviation, query, SMARTS, R-group, property, check issue or isotope peak is wrong, or a route, command, mark or check code is added." +--- + +# Stereo and queries + +## Purpose + +Keep the chemistry of 0.6.0 in one shape: the engine (RDKit) computes and proposes, the window commits one transaction per command, and every number carries its method. The doc is `docs/ANALYSIS.md`; the reasons are in `backend/HASHOUT_LOG.md` 78 to 98 and `frontend/HASHOUT_LOG.md` 133 to 148. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/services/chem/convert.py` | `_read_groups`, `apply_groups` (stereo groups and `chiral` into RDKit after perception), `groups_from_mol`, `_query_label` (query atoms and bare `*` are generics) | +| `chem/stereo.py` | `report` (centres, double bonds, axes, state, group label, CXSMILES), `regroup`, `groups_tx`, `preview`, `rewedge` (from the drawing, wanted CIP or 3D) | +| `chem/perceive.py` | `stereo_unknown`, `undefined_double_bond`, `not_ez_bonds` (cumulenes), the charged-atom valence rule | +| `chem/abbrev.py`, `chem/superatom.py` | 106 built-ins plus `abbreviations.json`; `match`, `PREFERRED`; `contract` and `expand` keeping ids | +| `chem/hydrogens.py` | `add_hydrogens`, `remove_hydrogens` | +| `chem/query.py`, `chem/search.py` | `query_mol`, `to_smarts`, `from_smarts`, `parse_atom_smarts`; `substructure` | +| `chem/v3000.py`, `chem/markush.py` | query molfile `write` and `read` (FormChem's own RGROUP reader); `member_attachments`, `enumerate_structures` | +| `chem/props.py`, `chem/check.py`, `chem/isotopes.py` | `compute` with `method` and `note`; `check` with `SEVERITY`, `FIX`, `SKIP`; `from_counts`, `pattern`, `parse_formula` | +| `backend/app/routers/analysis.py` | every `/api/analysis` route; `source` (stateless or `doc`), `finish` (`apply`), `_ids_of` | +| `backend/app/routers/mcp.py` | `t_properties`, `t_check_structure`, `t_stereo`, `t_substructure`, `_analysis_source` (lazy router import) | +| `frontend/src/engine/analysis-api.ts` | the only caller of `/api/analysis`; `sourceFor`, defensive readers | +| `frontend/src/app/chem-edits.ts`, `app/chem-commands.ts` | window-side op builders; `registerChemCommands`, `CHEM_MENU_ITEMS`, `chemContextItems` | +| `frontend/src/canvas/render/marks-layer.ts`, `marks-stereo.ts`, `marks-query.ts`, `canvas/marks-options.ts` | `ChemMarks` keyed layer and its view toggles | +| `frontend/src/ui/` | `periodic-grid`, `atom-list-dialog`, `rgroup-dialog`, `abbreviation-dialog`, `stereo-popover`, `query-menus`, `structure-check`, `analysis-properties`, `isotope-plot`, `markush-dialog` | +| `references/routes-and-codes.md` | the routes with their bodies and answers, the check codes by severity, the warning codes of each service. Open before adding a route, a code or a reader | + +## Rules + +- **Plain fields in the window, RDKit in the engine.** Atom lists, generic queries, query bonds and topology, stereo groups, the chiral flag and R-group definitions are field edits FORMAT defines: build them in `chem-edits.ts` and commit at once. Anything that needs perception (hydrogens, contract, expand, wedges, the check, properties, search, Markush, SMARTS) is an engine route that answers `tx: {label, ops}`. +- **One transaction per command.** The window commits the engine's ops once, across fragments, and only if every fragment record it sent is still current; otherwise it says the drawing changed. A route with `doc` and `apply: true` applies on the engine side instead. Never commit per fragment. +- **Groups go in after perception.** `apply_groups` runs after stereo perception so only real centres are grouped; anything that changes `stereo_groups` or `chiral` must stay in `derive.FRAGMENT_FIELDS` or cached CXSMILES goes stale. +- **Chiral flag 0 reads absolute.** A deliberate deviation from the clean-room spec (most files write 0 for enantiomers); do not "fix" it without the owner. +- **Ids survive contract and expand.** Expansion-internal ids are not live document ids (`_ids_of`); expand restores them unless they clash. +- **Every property names its method.** A new property row has `method` (the RDKit call) and `note` (in words), and the window's `PROPERTY_ROWS` gets a reserved width. +- **A fix is a command name.** A check issue names its repairing route in `fix`, never a transaction; add the code to `SEVERITY` (and `FIX` if repairable) and to the window's row text. +- **Marks are keyed.** New marks are specs in `marks-stereo.ts` or `marks-query.ts`, cached per fragment by `ChemMarks`; explicit fills, no CSS colours; never rebuild the layer. +- **Agents read through tools, change through commands.** Analysis tools stay read-only and outside `MUTATING`; a changing chemistry command is a window command agents reach with `run_command`. + +## Known gaps (do not paper over) + +Allene axial chirality and drawn atropisomers are not perceived; link nodes and variable attachment are not built; SMARTS import draws aromatic rings as single bonds (fix: order 1.5 when both ends are aromatic); Markush `count` is before dedup and if-then; Export SMARTS copies in the desktop shell until 0.7.0. + +## Gate + +- [ ] `backend/venv/bin/python -m compileall -q backend/app` is clean; `cd frontend && npx tsc --noEmit` is clean. +- [ ] A scratch script outside the repo checks the AC5.3 CIP table (L-alanine S, meso-tartaric R and S, pentane-2,3,4-triol S, r, R) and ibuprofen properties (cLogP 3.07, TPSA 37.3) and isotopes (CH2Cl2 M+2 63.92, C6H5Br M+2 97.45). +- [ ] Contract then expand gives back the same atom ids and coordinates; each command added exactly one undo step. +- [ ] Under 4x CPU throttling a mark toggle or a property refresh patches nodes only (MutationObserver), and the properties section keeps its height. diff --git a/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md new file mode 100644 index 00000000..a90f8fb6 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/stereo-and-queries/references/routes-and-codes.md @@ -0,0 +1,60 @@ +# Analysis routes and codes + +The `/api/analysis` routes of `backend/app/routers/analysis.py`, the structure check codes of `chem/check.py` and the warning codes of each 0.6.0 service, as of 0.6.0. `docs/ANALYSIS.md` has the full answer shapes; when this page and the code differ, the code wins and this page is the bug. + +## Contents + +- Request rules +- Routes +- Check codes by severity +- Service warning codes + +## Request rules + +- Source, stateless: `fragment`, optional `expansions`, optional `members` (fragment id to fragment). From a document: `doc` plus `object` or `objects`; expansions and members come from the document. +- Changing routes answer `tx: {label, ops}` (paths from the document root). `doc` with `apply: true` applies it (origin `user`) and adds `applied: {tx, rev}` or `applied: null`. +- Errors: 422 `{detail}` sentence, 404 unknown doc or object, 409 `{detail: {message, errors}}`, 413 over 20 MB. A per-fragment read puts `{error}` in a failing fragment's slot. +- Validators are chem.py's (`_fragment`, `_expansions`, `_bond_length`, `_num`, `MAX_TEXT`); reuse them for a new route so messages match. + +## Routes + +| Route | Changes | Key answer fields | +| --- | --- | --- | +| `GET abbreviations` | no | `abbreviations [{label, reversed, smiles, category, source}]`, `user_file`, `user_errors` | +| `POST properties` | no | `fragments {fid: {rows, values, lipinski, veber, elemental_analysis, excluded, engine, warnings}}` | +| `POST cip` | no | `fragments {fid: {atoms, bonds, centres, double_bonds, axes, chiral, stereo_groups, smiles, cxsmiles, warnings}}` | +| `POST check` (`query?`) | no | `fragments {fid: {issues, counts, engine}}` | +| `POST stereo-groups` (`set?`, `chiral?`) | tx when asked | `groups`, `chiral`, `cxsmiles`, `warnings` | +| `POST wedges` (`atoms?`, `cip?`, `coords3d?`) | tx | `changed`, `cip`, `warnings` | +| `POST expand` (`atoms?`, `bond_length?`) | tx | `expanded {abbreviation atom: [ids]}` | +| `POST contract` (`atoms`, `label?`) | tx | `atom`, `expansion`, `label` | +| `POST add-h`, `POST remove-h` (`atoms?`) | tx | `added`; `removed`, `kept` | +| `POST smarts/export` (`atoms?`) | no | `smarts` | +| `POST smarts/import` (`text`) | no | `fragments [fragment]` | +| `POST substructure` | no | `hits [{object, atoms, bonds, map}]`, `count`, `by_object`, `truncated`, `smarts` | +| `POST molfile`, `POST molfile/import` | no | `text`; `fragments [scaffold, member...]` | +| `POST markush` (`limit?`, `force?`) | no | `count`, `structures [{smiles, formula, choice}]`, `truncated`, `groups` | +| `POST isotope-pattern` (`threshold?`), `GET isotope-pattern?formula=` | no | `formula`, `monoisotopic`, `average`, `peaks [{mass, mz, abundance, fraction}]`, `adducts [{ion, charge, mz}]` | + +## Check codes by severity + +| Severity | Codes | +| --- | --- | +| error | `valence`, `bad_bond`, `engine_error`, `bad_expansion` | +| warning | `hypervalent`, `unknown_label`, `misplaced_wedge`, `ambiguous_wedge`, `conflicting_wedges`, `wedge_between_centres`, `ring_double_bond_stereo`, `stereo_ignored`, `undefined_double_bond`, `unusual_charge`, `unknown_isotope`, `abbreviation_bonds`, `abbreviation_valence`, `overlapping_atoms`, `short_bond`, `long_bond`, `aromatic_outside_ring`, `cannot_kekulise`, `unsupported_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre`, `rgroup_undefined`, `rgroup_member_missing`, `rgroup_bonds`, `cip_failed` | +| info | `undefined_stereocentre`, `stereo_unknown`, `unknown_ez`, `charge_imbalance`, `query_feature`, `uncommon_isotope`, `crossing_bonds`, `label_collides`, `rgroup_unused`, `rgroup_attachment_guessed` | + +`fix: "wedges"` for the wedge codes, `fix: "expand"` for the abbreviation codes. `SKIP` drops `query_ignored` and the InChI remarks. + +## Service warning codes + +| Service | Codes | +| --- | --- | +| derive and perceive | `stereo_unknown`, `undefined_double_bond`, `bad_stereo_group`, `stereo_group_overlap`, `stereo_group_not_centre` | +| wedges | `cip_unreachable`, `wedge_mismatch` | +| contract, expand | `label_mismatch`, `stereo_dropped`, `abbreviation_bonds` | +| hydrogens | `stereo_changed`, `hydrogens_kept` | +| SMARTS | `smarts_rgroups`, `smarts_stereo_groups`, `abbreviations_expanded`, `smarts_any_atom`, `bad_smarts`, `smarts_opaque`, `smarts_chirality`, `smarts_bond_simplified` | +| V3000 | `v3000_query_lossy` | +| Markush | `enumeration_truncated` | +| properties, isotopes | `property_failed`, `incomplete` | diff --git a/agents/manifest.json b/agents/manifest.json index 02ffd08c..3ff9a4a9 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -71,6 +71,7 @@ "menus", "reactions", "release", + "stereo-and-queries", "window-shell" ] } From 09296713ceeecd0dfdb359b12f7cca2ff693a670 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:11:41 -0500 Subject: [PATCH 279/279] chore(release): 0.6.0 (0.6.0) --- README.md | 2 +- backend/app/__init__.py | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- frontend/src/version.ts | 2 +- src-tauri/Cargo.lock | 2 +- src-tauri/Cargo.toml | 2 +- src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml | 1 + src-tauri/tauri.conf.json | 2 +- 9 files changed, 10 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 374807bb..2792eb7f 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ with an MCP server so an agent works in the same window you see. Local-first, no account.

- version 0.5.0 + version 0.6.0 TypeScript and Vite Python and FastAPI macOS, Windows, Linux diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 3d187266..906d362f 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.5.0" +__version__ = "0.6.0" diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d205955f..47e2ba66 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formchem", - "version": "0.5.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formchem", - "version": "0.5.0", + "version": "0.6.0", "license": "Apache-2.0", "dependencies": { "@tauri-apps/api": "2.12.1", diff --git a/frontend/package.json b/frontend/package.json index 9ad2ce65..467043c0 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formchem", "private": true, - "version": "0.5.0", + "version": "0.6.0", "description": "FormChem ยท chemical structure drawing in the FormAI family", "license": "Apache-2.0", "type": "module", diff --git a/frontend/src/version.ts b/frontend/src/version.ts index 243bfad8..cc337735 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.5.0'; +export const VERSION = '0.6.0'; diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index e23948e6..5e8527b5 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1163,7 +1163,7 @@ dependencies = [ [[package]] name = "formchem" -version = "0.5.0" +version = "0.6.0" dependencies = [ "fontdb", "gtk", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index a13cca4d..2faa408c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formchem" -version = "0.5.0" +version = "0.6.0" description = "FormChem desktop shell" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml b/src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml index 7846f927..4b0ec2a5 100644 --- a/src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml +++ b/src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml @@ -15,6 +15,7 @@ https://formai.tools/download/?utm_source=github + diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 0219c913..812c6e9a 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "FormChem", - "version": "0.5.0", + "version": "0.6.0", "identifier": "ai.nodemode.formchem", "build": { "frontendDist": "../frontend/dist"

Chemistry engine

RDKit in the engine works out canonical SMILES, CXSMILES, InChI, InChIKey, formula and masses after each change, flags valence problems on the canvas, and powers Clean Up, Lay Out and Check Structure.

Analysis panel

Formula, molecular weight, exact mass, m/z for charged species and elemental analysis for the selection or the whole page, with the formula in the status bar.

Analysis panel

Formula, masses, m/z and elemental analysis, plus cLogP, TPSA, molar refractivity, donors, acceptors, rotatable bonds and the rule of five, each with its method, and the isotope pattern with adduct m/z. Copy Analysis takes it all as text.

Arrange and style

Duplicate, delete, flip, rotate, align and distribute the selection; Drawing preferences set the default style and its bond length, widths and label size; element colours, carbon labels and stereo labels on request.

Stoichiometry and templates

A stoichiometry panel for moles, equivalents, the limiting reagent and yields, insertable as a table, and 206 original templates from rings to glassware. Find and rulers with guides.

MCP server

Ten tools over HTTP and stdio: agents see the open drawings with their formulas, run the same commands as the menus, and perceive, map, export and measure reactions.

Stereochemistry

CIP labels from the new rules (R, S, r, s, E, Z), enhanced stereo groups (abs, AND, OR) and the chiral flag, Assign Wedges, and abbreviations from a library of 106 that contract and expand without losing an atom.

Queries and R-groups

Atom lists, generic atoms and query bonds drawn as tags, Find Substructure by selection or SMARTS, SMARTS and V3000 query molfiles, and R-group definitions with Markush enumeration.

Structure check

A panel of errors, warnings and notes with a code each, from valence and charges to wedges, overlaps and R-group gaps. Click a row to select its atoms, or fix wedges and abbreviations in one step.

MCP server

Fourteen tools over HTTP and stdio: agents see the open drawings with their formulas, run the same commands as the menus, perceive, map, export and measure reactions, and read properties, structure checks, stereo and substructure hits.

The family shell

Home, Preferences, twelve menus with full keyboard use, Find a Command, the terminal and agent dock, Help and updates, in 26 interface languages.

Form extensions

Extensions installed by FormPortal run in a sandboxed frame from the Extensions menu and panel, and ask before they read or change a drawing.