diff --git a/.agents/skills/formchem-harness/EVALS.json b/.agents/skills/formchem-harness/EVALS.json index b9836b2d..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.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.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, @@ -138,10 +138,79 @@ "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" + ] + }, + { + "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}, + {"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 +236,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..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: 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, 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.4.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.4.0) +## What exists today (0.6.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.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 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 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), 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 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 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 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,6 +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, 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 @@ -52,12 +54,14 @@ 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` | -| 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) | +| 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, 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` | -| 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 +78,15 @@ 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 | +| "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 - `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/references/tools.md b/.agents/skills/formchem-harness/references/tools.md index d73cfc33..cfef0fe0 100644 --- a/.agents/skills/formchem-harness/references/tools.md +++ b/.agents/skills/formchem-harness/references/tools.md @@ -1,9 +1,28 @@ # 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. 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. +## 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 +- properties +- check_structure +- stereo +- substructure +- Resource + | Tool | Kind | | --- | --- | | `get_context` | read-only | @@ -12,10 +31,18 @@ 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 | +| `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. @@ -65,6 +92,88 @@ 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 | | + +## 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/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 3707b779..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.4.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". 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 new file mode 100644 index 00000000..90c83d04 --- /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, 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 + +## 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 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. + +## 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 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 50bde3ab..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 six tools 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 34473333..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.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.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 cf216927..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}, 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, 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 @@ -25,13 +25,17 @@ 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 | | 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 2fba324e..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,12 +1,15 @@ # 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.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 - Reading the catalogue - Drawings: open, save, close - 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 @@ -42,10 +45,58 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4. | `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` 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` | 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 @@ -56,13 +107,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. +`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 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, 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/skills/formchem-skillset/EVALS.json b/.agents/skills/formchem-skillset/EVALS.json index 8ed80a71..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.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.6.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,62 @@ "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" + ] + }, + { + "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}, {"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 +192,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..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 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, 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.4.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.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.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 @@ -23,6 +23,9 @@ 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` | +| 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` | @@ -39,7 +42,10 @@ 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; + 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 @@ -49,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 ``` @@ -80,13 +87,16 @@ 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 | +| 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` | @@ -98,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, canvas, 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 401642d7..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.4.0 +## What agents can reach in 0.6.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. +- 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. @@ -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..20e43a6d 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,9 @@ 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 | +| 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 e0ab61c4..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,13 +20,15 @@ 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}` | | `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 | +| 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 new file mode 100644 index 00000000..361ff088 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md @@ -0,0 +1,62 @@ +--- +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 | +| `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` (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. + +## 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/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-harness/EVALS.json b/.claude/skills/formchem-harness/EVALS.json index b9836b2d..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.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.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, @@ -138,10 +138,79 @@ "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" + ] + }, + { + "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}, + {"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 +236,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..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: 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, 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.4.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.4.0) +## What exists today (0.6.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.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 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 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), 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 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 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 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,6 +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, 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 @@ -52,12 +54,14 @@ 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` | -| 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) | +| 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, 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` | -| 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 +78,15 @@ 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 | +| "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 - `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/references/tools.md b/.claude/skills/formchem-harness/references/tools.md index d73cfc33..cfef0fe0 100644 --- a/.claude/skills/formchem-harness/references/tools.md +++ b/.claude/skills/formchem-harness/references/tools.md @@ -1,9 +1,28 @@ # 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. 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. +## 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 +- properties +- check_structure +- stereo +- substructure +- Resource + | Tool | Kind | | --- | --- | | `get_context` | read-only | @@ -12,10 +31,18 @@ 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 | +| `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. @@ -65,6 +92,88 @@ 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 | | + +## 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/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 3707b779..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.4.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". 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 new file mode 100644 index 00000000..90c83d04 --- /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, 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 + +## 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 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. + +## 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 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 50bde3ab..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 six tools 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 34473333..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.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.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 cf216927..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}, 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, 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 @@ -25,13 +25,17 @@ 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 | | 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 2fba324e..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,12 +1,15 @@ # 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.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 - Reading the catalogue - Drawings: open, save, close - 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 @@ -42,10 +45,58 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.4. | `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` 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` | 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 @@ -56,13 +107,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. +`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 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, 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-skillset/EVALS.json b/.claude/skills/formchem-skillset/EVALS.json index 8ed80a71..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.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.6.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,62 @@ "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" + ] + }, + { + "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}, {"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 +192,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..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 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, 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.4.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.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.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 @@ -23,6 +23,9 @@ 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` | +| 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` | @@ -39,7 +42,10 @@ 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; + 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 @@ -49,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 ``` @@ -80,13 +87,16 @@ 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 | +| 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` | @@ -98,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, canvas, 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 401642d7..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.4.0 +## What agents can reach in 0.6.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. +- 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. @@ -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..20e43a6d 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,9 @@ 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 | +| 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 e0ab61c4..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,13 +20,15 @@ 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}` | | `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 | +| 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 new file mode 100644 index 00000000..361ff088 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/reactions/SUB-SKILL.md @@ -0,0 +1,62 @@ +--- +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 | +| `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` (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. + +## 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/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/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index 74e12c77..8c29b749 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -15,14 +15,27 @@ 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. +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 | +| --- | --- | --- | +| `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 | +| `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, 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 ``` @@ -35,11 +48,16 @@ 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` | -| Check | `check-structure` opens a dialog for the person; formula and masses are in the Analysis panel (`show-analysis`) | +| 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 | +| 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. 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 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 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/Annotations.md b/.docs/wiki/Annotations.md new file mode 100644 index 00000000..43793657 --- /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... (`Ctrl+F`) searches text objects, captions, table cells, atom labels (with their hydrogens, so `OH` also finds `HO`), abbreviations, element symbols, formulas (`C2H6O` finds ethanol and dimethyl ether) and SMILES (compared in canonical form). The bar shows "n of m"; `Enter`, `Shift+Enter`, `F3` and `Shift+F3` step through the matches, and the view pans only when a match is off screen. Match Case narrows the search. Replace (`Ctrl+Alt+F`) changes text objects, captions and table cells and keeps their formatting; Replace All is one undo step. `Escape` closes the bar. Stoichiometry tables bound to a reaction are not searched, because their numbers are worked out rather than stored. + +## Rulers + +View > Show Rulers shows rulers along the top and left edges of the canvas; they lie over the edges, so turning them on does not move the drawing, and the setting is remembered. They count in the drawing's units; click the corner square to switch between pt, mm, cm and in for this window. Drag out of a ruler to place a guide, drag a guide back onto the ruler to remove it, or use View > Clear Guides. Guides belong to the window and are not saved in the file, and tools do not snap to them yet. + +## 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/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/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). diff --git a/.docs/wiki/Drawing.md b/.docs/wiki/Drawing.md index 930c7208..1c17ae0e 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; 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 @@ -68,8 +69,8 @@ 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 -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/Home.md b/.docs/wiki/Home.md index c84ef7a3..d7371c97 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,12 +2,16 @@ 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, 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 | | --- | --- | | [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 | +| [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/Project-Format.md b/.docs/wiki/Project-Format.md index 5aaec615..e61a18a7 100644 --- a/.docs/wiki/Project-Format.md +++ b/.docs/wiki/Project-Format.md @@ -20,10 +20,18 @@ 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. +- 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) 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 @@ -31,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. 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. 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 new file mode 100644 index 00000000..a0d981df --- /dev/null +++ b/.docs/wiki/Reactions.md @@ -0,0 +1,75 @@ +# 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, 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 + +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/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 ad54eaf6..b36e1ab9 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -3,6 +3,10 @@ - [Home](Home) - [Getting Started](Getting-Started) - [Drawing](Drawing) +- [Annotations](Annotations) +- [Reactions](Reactions) +- [Stereo and Queries](Stereo-and-Queries) +- [Analysis](Analysis) - [Agents](Agents) - [Terminal](Terminal) - [Extensions](Extensions) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9df4c667..8483ff03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,115 @@ 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. 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. +- 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. + +### 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 (`Ctrl+F`) searches text, captions, table cells, atom labels, abbreviations, element symbols, formulas such as `C2H6O` and SMILES. `Enter` or `F3` steps through the matches, and Replace (`Ctrl+Alt+F`) changes text, captions and table cells; Replace All is one undo step. +- View > Show Rulers shows rulers along the top and left of the canvas in the drawing's units (click the corner to switch between pt, mm, cm and in). Drag a guide out of a ruler, drag it back to remove it, or use Clear Guides. +- 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. +- Every new menu item, tool name, panel and message is translated into all 25 languages. The headings of a stoichiometry table drawn on the page stay in English, because they are part of the drawing. + +### 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. diff --git a/README.md b/README.md index 8a5d08c8..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.4.0 + version 0.6.0 TypeScript and Vite Python and FastAPI macOS, Windows, Linux @@ -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, works out the amounts, labels stereochemistry and computes properties with the method behind each number. @@ -38,11 +38,21 @@ FormChem 0.4.0 draws: open or start a drawing, draw structures on the canvas wit - + - + + + + + + + + + + + @@ -50,8 +60,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 - 3D models of molecules @@ -59,7 +67,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`, `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 @@ -96,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; 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. @@ -104,7 +112,7 @@ cd formchem | Path | What it is | |---|---| -| `backend/` | FastAPI engine: documents, 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 | diff --git a/agents/manifest.json b/agents/manifest.json index 8a3672a5..3ff9a4a9 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -9,17 +9,33 @@ "run_command", "extensions_list", "extension_command", - "handoff" + "handoff", + "perceive_reactions", + "map_reaction", + "export_reaction", + "reaction_stoichiometry", + "properties", + "check_structure", + "stereo", + "substructure" ], "read_only": [ "get_context", "list_commands", - "extensions_list" + "extensions_list", + "export_reaction", + "reaction_stoichiometry", + "properties", + "check_structure", + "stereo", + "substructure" ], "approval_gated": [ "run_command", "extension_command", - "handoff" + "handoff", + "perceive_reactions", + "map_reaction" ], "transports": [ "stdio", @@ -32,7 +48,9 @@ "sub_skills": [ "extension-drawings", "handoff", + "reactions", "session-and-connection", + "structure-analysis", "visual-qa", "window-commands" ] @@ -41,6 +59,7 @@ "name": "formchem-skillset", "sub_skills": [ "agents", + "annotations", "canvas", "chemistry-engine", "clean-room", @@ -50,7 +69,9 @@ "engine", "extensions", "menus", + "reactions", "release", + "stereo-and-queries", "window-shell" ] } diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 4904c701..7dc23de5 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.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 @@ -10,15 +10,23 @@ 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), 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), 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) + 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 setup/ the commands behind the dispatcher, plus notices.py, i18n_tool.py, catalogue.py @@ -89,6 +97,42 @@ 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 +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 +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) @@ -337,3 +381,147 @@ 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. + +## 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. + +## 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 (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/backend/app/__init__.py b/backend/app/__init__.py index 6a9beea8..906d362f 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.4.0" +__version__ = "0.6.0" 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" } + ] +} 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 } + ] + } + ] +} 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] } } + ] +} 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/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/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" } + ] +} diff --git a/backend/app/data/templates/rings.json b/backend/app/data/templates/rings.json new file mode 100644 index 00000000..b33ef570 --- /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": 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 }, + "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": 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 }, + "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 } } } + ] + } + ] +} 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" } + ] +} diff --git a/backend/app/main.py b/backend/app/main.py index 9b514653..9eb5b571 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 analysis, 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,9 @@ 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(analysis.router) +app.include_router(templates.router) app.include_router(commands.router) app.include_router(extensions.router) app.include_router(terminal.router) diff --git a/backend/app/routers/analysis.py b/backend/app/routers/analysis.py new file mode 100644 index 00000000..e7d0f64c --- /dev/null +++ b/backend/app/routers/analysis.py @@ -0,0 +1,342 @@ +import asyncio +import copy +from dataclasses import dataclass, field + +from fastapi import APIRouter, HTTPException + +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, isotopes, markush, props, query, search, stereo, superatom, v3000 +from app.services.store import STORE + +router = APIRouter() + + +@dataclass +class Source: + fragments: dict[str, dict] + expansions: dict | None = None + members: dict[str, dict] = field(default_factory=dict) + doc: str | None = None + has_map: bool = False + used: set[str] = field(default_factory=set) + elsewhere: set[str] = field(default_factory=set) + + @property + def one(self) -> dict: + return next(iter(self.fragments.values())) + + +def _ids_of(doc: dict) -> set[str]: + out = {doc.get("id", "")} + out.update(p.get("id") for p in doc.get("pages") or [] if isinstance(p, dict)) + for key, obj in (doc.get("objects") or {}).items(): + out.add(key) + if isinstance(obj, dict) and obj.get("kind") == "fragment": + out.update(obj.get("atoms") or {}) + out.update(obj.get("bonds") or {}) + out.update(doc.get("expansions") or {}) + return out + + +def _from_doc(body: dict, single: bool) -> Source: + doc_id = body.get("doc") + try: + s = STORE.get(doc_id) + except KeyError: + raise HTTPException(404, f"No open drawing has the id {doc_id}.") + with s.lock: + doc = copy.deepcopy(s.doc) + frags = {k: o for k, o in (doc.get("objects") or {}).items() if isinstance(o, dict) and o.get("kind") == "fragment"} + wanted = body.get("objects") + if body.get("object") is not None: + wanted = [body.get("object")] + if wanted is not None: + if not isinstance(wanted, list) or not all(isinstance(i, str) for i in wanted): + raise HTTPException(422, "objects must be a list of fragment ids") + missing = [i for i in wanted if i not in frags] + if missing: + raise HTTPException(404, f"{missing[0]} is not a fragment of {doc_id}.") + chosen = {i: frags[i] for i in wanted} + elif single: + raise HTTPException(422, "name the fragment with object") + else: + chosen = frags + if single and len(chosen) != 1: + raise HTTPException(422, "this command acts on one fragment: give object") + elsewhere = {a.get("expansion") for k, f in frags.items() if k not in chosen for a in (f.get("atoms") or {}).values() if a.get("expansion")} + elsewhere |= {a.get("expansion") for e in (doc.get("expansions") or {}).values() if isinstance(e, dict) for a in (e.get("atoms") or {}).values() if a.get("expansion")} + return Source(chosen, doc.get("expansions") or {}, frags, doc_id, "expansions" in doc, _ids_of(doc), elsewhere - {None}) + + +def source(body: dict, single: bool = False) -> Source: + if body.get("doc") is not None: + if not isinstance(body.get("doc"), str): + raise HTTPException(422, "doc must be a document id") + return _from_doc(body, single) + frag = _fragment(body) + members = body.get("members") or {} + if not isinstance(members, dict): + raise HTTPException(422, "members must be a map of fragment id to fragment") + checked = {k: _fragment({"fragment": {"id": k, **m}}) for k, m in members.items() if isinstance(m, dict)} + exp = _expansions(body) + return Source({frag["id"]: frag}, exp, checked, None, exp is not None) + + +def _unprocessable(exc: Exception) -> HTTPException: + return HTTPException(422, str(exc)) + + +async def run(fn, *args, **kwargs): + try: + return await asyncio.to_thread(fn, *args, **kwargs) + except HTTPException: + raise + except (ValueError, KeyError) as exc: + raise _unprocessable(exc) + + +def _each(src: Source, fn) -> dict: + out = {} + for fid, frag in src.fragments.items(): + try: + out[fid] = fn(frag) + except Exception as exc: + out[fid] = {"error": f"{type(exc).__name__}: {exc}"} + return {"fragments": out, "engine": ENGINE} + + +@router.get("/api/analysis/abbreviations") +def abbreviations() -> dict: + path = abbrev.user_path() + return {"abbreviations": abbrev.library(), "user_file": str(path) if path else None, "user_errors": abbrev.user_errors()} + + +@router.post("/api/analysis/properties") +async def properties(body: dict) -> dict: + src = source(body) + return await run(_each, src, lambda f: props.compute(f, src.expansions)) + + +@router.post("/api/analysis/cip") +async def cip(body: dict) -> dict: + src = source(body) + return await run(_each, src, lambda f: stereo.report(f, src.expansions)) + + +@router.post("/api/analysis/check") +async def check_structure(body: dict) -> dict: + src = source(body) + is_query = body.get("query") is True + return await run(_each, src, lambda f: check.check(f, src.expansions, src.members, is_query)) + + +def _atoms(body: dict, key: str = "atoms") -> list[str] | None: + value = body.get(key) + if value is None: + return None + if not isinstance(value, list) or not all(isinstance(i, str) for i in value): + raise HTTPException(422, f"{key} must be a list of atom ids") + return value + + +async def finish(body: dict, src: Source, result: dict) -> dict: + tx = result.get("tx") + if body.get("apply") is not True or not tx: + return result + if src.doc is None: + raise HTTPException(422, "apply needs doc: send the document id instead of a fragment") + if not tx["ops"]: + return {**result, "applied": None} + try: + done = await STORE.apply(src.doc, {"label": tx["label"], "ops": tx["ops"]}, "user") + except opsmod.OpError as exc: + raise HTTPException(409, {"message": str(exc), "errors": exc.errors}) + except KeyError: + raise HTTPException(404, f"The drawing {src.doc} was closed.") + return {**result, "applied": {"tx": done["tx"], "rev": done["rev"]}} + + +@router.post("/api/analysis/stereo-groups") +async def stereo_groups(body: dict) -> dict: + src = source(body, single=True) + frag = src.one + change = body.get("set") + groups = None + if change is not None: + if not isinstance(change, dict) or change.get("kind") not in stereo.KINDS: + raise HTTPException(422, "set needs kind abs, and or or, and atoms") + n = change.get("n") + if n is not None and (not isinstance(n, int) or isinstance(n, bool) or n < 1): + raise HTTPException(422, "n must be a group number from 1") + groups = stereo.regroup(frag, change["kind"], _atoms(change) or [], n) + set_chiral = "chiral" in body + flag = body.get("chiral") + if set_chiral and flag not in (None, *convert.CHIRAL_FLAGS): + raise HTTPException(422, "chiral must be absolute, relative, racemic or null") + out = await run(stereo.preview, frag, groups, flag, set_chiral, src.expansions) + if groups is not None or set_chiral: + out["tx"] = stereo.groups_tx(frag, groups, flag, set_chiral) + return await finish(body, src, out) + + +@router.post("/api/analysis/wedges") +async def wedges(body: dict) -> dict: + src = source(body, single=True) + wanted = body.get("cip") + if wanted is not None and (not isinstance(wanted, dict) or any(v not in ("R", "S") for v in wanted.values())): + raise HTTPException(422, "cip must map atom ids to R or S") + coords = body.get("coords3d") + if coords is not None and (not isinstance(coords, dict) or any(not isinstance(v, list) or len(v) != 3 or not all(_num(x) for x in v) for v in coords.values())): + raise HTTPException(422, "coords3d must map atom ids to [x, y, z]") + out = await run(stereo.rewedge, src.one, src.expansions, _atoms(body), wanted, coords) + return await finish(body, src, out) + + +@router.post("/api/analysis/expand") +async def expand(body: dict) -> dict: + src = source(body, single=True) + length = _bond_length(body) if body.get("bond_length") is not None else None + out = await run(superatom.expand, src.one, _atoms(body), src.expansions, length, src.used, src.elsewhere, src.doc is not None) + return await finish(body, src, out) + + +@router.post("/api/analysis/contract") +async def contract(body: dict) -> dict: + src = source(body, single=True) + atoms = _atoms(body) + if not atoms: + raise HTTPException(422, "atoms (the selected substituent) is required") + label = body.get("label") + if label is not None and (not isinstance(label, str) or not label.strip() or len(label) > 40): + raise HTTPException(422, "label must be a short text") + out = await run(superatom.contract, src.one, atoms, label.strip() if label else None, src.expansions, src.has_map, src.used) + return await finish(body, src, out) + + +@router.post("/api/analysis/add-h") +async def add_h(body: dict) -> dict: + src = source(body, single=True) + out = await run(hydrogens.add_hydrogens, src.one, src.expansions, _atoms(body), src.used) + return await finish(body, src, out) + + +@router.post("/api/analysis/remove-h") +async def remove_h(body: dict) -> dict: + src = source(body, single=True) + out = await run(hydrogens.remove_hydrogens, src.one, src.expansions, _atoms(body)) + return await finish(body, src, out) + + +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 _origin(body: dict) -> tuple[float, float]: + origin = body.get("origin") + if isinstance(origin, list) and len(origin) == 2 and all(_num(v) for v in origin): + return float(origin[0]), float(origin[1]) + return 72.0, 72.0 + + +def _limit(body: dict, key: str, default: int, top: int) -> int: + value = body.get(key, default) + if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= top: + raise HTTPException(422, f"{key} must be a whole number from 1 to {top}") + return value + + +@router.post("/api/analysis/smarts/export") +async def smarts_export(body: dict) -> dict: + src = source(body, single=True) + text, notes = await run(query.to_smarts, src.one, src.expansions, _atoms(body)) + return {"smarts": text, "warnings": notes, "engine": ENGINE} + + +@router.post("/api/analysis/smarts/import") +async def smarts_import(body: dict) -> dict: + frag, notes = await run(query.from_smarts, _text(body), _bond_length(body), _origin(body)) + return {"format": "smarts", "fragments": [frag], "warnings": notes} + + +@router.post("/api/analysis/substructure") +async def substructure(body: dict) -> dict: + smarts = body.get("smarts") + if smarts is not None and (not isinstance(smarts, str) or not smarts.strip()): + raise HTTPException(422, "smarts must be a SMARTS string") + pattern = None + src = source({k: v for k, v in body.items() if k != "object"}) if body.get("doc") is not None else None + if smarts is None: + named = body.get("query_object") + if src is not None and isinstance(named, str): + if named not in src.members: + raise HTTPException(404, f"{named} is not a fragment of {src.doc}.") + pattern = src.members[named] + elif isinstance(body.get("query"), dict): + pattern = _fragment({"fragment": body["query"]}) + else: + raise HTTPException(422, "give query (a fragment), query_object (a fragment of doc) or smarts") + if src is not None: + targets = {k: f for k, f in src.fragments.items() if not pattern or k != pattern.get("id")} + expansions = src.expansions + else: + given = body.get("fragments") + if not isinstance(given, dict) or not given: + raise HTTPException(422, "give doc (with optional objects) or fragments, a map of fragment id to fragment") + targets = {k: _fragment({"fragment": {"id": k, **f}}) for k, f in given.items() if isinstance(f, dict)} + expansions = _expansions(body) + return await run(search.substructure, targets, pattern, smarts, expansions, _limit(body, "max_hits", search.MAX_HITS, 100_000), body.get("chirality") is True) + + +@router.post("/api/analysis/molfile") +async def molfile(body: dict) -> dict: + src = source(body, single=True) + text, notes = await run(v3000.write, src.one, src.expansions, src.members) + return {"to": "molfile3000", "text": text, "warnings": notes, "engine": ENGINE} + + +@router.post("/api/analysis/molfile/import") +async def molfile_import(body: dict) -> dict: + frags, notes = await run(v3000.read, _text(body), _bond_length(body), _origin(body)) + return {"format": "molfile3000", "fragments": frags, "warnings": notes} + + +@router.post("/api/analysis/markush") +async def enumerate_markush(body: dict) -> dict: + src = source(body, single=True) + limit = _limit(body, "limit", markush.LIMIT, markush.HARD_LIMIT) + 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)) 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/routers/mcp.py b/backend/app/routers/mcp.py index 82bdee12..8fe1f043 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 @@ -21,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. @@ -50,6 +57,14 @@ - 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. +- properties {{doc?, object?}}: drug-like properties per fragment (cLogP, TPSA, donors, acceptors, rotatable bonds, rings, Lipinski, Veber), each with the RDKit method behind it. Read only. +- check_structure {{doc?, object?, query?}}: the structure check: issues with a code, a severity and the atom and bond ids. Read only. +- stereo {{doc?, object?}}: stereocentres, double bonds and axes with CIP labels, defined or not, and their enhanced stereo groups. Read only. +- substructure {{doc?, smarts | query_object, objects?, chirality?, max_hits?}}: substructure hits across the drawing's fragments by atom and bond id. 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. @@ -83,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), @@ -99,9 +115,38 @@ 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), + _tool("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.", + {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "object": {"type": "string", "description": "One fragment id; absent: every fragment"}}, + read=True), + _tool("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.", + {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "object": {"type": "string", "description": "One fragment id; absent: every fragment"}, + "query": {"type": "boolean", "description": "True when the drawing is a search query, so query features are not reported"}}, read=True), + _tool("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.", + {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "object": {"type": "string", "description": "One fragment id; absent: every fragment"}}, + read=True), + _tool("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.", + {"doc": {"type": "string", "description": "Document id from get_context (optional when one drawing is open)"}, "smarts": {"type": "string", "description": "SMARTS pattern, such as C(=O)[OH]"}, + "query_object": {"type": "string", "description": "A fragment of the drawing to use as the query instead of smarts"}, + "objects": {"type": "array", "items": {"type": "string"}, "description": "Fragment ids to search; absent: all"}, + "chirality": {"type": "boolean"}, "max_hits": {"type": "integer", "description": "Most hits to return (default 1000)"}}, 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: @@ -221,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)") @@ -339,6 +385,213 @@ 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}) + + +def _analysis_source(args: dict, single: bool = False, keep: tuple = ()): + from fastapi import HTTPException + from app.routers import analysis + doc = str(args.get("doc") or "").strip() + if not doc: + docs = _documents() + if len(docs) != 1: + raise ToolError("Give doc, a document id from get_context." if docs else "No drawing is open. Open one in the FormChem window, then retry.") + doc = docs[0]["id"] + body = {"doc": doc, **{k: args[k] for k in ("object", *keep) if args.get(k) is not None}} + try: + return analysis.source(body, single), body + except HTTPException as exc: + raise ToolError(str(exc.detail)) from None + + +async def _per_fragment(args: dict, fn) -> dict: + from app.routers import analysis + src, _ = _analysis_source(args) + if not src.fragments: + raise ToolError("This drawing has no structures yet.") + return await asyncio.to_thread(analysis._each, src, lambda f: fn(f, src)) + + +async def t_properties(a: Agent, args: dict) -> dict: + from app.services.chem import props + out = await _per_fragment(args, lambda f, src: props.compute(f, src.expansions)) + lines = [] + for fid, r in out["fragments"].items(): + if "error" in r: + lines.append(f"{fid}: {r['error']}") + continue + v = r["values"] + lines.append(f"{fid}: {v['formula']} · MW {v['mw']} · exact {v['exact_mass']} · cLogP {v['clogp']} (Crippen.MolLogP) · MR {v['mr']} · TPSA {v['tpsa']} · HBD {v['hbd']} · HBA {v['hba']} · " + f"rotatable {v['rotatable_bonds']} · rings {v['rings']} ({v['aromatic_rings']} aromatic) · Fsp3 {v['fraction_csp3']} · Lipinski {'pass' if r['lipinski']['pass'] else 'fail'} " + f"({r['lipinski']['violations']} violation{'' if r['lipinski']['violations'] == 1 else 's'}) · Veber {'pass' if r['veber']['pass'] else 'fail'}") + return _ok("\n".join(lines), out) + + +async def t_check_structure(a: Agent, args: dict) -> dict: + from app.services.chem import check + is_query = args.get("query") is True + out = await _per_fragment(args, lambda f, src: check.check(f, src.expansions, src.members, is_query)) + lines = [] + for fid, r in out["fragments"].items(): + if "error" in r: + lines.append(f"{fid}: {r['error']}") + continue + c = r["counts"] + lines.append(f"{fid}: {c['error']} error(s), {c['warning']} warning(s), {c['info']} note(s)") + lines.extend(f" {i['severity']} {i['code']}: {_clip(i['text'], 160)}" + (f" atoms {', '.join(i['atoms'][:8])}" if i.get("atoms") else "") + + (f" bonds {', '.join(i['bonds'][:8])}" if i.get("bonds") else "") for i in r["issues"]) + return _ok("\n".join(lines), out) + + +async def t_stereo(a: Agent, args: dict) -> dict: + from app.services.chem import stereo + out = await _per_fragment(args, lambda f, src: stereo.report(f, src.expansions)) + lines = [] + for fid, r in out["fragments"].items(): + if "error" in r: + lines.append(f"{fid}: {r['error']}") + continue + parts = [f"{c['atom']} {c['label'] or '?'} ({c['state']}{', ' + c['group'] if c.get('group') else ''})" for c in r["centres"]] + parts += [f"{b['bond']} {b['label'] or '?'} ({b['state']})" for b in r["double_bonds"] + r["axes"]] + lines.append(f"{fid}: " + ("; ".join(parts) if parts else "no stereogenic units") + f" · {r['cxsmiles']}") + return _ok("\n".join(lines), out) + + +async def t_substructure(a: Agent, args: dict) -> dict: + from app.services.chem import search + smarts = args.get("smarts") + named = args.get("query_object") + if not smarts and not named: + raise ToolError("Give smarts, or query_object (a fragment of the drawing drawn as the query).") + src, _ = _analysis_source(args, keep=("objects",)) + pattern = None + if not smarts: + pattern = src.members.get(str(named)) + if pattern is None: + raise ToolError(f"{named} is not a fragment of this drawing.") + targets = {k: f for k, f in src.fragments.items() if not pattern or k != pattern.get("id")} + limit = max(1, min(100_000, int(args.get("max_hits") or search.MAX_HITS))) + try: + out = await asyncio.to_thread(search.substructure, targets, pattern, str(smarts) if smarts else None, src.expansions, limit, args.get("chirality") is True) + except ValueError as exc: + raise ToolError(str(exc)) from None + lines = [f"{out['count']} hit{'' if out['count'] == 1 else 's'}" + (" (more were cut off)" if out["truncated"] else "") + f" for {out['smarts']}"] + lines.extend(f"- {h['object']}: atoms {', '.join(h['atoms'][:12])}" for h in out["hits"][:50]) + return _ok("\n".join(lines), out) + + async def _send_handoffs(client: Client, msg: dict) -> None: await client.send({"t": "handoffs", "items": _handoff_list()}) diff --git a/backend/app/routers/reactions.py b/backend/app/routers/reactions.py new file mode 100644 index 00000000..29527015 --- /dev/null +++ b/backend/app/routers/reactions.py @@ -0,0 +1,263 @@ +import asyncio +import copy +import math +from pathlib import Path + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +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 + +router = APIRouter() +MAX_TEXT = 20 * 1024 * 1024 + + +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)} + + +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} + + +@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(): + 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"]} + + +@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} 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 diff --git a/backend/app/services/chem/abbrev.py b/backend/app/services/chem/abbrev.py index 1cb6e5c0..0d4de1d5 100644 --- a/backend/app/services/chem/abbrev.py +++ b/backend/app/services/chem/abbrev.py @@ -1,5 +1,7 @@ +import json import re from functools import lru_cache +from pathlib import Path from rdkit import Chem @@ -81,8 +83,51 @@ "SO2Cl": ("*S(=O)(=O)Cl", "ClO2S"), "SO3H": ("*S(=O)(=O)O", "HO3S"), "N3": ("*N=[N+]=[N-]", "N3"), + "Hex": ("*CCCCCC", "Hex"), + "Vin": ("*C=C", "Vin"), + "All": ("*CC=C", "All"), + "Mes": ("*c1c(C)cc(C)cc1C", "Mes"), + "Tol": ("*c1ccc(C)cc1", "Tol"), + "PMP": ("*c1ccc(OC)cc1", "PMP"), + "C6F5": ("*c1c(F)c(F)c(F)c(F)c1F", "F5C6"), + "Py": ("*c1ccccn1", "Py"), + "DMB": ("*Cc1ccc(OC)cc1OC", "DMB"), + "SEM": ("*COCC[Si](C)(C)C", "SEM"), + "MEM": ("*COCCOC", "MEM"), + "BOM": ("*COCc1ccccc1", "BOM"), + "Troc": ("*C(=O)OCC(Cl)(Cl)Cl", "Troc"), + "Alloc": ("*C(=O)OCC=C", "Alloc"), + "Teoc": ("*C(=O)OCC[Si](C)(C)C", "Teoc"), + "Ns": ("*S(=O)(=O)c1ccc([N+](=O)[O-])cc1", "Ns"), + "Bs": ("*S(=O)(=O)c1ccc(Br)cc1", "Bs"), + "Nf": ("*S(=O)(=O)C(F)(F)C(F)(F)C(F)(F)C(F)(F)F", "Nf"), + "Bpin": ("*B1OC(C)(C)C(C)(C)O1", "pinB"), + "SO2Me": ("*S(C)(=O)=O", "MeO2S"), + "SO2Ph": ("*S(=O)(=O)c1ccccc1", "PhO2S"), + "OCF3": ("*OC(F)(F)F", "F3CO"), + "SCF3": ("*SC(F)(F)F", "F3CS"), + "NHPh": ("*Nc1ccccc1", "PhHN"), + "NPh2": ("*N(c1ccccc1)c1ccccc1", "Ph2N"), + "NMeBoc": ("*N(C)C(=O)OC(C)(C)C", "BocMeN"), + "CONMe2": ("*C(=O)N(C)C", "Me2NOC"), + "CONHMe": ("*C(=O)NC", "MeHNOC"), + "CO2Bn": ("*C(=O)OCc1ccccc1", "BnO2C"), + "CO2Ph": ("*C(=O)Oc1ccccc1", "PhO2C"), + "OCOCF3": ("*OC(=O)C(F)(F)F", "F3COCO"), } +CATEGORIES: dict[str, tuple[str, ...]] = { + "alkyl": ("Me", "Et", "Pr", "nPr", "iPr", "Bu", "nBu", "iBu", "sBu", "tBu", "Np", "Cy", "Hex", "Vin", "All", "CF3", "CCl3"), + "aryl": ("Ph", "Bn", "Mes", "Tol", "PMP", "C6F5", "Py"), + "protecting group": ("Ac", "Bz", "Piv", "Tr", "PMB", "DMB", "MOM", "MEM", "SEM", "BOM", "THP", "Boc", "Cbz", "Fmoc", "Troc", "Alloc", "Teoc", + "OAc", "OBz", "OBoc", "OMOM", "OTHP", "OPMB", "OBn", "NHAc", "NHBoc", "NHCbz", "NHFmoc", "NMeBoc", "OCOCF3"), + "silyl": ("TMS", "TES", "TBS", "TBDMS", "TIPS", "TBDPS", "OTMS", "OTBS", "OTIPS", "OTBDPS"), + "sulfonyl": ("Ts", "Ms", "Tf", "Ns", "Bs", "Nf", "OTs", "OMs", "OTf", "NHTs", "SO2Cl", "SO3H", "SO2Me", "SO2Ph"), +} +PREFERRED = ("Pr", "Bu", "Ac", "TBS", "CO2H", "Ms") +USER_FILE = "abbreviations.json" +_user: dict = {"key": None, "entries": {}, "errors": []} + ELEMENT_COLLISIONS = {"Ac", "Pr", "Np"} _ELEMENT_LIKE = re.compile(r"^\d*(H\d*)?([A-Z][a-z]?)(H\d*)?(\d*[+-]+\d*)?$") @@ -95,22 +140,128 @@ def element_like(label: str, element: str) -> bool: return bool(m) and m.group(2) == element +def user_path() -> Path | None: + try: + from app.core import config + return config.data_dir() / USER_FILE + except Exception: + return None + + +def _attachment_ok(smiles: str) -> bool: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + return False + stars = [a for a in mol.GetAtoms() if a.GetAtomicNum() == 0] + return len(stars) == 1 and stars[0].GetDegree() == 1 and mol.GetNumAtoms() > 1 + + +def _read_user(path: Path) -> tuple[dict, list[str]]: + raw = json.loads(path.read_text(encoding="utf-8")) + rows = raw.get("abbreviations", raw) if isinstance(raw, dict) else raw + if isinstance(rows, dict): + rows = [{"label": k, **v} if isinstance(v, dict) else {"label": k, "smiles": v} for k, v in rows.items()] + if not isinstance(rows, list): + return {}, ["the file must hold a list of {label, smiles, reversed?, category?, prefer?} entries"] + out, errors = {}, [] + for row in rows: + label = row.get("label") if isinstance(row, dict) else None + smiles = row.get("smiles") if isinstance(row, dict) else None + if not isinstance(label, str) or not label.strip() or not isinstance(smiles, str): + errors.append(f"entry {row!r:.60} needs a label and a smiles") + continue + if not _attachment_ok(smiles): + errors.append(f"{label}: the smiles needs exactly one * as its attachment point") + continue + rev = row.get("reversed") + out[label.strip()] = {"smiles": smiles, "reversed": rev if isinstance(rev, str) and rev else label.strip(), + "category": str(row.get("category") or "user"), "prefer": row.get("prefer") == "abbreviation"} + return out, errors + + +def user_entries() -> dict: + path = user_path() + try: + key = (str(path), path.stat().st_mtime_ns) if path is not None else None + except OSError: + key = None + if key != _user["key"]: + entries, errors = {}, [] + if key is not None: + try: + entries, errors = _read_user(path) + except (OSError, ValueError) as exc: + errors = [f"{USER_FILE} cannot be read: {exc}"] + _user.update(key=key, entries=entries, errors=errors) + return _user["entries"] + + +def user_errors() -> list[str]: + user_entries() + return list(_user["errors"]) + + +def entry(label: str) -> tuple[str, str] | None: + found = user_entries().get(label) + if found: + return found["smiles"], found["reversed"] + return ABBREVIATIONS.get(label) + + +def category(label: str) -> str: + found = user_entries().get(label) + if found: + return found["category"] + return next((k for k, labels in CATEGORIES.items() if label in labels), "functional") + + +def library() -> list[dict]: + rows = {label: {"label": label, "reversed": rev, "smiles": smi, "category": category(label), "source": "builtin"} + for label, (smi, rev) in ABBREVIATIONS.items()} + for label, e in user_entries().items(): + rows[label] = {"label": label, "reversed": e["reversed"], "smiles": e["smiles"], "category": e["category"], "source": "user"} + return sorted(rows.values(), key=lambda r: (r["category"], r["label"].lower())) + + def resolve(label: str | None, element: str, neighbour_elements: list[str]) -> str | None: - if not label or label not in ABBREVIATIONS: + found = entry(label) if label else None + if not found: return None if label == element and label in ELEMENTS: - if label not in ELEMENT_COLLISIONS: + mine = user_entries().get(label) + if label not in ELEMENT_COLLISIONS and not (mine and mine["prefer"]): return None - if label == "Np" and neighbour_elements != ["C"]: + if label == "Np" and not mine and neighbour_elements != ["C"]: return None elif element != "*" and element_like(label, element): return None - return ABBREVIATIONS[label][0] + return found[0] def reversed_label(label: str) -> str: - entry = ABBREVIATIONS.get(label) - return entry[1] if entry else label + found = entry(label) + return found[1] if found else label + + +def canonical(smiles: str) -> str | None: + mol = Chem.MolFromSmiles(smiles) + return Chem.MolToSmiles(mol) if mol is not None else None + + +def match(smiles: str) -> str | None: + key = canonical(smiles) + if key is None: + return None + for label, e in user_entries().items(): + if canonical(e["smiles"]) == key: + return label + hits = [label for label, (smi, _) in ABBREVIATIONS.items() if _canonical_builtin(smi) == key] + return next((h for h in hits if h in PREFERRED), hits[0] if hits else None) + + +@lru_cache(maxsize=512) +def _canonical_builtin(smiles: str) -> str | None: + return canonical(smiles) @lru_cache(maxsize=256) diff --git a/backend/app/services/chem/balance.py b/backend/app/services/chem/balance.py new file mode 100644 index 00000000..019a17b8 --- /dev/null +++ b/backend/app/services/chem/balance.py @@ -0,0 +1,242 @@ +import itertools +import math +from fractions import Fraction + +from rdkit import Chem + +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() +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 _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} + 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] diff --git a/backend/app/services/chem/check.py b/backend/app/services/chem/check.py new file mode 100644 index 00000000..0262ea5f --- /dev/null +++ b/backend/app/services/chem/check.py @@ -0,0 +1,140 @@ +from rdkit import Chem + +from app.services.chem import ENGINE, abbrev, convert, markush, perceive, query, warning + +PT = Chem.GetPeriodicTable() +ERROR, WARN, INFO = "error", "warning", "info" +SEVERITY = { + "valence": ERROR, "bad_bond": ERROR, "engine_error": ERROR, "bad_expansion": ERROR, + "hypervalent": WARN, "unknown_label": WARN, "misplaced_wedge": WARN, "ambiguous_wedge": WARN, "conflicting_wedges": WARN, + "unknown_isotope": WARN, "abbreviation_bonds": WARN, "abbreviation_valence": WARN, "overlapping_atoms": WARN, "short_bond": WARN, + "long_bond": WARN, "aromatic_outside_ring": WARN, "cannot_kekulise": WARN, "bad_stereo_group": WARN, "stereo_group_overlap": WARN, + "stereo_group_not_centre": WARN, "undefined_double_bond": WARN, "unusual_charge": WARN, "wedge_between_centres": WARN, + "ring_double_bond_stereo": WARN, "stereo_ignored": WARN, "unsupported_bond": WARN, "rgroup_undefined": WARN, "rgroup_member_missing": WARN, + "rgroup_bonds": WARN, "cip_failed": WARN, + "undefined_stereocentre": INFO, "stereo_unknown": INFO, "unknown_ez": INFO, "charge_imbalance": INFO, "query_feature": INFO, + "uncommon_isotope": INFO, "crossing_bonds": INFO, "label_collides": INFO, "rgroup_unused": INFO, "rgroup_attachment_guessed": INFO, +} +FIX = {"misplaced_wedge": "wedges", "ambiguous_wedge": "wedges", "conflicting_wedges": "wedges", "wedge_between_centres": "wedges", + "undefined_stereocentre": "wedges", "abbreviation_valence": "expand", "abbreviation_bonds": "expand"} +SKIP = {"query_ignored", "inchi_warning", "inchi_unavailable", "inchi_failed"} +COMMON_LABELS = {(1, 2), (1, 3), (6, 11), (6, 13), (6, 14), (7, 15), (8, 17), (8, 18), (9, 18), (15, 32), (15, 33), (16, 35), (53, 123), (53, 125), (53, 131)} +CROSSING_LIMIT = 1500 + + +def _issue(w: dict) -> dict: + out = {"code": w["code"], "severity": SEVERITY.get(w["code"], WARN), "text": w.get("text", "")} + for key in ("atoms", "bonds"): + if w.get(key): + out[key] = list(w[key]) + if w["code"] in FIX: + out["fix"] = FIX[w["code"]] + return out + + +def _charges(frag: dict, conv: convert.Conversion) -> list[dict]: + odd = [] + for a in conv.mol.GetAtoms(): + if not conv.drawn[a.GetIdx()]: + continue + q, z = a.GetFormalCharge(), a.GetAtomicNum() + if not q or z == 0: + continue + group = PT.GetNOuterElecs(z) + metal = z not in query.NONMETALS + if abs(q) >= 3 and not metal or z == 6 and abs(q) >= 2 or z in (2, 10, 18, 36, 54, 86) or z == 9 and q > 0 or metal and q < 0 and group <= 2: + odd.append(conv.owner[a.GetIdx()]) + return [warning("unusual_charge", "Unusual formal charge for this element.", odd)] if odd else [] + + +def _stereo(frag: dict, conv: convert.Conversion) -> list[dict]: + out = [] + mol = conv.mol + centres = {i for i in range(mol.GetNumAtoms()) if mol.GetAtomWithIdx(i).GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED} + both = [] + for bi in conv.wedged: + b = mol.GetBondWithIdx(bi) + if b.GetBeginAtomIdx() in centres and b.GetEndAtomIdx() in centres and conv.bond_id(bi): + both.append(conv.bond_id(bi)) + if both: + out.append(warning("wedge_between_centres", "This wedge joins two stereocentres; it is read at its narrow end only.", bonds=both)) + ring = [] + ri = mol.GetRingInfo() + for bi in conv.either: + if any(len(r) < 8 and bi in r for r in ri.BondRings()) and conv.bond_id(bi): + ring.append(conv.bond_id(bi)) + if ring: + out.append(warning("ring_double_bond_stereo", "A double bond in a ring smaller than eight atoms cannot carry E/Z; the crossed mark means nothing here.", bonds=ring)) + return out + + +def _isotopes(conv: convert.Conversion) -> list[dict]: + rare = [] + for a in conv.mol.GetAtoms(): + z, iso = a.GetAtomicNum(), a.GetIsotope() + if not iso or not z or not conv.drawn[a.GetIdx()] or (z, iso) in COMMON_LABELS: + continue + if PT.GetMassForIsotope(z, iso) > 0 and PT.GetAbundanceForIsotope(z, iso) <= 0: + rare.append(conv.owner[a.GetIdx()]) + return [warning("uncommon_isotope", "A known nuclide that does not occur naturally; check the mass number.", rare)] if rare else [] + + +def _segments_cross(p, q, r, s) -> bool: + def orient(a, b, c): + v = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + return 0 if abs(v) < 1e-9 else (1 if v > 0 else -1) + return orient(p, q, r) * orient(p, q, s) < 0 and orient(r, s, p) * orient(r, s, q) < 0 + + +def _crossings(frag: dict) -> list[dict]: + atoms = frag.get("atoms") or {} + bonds = [b for b in (frag.get("bonds") or {}).values() if b["a"] in atoms and b["b"] in atoms] + if len(bonds) > CROSSING_LIMIT: + return [] + pts = {k: (a["x"], a["y"]) for k, a in atoms.items()} + hit: set[str] = set() + for i, b in enumerate(bonds): + for c in bonds[i + 1:]: + if {b["a"], b["b"]} & {c["a"], c["b"]}: + continue + if _segments_cross(pts[b["a"]], pts[b["b"]], pts[c["a"]], pts[c["b"]]): + hit.update((b["id"], c["id"])) + return [warning("crossing_bonds", "Bonds cross each other.", bonds=hit)] if hit else [] + + +def _queries(frag: dict) -> list[dict]: + atoms = [k for k, a in (frag.get("atoms") or {}).items() if query.is_query_atom(a)] + bonds = [k for k, b in (frag.get("bonds") or {}).items() if query.is_query_bond(b)] + if not atoms and not bonds: + return [] + return [warning("query_feature", "Query features in a drawing that is not a query: chemistry ignores them.", atoms, bonds)] + + +def _labels(frag: dict) -> list[dict]: + hits = [k for k, a in (frag.get("atoms") or {}).items() if a.get("label") in abbrev.ELEMENT_COLLISIONS and a.get("element") == a.get("label")] + return [warning("label_collides", "This label is also an element symbol; it is read as the abbreviation (acetyl, propyl, neopentyl).", hits)] if hits else [] + + +def check(frag: dict, expansions: dict | None = None, members: dict[str, dict] | None = None, is_query: bool = False) -> dict: + if not frag.get("atoms"): + return {"issues": [], "counts": {ERROR: 0, WARN: 0, INFO: 0}, "engine": ENGINE} + conv = perceive.prepare(frag, expansions) + p = perceive.perceive(frag, expansions, conv) + found: list[dict] = [] + for v in p.valence_errors: + found.append({"code": "valence", "text": f"Valence {v['valence']} is more than allowed ({', '.join(str(x) for x in v['allowed'])}).", "atoms": [v["atom"]]}) + found.extend(w for w in p.warnings if w.get("code") not in SKIP) + ignored = {k for k, a in frag["atoms"].items() if a.get("ignore_warnings")} + extra = _charges(frag, conv) + _stereo(frag, conv) + _isotopes(conv) + _crossings(frag) + _labels(frag) + if not is_query: + extra += _queries(frag) + if frag.get("rgroups") or any(a.get("element") == "R#" for a in frag["atoms"].values()): + extra += markush.describe(frag, members or {})["warnings"] + found.extend(w for w in extra if not w.get("atoms") or not set(w["atoms"]) <= ignored) + issues = [_issue(w) for w in found] + rank = {ERROR: 0, WARN: 1, INFO: 2} + issues.sort(key=lambda i: rank[i["severity"]]) + counts = {ERROR: 0, WARN: 0, INFO: 0} + for i in issues: + counts[i["severity"]] += 1 + return {"issues": issues, "counts": counts, "engine": ENGINE} diff --git a/backend/app/services/chem/convert.py b/backend/app/services/chem/convert.py index ccae2f36..4c53a081 100644 --- a/backend/app/services/chem/convert.py +++ b/backend/app/services/chem/convert.py @@ -40,6 +40,8 @@ class Conversion: wedged: list[int] = field(default_factory=list) wavy: list[int] = field(default_factory=list) either: list[int] = field(default_factory=list) + groups: list[tuple[str, int, list[int]]] = field(default_factory=list) + chiral: str | None = None def atom_id(self, idx: int) -> str: return self.owner[idx] @@ -66,6 +68,13 @@ def _order_key(order: Any) -> Any: return order +def _query_label(a: dict) -> str: + q = a.get("query") if isinstance(a.get("query"), dict) else {} + if q.get("list"): + return ("not" if q.get("not") else "") + "[" + ",".join(str(s) for s in q["list"]) + "]" + return str(q.get("generic") or "") + + def _new_atom(a: dict, conv: Conversion) -> Chem.Atom: aid = a["id"] el = a.get("element", "C") @@ -79,11 +88,12 @@ def _new_atom(a: dict, conv: Conversion) -> Chem.Atom: conv.generic.append(aid) elif el == "*" or el not in ELEMENTS: atom = Chem.Atom(0) - label = a.get("label") or a.get("generic") or "" + asked = _query_label(a) + label = a.get("label") or a.get("generic") or asked if label: atom.SetProp("dummyLabel", label) atom.SetProp("atomLabel", label) - if a.get("generic") 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) @@ -211,6 +221,7 @@ def to_mol(frag: dict, expansions: dict | None = None, expand: bool = True, dept conv.warnings.append(warning("query_ignored", "Bond query features are not used for chemistry yet.", bonds=[bid])) _set_bond_stereo(conv, rb, bid, b.get("stereo") or "none") conv.bond_ids.append(bid) + _read_groups(conv, frag) conf = Chem.Conformer(conv.mol.GetNumAtoms()) for i, (x, y) in enumerate(conv.pos): @@ -221,6 +232,62 @@ def to_mol(frag: dict, expansions: dict | None = None, expand: bool = True, dept WEDGE_DIRS = {"wedge": Chem.BondDir.BEGINWEDGE, "hollow": Chem.BondDir.BEGINWEDGE, "hash": Chem.BondDir.BEGINDASH} +SG = Chem.StereoGroupType +GROUP_TYPES = {"abs": SG.STEREO_ABSOLUTE, "and": SG.STEREO_AND, "or": SG.STEREO_OR} +GROUP_KINDS = {v: k for k, v in GROUP_TYPES.items()} +CHIRAL_FLAGS = ("absolute", "relative", "racemic") + + +def _read_groups(conv: Conversion, frag: dict) -> None: + flag = frag.get("chiral") + conv.chiral = flag if flag in CHIRAL_FLAGS else None + seen: set[int] = set() + for i, g in enumerate(frag.get("stereo_groups") or []): + kind = g.get("kind") if isinstance(g, dict) else None + if kind not in GROUP_TYPES: + conv.warnings.append(warning("bad_stereo_group", f"Stereo group {i + 1} has no kind abs, and or or; it is ignored.")) + continue + n = g.get("n") if isinstance(g.get("n"), int) and not isinstance(g.get("n"), bool) and g.get("n") > 0 else 0 + idx = [] + for aid in g.get("atoms") or []: + j = conv.index.get(aid) if isinstance(aid, str) else None + if j is None or not conv.drawn[j]: + continue + if j in seen: + conv.warnings.append(warning("stereo_group_overlap", "This atom is in more than one stereo group; the first group wins.", [aid])) + continue + seen.add(j) + idx.append(j) + if idx: + conv.groups.append((kind, n, idx)) + + +def apply_groups(conv: Conversion) -> None: + mol = conv.mol + centres = {a.GetIdx() for a in mol.GetAtoms() if a.GetChiralTag() in (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW)} + if conv.chiral == "absolute": + mol.SetIntProp("_MolFileChiralFlag", 1) + if not conv.groups and conv.chiral not in ("relative", "racemic"): + return + used = {k: {n for kind, n, _ in conv.groups if kind == k and n} for k in ("and", "or")} + out, grouped = [], set() + for kind, n, idx in conv.groups: + atoms = [i for i in idx if i in centres] + stray = [conv.owner[i] for i in idx if i not in centres] + if stray: + conv.warnings.append(warning("stereo_group_not_centre", "Atoms in a stereo group that are not defined stereocentres are left out of it.", stray)) + if not atoms: + continue + if kind != "abs" and not n: + n = max(used[kind], default=0) + 1 + used[kind].add(n) + grouped.update(atoms) + out.append(Chem.CreateStereoGroup(GROUP_TYPES[kind], mol, atoms, readId=n)) + rest = sorted(centres - grouped) + if rest and conv.chiral in ("relative", "racemic"): + kind = "or" if conv.chiral == "relative" else "and" + out.append(Chem.CreateStereoGroup(GROUP_TYPES[kind], mol, rest, readId=max(used[kind], default=0) + 1)) + mol.SetStereoGroups(out) def _set_bond_stereo(conv: Conversion, rb: Chem.Bond, bid: str, stereo: str) -> None: @@ -333,6 +400,10 @@ def assign_stereo(conv: Conversion) -> None: if centre.GetChiralTag() == Chem.ChiralType.CHI_UNSPECIFIED and conv.bond_ids[bi]: conv.warnings.append(warning("misplaced_wedge", "The narrow end of this wedge is not at a stereocentre.", [conv.owner[centre.GetIdx()]], [conv.bond_ids[bi]])) + try: + apply_groups(conv) + except Exception as exc: + conv.problems.append({"code": "stereo_groups_failed", "text": str(exc)}) def _wedges_from_mol(mol: Chem.Mol) -> dict[int, tuple[str, int]]: @@ -469,10 +540,32 @@ def fresh(prefix: str) -> str: if stereo: rec["stereo"] = stereo[0] frag["bonds"][bid] = rec + groups = groups_from_mol(mol, ids) + if groups: + frag["stereo_groups"] = groups + if mol.HasProp("_MolFileChiralFlag") and mol.GetIntProp("_MolFileChiralFlag") == 1: + frag["chiral"] = "absolute" _pin_hydrogens(mol, frag, ids) return frag +def groups_from_mol(mol: Chem.Mol, ids: list[str]) -> list[dict]: + out: list[dict] = [] + counters = {"and": 0, "or": 0} + for g in mol.GetStereoGroups(): + kind = GROUP_KINDS.get(g.GetGroupType()) + atoms = [ids[a.GetIdx()] for a in g.GetAtoms() if a.GetIdx() < len(ids)] + if kind is None or not atoms: + continue + rec: dict = {"kind": kind} + if kind != "abs": + counters[kind] += 1 + rec["n"] = g.GetReadId() or g.GetWriteId() or counters[kind] + rec["atoms"] = atoms + out.append(rec) + return out + + def _pin_hydrogens(mol: Chem.Mol, frag: dict, ids: list[str]) -> None: probe = to_mol(frag, expand=False) try: diff --git a/backend/app/services/chem/derive.py b/backend/app/services/chem/derive.py index a245301d..c292eb35 100644 --- a/backend/app/services/chem/derive.py +++ b/backend/app/services/chem/derive.py @@ -7,8 +7,11 @@ 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") +FRAGMENT_FIELDS = ("chiral", "stereo_groups") _cache: "OrderedDict[str, dict]" = OrderedDict() _lock = threading.Lock() @@ -24,6 +27,7 @@ def content_key(frag: dict, expansions: dict | None = None) -> str: [[k, *(atoms[k].get(f) for f in ATOM_FIELDS), round(atoms[k].get("x", 0.0) - x0, 3), round(atoms[k].get("y", 0.0) - y0, 3)] for k in sorted(atoms)], [[k, *(bonds[k].get(f) for f in BOND_FIELDS)] for k in sorted(bonds)], [(expansions or {}).get(e) for e in used], + [frag.get(f) for f in FRAGMENT_FIELDS], ] return hashlib.sha1(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest() @@ -85,16 +89,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/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) diff --git a/backend/app/services/chem/hydrogens.py b/backend/app/services/chem/hydrogens.py new file mode 100644 index 00000000..82ecc55a --- /dev/null +++ b/backend/app/services/chem/hydrogens.py @@ -0,0 +1,153 @@ +import math + +from app.services.chem import abbrev, convert, derive, perceive, warning +from app.services.model import new_id +from app.services.ops import atom_path, bond_path + +Point = tuple[float, float] +H_LENGTH = 0.8 + + +def _angle(p: dict, q: dict) -> float: + return math.atan2(q["y"] - p["y"], q["x"] - p["x"]) % (2 * math.pi) + + +def directions(taken: list[float], n: int) -> list[float]: + if n <= 0: + return [] + if not taken: + return [2 * math.pi * i / n for i in range(n)] + ordered = sorted(taken) + gaps = [(ordered[i], ((ordered[(i + 1) % len(ordered)] - ordered[i]) % (2 * math.pi)) or 2 * math.pi) for i in range(len(ordered))] + share = [0] * len(gaps) + for _ in range(n): + best = max(range(len(gaps)), key=lambda i: gaps[i][1] / (share[i] + 2)) + share[best] += 1 + out = [] + for (start, width), k in zip(gaps, share): + out.extend((start + width * (i + 1) / (k + 1)) % (2 * math.pi) for i in range(k)) + return out + + +def _cip(frag: dict, expansions: dict | None) -> dict[str, str]: + return {k: v for k, v in derive.compute_fragment(frag, expansions).get("cip", {}).items() if k in frag["atoms"]} + + +def _used(frag: dict, extra: set[str] | None) -> set[str]: + return set(extra or ()) | set(frag.get("atoms") or {}) | set(frag.get("bonds") or {}) + + +def _fresh(prefix: str, used: set[str]) -> str: + while True: + i = new_id(prefix) + if i not in used: + used.add(i) + return i + + +def add_hydrogens(frag: dict, expansions: dict | None = None, atoms: list[str] | None = None, used: set[str] | None = None) -> dict: + fid = frag["id"] + frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {} + conv = perceive.prepare(frag, expansions) + length = convert.median_bond_length(frag) * H_LENGTH + scope = set(frag_atoms) if atoms is None else {a for a in atoms if a in frag_atoms} + taken = _used(frag, used) + trial = {**frag, "atoms": dict(frag_atoms), "bonds": dict(frag_bonds)} + new_atoms: dict[str, dict] = {} + new_bonds: dict[str, dict] = {} + cleared: dict[str, list[str]] = {} + added: dict[str, list[str]] = {} + for aid in sorted(scope): + a = frag_atoms[aid] + i = conv.index.get(aid) + if i is None or not conv.drawn[i] or a.get("element") in ("H", "*", "R#") or aid in conv.expanded: + continue + n = conv.mol.GetAtomWithIdx(i).GetTotalNumHs() + if n <= 0: + continue + angles = [_angle(a, frag_atoms[b["b"] if b["a"] == aid else b["a"]]) for b in frag_bonds.values() if aid in (b["a"], b["b"])] + added[aid] = [] + for t in directions(angles, n): + hid, bid = _fresh("a", taken), _fresh("b", taken) + new_atoms[hid] = {"id": hid, "element": "H", "x": round(a["x"] + length * math.cos(t), 3), "y": round(a["y"] + length * math.sin(t), 3)} + new_bonds[bid] = {"id": bid, "a": aid, "b": hid, "order": 1} + added[aid].append(hid) + fields = [f for f in ("hydrogens",) if f in a] + if a.get("label") and abbrev.element_like(a["label"], a.get("element", "C")): + fields.append("label") + if fields: + cleared[aid] = fields + if not added: + raise ValueError("no chosen atom has implicit hydrogens to draw") + trial["atoms"].update({k: {kk: vv for kk, vv in v.items() if kk not in cleared.get(k, ())} for k, v in frag_atoms.items() if k in cleared}) + trial["atoms"].update(new_atoms) + trial["bonds"].update(new_bonds) + notes: list[dict] = [] + before = _cip(frag, expansions) + for centre, label in before.items(): + if centre not in added or _cip(trial, expansions).get(centre) == label: + continue + bid = next(k for k, b in new_bonds.items() if b["a"] == centre) + for mark in ("hash", "wedge"): + new_bonds[bid] = {**new_bonds[bid], "stereo": mark} + trial["bonds"][bid] = new_bonds[bid] + if _cip(trial, expansions).get(centre) == label: + break + else: + new_bonds[bid] = {k: v for k, v in new_bonds[bid].items() if k != "stereo"} + trial["bonds"][bid] = new_bonds[bid] + notes.append(warning("stereo_changed", "Drawing the hydrogens changed how this centre reads; check its wedges.", [centre])) + ops = [{"op": "set", "path": atom_path(fid, k), "value": v} for k, v in new_atoms.items()] + ops += [{"op": "set", "path": bond_path(fid, k), "value": v} for k, v in new_bonds.items()] + ops += [{"op": "set", "path": atom_path(fid, aid, f)} for aid, fs in sorted(cleared.items()) for f in fs] + return {"tx": {"label": "Add explicit hydrogens", "ops": ops}, "added": added, "warnings": notes} + + +def _removable(h: dict, link: dict) -> bool: + if any(h.get(f) for f in ("isotope", "charge", "map", "query", "label")) or (h.get("radical") or "none") != "none": + return False + if link.get("order", 1) != 1 or (link.get("stereo") or "none") != "none": + return False + return True + + +def remove_hydrogens(frag: dict, expansions: dict | None = None, atoms: list[str] | None = None) -> dict: + fid = frag["id"] + frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {} + scope = set(frag_atoms) if atoms is None else {a for a in atoms if a in frag_atoms} + gone: dict[str, tuple[str, str]] = {} + kept: list[str] = [] + for hid, h in sorted(frag_atoms.items()): + if h.get("element") != "H": + continue + links = [b for b in frag_bonds.values() if hid in (b["a"], b["b"])] + heavy = [frag_atoms[b["b"] if b["a"] == hid else b["a"]] for b in links] + if hid not in scope and not any(x["id"] in scope for x in heavy): + continue + if len(links) != 1 or heavy[0].get("element") == "H" or not _removable(h, links[0]): + kept.append(hid) + continue + gone[hid] = (links[0]["id"], heavy[0]["id"]) + before = _cip(frag, expansions) + for _ in range(3): + trial = {**frag, "atoms": {k: v for k, v in frag_atoms.items() if k not in gone}, + "bonds": {k: b for k, b in frag_bonds.items() if k not in {g[0] for g in gone.values()}}} + after = _cip(trial, expansions) + changed = {c for c, v in before.items() if c in trial["atoms"] and after.get(c) != v} + back = [hid for hid, (_, heavy) in gone.items() if heavy in changed] + if not back: + break + for hid in back: + gone.pop(hid) + kept.append(hid) + if not gone: + raise ValueError("no explicit hydrogen here can be removed without losing information") + ops = [{"op": "set", "path": bond_path(fid, bid)} for bid, _ in gone.values()] + ops += [{"op": "set", "path": atom_path(fid, hid)} for hid in sorted(gone)] + pinned: dict[str, int] = {} + for _, heavy in gone.values(): + if isinstance(frag_atoms[heavy].get("hydrogens"), int): + pinned[heavy] = pinned.get(heavy, frag_atoms[heavy]["hydrogens"]) + 1 + ops += [{"op": "set", "path": atom_path(fid, aid, "hydrogens"), "value": min(12, n)} for aid, n in sorted(pinned.items())] + notes = [warning("hydrogens_kept", "These hydrogens carry an isotope, charge, map number, stereo or bridge two atoms, or hold a stereocentre's configuration, so they stay.", kept)] if kept else [] + return {"tx": {"label": "Remove explicit hydrogens", "ops": ops}, "removed": sorted(gone), "kept": sorted(kept), "warnings": notes} 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 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} diff --git a/backend/app/services/chem/markush.py b/backend/app/services/chem/markush.py new file mode 100644 index 00000000..590221e6 --- /dev/null +++ b/backend/app/services/chem/markush.py @@ -0,0 +1,217 @@ +import itertools +import math +import re + +from rdkit import Chem + +from app.services.chem import ids, perceive, warning + +LIMIT = 1000 +HARD_LIMIT = 100_000 + + +def occurrence_counts(text: str | None, sites: int) -> list[int]: + spec = (text or ">0").replace(" ", "") + allowed: set[int] = set() + for part in spec.split(","): + if not part: + continue + m = re.fullmatch(r"(\d+)-(\d+)", part) + if m: + allowed.update(range(int(m.group(1)), int(m.group(2)) + 1)) + continue + m = re.fullmatch(r"([<>])(\d+)", part) + if m: + n = int(m.group(2)) + allowed.update(range(n + 1, sites + 1) if m.group(1) == ">" else range(0, n)) + continue + if part.isdigit(): + allowed.add(int(part)) + continue + raise ValueError(f"occurrence {text} is not understood (use forms like 1, >0, 1-3 or 1,3)") + return sorted(c for c in allowed if 0 <= c <= sites) + + +def _stub_link(a: dict, bonds: dict) -> str | None: + if a.get("element") != "*" or a.get("label") not in (None, "", "*") or a.get("generic"): + return None + links = [b for b in bonds.values() if a["id"] in (b["a"], b["b"])] + return (links[0]["b"] if links[0]["a"] == a["id"] else links[0]["a"]) if len(links) == 1 else None + + +def member_attachments(member: dict, declared: list | None = None) -> tuple[list[str], set[str]]: + atoms = member.get("atoms") or {} + bonds = member.get("bonds") or {} + chosen = [a for a in declared if isinstance(a, str) and a in atoms] if isinstance(declared, list) else [] + if chosen: + attach, stubs = [], set() + for aid in chosen: + nb = _stub_link(atoms[aid], bonds) + attach.append(nb or aid) + if nb: + stubs.add(aid) + return attach, stubs + marked = sorted((a for a in atoms.values() if isinstance(a.get("data"), dict) and a["data"].get("attach") in (1, 2)), + key=lambda a: a["data"]["attach"]) + if marked: + return [a["id"] for a in marked], set() + stubs = [] + for a in sorted(atoms.values(), key=lambda a: a["id"]): + nb = _stub_link(a, bonds) + if nb: + stubs.append((a["id"], nb)) + if stubs: + return [n for _, n in stubs], {s for s, _ in stubs} + first = min(atoms) if atoms else None + return ([first] if first else []), set() + + +def describe(frag: dict, members: dict[str, dict]) -> dict: + atoms = frag.get("atoms") or {} + bonds = frag.get("bonds") or {} + notes: list[dict] = [] + sites: dict[int, list[str]] = {} + for aid in sorted(atoms): + a = atoms[aid] + if a.get("element") == "R#" and isinstance(a.get("rgroup"), int): + sites.setdefault(a["rgroup"], []).append(aid) + degree = sum(1 for b in bonds.values() if aid in (b["a"], b["b"])) + if degree != 1: + notes.append(warning("rgroup_bonds", f"R{a['rgroup']} has {degree} bonds; only single-bonded R-group atoms are enumerated.", [aid])) + defs = frag.get("rgroups") or {} + groups = [] + for key in sorted(set(defs) | {str(n) for n in sites}, key=lambda k: int(k) if k.isdigit() else 999): + d = defs.get(key) if isinstance(defs.get(key), dict) else {} + n = int(key) if key.isdigit() else 0 + rows = [] + for mid in d.get("members") or []: + member = members.get(mid) + if not member or not member.get("atoms"): + notes.append(warning("rgroup_member_missing", f"R{key} names {mid}, which is not a fragment of this document.")) + continue + declared = (d.get("attach") or {}).get(mid) if isinstance(d.get("attach"), dict) else None + attach, stubs = member_attachments(member, declared) + if not declared and not any(isinstance(a.get("data"), dict) and a["data"].get("attach") for a in member["atoms"].values()) and not stubs: + notes.append(warning("rgroup_attachment_guessed", f"Member {mid} of R{key} marks no attachment point; its first atom is used.")) + rows.append({"object": mid, "attach": attach, "stubs": sorted(stubs)}) + if n in sites and not rows: + notes.append(warning("rgroup_undefined", f"R{key} has no members.", sites[n])) + if key in defs and n not in sites: + notes.append(warning("rgroup_unused", f"R{key} is defined but no atom of the scaffold carries it.")) + groups.append({"n": n, "sites": sites.get(n, []), "members": rows, "occurrence": d.get("occurrence") or ">0", + "rest_h": bool(d.get("rest_h")), "if_then": d.get("if_then") if isinstance(d.get("if_then"), int) else None}) + return {"groups": groups, "warnings": notes} + + +def _choices(group: dict) -> list[tuple]: + k = len(group["sites"]) + m = len(group["members"]) + counts = occurrence_counts(group["occurrence"], k) + if not group["rest_h"]: + counts = [k] if k in counts or not counts else [] + out = [] + for c in counts: + for chosen in itertools.combinations(range(k), c): + for picks in itertools.product(range(m), repeat=c): + row = [None] * k + for site, pick in zip(chosen, picks): + row[site] = pick + out.append(tuple(row)) + return out + + +def count(desc: dict) -> int: + total = 1 + for g in desc["groups"]: + if not g["sites"]: + continue + k, m = len(g["sites"]), len(g["members"]) + counts = occurrence_counts(g["occurrence"], k) + if not g["rest_h"]: + counts = [k] if k in counts or not counts else [] + total *= sum(math.comb(k, c) * m ** c for c in counts) + return total + + +def _member_mol(member: dict, row: dict, label: int, expansions: dict | None) -> Chem.Mol: + conv = perceive.prepare(member, expansions) + mol = Chem.RWMol(conv.mol) + attach = conv.index[row["attach"][0]] + for sid in row["stubs"]: + mol.GetAtomWithIdx(conv.index[sid]).SetAtomMapNum(0) + if row["stubs"]: + stub = conv.index[row["stubs"][0]] + mol.GetAtomWithIdx(stub).SetAtomMapNum(label) + for extra in sorted((conv.index[s] for s in row["stubs"][1:]), reverse=True): + mol.RemoveAtom(extra) + else: + d = Chem.Atom(0) + d.SetAtomMapNum(label) + j = mol.AddAtom(d) + mol.AddBond(attach, j, Chem.BondType.SINGLE) + for a in mol.GetAtoms(): + if a.GetAtomicNum() and a.GetAtomMapNum(): + a.SetAtomMapNum(0) + return mol.GetMol() + + +def enumerate_structures(frag: dict, members: dict[str, dict], expansions: dict | None = None, limit: int = LIMIT, force: bool = False) -> dict: + desc = describe(frag, members) + notes = list(desc["warnings"]) + groups = [g for g in desc["groups"] if g["sites"]] + if not groups: + raise ValueError("the fragment has no R-group atoms") + total = count(desc) + if total > HARD_LIMIT and not force: + raise ValueError(f"{total} structures: more than {HARD_LIMIT}; pass force to enumerate anyway") + conv = perceive.prepare(frag, expansions) + base = Chem.RWMol(conv.mol) + for a in base.GetAtoms(): + a.SetAtomMapNum(0) + site_label = {} + for g in groups: + for aid in g["sites"]: + site_label[aid] = len(site_label) + 1 + base.GetAtomWithIdx(conv.index[aid]).SetAtomMapNum(site_label[aid]) + by_n = {g["n"]: g for g in groups} + out: list[dict] = [] + seen: set[str] = set() + truncated = False + params = Chem.MolzipParams() + params.label = Chem.MolzipLabel.AtomMapNumber + for combo in itertools.product(*(_choices(g) for g in groups)): + if len(out) >= limit: + truncated = True + notes.append(warning("enumeration_truncated", f"Only the first {limit} of {total} structures are listed.")) + break + filled = {g["n"]: any(c is not None for c in row) for g, row in zip(groups, combo)} + if any(filled[g["n"]] and g["if_then"] in by_n and not filled[g["if_then"]] for g in groups): + continue + mol = Chem.RWMol(base) + parts = Chem.Mol() + choice: dict[str, list] = {} + for g, row in zip(groups, combo): + choice[str(g["n"])] = [] + for aid, pick in zip(g["sites"], row): + if pick is None: + mol.GetAtomWithIdx(conv.index[aid]).SetAtomicNum(1) + mol.GetAtomWithIdx(conv.index[aid]).SetAtomMapNum(0) + mol.GetAtomWithIdx(conv.index[aid]).SetIsotope(0) + choice[str(g["n"])].append("H") + continue + member = g["members"][pick] + parts = Chem.CombineMols(parts, _member_mol(members[member["object"]], member, site_label[aid], expansions)) + choice[str(g["n"])].append(member["object"]) + try: + joined = Chem.molzip(Chem.CombineMols(mol, parts), params) if parts.GetNumAtoms() else mol.GetMol() + joined = Chem.RemoveHs(joined, sanitize=False) + Chem.SanitizeMol(joined, catchErrors=True) + smiles = ids.smiles(ids.identifier_mol(joined)) + except Exception as exc: + notes.append(warning("enumeration_failed", f"One combination could not be built: {exc}")) + continue + if smiles in seen: + continue + seen.add(smiles) + out.append({"smiles": smiles, "formula": ids.formula(joined), "choice": choice}) + return {"count": total, "structures": out, "truncated": truncated, "warnings": notes} diff --git a/backend/app/services/chem/perceive.py b/backend/app/services/chem/perceive.py index abd1317b..b509c15c 100644 --- a/backend/app/services/chem/perceive.py +++ b/backend/app/services/chem/perceive.py @@ -106,7 +106,7 @@ def _valence(p: Perception, ignored: set[str]) -> None: violated = a.HasValenceViolation() except Exception: violated = False - if not violated and valence <= max(allowed): + if valence <= max(allowed) and not (violated and a.GetFormalCharge() == 0): continue aid = conv.owner[a.GetIdx()] if aid in ignored: @@ -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 @@ -147,13 +175,22 @@ def _cip(p: Perception) -> None: if bid and b.HasProp("_CIPCode"): p.cip[bid] = b.GetProp("_CIPCode") try: - undefined = [conv.owner[si.centeredOn] for si in Chem.FindPotentialStereo(mol) - if si.type == Chem.StereoType.Atom_Tetrahedral and si.specified == Chem.StereoSpecified.Unspecified - and conv.drawn[si.centeredOn]] + found = list(Chem.FindPotentialStereo(mol)) except Exception: - undefined = [] + found = [] + centres = [si for si in found if si.type == Chem.StereoType.Atom_Tetrahedral and conv.drawn[si.centeredOn]] + 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", [])} + 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)) + if unknown: + p.warnings.append(warning("stereo_unknown", f"{len(unknown)} stereocentre(s) marked unknown with a wavy bond.", unknown)) + if loose: + p.warnings.append(warning("undefined_double_bond", "Stereogenic double bond drawn without a clear E or Z geometry (a substituent lies on the bond's line).", bonds=loose)) def _geometry(p: Perception, frag: dict) -> None: diff --git a/backend/app/services/chem/props.py b/backend/app/services/chem/props.py new file mode 100644 index 00000000..d1ca05b8 --- /dev/null +++ b/backend/app/services/chem/props.py @@ -0,0 +1,99 @@ +from rdkit import Chem +from rdkit.Chem import Crippen, rdMolDescriptors + +from app.services.chem import ENGINE, ids, mass, perceive, warning + +ROWS = ( + ("formula", "Formula", "", "ids.formula (Hill order)", "Hill order with charge"), + ("mw", "Molecular weight", "g/mol", "mass.average_mass (RDKit periodic table)", "standard atomic weights"), + ("exact_mass", "Exact mass", "Da", "mass.exact_mass (most abundant isotopes)", "monoisotopic, electron mass removed per charge"), + ("clogp", "cLogP", "", "Crippen.MolLogP", "Wildman and Crippen 1999 atom contributions; typical error 0.5 to 0.7 log units"), + ("mr", "Molar refractivity", "cm3/mol", "Crippen.MolMR", "Wildman and Crippen 1999 atom contributions"), + ("tpsa", "TPSA", "A2", "rdMolDescriptors.CalcTPSA", "Ertl 2000 fragment contributions, N and O only"), + ("tpsa_sp", "TPSA with S and P", "A2", "rdMolDescriptors.CalcTPSA(includeSandP=True)", "Ertl 2000 with S and P contributions"), + ("hbd", "H-bond donors", "", "rdMolDescriptors.CalcNumLipinskiHBD", "Lipinski: N-H and O-H"), + ("hba", "H-bond acceptors", "", "rdMolDescriptors.CalcNumLipinskiHBA", "Lipinski: every N and O"), + ("hbd_refined", "H-bond donors (refined)", "", "rdMolDescriptors.CalcNumHBD", "pattern rules"), + ("hba_refined", "H-bond acceptors (refined)", "", "rdMolDescriptors.CalcNumHBA", "pattern rules, no amide N or nitro O"), + ("rotatable_bonds", "Rotatable bonds", "", "rdMolDescriptors.CalcNumRotatableBonds", "strict: no amide C-N, no bonds to triple-bonded atoms"), + ("heavy_atoms", "Heavy atoms", "", "Mol.GetNumHeavyAtoms", "atoms other than hydrogen"), + ("rings", "Rings", "", "rdMolDescriptors.CalcNumRings", "smallest set of smallest rings"), + ("aromatic_rings", "Aromatic rings", "", "rdMolDescriptors.CalcNumAromaticRings", "RDKit aromaticity model"), + ("fraction_csp3", "Fraction Csp3", "", "rdMolDescriptors.CalcFractionCSP3", "sp3 carbons over all carbons"), + ("formal_charge", "Formal charge", "", "Chem.GetFormalCharge", "sum of formal charges"), + ("stereocentres", "Stereocentres", "", "Chem.FindPotentialStereo", "tetrahedral centres, defined and undefined"), + ("undefined_stereocentres", "Undefined stereocentres", "", "Chem.FindPotentialStereo", "centres without a configuration"), + ("pieces", "Pieces", "", "Chem.GetMolFrags", "disconnected components"), +) +LIPINSKI = (("mw", 500.0), ("clogp", 5.0), ("hbd", 5), ("hba", 10)) +VEBER = (("rotatable_bonds", 10), ("tpsa", 140.0)) +ROUND = {"mw": 2, "exact_mass": 4, "clogp": 2, "mr": 2, "tpsa": 2, "tpsa_sp": 2, "fraction_csp3": 3} + + +def _rule(values: dict, rules: tuple, name: str, method: str) -> dict: + rows = [{"key": k, "value": values.get(k), "limit": limit, "ok": values.get(k) is not None and values[k] <= limit} for k, limit in rules] + bad = sum(1 for r in rows if not r["ok"]) + return {"name": name, "method": method, "rules": rows, "violations": bad, "pass": bad <= (1 if name == "Lipinski" else 0)} + + +def _stereo_counts(mol: Chem.Mol, conv) -> tuple[int, int]: + try: + found = [si for si in Chem.FindPotentialStereo(mol) if si.type == Chem.StereoType.Atom_Tetrahedral] + except Exception: + return 0, 0 + return len(found), sum(1 for si in found if si.specified != Chem.StereoSpecified.Specified) + + +def compute(frag: dict, expansions: dict | None = None) -> dict: + conv = perceive.prepare(frag, expansions) + mol = ids.identifier_mol(conv.mol) + Chem.SanitizeMol(mol, Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_PROPERTIES, catchErrors=True) + mol.UpdatePropertyCache(strict=False) + Chem.GetSymmSSSR(mol) + notes = [w for w in conv.warnings if w.get("code") in ("unknown_label", "abbreviation_bonds", "bad_expansion")] + excluded = sorted({conv.owner[a.GetIdx()] for a in conv.mol.GetAtoms() if a.GetAtomicNum() == 0}) + if excluded: + notes.append(warning("incomplete", f"{len(excluded)} label(s) or R-group(s) are not counted; descriptors treat them as dummy atoms.", excluded)) + values: dict = { + "formula": ids.formula(conv.mol), + "mw": mass.average_mass(conv.mol), + "exact_mass": mass.exact_mass(conv.mol), + "formal_charge": Chem.GetFormalCharge(mol), + "heavy_atoms": mol.GetNumHeavyAtoms(), + "pieces": len(Chem.GetMolFrags(mol, sanitizeFrags=False)), + } + calls = { + "clogp": lambda: Crippen.MolLogP(mol), + "mr": lambda: Crippen.MolMR(mol), + "tpsa": lambda: rdMolDescriptors.CalcTPSA(mol), + "tpsa_sp": lambda: rdMolDescriptors.CalcTPSA(mol, includeSandP=True), + "hbd": lambda: rdMolDescriptors.CalcNumLipinskiHBD(mol), + "hba": lambda: rdMolDescriptors.CalcNumLipinskiHBA(mol), + "hbd_refined": lambda: rdMolDescriptors.CalcNumHBD(mol), + "hba_refined": lambda: rdMolDescriptors.CalcNumHBA(mol), + "rotatable_bonds": lambda: rdMolDescriptors.CalcNumRotatableBonds(mol, rdMolDescriptors.NumRotatableBondsOptions.Strict), + "rings": lambda: rdMolDescriptors.CalcNumRings(mol), + "aromatic_rings": lambda: rdMolDescriptors.CalcNumAromaticRings(mol), + "fraction_csp3": lambda: rdMolDescriptors.CalcFractionCSP3(mol), + } + for key, fn in calls.items(): + try: + values[key] = fn() + except Exception as exc: + values[key] = None + notes.append(warning("property_failed", f"{key} could not be computed: {exc}")) + values["stereocentres"], values["undefined_stereocentres"] = _stereo_counts(conv.mol, conv) + for key, digits in ROUND.items(): + if isinstance(values.get(key), float): + values[key] = round(values[key], digits) + rows = [{"key": k, "label": label, "value": values.get(k), "unit": unit, "method": method, "note": note} for k, label, unit, method, note in ROWS] + return { + "rows": rows, + "values": values, + "lipinski": _rule(values, LIPINSKI, "Lipinski", "Lipinski rule of five: MW <= 500, cLogP <= 5, HBD <= 5, HBA <= 10; one violation allowed"), + "veber": _rule(values, VEBER, "Veber", "Veber: rotatable bonds <= 10, TPSA <= 140"), + "elemental_analysis": mass.elemental_analysis(conv.mol), + "excluded": excluded, + "engine": ENGINE, + "warnings": notes, + } diff --git a/backend/app/services/chem/query.py b/backend/app/services/chem/query.py new file mode 100644 index 00000000..e863d2ac --- /dev/null +++ b/backend/app/services/chem/query.py @@ -0,0 +1,340 @@ +import re + +from rdkit import Chem +from rdkit.Chem import rdDepictor + +from app.services.chem import DEFAULT_BOND_LENGTH, convert, perceive, warning +from app.services.model import ELEMENTS, new_id + +BT = Chem.BondType +NONMETALS = frozenset({1, 2, 5, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 32, 33, 34, 35, 36, 51, 52, 53, 54, 85, 86, 117, 118}) +METALS = ",".join(f"#{z}" for z in range(1, 119) if z not in NONMETALS) +HALOGENS = "#9,#17,#35,#53,#85" +GENERIC_SMARTS = { + "A": "!#1", "AH": "*", "Q": "!#6&!#1", "QH": "!#6", "X": HALOGENS, "XH": f"{HALOGENS},#1", "M": METALS, "MH": f"{METALS},#1", +} +LABEL_SMARTS = {"Hal": HALOGENS, "X": HALOGENS, "Ar": "a", "Alk": "C", "Het": "!#6&!#1", "M": METALS, "R": "*", "G": "*"} +BOND_QUERY_SMARTS = {"any": "~", "single_or_double": "-,=", "single_or_aromatic": "-,:", "double_or_aromatic": "=,:"} +BOND_SMARTS = {BT.SINGLE: "-", BT.DOUBLE: "=", BT.TRIPLE: "#", BT.AROMATIC: ":", BT.QUADRUPLE: "$"} +UNSATURATED = "$(*=,#,:*)" +QUERY_KEYS = ("list", "not", "generic", "ring_bonds", "subst", "unsat", "h_min", "aromatic", "smarts") + + +def is_query_atom(a: dict) -> bool: + q = a.get("query") + return isinstance(q, dict) and any(k in q for k in QUERY_KEYS) + + +def is_query_bond(b: dict) -> bool: + return bool(b.get("query") or b.get("topology")) + + +def has_query(frag: dict) -> bool: + return any(is_query_atom(a) for a in (frag.get("atoms") or {}).values()) or any(is_query_bond(b) for b in (frag.get("bonds") or {}).values()) + + +def _number(symbol: str) -> str | None: + return f"#{ELEMENTS.index(symbol) + 1}" if symbol in ELEMENTS else None + + +def _or(terms: list[str]) -> str: + return ",".join(terms) + + +def _ring_bonds(frag: dict, aid: str, ring_bonds: set[str]) -> int: + return sum(1 for k, b in (frag.get("bonds") or {}).items() if k in ring_bonds and aid in (b["a"], b["b"])) + + +def _degree(frag: dict, aid: str) -> int: + atoms = frag.get("atoms") or {} + return sum(1 for b in (frag.get("bonds") or {}).values() if aid in (b["a"], b["b"]) + and atoms.get(b["b"] if b["a"] == aid else b["a"], {}).get("element") != "H") + + +def atom_smarts(a: dict, frag: dict, ring_bonds: set[str], notes: list[dict]) -> str: + q = a.get("query") if isinstance(a.get("query"), dict) else {} + el = a.get("element", "C") + if isinstance(q.get("smarts"), str) and q["smarts"].strip(): + raw = q["smarts"].strip() + return raw[1:-1] if raw.startswith("[") and raw.endswith("]") else raw + terms: list[str] = [] + listed = [n for n in (_number(s) for s in q.get("list") or []) if n] + if listed: + terms.append("&".join(f"!{n}" for n in listed) if q.get("not") else _or(listed)) + elif q.get("generic") in GENERIC_SMARTS: + terms.append(GENERIC_SMARTS[q["generic"]]) + elif el == "R#": + terms.append("*") + elif el == "*": + label = a.get("generic") or a.get("label") or "" + terms.append(LABEL_SMARTS.get(label, "*")) + if label and label not in LABEL_SMARTS: + notes.append(warning("smarts_any_atom", f"The label {label} is written as any atom.", [a["id"]])) + else: + iso = a.get("isotope") + terms.append(f"{iso}{_number(el)}" if iso else _number(el) or "*") + if q.get("aromatic") is True: + terms.append("a") + elif q.get("aromatic") is False: + terms.append("A") + charge = a.get("charge") or 0 + if charge: + terms.append(f"{'+' if charge > 0 else '-'}{abs(charge)}") + rb = q.get("ring_bonds") + if isinstance(rb, int) and not isinstance(rb, bool): + n = _ring_bonds(frag, a["id"], ring_bonds) if rb == -2 else rb + terms.append(f"x{n}" if n < 4 else "x4,x5,x6") + sub = q.get("subst") + if isinstance(sub, int) and not isinstance(sub, bool): + n = _degree(frag, a["id"]) if sub == -2 else sub + terms.append(f"D{n}" if n < 6 else "D6,D7,D8") + if q.get("unsat"): + terms.append(UNSATURATED) + h = q.get("h_min") + if isinstance(h, int) and not isinstance(h, bool) and h > 0: + terms.extend(f"!H{i}" for i in range(h)) + return ";".join(t for t in terms if t) if len(terms) > 1 else terms[0] + + +def bond_smarts(b: dict | None, rb: Chem.Bond) -> str: + q = (b or {}).get("query") + base = BOND_QUERY_SMARTS.get(q) or BOND_SMARTS.get(rb.GetBondType(), "~") + if rb.GetIsAromatic() and not q: + base = ":" + topo = (b or {}).get("topology") + if topo == "ring": + return "@" if base == "~" else f"{base};@" + if topo == "chain": + return "!@" if base == "~" else f"{base};!@" + return base + + +def query_mol(frag: dict, expansions: dict | None = None) -> tuple[Chem.Mol, convert.Conversion, list[dict]]: + conv = perceive.prepare(frag, expansions) + notes: list[dict] = [] + mol = conv.mol + atoms = frag.get("atoms") or {} + bonds = frag.get("bonds") or {} + ring_bonds = {conv.bond_id(b.GetIdx()) for b in mol.GetBonds() if conv.bond_id(b.GetIdx()) and mol.GetRingInfo().NumBondRings(b.GetIdx())} + qm = Chem.RWMol() + for a in mol.GetAtoms(): + i = a.GetIdx() + if conv.drawn[i]: + text = atom_smarts(atoms[conv.owner[i]], frag, ring_bonds, notes) + else: + text = f"#{a.GetAtomicNum()}" + (";a" if a.GetIsAromatic() else "") + qa = Chem.AtomFromSmarts(f"[{text}]") + if qa is None: + notes.append(warning("bad_smarts", f"The query on this atom ({text}) is not valid SMARTS; it matches any atom.", [conv.owner[i]])) + qa = Chem.AtomFromSmarts("[*]") + qa.SetChiralTag(a.GetChiralTag()) + qa.SetProp(convert.OWNER_PROP, conv.owner[i]) + qm.AddAtom(qa) + for b in mol.GetBonds(): + bid = conv.bond_id(b.GetIdx()) + qm.AddBond(b.GetBeginAtomIdx(), b.GetEndAtomIdx(), BT.UNSPECIFIED) + qb = Chem.BondFromSmarts(bond_smarts(bonds.get(bid) if bid else None, b)) + qm.ReplaceBond(qm.GetNumBonds() - 1, qb) + if any(a.GetAtomicNum() == 1 for a in mol.GetAtoms()): + try: + qm = Chem.RWMol(Chem.MergeQueryHs(qm)) + except Exception: + notes.append(warning("explicit_h", "Explicit hydrogens in the query could not be folded into hydrogen counts.")) + return qm.GetMol(), conv, notes + + +def to_smarts(frag: dict, expansions: dict | None = None, atoms: list[str] | None = None) -> tuple[str, list[dict]]: + if atoms is not None: + keep = {a for a in atoms if a in (frag.get("atoms") or {})} + if not keep: + raise ValueError("none of the chosen atoms is in the fragment") + frag = {**frag, "atoms": {k: v for k, v in frag["atoms"].items() if k in keep}, + "bonds": {k: b for k, b in (frag.get("bonds") or {}).items() if b["a"] in keep and b["b"] in keep}} + qm, conv, notes = query_mol(frag, expansions) + if conv.expanded: + notes.append(warning("abbreviations_expanded", "Abbreviations are written as their full structures.")) + if frag.get("rgroups"): + notes.append(warning("smarts_rgroups", "SMARTS cannot hold R-group definitions or their logic; R-groups are written as any atom.")) + if frag.get("stereo_groups"): + notes.append(warning("smarts_stereo_groups", "SMARTS cannot hold enhanced stereo groups.")) + return Chem.MolToSmarts(qm), notes + + +PRIMITIVE_LETTERS = {"A", "D", "H", "R", "X"} +AROMATIC_SYMBOLS = {"c": "C", "n": "N", "o": "O", "s": "S", "p": "P", "b": "B", "se": "Se", "as": "As", "te": "Te"} +GENERIC_BY_SMARTS = {v: k for k, v in GENERIC_SMARTS.items()} +BOND_FROM_SMARTS = {"-": (1, None), "=": (2, None), "#": (3, None), ":": (1.5, None), "$": (4, None), "~": (1, "any"), "": (1, "single_or_aromatic"), + "-,=": (1, "single_or_double"), "=,-": (1, "single_or_double"), "-,:": (1, "single_or_aromatic"), ":,-": (1, "single_or_aromatic"), + "=,:": (2, "double_or_aromatic"), ":,=": (2, "double_or_aromatic")} +_ISOTOPE = re.compile(r"^(\d+)(.*)$") +_CHARGE = re.compile(r"^([+-])(\d*)$|^(\+\++|--+)$") + + +def _element(prim: str) -> tuple[str, bool | None] | None: + m = re.fullmatch(r"#(\d+)", prim) + if m: + z = int(m.group(1)) + return (ELEMENTS[z - 1], None) if 1 <= z <= len(ELEMENTS) else None + if prim in AROMATIC_SYMBOLS: + return AROMATIC_SYMBOLS[prim], True + if prim in ELEMENTS and prim not in PRIMITIVE_LETTERS: + return prim, False + return None + + +def parse_atom_smarts(text: str) -> dict | None: + body = text[1:-1] if text.startswith("[") and text.endswith("]") else text + out: dict = {"query": {}} + m = re.fullmatch(r"(.*):(\d+)", body) + if m: + body, out["map"] = m.group(1), int(m.group(2)) + if body in GENERIC_BY_SMARTS: + out["element"] = "*" + out["query"]["generic"] = GENERIC_BY_SMARTS[body] + return out + if body == "*": + out["element"] = "*" + out["query"]["generic"] = "AH" + return out + h_not: list[int] = [] + nots: list[str] = [] + for term in re.split(r"[&;]", body): + if not term: + return None + if term == "$(*=,#,:*)": + out["query"]["unsat"] = True + continue + if "," in term: + alts = term.split(",") + els = [_element(a) for a in alts] + if all(els) and "element" not in out and "list" not in out["query"]: + out["query"]["list"] = [e[0] for e in els] + out["element"] = "*" + continue + if alts in (["x4", "x5", "x6"],): + out["query"]["ring_bonds"] = 4 + continue + if alts == ["D6", "D7", "D8"]: + out["query"]["subst"] = 6 + continue + return None + iso = _ISOTOPE.match(term) + if iso and iso.group(2) in ("*", "") or iso and _element(iso.group(2)): + out["isotope"] = int(iso.group(1)) + term = iso.group(2) + if term in ("*", ""): + continue + el = _element(term) + if el and "element" not in out: + out["element"] = el[0] + if el[1] is not None: + out["query"]["aromatic"] = el[1] + continue + neg = re.fullmatch(r"!(#\d+|[A-Z][a-z]?)", term) + if neg and _element(neg.group(1)): + nots.append(_element(neg.group(1))[0]) + continue + hm = re.fullmatch(r"!H(\d)", term) + if hm: + h_not.append(int(hm.group(1))) + continue + ch = _CHARGE.fullmatch(term) + if ch: + if ch.group(3): + out["charge"] = len(ch.group(3)) * (1 if ch.group(3)[0] == "+" else -1) + else: + out["charge"] = int(ch.group(2) or 1) * (1 if ch.group(1) == "+" else -1) + continue + for pattern, key in ((r"x(\d)", "ring_bonds"), (r"D(\d)", "subst")): + pm = re.fullmatch(pattern, term) + if pm: + out["query"][key] = int(pm.group(1)) + break + else: + if term == "R0": + out["query"]["ring_bonds"] = 0 + elif term in ("a", "A") and "aromatic" not in out["query"]: + out["query"]["aromatic"] = term == "a" + else: + return None + if nots: + if "element" in out or "list" in out["query"]: + return None + out["element"] = "*" + out["query"]["list"] = nots + out["query"]["not"] = True + if h_not: + if sorted(h_not) != list(range(len(h_not))): + return None + out["query"]["h_min"] = len(h_not) + out.setdefault("element", "*") + return out + + +def from_smarts(text: str, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0)) -> tuple[dict, list[dict]]: + mol = Chem.MolFromSmarts(text.strip()) + if mol is None: + raise ValueError("not valid SMARTS") + notes: list[dict] = [] + try: + mol.UpdatePropertyCache(strict=False) + Chem.FastFindRings(mol) + except Exception: + pass + rdDepictor.Compute2DCoords(mol) + pts = convert._page_coords(mol, bond_length) + if pts: + dx, dy = origin[0] - min(p[0] for p in pts), origin[1] - min(p[1] for p in pts) + pts = [(round(x + dx, 3), round(y + dy, 3)) for x, y in pts] + used: set[str] = set() + + def fresh(prefix: str) -> str: + while True: + i = new_id(prefix) + if i not in used: + used.add(i) + return i + + frag: dict = {"id": fresh("f"), "kind": "fragment", "atoms": {}, "bonds": {}} + ids: list[str] = [] + opaque: list[str] = [] + for a in mol.GetAtoms(): + aid = fresh("a") + ids.append(aid) + x, y = pts[a.GetIdx()] + found = parse_atom_smarts(a.GetSmarts()) + if found is None: + z = a.GetAtomicNum() + rec = {"id": aid, "element": ELEMENTS[z - 1] if 0 < z <= len(ELEMENTS) else "*", "x": x, "y": y, "query": {"smarts": a.GetSmarts()}} + opaque.append(aid) + else: + rec = {"id": aid, "x": x, "y": y, **found} + if not rec["query"]: + del rec["query"] + if a.GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED: + notes.append(warning("smarts_chirality", "Chirality in the SMARTS is not drawn; set it with wedges.", [aid])) + frag["atoms"][aid] = rec + if opaque: + notes.append(warning("smarts_opaque", "These atoms keep their SMARTS text as an opaque query.", opaque)) + for b in mol.GetBonds(): + bid = fresh("b") + text_b = b.GetSmarts() + topo = None + base = text_b + for suffix, kind in ((";!@", "chain"), ("&!@", "chain"), (";@", "ring"), ("&@", "ring")): + if text_b.endswith(suffix): + base, topo = text_b[: -len(suffix)], kind + break + else: + if text_b in ("@", "!@"): + base, topo = "~", "ring" if text_b == "@" else "chain" + order, q = BOND_FROM_SMARTS.get(base, (1, None)) + if base not in BOND_FROM_SMARTS: + notes.append(warning("smarts_bond_simplified", f"The bond query {text_b} is read as a single bond.", bonds=[bid])) + rec = {"id": bid, "a": ids[b.GetBeginAtomIdx()], "b": ids[b.GetEndAtomIdx()], "order": order} + if q: + rec["query"] = q + if topo: + rec["topology"] = topo + frag["bonds"][bid] = rec + return frag, notes diff --git a/backend/app/services/chem/reactions.py b/backend/app/services/chem/reactions.py new file mode 100644 index 00000000..4f21a197 --- /dev/null +++ b/backend/app/services/chem/reactions.py @@ -0,0 +1,356 @@ +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, + } + + +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 diff --git a/backend/app/services/chem/rxnio.py b/backend/app/services/chem/rxnio.py new file mode 100644 index 00000000..b7ecbe08 --- /dev/null +++ b/backend/app/services/chem/rxnio.py @@ -0,0 +1,90 @@ +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, 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(): + 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) + 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, kekulize: bool = False) -> 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, kekulize) + 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, 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: + 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 diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py new file mode 100644 index 00000000..9b2b400a --- /dev/null +++ b/backend/app/services/chem/scheme.py @@ -0,0 +1,177 @@ +import math + +from app.services import model +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 +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 _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) + 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 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, 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} + 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: + 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) + 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) + _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) + 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 + 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": [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.")) + 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), + 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.") + 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]: + 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 diff --git a/backend/app/services/chem/search.py b/backend/app/services/chem/search.py new file mode 100644 index 00000000..e9538208 --- /dev/null +++ b/backend/app/services/chem/search.py @@ -0,0 +1,61 @@ +from rdkit import Chem + +from app.services.chem import perceive, query, warning + +MAX_HITS = 1000 + + +def query_from(fragment: dict | None, smarts: str | None, expansions: dict | None = None) -> tuple[Chem.Mol, list[str] | None, list[dict]]: + if smarts is not None: + qm = Chem.MolFromSmarts(smarts.strip()) + if qm is None: + raise ValueError("not valid SMARTS") + return qm, None, [] + if not fragment or not fragment.get("atoms"): + raise ValueError("give a query fragment with atoms, or smarts") + qm, conv, notes = query.query_mol(fragment, expansions) + return qm, conv.owner, notes + + +def substructure(targets: dict[str, dict], fragment: dict | None = None, smarts: str | None = None, expansions: dict | None = None, + max_hits: int = MAX_HITS, chirality: bool = False) -> dict: + qm, owners, notes = query_from(fragment, smarts, expansions) + hits: list[dict] = [] + by_object: dict[str, int] = {} + truncated = False + for fid in sorted(targets): + frag = targets[fid] + if not frag.get("atoms"): + continue + left = max_hits - len(hits) + if left <= 0: + truncated = True + break + try: + conv = perceive.prepare(frag, expansions) + params = Chem.SubstructMatchParameters() + params.useChirality = chirality + params.maxMatches = left + 1 + params.uniquify = True + found = conv.mol.GetSubstructMatches(qm, params) + except Exception as exc: + notes.append(warning("search_failed", f"{fid} could not be searched: {exc}")) + continue + if len(found) > left: + found, truncated = found[:left], True + for match in found: + atoms = list(dict.fromkeys(conv.owner[i] for i in match)) + bonds = [] + for qb in qm.GetBonds(): + tb = conv.mol.GetBondBetweenAtoms(match[qb.GetBeginAtomIdx()], match[qb.GetEndAtomIdx()]) + bid = conv.bond_id(tb.GetIdx()) if tb is not None else None + if bid and bid not in bonds: + bonds.append(bid) + mapping: dict[str, str] = {} + for qi, ti in enumerate(match): + key = owners[qi] if owners else str(qi) + mapping.setdefault(key, conv.owner[ti]) + hits.append({"object": fid, "atoms": atoms, "bonds": bonds, "map": mapping}) + if found: + by_object[fid] = len(found) + return {"hits": hits, "count": len(hits), "by_object": by_object, "truncated": truncated, "smarts": Chem.MolToSmarts(qm), "warnings": notes} diff --git a/backend/app/services/chem/stereo.py b/backend/app/services/chem/stereo.py new file mode 100644 index 00000000..7c734aff --- /dev/null +++ b/backend/app/services/chem/stereo.py @@ -0,0 +1,253 @@ +from rdkit import Chem +from rdkit.Chem import rdCIPLabeler +from rdkit.Geometry import Point3D + +from app.services.chem import convert, ids, perceive, warning +from app.services.ops import bond_path, object_path + +ST = Chem.StereoType +SPEC = Chem.StereoSpecified +STEREO_CODES = {"undefined_stereocentre", "stereo_unknown", "undefined_double_bond", "unknown_ez", "misplaced_wedge", "ambiguous_wedge", + "conflicting_wedges", "wedge_between_centres", "ring_double_bond_stereo", "stereo_ignored", "cip_failed", "bad_stereo_group", + "stereo_group_overlap", "stereo_group_not_centre"} +SPECIFIED = {SPEC.Specified: "defined", SPEC.Unspecified: "undefined", SPEC.Unknown: "unknown"} +KINDS = ("abs", "and", "or") + + +def group_labels(conv: convert.Conversion) -> dict[int, str]: + out: dict[int, str] = {} + counters = {"and": 0, "or": 0} + for g in conv.mol.GetStereoGroups(): + kind = convert.GROUP_KINDS.get(g.GetGroupType()) + if kind is None: + continue + if kind == "abs": + label = "abs" + else: + counters[kind] += 1 + label = f"{kind}{g.GetReadId() or counters[kind]}" + for a in g.GetAtoms(): + out[a.GetIdx()] = label + return out + + +def report(frag: dict, expansions: dict | None = None) -> dict: + conv = perceive.prepare(frag, expansions) + p = perceive.perceive(frag, expansions, conv) + mol = conv.mol + groups = group_labels(conv) + try: + found = list(Chem.FindPotentialStereo(mol)) + 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]: + continue + aid = conv.owner[i] + row = {"atom": aid, "label": p.cip.get(aid), "state": SPECIFIED.get(si.specified, "undefined")} + if row["state"] == "defined": + row["group"] = groups.get(i, "abs") + centres.append(row) + elif si.type in (ST.Bond_Double, ST.Bond_Atropisomer, ST.Bond_Cumulene_Even): + bid = conv.bond_id(si.centeredOn) + if not bid: + continue + row = {"bond": bid, "label": p.cip.get(bid), "state": SPECIFIED.get(si.specified, "undefined")} + (axes if si.type == ST.Bond_Atropisomer else double_bonds).append(row) + atoms = {k: v for k, v in p.cip.items() if k in (frag.get("atoms") or {})} + bonds = {k: v for k, v in p.cip.items() if k in (frag.get("bonds") or {})} + id_mol = ids.identifier_mol(mol) + return { + "atoms": atoms, + "bonds": bonds, + "centres": centres, + "double_bonds": double_bonds, + "axes": axes, + "chiral": frag.get("chiral"), + "stereo_groups": convert.groups_from_mol(mol, conv.owner), + "smiles": ids.smiles(id_mol), + "cxsmiles": ids.cxsmiles(id_mol), + "warnings": [w for w in p.warnings if w.get("code") in STEREO_CODES], + } + + +def _clean_groups(groups: list) -> list[dict]: + out = [] + for g in groups or []: + if isinstance(g, dict) and g.get("kind") in KINDS: + out.append({k: v for k, v in g.items() if k != "atoms"} | {"atoms": [a for a in g.get("atoms") or [] if isinstance(a, str)]}) + return out + + +def regroup(frag: dict, kind: str, atoms: list[str], n: int | None = None) -> list[dict]: + if kind not in KINDS: + raise ValueError("kind must be abs, and or or") + moving = [a for a in dict.fromkeys(atoms) if a in (frag.get("atoms") or {})] + groups = _clean_groups(frag.get("stereo_groups") or []) + for g in groups: + g["atoms"] = [a for a in g["atoms"] if a not in moving] + groups = [g for g in groups if g["atoms"]] + if not moving: + return groups + if kind == "abs": + target = next((g for g in groups if g["kind"] == "abs"), None) + else: + taken = {g.get("n") for g in groups if g["kind"] == kind} + if n is None: + n = next(i for i in range(1, len(taken) + 2) if i not in taken) + target = next((g for g in groups if g["kind"] == kind and g.get("n") == n), None) + if target is None: + target = {"kind": kind, **({"n": n} if kind != "abs" else {}), "atoms": []} + groups.append(target) + target["atoms"].extend(moving) + return groups + + +def groups_tx(frag: dict, groups: list[dict] | None, chiral: str | None, set_chiral: bool) -> dict: + fid = frag["id"] + ops = [] + old = frag.get("stereo_groups") + if groups is not None and groups != old: + ops.append({"op": "set", "path": object_path(fid, "stereo_groups"), **({"value": groups} if groups else {})}) + if set_chiral and chiral != frag.get("chiral"): + ops.append({"op": "set", "path": object_path(fid, "chiral"), **({"value": chiral} if chiral else {})}) + label = "Set stereo group" if groups is not None else "Set chiral flag" + return {"label": label, "ops": ops} + + +def preview(frag: dict, groups: list[dict] | None, chiral: str | None, set_chiral: bool, expansions: dict | None = None) -> dict: + trial = dict(frag) + if groups is not None: + trial["stereo_groups"] = groups + if set_chiral: + trial["chiral"] = chiral + conv = perceive.prepare(trial, expansions) + id_mol = ids.identifier_mol(conv.mol) + return { + "groups": convert.groups_from_mol(conv.mol, conv.owner), + "chiral": trial.get("chiral"), + "cxsmiles": ids.cxsmiles(id_mol), + "warnings": [w for w in conv.warnings if w.get("code") in STEREO_CODES], + } + + +CT = Chem.ChiralType +TETRA = (CT.CHI_TETRAHEDRAL_CW, CT.CHI_TETRAHEDRAL_CCW) +BD = Chem.BondDir +WEDGES = ("wedge", "hash", "hollow") + + +def _cip_labels(mol: Chem.Mol) -> dict[int, str]: + probe = Chem.Mol(mol) + try: + rdCIPLabeler.AssignCIPLabels(probe, maxRecursiveIterations=perceive.CIP_MAX_ITERATIONS) + except Exception: + return {} + return {a.GetIdx(): a.GetProp("_CIPCode") for a in probe.GetAtoms() if a.HasProp("_CIPCode")} + + +def _from_3d(conv: convert.Conversion, mol: Chem.RWMol, coords3d: dict) -> None: + if conv.expanded: + raise ValueError("expand the abbreviations before reading 3D coordinates") + missing = [a for a in conv.index if a not in coords3d] + if missing: + raise ValueError(f"coords3d has no position for {len(missing)} atom(s), such as {missing[0]}") + conf = Chem.Conformer(mol.GetNumAtoms()) + for aid, i in conv.index.items(): + x, y, z = (float(v) for v in coords3d[aid]) + conf.SetAtomPosition(i, Point3D(x, y, z)) + conf.Set3D(True) + cid = mol.AddConformer(conf, assignId=True) + for a in mol.GetAtoms(): + a.SetChiralTag(CT.CHI_UNSPECIFIED) + Chem.AssignStereochemistryFrom3D(mol, confId=cid, replaceExistingTags=True) + mol.RemoveConformer(cid) + + +def _aim(conv: convert.Conversion, mol: Chem.RWMol, wanted: dict[str, str], notes: list[dict]) -> None: + targets = {conv.index[a]: v for a, v in wanted.items() if a in conv.index and conv.drawn[conv.index[a]]} + for _ in range(4): + labels = _cip_labels(mol) + wrong = [i for i, v in targets.items() if labels.get(i) != v] + if not wrong: + return + for i in wrong: + atom = mol.GetAtomWithIdx(i) + atom.SetChiralTag(CT.CHI_TETRAHEDRAL_CCW if atom.GetChiralTag() == CT.CHI_TETRAHEDRAL_CW else CT.CHI_TETRAHEDRAL_CW) + labels = _cip_labels(mol) + left = [conv.owner[i] for i, v in targets.items() if labels.get(i) != v] + for i in [i for i, v in targets.items() if labels.get(i) != v]: + mol.GetAtomWithIdx(i).SetChiralTag(conv.mol.GetAtomWithIdx(i).GetChiralTag()) + if left: + notes.append(warning("cip_unreachable", "These atoms cannot take the asked label (not a stereocentre, or the label depends on another centre).", left)) + + +def rewedge(frag: dict, expansions: dict | None = None, centres: list[str] | None = None, cip: dict[str, str] | None = None, + coords3d: dict | None = None) -> dict: + conv = perceive.prepare(frag, expansions) + mol = Chem.RWMol(conv.mol) + notes: list[dict] = [] + if coords3d: + _from_3d(conv, mol, coords3d) + if cip: + _aim(conv, mol, {k: v for k, v in cip.items() if v in ("R", "S")}, notes) + chiral = {i for i in range(mol.GetNumAtoms()) if conv.drawn[i] and mol.GetAtomWithIdx(i).GetChiralTag() in TETRA} + chosen = {conv.owner[i] for i in chiral} if centres is None else {a for a in centres if a in conv.index} & {conv.owner[i] for i in chiral} + for b in mol.GetBonds(): + if b.GetBondDir() in (BD.BEGINWEDGE, BD.BEGINDASH): + b.SetBondDir(BD.NONE) + try: + Chem.WedgeMolBonds(mol, mol.GetConformer()) + except Exception as exc: + raise ValueError(f"wedges could not be placed: {exc}") from exc + bonds = frag.get("bonds") or {} + fid = frag["id"] + ops: list[dict] = [] + changed: list[str] = [] + after = {k: dict(v) for k, v in bonds.items()} + for b in mol.GetBonds(): + bid = conv.bond_id(b.GetIdx()) + if not bid or bid not in bonds: + continue + rec = bonds[bid] + old = rec.get("stereo") or "none" + if old in ("wavy", "either"): + continue + d = b.GetBondDir() + new = "wedge" if d == BD.BEGINWEDGE else "hash" if d == BD.BEGINDASH else "none" + begin = conv.owner[b.GetBeginAtomIdx()] + if new != "none" and begin not in chosen: + continue + if new == "none" and not (old in WEDGES and rec["a"] in chosen): + continue + if new != "none" and old in WEDGES and rec["a"] not in chosen: + continue + if new == "wedge" and old == "hollow": + new = "hollow" + flip = new != "none" and rec["a"] != begin + if new == old and not flip: + continue + if flip: + ops.append({"op": "set", "path": bond_path(fid, bid, "a"), "value": rec["b"]}) + ops.append({"op": "set", "path": bond_path(fid, bid, "b"), "value": rec["a"]}) + after[bid]["a"], after[bid]["b"] = rec["b"], rec["a"] + ops.append({"op": "set", "path": bond_path(fid, bid, "stereo"), **({"value": new} if new != "none" else {})}) + after[bid]["stereo"] = new + changed.append(bid) + check = perceive.prepare({**frag, "bonds": after}, expansions) + off = [conv.owner[i] for i in chiral if conv.owner[i] in chosen and check.mol.GetAtomWithIdx(i).GetChiralTag() != mol.GetAtomWithIdx(i).GetChiralTag()] + if off: + notes.append(warning("wedge_mismatch", "The new wedges do not express the wanted configuration at these centres.", off)) + labels = _cip_labels(check.mol) + return { + "tx": {"label": "Assign wedges", "ops": ops}, + "changed": changed, + "cip": {conv.owner[i]: v for i, v in labels.items() if conv.drawn[i]}, + "warnings": notes, + } diff --git a/backend/app/services/chem/stoich.py b/backend/app/services/chem/stoich.py new file mode 100644 index 00000000..89e9b0a8 --- /dev/null +++ b/backend/app/services/chem/stoich.py @@ -0,0 +1,250 @@ +import math + +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") +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} + + +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 + + +def sig3(v: float) -> str: + if v == 0: + return "0" + 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], ...], least: float) -> str: + if v is None: + return "" + for factor, unit in reversed(steps): + 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")), 1.0) + + +def mass_text(mg: float | None) -> str: + 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")), 0.1) + + +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["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): + 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 + + +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 diff --git a/backend/app/services/chem/superatom.py b/backend/app/services/chem/superatom.py new file mode 100644 index 00000000..26e1da3e --- /dev/null +++ b/backend/app/services/chem/superatom.py @@ -0,0 +1,239 @@ +import math + +from rdkit import Chem + +from app.services.chem import abbrev, convert, ids, perceive, warning +from app.services.model import new_id +from app.services.ops import atom_path, bond_path, object_path + +Point = tuple[float, float] + + +def _fresh(prefix: str, used: set[str]) -> str: + while True: + i = new_id(prefix) + if i not in used: + used.add(i) + return i + + +def _bond_key(b: dict) -> tuple: + return (b.get("z") or 0, b["id"]) + + +def _rotate(dx: float, dy: float, c: float, s: float) -> Point: + return dx * c - dy * s, dx * s + dy * c + + +def _components(atoms: set[str], bonds: dict) -> int: + adj: dict[str, set[str]] = {a: set() for a in atoms} + for b in bonds.values(): + if b["a"] in atoms and b["b"] in atoms: + adj[b["a"]].add(b["b"]) + adj[b["b"]].add(b["a"]) + seen: set[str] = set() + count = 0 + for start in atoms: + if start in seen: + continue + count += 1 + stack = [start] + seen.add(start) + while stack: + for n in adj[stack.pop()] - seen: + seen.add(n) + stack.append(n) + return count + + +def substituent_smiles(frag: dict, sel: set[str], crossing: list[dict], expansions: dict | None = None) -> str: + atoms = frag["atoms"] + sub_atoms = {a: atoms[a] for a in sel} + sub_bonds = {k: b for k, b in frag["bonds"].items() if b["a"] in sel and b["b"] in sel} + for i, b in enumerate(crossing): + inner, outer = (b["a"], b["b"]) if b["a"] in sel else (b["b"], b["a"]) + sid = f"__star{i}" + sub_atoms[sid] = {"id": sid, "element": "*", "x": atoms[outer]["x"], "y": atoms[outer]["y"]} + sub_bonds[f"__bond{i}"] = {"id": f"__bond{i}", "a": inner, "b": sid, "order": b.get("order", 1)} + conv = perceive.prepare({"atoms": sub_atoms, "bonds": sub_bonds}, expansions) + mol = ids.identifier_mol(conv.mol) + Chem.RemoveStereochemistry(mol) + return ids.smiles(mol) + + +def contract(frag: dict, atoms: list[str], label: str | None = None, expansions: dict | None = None, + has_map: bool = True, used: set[str] | None = None) -> dict: + fid = frag["id"] + frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {} + sel = {a for a in atoms if a in frag_atoms} + if not sel: + raise ValueError("select the atoms of the substituent to contract") + if len(sel) == len(frag_atoms): + raise ValueError("the selection is the whole fragment; leave at least the atom it is attached to") + if _components(sel, frag_bonds) > 1: + raise ValueError("the selection must be one connected piece") + crossing = sorted((b for b in frag_bonds.values() if (b["a"] in sel) != (b["b"] in sel)), key=_bond_key) + if not crossing: + raise ValueError("the selection is not bonded to the rest of the fragment") + notes: list[dict] = [] + drawn = substituent_smiles(frag, sel, crossing[:1], expansions) if len(crossing) == 1 else "" + found = abbrev.match(drawn) if drawn else None + if label is None: + if found is None: + raise ValueError("no abbreviation in the library matches this selection; give a label") + label = found + elif drawn and abbrev.entry(label) and found != label: + notes.append(warning("label_mismatch", f"{label} in the library is a different group; the drawn atoms are kept as its expansion.")) + used = set(used or ()) | set(frag_atoms) | set(frag_bonds) + eid = _fresh("e", used | set(expansions or {})) + nid = _fresh("a", used) + attach = [] + for b in crossing: + inner = b["a"] if b["a"] in sel else b["b"] + if inner not in attach: + attach.append(inner) + first = crossing[0] + origin, outer = (first["a"], first["b"]) if first["a"] in sel else (first["b"], first["a"]) + ox, oy = frag_atoms[origin]["x"], frag_atoms[origin]["y"] + t = math.atan2(frag_atoms[outer]["y"] - oy, frag_atoms[outer]["x"] - ox) + c, s = math.cos(-t), math.sin(-t) + rec_atoms = {} + for aid in sorted(sel): + a = dict(frag_atoms[aid]) + a["x"], a["y"] = (round(v, 4) for v in _rotate(a["x"] - ox, a["y"] - oy, c, s)) + rec_atoms[aid] = a + rec = {"id": eid, "label": label, "reversed": abbrev.reversed_label(label) if abbrev.entry(label) else label, "atoms": rec_atoms, + "bonds": {k: dict(b) for k, b in frag_bonds.items() if b["a"] in sel and b["b"] in sel}, "attach": attach, + "source": "user" if label in abbrev.user_entries() or not abbrev.entry(label) else "builtin"} + ops: list[dict] = [{"op": "set", "path": ["expansions", eid], "value": rec} if has_map else {"op": "set", "path": ["expansions"], "value": {eid: rec}}] + ops.append({"op": "set", "path": atom_path(fid, nid), "value": {"id": nid, "element": "*", "x": ox, "y": oy, "label": label, "expansion": eid}}) + for b in crossing: + end = "a" if b["a"] in sel else "b" + ops.append({"op": "set", "path": bond_path(fid, b["id"], end), "value": nid}) + if end == "a" and (b.get("stereo") or "none") in ("wedge", "hash", "hollow", "wavy"): + ops.append({"op": "set", "path": bond_path(fid, b["id"], "stereo")}) + notes.append(warning("stereo_dropped", "A wedge that started inside the contracted atoms was removed.", bonds=[b["id"]])) + ops.extend({"op": "set", "path": bond_path(fid, k)} for k, b in sorted(frag_bonds.items()) if b["a"] in sel and b["b"] in sel) + ops.extend({"op": "set", "path": atom_path(fid, a)} for a in sorted(sel)) + groups = frag.get("stereo_groups") + if groups and any(a in sel for g in groups if isinstance(g, dict) for a in g.get("atoms") or []): + kept = [{**g, "atoms": [a for a in g.get("atoms") or [] if a not in sel]} for g in groups if isinstance(g, dict)] + kept = [g for g in kept if g["atoms"]] + ops.append({"op": "set", "path": object_path(fid, "stereo_groups"), **({"value": kept} if kept else {})}) + return {"tx": {"label": f"Contract to {label}", "ops": ops}, "atom": nid, "expansion": eid, "label": label, "warnings": notes} + + +def template_record(label: str, smiles: str, bond_length: float) -> dict | None: + mol = Chem.MolFromSmiles(smiles) + if mol is None: + return None + frag = convert.from_mol(mol, bond_length) + star = next((a for a in frag["atoms"].values() if a["element"] == "*"), None) + link = next((b for b in frag["bonds"].values() if star and star["id"] in (b["a"], b["b"])), None) + if star is None or link is None: + return None + origin = frag["atoms"][link["b"] if link["a"] == star["id"] else link["a"]] + t = math.atan2(star["y"] - origin["y"], star["x"] - origin["x"]) + c, s = math.cos(-t), math.sin(-t) + atoms = {} + for aid, a in frag["atoms"].items(): + if aid == star["id"]: + continue + x, y = _rotate(a["x"] - origin["x"], a["y"] - origin["y"], c, s) + atoms[aid] = {**a, "x": x, "y": y} + bonds = {k: b for k, b in frag["bonds"].items() if k != link["id"]} + return {"label": label, "atoms": atoms, "bonds": bonds, "attach": [origin["id"]]} + + +def _clashes(pts: dict[str, Point], others: list[Point], limit: float) -> float: + score = 0.0 + for x, y in pts.values(): + for ox, oy in others: + d = math.hypot(x - ox, y - oy) + if d < limit: + score += (limit - d) / limit + return score + + +def abbreviation_atoms(frag: dict, expansions: dict | None = None) -> list[str]: + out = [] + for aid, a in sorted((frag.get("atoms") or {}).items()): + if a.get("expansion") and a["expansion"] in (expansions or {}): + out.append(aid) + elif a.get("label"): + nbrs = [frag["atoms"][b["b"] if b["a"] == aid else b["a"]].get("element", "C") for b in (frag.get("bonds") or {}).values() if aid in (b["a"], b["b"])] + if abbrev.resolve(a["label"], a.get("element", "C"), nbrs): + out.append(aid) + return out + + +def expand(frag: dict, atoms: list[str] | None = None, expansions: dict | None = None, bond_length: float | None = None, + used: set[str] | None = None, elsewhere: set[str] | None = None, drop: bool = False) -> dict: + fid = frag["id"] + frag_atoms, frag_bonds = frag.get("atoms") or {}, frag.get("bonds") or {} + expansions = expansions or {} + length = bond_length or convert.median_bond_length(frag) + candidates = abbreviation_atoms(frag, expansions) + targets = candidates if atoms is None else [a for a in atoms if a in candidates] + if not targets: + raise ValueError("none of the chosen atoms is an abbreviation") + used = set(used or ()) | set(frag_atoms) | set(frag_bonds) + placed: list[Point] = [(a["x"], a["y"]) for k, a in frag_atoms.items() if k not in targets] + ops: list[dict] = [] + notes: list[dict] = [] + expanded: dict[str, list[str]] = {} + for sid in targets: + s_atom = frag_atoms[sid] + rec = expansions.get(s_atom.get("expansion")) if s_atom.get("expansion") else None + if rec is None: + nbrs = [frag_atoms[b["b"] if b["a"] == sid else b["a"]].get("element", "C") for b in frag_bonds.values() if sid in (b["a"], b["b"])] + smiles = abbrev.resolve(s_atom.get("label"), s_atom.get("element", "C"), nbrs) + rec = template_record(s_atom["label"], smiles, length) if smiles else None + attach = [a for a in (rec or {}).get("attach") or [] if a in (rec or {}).get("atoms", {})] + if not attach: + notes.append(warning("bad_expansion", "This abbreviation has no attachment atom and was left as is.", [sid])) + continue + links = sorted((b for b in frag_bonds.values() if sid in (b["a"], b["b"])), key=_bond_key) + px, py = s_atom["x"], s_atom["y"] + if links: + other = frag_atoms[links[0]["b"] if links[0]["a"] == sid else links[0]["a"]] + t = math.atan2(other["y"] - py, other["x"] - px) + else: + t = 0.0 + c, s = math.cos(t), math.sin(t) + ax0, ay0 = rec["atoms"][attach[0]]["x"], rec["atoms"][attach[0]]["y"] + best = None + for mirror in (1.0, -1.0): + pts = {} + for aid, a in rec["atoms"].items(): + dx, dy = _rotate(a["x"] - ax0, (a["y"] - ay0) * mirror, c, s) + pts[aid] = (round(px + dx, 3), round(py + dy, 3)) + score = _clashes({k: p for k, p in pts.items() if k != attach[0]}, placed, 0.6 * length) + if best is None or score < best[0] - 1e-9: + best = (score, pts) + pts = best[1] + idmap = {aid: (aid if aid not in used else _fresh("a", used)) for aid in rec["atoms"]} + used.update(idmap.values()) + for aid, a in rec["atoms"].items(): + nid = idmap[aid] + ops.append({"op": "set", "path": atom_path(fid, nid), "value": {**a, "id": nid, "x": pts[aid][0], "y": pts[aid][1]}}) + for bid, b in rec.get("bonds", {}).items(): + if b.get("a") not in idmap or b.get("b") not in idmap: + continue + nb = bid if bid not in used else _fresh("b", used) + used.add(nb) + ops.append({"op": "set", "path": bond_path(fid, nb), "value": {**b, "id": nb, "a": idmap[b["a"]], "b": idmap[b["b"]]}}) + if len(links) > len(attach): + notes.append(warning("abbreviation_bonds", f"{rec.get('label') or sid} has {len(attach)} attachment point(s) but {len(links)} bonds; the extra bonds join the last one.", [sid])) + for k, b in enumerate(links): + end = "a" if b["a"] == sid else "b" + ops.append({"op": "set", "path": bond_path(fid, b["id"], end), "value": idmap[attach[min(k, len(attach) - 1)]]}) + ops.append({"op": "set", "path": atom_path(fid, sid)}) + placed.extend(pts.values()) + expanded[sid] = [idmap[a] for a in sorted(rec["atoms"])] + if drop: + gone = {frag_atoms[s].get("expansion") for s in expanded if frag_atoms[s].get("expansion")} + still = {a.get("expansion") for k, a in frag_atoms.items() if k not in expanded} | set(elsewhere or ()) + ops.extend({"op": "set", "path": ["expansions", e]} for e in sorted(gone - still)) + label = "Expand abbreviation" if len(expanded) == 1 else "Expand abbreviations" + return {"tx": {"label": label, "ops": ops}, "expanded": expanded, "warnings": notes} diff --git a/backend/app/services/chem/v3000.py b/backend/app/services/chem/v3000.py new file mode 100644 index 00000000..c2a56e21 --- /dev/null +++ b/backend/app/services/chem/v3000.py @@ -0,0 +1,292 @@ +from rdkit import Chem + +from app.services.chem import DEFAULT_BOND_LENGTH, convert, io, markush, perceive, query, warning + +PREFIX = "M V30 " +WIDTH = 78 +BOND_TYPES = {"any": "8", "single_or_double": "5", "single_or_aromatic": "6", "double_or_aromatic": "7"} +TOPOLOGY = {"ring": "1", "chain": "2"} + + +def _unwrap(block: str) -> list[str]: + out: list[str] = [] + carry = "" + for line in block.splitlines(): + if carry: + line = carry + line[len(PREFIX):] if line.startswith(PREFIX) else carry + line + carry = "" + if line.startswith(PREFIX) and line.endswith("-"): + carry = line[:-1] + continue + out.append(line) + return out + + +def _wrap(line: str) -> list[str]: + if not line.startswith(PREFIX) or len(line) <= WIDTH: + return [line] + out, rest = [], line + while len(rest) > WIDTH: + out.append(rest[: WIDTH - 1] + "-") + rest = PREFIX + rest[WIDTH - 1:] + out.append(rest) + return out + + +def atom_type(a: dict) -> str | None: + q = a.get("query") if isinstance(a.get("query"), dict) else {} + if q.get("list"): + body = "[" + ",".join(q["list"]) + "]" + return f"NOT{body}" if q.get("not") else body + if q.get("generic") in query.GENERIC_SMARTS: + return q["generic"] + return None + + +def atom_keywords(a: dict, frag: dict, ring_bonds: set[str], notes: list[dict]) -> list[str]: + q = a.get("query") if isinstance(a.get("query"), dict) else {} + out = [] + rb = q.get("ring_bonds") + if isinstance(rb, int) and not isinstance(rb, bool): + out.append(f"RBCNT={-1 if rb == 0 else -2 if rb == -2 else min(rb, 4)}") + sub = q.get("subst") + if isinstance(sub, int) and not isinstance(sub, bool): + out.append(f"SUBST={-1 if sub == 0 else -2 if sub == -2 else min(sub, 6)}") + if q.get("unsat"): + out.append("UNSAT=1") + h = q.get("h_min") + if isinstance(h, int) and not isinstance(h, bool) and h > 0: + out.append(f"HCOUNT={h}") + if "aromatic" in q or q.get("smarts"): + lossy = next((w for w in notes if w["code"] == "v3000_query_lossy"), None) + if lossy is None: + notes.append(warning("v3000_query_lossy", "Aromaticity and SMARTS atom queries have no V3000 field; they are left out.", [a["id"]])) + else: + lossy["atoms"] = sorted({*lossy.get("atoms", []), a["id"]}) + return out + + +def _decorate(block: str, frag: dict, conv, notes: list[dict], attach: dict[str, int] | None = None) -> list[str]: + atoms = frag.get("atoms") or {} + bonds = frag.get("bonds") or {} + mol = conv.mol + ring_bonds = {conv.bond_id(b.GetIdx()) for b in mol.GetBonds() if conv.bond_id(b.GetIdx()) and mol.GetRingInfo().NumBondRings(b.GetIdx())} + lines = _unwrap(block) + section = None + out: list[str] = [] + for line in lines: + body = line[len(PREFIX):] if line.startswith(PREFIX) else None + if body in ("BEGIN ATOM", "BEGIN BOND"): + section = body[6:] + elif body in ("END ATOM", "END BOND"): + section = None + elif section and body: + parts = body.split() + i = int(parts[0]) - 1 + if section == "ATOM" and i < len(conv.owner) and conv.drawn[i]: + a = atoms[conv.owner[i]] + kind = atom_type(a) + if kind: + parts[1] = kind + parts.extend(atom_keywords(a, frag, ring_bonds, notes)) + if attach and conv.owner[i] in attach: + parts.append(f"ATTCHPT={attach[conv.owner[i]]}") + elif section == "BOND": + bid = conv.bond_id(i) + b = bonds.get(bid) if bid else None + if b and b.get("query") in BOND_TYPES: + parts[1] = BOND_TYPES[b["query"]] + if b and b.get("topology") in TOPOLOGY: + parts.append(f"TOPO={TOPOLOGY[b['topology']]}") + line = PREFIX + " ".join(parts) + out.append(line) + return out + + +def _ctab(frag: dict, expansions: dict | None, notes: list[dict], attach: dict[str, int] | None = None) -> list[str]: + mol, extra = io._writable(frag, expansions) + asked = {k for k, a in (frag.get("atoms") or {}).items() if query.is_query_atom(a)} + notes.extend(w for w in extra if w["code"] != "query_ignored" and not (w["code"] == "unknown_label" and set(w.get("atoms", [])) <= asked)) + conv = perceive.prepare(frag, expansions) + try: + block = Chem.MolToV3KMolBlock(mol, includeStereo=True, kekulize=True) + except Exception: + block = Chem.MolToV3KMolBlock(mol, includeStereo=True, kekulize=False) + return _decorate(block, frag, conv, notes, attach) + + +def _member(frag: dict, row: dict) -> dict: + stubs = set(row["stubs"]) + return {**frag, "atoms": {k: a for k, a in frag["atoms"].items() if k not in stubs}, + "bonds": {k: b for k, b in (frag.get("bonds") or {}).items() if b["a"] not in stubs and b["b"] not in stubs}} + + +def write(frag: dict, expansions: dict | None = None, members: dict[str, dict] | None = None) -> tuple[str, list[dict]]: + notes: list[dict] = [] + lines = _ctab(frag, expansions, notes) + blocks: list[str] = [] + if frag.get("rgroups"): + desc = markush.describe(frag, members or {}) + notes.extend(desc["warnings"]) + for g in desc["groups"]: + if not g["members"]: + continue + blocks.append(f"{PREFIX}BEGIN RGROUP {g['n']}") + blocks.append(f"{PREFIX}RLOGIC {g['if_then'] or 0} {1 if g['rest_h'] else 0} {g['occurrence']}") + for row in g["members"]: + member = _member(members[row["object"]], row) + ctab = _ctab(member, expansions, notes, {a: 1 for a in row["attach"][:1]}) + start = next(i for i, l in enumerate(ctab) if l == f"{PREFIX}BEGIN CTAB") + end = next(i for i, l in enumerate(ctab) if l == f"{PREFIX}END CTAB") + blocks.extend(ctab[start:end + 1]) + blocks.append(f"{PREFIX}END RGROUP") + end = len(lines) - 1 - next(i for i, l in enumerate(reversed(lines)) if l.startswith("M END")) + lines = lines[:end] + blocks + lines[end:] + seen: set[tuple] = set() + unique = [] + for w in notes: + key = (w["code"], tuple(w.get("atoms", ())), tuple(w.get("bonds", ()))) + if key not in seen: + seen.add(key) + unique.append(w) + return "\n".join(x for line in lines for x in _wrap(line)) + "\n", unique + + +GENERIC_TYPES = set(query.GENERIC_SMARTS) +QUERY_BONDS = {v: k for k, v in BOND_TYPES.items()} +TOPOLOGY_BY_CODE = {v: k for k, v in TOPOLOGY.items()} +HEADER = ["", " FormChem", "", " 0 0 0 0 0 999 V3000"] + + +def _keywords(parts: list[str]) -> dict[str, str]: + return {p.split("=", 1)[0].upper(): p.split("=", 1)[1] for p in parts if "=" in p} + + +def _read_ctab(lines: list[str], bond_length: float, origin: tuple[float, float], used: set[str]) -> tuple[dict, list[dict]]: + notes: list[dict] = [] + atom_q: list[dict] = [] + bond_q: list[dict] = [] + clean: list[str] = [] + section = None + for line in lines: + body = line[len(PREFIX):] if line.startswith(PREFIX) else None + if body in ("BEGIN ATOM", "BEGIN BOND"): + section = body[6:] + elif body in ("END ATOM", "END BOND"): + section = None + elif section and body: + parts = body.split() + kw = _keywords(parts[6:] if section == "ATOM" else parts[4:]) + if section == "ATOM": + q: dict = {} + kind = parts[1].strip('"') + listed = kind.upper().startswith("NOT") + inner = kind[3:].strip() if listed else kind + if inner.startswith("[") and inner.endswith("]"): + q["list"] = [s.strip() for s in inner[1:-1].split(",") if s.strip()] + if listed: + q["not"] = True + parts[1] = "C" + elif kind in GENERIC_TYPES: + q["generic"] = kind + parts[1] = "C" + for key, field, zero, cap in (("RBCNT", "ring_bonds", 0, 4), ("SUBST", "subst", 0, 6)): + if key in kw and kw[key].lstrip("-").isdigit() and int(kw[key]) != 0: + v = int(kw[key]) + q[field] = zero if v == -1 else -2 if v == -2 else min(v, cap) + if kw.get("UNSAT") == "1": + q["unsat"] = True + if kw.get("HCOUNT", "").isdigit() and int(kw["HCOUNT"]) > 0: + q["h_min"] = int(kw["HCOUNT"]) + atom_q.append({"query": q, "attach": int(kw["ATTCHPT"]) if kw.get("ATTCHPT", "").lstrip("-").isdigit() else 0}) + parts = parts[:6] + [p for p in parts[6:] if p.split("=", 1)[0].upper() not in ("RBCNT", "SUBST", "UNSAT", "HCOUNT", "ATTCHPT")] + else: + bond_q.append({"query": QUERY_BONDS.get(parts[1]), "topology": TOPOLOGY_BY_CODE.get(kw.get("TOPO", ""))}) + if parts[1] in QUERY_BONDS: + parts[1] = "2" if parts[1] == "7" else "1" + parts = parts[:4] + [p for p in parts[4:] if not p.upper().startswith("TOPO=")] + line = PREFIX + " ".join(parts) + clean.append(line) + mol = Chem.MolFromMolBlock("\n".join(HEADER + clean + ["M END"]), sanitize=False, removeHs=False, strictParsing=False) + if mol is None: + raise ValueError("a CTAB in this molfile cannot be read") + try: + Chem.SanitizeMol(mol, Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_PROPERTIES, catchErrors=True) + mol.UpdatePropertyCache(strict=False) + except Exception: + pass + frag = convert.from_mol(mol, bond_length, origin, used=used) + atom_ids, bond_ids = list(frag["atoms"]), list(frag["bonds"]) + for aid, extra in zip(atom_ids, atom_q): + a = frag["atoms"][aid] + if extra["query"]: + a["query"] = extra["query"] + if "list" in extra["query"] or "generic" in extra["query"]: + a["element"] = "*" + a.pop("hydrogens", None) + if extra["attach"]: + a["data"] = {**(a.get("data") or {}), "attach": 1 if extra["attach"] in (1, -1) else 2} + for bid, extra in zip(bond_ids, bond_q): + b = frag["bonds"][bid] + if extra["query"]: + b["query"] = extra["query"] + if extra["topology"]: + b["topology"] = extra["topology"] + return frag, notes + + +def read(text: str, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0)) -> tuple[list[dict], list[dict]]: + lines = _unwrap(text.replace("\r\n", "\n")) + if not any(line.startswith(f"{PREFIX}BEGIN CTAB") for line in lines): + raise ValueError("not a V3000 molfile") + used: set[str] = set() + root: list[str] = [] + groups: list[dict] = [] + current: dict | None = None + ctab: list[str] | None = None + for line in lines: + body = line[len(PREFIX):] if line.startswith(PREFIX) else None + if body is None: + continue + if body.startswith("BEGIN RGROUP"): + current = {"n": int(body.split()[2]), "logic": [], "ctabs": []} + groups.append(current) + elif body == "END RGROUP": + current = None + elif current is not None and body.startswith("RLOGIC"): + current["logic"] = body.split()[1:] + elif body == "BEGIN CTAB": + ctab = [line] + elif body == "END CTAB" and ctab is not None: + ctab.append(line) + if current is not None: + current["ctabs"].append(ctab) + else: + root.extend(ctab) + ctab = None + elif ctab is not None: + ctab.append(line) + notes: list[dict] = [] + scaffold, found = _read_ctab(root, bond_length, origin, used) + notes.extend(found) + out = [scaffold] + bottom = max((a["y"] for a in scaffold["atoms"].values()), default=origin[1]) + 3 * bond_length + rgroups: dict[str, dict] = {} + for g in groups: + x = origin[0] + members = [] + for lines_m in g["ctabs"]: + member, found = _read_ctab(lines_m, bond_length, (x, bottom), used) + notes.extend(found) + members.append(member["id"]) + out.append(member) + x = max((a["x"] for a in member["atoms"].values()), default=x) + 3 * bond_length + bottom += 4 * bond_length + logic = g["logic"] + rec: dict = {"members": members, "occurrence": logic[2].strip('"') if len(logic) > 2 else ">0", "rest_h": len(logic) > 1 and logic[1] == "1"} + if logic and logic[0].isdigit() and int(logic[0]) > 0: + rec["if_then"] = int(logic[0]) + rgroups[str(g["n"])] = rec + if rgroups: + scaffold["rgroups"] = rgroups + return out, notes diff --git a/backend/app/services/importers.py b/backend/app/services/importers.py index e4613ee4..f40d0335 100644 --- a/backend/app/services/importers.py +++ b/backend/app/services/importers.py @@ -170,6 +170,23 @@ 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], source: Path) -> bool: + margin = float(page.get("margins", 36)) + try: + from app.services.chem import scheme + 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 + 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 +206,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, 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.") + 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: diff --git a/backend/app/services/model.py b/backend/app/services/model.py index b80dab0d..71aa9551 100644 --- a/backend/app/services/model.py +++ b/backend/app/services/model.py @@ -92,6 +92,14 @@ class Bond(TypedDict): data: NotRequired[dict[str, Any]] +class RGroupDef(TypedDict): + members: list[str] + occurrence: NotRequired[str] + rest_h: NotRequired[bool] + if_then: NotRequired[int] + attach: NotRequired[dict[str, list[str]]] + + class Fragment(TypedDict): id: str kind: Literal["fragment"] @@ -105,7 +113,7 @@ class Fragment(TypedDict): data: NotRequired[dict[str, Any]] chiral: NotRequired[Literal["absolute", "relative", "racemic"]] stereo_groups: NotRequired[list[dict[str, Any]]] - rgroups: NotRequired[dict[str, dict[str, Any]]] + rgroups: NotRequired[dict[str, RGroupDef]] class Page(TypedDict): 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: 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)} diff --git a/build_app b/build_app index b66cc729..bb0e3f52 100755 --- a/build_app +++ b/build_app @@ -202,7 +202,7 @@ else say "up to date" fi TAURI="$ROOT/frontend/node_modules/.bin/tauri" -[ -x "$TAURI" ] || die "the Tauri CLI did not install; run ./build_app --reinstall" +[ -x "$TAURI" ] || die "the Tauri CLI is not in frontend/node_modules; check that frontend/package.json lists @tauri-apps/cli in devDependencies, then run ./build_app --reinstall" CLI_V="$("$TAURI" --version | awk '{print $2}')" CRATE_V="$(awk '/^name = "tauri"$/ {getline; gsub(/"/, "", $3); print $3; exit}' src-tauri/Cargo.lock 2>/dev/null || true)" if [ -n "$CRATE_V" ]; then @@ -235,6 +235,7 @@ freeze() { --distpath dist-engine --workpath build/pyinstaller --specpath build/pyinstaller \ --add-data "$ROOT/frontend/dist${SEP}frontend_dist" \ --add-data "$ROOT/THIRD-PARTY-NOTICES.txt${SEP}." \ + --add-data "$ROOT/backend/app/data/templates${SEP}templates" \ --collect-submodules app --collect-submodules uvicorn \ --collect-all rdkit --collect-all indigo \ ${EXTRA[@]+"${EXTRA[@]}"} \ 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. diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 006549fb..ed99b9ee 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -198,9 +198,9 @@ A fragment may hold several disconnected pieces (a salt is one fragment). Fields | --- | --- | | `atoms` | map of atoms by id | | `bonds` | map of bonds by id | -| `chiral` | optional whole-molecule stereo flag: `"absolute"`, `"relative"` or `"racemic"` (built from 0.6.0) | +| `chiral` | optional whole-molecule stereo flag: `"absolute"`, `"relative"` or `"racemic"` (built from 0.6.0). For chemistry, `relative` puts every stereocentre that is in no stereo group into one OR group and `racemic` puts them into one AND group, each with the next free group number; `absolute` (and absent) leaves them absolute. `absolute` also sets the molfile chiral flag | | `stereo_groups` | optional enhanced stereo groups `[ { "kind": "abs" }, { "kind": "and", "n": 1, "atoms": ["a4", "a9"] } ]`, kind `abs`, `and` or `or` (built from 0.6.0) | -| `rgroups` | optional R-group definitions keyed by number as a string: `{ "1": { "members": ["f..."], "occurrence": ">0", "rest_h": false, "if_then": 2 } }`, `members` naming fragment objects that hold one member each with an attachment atom (built from 0.6.0) | +| `rgroups` | optional R-group definitions keyed by number as a string: `{ "1": { "members": ["f..."], "occurrence": ">0", "rest_h": false, "if_then": 2 } }`, `members` naming fragment objects that hold one member each (built from 0.6.0). A definition may carry `attach`, a map of member fragment id to that member's attachment atom ids in order (first, then second attachment point): `{ "f...": ["a..."] }`. A member without an `attach` entry uses its atoms whose `data.attach` is 1 or 2 (V3000 import writes these), else its attachment stubs: `"*"` atoms with no label, no `generic` and exactly one bond, in id order. An attachment atom that is such a stub stands for the R-group atom: its neighbour bonds to the scaffold and the stub is not part of the member; any other attachment atom bonds to the scaffold itself. A member with none of these attaches at its first atom by id | ### Atoms @@ -222,7 +222,7 @@ A fragment may hold several disconnected pieces (a salt is one fragment). Fields | `map` | absent | atom-atom map number, an integer from 1 | | `lone_pairs` | 0 | lone pairs drawn, 0 to 4 | | `charge_angle` | absent | degrees around the atom where the person dragged the charge and radical marks; absent places them automatically | -| `query` | absent | query features (built from 0.6.0): `list` (element symbols, `["C", "N", "O"]`), `not` (true makes `list` a not-list), `generic` (`"A"`, `"AH"`, `"Q"`, `"QH"`, `"X"`, `"XH"`, `"M"`, `"MH"`), `ring_bonds`, `subst` (integers, or `-2` for "as drawn"), `unsat` (boolean), `h_min` (integer), `aromatic` (boolean) | +| `query` | absent | query features (built from 0.6.0): `list` (element symbols, `["C", "N", "O"]`), `not` (true makes `list` a not-list), `generic` (`"A"`, `"AH"`, `"Q"`, `"QH"`, `"X"`, `"XH"`, `"M"`, `"MH"`), `ring_bonds`, `subst` (integers, or `-2` for "as drawn"), `unsat` (boolean), `h_min` (integer), `aromatic` (boolean), `smarts` (the SMARTS text of an atom query the fields above cannot express, kept as it is; SMARTS import writes it, and it wins over the other fields when present) | | `note` | absent | a short atom note | | `ignore_warnings` | false | suppress valence and check warnings on this atom | | `color` | absent | colour override for the label and the atom's marks | @@ -257,7 +257,7 @@ Built from 0.6.0. An abbreviation atom (`label` `"OTs"`, `expansion` `"e5k2..."` "expansions": { "e5k20a9qz": { "id": "e5k20a9qz", "label": "OTs", "reversed": "TsO", "atoms": {}, "bonds": {}, "attach": ["a..."] } } ``` -`atoms` and `bonds` have the fragment shapes; their coordinates are in points relative to the first attachment atom at (0, 0) with the outgoing attachment bond along +x. `attach` lists the attachment atoms in order: the abbreviation atom's bonds attach to them in the order of the atom's bonds by `z`, then id. `reversed` is the label shown when the label is drawn on the left. Expanding replaces the abbreviation atom by these atoms laid out on the page; contracting creates an expansion and an abbreviation atom. +`atoms` and `bonds` have the fragment shapes; their coordinates are in points relative to the first attachment atom at (0, 0) with the outgoing attachment bond along +x. `attach` lists the attachment atoms in order: the abbreviation atom's bonds attach to them in the order of the atom's bonds by `z`, then id. `reversed` is the label shown when the label is drawn on the left. `source` is `"builtin"` when the expansion came from the shipped library and `"user"` otherwise (a user library entry or a label the person typed). Expanding replaces the abbreviation atom by these atoms laid out on the page; contracting creates an expansion and an abbreviation atom. ## Text, captions and the other kinds @@ -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 the target while the same transaction refreshes `x`, `y`. ### 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`. +`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,19 @@ 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 +{ "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. + +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. @@ -342,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/docs/REACTIONS.md b/docs/REACTIONS.md new file mode 100644 index 00000000..d1729f71 --- /dev/null +++ b/docs/REACTIONS.md @@ -0,0 +1,145 @@ +# 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". + +### 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: + +| 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 ("Set Reaction Roles") 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, 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 + +- 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. 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. diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index fbe3e265..5910c7e5 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.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 @@ -18,12 +18,26 @@ 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 +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 +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, 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 @@ -140,6 +154,47 @@ 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 +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 +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 +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) @@ -569,6 +624,178 @@ 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. + +## 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. + +## 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"`. + +## 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. + +## 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 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. diff --git a/frontend/index.html b/frontend/index.html index 07b62cd8..3b93a2cf 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -98,12 +98,16 @@ + + + + diff --git a/frontend/package-lock.json b/frontend/package-lock.json index bd4fd81a..47e2ba66 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formchem", - "version": "0.4.0", + "version": "0.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formchem", - "version": "0.4.0", + "version": "0.6.0", "license": "Apache-2.0", "dependencies": { "@tauri-apps/api": "2.12.1", @@ -14,6 +14,7 @@ "@xterm/xterm": "6.0.0" }, "devDependencies": { + "@tauri-apps/cli": "2.12.6", "typescript": "7.0.2", "vite": "8.3.5" }, @@ -378,6 +379,223 @@ "url": "https://opencollective.com/tauri" } }, + "node_modules/@tauri-apps/cli": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.6.tgz", + "integrity": "sha512-/cOeQgqq8PBDPODOjjT0YHs4qxKCHcQMWMiBm4rLM3JNr9mZE+PHNKOK4zAkhIUtYMNL/0fweW48VNvzD1AbqA==", + "dev": true, + "license": "Apache-2.0 OR MIT", + "bin": { + "tauri": "tauri.js" + }, + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/tauri" + }, + "optionalDependencies": { + "@tauri-apps/cli-darwin-arm64": "2.12.6", + "@tauri-apps/cli-darwin-x64": "2.12.6", + "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.6", + "@tauri-apps/cli-linux-arm64-gnu": "2.12.6", + "@tauri-apps/cli-linux-arm64-musl": "2.12.6", + "@tauri-apps/cli-linux-riscv64-gnu": "2.12.6", + "@tauri-apps/cli-linux-x64-gnu": "2.12.6", + "@tauri-apps/cli-linux-x64-musl": "2.12.6", + "@tauri-apps/cli-win32-arm64-msvc": "2.12.6", + "@tauri-apps/cli-win32-ia32-msvc": "2.12.6", + "@tauri-apps/cli-win32-x64-msvc": "2.12.6" + } + }, + "node_modules/@tauri-apps/cli-darwin-arm64": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.6.tgz", + "integrity": "sha512-Uokwk1hFfJoG54+kD8iU0St33jAIkNvojnjEfBZ6UbL5rnM10AiFwUS/2DHTJ9R4/Kba4U44v7djfMuWFTQgeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-darwin-x64": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.6.tgz", + "integrity": "sha512-WhahqzcyHCpCzh4Taf0ZbBm6nGkvuOSh5ffrgOO7EdYaYe+RBQK8LOlFu+bbjul5v9cdLDi3kco+0+7IlZtTVA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.6.tgz", + "integrity": "sha512-GB6weN+iFHxiFZ9SOKW6fINis7gnxohoOldR7sryBe7uaavkFGaMCa0yQs5njeXPWvzlE9WTQ13z8oDjmqK+Ww==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-gnu": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.6.tgz", + "integrity": "sha512-mdHoUFYKfztUtPKE0C2hhGkEo7j6swXjg+5yRRKSD7A2gLkRPQFIXWD/DAYhiJdeAkyA8MCP6nvvKvg/4YryWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-arm64-musl": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.6.tgz", + "integrity": "sha512-2BxB+9a3JRN0eJ0t0qGe8IKJfgBLOZDE8a499OXH+yg4J9bMpSK1oHXBxnHuSHFWhby4QnQ/t+sBf7tRC0UZeA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-riscv64-gnu": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.6.tgz", + "integrity": "sha512-sb58RsNHex9QVqHdN1cf9MMlamUWAtk1NzuxTZalUnBUHfblIbe71hfmdI6whDZ84MufgOdeg/bzvhrbZS1r0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-gnu": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.6.tgz", + "integrity": "sha512-ZAb4/CHRma3ErjL2RGfHjITTUBIs4zySf0hIli9BddOtEdSx0ze0hEgxl+HfBVc5OEW/QmbiZ2E2+CkkHc8Pcg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-linux-x64-musl": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.6.tgz", + "integrity": "sha512-ueSzM2Du6r4i1d/lby9kEvrhPnXw5zM/VYvcW1ldEWSpkUyVohsBXkmD+U7vMskEW5tXeCUenki7nYVxyGBGpQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-arm64-msvc": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.6.tgz", + "integrity": "sha512-6bmOt2BQSe0Bba+5CJcTKSML7VOYDxyiAKyBrjo86VxMdC1usIQmklu3Xc83s3QoK1rOMwwbANlPF6i5R2mvIg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-ia32-msvc": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.6.tgz", + "integrity": "sha512-9q9ZFNuFreBczwyJuhhlrEOBzGClwWUYirQ2GBl66Y6EaNl17IdLH8TRqoY9wYB1LnctNBi+Fa/WMGtFA4BtFQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tauri-apps/cli-win32-x64-msvc": { + "version": "2.12.6", + "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.6.tgz", + "integrity": "sha512-ion7Chbj21ROxMRpjQ7G8rz5sIOaI7IoBQum1oq5sl1V5zGWyc/oYnCrQhVqO2TxK/lBDWxt648BzLi02SY3Xg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0 OR MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, "node_modules/@tybys/wasm-util": { "version": "0.10.5", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", diff --git a/frontend/package.json b/frontend/package.json index da619353..467043c0 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formchem", "private": true, - "version": "0.4.0", + "version": "0.6.0", "description": "FormChem · chemical structure drawing in the FormAI family", "license": "Apache-2.0", "type": "module", @@ -20,6 +20,7 @@ "@xterm/xterm": "6.0.0" }, "devDependencies": { + "@tauri-apps/cli": "2.12.6", "typescript": "7.0.2", "vite": "8.3.5" } diff --git a/frontend/src/app.ts b/frontend/src/app.ts index e73ba6e4..c83bc698 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(); @@ -323,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/app/analysis-text.ts b/frontend/src/app/analysis-text.ts new file mode 100644 index 00000000..b1068e9e --- /dev/null +++ b/frontend/src/app/analysis-text.ts @@ -0,0 +1,95 @@ +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'; + +export interface PropertyRowDef { + key: RowKey; + label: string; + digits?: number; + unit?: string; + method: string; + width: number; +} + +export const PROPERTY_ROWS: readonly PropertyRowDef[] = [ + { key: 'formula', label: 'Formula', method: 'Hill order with charge, abbreviations expanded', width: 12 }, + { key: 'mw', label: 'Molecular weight', digits: 2, method: 'Standard atomic weights (CIAAW conventional values)', width: 8 }, + { key: 'exact_mass', label: 'Exact mass', digits: 4, method: 'Monoisotopic mass from the most abundant isotope of each element', width: 10 }, + { key: 'mz', label: 'm/z', digits: 4, method: 'Exact mass divided by the absolute charge, electron mass corrected', width: 10 }, + { key: 'elemental', label: 'Elemental analysis', method: 'Mass percent of each element, two decimals', width: 18 }, + { key: 'clogp', label: 'cLogP', digits: 2, method: 'Atom contributions (Wildman and Crippen 1999)', width: 6 }, + { key: 'tpsa', label: 'tPSA', digits: 2, unit: 'Ų', method: 'Topological polar surface area, N and O fragments (Ertl 2000)', width: 9 }, + { key: 'mr', label: 'Molar refractivity', digits: 2, unit: 'cm³/mol', method: 'Atom contributions (Wildman and Crippen 1999)', width: 13 }, + { key: 'hbd', label: 'H-bond donors', method: 'Lipinski counting: N-H and O-H groups', width: 3 }, + { key: 'hba', label: 'H-bond acceptors', method: 'Lipinski counting: N and O atoms', width: 3 }, + { key: 'rotatable', label: 'Rotatable bonds', method: 'Non-ring single bonds between non-terminal heavy atoms, amide C-N excluded', width: 3 }, + { key: 'lipinski', label: 'Lipinski rule of five', method: 'MW at most 500, cLogP at most 5, donors at most 5, acceptors at most 10', width: 16 }, +]; + +const LIMITS: ReadonlyArray<[string, PropertyKey, number]> = [['MW', 'mw', 500], ['cLogP', 'clogp', 5], ['HBD', 'hbd', 5], ['HBA', 'hba', 10]]; + +export function lipinskiRules(p: Properties): { violations: number; rules: LipinskiRule[] } | null { + if (p.lipinski && (p.lipinski.rules.length || p.lipinski.violations)) return p.lipinski; + const rules: LipinskiRule[] = []; + for (const [rule, key, limit] of LIMITS) { + const v = p.values[key]?.value; + if (typeof v !== 'number') return null; + rules.push({ rule, value: v, limit, pass: v <= limit }); + } + return { violations: rules.filter((r) => !r.pass).length, rules }; +} + +export function lipinskiText(p: Properties): string { + const l = lipinskiRules(p); + if (!l) return ''; + if (!l.violations) return t('Pass (0 violations)'); + const which = l.rules.filter((r) => !r.pass).map((r) => r.rule).join(', '); + return `${l.violations} ${l.violations === 1 ? t('violation') : t('violations')}${which ? ` (${which})` : ''}`; +} + +export function elementalText(ea: Record): string { + return Object.entries(ea).map(([el, pct]) => `${el} ${pct.toFixed(2)}%`).join(', '); +} + +export function rowValue(def: PropertyRowDef, p: Properties): string { + if (def.key === 'elemental') return elementalText(p.elemental); + if (def.key === 'lipinski') return lipinskiText(p); + const v = p.values[def.key]?.value; + if (v === undefined || v === null || v === '') return ''; + if (typeof v === 'string') return v; + const n = def.digits !== undefined ? v.toFixed(def.digits) : String(Math.round(v)); + const unit = p.values[def.key]?.unit ?? def.unit; + return unit ? `${n} ${unit}` : n; +} + +export function rowMethod(def: PropertyRowDef, p: Properties | null): string { + if (def.key === 'lipinski') return p?.lipinski?.method ?? def.method; + if (def.key === 'elemental') return def.method; + return p?.values[def.key]?.method ?? def.method; +} + +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[] = []; + if (opts.title) lines.push(opts.title); + if (opts.smiles) lines.push(`SMILES: ${opts.smiles}`); + for (const def of PROPERTY_ROWS) { + const v = rowValue(def, p); + 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/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index 8f40b24e..0f410628 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -1,24 +1,44 @@ -import { makeSelection, fragmentsTouched, isEmpty } from '../canvas/selection'; +import { 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'; -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 { Fragment, Id, Point } from '../engine/model'; import { atomPath, bondPath, type Op } from '../engine/ops'; import { t } from '../i18n'; import { post } from '../io/api'; import { setAnalysisOpen } from '../ui/analysis-panel'; -import { Dialog } from '../ui/dialogs'; -import { el, setText } from '../ui/dom'; +import type { FindBar } from '../ui/find-bar'; import { toast } from '../ui/toast'; 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[] { + 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 }[] } @@ -97,59 +117,9 @@ async function relayout(view: CanvasView, clean: boolean): Promise { if (notes.length) toast(notes[0]); } -function problemRows(view: CanvasView): Array<{ text: string; frag: Id; atoms: Id[]; bonds: Id[] }> | null { - const client = view.client; - if (!client) return []; - const derived = client.derived && client.derived.rev === client.rev ? client.derived : null; - const frags = selectedFragments(view); - if (frags.some((f) => !derived?.fragments[f.id])) return null; - const rows: Array<{ text: string; frag: Id; atoms: Id[]; bonds: Id[] }> = []; - for (const f of frags) { - const d: DerivedFragment = derived!.fragments[f.id]; - for (const e of d.valence_errors ?? []) { - const a = f.atoms[e.atom]; - if (!a || a.ignore_warnings) continue; - const allowed = e.allowed.length ? e.allowed.join(', ') : '-'; - rows.push({ text: `${a.label ?? a.element}: ${t('valence')} ${e.valence}, ${t('allowed')} ${allowed}`, frag: f.id, atoms: [e.atom], bonds: [] }); - } - for (const w of d.warnings ?? []) rows.push({ text: w.text, frag: f.id, atoms: w.atoms ?? [], bonds: w.bonds ?? [] }); - } - return rows; -} - -let checkDialog: Dialog | null = null; - -function checkStructure(view: CanvasView): void { - const rows = problemRows(view); - const dlg = (checkDialog ??= new Dialog(t('Check Structure'), 480)); - dlg.body.replaceChildren(); - dlg.foot.replaceChildren(); - const list = el('
'); - if (rows === null) { - list.appendChild(el(`

`)); - setText(list.firstElementChild, t('The engine has not finished checking this drawing. Try again in a moment.')); - } else if (!rows.length) { - list.appendChild(el(`

`)); - setText(list.firstElementChild, t('No problems found.')); - } - for (const r of rows ?? []) { - const row = el('
'); - setText(row.firstElementChild, r.text); - if (r.atoms.length || r.bonds.length) { - const link = el(''); - setText(link, r.atoms.length === 1 && !r.bonds.length ? t('Select atom') : t('Select')); - link.addEventListener('click', () => { - view.setSelection(makeSelection(r.atoms.map((a) => selectionKey(r.frag, a)), r.bonds.map((b) => selectionKey(r.frag, b)))); - dlg.close(); - view.focus(); - }); - row.appendChild(link); - } - list.appendChild(row); - } - dlg.body.appendChild(list); - dlg.button(t('Close'), 'primary', () => dlg.close()); - 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 { @@ -181,6 +151,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() }, @@ -202,9 +175,15 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { { id: 'distribute-v', label: () => t('Distribute Vertically'), group: 'Arrange', icon: 'distributeV', mutates: true, when: NEED_SELECTION, enabled: selected, run: () => { distribute(ctx(), 'v'); } }, { id: 'clean-structure', label: () => t('Clean Up Structure'), group: 'Structure', icon: 'magic', mutates: true, description: 'Tidies bond lengths and angles of the selection (or every structure on the page) in one undo step, keeping its place and stereochemistry.', when: NEED_DRAWING, enabled: open, run: () => relayout(view, true) }, { id: 'layout-structure', label: () => t('Lay Out Structure'), group: 'Structure', icon: 'layout', mutates: true, description: 'Computes fresh 2D coordinates for the selected structures (or every structure on the page) in one undo step.', when: NEED_DRAWING, enabled: open, run: () => relayout(view, false) }, - { 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'), + ...(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 357d802b..4ec0b451 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -1,4 +1,6 @@ +import { marksView, onMarksView } from '../canvas/marks-options'; 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'; @@ -8,10 +10,15 @@ 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'; import { registerCanvasCommands } from './canvas-commands'; +import { registerChemCommands } from './chem-commands'; import { commandStateChanged } from './commands-shell'; +import { objectCommandDefs } from './object-commands'; +import { registerReactionCommands } from './reaction-commands'; export interface CanvasHosts { stage: HTMLElement; stageCol: HTMLElement } @@ -32,6 +39,9 @@ function display(): RenderDisplay { aromaticCircle: pref('aromaticStyle') === 'circle', valenceWarnings: pref('valenceWarnings'), stereoLabels: pref('stereoLabels'), + enhancedStereo: marksView().enhanced, + queryMarks: marksView().query, + groupColours: marksView().groupColours, }; } @@ -40,7 +50,15 @@ 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 rulers = new Rulers(h.stage, view); + rulers.onChange(() => commandStateChanged()); + const find = mountFindBar(h.stage, view); + find.onChange(() => commandStateChanged()); + registerCanvasCommands({ view, homeOpen, find, rulers }); + commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); + registerReactionCommands({ view, homeOpen }); + registerChemCommands({ host: view, homeOpen }); + onMarksView(() => view.setDisplay(display())); view.setDisplay(display()); document.addEventListener(PREFS_EVENT, () => view.setDisplay(display())); @@ -56,6 +74,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/chem-commands.ts b/frontend/src/app/chem-commands.ts new file mode 100644 index 00000000..2ad4d2ed --- /dev/null +++ b/frontend/src/app/chem-commands.ts @@ -0,0 +1,612 @@ +import { marksView, setMarksView } from '../canvas/marks-options'; +import { attachmentAtoms } from '../canvas/render/marks-query'; +import { stereoCentres } from '../canvas/render/marks-stereo'; +import { atomsByFragment, bondsByFragment, isEmpty, makeSelection } from '../canvas/selection'; +import { selectionKey, type Hit, type Selection } from '../canvas/types'; +import { quickFormula } from '../chem/formula'; +import { commands, type CommandDef } from '../commands/registry'; +import { analysisApi, sourceFor, type EngineTx, type EngineWarning, type Properties, type Source } from '../engine/analysis-api'; +import type { DocumentClient } from '../engine/client-api'; +import type { BondQuery, FormChemDocument, Fragment, Id, Page, Point } from '../engine/model'; +import type { Op } from '../engine/ops'; +import { t } from '../i18n'; +import { ApiError } from '../io/api'; +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'; +import { askRGroup } from '../ui/rgroup-dialog'; +import { openStereoPopover } from '../ui/stereo-popover'; +import { showStructureCheck, type CheckRow } from '../ui/structure-check'; +import { toast } from '../ui/toast'; +import { formatAnalysisText } from './analysis-text'; +import { atomListOps, atomQueryOps, bondQueryOps, bondTopologyOps, clearStereoGroupOps, rgroupAtomOps, rgroupOps, stereoGroupOps, usedRGroups, type GroupKind } from './chem-edits'; + +export interface ChemHost { + readonly client: DocumentClient | null; + readonly doc: FormChemDocument; + selection(): Selection; + setSelection(s: Selection): void; + page(): Page | null; + style(): { bond_length: number }; + toClient(p: Point): { x: number; y: number }; + focus(): void; +} + +export interface ChemCommandDeps { + host: ChemHost; + homeOpen(): boolean; +} + +type Targets = Map; + +const NEED_DRAWING = 'Open or create a drawing first'; +const NEED_ATOMS = 'Select one or more atoms first'; +const NEED_BONDS = 'Select one or more bonds first'; +const MENU_PREFIX = 'canvas-menu:chem-'; + +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', 'enumerate-markush', 'copy-smarts', 'export-smarts', +]; + +const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); + +function topFragments(doc: FormChemDocument, ids: readonly Id[], out: Id[] = [], seen = new Set()): Id[] { + for (const id of ids) { + if (seen.has(id)) continue; + seen.add(id); + const o = doc.objects[id]; + if (o?.kind === 'fragment' && Object.keys(o.atoms).length) out.push(id); + else if (o?.kind === 'group') topFragments(doc, o.children, out, seen); + } + return out; +} + +function pageFragmentIds(host: ChemHost): Id[] { + const page = host.page(); + return page && host.client ? topFragments(host.client.doc, page.order) : []; +} + +function selectedAtoms(host: ChemHost): Map { + const doc = host.client?.doc; + const sel = host.selection(); + const out = atomsByFragment(sel); + if (!doc) return out; + for (const fid of topFragments(doc, [...sel.objects])) { + const f = doc.objects[fid] as Fragment; + out.set(fid, Object.keys(f.atoms)); + } + for (const [fid, list] of out) { + const f = doc.objects[fid]; + const live = f?.kind === 'fragment' ? list.filter((a) => !!f.atoms[a]) : []; + if (live.length) out.set(fid, live); + else out.delete(fid); + } + return out; +} + +function selectedBonds(host: ChemHost): Map { + const doc = host.client?.doc; + const out = bondsByFragment(host.selection()); + for (const [fid, list] of out) { + const f = doc?.objects[fid]; + const live = f?.kind === 'fragment' ? list.filter((b) => !!f.bonds[b]) : []; + if (live.length) out.set(fid, live); + else out.delete(fid); + } + return out; +} + +function targetsOf(host: ChemHost): Targets { + const sel = selectedAtoms(host); + if (sel.size) return new Map([...sel].map(([fid, atoms]) => [fid, isWhole(host, fid, atoms) ? null : atoms])); + return new Map(pageFragmentIds(host).map((fid) => [fid, null])); +} + +function isWhole(host: ChemHost, fid: Id, atoms: Id[]): boolean { + const f = host.client?.doc.objects[fid]; + return f?.kind === 'fragment' && atoms.length === Object.keys(f.atoms).length; +} + +let busy = false; + +async function engineEdit( + host: ChemHost, + label: string, + targets: Targets, + call: (src: Source, atoms: Id[] | undefined) => Promise, +): Promise { + const client = host.client; + if (!client || !targets.size || busy) return null; + busy = true; + const doc = client.doc; + const asked = new Map(); + const results: R[] = []; + const ops: Op[] = []; + try { + for (const [fid, atoms] of targets) { + const src = sourceFor(doc, fid); + if (!src) continue; + asked.set(fid, src.fragment); + const r = await call(src, atoms ?? undefined); + results.push(r); + if (r.tx?.ops.length) ops.push(...r.tx.ops); + } + } catch (e) { + toast(`${label}: ${errText(e)}`, 'error'); + return null; + } finally { + busy = false; + } + if (host.client !== client || [...asked].some(([fid, f]) => client.doc.objects[fid] !== f)) { + toast(t('The drawing changed while the engine worked; try again.'), 'error'); + return null; + } + if (ops.length) client.commit(label, ops); + const note = results.flatMap((r) => r.warnings)[0]; + if (note) toast(note.text); + return results; +} + +function commitPerFragment(host: ChemHost, label: string, groups: Map, build: (f: Fragment, ids: Id[]) => Op[]): boolean { + const client = host.client; + if (!client) return false; + const ops: Op[] = []; + for (const [fid, ids] of groups) { + const f = client.doc.objects[fid]; + if (f?.kind === 'fragment') ops.push(...build(f, ids)); + } + if (!ops.length) return false; + return !!client.commit(label, ops); +} + +export async function addHydrogens(host: ChemHost): Promise { + const res = await engineEdit(host, t('Add Explicit Hydrogens'), targetsOf(host), (src, atoms) => analysisApi.hydrogens(src, 'add', atoms)); + if (res && !res.some((r) => r.count)) toast(t('No implicit hydrogens to add.')); +} + +export async function removeHydrogens(host: ChemHost): Promise { + const res = await engineEdit(host, t('Remove Explicit Hydrogens'), targetsOf(host), (src, atoms) => analysisApi.hydrogens(src, 'remove', atoms)); + if (!res) return; + const kept = res.reduce((n, r) => n + r.kept.length, 0); + if (kept) toast(`${kept} ${t('hydrogens kept because they carry stereo, an isotope, a charge or a map number')}`); + else if (!res.some((r) => r.count)) toast(t('No explicit hydrogens to remove.')); +} + +function abbreviationAtoms(host: ChemHost): Targets { + const doc = host.client?.doc; + if (!doc) return new Map(); + const sel = selectedAtoms(host); + const scope = sel.size ? sel : new Map(pageFragmentIds(host).map((fid) => [fid, Object.keys((doc.objects[fid] as Fragment).atoms)])); + const out: Targets = new Map(); + for (const [fid, atoms] of scope) { + const f = doc.objects[fid] as Fragment; + const hits = atoms.filter((a) => !!f.atoms[a]?.expansion); + if (hits.length) out.set(fid, hits); + } + return out; +} + +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 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)); }); + if (keys.length) host.setSelection(makeSelection(keys)); +} + +export async function contractAbbreviation(host: ChemHost): Promise { + const sel = selectedAtoms(host); + if (sel.size !== 1) { toast(t('Select the atoms of one group in one structure to contract.')); return; } + const [[fid, atoms]] = [...sel]; + if (atoms.length < 2 || isWhole(host, fid, atoms)) { toast(t('Select the group to contract, without the atom it is attached to.')); return; } + const label = await askAbbreviation({ title: t('Contract Abbreviation'), okLabel: t('Contract'), hint: t('Pick a library abbreviation or type a new label for the selected atoms.') }); + if (!label) return; + const res = await engineEdit(host, t('Contract Abbreviation'), new Map([[fid, atoms]]), (src, ids) => analysisApi.contract(src, ids ?? atoms, label)); + const atom = res?.[0]?.atom; + if (atom) host.setSelection(makeSelection([selectionKey(fid, atom)])); +} + +function stereoTargets(host: ChemHost): Map { + const client = host.client; + const out = new Map(); + if (!client) return out; + const derived = client.derived; + for (const [fid, atoms] of selectedAtoms(host)) { + const f = client.doc.objects[fid] as Fragment; + const centres = stereoCentres(f, derived?.fragments[fid]?.cip); + const hit = atoms.filter((a) => centres.has(a)); + out.set(fid, hit.length ? hit : atoms); + } + return out; +} + +export function setStereoGroup(host: ChemHost, kind: GroupKind, n?: number): boolean { + return commitPerFragment(host, t('Set Stereo Group'), stereoTargets(host), (f, ids) => stereoGroupOps(f, ids, kind, n)); +} + +export function clearStereoGroup(host: ChemHost): boolean { + return commitPerFragment(host, t('Clear Stereo Group'), stereoTargets(host), (f, ids) => clearStereoGroupOps(f, ids)); +} + +function firstTarget(host: ChemHost, groups: Map): AtomTarget | null { + const first = [...groups][0]; + const f = first && host.client?.doc.objects[first[0]]; + return f?.kind === 'fragment' ? { frag: f, atoms: first[1] } : null; +} + +export function openStereoGroupPopover(host: ChemHost, at?: { x: number; y: number }): void { + const groups = stereoTargets(host); + const first = firstTarget(host, groups); + if (!first) { toast(t(NEED_ATOMS)); return; } + const fid = first.frag.id, ids = first.atoms; + const a = first.frag.atoms[ids[0]]; + const p = at ?? host.toClient([a.x, a.y]); + openStereoPopover(p.x + 12, p.y + 12, { + target: () => { const f = host.client?.doc.objects[fid]; return f?.kind === 'fragment' ? { frag: f, atoms: ids.filter((x) => !!f.atoms[x]) } : null; }, + commit: (label, ops) => { if (ops.length) host.client?.commit(label, ops); }, + }); +} + +export async function setAtomList(host: ChemHost, groups = selectedAtoms(host)): Promise { + const first = firstTarget(host, groups); + if (!first) { toast(t(NEED_ATOMS)); return; } + const q = first.frag.atoms[first.atoms[0]]?.query; + const value = await askAtomList({ list: q?.list ?? [], not: !!q?.not }); + if (!value) return; + const label = value.list.length ? t('Set Atom List') : t('Clear Atom List'); + commitPerFragment(host, label, groups, (f, ids) => (value.list.length ? atomListOps(f, ids, value.list, value.not) : atomQueryOps(f, ids, { list: undefined, not: undefined }))); +} + +export function setQueryBond(host: ChemHost, query: BondQuery | null): boolean { + return commitPerFragment(host, query ? t('Set Query Bond') : t('Clear Bond Query'), selectedBonds(host), (f, ids) => (query ? bondQueryOps(f, ids, query) : [...bondQueryOps(f, ids, null), ...bondTopologyOps(f, ids, null)])); +} + +function nextFreeR(doc: FormChemDocument): number { + const used = usedRGroups(doc.objects); + for (let n = 1; n <= 32; n++) if (!used.has(n)) return n; + return 1; +} + +export async function defineRGroup(host: ChemHost): Promise { + const client = host.client; + const sel = selectedAtoms(host); + const first = firstTarget(host, sel); + if (!client || !first) { toast(t('Select the atom that carries the R-group.')); return; } + const core = first.frag; + const atom = core.atoms[first.atoms[0]]; + const n = atom.element === 'R#' && atom.rgroup ? atom.rgroup : nextFreeR(client.doc); + const doc = client.doc; + const candidates = pageFragmentIds(host).filter((fid) => fid !== core.id).map((fid) => { + const f = doc.objects[fid] as Fragment; + const points = attachmentAtoms(f, core.rgroups?.[String(n)]).length; + return { id: fid, label: f.name ?? (quickFormula(f, doc.expansions) || fid), detail: points === 1 ? t('1 attachment point') : `${points} ${t('attachment points')}` }; + }); + const others = [...usedRGroups(doc.objects)].sort((a, b) => a - b); + const answer = await askRGroup({ n, def: core.rgroups?.[String(n)] ?? null, candidates, others }); + if (!answer) return; + const now = client.doc.objects[core.id]; + if (now?.kind !== 'fragment') return; + const ops: Op[] = [...rgroupAtomOps(now, first.atoms.filter((a) => now.atoms[a]?.element !== 'R#' || now.atoms[a]?.rgroup !== answer.n), answer.n), ...rgroupOps(now, answer.n, answer.def)]; + if (ops.length) client.commit(answer.def ? t('Define R-Group') : t('Remove R-Group Definition'), ops); +} + +export async function assignWedges(host: ChemHost): Promise { + const res = await engineEdit(host, t('Assign Wedges'), targetsOf(host), (src, atoms) => analysisApi.wedges(src, atoms)); + if (res && !res.some((r) => r.changed.length)) toast(t('The wedges already match the stereocentres.')); +} + +function derivedRows(host: ChemHost, fids: readonly Id[]): CheckRow[] { + const client = host.client; + const d = client?.derived && client.derived.rev === client.rev ? client.derived : null; + const rows: CheckRow[] = []; + for (const fid of fids) { + const f = client?.doc.objects[fid]; + const df = d?.fragments[fid]; + if (f?.kind !== 'fragment' || !df) continue; + for (const e of df.valence_errors ?? []) { + const a = f.atoms[e.atom]; + if (!a || a.ignore_warnings) continue; + rows.push({ key: `${fid}/valence/${e.atom}`, frag: fid, severity: 'error', code: 'valence', text: `${a.label ?? a.element}: ${t('valence')} ${e.valence}, ${t('allowed')} ${e.allowed.join(', ') || '-'}`, atoms: [e.atom], bonds: [], fixable: false }); + } + for (const w of df.warnings ?? []) rows.push({ key: `${fid}/${w.code}/${(w.atoms ?? []).join(',')}/${(w.bonds ?? []).join(',')}`, frag: fid, severity: 'warning', code: w.code, text: w.text, atoms: w.atoms ?? [], bonds: w.bonds ?? [], fixable: false }); + } + return rows; +} + +export function checkStructure(host: ChemHost): void { + if (!host.client) return; + 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[] = []; + const seen = new Map(); + try { + for (const fid of fids) { + const src = sourceFor(client.doc, fid); + if (!src) continue; + const res = await analysisApi.check(src); + for (const issue of res.issues) { + const base = `${fid}/${issue.code}/${issue.atoms.join(',')}/${issue.bonds.join(',')}`; + const k = seen.get(base) ?? 0; + seen.set(base, k + 1); + const key = k ? `${base}#${k}` : base; + if (issue.fix?.ops.length) fixes.set(key, issue.fix); + 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) { + if (e instanceof ApiError && (e.status === 404 || e.status === 405)) return derivedRows(host, fids); + throw e; + } + return rows; + }, + select: (row) => { + host.setSelection(makeSelection(row.atoms.map((a) => selectionKey(row.frag, a)), row.bonds.map((b) => selectionKey(row.frag, b)))); + }, + fix: async (row) => { + const client = host.client; + const tx = fixes.get(row.key); + 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({ 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) { + toast(`${t('Fix')}: ${errText(e)}`, 'error'); + } + }, + }); +} + +export function computeProperties(): void { + setAnalysisOpen(true); + refreshAnalysis(); +} + +function mergedSource(doc: FormChemDocument, fids: readonly Id[]): Source | null { + const frags = fids.map((id) => doc.objects[id]).filter((f): f is Fragment => f?.kind === 'fragment'); + if (!frags.length) return null; + if (frags.length === 1) return sourceFor(doc, frags[0].id); + const fragment: Fragment = { id: 'f~analysis', kind: 'fragment', atoms: {}, bonds: {} }; + for (const f of frags) { Object.assign(fragment.atoms, f.atoms); Object.assign(fragment.bonds, f.bonds); } + return doc.expansions ? { fragment, expansions: doc.expansions } : { fragment }; +} + +export async function copyAnalysis(host: ChemHost, props?: Properties | null): Promise { + const client = host.client; + if (!client) return; + 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) { + 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, isotopes: await isotopes })); + toast(ok ? t('Analysis copied') : t('Could not copy to the clipboard'), ok ? 'info' : 'error'); +} + +function queryOf(host: ChemHost): { query: Fragment; from: Id } | null { + const doc = host.client?.doc; + const sel = selectedAtoms(host); + if (!doc || sel.size !== 1) return null; + const [[fid, atoms]] = [...sel]; + const f = doc.objects[fid] as Fragment; + const keep = new Set(atoms); + const query: Fragment = { id: fid, kind: 'fragment', atoms: {}, bonds: {} }; + for (const a of atoms) query.atoms[a] = f.atoms[a]; + for (const b of Object.values(f.bonds)) if (keep.has(b.a) && keep.has(b.b)) query.bonds[b.id] = b; + return { query, from: fid }; +} + +export async function searchSubstructure(host: ChemHost): Promise { + const client = host.client; + if (!client) return; + const drawn = queryOf(host); + let query: Fragment | { smarts: string }; + if (drawn) query = drawn.query; + else { + const smarts = await promptName(t('Find Substructure'), '', t('Find'), t('SMARTS')); + if (!smarts) return; + query = { smarts }; + } + const doc = client.doc; + const targets: Record = {}; + for (const fid of pageFragmentIds(host)) if (fid !== drawn?.from) targets[fid] = doc.objects[fid] as Fragment; + if (!Object.keys(targets).length) { toast(t('Draw the structures to search on this page first.')); return; } + try { + const res = await analysisApi.substructure(query, targets, { maxHits: 1000 }); + const atoms: string[] = [], bonds: string[] = []; + for (const h of res.hits) { + for (const a of h.atoms) atoms.push(selectionKey(h.object, a)); + for (const b of h.bonds) bonds.push(selectionKey(h.object, b)); + } + if (host.client === client && res.hits.length) host.setSelection(makeSelection(atoms, bonds)); + const structures = Object.keys(res.byObject).length || new Set(res.hits.map((h) => h.object)).size; + toast(res.count ? `${res.count} ${res.count === 1 ? t('match') : t('matches')} ${t('in')} ${structures} ${structures === 1 ? t('structure') : t('structures')}${res.truncated ? ` (${t('first results only')})` : ''}` : t('No matches on this page.')); + } catch (e) { + toast(`${t('Find Substructure')}: ${errText(e)}`, 'error'); + } +} + +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') { + const look = (): AtomTarget | null => { + const f = host.client?.doc.objects[hit.frag]; + if (f?.kind !== 'fragment' || !f.atoms[hit.atom]) return null; + const sel = selectedAtoms(host).get(hit.frag); + return { frag: f, atoms: sel?.includes(hit.atom) ? sel : [hit.atom] }; + }; + const openList = (): void => { const l = look(); if (l) void setAtomList(host, new Map([[l.frag.id, l.atoms]])); }; + const popover = (): void => { + const l = look(); + if (!l) return; + if (!host.selection().atoms.has(selectionKey(l.frag.id, hit.atom))) host.setSelection(makeSelection(l.atoms.map((a) => selectionKey(l.frag.id, a)))); + openStereoGroupPopover(host); + }; + const items: MenuItem[] = [atomQuerySubmenu(MENU_PREFIX, look, commit, temp, openList), stereoGroupSubmenu(MENU_PREFIX, look, commit, temp, popover)]; + if (commands.has('define-rgroup')) items.push('define-rgroup'); + const atom = look()?.frag.atoms[hit.atom]; + if (atom?.expansion && commands.has('expand-abbreviation')) items.push('expand-abbreviation'); + return items; + } + if (hit.kind === 'bond') { + const look = (): { frag: Fragment; bonds: Id[] } | null => { + const f = host.client?.doc.objects[hit.frag]; + if (f?.kind !== 'fragment' || !f.bonds[hit.bond]) return null; + const sel = selectedBonds(host).get(hit.frag); + return { frag: f, bonds: sel?.includes(hit.bond) ? sel : [hit.bond] }; + }; + return [queryBondSubmenu(MENU_PREFIX, look, commit, temp)]; + } + return []; +} + +export function registerChemCommands(deps: ChemCommandDeps): () => void { + const { host } = deps; + const open = (): boolean => !!host.client && !deps.homeOpen(); + const atomsOn = (): boolean => open() && selectedAtoms(host).size > 0; + const bondsOn = (): boolean => open() && selectedBonds(host).size > 0; + const kinds: GroupKind[] = ['abs', 'and', 'or']; + + const defs: CommandDef[] = [ + { id: 'add-hydrogens', label: () => t('Add Explicit Hydrogens'), group: 'Structure', icon: 'hydrogenAdd', mutates: true, description: '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.', when: NEED_DRAWING, enabled: open, run: () => addHydrogens(host) }, + { id: 'remove-hydrogens', label: () => t('Remove Explicit Hydrogens'), group: 'Structure', icon: 'hydrogenRemove', mutates: true, description: '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.', when: NEED_DRAWING, enabled: open, run: () => removeHydrogens(host) }, + { id: 'expand-abbreviation', label: () => t('Expand Abbreviation'), group: 'Structure', icon: 'expandAbbr', mutates: true, description: 'Replaces the selected abbreviation atoms (or every abbreviation on the page) by their full structure, laid out along the attachment bond.', when: NEED_DRAWING, enabled: open, run: () => expandAbbreviation(host) }, + { id: 'contract-abbreviation', label: () => t('Contract Abbreviation...'), group: 'Structure', icon: 'contractAbbr', mutates: true, description: 'Collapses the selected group of atoms into one abbreviation atom with the label the person picks or types.', when: NEED_ATOMS, enabled: atomsOn, run: () => contractAbbreviation(host) }, + { id: 'show-stereo', label: () => t('Show Stereochemistry'), group: 'View', icon: 'stereoCentre', description: 'Shows or hides R, S, E and Z labels next to stereocentres and stereo double bonds.', checked: () => pref('stereoLabels'), run: () => setPref('stereoLabels', !pref('stereoLabels')) }, + { id: 'show-stereo-groups', label: () => t('Show Enhanced Stereo Groups'), group: 'View', icon: 'stereoGroup', description: 'Shows or hides the abs, and and or group labels next to stereocentres while stereo labels are on.', checked: () => marksView().enhanced, run: () => { setMarksView({ enhanced: !marksView().enhanced }); } }, + { id: 'show-query-marks', label: () => t('Show Query Features'), group: 'View', icon: 'queryBond', description: 'Shows or hides atom list, query bond and R-group marks on the canvas.', checked: () => marksView().query, run: () => { setMarksView({ query: !marksView().query }); } }, + { id: 'set-stereo-group', label: () => t('Set Stereo Group'), group: 'Structure', icon: 'stereoGroup', mutates: true, description: '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.', params: { kind: { type: 'string', required: true, enum: kinds, description: 'abs, and or or' }, n: { type: 'integer', min: 1, max: 99, description: 'Group number for and and or' } }, when: NEED_ATOMS, enabled: atomsOn, run: (p) => { const kind = kinds.includes(p?.kind as GroupKind) ? (p!.kind as GroupKind) : 'abs'; setStereoGroup(host, kind, typeof p?.n === 'number' ? p.n : undefined); } }, + { id: 'set-stereo-group-abs', label: () => t('Absolute (abs)'), group: 'Structure', mutates: true, when: NEED_ATOMS, enabled: atomsOn, run: () => { setStereoGroup(host, 'abs'); } }, + { id: 'set-stereo-group-and', label: () => t('New AND Group'), group: 'Structure', mutates: true, when: NEED_ATOMS, enabled: atomsOn, run: () => { setStereoGroup(host, 'and'); } }, + { id: 'set-stereo-group-or', label: () => t('New OR Group'), group: 'Structure', mutates: true, when: NEED_ATOMS, enabled: atomsOn, run: () => { setStereoGroup(host, 'or'); } }, + { id: 'clear-stereo-group', label: () => t('Clear Stereo Group'), group: 'Structure', mutates: true, when: NEED_ATOMS, enabled: atomsOn, run: () => { clearStereoGroup(host); } }, + { id: 'stereo-group-popover', label: () => t('Stereo Group...'), group: 'Structure', icon: 'stereoGroup', when: NEED_ATOMS, enabled: atomsOn, run: () => openStereoGroupPopover(host) }, + { id: 'set-atom-list', label: () => t('Atom List...'), group: 'Structure', icon: 'atomList', mutates: true, description: 'Turns the selected atoms into an atom list or not-list query picked on the periodic table.', when: NEED_ATOMS, enabled: atomsOn, run: () => setAtomList(host) }, + { id: 'set-query-bond', label: () => t('Set Query Bond'), group: 'Structure', icon: 'queryBond', mutates: true, description: 'Makes the selected bonds query bonds: any, single_or_double, single_or_aromatic or double_or_aromatic; leave query out to clear.', params: { query: { type: 'string', enum: BOND_QUERY_LABELS.map(([q]) => q), description: 'The query bond type' } }, when: NEED_BONDS, enabled: bondsOn, run: (p) => { const q = BOND_QUERY_LABELS.find(([k]) => k === p?.query)?.[0] ?? null; setQueryBond(host, q); } }, + ...BOND_QUERY_LABELS.map(([q, name]): CommandDef => ({ id: `set-query-bond-${q}`, label: () => t(name), group: 'Structure', mutates: true, when: NEED_BONDS, enabled: bondsOn, run: () => { setQueryBond(host, q); } })), + { id: 'clear-query-bond', label: () => t('Clear Bond Query'), group: 'Structure', mutates: true, when: NEED_BONDS, enabled: bondsOn, run: () => { setQueryBond(host, null); } }, + { id: 'define-rgroup', label: () => t('Define R-Group...'), group: 'Structure', icon: 'rgroup', mutates: true, description: 'Makes the selected atom an R-group label and defines its members, occurrence, rest H and if-then condition.', when: NEED_ATOMS, enabled: atomsOn, run: () => defineRGroup(host) }, + { id: 'assign-wedges', label: () => t('Assign Wedges'), group: 'Structure', icon: 'assignWedges', mutates: true, description: 'Lets the engine choose wedge and hash bonds that express the stereocentres of the selection (or the page) unambiguously.', when: NEED_DRAWING, enabled: open, run: () => assignWedges(host) }, + { id: 'check-structure', label: () => t('Check Structure'), group: 'Structure', icon: 'approve', description: 'Lists valence, stereo, geometry and label problems of the selection (or the page) in a panel whose rows select the atoms.', when: NEED_DRAWING, enabled: open, run: () => checkStructure(host) }, + { 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', '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', 'copy-smarts'] as MenuItem[], +}; diff --git a/frontend/src/app/chem-edits.ts b/frontend/src/app/chem-edits.ts new file mode 100644 index 00000000..a7529288 --- /dev/null +++ b/frontend/src/app/chem-edits.ts @@ -0,0 +1,155 @@ +import type { AtomQuery, BondQuery, BondTopology, Fragment, Id, RGroupDef, StereoGroup } from '../engine/model'; +import { atomPath, bondPath, objectPath, sameValue, type Op } from '../engine/ops'; + +export type GroupKind = StereoGroup['kind']; +export type ChiralFlag = NonNullable; + +const setOrDrop = (path: Op['path'], before: unknown, after: unknown): Op[] => { + if (sameValue(before, after)) return []; + return after === undefined ? [{ op: 'set', path }] : [{ op: 'set', path, value: after }]; +}; + +function cleanQuery(q: AtomQuery): AtomQuery | undefined { + const out: AtomQuery = {}; + for (const [k, v] of Object.entries(q) as [keyof AtomQuery, unknown][]) { + if (v === undefined || v === null || (v === false && k !== 'aromatic')) continue; + if (Array.isArray(v) && !v.length) continue; + (out as Record)[k] = v; + } + if (!out.list) delete out.not; + return Object.keys(out).length ? out : undefined; +} + +export function atomQueryOps(frag: Fragment, atoms: readonly Id[], patch: Partial | null): Op[] { + const ops: Op[] = []; + for (const aid of atoms) { + const atom = frag.atoms[aid]; + if (!atom) continue; + const next = patch === null ? undefined : cleanQuery({ ...(atom.query ?? {}), ...patch }); + ops.push(...setOrDrop(atomPath(frag.id, aid, 'query'), atom.query, next)); + } + return ops; +} + +export function atomListOps(frag: Fragment, atoms: readonly Id[], list: readonly string[], not: boolean): Op[] { + const ops: Op[] = []; + const clean = [...new Set(list)]; + for (const aid of atoms) { + const atom = frag.atoms[aid]; + if (!atom) continue; + ops.push(...atomQueryOps(frag, [aid], clean.length ? { list: clean, not: not || undefined, generic: undefined } : { list: undefined, not: undefined })); + if (clean.length && !not && atom.element !== clean[0] && atom.element !== 'R#') ops.push({ op: 'set', path: atomPath(frag.id, aid, 'element'), value: clean[0] }); + } + return ops; +} + +export function bondQueryOps(frag: Fragment, bonds: readonly Id[], query: BondQuery | null): Op[] { + const ops: Op[] = []; + for (const bid of bonds) { + const b = frag.bonds[bid]; + if (b) ops.push(...setOrDrop(bondPath(frag.id, bid, 'query'), b.query, query ?? undefined)); + } + return ops; +} + +export function bondTopologyOps(frag: Fragment, bonds: readonly Id[], topology: BondTopology | null): Op[] { + const ops: Op[] = []; + for (const bid of bonds) { + const b = frag.bonds[bid]; + if (b) ops.push(...setOrDrop(bondPath(frag.id, bid, 'topology'), b.topology, topology ?? undefined)); + } + return ops; +} + +export function nextGroupNumber(frag: Fragment, kind: GroupKind): number { + let max = 0; + for (const g of frag.stereo_groups ?? []) if (g.kind === kind) max = Math.max(max, g.n ?? 1); + return max + 1; +} + +export function groupOf(frag: Fragment, atom: Id): StereoGroup | null { + let abs: StereoGroup | null = null; + for (const g of frag.stereo_groups ?? []) { + if (g.atoms?.includes(atom)) return g; + if (g.kind === 'abs' && !g.atoms?.length) abs = g; + } + return abs; +} + +function withoutAtoms(groups: readonly StereoGroup[], atoms: ReadonlySet): StereoGroup[] { + const out: StereoGroup[] = []; + for (const g of groups) { + if (!g.atoms) { out.push(g); continue; } + const left = g.atoms.filter((a) => !atoms.has(a)); + if (left.length === g.atoms.length) out.push(g); + else if (left.length || g.kind === 'abs') out.push(left.length ? { ...g, atoms: left } : { kind: 'abs' }); + } + return dedupeAbs(out); +} + +function dedupeAbs(groups: StereoGroup[]): StereoGroup[] { + const abs = groups.filter((g) => g.kind === 'abs'); + if (abs.length < 2) return groups; + const atoms = abs.flatMap((g) => g.atoms ?? []); + const merged: StereoGroup = abs.some((g) => !g.atoms?.length) ? { kind: 'abs' } : { kind: 'abs', atoms }; + return [merged, ...groups.filter((g) => g.kind !== 'abs')]; +} + +export function stereoGroupOps(frag: Fragment, atoms: readonly Id[], kind: GroupKind, n?: number): Op[] { + const chosen = new Set(atoms.filter((a) => !!frag.atoms[a])); + if (!chosen.size) return []; + let groups = withoutAtoms(frag.stereo_groups ?? [], chosen); + if (kind === 'abs') { + const abs = groups.find((g) => g.kind === 'abs'); + if (!abs) groups = [{ kind: 'abs', atoms: [...chosen] }, ...groups]; + else if (abs.atoms?.length) groups = groups.map((g) => (g === abs ? { kind: 'abs', atoms: [...(abs.atoms ?? []), ...chosen] } : g)); + } else { + const num = n ?? nextGroupNumber({ ...frag, stereo_groups: groups }, kind); + const at = groups.findIndex((g) => g.kind === kind && (g.n ?? 1) === num); + if (at >= 0) groups = groups.map((g, i) => (i === at ? { ...g, atoms: [...(g.atoms ?? []), ...chosen] } : g)); + else groups = [...groups, { kind, n: num, atoms: [...chosen] }]; + } + return setOrDrop(objectPath(frag.id, 'stereo_groups'), frag.stereo_groups, groups.length ? groups : undefined); +} + +export function clearStereoGroupOps(frag: Fragment, atoms: readonly Id[]): Op[] { + const groups = withoutAtoms(frag.stereo_groups ?? [], new Set(atoms)); + const keep = groups.filter((g) => g.kind !== 'abs' || g.atoms?.length || groups.some((o) => o.kind !== 'abs')); + return setOrDrop(objectPath(frag.id, 'stereo_groups'), frag.stereo_groups, keep.length ? keep : undefined); +} + +export function chiralFlagOps(frag: Fragment, flag: ChiralFlag | null): Op[] { + return setOrDrop(objectPath(frag.id, 'chiral'), frag.chiral, flag ?? undefined); +} + +export function rgroupOps(core: Fragment, n: number, def: RGroupDef | null): Op[] { + const key = String(n); + const next: Record = { ...(core.rgroups ?? {}) }; + if (def) next[key] = def; + else delete next[key]; + return setOrDrop(objectPath(core.id, 'rgroups'), core.rgroups, Object.keys(next).length ? next : undefined); +} + +export function rgroupAtomOps(frag: Fragment, atoms: readonly Id[], n: number): Op[] { + const ops: Op[] = []; + for (const aid of atoms) { + const a = frag.atoms[aid]; + if (!a) continue; + if (a.element !== 'R#') ops.push({ op: 'set', path: atomPath(frag.id, aid, 'element'), value: 'R#' }); + ops.push(...setOrDrop(atomPath(frag.id, aid, 'rgroup'), a.rgroup, n)); + if (a.label !== undefined) ops.push({ op: 'set', path: atomPath(frag.id, aid, 'label') }); + if (a.query !== undefined) ops.push({ op: 'set', path: atomPath(frag.id, aid, 'query') }); + } + return ops; +} + +export function usedRGroups(objects: Readonly>): Set { + const out = new Set(); + for (const o of Object.values(objects)) { + const f = o as Fragment; + if (f?.kind !== 'fragment') continue; + for (const a of Object.values(f.atoms)) if (a.element === 'R#' && a.rgroup) out.add(a.rgroup); + for (const k of Object.keys(f.rgroups ?? {})) out.add(Number(k)); + } + return out; +} diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index 6e94f1f0..e7e8477c 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; @@ -115,15 +119,14 @@ 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', '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; @@ -167,11 +170,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'), { 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,33 +183,9 @@ 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'), - 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'), - later('add-hydrogens', 'Add Explicit Hydrogens', 'Structure', '0.6.0'), - 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'), - later('stoichiometry-grid', 'Stoichiometry Grid', 'Reaction', '0.5.0', 'table'), - - 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'), + { 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) }, + + { 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'), later('build-3d', 'Build 3D from 2D', '3D', '0.10.0', 'model3d'), 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..966e03aa 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -1,5 +1,6 @@ import type { MenuDef, MenuItem } from '../ui/menu'; import { isMacDesktop } from '../ui/native-menu'; +import { CHEM_MENU_ITEMS } from './chem-commands'; export type MenuSource = () => MenuItem[] | null | undefined; @@ -7,7 +8,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 => { @@ -16,13 +19,13 @@ 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: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', COPY_AS, 'paste', 'duplicate', 'delete', '-', 'select-all', '-', 'find', 'find-next', 'find-previous', 'replace', ...CHEM_MENU_ITEMS.edit] }, + { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', 'clear-guides', '-', ...CHEM_MENU_ITEMS.view, '-', '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: 'Structure', items: ['clean-structure', 'layout-structure', '-', ...CHEM_MENU_ITEMS.structure, '-', 'check-structure', 'compute-properties', '-', '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] }, { 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: 'Analysis', items: ['show-analysis', ...CHEM_MENU_ITEMS.analysis] }, { label: '3D', items: ['view-3d', '-', 'build-3d', 'minimize-3d', 'conformers'] }, { label: 'Window', items: ['next-window', '-', 'agents'] }, { label: 'Extensions', items: () => { const own = extensionItems?.(); return own?.length ? own : EXTENSIONS_FALLBACK; } }, diff --git a/frontend/src/app/object-commands.ts b/frontend/src/app/object-commands.ts new file mode 100644 index 00000000..9ee35154 --- /dev/null +++ b/frontend/src/app/object-commands.ts @@ -0,0 +1,203 @@ +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'; +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 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 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'); diff --git a/frontend/src/app/reaction-commands.ts b/frontend/src/app/reaction-commands.ts new file mode 100644 index 00000000..bfcf1d8f --- /dev/null +++ b/frontend/src/app/reaction-commands.ts @@ -0,0 +1,237 @@ +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 { 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 { + 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)}`); +} + +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(); + 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: '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) }, + { 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/canvas/context.ts b/frontend/src/canvas/context.ts index d17f3233..373fde75 100644 --- a/frontend/src/canvas/context.ts +++ b/frontend/src/canvas/context.ts @@ -1,6 +1,7 @@ import { commands, type CommandDef } from '../commands/registry'; import type { DocumentClient } from '../engine/client-api'; -import { isFragment, type Atom, type Bond, type BondOrder, type BondStereo, type DoublePosition, type FormChemDocument, type Fragment, type Id } from '../engine/model'; +import { chemContextItems } from '../app/chem-commands'; +import { isFragment, type Atom, type Bond, type BondOrder, type BondStereo, type DoublePosition, type FormChemDocument, type Fragment, type Id, type Page, type Point } from '../engine/model'; import { atomPath, bondPath, deleteAtomsOps, objectPath, pagePath, type Op } from '../engine/ops'; import { t } from '../i18n'; import { openContextMenu } from '../ui/context-menu'; @@ -18,6 +19,10 @@ export interface CanvasMenuHost { zoomOut(): void; zoomFit(): void; zoom100(): void; + page(): Page | null; + style(): { bond_length: number }; + toClient(p: Point): { x: number; y: number }; + focus(): void; } export const QUICK_ELEMENTS: readonly string[] = ['C', 'H', 'N', 'O', 'S', 'P', 'F', 'Cl', 'Br', 'I']; @@ -256,9 +261,13 @@ export function canvasMenuItems(host: CanvasMenuHost, hit: Hit): { items: MenuIt const temp: Temp[] = []; const sel = host.selection(); let items: MenuItem[]; - if (hit.kind !== 'none' && hasHit(sel, hit) && selectionSize(sel) > 1) items = selectionItems(host, temp); - else if (hit.kind === 'atom') items = atomItems(host, hit.frag, hit.atom, temp); - else if (hit.kind === 'bond') items = bondItems(host, hit.frag, hit.bond, temp); + const chem = (): MenuItem[] => { + const more = chemContextItems(host, hit, temp); + return more.length ? ['-', ...more] : []; + }; + if (hit.kind !== 'none' && hasHit(sel, hit) && selectionSize(sel) > 1) items = [...selectionItems(host, temp), ...chem(), ...(sel.atoms.size > 1 ? ['contract-abbreviation'] : [])]; + else if (hit.kind === 'atom') items = [...atomItems(host, hit.frag, hit.atom, temp), ...chem()]; + else if (hit.kind === 'bond') items = [...bondItems(host, hit.frag, hit.bond, temp), ...chem()]; else if (hit.kind === 'object') { if (!hasHit(sel, hit)) host.setSelection(selectHit(hit)); items = selectionItems(host, temp); 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/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; +} 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; +} 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; diff --git a/frontend/src/canvas/marks-options.ts b/frontend/src/canvas/marks-options.ts new file mode 100644 index 00000000..5c0ed3db --- /dev/null +++ b/frontend/src/canvas/marks-options.ts @@ -0,0 +1,50 @@ +export interface MarksView { + enhanced: boolean; + query: boolean; + groupColours: boolean; +} + +export const MARKS_KEY = 'formchem.marks'; +export const MARKS_EVENT = 'fc:marks-options'; + +const DEFAULTS: MarksView = { enhanced: true, query: true, groupColours: true }; + +let current: MarksView | null = null; + +function read(): MarksView { + try { + const raw = localStorage.getItem(MARKS_KEY); + const parsed = raw ? (JSON.parse(raw) as Partial) : {}; + return { + enhanced: typeof parsed.enhanced === 'boolean' ? parsed.enhanced : DEFAULTS.enhanced, + query: typeof parsed.query === 'boolean' ? parsed.query : DEFAULTS.query, + groupColours: typeof parsed.groupColours === 'boolean' ? parsed.groupColours : DEFAULTS.groupColours, + }; + } catch { + return { ...DEFAULTS }; + } +} + +function save(v: MarksView): void { + try { localStorage.setItem(MARKS_KEY, JSON.stringify(v)); } catch { return; } +} + +export function marksView(): MarksView { + current ??= read(); + return current; +} + +export function setMarksView(patch: Partial): MarksView { + const next = { ...marksView(), ...patch }; + if (next.enhanced === current?.enhanced && next.query === current.query && next.groupColours === current.groupColours) return current; + current = next; + save(next); + document.dispatchEvent(new CustomEvent(MARKS_EVENT, { detail: next })); + return next; +} + +export function onMarksView(fn: (v: MarksView) => void): () => void { + const h = (): void => fn(marksView()); + document.addEventListener(MARKS_EVENT, h); + return () => document.removeEventListener(MARKS_EVENT, h); +} 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; +} 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/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 }; } 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; +} 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/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/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/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/index.ts b/frontend/src/canvas/render/index.ts index 645757fe..ed2be1db 100644 --- a/frontend/src/canvas/render/index.ts +++ b/frontend/src/canvas/render/index.ts @@ -2,3 +2,9 @@ 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 { mediaCache, setMediaUrl, type MediaUrl } from './image'; +export { tlcLayout, spotGeom } from './tlc'; 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/marks-layer.ts b/frontend/src/canvas/render/marks-layer.ts new file mode 100644 index 00000000..17d592a6 --- /dev/null +++ b/frontend/src/canvas/render/marks-layer.ts @@ -0,0 +1,81 @@ +import type { DocObject, Fragment, Id, Style } from '../../engine/model'; +import type { MarksView } from '../marks-options'; +import type { Box } from './geom'; +import { queryMarkSpecs, type QueryMarkOptions } from './marks-query'; +import { stereoMarkSpecs, type MarkSpec, type StereoMarkOptions } from './marks-stereo'; +import { Keyed, specKey, svgEl } from './svg'; + +export interface MarkFragment { + id: Id; + frag: Fragment; + style: Style; + colour: string; + cip?: Readonly>; +} + +export type MarkOptions = StereoMarkOptions & QueryMarkOptions; + +export function markOptionsFor(style: Style, view: MarksView): MarkOptions { + const cip = style.stereo_labels !== 'none'; + return { + cip, + enhanced: style.stereo_labels === 'cip_enhanced' || (cip && view.enhanced), + groupColours: view.groupColours, + atoms: view.query, + bonds: view.query, + rgroups: view.query, + }; +} + +interface Cached { inputs: unknown[]; marks: MarkSpec[] } + +const sameList = (a: readonly unknown[], b: readonly unknown[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); + +export class ChemMarks { + private readonly keyed: Keyed; + private readonly cache = new Map(); + + constructor(parent: SVGGElement) { + this.keyed = new Keyed(parent, (id) => svgEl('g', { class: 'fc-chem-mark', 'data-id': id })); + } + + sync( + objects: Readonly>, + frags: Iterable, + labelBox: (frag: Id, atom: Id) => Box | null, + view: MarksView, + epoch: number, + ): number { + const keep = new Set(); + const live = new Set(); + let patched = 0; + for (const f of frags) { + live.add(f.id); + const opts = markOptionsFor(f.style, view); + const optsKey = JSON.stringify(opts); + const inputs: unknown[] = [f.frag, f.cip, f.style, f.colour, optsKey, epoch, f.frag.rgroups ? objects : null]; + let hit = this.cache.get(f.id); + if (!hit || !sameList(hit.inputs, inputs)) { + const marks = [ + ...stereoMarkSpecs(f.id, f.frag, f.cip, f.style, f.colour, (a) => labelBox(f.id, a), opts), + ...queryMarkSpecs(f.id, f.frag, objects, f.style, labelBox, opts), + ]; + hit = { inputs, marks }; + this.cache.set(f.id, hit); + } + for (const m of hit.marks) { + if (keep.has(m.key)) continue; + keep.add(m.key); + if (this.keyed.patch(m.key, m.specs, specKey(m.specs))) patched++; + } + } + for (const id of [...this.cache.keys()]) if (!live.has(id)) this.cache.delete(id); + this.keyed.keep(keep); + return patched; + } + + clear(): void { + this.cache.clear(); + this.keyed.clear(); + } +} diff --git a/frontend/src/canvas/render/marks-query.ts b/frontend/src/canvas/render/marks-query.ts new file mode 100644 index 00000000..2dd61464 --- /dev/null +++ b/frontend/src/canvas/render/marks-query.ts @@ -0,0 +1,176 @@ +import type { Atom, AtomQuery, Bond, BondQuery, DocObject, Fragment, Id, RGroupDef, Style } from '../../engine/model'; +import { dirOf, fmt, type Box, type V } from './geom'; +import { freeAngles } from './label'; +import { adjacency, block, clearOf, edgeReach, fragmentBox, markAngle, type Line, type MarkSpec } from './marks-stereo'; +import { cssFamily, measure } from './measure'; +import type { NodeSpec } from './svg'; + +export interface QueryMarkOptions { atoms: boolean; bonds: boolean; rgroups: boolean } + +export const QUERY_COLOUR = '#7a3fc4'; + +const BOND_QUERY_TEXT: Readonly> = { + any: 'any', single_or_double: 'S/D', single_or_aromatic: 'S/A', double_or_aromatic: 'D/A', +}; +const MARK_SCALE = 0.7; + +const asDrawn = (n: number, prefix: string): string => `${prefix}${n === -2 ? '*' : n}`; + +export function atomListText(q: AtomQuery): string | null { + if (!q.list?.length) return null; + const list = `[${q.list.join(',')}]`; + return q.not ? `not ${list}` : list; +} + +export function atomQueryText(q: AtomQuery | undefined): string | null { + if (!q) return null; + const parts: string[] = []; + const list = atomListText(q); + if (list) parts.push(list); + else if (q.generic) parts.push(q.generic); + if (q.ring_bonds !== undefined) parts.push(asDrawn(q.ring_bonds, 'rb')); + if (q.subst !== undefined) parts.push(asDrawn(q.subst, 's')); + if (q.unsat) parts.push('u'); + if (q.h_min !== undefined) parts.push(`H${q.h_min}`); + if (q.aromatic !== undefined) parts.push(q.aromatic ? 'arom' : 'aliph'); + return parts.length ? parts.join(' ') : null; +} + +export function bondQueryText(b: Bond): string | null { + const parts: string[] = []; + if (b.query) parts.push(BOND_QUERY_TEXT[b.query]); + if (b.topology) parts.push(b.topology); + return parts.length ? parts.join(' ') : null; +} + +export function rgroupSummary(n: string, def: RGroupDef): string { + const parts = [`R${n}`]; + parts.push(`occ ${def.occurrence?.trim() || '>0'}`); + if (def.rest_h) parts.push('rest H'); + if (def.if_then) parts.push(`if R${n} then R${def.if_then}`); + return parts.join(', '); +} + +export function attachmentAtoms(member: Fragment, def?: RGroupDef): Id[] { + const declared = def?.attach?.[member.id]; + if (declared?.length) return declared.filter((id) => !!member.atoms[id]); + const degree = new Map(); + for (const b of Object.values(member.bonds)) { + degree.set(b.a, (degree.get(b.a) ?? 0) + 1); + degree.set(b.b, (degree.get(b.b) ?? 0) + 1); + } + return Object.values(member.atoms).filter((a) => a.element === '*' && !a.generic && (!a.label || a.label === '*') && (degree.get(a.id) ?? 0) === 1).map((a) => a.id); +} + +function tagLines(text: string, fill: string, cls: string): Line[] { + return [{ text, italic: false, fill, cls }]; +} + +function halo(specs: NodeSpec[], background: string): NodeSpec[] { + return specs.map((s) => ({ ...s, a: { ...s.a, stroke: background, 'stroke-width': '2.4', 'stroke-linejoin': 'round', 'paint-order': 'stroke' } })); +} + +function wavy(at: V, u: V, L: number, colour: string, width: number): NodeSpec { + const n: V = [-u[1], u[0]]; + const half = 0.32 * L, amp = 0.09 * L, waves = 4; + const seg = (2 * half) / waves; + let x = at[0] - n[0] * half, y = at[1] - n[1] * half; + let d = `M${fmt(x)} ${fmt(y)}`; + for (let k = 0; k < waves; k++) { + const s = k % 2 ? -1 : 1; + const cx = x + n[0] * seg / 2 + u[0] * amp * 2 * s, cy = y + n[1] * seg / 2 + u[1] * amp * 2 * s; + x += n[0] * seg; + y += n[1] * seg; + d += `Q${fmt(cx)} ${fmt(cy)} ${fmt(x)} ${fmt(y)}`; + } + return { tag: 'path', a: { d, fill: 'none', stroke: colour, 'stroke-width': fmt(width), 'stroke-linecap': 'round', class: 'fc-mk fc-mk-attach' } }; +} + +function textAt(x: number, y: number, text: string, style: Style, fill: string, anchor: 'start' | 'middle' | 'end', cls: string): NodeSpec { + const size = style.label_font.size * MARK_SCALE; + const cap = measure.face(style.label_font.family).cap * size; + return { + tag: 'text', + a: { 'font-family': cssFamily(style.label_font.family), 'font-size': fmt(size), 'text-anchor': anchor, fill, class: `fc-mk ${cls}` }, + spans: [{ a: { x: fmt(x), y: fmt(y + cap / 2) }, text }], + }; +} + +function atomTag(fid: Id, atom: Atom, text: string, adj: ReturnType, style: Style, boxOf: (atom: Id) => Box | null, fill: string): MarkSpec { + const nbrs = adj.get(atom.id) ?? []; + const box = boxOf(atom.id); + const near = nbrs.map((n) => boxOf(n.atom.id)).filter((b): b is Box => !!b); + const angle = freeAngles(atom, nbrs, [markAngle(atom, nbrs, !!box)])[0]; + const d = dirOf(angle); + const at: V = [atom.x, atom.y]; + const gap = box ? edgeReach(box, at, d, 0) + 0.12 * style.bond_length : 0.3 * style.bond_length; + return { key: `${fid}/${atom.id}`, specs: halo(clearOf(at, d, gap, tagLines(text, fill, 'fc-mk-query'), style, near, style.bond_length), style.background) }; +} + +export function queryMarkSpecs( + fid: Id, + frag: Fragment, + objects: Readonly>, + style: Style, + labelBox: (frag: Id, atom: Id) => Box | null, + opts: QueryMarkOptions, + fill = QUERY_COLOUR, +): MarkSpec[] { + const out: MarkSpec[] = []; + const L = style.bond_length; + if (opts.atoms) { + let adj: ReturnType | null = null; + for (const atom of Object.values(frag.atoms)) { + const text = atomQueryText(atom.query); + if (!text) continue; + adj ??= adjacency(frag); + out.push(atomTag(fid, atom, text, adj, style, (a) => labelBox(fid, a), fill)); + } + } + if (opts.bonds) { + for (const bond of Object.values(frag.bonds)) { + const text = bondQueryText(bond); + const p = frag.atoms[bond.a], q = frag.atoms[bond.b]; + if (!text || !p || !q) continue; + const l = Math.hypot(q.x - p.x, q.y - p.y) || 1; + let nrm: V = [-(q.y - p.y) / l, (q.x - p.x) / l]; + if (nrm[1] > 0 || (Math.abs(nrm[1]) < 1e-6 && nrm[0] < 0)) nrm = [-nrm[0], -nrm[1]]; + const m: V = [(p.x + q.x) / 2, (p.y + q.y) / 2]; + out.push({ key: `${fid}/${bond.id}`, specs: halo(block(m, nrm, 0.22 * L, tagLines(text, fill, 'fc-mk-qbond'), style).specs, style.background) }); + } + } + if (opts.rgroups && frag.rgroups) { + const own = fragmentBox(frag, (a) => labelBox(fid, a)); + const size = style.label_font.size * MARK_SCALE; + let line = 0; + for (const [n, def] of Object.entries(frag.rgroups).sort((p, q) => Number(p[0]) - Number(q[0]))) { + if (own) { + const y = own.y + own.h + 0.45 * L + size * (1.6 + 1.2 * line); + out.push({ key: `${fid}/~rg${n}`, specs: [textAt(own.x, y, rgroupSummary(n, def), style, fill, 'start', 'fc-mk-rgdef')] }); + line++; + } + for (const mid of def.members) { + const member = objects[mid]; + if (member?.kind !== 'fragment') continue; + const mb = fragmentBox(member, (a) => labelBox(mid, a)); + if (!mb) continue; + const specs: NodeSpec[] = [textAt(mb.x - 0.5 * L, mb.y + mb.h / 2, `R${n} =`, style, fill, 'end', 'fc-mk-rglabel')]; + const attach = attachmentAtoms(member, def); + const madj = adjacency(member); + attach.forEach((aid, i) => { + const a = member.atoms[aid]; + const nb = madj.get(aid)?.[0]?.atom; + if (!a || !nb) return; + const l = Math.hypot(a.x - nb.x, a.y - nb.y) || 1; + const u: V = [(a.x - nb.x) / l, (a.y - nb.y) / l]; + const box = labelBox(mid, aid); + const back = Math.min(l * 0.45, box ? edgeReach(box, [a.x, a.y], [-u[0], -u[1]], 0) + 0.18 * L : 0.3 * L); + specs.push(wavy([a.x - u[0] * back, a.y - u[1] * back], u, L, style.foreground, style.line_width)); + if (attach.length > 1) specs.push(textAt(a.x + u[0] * 0.35 * L, a.y + u[1] * 0.35 * L - 0.3 * L, String(i + 1), style, fill, 'middle', 'fc-mk-attach-n')); + }); + out.push({ key: `${mid}/~rg${n}`, specs }); + } + } + } + return out; +} diff --git a/frontend/src/canvas/render/marks-stereo.ts b/frontend/src/canvas/render/marks-stereo.ts new file mode 100644 index 00000000..dbac9da1 --- /dev/null +++ b/frontend/src/canvas/render/marks-stereo.ts @@ -0,0 +1,214 @@ +import type { Atom, Bond, Fragment, Id, StereoGroup, Style } from '../../engine/model'; +import { dirOf, fmt, type Box, type V } from './geom'; +import { freeAngles, type Neighbour } from './label'; +import { cssFamily, measure } from './measure'; +import type { NodeSpec, SpanSpec } from './svg'; + +export interface MarkSpec { key: string; specs: NodeSpec[] } + +export interface StereoMarkOptions { cip: boolean; enhanced: boolean; groupColours?: boolean } + +export const GROUP_COLOURS: Readonly> = { abs: null, and: '#2b6fd6', or: '#c2521f' }; + +const CENTRE_CODES = new Set(['R', 'S', 'r', 's']); +const BOND_CODES = new Set(['E', 'Z', 'M', 'P']); +const WEDGES = new Set(['wedge', 'hash', 'hollow', 'wavy']); +const MARK_SCALE = 0.7; +const LINE_GAP = 1.05; + +export function stereoGroupLabel(g: StereoGroup): string { + return g.kind === 'abs' ? 'abs' : `${g.kind}${g.n ?? 1}`; +} + +export function stereoCentres(frag: Fragment, cip?: Readonly>): Set { + const out = new Set(); + if (cip) for (const [id, code] of Object.entries(cip)) if (frag.atoms[id] && CENTRE_CODES.has(code)) out.add(id); + for (const b of Object.values(frag.bonds)) if (b.stereo && WEDGES.has(b.stereo) && frag.atoms[b.a]) out.add(b.a); + return out; +} + +export interface GroupAssignment { byAtom: Map; allAbs: boolean } + +export function assignGroups(frag: Fragment, centres: ReadonlySet): GroupAssignment { + const byAtom = new Map(); + const groups = frag.stereo_groups ?? []; + let absAll: StereoGroup | null = null; + for (const g of groups) { + if (g.kind === 'abs' && !g.atoms?.length) absAll = g; + for (const a of g.atoms ?? []) if (frag.atoms[a]) byAtom.set(a, g); + } + if (absAll) for (const a of centres) if (!byAtom.has(a)) byAtom.set(a, absAll); + let allAbs = groups.length > 0 && centres.size > 0; + for (const a of centres) if (byAtom.get(a)?.kind !== 'abs') allAbs = false; + return { byAtom, allAbs }; +} + +export function adjacency(frag: Fragment): Map { + const out = new Map(); + const push = (id: Id, n: Neighbour): void => { + const list = out.get(id); + if (list) list.push(n); + else out.set(id, [n]); + }; + for (const b of Object.values(frag.bonds)) { + const p = frag.atoms[b.a], q = frag.atoms[b.b]; + if (!p || !q) continue; + push(b.a, { atom: q, bond: b }); + push(b.b, { atom: p, bond: b }); + } + return out; +} + +export function markAngle(atom: Atom, nbrs: readonly Neighbour[], labelled: boolean): number { + const taken: number[] = []; + if (!labelled && atom.charge) taken.push(atom.charge_angle !== undefined ? (atom.charge_angle * Math.PI) / 180 : freeAngles(atom, nbrs)[0]); + if (!labelled && atom.radical && atom.radical !== 'none') taken.push(freeAngles(atom, nbrs, taken)[0]); + for (let i = 0; i < Math.min(4, atom.lone_pairs ?? 0); i++) taken.push(freeAngles(atom, nbrs, taken)[0]); + if (atom.map !== undefined) taken.push(freeAngles(atom, nbrs, taken)[0]); + return freeAngles(atom, nbrs, taken)[0]; +} + +export function edgeReach(box: Box | null, centre: V, d: V, fallback: number): number { + if (!box) return fallback; + const hx = Math.max(Math.abs(box.x - centre[0]), Math.abs(box.x + box.w - centre[0])); + const hy = Math.max(Math.abs(box.y - centre[1]), Math.abs(box.y + box.h - centre[1])); + const tx = Math.abs(d[0]) > 1e-6 ? hx / Math.abs(d[0]) : Infinity; + const ty = Math.abs(d[1]) > 1e-6 ? hy / Math.abs(d[1]) : Infinity; + return Math.min(tx, ty); +} + +export interface Line { text: string; italic: boolean; fill: string; cls: string } + +export function block(at: V, d: V, gap: number, lines: Line[], style: Style): { specs: NodeSpec[]; box: Box } { + const family = style.label_font.family; + const size = style.label_font.size * MARK_SCALE; + const widths = lines.map((l) => measure.width(l.text, size, family, false, l.italic)); + const w = Math.max(...widths); + const h = size * (1 + LINE_GAP * (lines.length - 1)); + const out = gap + Math.abs(d[0]) * (w / 2) + Math.abs(d[1]) * (h / 2); + const cx = at[0] + d[0] * out, cy = at[1] + d[1] * out; + const cap = measure.face(family).cap * size; + const top = cy - h / 2 + size / 2; + const specs: NodeSpec[] = lines.map((l, i) => { + const span: SpanSpec = { a: { x: fmt(cx), y: fmt(top + i * size * LINE_GAP + cap / 2) }, text: l.text }; + const a: Record = { + 'font-family': cssFamily(family), 'font-size': fmt(size), 'text-anchor': 'middle', fill: l.fill, class: `fc-mk ${l.cls}`, + }; + if (l.italic) a['font-style'] = 'italic'; + return { tag: 'text', a, spans: [span] }; + }); + return { specs, box: { x: cx - w / 2, y: cy - h / 2, w, h } }; +} + +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 <= 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; +} + +function bondSide(frag: Fragment, bond: Bond, m: V, nrm: V, L: number): V { + let plus = 0, minus = 0; + for (const a of Object.values(frag.atoms)) { + if (a.id === bond.a || a.id === bond.b) continue; + const dx = a.x - m[0], dy = a.y - m[1]; + if (Math.hypot(dx, dy) > 1.6 * L) continue; + if (dx * nrm[0] + dy * nrm[1] > 0) plus++; + else minus++; + } + return plus > minus ? [-nrm[0], -nrm[1]] : nrm; +} + +export function fragmentBox(frag: Fragment, labelBox: (atom: Id) => Box | null): Box | null { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const a of Object.values(frag.atoms)) { + const b = labelBox(a.id) ?? { x: a.x, y: a.y, w: 0, h: 0 }; + 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 }; +} + +export function stereoMarkSpecs( + fid: Id, + frag: Fragment, + cip: Readonly> | undefined, + style: Style, + colour: string, + labelBox: (atom: Id) => Box | null, + opts: StereoMarkOptions, +): MarkSpec[] { + if (!opts.cip && !opts.enhanced) return []; + const L = style.bond_length; + const out: MarkSpec[] = []; + const adj = adjacency(frag); + const centres = stereoCentres(frag, cip); + const groups = opts.enhanced ? assignGroups(frag, centres) : { byAtom: new Map(), allAbs: false }; + const groupFill = (g: StereoGroup): string => (opts.groupColours ? GROUP_COLOURS[g.kind] ?? colour : colour); + + const atomIds = new Set(); + if (opts.cip && cip) for (const [id, code] of Object.entries(cip)) if (frag.atoms[id] && CENTRE_CODES.has(code)) atomIds.add(id); + if (opts.enhanced && !groups.allAbs) for (const id of groups.byAtom.keys()) atomIds.add(id); + + for (const id of atomIds) { + const atom = frag.atoms[id]; + const lines: Line[] = []; + const code = opts.cip ? cip?.[id] : undefined; + if (code && CENTRE_CODES.has(code)) lines.push({ text: `(${code})`, italic: true, fill: colour, cls: 'fc-mk-cip' }); + const g = opts.enhanced && !groups.allAbs ? groups.byAtom.get(id) : undefined; + if (g) lines.push({ text: stereoGroupLabel(g), italic: false, fill: groupFill(g), cls: `fc-mk-group fc-mk-${g.kind}` }); + if (!lines.length) continue; + const box = labelBox(id); + const nbrs = adj.get(id) ?? []; + const d = dirOf(markAngle(atom, nbrs, !!box)); + const at: V = [atom.x, atom.y]; + const gap = box ? edgeReach(box, at, d, 0) + 0.12 * L : 0.3 * L; + const near = nbrs.map((n) => labelBox(n.atom.id)).filter((b): b is Box => !!b); + out.push({ key: `${fid}/${id}`, specs: clearOf(at, d, gap, lines, style, near, L) }); + } + + if (opts.cip && cip) { + for (const [id, code] of Object.entries(cip)) { + const bond = frag.bonds[id]; + if (!bond || !BOND_CODES.has(code)) continue; + const p = frag.atoms[bond.a], q = frag.atoms[bond.b]; + if (!p || !q) continue; + const m: V = [(p.x + q.x) / 2, (p.y + q.y) / 2]; + const l = Math.hypot(q.x - p.x, q.y - p.y) || 1; + const side = bondSide(frag, bond, m, [-(q.y - p.y) / l, (q.x - p.x) / l], L); + out.push({ key: `${fid}/${id}`, specs: block(m, side, 0.28 * L, [{ text: `(${code})`, italic: true, fill: colour, cls: 'fc-mk-cip' }], style).specs }); + } + } + + if (opts.enhanced) { + const flag = frag.chiral ?? (groups.allAbs ? 'abs' : null); + const fb = flag ? fragmentBox(frag, labelBox) : null; + if (flag && fb) { + const size = style.label_font.size * MARK_SCALE; + const cap = measure.face(style.label_font.family).cap * size; + out.push({ + key: `${fid}/~chiral`, + specs: [{ + tag: 'text', + a: { 'font-family': cssFamily(style.label_font.family), 'font-size': fmt(size), 'text-anchor': 'end', fill: colour, class: 'fc-mk fc-mk-flag' }, + spans: [{ a: { x: fmt(fb.x + fb.w), y: fmt(fb.y + fb.h + 0.45 * L + cap) }, text: flag }], + }], + }); + } + } + return out; +} diff --git a/frontend/src/canvas/render/objects.ts b/frontend/src/canvas/render/objects.ts new file mode 100644 index 00000000..27a6cff2 --- /dev/null +++ b/frontend/src/canvas/render/objects.ts @@ -0,0 +1,101 @@ +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 { bracketKind } from './bracket'; +import { shapeKind } from './shape'; +import { lineKind } from './line'; +import { tableKind } from './table'; +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'; + +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[]; + derived?: boolean; +} + +type Registry = { [K in ObjectKind]?: ObjectKindDef }; + +export const OBJECT_KINDS: Registry = { + arrow: arrowKind, + plus: plusKind, + bracket: bracketKind, + shape: shapeKind, + line: lineKind, + table: tableKind, + image: imageKind, + tlc: tlcKind, + orbital: orbitalKind, + group: groupKind, + text: textKind, + caption: captionKind, +}; + +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/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 }; diff --git a/frontend/src/canvas/render/paint.ts b/frontend/src/canvas/render/paint.ts new file mode 100644 index 00000000..cbb153ea --- /dev/null +++ b/frontend/src/canvas/render/paint.ts @@ -0,0 +1,87 @@ +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 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 } + +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 }] } }; +} 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 }; diff --git a/frontend/src/canvas/render/renderer.ts b/frontend/src/canvas/render/renderer.ts index bab9cc79..43737e4a 100644 --- a/frontend/src/canvas/render/renderer.ts +++ b/frontend/src/canvas/render/renderer.ts @@ -1,17 +1,19 @@ -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 { stereoMarks } from './stereo'; -import { textView } from './text'; +import { Keyed, setAttrs, svgEl, type NodeSpec } from './svg'; +import { ChemMarks, type MarkFragment } from './marks-layer'; +import { marksView, type MarksView } from '../marks-options'; import { implicitHydrogens } from './valence'; interface AtomRec { ref: Atom; h: number; view: AtomView } @@ -36,18 +38,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 { @@ -121,6 +124,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 }; @@ -142,17 +153,21 @@ 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; + let chemMarks: ChemMarks | null = null; let stereoInputs: unknown[] = []; const styleFor = (d: FormChemDocument, obj: DocObject, prev: { styleRefs: unknown[]; style: Style; styleKey: string } | undefined): { styleRefs: unknown[]; style: Style; styleKey: string } => { @@ -378,16 +393,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 +473,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 +539,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 }); @@ -504,21 +549,17 @@ export function createRenderer(): FormChemRenderer { } function syncStereo(state: RenderState, d: FormChemDocument): void { - const inputs = [d, state.derived, state.display, measure.epoch]; - if (!stereoNodes || sameList(inputs, stereoInputs)) return; + const disp = state.display; + const fallback = marksView(); + const view: MarksView = { enhanced: disp?.enhancedStereo ?? fallback.enhanced, query: disp?.queryMarks ?? fallback.query, groupColours: disp?.groupColours ?? fallback.groupColours }; + const inputs = [d, state.derived, disp, measure.epoch, view.enhanced, view.query, view.groupColours]; + if (!chemMarks || sameList(inputs, stereoInputs)) return; stereoInputs = inputs; - const keep = new Set(); + const list: MarkFragment[] = []; for (const [fid, rec] of frags) { - const frag = rec.frag; - const cip = frag && rec.derivedFor === frag ? rec.derived?.cip : undefined; - if (!frag || !cip || rec.style.stereo_labels === 'none') continue; - const marks = stereoMarks(fid, frag, cip, rec.style, rec.colour, (aid) => rec.atoms.get(aid)?.view.box ?? null); - for (const m of marks) { - keep.add(m.key); - stereoNodes.patch(m.key, m.specs); - } + if (rec.frag) list.push({ id: fid, frag: rec.frag, style: rec.style, colour: rec.colour, cip: rec.derivedFor === rec.frag ? rec.derived?.cip : undefined }); } - stereoNodes.keep(keep); + chemMarks.sync(d.objects, list, (f, a) => frags.get(f)?.atoms.get(a)?.view.box ?? null, view, measure.epoch); } function render(state: RenderState): void { @@ -527,6 +568,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 +577,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,22 +592,36 @@ 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; + 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) 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); 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,7 +655,11 @@ 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 })); - stereoNodes = new Keyed(layers.stereo, (id) => svgEl('g', { class: 'fc-stereo-mark', 'data-id': id })); + objNodes = new Keyed(layers.objects, (id) => svgEl('g', { class: 'fc-obj', 'data-id': id })); + mediaWatch = mediaCache.subscribe(() => { + if (last) render(last); + }); + chemMarks = new ChemMarks(layers.stereo); selection = new MarkLayer(layers.selection, 'fc-sel'); hover = new MarkLayer(layers.hover, 'fc-hover'); warnings = new MarkLayer(layers.warnings, 'fc-warn', 1.25); @@ -621,6 +682,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,15 +702,21 @@ 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 = []; - stereoNodes = null; + chemMarks?.clear(); + chemMarks = null; svg = null; root = null; pageRect = null; 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 }; diff --git a/frontend/src/canvas/render/stereo.ts b/frontend/src/canvas/render/stereo.ts deleted file mode 100644 index 0453cd66..00000000 --- a/frontend/src/canvas/render/stereo.ts +++ /dev/null @@ -1,65 +0,0 @@ -import type { Fragment, Id, Style } from '../../engine/model'; -import { fmt, type Box, type V } from './geom'; -import { cssFamily } from './measure'; -import type { NodeSpec } from './svg'; - -export interface StereoMark { key: string; specs: NodeSpec[] } - -function textSpec(at: V, text: string, style: Style, colour: string): NodeSpec { - const size = style.label_font.size * 0.7; - return { - tag: 'text', - a: { - x: fmt(at[0]), y: fmt(at[1]), 'font-family': cssFamily(style.label_font.family), 'font-size': fmt(size), 'font-style': 'italic', - 'text-anchor': 'middle', 'dominant-baseline': 'central', fill: colour, class: 'fc-stereo', - }, - spans: [{ a: {}, text: `(${text})` }], - }; -} - -function awayFrom(origin: V, others: readonly V[]): V { - let x = 0, y = 0; - for (const o of others) { - const dx = o[0] - origin[0], dy = o[1] - origin[1]; - const l = Math.hypot(dx, dy) || 1; - x -= dx / l; - y -= dy / l; - } - const l = Math.hypot(x, y); - return l < 1e-3 ? [0, -1] : [x / l, y / l]; -} - -export function stereoMarks(fid: Id, frag: Fragment, cip: Readonly>, style: Style, colour: string, labelBox: (atom: Id) => Box | null): StereoMark[] { - const L = style.bond_length; - const out: StereoMark[] = []; - const nbrs = new Map(); - for (const b of Object.values(frag.bonds)) { - const p = frag.atoms[b.a], q = frag.atoms[b.b]; - if (!p || !q) continue; - (nbrs.get(b.a) ?? nbrs.set(b.a, []).get(b.a)!).push([q.x, q.y]); - (nbrs.get(b.b) ?? nbrs.set(b.b, []).get(b.b)!).push([p.x, p.y]); - } - let cx = 0, cy = 0, n = 0; - for (const a of Object.values(frag.atoms)) { cx += a.x; cy += a.y; n++; } - const centre: V = n ? [cx / n, cy / n] : [0, 0]; - for (const [id, code] of Object.entries(cip)) { - const atom = frag.atoms[id]; - if (atom) { - const at: V = [atom.x, atom.y]; - const dir = awayFrom(at, nbrs.get(id) ?? []); - const box = labelBox(id); - const reach = box ? Math.max(box.w, box.h) / 2 + 0.3 * L : 0.45 * L; - out.push({ key: `${fid}/${id}`, specs: [textSpec([at[0] + dir[0] * reach, at[1] + dir[1] * reach], code, style, colour)] }); - continue; - } - const bond = frag.bonds[id]; - const p = bond && frag.atoms[bond.a], q = bond && frag.atoms[bond.b]; - if (!p || !q) continue; - const m: V = [(p.x + q.x) / 2, (p.y + q.y) / 2]; - const l = Math.hypot(q.x - p.x, q.y - p.y) || 1; - let nrm: V = [-(q.y - p.y) / l, (q.x - p.x) / l]; - if ((m[0] - centre[0]) * nrm[0] + (m[1] - centre[1]) * nrm[1] < 0) nrm = [-nrm[0], -nrm[1]]; - out.push({ key: `${fid}/${id}`, specs: [textSpec([m[0] + nrm[0] * 0.5 * L, m[1] + nrm[1] * 0.5 * L], code, style, colour)] }); - } - return out; -} 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(); diff --git a/frontend/src/canvas/render/table.ts b/frontend/src/canvas/render/table.ts new file mode 100644 index 00000000..f8d7d6d5 --- /dev/null +++ b/frontend/src/canvas/render/table.ts @@ -0,0 +1,120 @@ +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 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 | null, given: boolean): GridCell { + return cell(sig(v), { i: !given && v !== null, align: 'r' }); +} + +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.name, { formula: r.name === r.formula }), + cell(role), + 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.massMg, r.typed.mass_mg !== undefined), + numCell(r.volumeMl, r.typed.volume_ml !== 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 !== 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; +} + +function stoichGrid(obj: TableObject, ctx: ObjectCtx): Grid | null { + if (!obj.stoich) return null; + 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 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; + 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 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])]; +} + +export const tableKind: ObjectKindDef<'table'> = { view: tableView, deps: tableDeps, derived: true }; diff --git a/frontend/src/canvas/render/tlc.ts b/frontend/src/canvas/render/tlc.ts new file mode 100644 index 00000000..de056b3b --- /dev/null +++ b/frontend/src/canvas/render/tlc.ts @@ -0,0 +1,111 @@ +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'; + +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); + 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) 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.7; + 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 }; diff --git a/frontend/src/canvas/rulers.ts b/frontend/src/canvas/rulers.ts new file mode 100644 index 00000000..fe345f51 --- /dev/null +++ b/frontend/src/canvas/rulers.ts @@ -0,0 +1,336 @@ +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; + +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 UNITS: Units[] = ['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; + notches: Map; +} + +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; + 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, 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 && (UNITS as string[]).includes(saved)) this.override = saved as Units; + 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); + 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 { return this.override === 'doc' ? this.docUnits() : this.override; } + + private docUnits(): Units { + 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.syncGuides(); + this.layout(); + } + + private cycleUnits(): void { + const next = UNITS[(UNITS.indexOf(this.units()) + 1) % UNITS.length]; + this.override = next === this.docUnits() ? 'doc' : next; + 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); + this.placeNotches(); + } + + 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/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/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/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/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 }; 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/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); 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/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 170598f0..99aebd1f 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -1,11 +1,22 @@ 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 { CaptionTool } from './caption'; 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'; +import { PlusTool } from './plus'; 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 => ({ @@ -26,6 +37,22 @@ 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), +}); + +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) }, @@ -49,7 +76,38 @@ 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'), + 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: '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: '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') }, + { 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: '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'), + 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() }, ]; @@ -58,12 +116,24 @@ 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 { BracketTool, editBracketLabel } from './bracket'; +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'; +export { OrbitalTool, orbitalObject, type OrbitalType } from './orbital'; +export { PlusTool } from './plus'; 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/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; + } +} 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/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; + } +} 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); + } +} diff --git a/frontend/src/canvas/tools/select.ts b/frontend/src/canvas/tools/select.ts index 42c7cd75..810463c6 100644 --- a/frontend/src/canvas/tools/select.ts +++ b/frontend/src/canvas/tools/select.ts @@ -6,6 +6,8 @@ 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 { groupHit } from './objects'; import { hoverKey } from './hotkeys'; import { nudge, rotateHandle, rotateSelection, selectionBounds, translateSelection } from './transform'; @@ -17,6 +19,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 +155,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); @@ -160,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)); @@ -183,9 +191,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 +228,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 +311,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); 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; + } +} 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; + } +} 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; + } +} diff --git a/frontend/src/canvas/tools/transform.ts b/frontend/src/canvas/tools/transform.ts index f23e8598..6c177acc 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,9 +161,25 @@ 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 }); + 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] }); } } diff --git a/frontend/src/canvas/types.ts b/frontend/src/canvas/types.ts index 7ee86a3f..9d13b8e1 100644 --- a/frontend/src/canvas/types.ts +++ b/frontend/src/canvas/types.ts @@ -24,6 +24,9 @@ export interface RenderDisplay { aromaticCircle: boolean; valenceWarnings: boolean; stereoLabels: boolean; + enhancedStereo?: boolean; + queryMarks?: boolean; + groupColours?: boolean; } export interface RenderState { diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 8ef7aa92..581addd9 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -6,9 +6,11 @@ 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'; +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,9 +24,14 @@ 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']); +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; @@ -152,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(); @@ -287,7 +296,7 @@ export class CanvasView { this.activate(); } this.fitIfReady(); - this.viewDirty = true; + this.viewDirty = this.renderDirty = true; this.invalidate(); this.emit('client'); this.emit('selection'); @@ -398,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 { @@ -584,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(); @@ -609,6 +654,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); } 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; +} diff --git a/frontend/src/chem/stoich-ops.ts b/frontend/src/chem/stoich-ops.ts new file mode 100644 index 00000000..8943c247 --- /dev/null +++ b/frontend/src/chem/stoich-ops.ts @@ -0,0 +1,112 @@ +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, 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'; + +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; +} + +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/chem/stoich.ts b/frontend/src/chem/stoich.ts new file mode 100644 index 00000000..64d3e5ce --- /dev/null +++ b/frontend/src/chem/stoich.ts @@ -0,0 +1,242 @@ +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); + 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) { + 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; +} diff --git a/frontend/src/engine/analysis-api.ts b/frontend/src/engine/analysis-api.ts new file mode 100644 index 00000000..ce22b309 --- /dev/null +++ b/frontend/src/engine/analysis-api.ts @@ -0,0 +1,324 @@ +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'; + +export const ANALYSIS = '/api/analysis'; + +export interface Source { + fragment: Fragment; + expansions?: Record; + members?: Record; +} + +export interface EngineTx { label: string; ops: Op[] } + +export interface EngineWarning { code?: string; text: string; atoms?: Id[]; bonds?: Id[] } + +export type Severity = 'error' | 'warning' | 'info'; + +export interface CheckIssue { + code: string; + severity: Severity; + text: string; + atoms: Id[]; + bonds: Id[]; + fix?: EngineTx | null; + fixCommand?: 'wedges' | 'expand'; +} + +export interface CheckResult { issues: CheckIssue[]; counts: Record } + +export interface PropertyValue { value: number | string | null; method?: string; unit?: string; note?: string } + +export type PropertyKey = + | 'formula' | 'mw' | 'exact_mass' | 'mz' | 'charge' | 'clogp' | 'tpsa' | 'mr' | 'hbd' | 'hba' | 'rotatable' | 'heavy_atoms' | 'rings' | 'aromatic_rings' | 'fsp3' | 'stereocentres'; + +export interface LipinskiRule { rule: string; value: number | null; limit: number; pass: boolean } + +export interface Properties { + values: Partial>; + elemental: Record; + lipinski: { violations: number; rules: LipinskiRule[]; method?: string } | null; + warnings: EngineWarning[]; +} + +export interface StereoInfo { cip: Record; centres: Id[]; undefined_centres: Id[] } + +export interface Abbreviation { label: string; reversed: string; smiles: string; category: string; source: 'builtin' | 'user' } + +export interface SubstructureHit { object: Id; atoms: Id[]; bonds: Id[]; map: Record } + +export interface SubstructureResult { hits: SubstructureHit[]; count: number; byObject: Record; truncated: boolean; warnings: EngineWarning[] } + +type Rec = Record; +const isRec = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v); +const ids = (v: unknown): Id[] => (Array.isArray(v) ? v.filter((x): x is Id => typeof x === 'string') : []); +const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null); + +export function sourceFor(doc: FormChemDocument, fid: Id): Source | null { + const frag = doc.objects[fid]; + if (frag?.kind !== 'fragment') return null; + const src: Source = { fragment: frag }; + if (doc.expansions && Object.keys(doc.expansions).length) src.expansions = doc.expansions; + if (frag.rgroups) { + const members: Record = {}; + for (const def of Object.values(frag.rgroups)) { + for (const m of def.members) { + const o = doc.objects[m]; + if (o?.kind === 'fragment') members[m] = o; + } + } + if (Object.keys(members).length) src.members = members; + } + return src; +} + +function txOf(v: unknown): EngineTx | null { + if (!isRec(v) || !Array.isArray(v.ops)) return null; + return { label: typeof v.label === 'string' ? v.label : '', ops: v.ops as Op[] }; +} + +function warningsOf(v: unknown): EngineWarning[] { + if (!Array.isArray(v)) return []; + const out: EngineWarning[] = []; + for (const w of v) { + if (typeof w === 'string') out.push({ text: w }); + else if (isRec(w) && typeof w.text === 'string') out.push({ code: typeof w.code === 'string' ? w.code : undefined, text: w.text, atoms: ids(w.atoms), bonds: ids(w.bonds) }); + } + return out; +} + +const SEVERITIES: readonly Severity[] = ['error', 'warning', 'info']; + +function issueOf(v: unknown): CheckIssue | null { + if (!isRec(v)) return 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'; + 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', 'formal_charge'], + clogp: ['clogp', 'logp', 'crippen_logp'], + tpsa: ['tpsa', 'psa'], + mr: ['mr', 'molar_refractivity'], + hbd: ['hbd', 'donors', 'h_donors'], + hba: ['hba', 'acceptors', 'h_acceptors'], + rotatable: ['rotatable', 'rotatable_bonds', 'rot_bonds'], + heavy_atoms: ['heavy_atoms'], + rings: ['rings', 'ring_count'], + aromatic_rings: ['aromatic_rings', 'aromatic_ring_count'], + fsp3: ['fsp3', 'fraction_csp3'], + stereocentres: ['stereocentres', 'stereocenters'], +}; + +function valueOf(raw: unknown, methods: Rec): PropertyValue | null { + if (typeof raw === 'number' || typeof raw === 'string') return { value: raw }; + if (!isRec(raw)) return null; + const value = typeof raw.value === 'number' || typeof raw.value === 'string' ? raw.value : null; + const out: PropertyValue = { value }; + const method = typeof raw.method === 'string' ? raw.method : typeof methods.method === 'string' ? methods.method : undefined; + if (method) out.method = method; + if (typeof raw.unit === 'string') out.unit = raw.unit; + if (typeof raw.note === 'string') out.note = raw.note; + return out; +} + +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(flat[n], {}); + if (!pv) continue; + const m = methods[key] ?? methods[n]; + if (!pv.method && typeof m === 'string') pv.method = m; + values[key] = pv; + break; + } + } + const elemental: Record = {}; + if (isRec(r.elemental_analysis)) for (const [el, pct] of Object.entries(r.elemental_analysis)) { const n = num(pct); if (n !== null) elemental[el] = n; } + let lipinski: Properties['lipinski'] = null; + if (isRec(r.lipinski)) { + const L = r.lipinski; + const rules: LipinskiRule[] = []; + const list = Array.isArray(L.rules) ? L.rules : []; + 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 }; + } + return { values, elemental, lipinski, warnings: warningsOf(r.warnings) }; +} + +export function stereoOf(v: unknown): StereoInfo { + const r = isRec(v) ? v : {}; + const cip: Record = {}; + 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 { + const out: Record = {}; + const frags = isRec(res) && isRec(res.fragments) ? res.fragments : {}; + for (const [fid, v] of Object.entries(frags)) out[fid] = read(v); + return out; +} + +function checkOf(v: unknown): CheckResult { + const r = isRec(v) ? v : {}; + const issues = (Array.isArray(r.issues) ? r.issues : []).map(issueOf).filter((x): x is CheckIssue => !!x); + const counts: Record = { error: 0, warning: 0, info: 0 }; + for (const i of issues) counts[i.severity]++; + return { issues, counts }; +} + +let abbreviationCache: Promise | null = null; + +export const analysisApi = { + abbreviations(fresh = false): Promise { + if (!abbreviationCache || fresh) { + abbreviationCache = get<{ abbreviations?: unknown }>(`${ANALYSIS}/abbreviations`).then((r) => { + const list = Array.isArray(r.abbreviations) ? r.abbreviations : []; + return list.filter(isRec).filter((a) => typeof a.label === 'string').map((a) => ({ + label: a.label as string, + reversed: typeof a.reversed === 'string' ? a.reversed : (a.label as string), + smiles: typeof a.smiles === 'string' ? a.smiles : '', + category: typeof a.category === 'string' ? a.category : '', + source: a.source === 'user' ? 'user' : 'builtin', + })); + }); + abbreviationCache.catch(() => { abbreviationCache = null; }); + } + return abbreviationCache; + }, + + async properties(src: Source, signal?: AbortSignal): Promise { + const res = await post(`${ANALYSIS}/properties`, src, signal); + const all = perFragment(res, propertiesOf); + return all[src.fragment.id] ?? Object.values(all)[0] ?? propertiesOf({}); + }, + + async cip(src: Source, signal?: AbortSignal): Promise { + const res = await post(`${ANALYSIS}/cip`, src, signal); + const all = perFragment(res, stereoOf); + return all[src.fragment.id] ?? Object.values(all)[0] ?? stereoOf({}); + }, + + async stereoGroups(src: Source, change: { set?: { kind: 'abs' | 'and' | 'or'; atoms: Id[]; n?: number }; chiral?: 'absolute' | 'relative' | 'racemic' | null }): Promise<{ tx: EngineTx | null; cxsmiles: string; warnings: EngineWarning[] }> { + const r = await post(`${ANALYSIS}/stereo-groups`, { ...src, ...change }); + return { tx: txOf(r.tx), cxsmiles: typeof r.cxsmiles === 'string' ? r.cxsmiles : '', warnings: warningsOf(r.warnings) }; + }, + + async wedges(src: Source, atoms?: Id[]): Promise<{ tx: EngineTx | null; changed: Id[]; cip: Record; warnings: EngineWarning[] }> { + const r = await post(`${ANALYSIS}/wedges`, atoms ? { ...src, atoms } : src); + return { tx: txOf(r.tx), changed: ids(r.changed), cip: stereoOf(r).cip, warnings: warningsOf(r.warnings) }; + }, + + async check(src: Source, query = false, signal?: AbortSignal): Promise { + const res = await post(`${ANALYSIS}/check`, query ? { ...src, query: true } : src, signal); + const all = perFragment(res, checkOf); + return all[src.fragment.id] ?? Object.values(all)[0] ?? checkOf({}); + }, + + 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; + const r = await post(`${ANALYSIS}/expand`, body); + const expanded: Record = {}; + if (isRec(r.expanded)) for (const [k, v] of Object.entries(r.expanded)) expanded[k] = ids(v); + return { tx: txOf(r.tx), expanded, warnings: warningsOf(r.warnings) }; + }, + + async contract(src: Source, atoms: Id[], label?: string): Promise<{ tx: EngineTx | null; atom: Id | null; label: string; warnings: EngineWarning[] }> { + const r = await post(`${ANALYSIS}/contract`, label ? { ...src, atoms, label } : { ...src, atoms }); + return { tx: txOf(r.tx), atom: typeof r.atom === 'string' ? r.atom : null, label: typeof r.label === 'string' ? r.label : label ?? '', warnings: warningsOf(r.warnings) }; + }, + + async hydrogens(src: Source, mode: 'add' | 'remove', atoms?: Id[]): Promise<{ tx: EngineTx | null; count: number; kept: Id[]; warnings: EngineWarning[] }> { + const r = await post(`${ANALYSIS}/${mode === 'add' ? 'add-h' : 'remove-h'}`, atoms?.length ? { ...src, atoms } : src); + let count = 0; + if (mode === 'add' && isRec(r.added)) for (const v of Object.values(r.added)) count += ids(v).length; + if (mode === 'remove') count = ids(r.removed).length; + 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; + if (opts.chirality) body.chirality = true; + const r = await post(`${ANALYSIS}/substructure`, body, signal); + const hits: SubstructureHit[] = []; + for (const h of Array.isArray(r.hits) ? r.hits : []) { + if (!isRec(h) || typeof h.object !== 'string') continue; + const map: Record = {}; + if (isRec(h.map)) for (const [k, v] of Object.entries(h.map)) if (typeof v === 'string') map[k] = v; + hits.push({ object: h.object, atoms: ids(h.atoms), bonds: ids(h.bonds), map }); + } + const byObject: Record = {}; + if (isRec(r.by_object)) for (const [k, v] of Object.entries(r.by_object)) { const n = num(v); if (n !== null) byObject[k] = n; } + return { hits, count: num(r.count) ?? hits.length, byObject, truncated: r.truncated === true, warnings: warningsOf(r.warnings) }; + }, +}; 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 } diff --git a/frontend/src/engine/model.ts b/frontend/src/engine/model.ts index c57c9d37..3201b2ec 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'; @@ -77,6 +95,7 @@ export interface AtomQuery { unsat?: boolean; h_min?: number; aromatic?: boolean; + smarts?: string; } export interface Atom { @@ -141,7 +160,7 @@ export interface ObjectBase { } export interface StereoGroup { kind: 'abs' | 'and' | 'or'; n?: number; atoms?: Id[] } -export interface RGroupDef { members: Id[]; occurrence?: string; rest_h?: boolean; if_then?: number } +export interface RGroupDef { members: Id[]; occurrence?: string; rest_h?: boolean; if_then?: number; attach?: Record } export interface Fragment extends ObjectBase { kind: 'fragment'; @@ -257,6 +276,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 { @@ -353,7 +373,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', 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()), +}; diff --git a/frontend/src/i18n/keys/part05.json b/frontend/src/i18n/keys/part05.json new file mode 100644 index 00000000..99db049d --- /dev/null +++ b/frontend/src/i18n/keys/part05.json @@ -0,0 +1,162 @@ +[ +"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.", +"Clear Guides", +"Removes every ruler guide from the active drawing in this window. Guides are never saved in the document.", +"Drag a guide out of a ruler first", +"Open the find bar and type what to find first", +"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.", +"Find Next", +"Selects the next find match and pans to it when it is off screen.", +"Find Previous", +"Selects the previous find match and pans to it when it is off screen.", +"Replace...", +"Opens the find bar with its Replace row. Replace changes the current text match; Replace All changes every text match in one undo step.", +"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.", +"Stoichiometry Panel", +"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.", +"Template id from GET /api/templates, such as benzene or l-alanine; leave it out to open the library", +"Arrives in 0.6.0; until then Perceive Reactions sets the roles from the drawing", +"Insert Stoichiometry Table", +"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.", +"Draw a reaction with an arrow first", +"Copy Reaction As", +"Export Reaction", +"Draw a reaction arrow with reactants and products first", +"No reaction found: draw an arrow with structures on both sides.", +"The step has no atom mapping.", +"Check Balance", +"The reaction is balanced.", +"The reaction is not balanced.", +"{0}: {1} / {2} g/mol", +"Balance", +"Balanced the reaction.", +"Could not balance the reaction", +"The reaction is already balanced.", +"the clipboard is not available", +"Insert Reaction", +"Reaction SMILES or RXN", +"Perceive Reactions", +"Reads the reaction arrows on the page and stores each step with its reactants, products, agents and conditions, as one undo step.", +"Could not perceive the reactions", +"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.", +"Could not map the atoms", +"Removes the atom map numbers and reacting-centre marks of the selected reaction step.", +"Could not clear the mapping", +"Check Balance...", +"Shows the element, charge and mass balance of the selected reaction step, with a suggestion when it is not balanced.", +"Could not check the reaction", +"Balance Reaction", +"Sets the coefficients of the selected reaction step to the balanced values, as one undo step.", +"Copy Reaction SMILES", +"Could not copy the reaction", +"Copy Reaction as RXN", +"Export Reaction SMILES...", +"Could not export the reaction", +"Export Reaction as RXN...", +"Insert Reaction from Clipboard", +"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.", +"Could not insert the reaction", +"Compound", +"Role", +"MW", +"Equiv", +"Mass (mg)", +"Volume (mL)", +"Theoretical yield", +"Yield", +"Ruler units follow the drawing; click to change", +"Ruler units; click to change", +"Add arrow", +"Set bracket label", +"Add bracket", +"Add compound number", +"Add caption", +"Add electron-pushing arrow", +"Add fishhook arrow", +"Bend arrow", +"Move arrow end", +"Move point", +"Resize", +"Add image", +"Caption", +"Reaction arrow", +"Equilibrium arrow", +"Retrosynthetic arrow", +"Resonance arrow", +"No-go arrow", +"Dashed arrow", +"Line arrow", +"Electron-pushing arrow", +"Fishhook arrow", +"Plus sign", +"Equals sign", +"Adduct dot", +"Round brackets", +"Square brackets", +"Curly braces", +"Rectangle", +"Rounded rectangle", +"Ellipse", +"Polygon", +"Line and polyline", +"TLC plate", +"Image", +"p orbital", +"s orbital", +"d orbital", +"dz2 orbital", +"sp hybrid orbital", +"Sigma bond orbital", +"Pi bond orbital", +"Add line", +"Add orbital", +"Add plus sign", +"Add shape", +"Add table", +"Add TLC plate", +"Add TLC spot", +"Find text, labels, formulas or SMILES", +"Find", +"Replace with", +"Show Replace", +"Match Case", +"{0} (Shift+F3)", +"Previous Match", +"Next Match", +"{0} (Esc)", +"Replace", +"Replace All", +"No results", +"Hide Replace", +"Replaced 1 match", +"Replaced {0} matches", +"Component", +"Mass", +"Volume", +"Density", +"Conc", +"Purity", +"Reactant", +"Reagent", +"Product", +"Auto", +"{0} mg · {1} mmol", +"Edit Stoichiometry", +"{0} (mg)", +"{0} (mL)", +"Isolated", +"Not Found", +"The template is empty.", +"Inserted template {0} ({1}) into \"{2}\" ({3}) as one undo step", +"Insert Template", +"Search templates", +"Template categories", +"Loading templates...", +"No templates match this search.", +"Arrows", +"Symbols", +"Brackets", +"Orbitals", +"Shapes", +"TLC" +] 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" +] diff --git a/frontend/src/i18n/locales/cs/part05.json b/frontend/src/i18n/locales/cs/part05.json new file mode 100644 index 00000000..520906c4 --- /dev/null +++ b/frontend/src/i18n/locales/cs/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Zobrazí nebo skryje pravítka podél horního a levého okraje plátna v jednotkách výkresu (kliknutím na roh přepnete jednotky). Tažením z pravítka umístíte vodicí linku; tažením vodicí linky zpět na pravítko ji odstraníte. Volba se pamatuje.", + "1": "Vymazat vodicí linky", + "2": "Odebere všechny vodicí linky pravítek z aktivního výkresu v tomto okně. Vodicí linky se nikdy neukládají do dokumentu.", + "3": "Nejprve vytáhněte vodicí linku z pravítka", + "4": "Otevřete panel hledání a nejprve zadejte, co hledat", + "5": "Otevře panel hledání nad plátnem. Najde text, popisky, buňky tabulek, popisky atomů a zkratky, značky prvků, vzorce jako C2H6O a SMILES v aktivním výkresu; Enter nebo F3 přejde na další shodu a vybere ji.", + "6": "Najít další", + "7": "Vybere další nalezenou shodu a posune zobrazení k ní, pokud je mimo obrazovku.", + "8": "Najít předchozí", + "9": "Vybere předchozí nalezenou shodu a posune zobrazení k ní, pokud je mimo obrazovku.", + "10": "Nahradit...", + "11": "Otevře panel hledání s řádkem pro nahrazení. Nahradit změní aktuální textovou shodu; Nahradit vše změní všechny textové shody v jednom kroku zpět.", + "12": "Vyžádá si od uživatele obrázek PNG, JPEG, GIF, WebP nebo SVG a umístí jej doprostřed viditelné stránky v jednom kroku zpět.", + "13": "Panel stechiometrie", + "14": "Otevře knihovnu šablon; s id vloží danou šablonu (s novými id, přizpůsobenou délce vazby výkresu) na střed zobrazení aktivního výkresu nebo nového výkresu v jednom kroku zpět. GET /api/templates vypíše id.", + "15": "Id šablony z GET /api/templates, například benzene nebo l-alanine; vynechejte pro otevření knihovny", + "16": "Přibude ve verzi 0.6.0; do té doby nastaví role podle výkresu Rozpoznat reakce", + "17": "Vložit tabulku stechiometrie", + "18": "Vloží mřížku stechiometrie vybraného kroku reakce jako tabulku pod reakci, nebo obnoví tabulku již navázanou na tento krok, v jednom kroku zpět.", + "19": "Nejprve nakreslete reakci se šipkou", + "20": "Kopírovat reakci jako", + "21": "Exportovat reakci", + "22": "Nejprve nakreslete reakční šipku s reaktanty a produkty", + "23": "Nenalezena žádná reakce: nakreslete šipku se strukturami po obou stranách.", + "24": "Krok nemá mapování atomů.", + "25": "Zkontrolovat bilanci", + "26": "Reakce je vyčíslená.", + "27": "Reakce není vyčíslená.", + "28": "{0}: {1} / {2} g/mol", + "29": "Vyčíslit", + "30": "Reakce byla vyčíslena.", + "31": "Reakci se nepodařilo vyčíslit", + "32": "Reakce je již vyčíslená.", + "33": "schránka není dostupná", + "34": "Vložit reakci", + "35": "SMILES reakce nebo RXN", + "36": "Rozpoznat reakce", + "37": "Přečte reakční šipky na stránce a uloží každý krok s jeho reaktanty, produkty, činidly a podmínkami v jednom kroku zpět.", + "38": "Reakce se nepodařilo rozpoznat", + "39": "Mapuje atomy vybraného kroku reakce (nejprve rozpozná reakce, pokud žádná není uložena) a označí vazby zanikající, vznikající a měněné v jednom kroku zpět.", + "40": "Atomy se nepodařilo namapovat", + "41": "Odebere čísla mapování atomů a značky reakčního centra vybraného kroku reakce.", + "42": "Mapování se nepodařilo vymazat", + "43": "Zkontrolovat bilanci...", + "44": "Zobrazí bilanci prvků, náboje a hmotnosti vybraného kroku reakce s návrhem, pokud není vyčíslený.", + "45": "Reakci se nepodařilo zkontrolovat", + "46": "Vyčíslit reakci", + "47": "Nastaví koeficienty vybraného kroku reakce na vyčíslené hodnoty v jednom kroku zpět.", + "48": "Kopírovat SMILES reakce", + "49": "Reakci se nepodařilo zkopírovat", + "50": "Kopírovat reakci jako RXN", + "51": "Exportovat SMILES reakce...", + "52": "Reakci se nepodařilo exportovat", + "53": "Exportovat reakci jako RXN...", + "54": "Vložit reakci ze schránky", + "55": "Přečte SMILES reakce nebo soubor RXN ze schránky a rozloží jej na stránce s nastavenými rolemi v jednom kroku zpět.", + "56": "Reakci se nepodařilo vložit", + "57": "Sloučenina", + "58": "Role", + "59": "MW", + "60": "Ekv", + "61": "Hmotnost (mg)", + "62": "Objem (mL)", + "63": "Teoretický výtěžek", + "64": "Výtěžek", + "65": "Jednotky pravítka sledují výkres; kliknutím změníte", + "66": "Jednotky pravítka; kliknutím změníte", + "67": "Přidat šipku", + "68": "Nastavit popisek závorky", + "69": "Přidat závorku", + "70": "Přidat číslo sloučeniny", + "71": "Přidat popisek", + "72": "Přidat šipku pohybu elektronů", + "73": "Přidat šipku pohybu jednoho elektronu", + "74": "Ohnout šipku", + "75": "Přesunout konec šipky", + "76": "Přesunout bod", + "77": "Změnit velikost", + "78": "Přidat obrázek", + "79": "Popisek", + "80": "Reakční šipka", + "81": "Rovnovážná šipka", + "82": "Retrosyntetická šipka", + "83": "Rezonanční šipka", + "84": "Přeškrtnutá šipka", + "85": "Čárkovaná šipka", + "86": "Čára se šipkou", + "87": "Šipka pohybu elektronů", + "88": "Šipka pohybu jednoho elektronu", + "89": "Znaménko plus", + "90": "Znaménko rovná se", + "91": "Tečka aduktu", + "92": "Kulaté závorky", + "93": "Hranaté závorky", + "94": "Složené závorky", + "95": "Obdélník", + "96": "Zaoblený obdélník", + "97": "Elipsa", + "98": "Mnohoúhelník", + "99": "Čára a lomená čára", + "100": "Deska TLC", + "101": "Obrázek", + "102": "Orbital p", + "103": "Orbital s", + "104": "Orbital d", + "105": "Orbital dz2", + "106": "Hybridní orbital sp", + "107": "Orbital vazby sigma", + "108": "Orbital vazby pí", + "109": "Přidat čáru", + "110": "Přidat orbital", + "111": "Přidat znaménko plus", + "112": "Přidat tvar", + "113": "Přidat tabulku", + "114": "Přidat desku TLC", + "115": "Přidat skvrnu TLC", + "116": "Hledat text, popisky, vzorce nebo SMILES", + "117": "Najít", + "118": "Nahradit čím", + "119": "Zobrazit nahrazení", + "120": "Rozlišovat velikost písmen", + "121": "{0} (Shift+F3)", + "122": "Předchozí shoda", + "123": "Další shoda", + "124": "{0} (Esc)", + "125": "Nahradit", + "126": "Nahradit vše", + "127": "Žádné výsledky", + "128": "Skrýt nahrazení", + "129": "Nahrazeno shod: 1", + "130": "Nahrazeno shod: {0}", + "131": "Složka", + "132": "Hmotnost", + "133": "Objem", + "134": "Hustota", + "135": "Konc.", + "136": "Čistota", + "137": "Reaktant", + "138": "Činidlo", + "139": "Produkt", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Upravit stechiometrii", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Izolovaný", + "146": "Nenalezeno", + "147": "Šablona je prázdná.", + "148": "Šablona {0} ({1}) byla vložena do \"{2}\" ({3}) v jednom kroku zpět", + "149": "Vložit šablonu", + "150": "Hledat šablony", + "151": "Kategorie šablon", + "152": "Načítání šablon...", + "153": "Hledání neodpovídá žádná šablona.", + "154": "Šipky", + "155": "Symboly", + "156": "Závorky", + "157": "Orbitaly", + "158": "Tvary", + "159": "TLC" +} 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ě" +} diff --git a/frontend/src/i18n/locales/da/part05.json b/frontend/src/i18n/locales/da/part05.json new file mode 100644 index 00000000..cebbe265 --- /dev/null +++ b/frontend/src/i18n/locales/da/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Viser eller skjuler linealer langs lærredets øverste og venstre kant i tegningens enheder (klik på hjørnet for at skifte enhed). Træk fra en lineal for at placere en hjælpelinje; træk en hjælpelinje tilbage på en lineal for at fjerne den. Valget huskes.", + "1": "Ryd hjælpelinjer", + "2": "Fjerner alle linealens hjælpelinjer fra den aktive tegning i dette vindue. Hjælpelinjer gemmes aldrig i dokumentet.", + "3": "Træk først en hjælpelinje ud af en lineal", + "4": "Åbn først søgelinjen, og skriv, hvad der skal findes", + "5": "Åbner søgelinjen over lærredet. Den finder tekst, billedtekster, tabelceller, atometiketter og forkortelser, grundstofsymboler, formler som C2H6O og SMILES i den aktive tegning; Enter eller F3 går til næste match og markerer det.", + "6": "Find næste", + "7": "Markerer næste match og panorerer til det, når det ligger uden for skærmen.", + "8": "Find forrige", + "9": "Markerer forrige match og panorerer til det, når det ligger uden for skærmen.", + "10": "Erstat...", + "11": "Åbner søgelinjen med rækken Erstat. Erstat ændrer det aktuelle tekstmatch; Erstat alle ændrer hvert tekstmatch i ét fortryd-trin.", + "12": "Beder om et PNG-, JPEG-, GIF-, WebP- eller SVG-billede og placerer det midt på den synlige side i ét fortryd-trin.", + "13": "Støkiometripanel", + "14": "Åbner skabelonbiblioteket; med et id indsættes den skabelon (nye id'er, skaleret til tegningens bindingslængde) centreret i visningen af den aktive tegning, eller en ny, i ét fortryd-trin. GET /api/templates viser id'erne.", + "15": "Skabelon-id fra GET /api/templates, f.eks. benzene eller l-alanine; udelad for at åbne biblioteket", + "16": "Kommer i 0.6.0; indtil da angiver Genkend reaktioner rollerne ud fra tegningen", + "17": "Indsæt støkiometritabel", + "18": "Indsætter støkiometrigitteret for det markerede reaktionstrin som en tabel under reaktionen eller opdaterer den tabel, der allerede er knyttet til trinnet, i ét fortryd-trin.", + "19": "Tegn først en reaktion med en pil", + "20": "Kopiér reaktion som", + "21": "Eksportér reaktion", + "22": "Tegn først en reaktionspil med reaktanter og produkter", + "23": "Ingen reaktion fundet: tegn en pil med strukturer på begge sider.", + "24": "Trinnet har ingen atomkortlægning.", + "25": "Kontrollér balance", + "26": "Reaktionen er afstemt.", + "27": "Reaktionen er ikke afstemt.", + "28": "{0}: {1} / {2} g/mol", + "29": "Afstem", + "30": "Reaktionen er afstemt.", + "31": "Reaktionen kunne ikke afstemmes", + "32": "Reaktionen er allerede afstemt.", + "33": "udklipsholderen er ikke tilgængelig", + "34": "Indsæt reaktion", + "35": "Reaktions-SMILES eller RXN", + "36": "Genkend reaktioner", + "37": "Læser reaktionspilene på siden og gemmer hvert trin med dets reaktanter, produkter, agenser og betingelser i ét fortryd-trin.", + "38": "Reaktionerne kunne ikke genkendes", + "39": "Kortlægger atomerne i det markerede reaktionstrin (genkender først reaktionerne, hvis ingen er gemt) og markerer de brudte, dannede og ændrede bindinger i ét fortryd-trin.", + "40": "Atomerne kunne ikke kortlægges", + "41": "Fjerner atomkortlægningsnumrene og markeringerne af reaktionscentret for det markerede reaktionstrin.", + "42": "Kortlægningen kunne ikke ryddes", + "43": "Kontrollér balance...", + "44": "Viser grundstof-, ladnings- og massebalancen for det markerede reaktionstrin med et forslag, når det ikke er afstemt.", + "45": "Reaktionen kunne ikke kontrolleres", + "46": "Afstem reaktion", + "47": "Sætter koefficienterne for det markerede reaktionstrin til de afstemte værdier i ét fortryd-trin.", + "48": "Kopiér reaktions-SMILES", + "49": "Reaktionen kunne ikke kopieres", + "50": "Kopiér reaktion som RXN", + "51": "Eksportér reaktions-SMILES...", + "52": "Reaktionen kunne ikke eksporteres", + "53": "Eksportér reaktion som RXN...", + "54": "Indsæt reaktion fra udklipsholder", + "55": "Læser reaktions-SMILES eller en RXN-fil fra udklipsholderen og lægger den ud på siden med rollerne angivet, i ét fortryd-trin.", + "56": "Reaktionen kunne ikke indsættes", + "57": "Forbindelse", + "58": "Rolle", + "59": "MW", + "60": "Ækv.", + "61": "Masse (mg)", + "62": "Volumen (mL)", + "63": "Teoretisk udbytte", + "64": "Udbytte", + "65": "Linealenhederne følger tegningen; klik for at ændre", + "66": "Linealenheder; klik for at ændre", + "67": "Tilføj pil", + "68": "Angiv parentesetiket", + "69": "Tilføj parentes", + "70": "Tilføj forbindelsesnummer", + "71": "Tilføj billedtekst", + "72": "Tilføj elektronskubbende pil", + "73": "Tilføj enkelthovedet pil", + "74": "Bøj pil", + "75": "Flyt pilens ende", + "76": "Flyt punkt", + "77": "Tilpas størrelse", + "78": "Tilføj billede", + "79": "Billedtekst", + "80": "Reaktionspil", + "81": "Ligevægtspil", + "82": "Retrosyntesepil", + "83": "Resonanspil", + "84": "Pil for udeblevet reaktion", + "85": "Stiplet pil", + "86": "Linjepil", + "87": "Elektronskubbende pil", + "88": "Enkelthovedet pil", + "89": "Plustegn", + "90": "Lighedstegn", + "91": "Addukt-prik", + "92": "Runde parenteser", + "93": "Firkantede parenteser", + "94": "Tuborgparenteser", + "95": "Rektangel", + "96": "Afrundet rektangel", + "97": "Ellipse", + "98": "Polygon", + "99": "Linje og polylinje", + "100": "TLC-plade", + "101": "Billede", + "102": "p-orbital", + "103": "s-orbital", + "104": "d-orbital", + "105": "dz2-orbital", + "106": "sp-hybridorbital", + "107": "Sigmabindingsorbital", + "108": "Pibindingsorbital", + "109": "Tilføj linje", + "110": "Tilføj orbital", + "111": "Tilføj plustegn", + "112": "Tilføj form", + "113": "Tilføj tabel", + "114": "Tilføj TLC-plade", + "115": "Tilføj TLC-plet", + "116": "Find tekst, etiketter, formler eller SMILES", + "117": "Find", + "118": "Erstat med", + "119": "Vis Erstat", + "120": "Skeln mellem store og små bogstaver", + "121": "{0} (Shift+F3)", + "122": "Forrige match", + "123": "Næste match", + "124": "{0} (Esc)", + "125": "Erstat", + "126": "Erstat alle", + "127": "Ingen resultater", + "128": "Skjul Erstat", + "129": "1 match erstattet", + "130": "{0} match erstattet", + "131": "Komponent", + "132": "Masse", + "133": "Volumen", + "134": "Densitet", + "135": "Konc", + "136": "Renhed", + "137": "Reaktant", + "138": "Reagens", + "139": "Produkt", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Rediger støkiometri", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isoleret", + "146": "Ikke fundet", + "147": "Skabelonen er tom.", + "148": "Skabelonen {0} ({1}) er indsat i \"{2}\" ({3}) i ét fortryd-trin", + "149": "Indsæt skabelon", + "150": "Søg i skabeloner", + "151": "Skabelonkategorier", + "152": "Indlæser skabeloner...", + "153": "Ingen skabeloner matcher denne søgning.", + "154": "Pile", + "155": "Symboler", + "156": "Parenteser", + "157": "Orbitaler", + "158": "Former", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/de/part05.json b/frontend/src/i18n/locales/de/part05.json new file mode 100644 index 00000000..8f6f00a3 --- /dev/null +++ b/frontend/src/i18n/locales/de/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Blendet Lineale am oberen und linken Rand der Zeichenfläche in den Zeicheneinheiten ein oder aus (Klick auf die Ecke wechselt die Einheit). Aus einem Lineal ziehen, um eine Hilfslinie zu setzen; eine Hilfslinie zurück auf ein Lineal ziehen, um sie zu entfernen. Die Einstellung wird gespeichert.", + "1": "Hilfslinien löschen", + "2": "Entfernt alle Lineal-Hilfslinien aus der aktiven Zeichnung in diesem Fenster. Hilfslinien werden nie im Dokument gespeichert.", + "3": "Ziehen Sie zuerst eine Hilfslinie aus einem Lineal", + "4": "Öffnen Sie zuerst die Suchleiste und geben Sie den Suchbegriff ein", + "5": "Öffnet die Suchleiste über der Zeichenfläche. Sie findet Text, Beschriftungen, Tabellenzellen, Atombezeichnungen und Abkürzungen, Elementsymbole, Summenformeln wie C2H6O und SMILES in der aktiven Zeichnung; Enter oder F3 springt zum nächsten Treffer und wählt ihn aus.", + "6": "Weitersuchen", + "7": "Wählt den nächsten Treffer aus und verschiebt die Ansicht dorthin, wenn er außerhalb des sichtbaren Bereichs liegt.", + "8": "Rückwärts suchen", + "9": "Wählt den vorherigen Treffer aus und verschiebt die Ansicht dorthin, wenn er außerhalb des sichtbaren Bereichs liegt.", + "10": "Ersetzen...", + "11": "Öffnet die Suchleiste mit der Zeile zum Ersetzen. Ersetzen ändert den aktuellen Texttreffer; Alle ersetzen ändert jeden Texttreffer in einem Rückgängig-Schritt.", + "12": "Fragt nach einem Bild (PNG, JPEG, GIF, WebP oder SVG) und platziert es in einem Rückgängig-Schritt in der Mitte der sichtbaren Seite.", + "13": "Stöchiometrie-Bereich", + "14": "Öffnet die Vorlagenbibliothek; mit einer ID wird diese Vorlage (neue IDs, auf die Bindungslänge der Zeichnung skaliert) in einem Rückgängig-Schritt zentriert in der Ansicht der aktiven oder einer neuen Zeichnung eingefügt. GET /api/templates listet die IDs auf.", + "15": "Vorlagen-ID aus GET /api/templates, etwa benzene oder l-alanine; weglassen, um die Bibliothek zu öffnen", + "16": "Kommt in 0.6.0; bis dahin legt Reaktionen erkennen die Rollen aus der Zeichnung fest", + "17": "Stöchiometrie-Tabelle einfügen", + "18": "Fügt das Stöchiometrie-Raster des ausgewählten Reaktionsschritts als Tabelle unter der Reaktion ein oder aktualisiert die bereits an diesen Schritt gebundene Tabelle, in einem Rückgängig-Schritt.", + "19": "Zeichnen Sie zuerst eine Reaktion mit einem Pfeil", + "20": "Reaktion kopieren als", + "21": "Reaktion exportieren", + "22": "Zeichnen Sie zuerst einen Reaktionspfeil mit Edukten und Produkten", + "23": "Keine Reaktion gefunden: Zeichnen Sie einen Pfeil mit Strukturen auf beiden Seiten.", + "24": "Der Schritt hat kein Atom-Mapping.", + "25": "Bilanz prüfen", + "26": "Die Reaktion ist ausgeglichen.", + "27": "Die Reaktion ist nicht ausgeglichen.", + "28": "{0}: {1} / {2} g/mol", + "29": "Bilanz", + "30": "Die Reaktion wurde ausgeglichen.", + "31": "Die Reaktion konnte nicht ausgeglichen werden", + "32": "Die Reaktion ist bereits ausgeglichen.", + "33": "die Zwischenablage ist nicht verfügbar", + "34": "Reaktion einfügen", + "35": "Reaktions-SMILES oder RXN", + "36": "Reaktionen erkennen", + "37": "Liest die Reaktionspfeile der Seite und speichert jeden Schritt mit seinen Edukten, Produkten, Reagenzien und Bedingungen, in einem Rückgängig-Schritt.", + "38": "Die Reaktionen konnten nicht erkannt werden", + "39": "Ordnet die Atome des ausgewählten Reaktionsschritts zu (erkennt zuvor die Reaktionen, falls keine gespeichert sind) und markiert gebrochene, gebildete und veränderte Bindungen, in einem Rückgängig-Schritt.", + "40": "Die Atome konnten nicht zugeordnet werden", + "41": "Entfernt die Atom-Mapping-Nummern und die Markierungen des Reaktionszentrums des ausgewählten Reaktionsschritts.", + "42": "Das Mapping konnte nicht entfernt werden", + "43": "Bilanz prüfen...", + "44": "Zeigt die Element-, Ladungs- und Massenbilanz des ausgewählten Reaktionsschritts mit einem Vorschlag, wenn er nicht ausgeglichen ist.", + "45": "Die Reaktion konnte nicht geprüft werden", + "46": "Reaktion ausgleichen", + "47": "Setzt die Koeffizienten des ausgewählten Reaktionsschritts auf die ausgeglichenen Werte, in einem Rückgängig-Schritt.", + "48": "Reaktions-SMILES kopieren", + "49": "Die Reaktion konnte nicht kopiert werden", + "50": "Reaktion als RXN kopieren", + "51": "Reaktions-SMILES exportieren...", + "52": "Die Reaktion konnte nicht exportiert werden", + "53": "Reaktion als RXN exportieren...", + "54": "Reaktion aus Zwischenablage einfügen", + "55": "Liest Reaktions-SMILES oder eine RXN-Datei aus der Zwischenablage und legt sie mit gesetzten Rollen auf der Seite aus, in einem Rückgängig-Schritt.", + "56": "Die Reaktion konnte nicht eingefügt werden", + "57": "Verbindung", + "58": "Rolle", + "59": "MW", + "60": "Äquiv.", + "61": "Masse (mg)", + "62": "Volumen (mL)", + "63": "Theoretische Ausbeute", + "64": "Ausbeute", + "65": "Die Lineal-Einheiten folgen der Zeichnung; zum Ändern klicken", + "66": "Lineal-Einheiten; zum Ändern klicken", + "67": "Pfeil hinzufügen", + "68": "Klammerbeschriftung festlegen", + "69": "Klammer hinzufügen", + "70": "Verbindungsnummer hinzufügen", + "71": "Beschriftung hinzufügen", + "72": "Elektronenverschiebungspfeil hinzufügen", + "73": "Halbpfeil hinzufügen", + "74": "Pfeil biegen", + "75": "Pfeilende verschieben", + "76": "Punkt verschieben", + "77": "Größe ändern", + "78": "Bild hinzufügen", + "79": "Beschriftung", + "80": "Reaktionspfeil", + "81": "Gleichgewichtspfeil", + "82": "Retrosynthesepfeil", + "83": "Mesomeriepfeil", + "84": "Pfeil für nicht ablaufende Reaktion", + "85": "Gestrichelter Pfeil", + "86": "Linienpfeil", + "87": "Elektronenverschiebungspfeil", + "88": "Halbpfeil", + "89": "Pluszeichen", + "90": "Gleichheitszeichen", + "91": "Addukt-Punkt", + "92": "Runde Klammern", + "93": "Eckige Klammern", + "94": "Geschweifte Klammern", + "95": "Rechteck", + "96": "Abgerundetes Rechteck", + "97": "Ellipse", + "98": "Polygon", + "99": "Linie und Polylinie", + "100": "DC-Platte", + "101": "Bild", + "102": "p-Orbital", + "103": "s-Orbital", + "104": "d-Orbital", + "105": "dz2-Orbital", + "106": "sp-Hybridorbital", + "107": "Sigma-Bindungsorbital", + "108": "Pi-Bindungsorbital", + "109": "Linie hinzufügen", + "110": "Orbital hinzufügen", + "111": "Pluszeichen hinzufügen", + "112": "Form hinzufügen", + "113": "Tabelle hinzufügen", + "114": "DC-Platte hinzufügen", + "115": "DC-Fleck hinzufügen", + "116": "Text, Beschriftungen, Formeln oder SMILES suchen", + "117": "Suchen", + "118": "Ersetzen durch", + "119": "Ersetzen anzeigen", + "120": "Groß-/Kleinschreibung beachten", + "121": "{0} (Shift+F3)", + "122": "Vorheriger Treffer", + "123": "Nächster Treffer", + "124": "{0} (Esc)", + "125": "Ersetzen", + "126": "Alle ersetzen", + "127": "Keine Ergebnisse", + "128": "Ersetzen ausblenden", + "129": "1 Treffer ersetzt", + "130": "{0} Treffer ersetzt", + "131": "Komponente", + "132": "Masse", + "133": "Volumen", + "134": "Dichte", + "135": "Konz.", + "136": "Reinheit", + "137": "Edukt", + "138": "Reagenz", + "139": "Produkt", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Stöchiometrie bearbeiten", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isoliert", + "146": "Nicht gefunden", + "147": "Die Vorlage ist leer.", + "148": "Vorlage {0} ({1}) in \"{2}\" ({3}) in einem Rückgängig-Schritt eingefügt", + "149": "Vorlage einfügen", + "150": "Vorlagen durchsuchen", + "151": "Vorlagenkategorien", + "152": "Vorlagen werden geladen...", + "153": "Keine Vorlagen passen zu dieser Suche.", + "154": "Pfeile", + "155": "Symbole", + "156": "Klammern", + "157": "Orbitale", + "158": "Formen", + "159": "DC" +} 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" +} diff --git a/frontend/src/i18n/locales/es-MX/part05.json b/frontend/src/i18n/locales/es-MX/part05.json new file mode 100644 index 00000000..4097699b --- /dev/null +++ b/frontend/src/i18n/locales/es-MX/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Muestra u oculta las reglas a lo largo de los bordes superior e izquierdo del lienzo, en las unidades del dibujo (haz clic en la esquina para cambiar de unidades). Arrastra desde una regla para colocar una guía; arrastra una guía de vuelta a una regla para quitarla. La elección se recuerda.", + "1": "Borrar guías", + "2": "Quita todas las guías de las reglas del dibujo activo en esta ventana. Las guías nunca se guardan en el documento.", + "3": "Primero arrastra una guía fuera de una regla", + "4": "Abre la barra de búsqueda y escribe primero lo que quieres buscar", + "5": "Abre la barra de búsqueda sobre el lienzo. Busca texto, leyendas, celdas de tablas, etiquetas de átomos y abreviaturas, símbolos de elementos, fórmulas como C2H6O y SMILES en el dibujo activo; Intro o F3 pasa a la siguiente coincidencia y la selecciona.", + "6": "Buscar siguiente", + "7": "Selecciona la siguiente coincidencia de la búsqueda y desplaza la vista hasta ella si está fuera de la pantalla.", + "8": "Buscar anterior", + "9": "Selecciona la coincidencia anterior de la búsqueda y desplaza la vista hasta ella si está fuera de la pantalla.", + "10": "Reemplazar...", + "11": "Abre la barra de búsqueda con su fila de reemplazo. Reemplazar cambia la coincidencia de texto actual; Reemplazar todo cambia todas las coincidencias de texto en un solo paso de deshacer.", + "12": "Pide al usuario una imagen PNG, JPEG, GIF, WebP o SVG y la coloca en el centro de la página visible en un solo paso de deshacer.", + "13": "Panel de estequiometría", + "14": "Abre la biblioteca de plantillas; con id inserta esa plantilla (con identificadores nuevos y escalada a la longitud de enlace del dibujo) centrada en la vista del dibujo activo, o en uno nuevo, en un solo paso de deshacer. GET /api/templates enumera los id.", + "15": "Id de plantilla de GET /api/templates, como benzene o l-alanine; omítelo para abrir la biblioteca", + "16": "Llegará en la versión 0.6.0; hasta entonces, Percibir reacciones establece los roles a partir del dibujo", + "17": "Insertar tabla de estequiometría", + "18": "Inserta la cuadrícula de estequiometría de la etapa de reacción seleccionada como una tabla debajo de la reacción, o actualiza la tabla ya vinculada a esa etapa, en un solo paso de deshacer.", + "19": "Dibuja primero una reacción con una flecha", + "20": "Copiar reacción como", + "21": "Exportar reacción", + "22": "Dibuja primero una flecha de reacción con reactivos y productos", + "23": "No se encontró ninguna reacción: dibuja una flecha con estructuras a ambos lados.", + "24": "La etapa no tiene mapeo de átomos.", + "25": "Comprobar balance", + "26": "La reacción está balanceada.", + "27": "La reacción no está balanceada.", + "28": "{0}: {1} / {2} g/mol", + "29": "Balancear", + "30": "Se balanceó la reacción.", + "31": "No se pudo balancear la reacción", + "32": "La reacción ya está balanceada.", + "33": "el portapapeles no está disponible", + "34": "Insertar reacción", + "35": "SMILES de reacción o RXN", + "36": "Percibir reacciones", + "37": "Lee las flechas de reacción de la página y guarda cada etapa con sus reactivos, productos, agentes y condiciones, en un solo paso de deshacer.", + "38": "No se pudieron percibir las reacciones", + "39": "Mapea los átomos de la etapa de reacción seleccionada (percibiendo antes las reacciones si no hay ninguna guardada) y marca los enlaces rotos, formados y modificados, en un solo paso de deshacer.", + "40": "No se pudieron mapear los átomos", + "41": "Quita los números de mapeo de átomos y las marcas del centro de reacción de la etapa de reacción seleccionada.", + "42": "No se pudo borrar el mapeo", + "43": "Comprobar balance...", + "44": "Muestra el balance de elementos, carga y masa de la etapa de reacción seleccionada, con una sugerencia cuando no está balanceada.", + "45": "No se pudo comprobar la reacción", + "46": "Balancear reacción", + "47": "Establece los coeficientes de la etapa de reacción seleccionada con los valores balanceados, en un solo paso de deshacer.", + "48": "Copiar SMILES de reacción", + "49": "No se pudo copiar la reacción", + "50": "Copiar reacción como RXN", + "51": "Exportar SMILES de reacción...", + "52": "No se pudo exportar la reacción", + "53": "Exportar reacción como RXN...", + "54": "Insertar reacción desde el portapapeles", + "55": "Lee SMILES de reacción o un archivo RXN del portapapeles y lo acomoda en la página con sus roles establecidos, en un solo paso de deshacer.", + "56": "No se pudo insertar la reacción", + "57": "Compuesto", + "58": "Rol", + "59": "PM", + "60": "Equiv.", + "61": "Masa (mg)", + "62": "Volumen (mL)", + "63": "Rendimiento teórico", + "64": "Rendimiento", + "65": "Las unidades de la regla siguen al dibujo; haz clic para cambiarlas", + "66": "Unidades de la regla; haz clic para cambiarlas", + "67": "Agregar flecha", + "68": "Establecer etiqueta del corchete", + "69": "Agregar corchete", + "70": "Agregar número de compuesto", + "71": "Agregar leyenda", + "72": "Agregar flecha de movimiento de electrones", + "73": "Agregar flecha de anzuelo", + "74": "Curvar flecha", + "75": "Mover extremo de la flecha", + "76": "Mover punto", + "77": "Cambiar tamaño", + "78": "Agregar imagen", + "79": "Leyenda", + "80": "Flecha de reacción", + "81": "Flecha de equilibrio", + "82": "Flecha retrosintética", + "83": "Flecha de resonancia", + "84": "Flecha de reacción imposible", + "85": "Flecha discontinua", + "86": "Flecha de línea", + "87": "Flecha de movimiento de electrones", + "88": "Flecha de anzuelo", + "89": "Signo más", + "90": "Signo igual", + "91": "Punto de aducto", + "92": "Paréntesis", + "93": "Corchetes", + "94": "Llaves", + "95": "Rectángulo", + "96": "Rectángulo redondeado", + "97": "Elipse", + "98": "Polígono", + "99": "Línea y polilínea", + "100": "Placa de CCF", + "101": "Imagen", + "102": "Orbital p", + "103": "Orbital s", + "104": "Orbital d", + "105": "Orbital dz2", + "106": "Orbital híbrido sp", + "107": "Orbital de enlace sigma", + "108": "Orbital de enlace pi", + "109": "Agregar línea", + "110": "Agregar orbital", + "111": "Agregar signo más", + "112": "Agregar forma", + "113": "Agregar tabla", + "114": "Agregar placa de CCF", + "115": "Agregar mancha de CCF", + "116": "Buscar texto, etiquetas, fórmulas o SMILES", + "117": "Buscar", + "118": "Reemplazar con", + "119": "Mostrar reemplazo", + "120": "Distinguir mayúsculas", + "121": "{0} (Shift+F3)", + "122": "Coincidencia anterior", + "123": "Coincidencia siguiente", + "124": "{0} (Esc)", + "125": "Reemplazar", + "126": "Reemplazar todo", + "127": "Sin resultados", + "128": "Ocultar reemplazo", + "129": "Se reemplazó 1 coincidencia", + "130": "Se reemplazaron {0} coincidencias", + "131": "Componente", + "132": "Masa", + "133": "Volumen", + "134": "Densidad", + "135": "Conc.", + "136": "Pureza", + "137": "Reactivo de partida", + "138": "Reactivo", + "139": "Producto", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Editar estequiometría", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Aislado", + "146": "No encontrado", + "147": "La plantilla está vacía.", + "148": "Se insertó la plantilla {0} ({1}) en \"{2}\" ({3}) en un solo paso de deshacer", + "149": "Insertar plantilla", + "150": "Buscar plantillas", + "151": "Categorías de plantillas", + "152": "Cargando plantillas...", + "153": "Ninguna plantilla coincide con esta búsqueda.", + "154": "Flechas", + "155": "Símbolos", + "156": "Corchetes", + "157": "Orbitales", + "158": "Formas", + "159": "CCF" +} 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" +} diff --git a/frontend/src/i18n/locales/es/part05.json b/frontend/src/i18n/locales/es/part05.json new file mode 100644 index 00000000..8186c3ef --- /dev/null +++ b/frontend/src/i18n/locales/es/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Muestra u oculta las reglas a lo largo de los bordes superior e izquierdo del lienzo, en las unidades del dibujo (haz clic en la esquina para cambiar de unidades). Arrastra desde una regla para colocar una guía; arrastra una guía de vuelta a una regla para quitarla. La elección se recuerda.", + "1": "Borrar guías", + "2": "Quita todas las guías de las reglas del dibujo activo en esta ventana. Las guías nunca se guardan en el documento.", + "3": "Primero arrastra una guía fuera de una regla", + "4": "Abre la barra de búsqueda y escribe primero lo que quieres buscar", + "5": "Abre la barra de búsqueda sobre el lienzo. Busca texto, leyendas, celdas de tablas, etiquetas de átomos y abreviaturas, símbolos de elementos, fórmulas como C2H6O y SMILES en el dibujo activo; Intro o F3 pasa a la siguiente coincidencia y la selecciona.", + "6": "Buscar siguiente", + "7": "Selecciona la siguiente coincidencia de la búsqueda y desplaza la vista hasta ella si está fuera de la pantalla.", + "8": "Buscar anterior", + "9": "Selecciona la coincidencia anterior de la búsqueda y desplaza la vista hasta ella si está fuera de la pantalla.", + "10": "Reemplazar...", + "11": "Abre la barra de búsqueda con su fila de reemplazo. Reemplazar cambia la coincidencia de texto actual; Reemplazar todo cambia todas las coincidencias de texto en un solo paso de deshacer.", + "12": "Pide al usuario una imagen PNG, JPEG, GIF, WebP o SVG y la coloca en el centro de la página visible en un solo paso de deshacer.", + "13": "Panel de estequiometría", + "14": "Abre la biblioteca de plantillas; con id inserta esa plantilla (con identificadores nuevos y escalada a la longitud de enlace del dibujo) centrada en la vista del dibujo activo, o en uno nuevo, en un solo paso de deshacer. GET /api/templates enumera los id.", + "15": "Id de plantilla de GET /api/templates, como benzene o l-alanine; omítelo para abrir la biblioteca", + "16": "Llegará en la versión 0.6.0; hasta entonces, Percibir reacciones establece los roles a partir del dibujo", + "17": "Insertar tabla de estequiometría", + "18": "Inserta la cuadrícula de estequiometría de la etapa de reacción seleccionada como una tabla bajo la reacción, o actualiza la tabla ya vinculada a esa etapa, en un solo paso de deshacer.", + "19": "Dibuja primero una reacción con una flecha", + "20": "Copiar reacción como", + "21": "Exportar reacción", + "22": "Dibuja primero una flecha de reacción con reactivos y productos", + "23": "No se encontró ninguna reacción: dibuja una flecha con estructuras a ambos lados.", + "24": "La etapa no tiene mapeo de átomos.", + "25": "Comprobar balance", + "26": "La reacción está balanceada.", + "27": "La reacción no está balanceada.", + "28": "{0}: {1} / {2} g/mol", + "29": "Balancear", + "30": "Se balanceó la reacción.", + "31": "No se pudo balancear la reacción", + "32": "La reacción ya está balanceada.", + "33": "el portapapeles no está disponible", + "34": "Insertar reacción", + "35": "SMILES de reacción o RXN", + "36": "Percibir reacciones", + "37": "Lee las flechas de reacción de la página y guarda cada etapa con sus reactivos, productos, agentes y condiciones, en un solo paso de deshacer.", + "38": "No se pudieron percibir las reacciones", + "39": "Mapea los átomos de la etapa de reacción seleccionada (percibiendo antes las reacciones si no hay ninguna guardada) y marca los enlaces rotos, formados y modificados, en un solo paso de deshacer.", + "40": "No se pudieron mapear los átomos", + "41": "Quita los números de mapeo de átomos y las marcas del centro de reacción de la etapa de reacción seleccionada.", + "42": "No se pudo borrar el mapeo", + "43": "Comprobar balance...", + "44": "Muestra el balance de elementos, carga y masa de la etapa de reacción seleccionada, con una sugerencia cuando no está balanceada.", + "45": "No se pudo comprobar la reacción", + "46": "Balancear reacción", + "47": "Establece los coeficientes de la etapa de reacción seleccionada con los valores balanceados, en un solo paso de deshacer.", + "48": "Copiar SMILES de reacción", + "49": "No se pudo copiar la reacción", + "50": "Copiar reacción como RXN", + "51": "Exportar SMILES de reacción...", + "52": "No se pudo exportar la reacción", + "53": "Exportar reacción como RXN...", + "54": "Insertar reacción desde el portapapeles", + "55": "Lee SMILES de reacción o un archivo RXN del portapapeles y lo dispone en la página con sus roles establecidos, en un solo paso de deshacer.", + "56": "No se pudo insertar la reacción", + "57": "Compuesto", + "58": "Rol", + "59": "PM", + "60": "Equiv.", + "61": "Masa (mg)", + "62": "Volumen (mL)", + "63": "Rendimiento teórico", + "64": "Rendimiento", + "65": "Las unidades de la regla siguen al dibujo; haz clic para cambiarlas", + "66": "Unidades de la regla; haz clic para cambiarlas", + "67": "Añadir flecha", + "68": "Establecer etiqueta del corchete", + "69": "Añadir corchete", + "70": "Añadir número de compuesto", + "71": "Añadir leyenda", + "72": "Añadir flecha de movimiento de electrones", + "73": "Añadir flecha de anzuelo", + "74": "Curvar flecha", + "75": "Mover extremo de la flecha", + "76": "Mover punto", + "77": "Redimensionar", + "78": "Añadir imagen", + "79": "Leyenda", + "80": "Flecha de reacción", + "81": "Flecha de equilibrio", + "82": "Flecha retrosintética", + "83": "Flecha de resonancia", + "84": "Flecha de reacción imposible", + "85": "Flecha discontinua", + "86": "Flecha de línea", + "87": "Flecha de movimiento de electrones", + "88": "Flecha de anzuelo", + "89": "Signo más", + "90": "Signo igual", + "91": "Punto de aducto", + "92": "Paréntesis", + "93": "Corchetes", + "94": "Llaves", + "95": "Rectángulo", + "96": "Rectángulo redondeado", + "97": "Elipse", + "98": "Polígono", + "99": "Línea y polilínea", + "100": "Placa de CCF", + "101": "Imagen", + "102": "Orbital p", + "103": "Orbital s", + "104": "Orbital d", + "105": "Orbital dz2", + "106": "Orbital híbrido sp", + "107": "Orbital de enlace sigma", + "108": "Orbital de enlace pi", + "109": "Añadir línea", + "110": "Añadir orbital", + "111": "Añadir signo más", + "112": "Añadir forma", + "113": "Añadir tabla", + "114": "Añadir placa de CCF", + "115": "Añadir mancha de CCF", + "116": "Buscar texto, etiquetas, fórmulas o SMILES", + "117": "Buscar", + "118": "Reemplazar con", + "119": "Mostrar reemplazo", + "120": "Distinguir mayúsculas", + "121": "{0} (Shift+F3)", + "122": "Coincidencia anterior", + "123": "Coincidencia siguiente", + "124": "{0} (Esc)", + "125": "Reemplazar", + "126": "Reemplazar todo", + "127": "Sin resultados", + "128": "Ocultar reemplazo", + "129": "Se reemplazó 1 coincidencia", + "130": "Se reemplazaron {0} coincidencias", + "131": "Componente", + "132": "Masa", + "133": "Volumen", + "134": "Densidad", + "135": "Conc.", + "136": "Pureza", + "137": "Reactivo de partida", + "138": "Reactivo", + "139": "Producto", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Editar estequiometría", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Aislado", + "146": "No encontrado", + "147": "La plantilla está vacía.", + "148": "Se insertó la plantilla {0} ({1}) en \"{2}\" ({3}) en un solo paso de deshacer", + "149": "Insertar plantilla", + "150": "Buscar plantillas", + "151": "Categorías de plantillas", + "152": "Cargando plantillas...", + "153": "Ninguna plantilla coincide con esta búsqueda.", + "154": "Flechas", + "155": "Símbolos", + "156": "Corchetes", + "157": "Orbitales", + "158": "Formas", + "159": "CCF" +} 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" +} diff --git a/frontend/src/i18n/locales/fi/part05.json b/frontend/src/i18n/locales/fi/part05.json new file mode 100644 index 00000000..e452812d --- /dev/null +++ b/frontend/src/i18n/locales/fi/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Näyttää tai piilottaa viivaimet piirtoalueen ylä- ja vasemmassa reunassa piirroksen yksiköissä (vaihda yksikköä napsauttamalla kulmaa). Vedä viivaimesta asettaaksesi apuviivan; vedä apuviiva takaisin viivaimelle poistaaksesi sen. Valinta muistetaan.", + "1": "Tyhjennä apuviivat", + "2": "Poistaa kaikki viivainten apuviivat tämän ikkunan aktiivisesta piirroksesta. Apuviivoja ei koskaan tallenneta asiakirjaan.", + "3": "Vedä ensin apuviiva ulos viivaimesta", + "4": "Avaa ensin hakupalkki ja kirjoita, mitä etsitään", + "5": "Avaa hakupalkin piirtoalueen päälle. Se etsii aktiivisesta piirroksesta tekstiä, kuvatekstejä, taulukon soluja, atomien nimiöitä ja lyhenteitä, alkuainesymboleja, kaavoja kuten C2H6O ja SMILES-merkkijonoja; Enter tai F3 siirtyy seuraavaan osumaan ja valitsee sen.", + "6": "Hae seuraava", + "7": "Valitsee seuraavan osuman ja siirtää näkymän siihen, kun se on näkymän ulkopuolella.", + "8": "Hae edellinen", + "9": "Valitsee edellisen osuman ja siirtää näkymän siihen, kun se on näkymän ulkopuolella.", + "10": "Korvaa...", + "11": "Avaa hakupalkin Korvaa-rivin kanssa. Korvaa muuttaa nykyisen tekstiosuman; Korvaa kaikki muuttaa jokaisen tekstiosuman yhtenä kumoamisvaiheena.", + "12": "Pyytää PNG-, JPEG-, GIF-, WebP- tai SVG-kuvan ja asettaa sen näkyvän sivun keskelle yhtenä kumoamisvaiheena.", + "13": "Stoikiometriapaneeli", + "14": "Avaa mallikirjaston; tunnuksella lisää kyseisen mallin (uudet tunnukset, skaalattu piirroksen sidospituuteen) keskitettynä aktiivisen piirroksen näkymään tai uuteen piirrokseen yhtenä kumoamisvaiheena. GET /api/templates luettelee tunnukset.", + "15": "Mallin tunnus osoitteesta GET /api/templates, esimerkiksi benzene tai l-alanine; jätä pois avataksesi kirjaston", + "16": "Tulee versiossa 0.6.0; siihen asti Tunnista reaktiot asettaa roolit piirroksen perusteella", + "17": "Lisää stoikiometriataulukko", + "18": "Lisää valitun reaktiovaiheen stoikiometriaruudukon taulukkona reaktion alle tai päivittää vaiheeseen jo sidotun taulukon yhtenä kumoamisvaiheena.", + "19": "Piirrä ensin reaktio nuolella", + "20": "Kopioi reaktio muodossa", + "21": "Vie reaktio", + "22": "Piirrä ensin reaktionuoli, jonka molemmin puolin on lähtöaineita ja tuotteita", + "23": "Reaktiota ei löytynyt: piirrä nuoli, jonka molemmin puolin on rakenteita.", + "24": "Vaiheessa ei ole atomikartoitusta.", + "25": "Tarkista tasapaino", + "26": "Reaktio on tasapainotettu.", + "27": "Reaktio ei ole tasapainotettu.", + "28": "{0}: {1} / {2} g/mol", + "29": "Tasapainota", + "30": "Reaktio tasapainotettiin.", + "31": "Reaktiota ei voitu tasapainottaa", + "32": "Reaktio on jo tasapainotettu.", + "33": "leikepöytä ei ole käytettävissä", + "34": "Lisää reaktio", + "35": "Reaktio-SMILES tai RXN", + "36": "Tunnista reaktiot", + "37": "Lukee sivun reaktionuolet ja tallentaa jokaisen vaiheen lähtöaineineen, tuotteineen, aineineen ja olosuhteineen yhtenä kumoamisvaiheena.", + "38": "Reaktioita ei voitu tunnistaa", + "39": "Kartoittaa valitun reaktiovaiheen atomit (tunnistaa ensin reaktiot, jos yhtään ei ole tallennettu) ja merkitsee katkenneet, muodostuneet ja muuttuneet sidokset yhtenä kumoamisvaiheena.", + "40": "Atomeja ei voitu kartoittaa", + "41": "Poistaa valitun reaktiovaiheen atomikartoitusnumerot ja reaktiokeskuksen merkinnät.", + "42": "Kartoitusta ei voitu tyhjentää", + "43": "Tarkista tasapaino...", + "44": "Näyttää valitun reaktiovaiheen alkuaine-, varaus- ja massatasapainon sekä ehdotuksen, kun se ei ole tasapainossa.", + "45": "Reaktiota ei voitu tarkistaa", + "46": "Tasapainota reaktio", + "47": "Asettaa valitun reaktiovaiheen kertoimet tasapainotettuihin arvoihin yhtenä kumoamisvaiheena.", + "48": "Kopioi reaktio-SMILES", + "49": "Reaktiota ei voitu kopioida", + "50": "Kopioi reaktio RXN-muodossa", + "51": "Vie reaktio-SMILES...", + "52": "Reaktiota ei voitu viedä", + "53": "Vie reaktio RXN-muodossa...", + "54": "Lisää reaktio leikepöydältä", + "55": "Lukee reaktio-SMILES-merkkijonon tai RXN-tiedoston leikepöydältä ja asettelee sen sivulle rooleineen yhtenä kumoamisvaiheena.", + "56": "Reaktiota ei voitu lisätä", + "57": "Yhdiste", + "58": "Rooli", + "59": "MW", + "60": "Ekv.", + "61": "Massa (mg)", + "62": "Tilavuus (mL)", + "63": "Teoreettinen saanto", + "64": "Saanto", + "65": "Viivainyksiköt seuraavat piirrosta; vaihda napsauttamalla", + "66": "Viivainyksiköt; vaihda napsauttamalla", + "67": "Lisää nuoli", + "68": "Aseta sulkeen nimiö", + "69": "Lisää sulku", + "70": "Lisää yhdisteen numero", + "71": "Lisää kuvateksti", + "72": "Lisää elektronien siirtonuoli", + "73": "Lisää yhden elektronin siirtonuoli", + "74": "Taivuta nuolta", + "75": "Siirrä nuolen päätä", + "76": "Siirrä pistettä", + "77": "Muuta kokoa", + "78": "Lisää kuva", + "79": "Kuvateksti", + "80": "Reaktionuoli", + "81": "Tasapainonuoli", + "82": "Retrosynteesinuoli", + "83": "Resonanssinuoli", + "84": "Toteutumattoman reaktion nuoli", + "85": "Katkoviivanuoli", + "86": "Viivanuoli", + "87": "Elektronien siirtonuoli", + "88": "Yhden elektronin siirtonuoli", + "89": "Plusmerkki", + "90": "Yhtäsuuruusmerkki", + "91": "Addukkipiste", + "92": "Pyöreät sulut", + "93": "Hakasulut", + "94": "Aaltosulut", + "95": "Suorakulmio", + "96": "Pyöristetty suorakulmio", + "97": "Ellipsi", + "98": "Monikulmio", + "99": "Viiva ja murtoviiva", + "100": "TLC-levy", + "101": "Kuva", + "102": "p-orbitaali", + "103": "s-orbitaali", + "104": "d-orbitaali", + "105": "dz2-orbitaali", + "106": "sp-hybridiorbitaali", + "107": "Sigmasidoksen orbitaali", + "108": "Pisidoksen orbitaali", + "109": "Lisää viiva", + "110": "Lisää orbitaali", + "111": "Lisää plusmerkki", + "112": "Lisää muoto", + "113": "Lisää taulukko", + "114": "Lisää TLC-levy", + "115": "Lisää TLC-piste", + "116": "Etsi tekstiä, nimiöitä, kaavoja tai SMILES-merkkijonoja", + "117": "Etsi", + "118": "Korvaa tällä", + "119": "Näytä Korvaa", + "120": "Erota isot ja pienet kirjaimet", + "121": "{0} (Shift+F3)", + "122": "Edellinen osuma", + "123": "Seuraava osuma", + "124": "{0} (Esc)", + "125": "Korvaa", + "126": "Korvaa kaikki", + "127": "Ei tuloksia", + "128": "Piilota Korvaa", + "129": "Korvattiin 1 osuma", + "130": "Korvattiin {0} osumaa", + "131": "Komponentti", + "132": "Massa", + "133": "Tilavuus", + "134": "Tiheys", + "135": "Pit.", + "136": "Puhtaus", + "137": "Lähtöaine", + "138": "Reagenssi", + "139": "Tuote", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Muokkaa stoikiometriaa", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Eristetty", + "146": "Ei löytynyt", + "147": "Malli on tyhjä.", + "148": "Malli {0} ({1}) lisättiin kohteeseen \"{2}\" ({3}) yhtenä kumoamisvaiheena", + "149": "Lisää malli", + "150": "Hae malleja", + "151": "Mallien luokat", + "152": "Ladataan malleja...", + "153": "Mikään malli ei vastaa tätä hakua.", + "154": "Nuolet", + "155": "Symbolit", + "156": "Sulut", + "157": "Orbitaalit", + "158": "Muodot", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/fr-CA/part05.json b/frontend/src/i18n/locales/fr-CA/part05.json new file mode 100644 index 00000000..780add9a --- /dev/null +++ b/frontend/src/i18n/locales/fr-CA/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Affiche ou masque les règles le long des bords supérieur et gauche du canevas, dans les unités du dessin (cliquez sur le coin pour changer d’unités). Faites glisser depuis une règle pour placer un repère; refaites glisser un repère sur une règle pour le supprimer. Le choix est mémorisé.", + "1": "Effacer les repères", + "2": "Supprime tous les repères de règle du dessin actif dans cette fenêtre. Les repères ne sont jamais enregistrés dans le document.", + "3": "Faites d’abord glisser un repère hors d’une règle", + "4": "Ouvrez la barre de recherche et saisissez d’abord ce que vous cherchez", + "5": "Ouvre la barre de recherche au-dessus du canevas. Elle trouve le texte, les légendes, les cellules de tableau, les étiquettes d’atomes et les abréviations, les symboles d’éléments, les formules comme C2H6O et les SMILES dans le dessin actif; Entrée ou F3 passe à l’occurrence suivante et la sélectionne.", + "6": "Occurrence suivante", + "7": "Sélectionne l’occurrence suivante de la recherche et fait défiler la vue jusqu’à elle si elle est hors de l’écran.", + "8": "Occurrence précédente", + "9": "Sélectionne l’occurrence précédente de la recherche et fait défiler la vue jusqu’à elle si elle est hors de l’écran.", + "10": "Remplacer...", + "11": "Ouvre la barre de recherche avec sa ligne de remplacement. Remplacer modifie l’occurrence de texte courante; Tout remplacer modifie toutes les occurrences de texte en une seule étape d’annulation.", + "12": "Demande à l’utilisateur une image PNG, JPEG, GIF, WebP ou SVG et la place au milieu de la page visible en une seule étape d’annulation.", + "13": "Panneau de stœchiométrie", + "14": "Ouvre la bibliothèque de modèles; avec id, insère ce modèle (avec de nouveaux identifiants, à l’échelle de la longueur de liaison du dessin) au centre de la vue du dessin actif, ou d’un nouveau, en une seule étape d’annulation. GET /api/templates liste les id.", + "15": "Id de modèle issu de GET /api/templates, comme benzene ou l-alanine; omettez-le pour ouvrir la bibliothèque", + "16": "Arrive dans la version 0.6.0; d’ici là, Détecter les réactions définit les rôles à partir du dessin", + "17": "Insérer un tableau de stœchiométrie", + "18": "Insère la grille de stœchiométrie de l’étape de réaction sélectionnée sous forme de tableau sous la réaction, ou actualise le tableau déjà lié à cette étape, en une seule étape d’annulation.", + "19": "Dessinez d’abord une réaction avec une flèche", + "20": "Copier la réaction en tant que", + "21": "Exporter la réaction", + "22": "Dessinez d’abord une flèche de réaction avec des réactifs et des produits", + "23": "Aucune réaction trouvée : dessinez une flèche avec des structures de chaque côté.", + "24": "L’étape n’a pas de mappage des atomes.", + "25": "Vérifier l’équilibre", + "26": "La réaction est équilibrée.", + "27": "La réaction n’est pas équilibrée.", + "28": "{0} : {1} / {2} g/mol", + "29": "Équilibrer", + "30": "La réaction a été équilibrée.", + "31": "Impossible d’équilibrer la réaction", + "32": "La réaction est déjà équilibrée.", + "33": "le presse-papiers n’est pas disponible", + "34": "Insérer une réaction", + "35": "SMILES de réaction ou RXN", + "36": "Détecter les réactions", + "37": "Lit les flèches de réaction de la page et mémorise chaque étape avec ses réactifs, produits, agents et conditions, en une seule étape d’annulation.", + "38": "Impossible de détecter les réactions", + "39": "Mappe les atomes de l’étape de réaction sélectionnée (en détectant d’abord les réactions si aucune n’est mémorisée) et marque les liaisons rompues, formées et modifiées, en une seule étape d’annulation.", + "40": "Impossible de mapper les atomes", + "41": "Supprime les numéros de mappage des atomes et les marques du centre réactionnel de l’étape de réaction sélectionnée.", + "42": "Impossible d’effacer le mappage", + "43": "Vérifier l’équilibre...", + "44": "Affiche le bilan des éléments, de la charge et de la masse de l’étape de réaction sélectionnée, avec une suggestion lorsqu’elle n’est pas équilibrée.", + "45": "Impossible de vérifier la réaction", + "46": "Équilibrer la réaction", + "47": "Définit les coefficients de l’étape de réaction sélectionnée avec les valeurs équilibrées, en une seule étape d’annulation.", + "48": "Copier le SMILES de réaction", + "49": "Impossible de copier la réaction", + "50": "Copier la réaction en RXN", + "51": "Exporter le SMILES de réaction...", + "52": "Impossible d’exporter la réaction", + "53": "Exporter la réaction en RXN...", + "54": "Insérer une réaction depuis le presse-papiers", + "55": "Lit un SMILES de réaction ou un fichier RXN depuis le presse-papiers et le dispose sur la page avec ses rôles définis, en une seule étape d’annulation.", + "56": "Impossible d’insérer la réaction", + "57": "Composé", + "58": "Rôle", + "59": "MM", + "60": "Éq.", + "61": "Masse (mg)", + "62": "Volume (mL)", + "63": "Rendement théorique", + "64": "Rendement", + "65": "Les unités de la règle suivent le dessin; cliquez pour les changer", + "66": "Unités de la règle; cliquez pour les changer", + "67": "Ajouter une flèche", + "68": "Définir l’étiquette du crochet", + "69": "Ajouter un crochet", + "70": "Ajouter un numéro de composé", + "71": "Ajouter une légende", + "72": "Ajouter une flèche de déplacement d’électrons", + "73": "Ajouter une flèche à demi-pointe", + "74": "Courber la flèche", + "75": "Déplacer l’extrémité de la flèche", + "76": "Déplacer le point", + "77": "Redimensionner", + "78": "Ajouter une image", + "79": "Légende", + "80": "Flèche de réaction", + "81": "Flèche d’équilibre", + "82": "Flèche rétrosynthétique", + "83": "Flèche de mésomérie", + "84": "Flèche de réaction impossible", + "85": "Flèche en pointillés", + "86": "Flèche simple", + "87": "Flèche de déplacement d’électrons", + "88": "Flèche à demi-pointe", + "89": "Signe plus", + "90": "Signe égal", + "91": "Point d’adduit", + "92": "Parenthèses", + "93": "Crochets", + "94": "Accolades", + "95": "Rectangle", + "96": "Rectangle arrondi", + "97": "Ellipse", + "98": "Polygone", + "99": "Ligne et polyligne", + "100": "Plaque CCM", + "101": "Image", + "102": "Orbitale p", + "103": "Orbitale s", + "104": "Orbitale d", + "105": "Orbitale dz2", + "106": "Orbitale hybride sp", + "107": "Orbitale de liaison sigma", + "108": "Orbitale de liaison pi", + "109": "Ajouter une ligne", + "110": "Ajouter une orbitale", + "111": "Ajouter un signe plus", + "112": "Ajouter une forme", + "113": "Ajouter un tableau", + "114": "Ajouter une plaque CCM", + "115": "Ajouter une tache CCM", + "116": "Rechercher du texte, des étiquettes, des formules ou des SMILES", + "117": "Rechercher", + "118": "Remplacer par", + "119": "Afficher le remplacement", + "120": "Respecter la casse", + "121": "{0} (Shift+F3)", + "122": "Occurrence précédente", + "123": "Occurrence suivante", + "124": "{0} (Esc)", + "125": "Remplacer", + "126": "Tout remplacer", + "127": "Aucun résultat", + "128": "Masquer le remplacement", + "129": "1 occurrence remplacée", + "130": "{0} occurrences remplacées", + "131": "Composant", + "132": "Masse", + "133": "Volume", + "134": "Densité", + "135": "Conc.", + "136": "Pureté", + "137": "Réactif de départ", + "138": "Réactif", + "139": "Produit", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Modifier la stœchiométrie", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isolé", + "146": "Introuvable", + "147": "Le modèle est vide.", + "148": "Modèle {0} ({1}) inséré dans « {2} » ({3}) en une seule étape d’annulation", + "149": "Insérer un modèle", + "150": "Rechercher des modèles", + "151": "Catégories de modèles", + "152": "Chargement des modèles...", + "153": "Aucun modèle ne correspond à cette recherche.", + "154": "Flèches", + "155": "Symboles", + "156": "Crochets", + "157": "Orbitales", + "158": "Formes", + "159": "CCM" +} 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" +} diff --git a/frontend/src/i18n/locales/fr/part05.json b/frontend/src/i18n/locales/fr/part05.json new file mode 100644 index 00000000..986362e2 --- /dev/null +++ b/frontend/src/i18n/locales/fr/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Affiche ou masque les règles le long des bords supérieur et gauche du canevas, dans les unités du dessin (cliquez sur le coin pour changer d’unités). Faites glisser depuis une règle pour placer un repère ; refaites glisser un repère sur une règle pour le supprimer. Le choix est mémorisé.", + "1": "Effacer les repères", + "2": "Supprime tous les repères de règle du dessin actif dans cette fenêtre. Les repères ne sont jamais enregistrés dans le document.", + "3": "Faites d’abord glisser un repère hors d’une règle", + "4": "Ouvrez la barre de recherche et saisissez d’abord ce que vous cherchez", + "5": "Ouvre la barre de recherche au-dessus du canevas. Elle trouve le texte, les légendes, les cellules de tableau, les étiquettes d’atomes et les abréviations, les symboles d’éléments, les formules comme C2H6O et les SMILES dans le dessin actif ; Entrée ou F3 passe à l’occurrence suivante et la sélectionne.", + "6": "Occurrence suivante", + "7": "Sélectionne l’occurrence suivante de la recherche et fait défiler la vue jusqu’à elle si elle est hors de l’écran.", + "8": "Occurrence précédente", + "9": "Sélectionne l’occurrence précédente de la recherche et fait défiler la vue jusqu’à elle si elle est hors de l’écran.", + "10": "Remplacer...", + "11": "Ouvre la barre de recherche avec sa ligne de remplacement. Remplacer modifie l’occurrence de texte courante ; Tout remplacer modifie toutes les occurrences de texte en une seule étape d’annulation.", + "12": "Demande à l’utilisateur une image PNG, JPEG, GIF, WebP ou SVG et la place au milieu de la page visible en une seule étape d’annulation.", + "13": "Panneau de stœchiométrie", + "14": "Ouvre la bibliothèque de modèles ; avec id, insère ce modèle (avec de nouveaux identifiants, à l’échelle de la longueur de liaison du dessin) au centre de la vue du dessin actif, ou d’un nouveau, en une seule étape d’annulation. GET /api/templates liste les id.", + "15": "Id de modèle issu de GET /api/templates, comme benzene ou l-alanine ; omettez-le pour ouvrir la bibliothèque", + "16": "Arrive dans la version 0.6.0 ; d’ici là, Détecter les réactions définit les rôles à partir du dessin", + "17": "Insérer un tableau de stœchiométrie", + "18": "Insère la grille de stœchiométrie de l’étape de réaction sélectionnée sous forme de tableau sous la réaction, ou actualise le tableau déjà lié à cette étape, en une seule étape d’annulation.", + "19": "Dessinez d’abord une réaction avec une flèche", + "20": "Copier la réaction en tant que", + "21": "Exporter la réaction", + "22": "Dessinez d’abord une flèche de réaction avec des réactifs et des produits", + "23": "Aucune réaction trouvée : dessinez une flèche avec des structures de chaque côté.", + "24": "L’étape n’a pas de mappage des atomes.", + "25": "Vérifier l’équilibre", + "26": "La réaction est équilibrée.", + "27": "La réaction n’est pas équilibrée.", + "28": "{0} : {1} / {2} g/mol", + "29": "Équilibrer", + "30": "La réaction a été équilibrée.", + "31": "Impossible d’équilibrer la réaction", + "32": "La réaction est déjà équilibrée.", + "33": "le presse-papiers n’est pas disponible", + "34": "Insérer une réaction", + "35": "SMILES de réaction ou RXN", + "36": "Détecter les réactions", + "37": "Lit les flèches de réaction de la page et mémorise chaque étape avec ses réactifs, produits, agents et conditions, en une seule étape d’annulation.", + "38": "Impossible de détecter les réactions", + "39": "Mappe les atomes de l’étape de réaction sélectionnée (en détectant d’abord les réactions si aucune n’est mémorisée) et marque les liaisons rompues, formées et modifiées, en une seule étape d’annulation.", + "40": "Impossible de mapper les atomes", + "41": "Supprime les numéros de mappage des atomes et les marques du centre réactionnel de l’étape de réaction sélectionnée.", + "42": "Impossible d’effacer le mappage", + "43": "Vérifier l’équilibre...", + "44": "Affiche le bilan des éléments, de la charge et de la masse de l’étape de réaction sélectionnée, avec une suggestion lorsqu’elle n’est pas équilibrée.", + "45": "Impossible de vérifier la réaction", + "46": "Équilibrer la réaction", + "47": "Définit les coefficients de l’étape de réaction sélectionnée avec les valeurs équilibrées, en une seule étape d’annulation.", + "48": "Copier le SMILES de réaction", + "49": "Impossible de copier la réaction", + "50": "Copier la réaction en RXN", + "51": "Exporter le SMILES de réaction...", + "52": "Impossible d’exporter la réaction", + "53": "Exporter la réaction en RXN...", + "54": "Insérer une réaction depuis le presse-papiers", + "55": "Lit un SMILES de réaction ou un fichier RXN depuis le presse-papiers et le dispose sur la page avec ses rôles définis, en une seule étape d’annulation.", + "56": "Impossible d’insérer la réaction", + "57": "Composé", + "58": "Rôle", + "59": "MM", + "60": "Éq.", + "61": "Masse (mg)", + "62": "Volume (mL)", + "63": "Rendement théorique", + "64": "Rendement", + "65": "Les unités de la règle suivent le dessin ; cliquez pour les changer", + "66": "Unités de la règle ; cliquez pour les changer", + "67": "Ajouter une flèche", + "68": "Définir l’étiquette du crochet", + "69": "Ajouter un crochet", + "70": "Ajouter un numéro de composé", + "71": "Ajouter une légende", + "72": "Ajouter une flèche de déplacement d’électrons", + "73": "Ajouter une flèche à demi-pointe", + "74": "Courber la flèche", + "75": "Déplacer l’extrémité de la flèche", + "76": "Déplacer le point", + "77": "Redimensionner", + "78": "Ajouter une image", + "79": "Légende", + "80": "Flèche de réaction", + "81": "Flèche d’équilibre", + "82": "Flèche rétrosynthétique", + "83": "Flèche de mésomérie", + "84": "Flèche de réaction impossible", + "85": "Flèche en pointillés", + "86": "Flèche simple", + "87": "Flèche de déplacement d’électrons", + "88": "Flèche à demi-pointe", + "89": "Signe plus", + "90": "Signe égal", + "91": "Point d’adduit", + "92": "Parenthèses", + "93": "Crochets", + "94": "Accolades", + "95": "Rectangle", + "96": "Rectangle arrondi", + "97": "Ellipse", + "98": "Polygone", + "99": "Ligne et polyligne", + "100": "Plaque CCM", + "101": "Image", + "102": "Orbitale p", + "103": "Orbitale s", + "104": "Orbitale d", + "105": "Orbitale dz2", + "106": "Orbitale hybride sp", + "107": "Orbitale de liaison sigma", + "108": "Orbitale de liaison pi", + "109": "Ajouter une ligne", + "110": "Ajouter une orbitale", + "111": "Ajouter un signe plus", + "112": "Ajouter une forme", + "113": "Ajouter un tableau", + "114": "Ajouter une plaque CCM", + "115": "Ajouter une tache CCM", + "116": "Rechercher du texte, des étiquettes, des formules ou des SMILES", + "117": "Rechercher", + "118": "Remplacer par", + "119": "Afficher le remplacement", + "120": "Respecter la casse", + "121": "{0} (Shift+F3)", + "122": "Occurrence précédente", + "123": "Occurrence suivante", + "124": "{0} (Esc)", + "125": "Remplacer", + "126": "Tout remplacer", + "127": "Aucun résultat", + "128": "Masquer le remplacement", + "129": "1 occurrence remplacée", + "130": "{0} occurrences remplacées", + "131": "Composant", + "132": "Masse", + "133": "Volume", + "134": "Densité", + "135": "Conc.", + "136": "Pureté", + "137": "Réactif de départ", + "138": "Réactif", + "139": "Produit", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Modifier la stœchiométrie", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isolé", + "146": "Introuvable", + "147": "Le modèle est vide.", + "148": "Modèle {0} ({1}) inséré dans « {2} » ({3}) en une seule étape d’annulation", + "149": "Insérer un modèle", + "150": "Rechercher des modèles", + "151": "Catégories de modèles", + "152": "Chargement des modèles...", + "153": "Aucun modèle ne correspond à cette recherche.", + "154": "Flèches", + "155": "Symboles", + "156": "Crochets", + "157": "Orbitales", + "158": "Formes", + "159": "CCM" +} 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" +} diff --git a/frontend/src/i18n/locales/hu/part05.json b/frontend/src/i18n/locales/hu/part05.json new file mode 100644 index 00000000..8381a598 --- /dev/null +++ b/frontend/src/i18n/locales/hu/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Vonalzókat jelenít meg vagy rejt el a vászon felső és bal szélén, a rajz mértékegységeiben (a sarokra kattintva mértékegységet válthat). Húzzon egy vonalzóról segédvonalat a lerakáshoz; a segédvonalat visszahúzva a vonalzóra eltávolíthatja. A választás megmarad.", + "1": "Segédvonalak törlése", + "2": "Eltávolítja az aktív rajz összes vonalzó-segédvonalát ebben az ablakban. A segédvonalak soha nem kerülnek a dokumentumba.", + "3": "Előbb húzzon ki egy segédvonalat egy vonalzóról", + "4": "Nyissa meg a keresősávot, és előbb írja be, mit keressen", + "5": "Megnyitja a keresősávot a vászon fölött. Az aktív rajzban szöveget, feliratokat, táblázatcellákat, atomfeliratokat és rövidítéseket, elemszimbólumokat, képleteket (például C2H6O) és SMILES-eket keres; az Enter vagy az F3 a következő találatra ugrik, és kijelöli azt.", + "6": "Következő találat", + "7": "Kijelöli a következő találatot, és odagörget, ha az a képernyőn kívül van.", + "8": "Előző találat", + "9": "Kijelöli az előző találatot, és odagörget, ha az a képernyőn kívül van.", + "10": "Csere...", + "11": "Megnyitja a keresősávot a Csere sorral. A Csere az aktuális szöveges találatot módosítja; az Összes cseréje egyetlen visszavonási lépésként minden szöveges találatot módosít.", + "12": "Bekér egy PNG, JPEG, GIF, WebP vagy SVG képet, és egyetlen visszavonási lépésként a látható oldal közepére helyezi.", + "13": "Sztöchiometria panel", + "14": "Megnyitja a sablonkönyvtárat; azonosítóval beszúrja az adott sablont (új azonosítókkal, a rajz kötéshosszához méretezve) az aktív rajz nézetének közepére, vagy egy újba, egyetlen visszavonási lépésként. A GET /api/templates felsorolja az azonosítókat.", + "15": "A GET /api/templates sablonazonosítója, például benzene vagy l-alanine; a könyvtár megnyitásához hagyja el", + "16": "A 0.6.0 verzióban érkezik; addig a Reakciók felismerése a rajz alapján állítja be a szerepeket", + "17": "Sztöchiometriai táblázat beszúrása", + "18": "A kijelölt reakciólépés sztöchiometriai rácsát táblázatként beszúrja a reakció alá, vagy frissíti a lépéshez már kötött táblázatot, egyetlen visszavonási lépésként.", + "19": "Előbb rajzoljon reakciót nyíllal", + "20": "Reakció másolása mint", + "21": "Reakció exportálása", + "22": "Előbb rajzoljon reakciónyilat reaktánsokkal és termékekkel", + "23": "Nincs reakció: rajzoljon nyilat, mindkét oldalán szerkezetekkel.", + "24": "A lépésnek nincs atomleképezése.", + "25": "Kiegyenlítettség ellenőrzése", + "26": "A reakció kiegyenlített.", + "27": "A reakció nincs kiegyenlítve.", + "28": "{0}: {1} / {2} g/mol", + "29": "Kiegyenlítés", + "30": "A reakció kiegyenlítve.", + "31": "Nem sikerült kiegyenlíteni a reakciót", + "32": "A reakció már ki van egyenlítve.", + "33": "a vágólap nem érhető el", + "34": "Reakció beszúrása", + "35": "Reakció-SMILES vagy RXN", + "36": "Reakciók felismerése", + "37": "Beolvassa az oldalon lévő reakciónyilakat, és minden lépést eltárol reaktánsaival, termékeivel, segédanyagaival és körülményeivel, egyetlen visszavonási lépésként.", + "38": "Nem sikerült felismerni a reakciókat", + "39": "Leképezi a kijelölt reakciólépés atomjait (ha nincs eltárolt reakció, előbb felismeri a reakciókat), és megjelöli a felbomló, kialakuló és megváltozó kötéseket, egyetlen visszavonási lépésként.", + "40": "Nem sikerült leképezni az atomokat", + "41": "Eltávolítja a kijelölt reakciólépés atomleképezési számait és reakciócentrum-jelöléseit.", + "42": "Nem sikerült törölni a leképezést", + "43": "Kiegyenlítettség ellenőrzése...", + "44": "Megmutatja a kijelölt reakciólépés elem-, töltés- és tömegegyensúlyát, kiegyenlítetlenség esetén javaslattal.", + "45": "Nem sikerült ellenőrizni a reakciót", + "46": "Reakció kiegyenlítése", + "47": "A kijelölt reakciólépés együtthatóit a kiegyenlített értékekre állítja, egyetlen visszavonási lépésként.", + "48": "Reakció-SMILES másolása", + "49": "Nem sikerült másolni a reakciót", + "50": "Reakció másolása RXN-ként", + "51": "Reakció-SMILES exportálása...", + "52": "Nem sikerült exportálni a reakciót", + "53": "Reakció exportálása RXN-ként...", + "54": "Reakció beszúrása a vágólapról", + "55": "Beolvas egy reakció-SMILES-t vagy RXN fájlt a vágólapról, és beállított szerepekkel elrendezi az oldalon, egyetlen visszavonási lépésként.", + "56": "Nem sikerült beszúrni a reakciót", + "57": "Vegyület", + "58": "Szerep", + "59": "MW", + "60": "Ekv.", + "61": "Tömeg (mg)", + "62": "Térfogat (mL)", + "63": "Elméleti kitermelés", + "64": "Kitermelés", + "65": "A vonalzó mértékegysége a rajzot követi; kattintson a módosításhoz", + "66": "Vonalzó mértékegysége; kattintson a módosításhoz", + "67": "Nyíl hozzáadása", + "68": "Zárójelfelirat beállítása", + "69": "Zárójel hozzáadása", + "70": "Vegyületszám hozzáadása", + "71": "Felirat hozzáadása", + "72": "Elektronmozgás-nyíl hozzáadása", + "73": "Félnyíl hozzáadása", + "74": "Nyíl hajlítása", + "75": "Nyílvég áthelyezése", + "76": "Pont áthelyezése", + "77": "Átméretezés", + "78": "Kép hozzáadása", + "79": "Felirat", + "80": "Reakciónyíl", + "81": "Egyensúlyi nyíl", + "82": "Retroszintetikus nyíl", + "83": "Rezonancianyíl", + "84": "Tiltó nyíl", + "85": "Szaggatott nyíl", + "86": "Vonalnyíl", + "87": "Elektronmozgás-nyíl", + "88": "Félnyíl", + "89": "Pluszjel", + "90": "Egyenlőségjel", + "91": "Addukt pont", + "92": "Kerek zárójel", + "93": "Szögletes zárójel", + "94": "Kapcsos zárójel", + "95": "Téglalap", + "96": "Lekerekített téglalap", + "97": "Ellipszis", + "98": "Sokszög", + "99": "Vonal és töröttvonal", + "100": "DC-lemez", + "101": "Kép", + "102": "p pálya", + "103": "s pálya", + "104": "d pálya", + "105": "dz2 pálya", + "106": "sp hibridpálya", + "107": "Szigma-kötés pálya", + "108": "Pi-kötés pálya", + "109": "Vonal hozzáadása", + "110": "Pálya hozzáadása", + "111": "Pluszjel hozzáadása", + "112": "Alakzat hozzáadása", + "113": "Táblázat hozzáadása", + "114": "DC-lemez hozzáadása", + "115": "DC-folt hozzáadása", + "116": "Szöveg, feliratok, képletek vagy SMILES keresése", + "117": "Keresés", + "118": "Csere erre", + "119": "Csere megjelenítése", + "120": "Kis- és nagybetű megkülönböztetése", + "121": "{0} (Shift+F3)", + "122": "Előző találat", + "123": "Következő találat", + "124": "{0} (Esc)", + "125": "Csere", + "126": "Összes cseréje", + "127": "Nincs találat", + "128": "Csere elrejtése", + "129": "1 találat lecserélve", + "130": "{0} találat lecserélve", + "131": "Komponens", + "132": "Tömeg", + "133": "Térfogat", + "134": "Sűrűség", + "135": "Konc.", + "136": "Tisztaság", + "137": "Reaktáns", + "138": "Reagens", + "139": "Termék", + "140": "Automatikus", + "141": "{0} mg · {1} mmol", + "142": "Sztöchiometria szerkesztése", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Izolált", + "146": "Nem található", + "147": "A sablon üres.", + "148": "A(z) {0} ({1}) sablon beszúrva ide: \"{2}\" ({3}), egyetlen visszavonási lépésként", + "149": "Sablon beszúrása", + "150": "Sablonok keresése", + "151": "Sablonkategóriák", + "152": "Sablonok betöltése...", + "153": "Egyetlen sablon sem felel meg a keresésnek.", + "154": "Nyilak", + "155": "Szimbólumok", + "156": "Zárójelek", + "157": "Pályák", + "158": "Alakzatok", + "159": "DC" +} 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" +} diff --git a/frontend/src/i18n/locales/id/part05.json b/frontend/src/i18n/locales/id/part05.json new file mode 100644 index 00000000..083cc6d9 --- /dev/null +++ b/frontend/src/i18n/locales/id/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Menampilkan atau menyembunyikan penggaris di sepanjang tepi atas dan kiri kanvas, dalam satuan gambar (klik sudut untuk mengganti satuan). Seret dari penggaris untuk menempatkan pemandu; seret pemandu kembali ke penggaris untuk menghapusnya. Pilihan ini diingat.", + "1": "Hapus Pemandu", + "2": "Menghapus setiap pemandu penggaris dari gambar aktif di jendela ini. Pemandu tidak pernah disimpan dalam dokumen.", + "3": "Seret pemandu keluar dari penggaris terlebih dahulu", + "4": "Buka bilah cari dan ketik yang ingin dicari terlebih dahulu", + "5": "Membuka bilah cari di atas kanvas. Bilah ini mencari teks, keterangan, sel tabel, label atom dan singkatan, simbol unsur, rumus seperti C2H6O, dan SMILES dalam gambar aktif; Enter atau F3 pindah ke kecocokan berikutnya dan memilihnya.", + "6": "Cari Berikutnya", + "7": "Memilih kecocokan berikutnya dan menggeser tampilan ke sana bila berada di luar layar.", + "8": "Cari Sebelumnya", + "9": "Memilih kecocokan sebelumnya dan menggeser tampilan ke sana bila berada di luar layar.", + "10": "Ganti...", + "11": "Membuka bilah cari dengan baris Ganti. Ganti mengubah kecocokan teks saat ini; Ganti Semua mengubah setiap kecocokan teks dalam satu langkah urungkan.", + "12": "Meminta gambar PNG, JPEG, GIF, WebP, atau SVG dan menempatkannya di tengah halaman yang terlihat dalam satu langkah urungkan.", + "13": "Panel Stoikiometri", + "14": "Membuka pustaka templat; dengan id, menyisipkan templat tersebut (dengan id baru, diskalakan ke panjang ikatan gambar) di tengah tampilan gambar aktif, atau gambar baru, dalam satu langkah urungkan. GET /api/templates mencantumkan id.", + "15": "Id templat dari GET /api/templates, seperti benzene atau l-alanine; kosongkan untuk membuka pustaka", + "16": "Hadir di 0.6.0; sampai saat itu Kenali Reaksi menetapkan peran dari gambar", + "17": "Sisipkan Tabel Stoikiometri", + "18": "Menyisipkan kisi stoikiometri dari langkah reaksi terpilih sebagai tabel di bawah reaksi, atau menyegarkan tabel yang sudah terikat ke langkah itu, dalam satu langkah urungkan.", + "19": "Gambar reaksi dengan panah terlebih dahulu", + "20": "Salin Reaksi Sebagai", + "21": "Ekspor Reaksi", + "22": "Gambar panah reaksi dengan reaktan dan produk terlebih dahulu", + "23": "Reaksi tidak ditemukan: gambar panah dengan struktur di kedua sisinya.", + "24": "Langkah ini tidak memiliki pemetaan atom.", + "25": "Periksa Kesetimbangan", + "26": "Reaksi sudah setara.", + "27": "Reaksi belum setara.", + "28": "{0}: {1} / {2} g/mol", + "29": "Setarakan", + "30": "Reaksi telah disetarakan.", + "31": "Tidak dapat menyetarakan reaksi", + "32": "Reaksi sudah setara.", + "33": "papan klip tidak tersedia", + "34": "Sisipkan Reaksi", + "35": "SMILES reaksi atau RXN", + "36": "Kenali Reaksi", + "37": "Membaca panah reaksi pada halaman dan menyimpan setiap langkah beserta reaktan, produk, agen, dan kondisinya, dalam satu langkah urungkan.", + "38": "Tidak dapat mengenali reaksi", + "39": "Memetakan atom dari langkah reaksi terpilih (mengenali reaksi terlebih dahulu bila belum ada yang tersimpan) dan menandai ikatan yang putus, terbentuk, dan berubah, dalam satu langkah urungkan.", + "40": "Tidak dapat memetakan atom", + "41": "Menghapus nomor pemetaan atom dan tanda pusat reaksi dari langkah reaksi terpilih.", + "42": "Tidak dapat menghapus pemetaan", + "43": "Periksa Kesetimbangan...", + "44": "Menampilkan kesetimbangan unsur, muatan, dan massa dari langkah reaksi terpilih, dengan saran bila belum setara.", + "45": "Tidak dapat memeriksa reaksi", + "46": "Setarakan Reaksi", + "47": "Mengatur koefisien langkah reaksi terpilih ke nilai yang setara, dalam satu langkah urungkan.", + "48": "Salin SMILES Reaksi", + "49": "Tidak dapat menyalin reaksi", + "50": "Salin Reaksi sebagai RXN", + "51": "Ekspor SMILES Reaksi...", + "52": "Tidak dapat mengekspor reaksi", + "53": "Ekspor Reaksi sebagai RXN...", + "54": "Sisipkan Reaksi dari Papan Klip", + "55": "Membaca SMILES reaksi atau berkas RXN dari papan klip dan menata di halaman dengan perannya sudah ditetapkan, dalam satu langkah urungkan.", + "56": "Tidak dapat menyisipkan reaksi", + "57": "Senyawa", + "58": "Peran", + "59": "MW", + "60": "Ekuiv", + "61": "Massa (mg)", + "62": "Volume (mL)", + "63": "Rendemen teoretis", + "64": "Rendemen", + "65": "Satuan penggaris mengikuti gambar; klik untuk mengubah", + "66": "Satuan penggaris; klik untuk mengubah", + "67": "Tambah panah", + "68": "Atur label kurung", + "69": "Tambah kurung", + "70": "Tambah nomor senyawa", + "71": "Tambah keterangan", + "72": "Tambah panah pergerakan elektron", + "73": "Tambah panah setengah kepala", + "74": "Lengkungkan panah", + "75": "Pindahkan ujung panah", + "76": "Pindahkan titik", + "77": "Ubah ukuran", + "78": "Tambah gambar", + "79": "Keterangan", + "80": "Panah reaksi", + "81": "Panah kesetimbangan", + "82": "Panah retrosintetik", + "83": "Panah resonansi", + "84": "Panah terlarang", + "85": "Panah putus-putus", + "86": "Panah garis", + "87": "Panah pergerakan elektron", + "88": "Panah setengah kepala", + "89": "Tanda tambah", + "90": "Tanda sama dengan", + "91": "Titik adduk", + "92": "Kurung bulat", + "93": "Kurung siku", + "94": "Kurung kurawal", + "95": "Persegi panjang", + "96": "Persegi panjang bersudut bulat", + "97": "Elips", + "98": "Poligon", + "99": "Garis dan garis majemuk", + "100": "Pelat KLT", + "101": "Gambar", + "102": "Orbital p", + "103": "Orbital s", + "104": "Orbital d", + "105": "Orbital dz2", + "106": "Orbital hibrida sp", + "107": "Orbital ikatan sigma", + "108": "Orbital ikatan pi", + "109": "Tambah garis", + "110": "Tambah orbital", + "111": "Tambah tanda tambah", + "112": "Tambah bentuk", + "113": "Tambah tabel", + "114": "Tambah pelat KLT", + "115": "Tambah bercak KLT", + "116": "Cari teks, label, rumus, atau SMILES", + "117": "Cari", + "118": "Ganti dengan", + "119": "Tampilkan Ganti", + "120": "Cocokkan Huruf Besar/Kecil", + "121": "{0} (Shift+F3)", + "122": "Kecocokan Sebelumnya", + "123": "Kecocokan Berikutnya", + "124": "{0} (Esc)", + "125": "Ganti", + "126": "Ganti Semua", + "127": "Tidak ada hasil", + "128": "Sembunyikan Ganti", + "129": "1 kecocokan diganti", + "130": "{0} kecocokan diganti", + "131": "Komponen", + "132": "Massa", + "133": "Volume", + "134": "Massa jenis", + "135": "Konsentrasi", + "136": "Kemurnian", + "137": "Reaktan", + "138": "Pereaksi", + "139": "Produk", + "140": "Otomatis", + "141": "{0} mg · {1} mmol", + "142": "Edit Stoikiometri", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Terisolasi", + "146": "Tidak Ditemukan", + "147": "Templat kosong.", + "148": "Templat {0} ({1}) disisipkan ke \"{2}\" ({3}) dalam satu langkah urungkan", + "149": "Sisipkan Templat", + "150": "Cari templat", + "151": "Kategori templat", + "152": "Memuat templat...", + "153": "Tidak ada templat yang cocok dengan pencarian ini.", + "154": "Panah", + "155": "Simbol", + "156": "Kurung", + "157": "Orbital", + "158": "Bentuk", + "159": "KLT" +} 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" +} diff --git a/frontend/src/i18n/locales/it/part05.json b/frontend/src/i18n/locales/it/part05.json new file mode 100644 index 00000000..24caa66f --- /dev/null +++ b/frontend/src/i18n/locales/it/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Mostra o nasconde i righelli lungo i bordi superiore e sinistro dell'area di disegno, nelle unità del disegno (clicca sull'angolo per cambiare unità). Trascina da un righello per posizionare una guida; trascina una guida di nuovo su un righello per rimuoverla. La scelta viene ricordata.", + "1": "Cancella guide", + "2": "Rimuove ogni guida dei righelli dal disegno attivo in questa finestra. Le guide non vengono mai salvate nel documento.", + "3": "Trascina prima una guida fuori da un righello", + "4": "Apri prima la barra di ricerca e digita cosa cercare", + "5": "Apre la barra di ricerca sopra l'area di disegno. Trova testo, didascalie, celle di tabella, etichette e abbreviazioni degli atomi, simboli degli elementi, formule come C2H6O e SMILES nel disegno attivo; Invio o F3 passa alla corrispondenza successiva e la seleziona.", + "6": "Trova successivo", + "7": "Seleziona la corrispondenza successiva e sposta la vista su di essa se è fuori schermo.", + "8": "Trova precedente", + "9": "Seleziona la corrispondenza precedente e sposta la vista su di essa se è fuori schermo.", + "10": "Sostituisci...", + "11": "Apre la barra di ricerca con la riga Sostituisci. Sostituisci modifica la corrispondenza di testo corrente; Sostituisci tutto modifica ogni corrispondenza di testo in un solo passaggio di annullamento.", + "12": "Chiede un'immagine PNG, JPEG, GIF, WebP o SVG e la posiziona al centro della pagina visibile in un solo passaggio di annullamento.", + "13": "Pannello stechiometria", + "14": "Apre la libreria dei modelli; con un id inserisce quel modello (nuovi id, scalato sulla lunghezza di legame del disegno) al centro della vista del disegno attivo, o di uno nuovo, in un solo passaggio di annullamento. GET /api/templates elenca gli id.", + "15": "Id del modello da GET /api/templates, come benzene o l-alanine; omettilo per aprire la libreria", + "16": "Arriva nella 0.6.0; fino ad allora Riconosci reazioni imposta i ruoli dal disegno", + "17": "Inserisci tabella stechiometrica", + "18": "Inserisce la griglia stechiometrica del passaggio di reazione selezionato come tabella sotto la reazione, oppure aggiorna la tabella già legata a quel passaggio, in un solo passaggio di annullamento.", + "19": "Disegna prima una reazione con una freccia", + "20": "Copia reazione come", + "21": "Esporta reazione", + "22": "Disegna prima una freccia di reazione con reagenti e prodotti", + "23": "Nessuna reazione trovata: disegna una freccia con strutture su entrambi i lati.", + "24": "Il passaggio non ha mappatura degli atomi.", + "25": "Verifica bilanciamento", + "26": "La reazione è bilanciata.", + "27": "La reazione non è bilanciata.", + "28": "{0}: {1} / {2} g/mol", + "29": "Bilancia", + "30": "Reazione bilanciata.", + "31": "Impossibile bilanciare la reazione", + "32": "La reazione è già bilanciata.", + "33": "gli appunti non sono disponibili", + "34": "Inserisci reazione", + "35": "SMILES di reazione o RXN", + "36": "Riconosci reazioni", + "37": "Legge le frecce di reazione della pagina e memorizza ogni passaggio con i suoi reagenti, prodotti, agenti e condizioni, in un solo passaggio di annullamento.", + "38": "Impossibile riconoscere le reazioni", + "39": "Mappa gli atomi del passaggio di reazione selezionato (riconoscendo prima le reazioni se nessuna è memorizzata) e segna i legami rotti, formati e modificati, in un solo passaggio di annullamento.", + "40": "Impossibile mappare gli atomi", + "41": "Rimuove i numeri di mappatura degli atomi e i segni del centro di reazione del passaggio di reazione selezionato.", + "42": "Impossibile cancellare la mappatura", + "43": "Verifica bilanciamento...", + "44": "Mostra il bilancio di elementi, carica e massa del passaggio di reazione selezionato, con un suggerimento se non è bilanciato.", + "45": "Impossibile verificare la reazione", + "46": "Bilancia reazione", + "47": "Imposta i coefficienti del passaggio di reazione selezionato ai valori bilanciati, in un solo passaggio di annullamento.", + "48": "Copia SMILES di reazione", + "49": "Impossibile copiare la reazione", + "50": "Copia reazione come RXN", + "51": "Esporta SMILES di reazione...", + "52": "Impossibile esportare la reazione", + "53": "Esporta reazione come RXN...", + "54": "Inserisci reazione dagli appunti", + "55": "Legge uno SMILES di reazione o un file RXN dagli appunti e lo dispone sulla pagina con i ruoli impostati, in un solo passaggio di annullamento.", + "56": "Impossibile inserire la reazione", + "57": "Composto", + "58": "Ruolo", + "59": "MW", + "60": "Equiv", + "61": "Massa (mg)", + "62": "Volume (mL)", + "63": "Resa teorica", + "64": "Resa", + "65": "Le unità del righello seguono il disegno; clicca per cambiare", + "66": "Unità del righello; clicca per cambiare", + "67": "Aggiungi freccia", + "68": "Imposta etichetta della parentesi", + "69": "Aggiungi parentesi", + "70": "Aggiungi numero del composto", + "71": "Aggiungi didascalia", + "72": "Aggiungi freccia di spostamento elettronico", + "73": "Aggiungi freccia a mezza punta", + "74": "Curva freccia", + "75": "Sposta estremità della freccia", + "76": "Sposta punto", + "77": "Ridimensiona", + "78": "Aggiungi immagine", + "79": "Didascalia", + "80": "Freccia di reazione", + "81": "Freccia di equilibrio", + "82": "Freccia retrosintetica", + "83": "Freccia di risonanza", + "84": "Freccia di reazione non avvenuta", + "85": "Freccia tratteggiata", + "86": "Freccia a linea", + "87": "Freccia di spostamento elettronico", + "88": "Freccia a mezza punta", + "89": "Segno più", + "90": "Segno uguale", + "91": "Punto di addotto", + "92": "Parentesi tonde", + "93": "Parentesi quadre", + "94": "Parentesi graffe", + "95": "Rettangolo", + "96": "Rettangolo arrotondato", + "97": "Ellisse", + "98": "Poligono", + "99": "Linea e spezzata", + "100": "Lastra TLC", + "101": "Immagine", + "102": "Orbitale p", + "103": "Orbitale s", + "104": "Orbitale d", + "105": "Orbitale dz2", + "106": "Orbitale ibrido sp", + "107": "Orbitale del legame sigma", + "108": "Orbitale del legame pi greco", + "109": "Aggiungi linea", + "110": "Aggiungi orbitale", + "111": "Aggiungi segno più", + "112": "Aggiungi forma", + "113": "Aggiungi tabella", + "114": "Aggiungi lastra TLC", + "115": "Aggiungi macchia TLC", + "116": "Trova testo, etichette, formule o SMILES", + "117": "Trova", + "118": "Sostituisci con", + "119": "Mostra Sostituisci", + "120": "Maiuscole/minuscole", + "121": "{0} (Shift+F3)", + "122": "Corrispondenza precedente", + "123": "Corrispondenza successiva", + "124": "{0} (Esc)", + "125": "Sostituisci", + "126": "Sostituisci tutto", + "127": "Nessun risultato", + "128": "Nascondi Sostituisci", + "129": "Sostituita 1 corrispondenza", + "130": "Sostituite {0} corrispondenze", + "131": "Componente", + "132": "Massa", + "133": "Volume", + "134": "Densità", + "135": "Conc", + "136": "Purezza", + "137": "Reagente", + "138": "Reattivo", + "139": "Prodotto", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Modifica stechiometria", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isolata", + "146": "Non trovato", + "147": "Il modello è vuoto.", + "148": "Inserito il modello {0} ({1}) in \"{2}\" ({3}) in un solo passaggio di annullamento", + "149": "Inserisci modello", + "150": "Cerca modelli", + "151": "Categorie di modelli", + "152": "Caricamento dei modelli...", + "153": "Nessun modello corrisponde a questa ricerca.", + "154": "Frecce", + "155": "Simboli", + "156": "Parentesi", + "157": "Orbitali", + "158": "Forme", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/ja/part05.json b/frontend/src/i18n/locales/ja/part05.json new file mode 100644 index 00000000..e700e625 --- /dev/null +++ b/frontend/src/i18n/locales/ja/part05.json @@ -0,0 +1,162 @@ +{ + "0": "キャンバスの上端と左端のルーラを、図面の単位で表示または非表示にします(角をクリックすると単位を切り替えます)。ルーラからドラッグするとガイドを置け、ガイドをルーラへドラッグして戻すと削除されます。この設定は記憶されます。", + "1": "ガイドを消去", + "2": "このウィンドウで開いている図面のルーラガイドをすべて削除します。ガイドはドキュメントには保存されません。", + "3": "先にルーラからガイドをドラッグしてください", + "4": "先に検索バーを開き、検索する文字列を入力してください", + "5": "キャンバスの上に検索バーを開きます。開いている図面から、テキスト、キャプション、表のセル、原子ラベルと略号、元素記号、C2H6O などの分子式、SMILES を検索します。Enter または F3 で次の一致箇所に移動して選択します。", + "6": "次を検索", + "7": "次の一致箇所を選択し、画面外にある場合はそこまでスクロールします。", + "8": "前を検索", + "9": "前の一致箇所を選択し、画面外にある場合はそこまでスクロールします。", + "10": "置換...", + "11": "置換欄つきで検索バーを開きます。「置換」は現在のテキストの一致箇所を変更し、「すべて置換」はテキストの一致箇所をすべて、取り消し 1 回分としてまとめて変更します。", + "12": "PNG、JPEG、GIF、WebP、SVG の画像を選んでもらい、表示中のページの中央に、取り消し 1 回分として配置します。", + "13": "化学量論パネル", + "14": "テンプレートライブラリを開きます。id を指定すると、そのテンプレート(新しい id を割り当て、図面の結合長に合わせて拡大縮小)を、開いている図面の表示範囲の中央または新しい図面に、取り消し 1 回分として挿入します。id の一覧は GET /api/templates で取得できます。", + "15": "GET /api/templates のテンプレート id (benzene、l-alanine など)。省略するとライブラリを開きます", + "16": "0.6.0 で提供されます。それまでは「反応を認識」で図面から役割を設定します", + "17": "化学量論の表を挿入", + "18": "選択した反応ステップの化学量論グリッドを、反応の下に表として挿入します。すでにそのステップに結び付いた表がある場合は更新します。取り消し 1 回分です。", + "19": "先に矢印で反応を描いてください", + "20": "反応をコピー形式", + "21": "反応を書き出し", + "22": "先に反応物と生成物のある反応矢印を描いてください", + "23": "反応が見つかりません。両側に構造がある矢印を描いてください。", + "24": "このステップには原子マッピングがありません。", + "25": "収支を確認", + "26": "反応は釣り合っています。", + "27": "反応は釣り合っていません。", + "28": "{0}: {1} / {2} g/mol", + "29": "係数を調整", + "30": "反応の係数を調整しました。", + "31": "反応の係数を調整できませんでした", + "32": "反応はすでに釣り合っています。", + "33": "クリップボードを利用できません", + "34": "反応を挿入", + "35": "反応 SMILES または RXN", + "36": "反応を認識", + "37": "ページ上の反応矢印を読み取り、各ステップの反応物、生成物、試薬、条件を、取り消し 1 回分として保存します。", + "38": "反応を認識できませんでした", + "39": "選択した反応ステップの原子をマッピングし(反応が保存されていない場合は先に反応を認識します)、切断、生成、変化した結合に印を付けます。取り消し 1 回分です。", + "40": "原子をマッピングできませんでした", + "41": "選択した反応ステップの原子マップ番号と反応中心の印を削除します。", + "42": "マッピングを消去できませんでした", + "43": "収支を確認...", + "44": "選択した反応ステップの元素、電荷、質量の収支を表示します。釣り合っていない場合は提案も表示します。", + "45": "反応を確認できませんでした", + "46": "反応の係数を調整", + "47": "選択した反応ステップの係数を釣り合う値に設定します。取り消し 1 回分です。", + "48": "反応 SMILES をコピー", + "49": "反応をコピーできませんでした", + "50": "反応を RXN としてコピー", + "51": "反応 SMILES を書き出し...", + "52": "反応を書き出せませんでした", + "53": "反応を RXN として書き出し...", + "54": "クリップボードから反応を挿入", + "55": "クリップボードから反応 SMILES または RXN ファイルを読み取り、役割を設定してページに配置します。取り消し 1 回分です。", + "56": "反応を挿入できませんでした", + "57": "化合物", + "58": "役割", + "59": "MW", + "60": "当量", + "61": "質量 (mg)", + "62": "体積 (mL)", + "63": "理論収量", + "64": "収率", + "65": "ルーラの単位は図面に従います。クリックで変更", + "66": "ルーラの単位。クリックで変更", + "67": "矢印を追加", + "68": "括弧のラベルを設定", + "69": "括弧を追加", + "70": "化合物番号を追加", + "71": "キャプションを追加", + "72": "電子移動の矢印を追加", + "73": "片羽矢印を追加", + "74": "矢印を曲げる", + "75": "矢印の端を移動", + "76": "点を移動", + "77": "サイズ変更", + "78": "画像を追加", + "79": "キャプション", + "80": "反応矢印", + "81": "平衡矢印", + "82": "逆合成矢印", + "83": "共鳴矢印", + "84": "不可矢印", + "85": "破線矢印", + "86": "線の矢印", + "87": "電子移動の矢印", + "88": "片羽矢印", + "89": "プラス記号", + "90": "等号", + "91": "付加体のドット", + "92": "丸括弧", + "93": "角括弧", + "94": "波括弧", + "95": "長方形", + "96": "角丸長方形", + "97": "楕円", + "98": "多角形", + "99": "線と折れ線", + "100": "TLC プレート", + "101": "画像", + "102": "p 軌道", + "103": "s 軌道", + "104": "d 軌道", + "105": "dz2 軌道", + "106": "sp 混成軌道", + "107": "σ 結合の軌道", + "108": "π 結合の軌道", + "109": "線を追加", + "110": "軌道を追加", + "111": "プラス記号を追加", + "112": "図形を追加", + "113": "表を追加", + "114": "TLC プレートを追加", + "115": "TLC スポットを追加", + "116": "テキスト、ラベル、分子式、SMILES を検索", + "117": "検索", + "118": "置換後の文字列", + "119": "置換を表示", + "120": "大文字と小文字を区別", + "121": "{0} (Shift+F3)", + "122": "前の一致箇所", + "123": "次の一致箇所", + "124": "{0} (Esc)", + "125": "置換", + "126": "すべて置換", + "127": "結果なし", + "128": "置換を非表示", + "129": "1 件を置換しました", + "130": "{0} 件を置換しました", + "131": "成分", + "132": "質量", + "133": "体積", + "134": "密度", + "135": "濃度", + "136": "純度", + "137": "反応物", + "138": "試薬", + "139": "生成物", + "140": "自動", + "141": "{0} mg · {1} mmol", + "142": "化学量論を編集", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "単離収率", + "146": "見つかりません", + "147": "テンプレートが空です。", + "148": "テンプレート {0} ({1}) を「{2}」({3}) に、取り消し 1 回分として挿入しました", + "149": "テンプレートを挿入", + "150": "テンプレートを検索", + "151": "テンプレートのカテゴリ", + "152": "テンプレートを読み込み中...", + "153": "この検索に一致するテンプレートはありません。", + "154": "矢印", + "155": "記号", + "156": "括弧", + "157": "軌道", + "158": "図形", + "159": "TLC" +} 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": "キャンバス上で選択" +} diff --git a/frontend/src/i18n/locales/ko/part05.json b/frontend/src/i18n/locales/ko/part05.json new file mode 100644 index 00000000..30f10ff9 --- /dev/null +++ b/frontend/src/i18n/locales/ko/part05.json @@ -0,0 +1,162 @@ +{ + "0": "캔버스 위쪽과 왼쪽 가장자리의 눈금자를 도면 단위로 표시하거나 숨깁니다(모서리를 클릭하면 단위가 바뀝니다). 눈금자에서 드래그하면 안내선을 놓을 수 있고, 안내선을 눈금자로 다시 끌어오면 삭제됩니다. 이 설정은 기억됩니다.", + "1": "안내선 지우기", + "2": "이 창에서 열린 도면의 눈금자 안내선을 모두 제거합니다. 안내선은 문서에 저장되지 않습니다.", + "3": "먼저 눈금자에서 안내선을 끌어내세요", + "4": "먼저 찾기 막대를 열고 찾을 내용을 입력하세요", + "5": "캔버스 위에 찾기 막대를 엽니다. 열린 도면에서 텍스트, 캡션, 표 셀, 원자 레이블과 약어, 원소 기호, C2H6O 같은 분자식, SMILES를 찾습니다. Enter 또는 F3을 누르면 다음 일치 항목으로 이동해 선택합니다.", + "6": "다음 찾기", + "7": "다음 일치 항목을 선택하고, 화면 밖에 있으면 그 위치로 이동합니다.", + "8": "이전 찾기", + "9": "이전 일치 항목을 선택하고, 화면 밖에 있으면 그 위치로 이동합니다.", + "10": "바꾸기...", + "11": "바꾸기 줄과 함께 찾기 막대를 엽니다. 바꾸기는 현재 텍스트 일치 항목을 바꾸고, 모두 바꾸기는 모든 텍스트 일치 항목을 실행 취소 한 번으로 바꿉니다.", + "12": "PNG, JPEG, GIF, WebP 또는 SVG 그림을 선택하게 하고, 보이는 페이지의 가운데에 실행 취소 한 번으로 배치합니다.", + "13": "화학량론 패널", + "14": "템플릿 라이브러리를 엽니다. id를 지정하면 해당 템플릿(새 id를 부여하고 도면의 결합 길이에 맞게 크기 조정)을 열린 도면의 보기 가운데 또는 새 도면에 실행 취소 한 번으로 삽입합니다. id 목록은 GET /api/templates에서 확인할 수 있습니다.", + "15": "GET /api/templates의 템플릿 id(예: benzene, l-alanine). 생략하면 라이브러리를 엽니다", + "16": "0.6.0에서 제공됩니다. 그때까지는 반응 인식으로 도면에서 역할을 설정합니다", + "17": "화학량론 표 삽입", + "18": "선택한 반응 단계의 화학량론 표를 반응 아래에 표로 삽입하거나, 이미 그 단계에 연결된 표를 새로 고칩니다. 실행 취소 한 번으로 처리됩니다.", + "19": "먼저 화살표로 반응을 그리세요", + "20": "반응 복사 형식", + "21": "반응 내보내기", + "22": "먼저 반응물과 생성물이 있는 반응 화살표를 그리세요", + "23": "반응을 찾을 수 없습니다. 양쪽에 구조가 있는 화살표를 그리세요.", + "24": "이 단계에는 원자 매핑이 없습니다.", + "25": "균형 확인", + "26": "반응의 균형이 맞습니다.", + "27": "반응의 균형이 맞지 않습니다.", + "28": "{0}: {1} / {2} g/mol", + "29": "균형 맞추기", + "30": "반응의 균형을 맞췄습니다.", + "31": "반응의 균형을 맞출 수 없습니다", + "32": "반응의 균형이 이미 맞습니다.", + "33": "클립보드를 사용할 수 없습니다", + "34": "반응 삽입", + "35": "반응 SMILES 또는 RXN", + "36": "반응 인식", + "37": "페이지의 반응 화살표를 읽어 각 단계의 반응물, 생성물, 시약, 조건을 실행 취소 한 번으로 저장합니다.", + "38": "반응을 인식할 수 없습니다", + "39": "선택한 반응 단계의 원자를 매핑하고(저장된 반응이 없으면 먼저 반응을 인식합니다) 끊어지거나 생성되거나 바뀐 결합을 표시합니다. 실행 취소 한 번으로 처리됩니다.", + "40": "원자를 매핑할 수 없습니다", + "41": "선택한 반응 단계의 원자 매핑 번호와 반응 중심 표시를 제거합니다.", + "42": "매핑을 지울 수 없습니다", + "43": "균형 확인...", + "44": "선택한 반응 단계의 원소, 전하, 질량 균형을 보여 주며, 균형이 맞지 않으면 제안을 함께 표시합니다.", + "45": "반응을 확인할 수 없습니다", + "46": "반응 균형 맞추기", + "47": "선택한 반응 단계의 계수를 균형이 맞는 값으로 설정합니다. 실행 취소 한 번으로 처리됩니다.", + "48": "반응 SMILES 복사", + "49": "반응을 복사할 수 없습니다", + "50": "반응을 RXN으로 복사", + "51": "반응 SMILES 내보내기...", + "52": "반응을 내보낼 수 없습니다", + "53": "반응을 RXN으로 내보내기...", + "54": "클립보드에서 반응 삽입", + "55": "클립보드에서 반응 SMILES 또는 RXN 파일을 읽어 역할을 설정한 채 페이지에 배치합니다. 실행 취소 한 번으로 처리됩니다.", + "56": "반응을 삽입할 수 없습니다", + "57": "화합물", + "58": "역할", + "59": "MW", + "60": "당량", + "61": "질량 (mg)", + "62": "부피 (mL)", + "63": "이론 수득량", + "64": "수율", + "65": "눈금자 단위는 도면을 따릅니다. 클릭하여 변경", + "66": "눈금자 단위. 클릭하여 변경", + "67": "화살표 추가", + "68": "괄호 레이블 설정", + "69": "괄호 추가", + "70": "화합물 번호 추가", + "71": "캡션 추가", + "72": "전자 이동 화살표 추가", + "73": "외가닥 화살표 추가", + "74": "화살표 구부리기", + "75": "화살표 끝 이동", + "76": "점 이동", + "77": "크기 조정", + "78": "그림 추가", + "79": "캡션", + "80": "반응 화살표", + "81": "평형 화살표", + "82": "역합성 화살표", + "83": "공명 화살표", + "84": "불가 화살표", + "85": "점선 화살표", + "86": "선 화살표", + "87": "전자 이동 화살표", + "88": "외가닥 화살표", + "89": "더하기 기호", + "90": "등호", + "91": "부가물 점", + "92": "둥근 괄호", + "93": "대괄호", + "94": "중괄호", + "95": "직사각형", + "96": "둥근 직사각형", + "97": "타원", + "98": "다각형", + "99": "선과 폴리라인", + "100": "TLC 플레이트", + "101": "그림", + "102": "p 오비탈", + "103": "s 오비탈", + "104": "d 오비탈", + "105": "dz2 오비탈", + "106": "sp 혼성 오비탈", + "107": "시그마 결합 오비탈", + "108": "파이 결합 오비탈", + "109": "선 추가", + "110": "오비탈 추가", + "111": "더하기 기호 추가", + "112": "도형 추가", + "113": "표 추가", + "114": "TLC 플레이트 추가", + "115": "TLC 스폿 추가", + "116": "텍스트, 레이블, 분자식 또는 SMILES 찾기", + "117": "찾기", + "118": "바꿀 내용", + "119": "바꾸기 표시", + "120": "대소문자 구분", + "121": "{0} (Shift+F3)", + "122": "이전 일치 항목", + "123": "다음 일치 항목", + "124": "{0} (Esc)", + "125": "바꾸기", + "126": "모두 바꾸기", + "127": "결과 없음", + "128": "바꾸기 숨기기", + "129": "1개를 바꿨습니다", + "130": "{0}개를 바꿨습니다", + "131": "성분", + "132": "질량", + "133": "부피", + "134": "밀도", + "135": "농도", + "136": "순도", + "137": "반응물", + "138": "시약", + "139": "생성물", + "140": "자동", + "141": "{0} mg · {1} mmol", + "142": "화학량론 편집", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "분리 수율", + "146": "찾을 수 없음", + "147": "템플릿이 비어 있습니다.", + "148": "템플릿 {0}({1})을(를) \"{2}\"({3})에 실행 취소 한 번으로 삽입했습니다", + "149": "템플릿 삽입", + "150": "템플릿 검색", + "151": "템플릿 범주", + "152": "템플릿을 불러오는 중...", + "153": "이 검색과 일치하는 템플릿이 없습니다.", + "154": "화살표", + "155": "기호", + "156": "괄호", + "157": "오비탈", + "158": "도형", + "159": "TLC" +} 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": "캔버스에서 선택" +} diff --git a/frontend/src/i18n/locales/nb/part05.json b/frontend/src/i18n/locales/nb/part05.json new file mode 100644 index 00000000..2486a825 --- /dev/null +++ b/frontend/src/i18n/locales/nb/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Viser eller skjuler linjaler langs øvre og venstre kant av lerretet, i tegningens enheter (klikk i hjørnet for å bytte enhet). Dra fra en linjal for å sette ut en hjelpelinje; dra en hjelpelinje tilbake til en linjal for å fjerne den. Valget huskes.", + "1": "Fjern hjelpelinjer", + "2": "Fjerner alle hjelpelinjer fra den aktive tegningen i dette vinduet. Hjelpelinjer lagres aldri i dokumentet.", + "3": "Dra først en hjelpelinje ut fra en linjal", + "4": "Åpne søkefeltet og skriv først inn hva som skal finnes", + "5": "Åpner søkefeltet over lerretet. Det finner tekst, bildetekster, tabellceller, atometiketter og forkortelser, elementsymboler, formler som C2H6O og SMILES i den aktive tegningen; Enter eller F3 går til neste treff og markerer det.", + "6": "Finn neste", + "7": "Markerer neste søketreff og panorerer til det når det er utenfor skjermen.", + "8": "Finn forrige", + "9": "Markerer forrige søketreff og panorerer til det når det er utenfor skjermen.", + "10": "Erstatt...", + "11": "Åpner søkefeltet med erstatningsraden. Erstatt endrer gjeldende teksttreff; Erstatt alle endrer alle teksttreff i ett angretrinn.", + "12": "Ber brukeren om et PNG-, JPEG-, GIF-, WebP- eller SVG-bilde og plasserer det midt på den synlige siden i ett angretrinn.", + "13": "Støkiometripanel", + "14": "Åpner malbiblioteket; med id setter den inn den malen (nye id-er, skalert til tegningens bindingslengde) midt i visningen av den aktive tegningen, eller i en ny, i ett angretrinn. GET /api/templates viser id-ene.", + "15": "Mal-id fra GET /api/templates, for eksempel benzene eller l-alanine; utelat den for å åpne biblioteket", + "16": "Kommer i 0.6.0; inntil da setter Gjenkjenn reaksjoner rollene ut fra tegningen", + "17": "Sett inn støkiometritabell", + "18": "Setter inn støkiometrirutenettet for det valgte reaksjonstrinnet som en tabell under reaksjonen, eller oppdaterer tabellen som allerede er knyttet til trinnet, i ett angretrinn.", + "19": "Tegn først en reaksjon med en pil", + "20": "Kopier reaksjon som", + "21": "Eksporter reaksjon", + "22": "Tegn først en reaksjonspil med reaktanter og produkter", + "23": "Fant ingen reaksjon: tegn en pil med strukturer på begge sider.", + "24": "Trinnet har ingen atomkartlegging.", + "25": "Kontroller balanse", + "26": "Reaksjonen er balansert.", + "27": "Reaksjonen er ikke balansert.", + "28": "{0}: {1} / {2} g/mol", + "29": "Balanser", + "30": "Reaksjonen ble balansert.", + "31": "Kunne ikke balansere reaksjonen", + "32": "Reaksjonen er allerede balansert.", + "33": "utklippstavlen er ikke tilgjengelig", + "34": "Sett inn reaksjon", + "35": "Reaksjons-SMILES eller RXN", + "36": "Gjenkjenn reaksjoner", + "37": "Leser reaksjonspilene på siden og lagrer hvert trinn med reaktanter, produkter, agenter og betingelser, i ett angretrinn.", + "38": "Kunne ikke gjenkjenne reaksjonene", + "39": "Kartlegger atomene i det valgte reaksjonstrinnet (gjenkjenner reaksjoner først hvis ingen er lagret) og markerer bindinger som brytes, dannes og endres, i ett angretrinn.", + "40": "Kunne ikke kartlegge atomene", + "41": "Fjerner atomkartleggingsnumrene og markeringene av reaksjonssenteret for det valgte reaksjonstrinnet.", + "42": "Kunne ikke fjerne kartleggingen", + "43": "Kontroller balanse...", + "44": "Viser grunnstoff-, ladnings- og massebalansen for det valgte reaksjonstrinnet, med et forslag når det ikke er balansert.", + "45": "Kunne ikke kontrollere reaksjonen", + "46": "Balanser reaksjon", + "47": "Setter koeffisientene for det valgte reaksjonstrinnet til de balanserte verdiene, i ett angretrinn.", + "48": "Kopier reaksjons-SMILES", + "49": "Kunne ikke kopiere reaksjonen", + "50": "Kopier reaksjon som RXN", + "51": "Eksporter reaksjons-SMILES...", + "52": "Kunne ikke eksportere reaksjonen", + "53": "Eksporter reaksjon som RXN...", + "54": "Sett inn reaksjon fra utklippstavlen", + "55": "Leser reaksjons-SMILES eller en RXN-fil fra utklippstavlen og legger den ut på siden med rollene satt, i ett angretrinn.", + "56": "Kunne ikke sette inn reaksjonen", + "57": "Forbindelse", + "58": "Rolle", + "59": "MW", + "60": "Ekv", + "61": "Masse (mg)", + "62": "Volum (mL)", + "63": "Teoretisk utbytte", + "64": "Utbytte", + "65": "Linjaleenheter følger tegningen; klikk for å endre", + "66": "Linjaleenheter; klikk for å endre", + "67": "Legg til pil", + "68": "Angi klammeetikett", + "69": "Legg til klamme", + "70": "Legg til forbindelsesnummer", + "71": "Legg til bildetekst", + "72": "Legg til elektronpil", + "73": "Legg til enkeltelektronpil", + "74": "Bøy pil", + "75": "Flytt pilende", + "76": "Flytt punkt", + "77": "Endre størrelse", + "78": "Legg til bilde", + "79": "Bildetekst", + "80": "Reaksjonspil", + "81": "Likevektspil", + "82": "Retrosyntetisk pil", + "83": "Resonanspil", + "84": "Overstreket pil", + "85": "Stiplet pil", + "86": "Linjepil", + "87": "Elektronpil", + "88": "Enkeltelektronpil", + "89": "Plusstegn", + "90": "Likhetstegn", + "91": "Adduktprikk", + "92": "Runde parenteser", + "93": "Hakeparenteser", + "94": "Krøllparenteser", + "95": "Rektangel", + "96": "Avrundet rektangel", + "97": "Ellipse", + "98": "Mangekant", + "99": "Linje og polylinje", + "100": "TLC-plate", + "101": "Bilde", + "102": "p-orbital", + "103": "s-orbital", + "104": "d-orbital", + "105": "dz2-orbital", + "106": "sp-hybridorbital", + "107": "Sigmabindingsorbital", + "108": "Pibindingsorbital", + "109": "Legg til linje", + "110": "Legg til orbital", + "111": "Legg til plusstegn", + "112": "Legg til form", + "113": "Legg til tabell", + "114": "Legg til TLC-plate", + "115": "Legg til TLC-flekk", + "116": "Finn tekst, etiketter, formler eller SMILES", + "117": "Finn", + "118": "Erstatt med", + "119": "Vis erstatning", + "120": "Skill mellom store og små bokstaver", + "121": "{0} (Shift+F3)", + "122": "Forrige treff", + "123": "Neste treff", + "124": "{0} (Esc)", + "125": "Erstatt", + "126": "Erstatt alle", + "127": "Ingen resultater", + "128": "Skjul erstatning", + "129": "Erstattet 1 treff", + "130": "Erstattet {0} treff", + "131": "Komponent", + "132": "Masse", + "133": "Volum", + "134": "Tetthet", + "135": "Konsentrasjon", + "136": "Renhet", + "137": "Reaktant", + "138": "Reagens", + "139": "Produkt", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Rediger støkiometri", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isolert", + "146": "Ikke funnet", + "147": "Malen er tom.", + "148": "Satte inn malen {0} ({1}) i \"{2}\" ({3}) i ett angretrinn", + "149": "Sett inn mal", + "150": "Søk i maler", + "151": "Malkategorier", + "152": "Laster maler...", + "153": "Ingen maler samsvarer med søket.", + "154": "Piler", + "155": "Symboler", + "156": "Klammer", + "157": "Orbitaler", + "158": "Former", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/nl/part05.json b/frontend/src/i18n/locales/nl/part05.json new file mode 100644 index 00000000..5d70773e --- /dev/null +++ b/frontend/src/i18n/locales/nl/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Toont of verbergt linialen langs de boven- en linkerrand van het tekengebied, in de tekeneenheden (klik op de hoek om van eenheid te wisselen). Sleep vanuit een liniaal om een hulplijn te plaatsen; sleep een hulplijn terug naar een liniaal om hem te verwijderen. De keuze wordt onthouden.", + "1": "Hulplijnen wissen", + "2": "Verwijdert alle hulplijnen van de linialen uit de actieve tekening in dit venster. Hulplijnen worden nooit in het document opgeslagen.", + "3": "Sleep eerst een hulplijn uit een liniaal", + "4": "Open eerst de zoekbalk en typ wat u zoekt", + "5": "Opent de zoekbalk boven het tekengebied. Zoekt tekst, bijschriften, tabelcellen, atoomlabels en afkortingen, elementsymbolen, formules zoals C2H6O en SMILES in de actieve tekening; Enter of F3 gaat naar de volgende treffer en selecteert die.", + "6": "Volgende zoeken", + "7": "Selecteert de volgende treffer en schuift de weergave ernaartoe als die buiten beeld ligt.", + "8": "Vorige zoeken", + "9": "Selecteert de vorige treffer en schuift de weergave ernaartoe als die buiten beeld ligt.", + "10": "Vervangen...", + "11": "Opent de zoekbalk met de rij Vervangen. Vervangen wijzigt de huidige teksttreffer; Alles vervangen wijzigt elke teksttreffer in één ongedaanmakingsstap.", + "12": "Vraagt om een PNG-, JPEG-, GIF-, WebP- of SVG-afbeelding en plaatst die in het midden van de zichtbare pagina in één ongedaanmakingsstap.", + "13": "Stoichiometriepaneel", + "14": "Opent de sjabloonbibliotheek; met een id wordt dat sjabloon (nieuwe id's, geschaald naar de bindingslengte van de tekening) gecentreerd in de weergave van de actieve tekening, of een nieuwe, ingevoegd in één ongedaanmakingsstap. GET /api/templates toont de id's.", + "15": "Sjabloon-id uit GET /api/templates, zoals benzene of l-alanine; laat weg om de bibliotheek te openen", + "16": "Komt in 0.6.0; tot dan stelt Reacties herkennen de rollen in vanuit de tekening", + "17": "Stoichiometrietabel invoegen", + "18": "Voegt het stoichiometrieraster van de geselecteerde reactiestap in als tabel onder de reactie, of vernieuwt de tabel die al aan die stap is gekoppeld, in één ongedaanmakingsstap.", + "19": "Teken eerst een reactie met een pijl", + "20": "Reactie kopiëren als", + "21": "Reactie exporteren", + "22": "Teken eerst een reactiepijl met reactanten en producten", + "23": "Geen reactie gevonden: teken een pijl met structuren aan beide kanten.", + "24": "De stap heeft geen atoommapping.", + "25": "Balans controleren", + "26": "De reactie is in evenwicht.", + "27": "De reactie is niet in evenwicht.", + "28": "{0}: {1} / {2} g/mol", + "29": "Balans", + "30": "De reactie is in evenwicht gebracht.", + "31": "Kon de reactie niet in evenwicht brengen", + "32": "De reactie is al in evenwicht.", + "33": "het klembord is niet beschikbaar", + "34": "Reactie invoegen", + "35": "Reactie-SMILES of RXN", + "36": "Reacties herkennen", + "37": "Leest de reactiepijlen op de pagina en slaat elke stap op met zijn reactanten, producten, agentia en omstandigheden, in één ongedaanmakingsstap.", + "38": "Kon de reacties niet herkennen", + "39": "Wijst de atomen van de geselecteerde reactiestap toe (en herkent eerst de reacties als er geen zijn opgeslagen) en markeert de verbroken, gevormde en gewijzigde bindingen, in één ongedaanmakingsstap.", + "40": "Kon de atomen niet toewijzen", + "41": "Verwijdert de atoommappingnummers en de markeringen van het reactiecentrum van de geselecteerde reactiestap.", + "42": "Kon de mapping niet wissen", + "43": "Balans controleren...", + "44": "Toont de element-, lading- en massabalans van de geselecteerde reactiestap, met een suggestie als die niet in evenwicht is.", + "45": "Kon de reactie niet controleren", + "46": "Reactie in evenwicht brengen", + "47": "Stelt de coëfficiënten van de geselecteerde reactiestap in op de waarden in evenwicht, in één ongedaanmakingsstap.", + "48": "Reactie-SMILES kopiëren", + "49": "Kon de reactie niet kopiëren", + "50": "Reactie kopiëren als RXN", + "51": "Reactie-SMILES exporteren...", + "52": "Kon de reactie niet exporteren", + "53": "Reactie exporteren als RXN...", + "54": "Reactie invoegen vanaf klembord", + "55": "Leest reactie-SMILES of een RXN-bestand van het klembord en legt die op de pagina neer met ingestelde rollen, in één ongedaanmakingsstap.", + "56": "Kon de reactie niet invoegen", + "57": "Verbinding", + "58": "Rol", + "59": "MW", + "60": "Equiv", + "61": "Massa (mg)", + "62": "Volume (mL)", + "63": "Theoretisch rendement", + "64": "Rendement", + "65": "De eenheden van de linialen volgen de tekening; klik om te wijzigen", + "66": "Eenheden van de linialen; klik om te wijzigen", + "67": "Pijl toevoegen", + "68": "Haakjeslabel instellen", + "69": "Haakje toevoegen", + "70": "Verbindingsnummer toevoegen", + "71": "Bijschrift toevoegen", + "72": "Elektronenverschuivingspijl toevoegen", + "73": "Vishaakpijl toevoegen", + "74": "Pijl buigen", + "75": "Pijleinde verplaatsen", + "76": "Punt verplaatsen", + "77": "Formaat wijzigen", + "78": "Afbeelding toevoegen", + "79": "Bijschrift", + "80": "Reactiepijl", + "81": "Evenwichtspijl", + "82": "Retrosynthesepijl", + "83": "Resonantiepijl", + "84": "Pijl voor uitgebleven reactie", + "85": "Gestippelde pijl", + "86": "Lijnpijl", + "87": "Elektronenverschuivingspijl", + "88": "Vishaakpijl", + "89": "Plusteken", + "90": "Is-gelijk-teken", + "91": "Adductpunt", + "92": "Ronde haakjes", + "93": "Rechte haken", + "94": "Accolades", + "95": "Rechthoek", + "96": "Afgeronde rechthoek", + "97": "Ellips", + "98": "Veelhoek", + "99": "Lijn en polylijn", + "100": "DC-plaat", + "101": "Afbeelding", + "102": "p-orbitaal", + "103": "s-orbitaal", + "104": "d-orbitaal", + "105": "dz2-orbitaal", + "106": "sp-hybride orbitaal", + "107": "Sigmabindingsorbitaal", + "108": "Pibindingsorbitaal", + "109": "Lijn toevoegen", + "110": "Orbitaal toevoegen", + "111": "Plusteken toevoegen", + "112": "Vorm toevoegen", + "113": "Tabel toevoegen", + "114": "DC-plaat toevoegen", + "115": "DC-vlek toevoegen", + "116": "Zoek tekst, labels, formules of SMILES", + "117": "Zoeken", + "118": "Vervangen door", + "119": "Vervangen tonen", + "120": "Hoofdlettergevoelig", + "121": "{0} (Shift+F3)", + "122": "Vorige treffer", + "123": "Volgende treffer", + "124": "{0} (Esc)", + "125": "Vervangen", + "126": "Alles vervangen", + "127": "Geen resultaten", + "128": "Vervangen verbergen", + "129": "1 treffer vervangen", + "130": "{0} treffers vervangen", + "131": "Component", + "132": "Massa", + "133": "Volume", + "134": "Dichtheid", + "135": "Conc", + "136": "Zuiverheid", + "137": "Reactant", + "138": "Reagens", + "139": "Product", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Stoichiometrie bewerken", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Geïsoleerd", + "146": "Niet gevonden", + "147": "Het sjabloon is leeg.", + "148": "Sjabloon {0} ({1}) ingevoegd in \"{2}\" ({3}) in één ongedaanmakingsstap", + "149": "Sjabloon invoegen", + "150": "Sjablonen zoeken", + "151": "Sjablooncategorieën", + "152": "Sjablonen laden...", + "153": "Geen sjablonen komen overeen met deze zoekopdracht.", + "154": "Pijlen", + "155": "Symbolen", + "156": "Haakjes", + "157": "Orbitalen", + "158": "Vormen", + "159": "DC" +} 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" +} diff --git a/frontend/src/i18n/locales/pl/part05.json b/frontend/src/i18n/locales/pl/part05.json new file mode 100644 index 00000000..2d1a45c1 --- /dev/null +++ b/frontend/src/i18n/locales/pl/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Pokazuje lub ukrywa linijki wzdłuż górnej i lewej krawędzi kanwy, w jednostkach rysunku (kliknij róg, aby zmienić jednostki). Przeciągnij z linijki, aby umieścić prowadnicę; przeciągnij prowadnicę z powrotem na linijkę, aby ją usunąć. Wybór jest zapamiętywany.", + "1": "Wyczyść prowadnice", + "2": "Usuwa wszystkie prowadnice linijek z aktywnego rysunku w tym oknie. Prowadnice nigdy nie są zapisywane w dokumencie.", + "3": "Najpierw przeciągnij prowadnicę z linijki", + "4": "Otwórz pasek wyszukiwania i najpierw wpisz, czego szukać", + "5": "Otwiera pasek wyszukiwania nad kanwą. Znajduje tekst, podpisy, komórki tabel, etykiety atomów i skróty, symbole pierwiastków, wzory takie jak C2H6O oraz SMILES w aktywnym rysunku; Enter lub F3 przechodzi do następnego dopasowania i je zaznacza.", + "6": "Znajdź następne", + "7": "Zaznacza następne dopasowanie i przesuwa widok do niego, gdy jest poza ekranem.", + "8": "Znajdź poprzednie", + "9": "Zaznacza poprzednie dopasowanie i przesuwa widok do niego, gdy jest poza ekranem.", + "10": "Zamień...", + "11": "Otwiera pasek wyszukiwania z wierszem zamiany. Zamień zmienia bieżące dopasowanie tekstu; Zamień wszystko zmienia wszystkie dopasowania tekstu w jednym kroku cofania.", + "12": "Prosi użytkownika o obraz PNG, JPEG, GIF, WebP lub SVG i umieszcza go pośrodku widocznej strony w jednym kroku cofania.", + "13": "Panel stechiometrii", + "14": "Otwiera bibliotekę szablonów; z id wstawia ten szablon (z nowymi id, przeskalowany do długości wiązania rysunku) na środku widoku aktywnego rysunku lub nowego rysunku, w jednym kroku cofania. GET /api/templates wymienia id.", + "15": "Id szablonu z GET /api/templates, na przykład benzene lub l-alanine; pomiń, aby otworzyć bibliotekę", + "16": "Pojawi się w wersji 0.6.0; do tego czasu Rozpoznaj reakcje ustawia role na podstawie rysunku", + "17": "Wstaw tabelę stechiometrii", + "18": "Wstawia siatkę stechiometrii wybranego etapu reakcji jako tabelę pod reakcją lub odświeża tabelę już powiązaną z tym etapem, w jednym kroku cofania.", + "19": "Najpierw narysuj reakcję ze strzałką", + "20": "Kopiuj reakcję jako", + "21": "Eksportuj reakcję", + "22": "Najpierw narysuj strzałkę reakcji z substratami i produktami", + "23": "Nie znaleziono reakcji: narysuj strzałkę ze strukturami po obu stronach.", + "24": "Etap nie ma mapowania atomów.", + "25": "Sprawdź bilans", + "26": "Reakcja jest zbilansowana.", + "27": "Reakcja nie jest zbilansowana.", + "28": "{0}: {1} / {2} g/mol", + "29": "Zbilansuj", + "30": "Zbilansowano reakcję.", + "31": "Nie udało się zbilansować reakcji", + "32": "Reakcja jest już zbilansowana.", + "33": "schowek jest niedostępny", + "34": "Wstaw reakcję", + "35": "SMILES reakcji lub RXN", + "36": "Rozpoznaj reakcje", + "37": "Odczytuje strzałki reakcji na stronie i zapisuje każdy etap wraz z jego substratami, produktami, czynnikami i warunkami, w jednym kroku cofania.", + "38": "Nie udało się rozpoznać reakcji", + "39": "Mapuje atomy wybranego etapu reakcji (najpierw rozpoznaje reakcje, jeśli żadna nie jest zapisana) i oznacza wiązania zrywane, tworzone i zmieniane, w jednym kroku cofania.", + "40": "Nie udało się zmapować atomów", + "41": "Usuwa numery mapowania atomów i znaczniki centrum reakcji wybranego etapu reakcji.", + "42": "Nie udało się wyczyścić mapowania", + "43": "Sprawdź bilans...", + "44": "Pokazuje bilans pierwiastków, ładunku i masy wybranego etapu reakcji, z podpowiedzią, gdy nie jest zbilansowany.", + "45": "Nie udało się sprawdzić reakcji", + "46": "Zbilansuj reakcję", + "47": "Ustawia współczynniki wybranego etapu reakcji na wartości zbilansowane, w jednym kroku cofania.", + "48": "Kopiuj SMILES reakcji", + "49": "Nie udało się skopiować reakcji", + "50": "Kopiuj reakcję jako RXN", + "51": "Eksportuj SMILES reakcji...", + "52": "Nie udało się wyeksportować reakcji", + "53": "Eksportuj reakcję jako RXN...", + "54": "Wstaw reakcję ze schowka", + "55": "Odczytuje SMILES reakcji lub plik RXN ze schowka i układa go na stronie z ustawionymi rolami, w jednym kroku cofania.", + "56": "Nie udało się wstawić reakcji", + "57": "Związek", + "58": "Rola", + "59": "MW", + "60": "Równ.", + "61": "Masa (mg)", + "62": "Objętość (mL)", + "63": "Wydajność teoretyczna", + "64": "Wydajność", + "65": "Jednostki linijki zgodne z rysunkiem; kliknij, aby zmienić", + "66": "Jednostki linijki; kliknij, aby zmienić", + "67": "Dodaj strzałkę", + "68": "Ustaw etykietę nawiasu", + "69": "Dodaj nawias", + "70": "Dodaj numer związku", + "71": "Dodaj podpis", + "72": "Dodaj strzałkę ruchu elektronów", + "73": "Dodaj strzałkę ruchu jednego elektronu", + "74": "Zegnij strzałkę", + "75": "Przesuń koniec strzałki", + "76": "Przesuń punkt", + "77": "Zmień rozmiar", + "78": "Dodaj obraz", + "79": "Podpis", + "80": "Strzałka reakcji", + "81": "Strzałka równowagi", + "82": "Strzałka retrosyntetyczna", + "83": "Strzałka rezonansu", + "84": "Przekreślona strzałka", + "85": "Przerywana strzałka", + "86": "Linia ze strzałką", + "87": "Strzałka ruchu elektronów", + "88": "Strzałka ruchu jednego elektronu", + "89": "Znak plus", + "90": "Znak równości", + "91": "Kropka adduktu", + "92": "Nawiasy okrągłe", + "93": "Nawiasy kwadratowe", + "94": "Nawiasy klamrowe", + "95": "Prostokąt", + "96": "Prostokąt z zaokrąglonymi rogami", + "97": "Elipsa", + "98": "Wielokąt", + "99": "Linia i linia łamana", + "100": "Płytka TLC", + "101": "Obraz", + "102": "Orbital p", + "103": "Orbital s", + "104": "Orbital d", + "105": "Orbital dz2", + "106": "Orbital hybrydowy sp", + "107": "Orbital wiązania sigma", + "108": "Orbital wiązania pi", + "109": "Dodaj linię", + "110": "Dodaj orbital", + "111": "Dodaj znak plus", + "112": "Dodaj kształt", + "113": "Dodaj tabelę", + "114": "Dodaj płytkę TLC", + "115": "Dodaj plamkę TLC", + "116": "Szukaj tekstu, etykiet, wzorów lub SMILES", + "117": "Znajdź", + "118": "Zamień na", + "119": "Pokaż zamianę", + "120": "Uwzględnij wielkość liter", + "121": "{0} (Shift+F3)", + "122": "Poprzednie dopasowanie", + "123": "Następne dopasowanie", + "124": "{0} (Esc)", + "125": "Zamień", + "126": "Zamień wszystko", + "127": "Brak wyników", + "128": "Ukryj zamianę", + "129": "Zamieniono dopasowań: 1", + "130": "Zamieniono dopasowań: {0}", + "131": "Składnik", + "132": "Masa", + "133": "Objętość", + "134": "Gęstość", + "135": "Stęż.", + "136": "Czystość", + "137": "Substrat", + "138": "Odczynnik", + "139": "Produkt", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Edytuj stechiometrię", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Wyizolowana", + "146": "Nie znaleziono", + "147": "Szablon jest pusty.", + "148": "Wstawiono szablon {0} ({1}) do \"{2}\" ({3}) w jednym kroku cofania", + "149": "Wstaw szablon", + "150": "Szukaj szablonów", + "151": "Kategorie szablonów", + "152": "Wczytywanie szablonów...", + "153": "Żaden szablon nie pasuje do tego wyszukiwania.", + "154": "Strzałki", + "155": "Symbole", + "156": "Nawiasy", + "157": "Orbitale", + "158": "Kształty", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/pt-BR/part05.json b/frontend/src/i18n/locales/pt-BR/part05.json new file mode 100644 index 00000000..3a03b367 --- /dev/null +++ b/frontend/src/i18n/locales/pt-BR/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Mostra ou oculta as réguas ao longo das bordas superior e esquerda da tela, nas unidades do desenho (clique no canto para alternar as unidades). Arraste a partir de uma régua para posicionar uma guia; arraste uma guia de volta para uma régua para removê-la. A escolha é lembrada.", + "1": "Limpar guias", + "2": "Remove todas as guias de régua do desenho ativo nesta janela. As guias nunca são salvas no documento.", + "3": "Primeiro arraste uma guia para fora de uma régua", + "4": "Abra a barra de busca e digite primeiro o que deseja localizar", + "5": "Abre a barra de busca sobre a tela. Localiza texto, legendas, células de tabela, rótulos de átomos e abreviações, símbolos de elementos, fórmulas como C2H6O e SMILES no desenho ativo; Enter ou F3 vai para a próxima ocorrência e a seleciona.", + "6": "Localizar próxima", + "7": "Seleciona a próxima ocorrência da busca e move a visualização até ela quando estiver fora da tela.", + "8": "Localizar anterior", + "9": "Seleciona a ocorrência anterior da busca e move a visualização até ela quando estiver fora da tela.", + "10": "Substituir...", + "11": "Abre a barra de busca com a linha de substituição. Substituir altera a ocorrência de texto atual; Substituir tudo altera todas as ocorrências de texto em uma única etapa de desfazer.", + "12": "Pede ao usuário uma imagem PNG, JPEG, GIF, WebP ou SVG e a coloca no meio da página visível em uma única etapa de desfazer.", + "13": "Painel de estequiometria", + "14": "Abre a biblioteca de modelos; com id, insere esse modelo (com ids novos e ajustado ao comprimento de ligação do desenho) centralizado na visualização do desenho ativo, ou em um novo, em uma única etapa de desfazer. GET /api/templates lista os ids.", + "15": "Id de modelo de GET /api/templates, como benzene ou l-alanine; omita para abrir a biblioteca", + "16": "Chega na versão 0.6.0; até lá, Perceber reações define os papéis a partir do desenho", + "17": "Inserir tabela de estequiometria", + "18": "Insere a grade de estequiometria da etapa de reação selecionada como uma tabela abaixo da reação, ou atualiza a tabela já vinculada a essa etapa, em uma única etapa de desfazer.", + "19": "Desenhe primeiro uma reação com uma seta", + "20": "Copiar reação como", + "21": "Exportar reação", + "22": "Desenhe primeiro uma seta de reação com reagentes e produtos", + "23": "Nenhuma reação encontrada: desenhe uma seta com estruturas dos dois lados.", + "24": "A etapa não tem mapeamento de átomos.", + "25": "Verificar balanceamento", + "26": "A reação está balanceada.", + "27": "A reação não está balanceada.", + "28": "{0}: {1} / {2} g/mol", + "29": "Balancear", + "30": "A reação foi balanceada.", + "31": "Não foi possível balancear a reação", + "32": "A reação já está balanceada.", + "33": "a área de transferência não está disponível", + "34": "Inserir reação", + "35": "SMILES de reação ou RXN", + "36": "Perceber reações", + "37": "Lê as setas de reação da página e armazena cada etapa com seus reagentes, produtos, agentes e condições, em uma única etapa de desfazer.", + "38": "Não foi possível perceber as reações", + "39": "Mapeia os átomos da etapa de reação selecionada (percebendo as reações antes, se nenhuma estiver armazenada) e marca as ligações rompidas, formadas e alteradas, em uma única etapa de desfazer.", + "40": "Não foi possível mapear os átomos", + "41": "Remove os números de mapeamento de átomos e as marcas do centro reacional da etapa de reação selecionada.", + "42": "Não foi possível limpar o mapeamento", + "43": "Verificar balanceamento...", + "44": "Mostra o balanço de elementos, carga e massa da etapa de reação selecionada, com uma sugestão quando ela não está balanceada.", + "45": "Não foi possível verificar a reação", + "46": "Balancear reação", + "47": "Define os coeficientes da etapa de reação selecionada com os valores balanceados, em uma única etapa de desfazer.", + "48": "Copiar SMILES da reação", + "49": "Não foi possível copiar a reação", + "50": "Copiar reação como RXN", + "51": "Exportar SMILES da reação...", + "52": "Não foi possível exportar a reação", + "53": "Exportar reação como RXN...", + "54": "Inserir reação da área de transferência", + "55": "Lê SMILES de reação ou um arquivo RXN da área de transferência e o organiza na página com seus papéis definidos, em uma única etapa de desfazer.", + "56": "Não foi possível inserir a reação", + "57": "Composto", + "58": "Papel", + "59": "MM", + "60": "Equiv.", + "61": "Massa (mg)", + "62": "Volume (mL)", + "63": "Rendimento teórico", + "64": "Rendimento", + "65": "As unidades da régua seguem o desenho; clique para alterar", + "66": "Unidades da régua; clique para alterar", + "67": "Adicionar seta", + "68": "Definir rótulo do colchete", + "69": "Adicionar colchete", + "70": "Adicionar número de composto", + "71": "Adicionar legenda", + "72": "Adicionar seta de movimento de elétrons", + "73": "Adicionar seta de meia ponta", + "74": "Curvar seta", + "75": "Mover extremidade da seta", + "76": "Mover ponto", + "77": "Redimensionar", + "78": "Adicionar imagem", + "79": "Legenda", + "80": "Seta de reação", + "81": "Seta de equilíbrio", + "82": "Seta retrossintética", + "83": "Seta de ressonância", + "84": "Seta de reação impossível", + "85": "Seta tracejada", + "86": "Seta de linha", + "87": "Seta de movimento de elétrons", + "88": "Seta de meia ponta", + "89": "Sinal de mais", + "90": "Sinal de igual", + "91": "Ponto de aduto", + "92": "Parênteses", + "93": "Colchetes", + "94": "Chaves", + "95": "Retângulo", + "96": "Retângulo arredondado", + "97": "Elipse", + "98": "Polígono", + "99": "Linha e polilinha", + "100": "Placa de CCD", + "101": "Imagem", + "102": "Orbital p", + "103": "Orbital s", + "104": "Orbital d", + "105": "Orbital dz2", + "106": "Orbital híbrido sp", + "107": "Orbital de ligação sigma", + "108": "Orbital de ligação pi", + "109": "Adicionar linha", + "110": "Adicionar orbital", + "111": "Adicionar sinal de mais", + "112": "Adicionar forma", + "113": "Adicionar tabela", + "114": "Adicionar placa de CCD", + "115": "Adicionar mancha de CCD", + "116": "Localizar texto, rótulos, fórmulas ou SMILES", + "117": "Localizar", + "118": "Substituir por", + "119": "Mostrar substituição", + "120": "Diferenciar maiúsculas de minúsculas", + "121": "{0} (Shift+F3)", + "122": "Ocorrência anterior", + "123": "Próxima ocorrência", + "124": "{0} (Esc)", + "125": "Substituir", + "126": "Substituir tudo", + "127": "Nenhum resultado", + "128": "Ocultar substituição", + "129": "1 ocorrência substituída", + "130": "{0} ocorrências substituídas", + "131": "Componente", + "132": "Massa", + "133": "Volume", + "134": "Densidade", + "135": "Conc.", + "136": "Pureza", + "137": "Reagente de partida", + "138": "Reagente", + "139": "Produto", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Editar estequiometria", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isolado", + "146": "Não encontrado", + "147": "O modelo está vazio.", + "148": "Modelo {0} ({1}) inserido em \"{2}\" ({3}) em uma única etapa de desfazer", + "149": "Inserir modelo", + "150": "Pesquisar modelos", + "151": "Categorias de modelos", + "152": "Carregando modelos...", + "153": "Nenhum modelo corresponde a esta pesquisa.", + "154": "Setas", + "155": "Símbolos", + "156": "Colchetes", + "157": "Orbitais", + "158": "Formas", + "159": "CCD" +} 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" +} diff --git a/frontend/src/i18n/locales/ru/part05.json b/frontend/src/i18n/locales/ru/part05.json new file mode 100644 index 00000000..266238d7 --- /dev/null +++ b/frontend/src/i18n/locales/ru/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Показывает или скрывает линейки вдоль верхнего и левого краёв холста в единицах рисунка (щёлкните угол, чтобы сменить единицы). Перетащите от линейки, чтобы разместить направляющую; перетащите направляющую обратно на линейку, чтобы удалить её. Выбор запоминается.", + "1": "Очистить направляющие", + "2": "Удаляет все направляющие линейки из активного рисунка в этом окне. Направляющие никогда не сохраняются в документе.", + "3": "Сначала вытащите направляющую из линейки", + "4": "Откройте строку поиска и сначала введите, что искать", + "5": "Открывает строку поиска над холстом. Она находит текст, подписи, ячейки таблиц, метки атомов и сокращения, символы элементов, формулы вроде C2H6O и SMILES в активном рисунке; Enter или F3 переходит к следующему совпадению и выделяет его.", + "6": "Найти далее", + "7": "Выделяет следующее найденное совпадение и прокручивает к нему, если оно за пределами экрана.", + "8": "Найти ранее", + "9": "Выделяет предыдущее найденное совпадение и прокручивает к нему, если оно за пределами экрана.", + "10": "Заменить...", + "11": "Открывает строку поиска со строкой замены. «Заменить» изменяет текущее текстовое совпадение; «Заменить все» изменяет все текстовые совпадения одним шагом отмены.", + "12": "Запрашивает у пользователя изображение PNG, JPEG, GIF, WebP или SVG и помещает его в центр видимой страницы одним шагом отмены.", + "13": "Панель стехиометрии", + "14": "Открывает библиотеку шаблонов; с id вставляет этот шаблон (с новыми id, масштабированный по длине связи рисунка) по центру вида активного рисунка или нового рисунка одним шагом отмены. GET /api/templates перечисляет id.", + "15": "id шаблона из GET /api/templates, например benzene или l-alanine; опустите, чтобы открыть библиотеку", + "16": "Появится в 0.6.0; до тех пор «Распознать реакции» назначает роли по рисунку", + "17": "Вставить таблицу стехиометрии", + "18": "Вставляет сетку стехиометрии выбранной стадии реакции в виде таблицы под реакцией или обновляет таблицу, уже привязанную к этой стадии, одним шагом отмены.", + "19": "Сначала нарисуйте реакцию со стрелкой", + "20": "Копировать реакцию как", + "21": "Экспорт реакции", + "22": "Сначала нарисуйте стрелку реакции с исходными веществами и продуктами", + "23": "Реакция не найдена: нарисуйте стрелку со структурами по обе стороны.", + "24": "У стадии нет отображения атомов.", + "25": "Проверить баланс", + "26": "Реакция сбалансирована.", + "27": "Реакция не сбалансирована.", + "28": "{0}: {1} / {2} g/mol", + "29": "Баланс", + "30": "Реакция сбалансирована.", + "31": "Не удалось сбалансировать реакцию", + "32": "Реакция уже сбалансирована.", + "33": "буфер обмена недоступен", + "34": "Вставить реакцию", + "35": "Реакционный SMILES или RXN", + "36": "Распознать реакции", + "37": "Считывает стрелки реакций на странице и сохраняет каждую стадию с её исходными веществами, продуктами, агентами и условиями одним шагом отмены.", + "38": "Не удалось распознать реакции", + "39": "Сопоставляет атомы выбранной стадии реакции (сначала распознаёт реакции, если ни одна не сохранена) и отмечает разрывающиеся, образующиеся и изменяющиеся связи одним шагом отмены.", + "40": "Не удалось сопоставить атомы", + "41": "Удаляет номера отображения атомов и отметки реакционного центра выбранной стадии реакции.", + "42": "Не удалось очистить отображение", + "43": "Проверить баланс...", + "44": "Показывает баланс элементов, заряда и массы выбранной стадии реакции с подсказкой, если она не сбалансирована.", + "45": "Не удалось проверить реакцию", + "46": "Сбалансировать реакцию", + "47": "Устанавливает коэффициенты выбранной стадии реакции в сбалансированные значения одним шагом отмены.", + "48": "Копировать SMILES реакции", + "49": "Не удалось скопировать реакцию", + "50": "Копировать реакцию как RXN", + "51": "Экспорт SMILES реакции...", + "52": "Не удалось экспортировать реакцию", + "53": "Экспорт реакции как RXN...", + "54": "Вставить реакцию из буфера обмена", + "55": "Считывает реакционный SMILES или файл RXN из буфера обмена и размещает его на странице с назначенными ролями одним шагом отмены.", + "56": "Не удалось вставить реакцию", + "57": "Соединение", + "58": "Роль", + "59": "MW", + "60": "Экв", + "61": "Масса (mg)", + "62": "Объём (mL)", + "63": "Теоретический выход", + "64": "Выход", + "65": "Единицы линейки соответствуют рисунку; щёлкните, чтобы изменить", + "66": "Единицы линейки; щёлкните, чтобы изменить", + "67": "Добавить стрелку", + "68": "Задать подпись скобки", + "69": "Добавить скобку", + "70": "Добавить номер соединения", + "71": "Добавить подпись", + "72": "Добавить стрелку движения электронов", + "73": "Добавить стрелку движения одного электрона", + "74": "Изогнуть стрелку", + "75": "Переместить конец стрелки", + "76": "Переместить точку", + "77": "Изменить размер", + "78": "Добавить изображение", + "79": "Подпись", + "80": "Стрелка реакции", + "81": "Стрелка равновесия", + "82": "Ретросинтетическая стрелка", + "83": "Стрелка резонанса", + "84": "Перечёркнутая стрелка", + "85": "Штриховая стрелка", + "86": "Линия со стрелкой", + "87": "Стрелка движения электронов", + "88": "Стрелка движения одного электрона", + "89": "Знак плюс", + "90": "Знак равенства", + "91": "Точка аддукта", + "92": "Круглые скобки", + "93": "Квадратные скобки", + "94": "Фигурные скобки", + "95": "Прямоугольник", + "96": "Скруглённый прямоугольник", + "97": "Эллипс", + "98": "Многоугольник", + "99": "Линия и ломаная", + "100": "Пластина ТСХ", + "101": "Изображение", + "102": "p-орбиталь", + "103": "s-орбиталь", + "104": "d-орбиталь", + "105": "dz2-орбиталь", + "106": "sp-гибридная орбиталь", + "107": "Орбиталь сигма-связи", + "108": "Орбиталь пи-связи", + "109": "Добавить линию", + "110": "Добавить орбиталь", + "111": "Добавить знак плюс", + "112": "Добавить фигуру", + "113": "Добавить таблицу", + "114": "Добавить пластину ТСХ", + "115": "Добавить пятно ТСХ", + "116": "Поиск текста, меток, формул или SMILES", + "117": "Найти", + "118": "Заменить на", + "119": "Показать замену", + "120": "Учитывать регистр", + "121": "{0} (Shift+F3)", + "122": "Предыдущее совпадение", + "123": "Следующее совпадение", + "124": "{0} (Esc)", + "125": "Заменить", + "126": "Заменить все", + "127": "Нет результатов", + "128": "Скрыть замену", + "129": "Заменено совпадений: 1", + "130": "Заменено совпадений: {0}", + "131": "Компонент", + "132": "Масса", + "133": "Объём", + "134": "Плотность", + "135": "Конц.", + "136": "Чистота", + "137": "Исходное вещество", + "138": "Реагент", + "139": "Продукт", + "140": "Авто", + "141": "{0} mg · {1} mmol", + "142": "Изменить стехиометрию", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Выделено", + "146": "Не найдено", + "147": "Шаблон пуст.", + "148": "Шаблон {0} ({1}) вставлен в «{2}» ({3}) одним шагом отмены", + "149": "Вставить шаблон", + "150": "Поиск шаблонов", + "151": "Категории шаблонов", + "152": "Загрузка шаблонов...", + "153": "Нет шаблонов, подходящих под этот поиск.", + "154": "Стрелки", + "155": "Символы", + "156": "Скобки", + "157": "Орбитали", + "158": "Фигуры", + "159": "ТСХ" +} 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": "Выбрать на холсте" +} diff --git a/frontend/src/i18n/locales/sv/part05.json b/frontend/src/i18n/locales/sv/part05.json new file mode 100644 index 00000000..c07eb9f0 --- /dev/null +++ b/frontend/src/i18n/locales/sv/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Visar eller döljer linjaler längs ritytans övre och vänstra kant, i ritningens enheter (klicka i hörnet för att byta enhet). Dra från en linjal för att placera en hjälplinje; dra en hjälplinje tillbaka till en linjal för att ta bort den. Valet sparas.", + "1": "Rensa hjälplinjer", + "2": "Tar bort alla hjälplinjer från den aktiva ritningen i det här fönstret. Hjälplinjer sparas aldrig i dokumentet.", + "3": "Dra först ut en hjälplinje från en linjal", + "4": "Öppna sökfältet och skriv först vad som ska sökas", + "5": "Öppnar sökfältet över ritytan. Det hittar text, bildtexter, tabellceller, atometiketter och förkortningar, elementsymboler, formler som C2H6O och SMILES i den aktiva ritningen; Enter eller F3 går till nästa träff och markerar den.", + "6": "Sök nästa", + "7": "Markerar nästa sökträff och panorerar till den när den ligger utanför bilden.", + "8": "Sök föregående", + "9": "Markerar föregående sökträff och panorerar till den när den ligger utanför bilden.", + "10": "Ersätt...", + "11": "Öppnar sökfältet med ersättningsraden. Ersätt ändrar den aktuella textträffen; Ersätt alla ändrar alla textträffar i ett ångra-steg.", + "12": "Ber användaren om en PNG-, JPEG-, GIF-, WebP- eller SVG-bild och placerar den mitt på den synliga sidan i ett ångra-steg.", + "13": "Stökiometripanel", + "14": "Öppnar mallbiblioteket; med id infogas den mallen (nya id:n, skalad till ritningens bindningslängd) centrerad i vyn av den aktiva ritningen, eller i en ny, i ett ångra-steg. GET /api/templates visar id:na.", + "15": "Mall-id från GET /api/templates, till exempel benzene eller l-alanine; utelämna det för att öppna biblioteket", + "16": "Kommer i 0.6.0; tills dess sätter Identifiera reaktioner rollerna utifrån ritningen", + "17": "Infoga stökiometritabell", + "18": "Infogar stökiometrirutnätet för det markerade reaktionssteget som en tabell under reaktionen, eller uppdaterar tabellen som redan är kopplad till steget, i ett ångra-steg.", + "19": "Rita först en reaktion med en pil", + "20": "Kopiera reaktion som", + "21": "Exportera reaktion", + "22": "Rita först en reaktionspil med reaktanter och produkter", + "23": "Ingen reaktion hittades: rita en pil med strukturer på båda sidor.", + "24": "Steget har ingen atommappning.", + "25": "Kontrollera balans", + "26": "Reaktionen är balanserad.", + "27": "Reaktionen är inte balanserad.", + "28": "{0}: {1} / {2} g/mol", + "29": "Balansera", + "30": "Reaktionen balanserades.", + "31": "Det gick inte att balansera reaktionen", + "32": "Reaktionen är redan balanserad.", + "33": "urklipp är inte tillgängligt", + "34": "Infoga reaktion", + "35": "Reaktions-SMILES eller RXN", + "36": "Identifiera reaktioner", + "37": "Läser reaktionspilarna på sidan och lagrar varje steg med dess reaktanter, produkter, agens och villkor, i ett ångra-steg.", + "38": "Det gick inte att identifiera reaktionerna", + "39": "Mappar atomerna i det markerade reaktionssteget (identifierar reaktioner först om ingen är lagrad) och markerar bindningar som bryts, bildas och ändras, i ett ångra-steg.", + "40": "Det gick inte att mappa atomerna", + "41": "Tar bort atommappningsnumren och markeringarna av reaktionscentrum för det markerade reaktionssteget.", + "42": "Det gick inte att ta bort mappningen", + "43": "Kontrollera balans...", + "44": "Visar balansen av grundämnen, laddning och massa för det markerade reaktionssteget, med ett förslag när det inte är balanserat.", + "45": "Det gick inte att kontrollera reaktionen", + "46": "Balansera reaktion", + "47": "Sätter koefficienterna för det markerade reaktionssteget till de balanserade värdena, i ett ångra-steg.", + "48": "Kopiera reaktions-SMILES", + "49": "Det gick inte att kopiera reaktionen", + "50": "Kopiera reaktion som RXN", + "51": "Exportera reaktions-SMILES...", + "52": "Det gick inte att exportera reaktionen", + "53": "Exportera reaktion som RXN...", + "54": "Infoga reaktion från urklipp", + "55": "Läser reaktions-SMILES eller en RXN-fil från urklipp och lägger ut den på sidan med rollerna satta, i ett ångra-steg.", + "56": "Det gick inte att infoga reaktionen", + "57": "Förening", + "58": "Roll", + "59": "MW", + "60": "Ekv", + "61": "Massa (mg)", + "62": "Volym (mL)", + "63": "Teoretiskt utbyte", + "64": "Utbyte", + "65": "Linjalenheter följer ritningen; klicka för att ändra", + "66": "Linjalenheter; klicka för att ändra", + "67": "Lägg till pil", + "68": "Ange hakparentesetikett", + "69": "Lägg till hakparentes", + "70": "Lägg till föreningsnummer", + "71": "Lägg till bildtext", + "72": "Lägg till elektronpil", + "73": "Lägg till enelektronpil", + "74": "Böj pil", + "75": "Flytta pilände", + "76": "Flytta punkt", + "77": "Ändra storlek", + "78": "Lägg till bild", + "79": "Bildtext", + "80": "Reaktionspil", + "81": "Jämviktspil", + "82": "Retrosyntetisk pil", + "83": "Resonanspil", + "84": "Överstruken pil", + "85": "Streckad pil", + "86": "Linjepil", + "87": "Elektronpil", + "88": "Enelektronpil", + "89": "Plustecken", + "90": "Likhetstecken", + "91": "Addukt-prick", + "92": "Runda parenteser", + "93": "Hakparenteser", + "94": "Klammerparenteser", + "95": "Rektangel", + "96": "Rektangel med rundade hörn", + "97": "Ellips", + "98": "Polygon", + "99": "Linje och polylinje", + "100": "TLC-platta", + "101": "Bild", + "102": "p-orbital", + "103": "s-orbital", + "104": "d-orbital", + "105": "dz2-orbital", + "106": "sp-hybridorbital", + "107": "Sigmabindningsorbital", + "108": "Pibindningsorbital", + "109": "Lägg till linje", + "110": "Lägg till orbital", + "111": "Lägg till plustecken", + "112": "Lägg till form", + "113": "Lägg till tabell", + "114": "Lägg till TLC-platta", + "115": "Lägg till TLC-fläck", + "116": "Sök text, etiketter, formler eller SMILES", + "117": "Sök", + "118": "Ersätt med", + "119": "Visa ersättning", + "120": "Matcha skiftläge", + "121": "{0} (Shift+F3)", + "122": "Föregående träff", + "123": "Nästa träff", + "124": "{0} (Esc)", + "125": "Ersätt", + "126": "Ersätt alla", + "127": "Inga resultat", + "128": "Dölj ersättning", + "129": "Ersatte 1 träff", + "130": "Ersatte {0} träffar", + "131": "Komponent", + "132": "Massa", + "133": "Volym", + "134": "Densitet", + "135": "Konc", + "136": "Renhet", + "137": "Reaktant", + "138": "Reagens", + "139": "Produkt", + "140": "Auto", + "141": "{0} mg · {1} mmol", + "142": "Redigera stökiometri", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Isolerat", + "146": "Hittades inte", + "147": "Mallen är tom.", + "148": "Infogade mallen {0} ({1}) i \"{2}\" ({3}) i ett ångra-steg", + "149": "Infoga mall", + "150": "Sök mallar", + "151": "Mallkategorier", + "152": "Läser in mallar...", + "153": "Inga mallar matchar sökningen.", + "154": "Pilar", + "155": "Symboler", + "156": "Parenteser", + "157": "Orbitaler", + "158": "Former", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/th/part05.json b/frontend/src/i18n/locales/th/part05.json new file mode 100644 index 00000000..28b6d495 --- /dev/null +++ b/frontend/src/i18n/locales/th/part05.json @@ -0,0 +1,162 @@ +{ + "0": "แสดงหรือซ่อนไม้บรรทัดที่ขอบบนและขอบซ้ายของผืนผ้าใบ ตามหน่วยของแบบวาด (คลิกที่มุมเพื่อสลับหน่วย) ลากจากไม้บรรทัดเพื่อวางเส้นนำ และลากเส้นนำกลับไปที่ไม้บรรทัดเพื่อลบ ระบบจะจำตัวเลือกนี้ไว้", + "1": "ล้างเส้นนำ", + "2": "ลบเส้นนำของไม้บรรทัดทั้งหมดออกจากแบบวาดที่เปิดอยู่ในหน้าต่างนี้ เส้นนำจะไม่ถูกบันทึกในเอกสาร", + "3": "ลากเส้นนำออกจากไม้บรรทัดก่อน", + "4": "เปิดแถบค้นหาและพิมพ์สิ่งที่จะค้นหาก่อน", + "5": "เปิดแถบค้นหาเหนือผืนผ้าใบ ค้นหาข้อความ คำบรรยาย เซลล์ในตาราง ป้ายกำกับอะตอมและตัวย่อ สัญลักษณ์ธาตุ สูตรเคมีเช่น C2H6O และ SMILES ในแบบวาดที่เปิดอยู่ กด Enter หรือ F3 เพื่อไปยังรายการที่ตรงกันถัดไปและเลือกรายการนั้น", + "6": "ค้นหาถัดไป", + "7": "เลือกรายการที่ตรงกันถัดไป และเลื่อนไปยังรายการนั้นหากอยู่นอกหน้าจอ", + "8": "ค้นหาก่อนหน้า", + "9": "เลือกรายการที่ตรงกันก่อนหน้า และเลื่อนไปยังรายการนั้นหากอยู่นอกหน้าจอ", + "10": "แทนที่...", + "11": "เปิดแถบค้นหาพร้อมแถวสำหรับแทนที่ \"แทนที่\" จะเปลี่ยนข้อความที่ตรงกันรายการปัจจุบัน ส่วน \"แทนที่ทั้งหมด\" จะเปลี่ยนข้อความที่ตรงกันทุกรายการในการเลิกทำหนึ่งขั้นตอน", + "12": "ให้ผู้ใช้เลือกรูป PNG, JPEG, GIF, WebP หรือ SVG แล้ววางไว้กลางหน้าที่มองเห็นในการเลิกทำหนึ่งขั้นตอน", + "13": "แผงปริมาณสัมพันธ์", + "14": "เปิดคลังแม่แบบ หากระบุ id จะแทรกแม่แบบนั้น (ใช้ id ใหม่ และปรับขนาดตามความยาวพันธะของแบบวาด) ไว้กลางมุมมองของแบบวาดที่เปิดอยู่ หรือในแบบวาดใหม่ ในการเลิกทำหนึ่งขั้นตอน GET /api/templates จะแสดงรายการ id", + "15": "id ของแม่แบบจาก GET /api/templates เช่น benzene หรือ l-alanine หากไม่ระบุจะเปิดคลัง", + "16": "จะมาใน 0.6.0 ก่อนหน้านั้นให้ใช้ \"รับรู้ปฏิกิริยา\" เพื่อกำหนดบทบาทจากแบบวาด", + "17": "แทรกตารางปริมาณสัมพันธ์", + "18": "แทรกตารางปริมาณสัมพันธ์ของขั้นตอนปฏิกิริยาที่เลือกเป็นตารางใต้ปฏิกิริยา หรือรีเฟรชตารางที่ผูกกับขั้นตอนนั้นอยู่แล้ว ในการเลิกทำหนึ่งขั้นตอน", + "19": "วาดปฏิกิริยาด้วยลูกศรก่อน", + "20": "คัดลอกปฏิกิริยาเป็น", + "21": "ส่งออกปฏิกิริยา", + "22": "วาดลูกศรปฏิกิริยาพร้อมสารตั้งต้นและผลิตภัณฑ์ก่อน", + "23": "ไม่พบปฏิกิริยา: วาดลูกศรที่มีโครงสร้างทั้งสองด้าน", + "24": "ขั้นตอนนี้ไม่มีการจับคู่อะตอม", + "25": "ตรวจสอบสมดุล", + "26": "ปฏิกิริยาสมดุลแล้ว", + "27": "ปฏิกิริยายังไม่สมดุล", + "28": "{0}: {1} / {2} g/mol", + "29": "ดุลสมการ", + "30": "ดุลสมการปฏิกิริยาแล้ว", + "31": "ดุลสมการปฏิกิริยาไม่ได้", + "32": "ปฏิกิริยาสมดุลอยู่แล้ว", + "33": "ไม่สามารถใช้คลิปบอร์ดได้", + "34": "แทรกปฏิกิริยา", + "35": "SMILES ของปฏิกิริยาหรือ RXN", + "36": "รับรู้ปฏิกิริยา", + "37": "อ่านลูกศรปฏิกิริยาในหน้า และเก็บแต่ละขั้นตอนพร้อมสารตั้งต้น ผลิตภัณฑ์ รีเอเจนต์ และสภาวะ ในการเลิกทำหนึ่งขั้นตอน", + "38": "รับรู้ปฏิกิริยาไม่ได้", + "39": "จับคู่อะตอมของขั้นตอนปฏิกิริยาที่เลือก (รับรู้ปฏิกิริยาก่อนหากยังไม่มีที่เก็บไว้) และทำเครื่องหมายพันธะที่แตก เกิดขึ้น และเปลี่ยนไป ในการเลิกทำหนึ่งขั้นตอน", + "40": "จับคู่อะตอมไม่ได้", + "41": "ลบหมายเลขการจับคู่อะตอมและเครื่องหมายศูนย์กลางปฏิกิริยาของขั้นตอนปฏิกิริยาที่เลือก", + "42": "ล้างการจับคู่ไม่ได้", + "43": "ตรวจสอบสมดุล...", + "44": "แสดงสมดุลของธาตุ ประจุ และมวลของขั้นตอนปฏิกิริยาที่เลือก พร้อมคำแนะนำเมื่อยังไม่สมดุล", + "45": "ตรวจสอบปฏิกิริยาไม่ได้", + "46": "ดุลสมการปฏิกิริยา", + "47": "ตั้งสัมประสิทธิ์ของขั้นตอนปฏิกิริยาที่เลือกเป็นค่าที่สมดุล ในการเลิกทำหนึ่งขั้นตอน", + "48": "คัดลอก SMILES ของปฏิกิริยา", + "49": "คัดลอกปฏิกิริยาไม่ได้", + "50": "คัดลอกปฏิกิริยาเป็น RXN", + "51": "ส่งออก SMILES ของปฏิกิริยา...", + "52": "ส่งออกปฏิกิริยาไม่ได้", + "53": "ส่งออกปฏิกิริยาเป็น RXN...", + "54": "แทรกปฏิกิริยาจากคลิปบอร์ด", + "55": "อ่าน SMILES ของปฏิกิริยาหรือไฟล์ RXN จากคลิปบอร์ด แล้ววางลงในหน้าพร้อมกำหนดบทบาท ในการเลิกทำหนึ่งขั้นตอน", + "56": "แทรกปฏิกิริยาไม่ได้", + "57": "สารประกอบ", + "58": "บทบาท", + "59": "MW", + "60": "สมมูล", + "61": "มวล (mg)", + "62": "ปริมาตร (mL)", + "63": "ผลได้ตามทฤษฎี", + "64": "ผลได้", + "65": "หน่วยของไม้บรรทัดเป็นไปตามแบบวาด คลิกเพื่อเปลี่ยน", + "66": "หน่วยของไม้บรรทัด คลิกเพื่อเปลี่ยน", + "67": "เพิ่มลูกศร", + "68": "ตั้งป้ายกำกับวงเล็บ", + "69": "เพิ่มวงเล็บ", + "70": "เพิ่มหมายเลขสารประกอบ", + "71": "เพิ่มคำบรรยาย", + "72": "เพิ่มลูกศรการเคลื่อนที่ของอิเล็กตรอน", + "73": "เพิ่มลูกศรครึ่งหัว", + "74": "ดัดลูกศร", + "75": "ย้ายปลายลูกศร", + "76": "ย้ายจุด", + "77": "ปรับขนาด", + "78": "เพิ่มรูปภาพ", + "79": "คำบรรยาย", + "80": "ลูกศรปฏิกิริยา", + "81": "ลูกศรสมดุล", + "82": "ลูกศรการสังเคราะห์ย้อนกลับ", + "83": "ลูกศรเรโซแนนซ์", + "84": "ลูกศรห้าม", + "85": "ลูกศรเส้นประ", + "86": "ลูกศรเส้น", + "87": "ลูกศรการเคลื่อนที่ของอิเล็กตรอน", + "88": "ลูกศรครึ่งหัว", + "89": "เครื่องหมายบวก", + "90": "เครื่องหมายเท่ากับ", + "91": "จุดแอดดักต์", + "92": "วงเล็บกลม", + "93": "วงเล็บเหลี่ยม", + "94": "วงเล็บปีกกา", + "95": "สี่เหลี่ยมผืนผ้า", + "96": "สี่เหลี่ยมผืนผ้ามุมมน", + "97": "วงรี", + "98": "รูปหลายเหลี่ยม", + "99": "เส้นและเส้นหลายช่วง", + "100": "แผ่น TLC", + "101": "รูปภาพ", + "102": "ออร์บิทัล p", + "103": "ออร์บิทัล s", + "104": "ออร์บิทัล d", + "105": "ออร์บิทัล dz2", + "106": "ออร์บิทัลลูกผสม sp", + "107": "ออร์บิทัลพันธะซิกมา", + "108": "ออร์บิทัลพันธะพาย", + "109": "เพิ่มเส้น", + "110": "เพิ่มออร์บิทัล", + "111": "เพิ่มเครื่องหมายบวก", + "112": "เพิ่มรูปร่าง", + "113": "เพิ่มตาราง", + "114": "เพิ่มแผ่น TLC", + "115": "เพิ่มจุด TLC", + "116": "ค้นหาข้อความ ป้ายกำกับ สูตรเคมี หรือ SMILES", + "117": "ค้นหา", + "118": "แทนที่ด้วย", + "119": "แสดงการแทนที่", + "120": "ตรงตามตัวพิมพ์", + "121": "{0} (Shift+F3)", + "122": "รายการที่ตรงกันก่อนหน้า", + "123": "รายการที่ตรงกันถัดไป", + "124": "{0} (Esc)", + "125": "แทนที่", + "126": "แทนที่ทั้งหมด", + "127": "ไม่มีผลลัพธ์", + "128": "ซ่อนการแทนที่", + "129": "แทนที่ 1 รายการแล้ว", + "130": "แทนที่ {0} รายการแล้ว", + "131": "องค์ประกอบ", + "132": "มวล", + "133": "ปริมาตร", + "134": "ความหนาแน่น", + "135": "ความเข้มข้น", + "136": "ความบริสุทธิ์", + "137": "สารตั้งต้น", + "138": "รีเอเจนต์", + "139": "ผลิตภัณฑ์", + "140": "อัตโนมัติ", + "141": "{0} mg · {1} mmol", + "142": "แก้ไขปริมาณสัมพันธ์", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "ผลได้หลังแยกบริสุทธิ์", + "146": "ไม่พบ", + "147": "แม่แบบว่างเปล่า", + "148": "แทรกแม่แบบ {0} ({1}) ลงใน \"{2}\" ({3}) ในการเลิกทำหนึ่งขั้นตอนแล้ว", + "149": "แทรกแม่แบบ", + "150": "ค้นหาแม่แบบ", + "151": "หมวดหมู่แม่แบบ", + "152": "กำลังโหลดแม่แบบ...", + "153": "ไม่มีแม่แบบที่ตรงกับการค้นหานี้", + "154": "ลูกศร", + "155": "สัญลักษณ์", + "156": "วงเล็บ", + "157": "ออร์บิทัล", + "158": "รูปร่าง", + "159": "TLC" +} 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": "เลือกบนผืนผ้าใบ" +} diff --git a/frontend/src/i18n/locales/tr/part05.json b/frontend/src/i18n/locales/tr/part05.json new file mode 100644 index 00000000..45ef65dc --- /dev/null +++ b/frontend/src/i18n/locales/tr/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Tuvalin üst ve sol kenarındaki cetvelleri çizim birimlerinde gösterir veya gizler (birimleri değiştirmek için köşeye tıklayın). Kılavuz yerleştirmek için bir cetvelden sürükleyin; kaldırmak için kılavuzu tekrar cetvelin üzerine sürükleyin. Seçim hatırlanır.", + "1": "Kılavuzları Temizle", + "2": "Bu penceredeki etkin çizimin tüm cetvel kılavuzlarını kaldırır. Kılavuzlar belgeye hiçbir zaman kaydedilmez.", + "3": "Önce bir cetvelden kılavuz sürükleyin", + "4": "Önce bul çubuğunu açın ve aranacak şeyi yazın", + "5": "Tuvalin üzerinde bul çubuğunu açar. Etkin çizimde metin, başlık, tablo hücresi, atom etiketi ve kısaltma, element sembolü, C2H6O gibi formül ve SMILES arar; Enter veya F3 sonraki eşleşmeye gider ve onu seçer.", + "6": "Sonrakini Bul", + "7": "Sonraki eşleşmeyi seçer ve ekran dışındaysa oraya kaydırır.", + "8": "Öncekini Bul", + "9": "Önceki eşleşmeyi seçer ve ekran dışındaysa oraya kaydırır.", + "10": "Değiştir...", + "11": "Bul çubuğunu Değiştir satırıyla açar. Değiştir geçerli metin eşleşmesini değiştirir; Tümünü Değiştir tüm metin eşleşmelerini tek bir geri alma adımında değiştirir.", + "12": "Kullanıcıdan bir PNG, JPEG, GIF, WebP veya SVG resmi ister ve tek bir geri alma adımında görünen sayfanın ortasına yerleştirir.", + "13": "Stokiyometri Paneli", + "14": "Şablon kitaplığını açar; kimlik verilirse o şablonu (yeni kimliklerle, çizimin bağ uzunluğuna ölçeklenmiş olarak) etkin çizimin görünümünün ortasına veya yeni bir çizime tek bir geri alma adımında ekler. GET /api/templates kimlikleri listeler.", + "15": "GET /api/templates içindeki şablon kimliği, örneğin benzene veya l-alanine; kitaplığı açmak için boş bırakın", + "16": "0.6.0 sürümünde gelecek; o zamana kadar Tepkimeleri Algıla rolleri çizimden belirler", + "17": "Stokiyometri Tablosu Ekle", + "18": "Seçili tepkime adımının stokiyometri ızgarasını tepkimenin altına tablo olarak ekler veya o adıma bağlı mevcut tabloyu tek bir geri alma adımında yeniler.", + "19": "Önce bir okla tepkime çizin", + "20": "Tepkimeyi Şu Olarak Kopyala", + "21": "Tepkimeyi Dışa Aktar", + "22": "Önce girenler ve ürünlerle bir tepkime oku çizin", + "23": "Tepkime bulunamadı: iki yanında yapılar bulunan bir ok çizin.", + "24": "Adımın atom eşlemesi yok.", + "25": "Denkliği Denetle", + "26": "Tepkime denktir.", + "27": "Tepkime denk değildir.", + "28": "{0}: {1} / {2} g/mol", + "29": "Denkleştir", + "30": "Tepkime denkleştirildi.", + "31": "Tepkime denkleştirilemedi", + "32": "Tepkime zaten denk.", + "33": "pano kullanılamıyor", + "34": "Tepkime Ekle", + "35": "Tepkime SMILES veya RXN", + "36": "Tepkimeleri Algıla", + "37": "Sayfadaki tepkime oklarını okur ve her adımı girenleri, ürünleri, ajanları ve koşullarıyla birlikte tek bir geri alma adımında saklar.", + "38": "Tepkimeler algılanamadı", + "39": "Seçili tepkime adımının atomlarını eşler (hiçbiri saklı değilse önce tepkimeleri algılar) ve kopan, oluşan ve değişen bağları tek bir geri alma adımında işaretler.", + "40": "Atomlar eşlenemedi", + "41": "Seçili tepkime adımının atom eşleme numaralarını ve tepkime merkezi işaretlerini kaldırır.", + "42": "Eşleme temizlenemedi", + "43": "Denkliği Denetle...", + "44": "Seçili tepkime adımının element, yük ve kütle denkliğini, denk değilse bir öneriyle birlikte gösterir.", + "45": "Tepkime denetlenemedi", + "46": "Tepkimeyi Denkleştir", + "47": "Seçili tepkime adımının katsayılarını denk değerlere tek bir geri alma adımında ayarlar.", + "48": "Tepkime SMILES'ını Kopyala", + "49": "Tepkime kopyalanamadı", + "50": "Tepkimeyi RXN Olarak Kopyala", + "51": "Tepkime SMILES'ını Dışa Aktar...", + "52": "Tepkime dışa aktarılamadı", + "53": "Tepkimeyi RXN Olarak Dışa Aktar...", + "54": "Panodan Tepkime Ekle", + "55": "Panodan tepkime SMILES veya RXN dosyası okur ve rolleri ayarlanmış olarak sayfaya tek bir geri alma adımında yerleştirir.", + "56": "Tepkime eklenemedi", + "57": "Bileşik", + "58": "Rol", + "59": "MW", + "60": "Eşdeğer", + "61": "Kütle (mg)", + "62": "Hacim (mL)", + "63": "Teorik verim", + "64": "Verim", + "65": "Cetvel birimleri çizimi izler; değiştirmek için tıklayın", + "66": "Cetvel birimleri; değiştirmek için tıklayın", + "67": "Ok ekle", + "68": "Parantez etiketini ayarla", + "69": "Parantez ekle", + "70": "Bileşik numarası ekle", + "71": "Başlık ekle", + "72": "Elektron itme oku ekle", + "73": "Olta oku ekle", + "74": "Oku bük", + "75": "Ok ucunu taşı", + "76": "Noktayı taşı", + "77": "Yeniden boyutlandır", + "78": "Resim ekle", + "79": "Başlık", + "80": "Tepkime oku", + "81": "Denge oku", + "82": "Retrosentetik ok", + "83": "Rezonans oku", + "84": "Yasak oku", + "85": "Kesikli ok", + "86": "Çizgi oku", + "87": "Elektron itme oku", + "88": "Olta oku", + "89": "Artı işareti", + "90": "Eşittir işareti", + "91": "Katılma ürünü noktası", + "92": "Yuvarlak parantez", + "93": "Köşeli parantez", + "94": "Küme parantezi", + "95": "Dikdörtgen", + "96": "Yuvarlatılmış dikdörtgen", + "97": "Elips", + "98": "Çokgen", + "99": "Çizgi ve çoklu çizgi", + "100": "TLC plakası", + "101": "Resim", + "102": "p orbitali", + "103": "s orbitali", + "104": "d orbitali", + "105": "dz2 orbitali", + "106": "sp hibrit orbitali", + "107": "Sigma bağı orbitali", + "108": "Pi bağı orbitali", + "109": "Çizgi ekle", + "110": "Orbital ekle", + "111": "Artı işareti ekle", + "112": "Şekil ekle", + "113": "Tablo ekle", + "114": "TLC plakası ekle", + "115": "TLC lekesi ekle", + "116": "Metin, etiket, formül veya SMILES bul", + "117": "Bul", + "118": "Yeni metin", + "119": "Değiştirmeyi Göster", + "120": "Büyük/Küçük Harf Eşleştir", + "121": "{0} (Shift+F3)", + "122": "Önceki Eşleşme", + "123": "Sonraki Eşleşme", + "124": "{0} (Esc)", + "125": "Değiştir", + "126": "Tümünü Değiştir", + "127": "Sonuç yok", + "128": "Değiştirmeyi Gizle", + "129": "1 eşleşme değiştirildi", + "130": "{0} eşleşme değiştirildi", + "131": "Bileşen", + "132": "Kütle", + "133": "Hacim", + "134": "Yoğunluk", + "135": "Der.", + "136": "Saflık", + "137": "Giren", + "138": "Reaktif", + "139": "Ürün", + "140": "Otomatik", + "141": "{0} mg · {1} mmol", + "142": "Stokiyometriyi Düzenle", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "İzole", + "146": "Bulunamadı", + "147": "Şablon boş.", + "148": "{0} ({1}) şablonu \"{2}\" ({3}) içine tek bir geri alma adımında eklendi", + "149": "Şablon Ekle", + "150": "Şablonlarda ara", + "151": "Şablon kategorileri", + "152": "Şablonlar yükleniyor...", + "153": "Bu aramayla eşleşen şablon yok.", + "154": "Oklar", + "155": "Semboller", + "156": "Parantezler", + "157": "Orbitaller", + "158": "Şekiller", + "159": "TLC" +} 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ç" +} diff --git a/frontend/src/i18n/locales/uk/part05.json b/frontend/src/i18n/locales/uk/part05.json new file mode 100644 index 00000000..4ab00814 --- /dev/null +++ b/frontend/src/i18n/locales/uk/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Показує або приховує лінійки вздовж верхнього та лівого країв полотна в одиницях рисунка (клацніть кут, щоб змінити одиниці). Перетягніть напрямну з лінійки, щоб розмістити її; перетягніть напрямну назад на лінійку, щоб видалити. Вибір запам’ятовується.", + "1": "Очистити напрямні", + "2": "Видаляє всі напрямні лінійок з активного рисунка в цьому вікні. Напрямні ніколи не зберігаються в документі.", + "3": "Спершу витягніть напрямну з лінійки", + "4": "Відкрийте рядок пошуку й спершу введіть, що шукати", + "5": "Відкриває рядок пошуку над полотном. Він шукає в активному рисунку текст, підписи, клітинки таблиць, мітки атомів і скорочення, символи елементів, формули, як-от C2H6O, та SMILES; Enter або F3 переходить до наступного збігу й виділяє його.", + "6": "Знайти далі", + "7": "Виділяє наступний збіг і прокручує до нього, якщо він поза екраном.", + "8": "Знайти раніше", + "9": "Виділяє попередній збіг і прокручує до нього, якщо він поза екраном.", + "10": "Замінити...", + "11": "Відкриває рядок пошуку з рядком заміни. Замінити змінює поточний текстовий збіг; Замінити все змінює всі текстові збіги одним кроком скасування.", + "12": "Запитує зображення PNG, JPEG, GIF, WebP або SVG і розміщує його посередині видимої сторінки одним кроком скасування.", + "13": "Панель стехіометрії", + "14": "Відкриває бібліотеку шаблонів; з ідентифікатором вставляє цей шаблон (з новими ідентифікаторами, масштабований до довжини зв’язку рисунка) у центр вигляду активного рисунка або в новий, одним кроком скасування. GET /api/templates перелічує ідентифікатори.", + "15": "Ідентифікатор шаблону з GET /api/templates, наприклад benzene або l-alanine; пропустіть, щоб відкрити бібліотеку", + "16": "З’явиться у 0.6.0; до того Розпізнати реакції задає ролі за рисунком", + "17": "Вставити таблицю стехіометрії", + "18": "Вставляє сітку стехіометрії виділеного кроку реакції як таблицю під реакцією або оновлює таблицю, вже пов’язану з цим кроком, одним кроком скасування.", + "19": "Спершу намалюйте реакцію зі стрілкою", + "20": "Копіювати реакцію як", + "21": "Експортувати реакцію", + "22": "Спершу намалюйте стрілку реакції з реагентами та продуктами", + "23": "Реакцію не знайдено: намалюйте стрілку зі структурами з обох боків.", + "24": "Крок не має атомного відображення.", + "25": "Перевірити баланс", + "26": "Реакція збалансована.", + "27": "Реакція не збалансована.", + "28": "{0}: {1} / {2} g/mol", + "29": "Збалансувати", + "30": "Реакцію збалансовано.", + "31": "Не вдалося збалансувати реакцію", + "32": "Реакція вже збалансована.", + "33": "буфер обміну недоступний", + "34": "Вставити реакцію", + "35": "SMILES реакції або RXN", + "36": "Розпізнати реакції", + "37": "Зчитує стрілки реакцій на сторінці та зберігає кожен крок з його реагентами, продуктами, агентами й умовами одним кроком скасування.", + "38": "Не вдалося розпізнати реакції", + "39": "Зіставляє атоми виділеного кроку реакції (спершу розпізнаючи реакції, якщо жодної не збережено) і позначає розірвані, утворені та змінені зв’язки одним кроком скасування.", + "40": "Не вдалося зіставити атоми", + "41": "Видаляє номери зіставлення атомів і позначки реакційного центру виділеного кроку реакції.", + "42": "Не вдалося очистити зіставлення", + "43": "Перевірити баланс...", + "44": "Показує баланс елементів, заряду й маси виділеного кроку реакції з підказкою, якщо реакція не збалансована.", + "45": "Не вдалося перевірити реакцію", + "46": "Збалансувати реакцію", + "47": "Задає коефіцієнти виділеного кроку реакції збалансованими значеннями одним кроком скасування.", + "48": "Копіювати SMILES реакції", + "49": "Не вдалося скопіювати реакцію", + "50": "Копіювати реакцію як RXN", + "51": "Експортувати SMILES реакції...", + "52": "Не вдалося експортувати реакцію", + "53": "Експортувати реакцію як RXN...", + "54": "Вставити реакцію з буфера обміну", + "55": "Зчитує SMILES реакції або файл RXN з буфера обміну та розкладає його на сторінці із заданими ролями одним кроком скасування.", + "56": "Не вдалося вставити реакцію", + "57": "Сполука", + "58": "Роль", + "59": "MW", + "60": "Екв.", + "61": "Маса (mg)", + "62": "Об’єм (mL)", + "63": "Теоретичний вихід", + "64": "Вихід", + "65": "Одиниці лінійки відповідають рисунку; клацніть, щоб змінити", + "66": "Одиниці лінійки; клацніть, щоб змінити", + "67": "Додати стрілку", + "68": "Задати підпис дужки", + "69": "Додати дужку", + "70": "Додати номер сполуки", + "71": "Додати підпис", + "72": "Додати стрілку переміщення електронів", + "73": "Додати півстрілку", + "74": "Зігнути стрілку", + "75": "Перемістити кінець стрілки", + "76": "Перемістити точку", + "77": "Змінити розмір", + "78": "Додати зображення", + "79": "Підпис", + "80": "Стрілка реакції", + "81": "Стрілка рівноваги", + "82": "Ретросинтетична стрілка", + "83": "Резонансна стрілка", + "84": "Заборонна стрілка", + "85": "Пунктирна стрілка", + "86": "Лінійна стрілка", + "87": "Стрілка переміщення електронів", + "88": "Півстрілка", + "89": "Знак плюс", + "90": "Знак дорівнює", + "91": "Крапка аддукту", + "92": "Круглі дужки", + "93": "Квадратні дужки", + "94": "Фігурні дужки", + "95": "Прямокутник", + "96": "Прямокутник із округленими кутами", + "97": "Еліпс", + "98": "Багатокутник", + "99": "Лінія та ламана", + "100": "Пластинка ТШХ", + "101": "Зображення", + "102": "p-орбіталь", + "103": "s-орбіталь", + "104": "d-орбіталь", + "105": "dz2-орбіталь", + "106": "sp-гібридна орбіталь", + "107": "Орбіталь сигма-зв’язку", + "108": "Орбіталь пі-зв’язку", + "109": "Додати лінію", + "110": "Додати орбіталь", + "111": "Додати знак плюс", + "112": "Додати фігуру", + "113": "Додати таблицю", + "114": "Додати пластинку ТШХ", + "115": "Додати пляму ТШХ", + "116": "Шукати текст, підписи, формули або SMILES", + "117": "Знайти", + "118": "Замінити на", + "119": "Показати заміну", + "120": "З урахуванням регістру", + "121": "{0} (Shift+F3)", + "122": "Попередній збіг", + "123": "Наступний збіг", + "124": "{0} (Esc)", + "125": "Замінити", + "126": "Замінити все", + "127": "Немає результатів", + "128": "Сховати заміну", + "129": "Замінено 1 збіг", + "130": "Замінено збігів: {0}", + "131": "Компонент", + "132": "Маса", + "133": "Об’єм", + "134": "Густина", + "135": "Конц.", + "136": "Чистота", + "137": "Реактант", + "138": "Реагент", + "139": "Продукт", + "140": "Авто", + "141": "{0} mg · {1} mmol", + "142": "Редагувати стехіометрію", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Виділений", + "146": "Не знайдено", + "147": "Шаблон порожній.", + "148": "Шаблон {0} ({1}) вставлено в \"{2}\" ({3}) одним кроком скасування", + "149": "Вставити шаблон", + "150": "Шукати шаблони", + "151": "Категорії шаблонів", + "152": "Завантаження шаблонів...", + "153": "Жоден шаблон не відповідає цьому пошуку.", + "154": "Стрілки", + "155": "Символи", + "156": "Дужки", + "157": "Орбіталі", + "158": "Фігури", + "159": "ТШХ" +} 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": "Виділити на полотні" +} diff --git a/frontend/src/i18n/locales/vi/part05.json b/frontend/src/i18n/locales/vi/part05.json new file mode 100644 index 00000000..798cd668 --- /dev/null +++ b/frontend/src/i18n/locales/vi/part05.json @@ -0,0 +1,162 @@ +{ + "0": "Hiện hoặc ẩn thước dọc theo mép trên và mép trái của canvas, theo đơn vị của bản vẽ (nhấp vào góc để đổi đơn vị). Kéo từ thước để đặt đường dẫn; kéo đường dẫn trở lại thước để xóa. Lựa chọn này được ghi nhớ.", + "1": "Xóa đường dẫn", + "2": "Xóa mọi đường dẫn của thước khỏi bản vẽ đang dùng trong cửa sổ này. Đường dẫn không bao giờ được lưu vào tài liệu.", + "3": "Hãy kéo một đường dẫn ra từ thước trước", + "4": "Hãy mở thanh tìm kiếm và nhập nội dung cần tìm trước", + "5": "Mở thanh tìm kiếm phía trên canvas. Thanh này tìm văn bản, chú thích, ô bảng, nhãn nguyên tử và chữ viết tắt, ký hiệu nguyên tố, công thức như C2H6O và SMILES trong bản vẽ đang dùng; Enter hoặc F3 chuyển đến kết quả khớp tiếp theo và chọn nó.", + "6": "Tìm tiếp", + "7": "Chọn kết quả khớp tiếp theo và cuộn đến đó nếu nó nằm ngoài màn hình.", + "8": "Tìm lùi", + "9": "Chọn kết quả khớp trước đó và cuộn đến đó nếu nó nằm ngoài màn hình.", + "10": "Thay thế...", + "11": "Mở thanh tìm kiếm cùng hàng Thay thế. Thay thế đổi kết quả khớp văn bản hiện tại; Thay thế tất cả đổi mọi kết quả khớp văn bản trong một bước hoàn tác.", + "12": "Yêu cầu chọn ảnh PNG, JPEG, GIF, WebP hoặc SVG và đặt vào giữa trang đang hiển thị trong một bước hoàn tác.", + "13": "Bảng phân tích hợp thức", + "14": "Mở thư viện mẫu; nếu có id thì chèn mẫu đó (với id mới, co giãn theo độ dài liên kết của bản vẽ) vào giữa vùng xem của bản vẽ đang dùng, hoặc vào bản vẽ mới, trong một bước hoàn tác. GET /api/templates liệt kê các id.", + "15": "Id mẫu từ GET /api/templates, chẳng hạn benzene hoặc l-alanine; bỏ trống để mở thư viện", + "16": "Sẽ có trong 0.6.0; cho đến lúc đó Nhận diện phản ứng đặt vai trò từ bản vẽ", + "17": "Chèn bảng hợp thức", + "18": "Chèn lưới hợp thức của bước phản ứng được chọn dưới dạng bảng bên dưới phản ứng, hoặc làm mới bảng đã gắn với bước đó, trong một bước hoàn tác.", + "19": "Hãy vẽ phản ứng có mũi tên trước", + "20": "Sao chép phản ứng dưới dạng", + "21": "Xuất phản ứng", + "22": "Hãy vẽ mũi tên phản ứng cùng chất phản ứng và sản phẩm trước", + "23": "Không tìm thấy phản ứng: hãy vẽ mũi tên có cấu trúc ở cả hai bên.", + "24": "Bước này chưa có ánh xạ nguyên tử.", + "25": "Kiểm tra cân bằng", + "26": "Phản ứng đã cân bằng.", + "27": "Phản ứng chưa cân bằng.", + "28": "{0}: {1} / {2} g/mol", + "29": "Cân bằng", + "30": "Đã cân bằng phản ứng.", + "31": "Không thể cân bằng phản ứng", + "32": "Phản ứng đã được cân bằng.", + "33": "không dùng được bộ nhớ tạm", + "34": "Chèn phản ứng", + "35": "SMILES phản ứng hoặc RXN", + "36": "Nhận diện phản ứng", + "37": "Đọc các mũi tên phản ứng trên trang và lưu từng bước cùng chất phản ứng, sản phẩm, tác nhân và điều kiện, trong một bước hoàn tác.", + "38": "Không thể nhận diện phản ứng", + "39": "Ánh xạ các nguyên tử của bước phản ứng được chọn (nhận diện phản ứng trước nếu chưa lưu phản ứng nào) và đánh dấu các liên kết bị phá vỡ, được tạo thành và thay đổi, trong một bước hoàn tác.", + "40": "Không thể ánh xạ nguyên tử", + "41": "Xóa số ánh xạ nguyên tử và dấu tâm phản ứng của bước phản ứng được chọn.", + "42": "Không thể xóa ánh xạ", + "43": "Kiểm tra cân bằng...", + "44": "Hiển thị cân bằng nguyên tố, điện tích và khối lượng của bước phản ứng được chọn, kèm gợi ý khi chưa cân bằng.", + "45": "Không thể kiểm tra phản ứng", + "46": "Cân bằng phản ứng", + "47": "Đặt hệ số của bước phản ứng được chọn về các giá trị đã cân bằng, trong một bước hoàn tác.", + "48": "Sao chép SMILES phản ứng", + "49": "Không thể sao chép phản ứng", + "50": "Sao chép phản ứng dưới dạng RXN", + "51": "Xuất SMILES phản ứng...", + "52": "Không thể xuất phản ứng", + "53": "Xuất phản ứng dưới dạng RXN...", + "54": "Chèn phản ứng từ bộ nhớ tạm", + "55": "Đọc SMILES phản ứng hoặc tệp RXN từ bộ nhớ tạm và bố trí trên trang với vai trò đã đặt, trong một bước hoàn tác.", + "56": "Không thể chèn phản ứng", + "57": "Hợp chất", + "58": "Vai trò", + "59": "MW", + "60": "Đương lượng", + "61": "Khối lượng (mg)", + "62": "Thể tích (mL)", + "63": "Hiệu suất lý thuyết", + "64": "Hiệu suất", + "65": "Đơn vị thước theo bản vẽ; nhấp để đổi", + "66": "Đơn vị thước; nhấp để đổi", + "67": "Thêm mũi tên", + "68": "Đặt nhãn ngoặc", + "69": "Thêm ngoặc", + "70": "Thêm số hợp chất", + "71": "Thêm chú thích", + "72": "Thêm mũi tên dịch chuyển electron", + "73": "Thêm mũi tên nửa đầu", + "74": "Uốn mũi tên", + "75": "Di chuyển đầu mũi tên", + "76": "Di chuyển điểm", + "77": "Đổi kích thước", + "78": "Thêm ảnh", + "79": "Chú thích", + "80": "Mũi tên phản ứng", + "81": "Mũi tên cân bằng", + "82": "Mũi tên tổng hợp ngược", + "83": "Mũi tên cộng hưởng", + "84": "Mũi tên cấm", + "85": "Mũi tên nét đứt", + "86": "Mũi tên đường thẳng", + "87": "Mũi tên dịch chuyển electron", + "88": "Mũi tên nửa đầu", + "89": "Dấu cộng", + "90": "Dấu bằng", + "91": "Chấm sản phẩm cộng", + "92": "Ngoặc tròn", + "93": "Ngoặc vuông", + "94": "Ngoặc nhọn", + "95": "Hình chữ nhật", + "96": "Hình chữ nhật bo góc", + "97": "Hình elip", + "98": "Đa giác", + "99": "Đường thẳng và đường gấp khúc", + "100": "Bản mỏng TLC", + "101": "Ảnh", + "102": "Obitan p", + "103": "Obitan s", + "104": "Obitan d", + "105": "Obitan dz2", + "106": "Obitan lai hóa sp", + "107": "Obitan liên kết sigma", + "108": "Obitan liên kết pi", + "109": "Thêm đường thẳng", + "110": "Thêm obitan", + "111": "Thêm dấu cộng", + "112": "Thêm hình", + "113": "Thêm bảng", + "114": "Thêm bản mỏng TLC", + "115": "Thêm vết TLC", + "116": "Tìm văn bản, nhãn, công thức hoặc SMILES", + "117": "Tìm", + "118": "Thay bằng", + "119": "Hiện thay thế", + "120": "Phân biệt hoa thường", + "121": "{0} (Shift+F3)", + "122": "Kết quả khớp trước", + "123": "Kết quả khớp tiếp theo", + "124": "{0} (Esc)", + "125": "Thay thế", + "126": "Thay thế tất cả", + "127": "Không có kết quả", + "128": "Ẩn thay thế", + "129": "Đã thay thế 1 kết quả khớp", + "130": "Đã thay thế {0} kết quả khớp", + "131": "Thành phần", + "132": "Khối lượng", + "133": "Thể tích", + "134": "Khối lượng riêng", + "135": "Nồng độ", + "136": "Độ tinh khiết", + "137": "Chất phản ứng", + "138": "Thuốc thử", + "139": "Sản phẩm", + "140": "Tự động", + "141": "{0} mg · {1} mmol", + "142": "Sửa hợp thức", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "Đã phân lập", + "146": "Không tìm thấy", + "147": "Mẫu trống.", + "148": "Đã chèn mẫu {0} ({1}) vào \"{2}\" ({3}) trong một bước hoàn tác", + "149": "Chèn mẫu", + "150": "Tìm mẫu", + "151": "Danh mục mẫu", + "152": "Đang tải mẫu...", + "153": "Không có mẫu nào khớp với tìm kiếm này.", + "154": "Mũi tên", + "155": "Ký hiệu", + "156": "Ngoặc", + "157": "Obitan", + "158": "Hình", + "159": "TLC" +} 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" +} diff --git a/frontend/src/i18n/locales/zh-Hans/part05.json b/frontend/src/i18n/locales/zh-Hans/part05.json new file mode 100644 index 00000000..a9aacf95 --- /dev/null +++ b/frontend/src/i18n/locales/zh-Hans/part05.json @@ -0,0 +1,162 @@ +{ + "0": "在画布顶部和左侧边缘显示或隐藏标尺,单位与绘图单位一致(点击角落可切换单位)。从标尺拖出可放置参考线;将参考线拖回标尺即可删除。此选择会被记住。", + "1": "清除参考线", + "2": "移除此窗口中当前绘图的所有标尺参考线。参考线不会保存到文档中。", + "3": "请先从标尺上拖出一条参考线", + "4": "请先打开查找栏并输入要查找的内容", + "5": "在画布上方打开查找栏。可在当前绘图中查找文本、说明文字、表格单元格、原子标签和缩写、元素符号、C2H6O 等分子式以及 SMILES;按 Enter 或 F3 跳到下一个匹配项并将其选中。", + "6": "查找下一个", + "7": "选中下一个查找匹配项,若其在屏幕之外则平移到该处。", + "8": "查找上一个", + "9": "选中上一个查找匹配项,若其在屏幕之外则平移到该处。", + "10": "替换...", + "11": "打开带有替换行的查找栏。“替换”会更改当前文本匹配项;“全部替换”会以一个撤销步骤更改所有文本匹配项。", + "12": "请用户选择 PNG、JPEG、GIF、WebP 或 SVG 图片,并以一个撤销步骤将其放置在可见页面的中央。", + "13": "化学计量面板", + "14": "打开模板库;若提供 id,则以一个撤销步骤将该模板(使用新的 id,并按绘图键长缩放)居中插入当前绘图的视图中,或插入到新绘图中。GET /api/templates 会列出所有 id。", + "15": "来自 GET /api/templates 的模板 id,例如 benzene 或 l-alanine;省略则打开模板库", + "16": "将在 0.6.0 版本推出;在此之前,请使用“识别反应”根据绘图设置角色", + "17": "插入化学计量表", + "18": "以一个撤销步骤,将所选反应步骤的化学计量网格作为表格插入反应下方,或刷新已绑定到该步骤的表格。", + "19": "请先用箭头绘制一个反应", + "20": "将反应复制为", + "21": "导出反应", + "22": "请先绘制带有反应物和产物的反应箭头", + "23": "未找到反应:请绘制两侧都有结构的箭头。", + "24": "该步骤没有原子映射。", + "25": "检查配平", + "26": "反应已配平。", + "27": "反应未配平。", + "28": "{0}:{1} / {2} g/mol", + "29": "配平", + "30": "已配平反应。", + "31": "无法配平反应", + "32": "反应已经配平。", + "33": "剪贴板不可用", + "34": "插入反应", + "35": "反应 SMILES 或 RXN", + "36": "识别反应", + "37": "读取页面上的反应箭头,并以一个撤销步骤保存每个步骤的反应物、产物、试剂和条件。", + "38": "无法识别反应", + "39": "为所选反应步骤映射原子(若尚未保存任何反应,则先识别反应),并标出断裂、形成和改变的键,作为一个撤销步骤。", + "40": "无法映射原子", + "41": "移除所选反应步骤的原子映射编号和反应中心标记。", + "42": "无法清除映射", + "43": "检查配平...", + "44": "显示所选反应步骤的元素、电荷和质量平衡;若未配平则给出建议。", + "45": "无法检查反应", + "46": "配平反应", + "47": "以一个撤销步骤,将所选反应步骤的系数设为配平后的值。", + "48": "复制反应 SMILES", + "49": "无法复制反应", + "50": "将反应复制为 RXN", + "51": "导出反应 SMILES...", + "52": "无法导出反应", + "53": "将反应导出为 RXN...", + "54": "从剪贴板插入反应", + "55": "从剪贴板读取反应 SMILES 或 RXN 文件,设置好角色后排布到页面上,作为一个撤销步骤。", + "56": "无法插入反应", + "57": "化合物", + "58": "角色", + "59": "MW", + "60": "当量", + "61": "质量 (mg)", + "62": "体积 (mL)", + "63": "理论产量", + "64": "产率", + "65": "标尺单位与绘图一致;点击可更改", + "66": "标尺单位;点击可更改", + "67": "添加箭头", + "68": "设置括号标签", + "69": "添加括号", + "70": "添加化合物编号", + "71": "添加说明文字", + "72": "添加电子转移箭头", + "73": "添加单电子转移箭头", + "74": "弯曲箭头", + "75": "移动箭头端点", + "76": "移动点", + "77": "调整大小", + "78": "添加图片", + "79": "说明文字", + "80": "反应箭头", + "81": "平衡箭头", + "82": "逆合成箭头", + "83": "共振箭头", + "84": "禁止箭头", + "85": "虚线箭头", + "86": "直线箭头", + "87": "电子转移箭头", + "88": "单电子转移箭头", + "89": "加号", + "90": "等号", + "91": "加合物点", + "92": "圆括号", + "93": "方括号", + "94": "花括号", + "95": "矩形", + "96": "圆角矩形", + "97": "椭圆", + "98": "多边形", + "99": "直线和折线", + "100": "TLC 板", + "101": "图片", + "102": "p 轨道", + "103": "s 轨道", + "104": "d 轨道", + "105": "dz2 轨道", + "106": "sp 杂化轨道", + "107": "σ 键轨道", + "108": "π 键轨道", + "109": "添加线条", + "110": "添加轨道", + "111": "添加加号", + "112": "添加形状", + "113": "添加表格", + "114": "添加 TLC 板", + "115": "添加 TLC 斑点", + "116": "查找文本、标签、分子式或 SMILES", + "117": "查找", + "118": "替换为", + "119": "显示替换", + "120": "区分大小写", + "121": "{0} (Shift+F3)", + "122": "上一个匹配项", + "123": "下一个匹配项", + "124": "{0} (Esc)", + "125": "替换", + "126": "全部替换", + "127": "无结果", + "128": "隐藏替换", + "129": "已替换 1 处匹配", + "130": "已替换 {0} 处匹配", + "131": "组分", + "132": "质量", + "133": "体积", + "134": "密度", + "135": "浓度", + "136": "纯度", + "137": "反应物", + "138": "试剂", + "139": "产物", + "140": "自动", + "141": "{0} mg · {1} mmol", + "142": "编辑化学计量", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "分离产率", + "146": "未找到", + "147": "模板为空。", + "148": "已将模板 {0}({1})插入“{2}”({3}),作为一个撤销步骤", + "149": "插入模板", + "150": "搜索模板", + "151": "模板类别", + "152": "正在加载模板...", + "153": "没有与此搜索匹配的模板。", + "154": "箭头", + "155": "符号", + "156": "括号", + "157": "轨道", + "158": "形状", + "159": "TLC" +} 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": "在画布上选中" +} diff --git a/frontend/src/i18n/locales/zh-Hant/part05.json b/frontend/src/i18n/locales/zh-Hant/part05.json new file mode 100644 index 00000000..b209616d --- /dev/null +++ b/frontend/src/i18n/locales/zh-Hant/part05.json @@ -0,0 +1,162 @@ +{ + "0": "在畫布頂部和左側邊緣顯示或隱藏尺規,單位與繪圖單位一致(點擊角落可切換單位)。從尺規拖曳可放置參考線;將參考線拖回尺規即可移除。此選擇會被記住。", + "1": "清除參考線", + "2": "移除此視窗中目前繪圖的所有尺規參考線。參考線不會儲存到文件中。", + "3": "請先從尺規拖出一條參考線", + "4": "請先開啟尋找列並輸入要尋找的內容", + "5": "在畫布上方開啟尋找列。可在目前繪圖中尋找文字、說明文字、表格儲存格、原子標籤和縮寫、元素符號、C2H6O 等分子式以及 SMILES;按 Enter 或 F3 跳到下一個符合項並將其選取。", + "6": "尋找下一個", + "7": "選取下一個符合項,若其在螢幕之外則平移到該處。", + "8": "尋找上一個", + "9": "選取上一個符合項,若其在螢幕之外則平移到該處。", + "10": "取代...", + "11": "開啟帶有取代列的尋找列。「取代」會變更目前的文字符合項;「全部取代」會以一個復原步驟變更所有文字符合項。", + "12": "請使用者選擇 PNG、JPEG、GIF、WebP 或 SVG 圖片,並以一個復原步驟將其放置在可見頁面的中央。", + "13": "化學計量面板", + "14": "開啟範本庫;若提供 id,則以一個復原步驟將該範本(使用新的 id,並依繪圖鍵長縮放)置中插入目前繪圖的檢視中,或插入到新繪圖中。GET /api/templates 會列出所有 id。", + "15": "來自 GET /api/templates 的範本 id,例如 benzene 或 l-alanine;省略則開啟範本庫", + "16": "將於 0.6.0 版推出;在此之前,請使用「辨識反應」依繪圖設定角色", + "17": "插入化學計量表", + "18": "以一個復原步驟,將所選反應步驟的化學計量網格作為表格插入反應下方,或更新已綁定到該步驟的表格。", + "19": "請先用箭頭繪製一個反應", + "20": "將反應複製為", + "21": "匯出反應", + "22": "請先繪製帶有反應物和產物的反應箭頭", + "23": "找不到反應:請繪製兩側都有結構的箭頭。", + "24": "該步驟沒有原子對應。", + "25": "檢查平衡", + "26": "反應已平衡。", + "27": "反應未平衡。", + "28": "{0}:{1} / {2} g/mol", + "29": "平衡", + "30": "已平衡反應。", + "31": "無法平衡反應", + "32": "反應已經平衡。", + "33": "剪貼簿無法使用", + "34": "插入反應", + "35": "反應 SMILES 或 RXN", + "36": "辨識反應", + "37": "讀取頁面上的反應箭頭,並以一個復原步驟儲存每個步驟的反應物、產物、試劑和條件。", + "38": "無法辨識反應", + "39": "為所選反應步驟對應原子(若尚未儲存任何反應,則先辨識反應),並標出斷裂、形成和改變的鍵,作為一個復原步驟。", + "40": "無法對應原子", + "41": "移除所選反應步驟的原子對應編號和反應中心標記。", + "42": "無法清除對應", + "43": "檢查平衡...", + "44": "顯示所選反應步驟的元素、電荷和質量平衡;若未平衡則提供建議。", + "45": "無法檢查反應", + "46": "平衡反應", + "47": "以一個復原步驟,將所選反應步驟的係數設為平衡後的值。", + "48": "複製反應 SMILES", + "49": "無法複製反應", + "50": "將反應複製為 RXN", + "51": "匯出反應 SMILES...", + "52": "無法匯出反應", + "53": "將反應匯出為 RXN...", + "54": "從剪貼簿插入反應", + "55": "從剪貼簿讀取反應 SMILES 或 RXN 檔案,設定好角色後排列到頁面上,作為一個復原步驟。", + "56": "無法插入反應", + "57": "化合物", + "58": "角色", + "59": "MW", + "60": "當量", + "61": "質量 (mg)", + "62": "體積 (mL)", + "63": "理論產量", + "64": "產率", + "65": "尺規單位與繪圖一致;點擊可變更", + "66": "尺規單位;點擊可變更", + "67": "新增箭頭", + "68": "設定括號標籤", + "69": "新增括號", + "70": "新增化合物編號", + "71": "新增說明文字", + "72": "新增電子轉移箭頭", + "73": "新增單電子轉移箭頭", + "74": "彎曲箭頭", + "75": "移動箭頭端點", + "76": "移動點", + "77": "調整大小", + "78": "新增圖片", + "79": "說明文字", + "80": "反應箭頭", + "81": "平衡箭頭", + "82": "逆合成箭頭", + "83": "共振箭頭", + "84": "禁止箭頭", + "85": "虛線箭頭", + "86": "直線箭頭", + "87": "電子轉移箭頭", + "88": "單電子轉移箭頭", + "89": "加號", + "90": "等號", + "91": "加成物點", + "92": "圓括號", + "93": "方括號", + "94": "大括號", + "95": "矩形", + "96": "圓角矩形", + "97": "橢圓", + "98": "多邊形", + "99": "直線和折線", + "100": "TLC 板", + "101": "圖片", + "102": "p 軌域", + "103": "s 軌域", + "104": "d 軌域", + "105": "dz2 軌域", + "106": "sp 混成軌域", + "107": "σ 鍵軌域", + "108": "π 鍵軌域", + "109": "新增線條", + "110": "新增軌域", + "111": "新增加號", + "112": "新增形狀", + "113": "新增表格", + "114": "新增 TLC 板", + "115": "新增 TLC 斑點", + "116": "尋找文字、標籤、分子式或 SMILES", + "117": "尋找", + "118": "取代為", + "119": "顯示取代", + "120": "區分大小寫", + "121": "{0} (Shift+F3)", + "122": "上一個符合項", + "123": "下一個符合項", + "124": "{0} (Esc)", + "125": "取代", + "126": "全部取代", + "127": "無結果", + "128": "隱藏取代", + "129": "已取代 1 處符合項", + "130": "已取代 {0} 處符合項", + "131": "成分", + "132": "質量", + "133": "體積", + "134": "密度", + "135": "濃度", + "136": "純度", + "137": "反應物", + "138": "試劑", + "139": "產物", + "140": "自動", + "141": "{0} mg · {1} mmol", + "142": "編輯化學計量", + "143": "{0} (mg)", + "144": "{0} (mL)", + "145": "分離產率", + "146": "找不到", + "147": "範本是空的。", + "148": "已將範本 {0}({1})插入「{2}」({3}),作為一個復原步驟", + "149": "插入範本", + "150": "搜尋範本", + "151": "範本類別", + "152": "正在載入範本...", + "153": "沒有符合此搜尋的範本。", + "154": "箭頭", + "155": "符號", + "156": "括號", + "157": "軌域", + "158": "形狀", + "159": "TLC" +} 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": "在畫布上選取" +} diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index 2e07f54f..afc792f0 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; } @@ -29,6 +31,57 @@ .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); } + +.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); } +.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; } + .fc-find-more .icon { transition: none; } } diff --git a/frontend/src/styles/chem-marks.css b/frontend/src/styles/chem-marks.css new file mode 100644 index 00000000..6f22adea --- /dev/null +++ b/frontend/src/styles/chem-marks.css @@ -0,0 +1,29 @@ +.fc-canvas .fc-layer-stereo, +.fc-canvas .fc-chem-mark { + pointer-events: none; +} + +.fc-canvas .fc-mk { + white-space: pre; + dominant-baseline: alphabetic; +} + +.fc-canvas .fc-mk-cip { + letter-spacing: 0.01em; +} + +.fc-canvas .fc-mk-group, +.fc-canvas .fc-mk-flag { + font-weight: 600; +} + +.fc-canvas .fc-mk-query, +.fc-canvas .fc-mk-qbond, +.fc-canvas .fc-mk-rgdef, +.fc-canvas .fc-mk-rglabel { + font-weight: 500; +} + +.fc-canvas .fc-mk-attach { + stroke-width: max(var(--fc-lw, 0.6px), calc(1px / var(--fc-zoom))); +} diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css new file mode 100644 index 00000000..79b7c0b7 --- /dev/null +++ b/frontend/src/styles/chem-ui.css @@ -0,0 +1,146 @@ +.fc-chip { display: inline-flex; align-items: center; gap: 4px; height: 24px; padding: 0 6px 0 9px; border: 1px solid var(--line-2); border-radius: var(--radius-pill); background: var(--surface-raised); color: var(--text-primary); font: 500 var(--fc-12)/1 var(--font-mono); cursor: pointer; } +.fc-chip:hover { border-color: var(--line-3); background: var(--bg-hover); } +.fc-chip:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } +.fc-chip > .icon { color: var(--text-muted); } +.fc-chip-and { border-color: color-mix(in srgb, #2b6fd6 45%, var(--line-2)); color: color-mix(in srgb, #2b6fd6 70%, var(--text-primary)); } +.fc-chip-or { border-color: color-mix(in srgb, #c2521f 45%, var(--line-2)); color: color-mix(in srgb, #c2521f 70%, var(--text-primary)); } + +.fc-ptable { display: grid; grid-template-columns: repeat(18, minmax(0, 1fr)); grid-template-rows: repeat(7, 26px) 8px repeat(2, 26px); gap: 2px; user-select: none; -webkit-user-select: none; } +.fc-ptable-gap { grid-row: 8; grid-column: 1 / -1; } +.fc-ptable-el { min-width: 0; height: 26px; padding: 0; border: 1px solid var(--line-1); border-radius: var(--radius-xs); background: var(--surface-1); color: var(--text-secondary); font: 500 var(--fc-11)/1 var(--font-ui); cursor: pointer; } +.fc-ptable-el.is-organic { color: var(--text-primary); background: var(--surface-raised); } +.fc-ptable-el.is-f { opacity: 0.85; } +.fc-ptable-el:hover { border-color: var(--line-3); color: var(--text-primary); } +.fc-ptable-el:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 0; position: relative; z-index: var(--z-local-2); } +.fc-ptable-el.is-on { border-color: var(--accent-color); background: var(--accent-wash); color: var(--accent-ink); font-weight: 600; } + +.fc-atomlist-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-3); } +.fc-atomlist-head .fc-seg { flex: none; width: 260px; } +.fc-atomlist-preview { min-width: 0; overflow: hidden; color: var(--text-primary); font: var(--fc-13)/1.3 var(--font-mono); text-overflow: ellipsis; white-space: nowrap; } +.fc-atomlist-preview.is-empty { color: var(--text-muted); font-family: var(--font-ui); } +.fc-atomlist-chips-row { display: grid; grid-template-columns: auto minmax(0, 1fr); align-items: center; column-gap: var(--space-3); min-height: 28px; } +.fc-atomlist-chips { display: flex; flex-wrap: wrap; gap: 4px; min-height: 24px; } +.fc-atomlist-chips:empty { display: none; } +.fc-atomlist-empty { grid-column: 2; } + +.fc-rgroup-members { display: grid; gap: 2px; max-height: 168px; overflow-y: auto; padding: 4px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); } +.fc-rgroup-members:empty { display: none; } +.fc-dialog .fc-rgroup-member { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; min-height: 28px; padding: 0 6px; border-radius: var(--radius-sm); } +.fc-rgroup-member:hover { background: var(--bg-hover); } +.fc-rgroup-member-label { overflow: hidden; color: var(--text-primary); font-family: var(--font-mono); text-overflow: ellipsis; white-space: nowrap; } +.fc-rgroup-member-detail { color: var(--text-muted); font-size: var(--fc-11); } +.fc-rgroup-occ-note { margin-top: -6px; padding-left: calc(110px + var(--space-3)); min-height: 17px; } +.fc-note.is-error { color: var(--danger-text); } + +.fc-abbr-name { font-family: var(--font-mono); } +.fc-abbr-name.is-invalid { border-color: var(--danger); } +.fc-abbr-lib { display: grid; gap: var(--space-2); } +.fc-abbr-list { display: flex; flex-direction: column; height: calc(var(--fc-abbr-rows, 9) * 30px + 8px); padding: 4px; overflow-y: auto; overscroll-behavior: contain; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); } +.fc-abbr-row { display: grid; grid-template-columns: 9ch 9ch minmax(0, 1fr); align-items: center; column-gap: var(--space-3); flex: none; height: 30px; padding: 0 8px; border-radius: var(--radius-sm); color: var(--text-secondary); font-size: var(--fc-12); cursor: pointer; } +.fc-abbr-row:hover { background: var(--bg-hover); color: var(--text-primary); } +.fc-abbr-row.is-on { background: var(--accent-wash); color: var(--text-primary); } +.fc-abbr-label { color: var(--text-primary); font: 600 var(--fc-13)/1 var(--font-mono); } +.fc-abbr-rev { color: var(--text-muted); font: var(--fc-12)/1 var(--font-mono); } +.fc-abbr-cat { overflow: hidden; text-align: right; text-overflow: ellipsis; white-space: nowrap; } +.fc-abbr-row.is-user .fc-abbr-cat { color: var(--accent-ink); } +.fc-abbr-skel { flex: none; height: 22px; margin: 4px 8px; border-radius: var(--radius-sm); background: var(--surface-raised); visibility: hidden; } +.fc-abbr-list.is-shown .fc-abbr-skel { visibility: visible; } + +.fc-popover { position: fixed; left: 0; top: 0; z-index: var(--z-menu); border: 1px solid var(--line-3); border-radius: var(--radius-lg); background: var(--surface-2); box-shadow: var(--shadow-lg); color: var(--text-primary); outline: 0; } +.fc-popover[hidden] { display: none; } +.fc-popover .fc-seg { display: flex; gap: 2px; padding: 3px; border: 1px solid var(--line-2); border-radius: 9px; background: var(--surface-1); } +.fc-popover .fc-seg button { flex: 1; height: 24px; padding: 0 8px; border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font: 500 var(--fc-12)/1 var(--font-mono); cursor: pointer; } +.fc-popover .fc-seg button.is-on { background: var(--surface-raised); color: var(--text-primary); } +.fc-popover .fc-seg button:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } + +.fc-sgpop { display: grid; gap: 10px; width: 232px; padding: 10px 12px 12px; } +.fc-sgpop-head { display: flex; align-items: center; gap: 6px; color: var(--text-secondary); font-size: var(--fc-12); font-weight: 600; } +.fc-sgpop-summary { min-height: 17px; } +.fc-sgpop-num { display: grid; grid-template-columns: minmax(0, 1fr) auto 56px auto; align-items: center; gap: 4px; color: var(--text-secondary); font-size: var(--fc-12); } +.fc-sgpop-num[hidden] { display: none; } +.fc-sgpop-n { height: 26px; padding: 0 6px; text-align: center; font-family: var(--font-mono); } +.fc-sgpop-chips { display: flex; flex-wrap: wrap; gap: 4px; } +.fc-sgpop-chips[hidden] { display: none; } +.fc-sgpop-foot { display: flex; justify-content: flex-end; gap: 6px; } + +.fc-check-panel { top: calc(var(--fc-titlebar-h, 40px) + 16px); left: auto; right: 16px; display: grid; grid-template-rows: auto auto minmax(0, 1fr) auto; width: min(380px, calc(100vw - 32px)); max-height: min(60vh, 520px); } +.fc-check-head { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto; align-items: center; gap: 4px; height: 40px; padding: 0 6px 0 12px; border-bottom: 1px solid var(--line-1); } +.fc-check-title { overflow: hidden; color: var(--text-primary); font-size: var(--fc-13); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } +.fc-check-counts { display: inline-flex; gap: 8px; margin-right: 6px; font: var(--fc-12)/1 var(--font-mono); } +.fc-check-count { display: inline-flex; align-items: center; gap: 3px; min-width: 3.2ch; } +.fc-check-count.is-error { color: var(--danger-text); } +.fc-check-count.is-warning { color: var(--warn); } +.fc-check-count.is-info { color: var(--text-secondary); } +.fc-check-count.is-zero { color: var(--text-muted); opacity: 0.7; } +.fc-check-scope { padding: 8px 12px 0; } +.fc-check-scope[hidden] { display: none; } +.fc-check-items { min-height: 64px; padding: 6px; overflow-y: auto; overscroll-behavior: contain; transition: opacity var(--transition-fast); } +.fc-check-panel.is-stale:has(.fc-check-status.is-shown) .fc-check-items { opacity: 0.55; } +.fc-check-item { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 6px; border-radius: var(--radius-md); } +.fc-check-item.is-active { background: var(--accent-wash); } +.fc-check-item > .fc-btn[hidden] { display: none; } +.fc-check-main { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; align-items: start; column-gap: 8px; width: 100%; min-height: 32px; padding: 7px 8px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-secondary); font: var(--fc-12)/1.4 var(--font-ui); text-align: left; cursor: pointer; } +.fc-check-main:hover:not(:disabled) { background: var(--bg-hover); color: var(--text-primary); } +.fc-check-main:disabled { cursor: default; } +.fc-check-main:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } +.fc-check-icon { display: inline-grid; place-items: center; height: 17px; } +.fc-check-item.is-error .fc-check-icon { color: var(--danger-text); } +.fc-check-item.is-warning .fc-check-icon { color: var(--warn); } +.fc-check-item.is-info .fc-check-icon { color: var(--text-muted); } +.fc-check-msg { min-width: 0; overflow-wrap: anywhere; } +.fc-check-code { color: var(--text-muted); font: var(--fc-10)/1.7 var(--font-mono); } +.fc-check-status { min-height: 34px; padding: 8px 12px 10px; border-top: 1px solid var(--line-1); } +.fc-check-panel.is-stale .fc-check-status:not(.is-shown) { visibility: hidden; } + +.fc-apx { display: grid; gap: 4px; margin-top: var(--space-4); padding-top: var(--space-3); border-top: 1px solid var(--line-1); } +.fc-apx-head { display: flex; align-items: center; justify-content: space-between; min-height: 28px; } +.fc-apx-title { color: var(--text-secondary); font-size: var(--fc-11); font-weight: 600; letter-spacing: 0.4px; text-transform: uppercase; } +.fc-apx-rows { display: grid; margin: 0; } +.fc-apx-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; column-gap: var(--space-3); min-height: 28px; padding: 5px 0; border-bottom: 1px solid var(--line-0); } +.fc-apx-row:last-child { border-bottom: 0; } +.fc-apx-row dt { overflow: hidden; color: var(--text-secondary); font-size: var(--fc-12); text-overflow: ellipsis; white-space: nowrap; cursor: help; } +.fc-apx-val { min-width: min(var(--fc-apx-w, 8ch), 100%); max-width: 100%; margin: 0; overflow: hidden; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; text-overflow: ellipsis; white-space: nowrap; transition: opacity var(--transition-fast); user-select: text; -webkit-user-select: text; } +.fc-apx-row[data-row="elemental"], .fc-apx-row[data-row="lipinski"] { grid-template-columns: auto minmax(0, 1fr); } +.fc-apx-row.is-empty .fc-apx-val { color: var(--text-muted); } +.fc-apx-row.is-pass .fc-apx-val { color: var(--ok-soft); } +.fc-apx-row.is-fail .fc-apx-val { color: var(--warn); } +.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; } +.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; } + +.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; } + +.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/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; } 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; } diff --git a/frontend/src/ui/abbreviation-dialog.ts b/frontend/src/ui/abbreviation-dialog.ts new file mode 100644 index 00000000..24a82d92 --- /dev/null +++ b/frontend/src/ui/abbreviation-dialog.ts @@ -0,0 +1,139 @@ +import { analysisApi, type Abbreviation } from '../engine/analysis-api'; +import { t } from '../i18n'; +import { Dialog } from './dialogs'; +import { el, patchList, pendingClass, q, setClass, setDisabled, setHidden, setText } from './dom'; +import { icon } from './icons'; + +export interface AbbreviationRequest { + title: string; + okLabel: string; + initial?: string; + hint?: string; +} + +const LABEL = /^[A-Za-z][A-Za-z0-9()+-]{0,15}$/; +const ROWS = 9; + +export const validAbbreviation = (s: string): boolean => LABEL.test(s.trim()); + +class AbbreviationDialog extends Dialog { + private readonly name: HTMLInputElement; + private readonly hint: HTMLElement; + private readonly filter: HTMLInputElement; + private readonly list: HTMLElement; + private readonly empty: HTMLElement; + private readonly ok: HTMLButtonElement; + private all: Abbreviation[] = []; + private loaded = false; + private resolve: ((v: string | null) => void) | null = null; + + constructor() { + super(t('Abbreviation'), 460); + this.name = el(''); + this.field(t('Label'), this.name); + this.hint = el('

'); + this.body.appendChild(this.hint); + const lib = el(`
+ +
+ +
`); + this.filter = q(lib, 'input'); + this.filter.placeholder = t('Search the library'); + this.list = q(lib, '.fc-abbr-list'); + this.list.style.setProperty('--fc-abbr-rows', String(ROWS)); + for (let i = 0; i < ROWS; i++) this.list.appendChild(el(``)); + this.empty = q(lib, '.fc-abbr-empty'); + this.body.appendChild(lib); + this.list.addEventListener('click', (e) => { + const row = (e.target as HTMLElement).closest('.fc-abbr-row'); + if (!row?.dataset.key) return; + this.name.value = row.dataset.key; + this.sync(); + this.name.focus(); + }); + this.list.addEventListener('dblclick', (e) => { + const row = (e.target as HTMLElement).closest('.fc-abbr-row'); + if (row?.dataset.key) this.finish(row.dataset.key); + }); + this.filter.addEventListener('input', () => this.paint()); + this.name.addEventListener('input', () => this.sync()); + this.name.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); if (!this.ok.disabled) this.ok.click(); } }); + this.button(t('Cancel'), 'ghost', () => this.finish(null)); + this.ok = this.button(t('OK'), 'primary', () => this.finish(this.name.value.trim())); + this.onClose = () => this.finish(null); + } + + ask(req: AbbreviationRequest): Promise { + this.resolve?.(null); + this.setTitle(req.title); + setText(this.ok, req.okLabel); + setText(this.hint, req.hint ?? ''); + setHidden(this.hint, !req.hint); + this.name.value = req.initial ?? ''; + this.filter.value = ''; + this.sync(); + this.load(); + this.open(this.name); + this.name.select(); + return new Promise((r) => { this.resolve = r; }); + } + + private load(): void { + if (this.loaded) { this.paint(); return; } + const done = pendingClass(this.list, 200, 250); + analysisApi.abbreviations().then((list) => { + this.all = [...list].sort((a, b) => a.label.localeCompare(b.label)); + this.loaded = true; + }, () => { + setText(this.empty, t('The abbreviation library could not be loaded. You can still type a label.')); + }).finally(() => { done(); this.paint(); }); + } + + private paint(): void { + if (!this.loaded) { + setHidden(this.empty, !this.empty.textContent); + return; + } + const f = this.filter.value.trim().toLowerCase(); + const rows = f ? this.all.filter((a) => a.label.toLowerCase().includes(f) || a.category.toLowerCase().includes(f)) : this.all; + const chosen = this.name.value.trim(); + patchList(this.list, rows, { + key: (a) => a.label, + create: (a) => { + const row = el(`
`); + setText(q(row, '.fc-abbr-label'), a.label); + setText(q(row, '.fc-abbr-rev'), a.reversed !== a.label ? a.reversed : ''); + setText(q(row, '.fc-abbr-cat'), a.category); + if (a.smiles) row.title = a.smiles; + setClass(row, 'is-user', a.source === 'user'); + return row; + }, + update: (row, a) => { setClass(row, 'is-on', a.label === chosen); row.setAttribute('aria-selected', String(a.label === chosen)); }, + }); + setText(this.empty, t('No abbreviation matches. The label you type is used as it is.')); + setHidden(this.empty, rows.length > 0); + } + + private sync(): void { + const v = this.name.value.trim(); + const ok = validAbbreviation(v); + setDisabled(this.ok, !ok); + setClass(this.name, 'is-invalid', !!v && !ok); + if (this.loaded) this.paint(); + } + + private finish(v: string | null): void { + const r = this.resolve; + this.resolve = null; + if (this.isOpen) this.close(); + r?.(v); + } +} + +let dialog: AbbreviationDialog | null = null; + +export function askAbbreviation(req: AbbreviationRequest): Promise { + dialog ??= new AbbreviationDialog(); + return dialog.ask(req); +} diff --git a/frontend/src/ui/analysis-panel.ts b/frontend/src/ui/analysis-panel.ts index 4d388d65..0a1fea84 100644 --- a/frontend/src/ui/analysis-panel.ts +++ b/frontend/src/ui/analysis-panel.ts @@ -3,6 +3,7 @@ import { documentCounts, hillFormula } from '../chem/formula'; import type { DocEvent } from '../engine/client-api'; import { isFragment, type Derived, type DerivedFragment, type FormChemDocument, type Fragment, type Id } from '../engine/model'; import { t } from '../i18n'; +import { mountAnalysisProperties, type PropertiesSection } from './analysis-properties'; import { setStatusFormula } from './status'; import { mountOnce, q, setAttr, setClass, setHidden, setText } from './dom'; import { icon } from './icons'; @@ -22,6 +23,7 @@ const ROWS: Array<[AnalysisRow, string]> = [ const DASH = '–'; let panel: HTMLElement | null = null; +let props: PropertiesSection | null = null; let open = false; const listeners = new Set<(open: boolean) => void>(); @@ -48,10 +50,11 @@ export function mountAnalysisPanel(host: HTMLElement): void {
${t('Analysis')}

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

-
${rows}
+
`); 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(''); diff --git a/frontend/src/ui/analysis-properties.ts b/frontend/src/ui/analysis-properties.ts new file mode 100644 index 00000000..9d8d914a --- /dev/null +++ b/frontend/src/ui/analysis-properties.ts @@ -0,0 +1,147 @@ +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 = '–'; +const DEBOUNCE_MS = 120; + +export interface PropertiesSection { + readonly root: HTMLElement; + update(doc: FormChemDocument | null, fragments: readonly Fragment[]): void; + current(): Properties | null; + copyText(methods?: boolean): string; + destroy(): void; +} + +function merged(doc: FormChemDocument, frags: readonly Fragment[]): Source { + const fragment: Fragment = frags.length === 1 ? frags[0] : { id: 'f~analysis', kind: 'fragment', atoms: {}, bonds: {} }; + if (frags.length > 1) for (const f of frags) { Object.assign(fragment.atoms, f.atoms); Object.assign(fragment.bonds, f.bonds); } + const src: Source = { fragment }; + if (doc.expansions && Object.keys(doc.expansions).length) src.expansions = doc.expansions; + return src; +} + +const sameRefs = (a: readonly unknown[], b: readonly unknown[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); + +export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { + const rows = PROPERTY_ROWS.map((d) => `
${DASH}
`).join(''); + const root = el(`
+
${copyButtonHtml()}
+
${rows}
+ +
`); + setText(q(root, '.fc-apx-title'), t('Properties')); + const note = q(root, '.fc-apx-note'); + const copyBtn = q(root, '[data-copy]'); + const cells = new Map(); + for (const def of PROPERTY_ROWS) { + const row = q(root, `.fc-apx-row[data-row="${def.key}"]`); + const dt = q(row, 'dt'), dd = q(row, 'dd'); + setText(dt, t(def.label)); + 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; + let pending: (() => void) | null = null; + let ticket = 0; + + const paint = (): void => { + for (const { row, dt, dd, def } of cells.values()) { + const v = props ? rowValue(def, props) : ''; + setText(dd, v || DASH); + const method = `${t('Method')}: ${rowMethod(def, props)}`; + setTitle(dt, method); + setTitle(dd, v ? `${v}\n${method}` : method); + setClass(row, 'is-empty', !v); + if (def.key === 'lipinski') { + const l = props ? lipinskiRules(props) : null; + setClass(row, 'is-pass', !!l && l.violations === 0); + 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); + setClass(note, 'is-error', false); + setHidden(note, !warn); + }; + + const settle = (): void => { + pending?.(); + pending = null; + root.setAttribute('aria-busy', 'false'); + }; + + const fetchNow = (src: Source): void => { + ctrl?.abort(); + const c = new AbortController(); + ctrl = c; + const mine = ++ticket; + pending ??= pendingClass(root, 200, 250); + root.setAttribute('aria-busy', 'true'); + 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) => { + if (mine !== ticket || c.signal.aborted) return; + settle(); + setText(note, `${t('Properties could not be computed')}: ${e instanceof Error ? e.message : String(e)}`); + setClass(note, 'is-error', true); + setHidden(note, false); + }); + }; + + paint(); + copyBtn.addEventListener('click', () => { + if (!props) return; + void copyText(formatAnalysisText(props, { methods: false, isotopes: pattern })).then((ok) => flashCopied(copyBtn, ok, () => toast(t('Could not copy to the clipboard'), 'error'))); + }); + + return { + root, + update(doc, fragments) { + const frags = fragments.filter((f) => Object.keys(f.atoms).length > 0); + const next = [doc?.expansions, ...frags]; + if (doc && frags.length && sameRefs(next, inputs)) return; + inputs = next; + window.clearTimeout(timer); + if (!doc || !frags.length) { + ticket++; + ctrl?.abort(); + settle(); + props = null; + pattern = null; + paint(); + return; + } + const src = merged(doc, frags); + timer = window.setTimeout(() => fetchNow(src), DEBOUNCE_MS); + }, + current: () => props, + copyText: (methods = false) => (props ? formatAnalysisText(props, { methods, isotopes: pattern }) : ''), + destroy() { + window.clearTimeout(timer); + ctrl?.abort(); + settle(); + root.remove(); + }, + }; +} diff --git a/frontend/src/ui/atom-list-dialog.ts b/frontend/src/ui/atom-list-dialog.ts new file mode 100644 index 00000000..42389fd7 --- /dev/null +++ b/frontend/src/ui/atom-list-dialog.ts @@ -0,0 +1,98 @@ +import { t } from '../i18n'; +import { Dialog, segOn, segSet } from './dialogs'; +import { el, patchList, q, setClass, setDisabled, setHidden, setText } from './dom'; +import { icon } from './icons'; +import { createPeriodicGrid, type PeriodicGrid } from './periodic-grid'; + +export interface AtomListValue { list: string[]; not: boolean } + +class AtomListDialog extends Dialog { + private readonly grid: PeriodicGrid; + private readonly seg: HTMLElement; + private readonly chips: HTMLElement; + private readonly empty: HTMLElement; + private readonly preview: HTMLElement; + private readonly apply: HTMLButtonElement; + private list: string[] = []; + private not = false; + private resolve: ((v: AtomListValue | null) => void) | null = null; + + constructor() { + super(t('Atom List'), 640); + this.frame.classList.add('fc-atomlist'); + const head = el(`
+
+ +
`); + this.seg = q(head, '.fc-seg'); + this.preview = q(head, '.fc-atomlist-preview'); + segOn(this.seg, (v) => { this.not = v === 'not'; this.sync(); }); + this.body.appendChild(head); + this.grid = createPeriodicGrid((s) => this.toggle(s)); + this.body.appendChild(this.grid.root); + const row = el(`
${t('Chosen')}
`); + this.chips = q(row, '.fc-atomlist-chips'); + this.empty = q(row, '.fc-atomlist-empty'); + setText(this.empty, t('Click elements in the table to add them.')); + this.chips.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-el]'); + if (b?.dataset.el) this.toggle(b.dataset.el); + }); + this.body.appendChild(row); + this.button(t('Clear Query'), 'ghost', () => this.finish({ list: [], not: false })).classList.add('fc-btn-apart'); + this.button(t('Cancel'), 'ghost', () => this.finish(null)); + this.apply = this.button(t('Apply'), 'primary', () => this.finish({ list: [...this.list], not: this.not })); + this.onClose = () => this.finish(null); + } + + ask(initial: AtomListValue): Promise { + this.resolve?.(null); + this.list = [...initial.list]; + this.not = initial.not; + this.sync(); + this.open(this.apply); + if (this.list[0]) this.grid.focusSymbol(this.list[0]); + return new Promise((r) => { this.resolve = r; }); + } + + private toggle(symbol: string): void { + const at = this.list.indexOf(symbol); + if (at >= 0) this.list.splice(at, 1); + else this.list.push(symbol); + this.sync(); + } + + private sync(): void { + segSet(this.seg, this.not ? 'not' : 'in'); + this.grid.set(this.list); + patchList(this.chips, this.list, { + key: (s) => s, + create: (s) => { + const b = el(``); + setText(b.firstElementChild, s); + b.title = t('Remove'); + return b; + }, + update: () => undefined, + }); + setHidden(this.empty, this.list.length > 0); + const text = this.list.length ? `${this.not ? 'not ' : ''}[${this.list.join(',')}]` : ''; + setText(this.preview, text || t('No query')); + setClass(this.preview, 'is-empty', !text); + setDisabled(this.apply, this.list.length === 0); + } + + private finish(v: AtomListValue | null): void { + const r = this.resolve; + this.resolve = null; + if (this.isOpen) this.close(); + r?.(v); + } +} + +let dialog: AtomListDialog | null = null; + +export function askAtomList(initial: AtomListValue = { list: [], not: false }): Promise { + dialog ??= new AtomListDialog(); + return dialog.ask(initial); +} 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); }; + }, + }; +} 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(); }, + }; +} 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; diff --git a/frontend/src/ui/icons.ts b/frontend/src/ui/icons.ts index 3af6d9a4..f5975859 100644 --- a/frontend/src/ui/icons.ts +++ b/frontend/src/ui/icons.ts @@ -277,6 +277,42 @@ 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(``), + stereoCentre: L(``), + stereoGroup: L(''), + hydrogenAdd: L(''), + hydrogenRemove: L(''), + expandAbbr: L(''), + contractAbbr: L(''), + atomList: L(''), + queryBond: L(''), + rgroup: L(''), + assignWedges: L(``), + substructure: L(''), + periodicTable: L(''), }; export function icon(name: string, size = 16): string { 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); + }); + }, + }; +} 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(); +} diff --git a/frontend/src/ui/periodic-grid.ts b/frontend/src/ui/periodic-grid.ts new file mode 100644 index 00000000..1ce25dc0 --- /dev/null +++ b/frontend/src/ui/periodic-grid.ts @@ -0,0 +1,69 @@ +import { elementInfo } from '../chem/elements'; +import { ELEMENTS } from '../engine/model'; +import { el, setAttr, setClass } from './dom'; + +export interface PeriodicGrid { + readonly root: HTMLElement; + set(selected: Iterable): void; + focusSymbol(symbol: string): void; +} + +const ORGANIC = new Set(['H', 'B', 'C', 'N', 'O', 'F', 'Si', 'P', 'S', 'Cl', 'Se', 'Br', 'I']); +const F_START = { 6: 57, 7: 89 } as const; + +function cell(symbol: string): { row: number; col: number } | null { + const info = elementInfo(symbol); + if (!info) return null; + if (info.group !== null) return { row: info.period, col: info.group }; + const start = F_START[info.period as 6 | 7]; + return start ? { row: info.period + 3, col: 3 + info.z - start } : null; +} + +export function createPeriodicGrid(onPick: (symbol: string, e: MouseEvent | KeyboardEvent) => void): PeriodicGrid { + const root = el('
'); + const buttons = new Map(); + for (const symbol of ELEMENTS) { + const at = cell(symbol); + if (!at) continue; + const info = elementInfo(symbol)!; + const b = el(``); + b.textContent = symbol; + b.title = `${symbol} (${info.z})`; + b.style.gridRow = String(at.row); + b.style.gridColumn = String(at.col); + buttons.set(symbol, b); + root.appendChild(b); + } + root.appendChild(el('')); + root.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('button[data-el]'); + if (b?.dataset.el) onPick(b.dataset.el, e); + }); + root.addEventListener('keydown', (e) => { + const b = (e.target as HTMLElement).closest('button[data-el]'); + if (!b?.dataset.el) return; + const at = cell(b.dataset.el); + if (!at) return; + const step: Record = { ArrowLeft: [0, -1], ArrowRight: [0, 1], ArrowUp: [-1, 0], ArrowDown: [1, 0] }; + const d = step[e.key]; + if (!d) return; + e.preventDefault(); + for (let k = 1; k < 18; k++) { + const row = at.row + d[0] * k, col = at.col + d[1] * k; + const hit = [...buttons.entries()].find(([s]) => { const c = cell(s); return c?.row === row && c.col === col; }); + if (hit) { hit[1].focus(); return; } + if (row < 1 || row > 10 || col < 1 || col > 18) return; + } + }); + return { + root, + set(selected) { + const on = new Set(selected); + for (const [s, b] of buttons) { + setClass(b, 'is-on', on.has(s)); + setAttr(b, 'aria-pressed', String(on.has(s))); + } + }, + focusSymbol(symbol) { buttons.get(symbol)?.focus(); }, + }; +} diff --git a/frontend/src/ui/query-menus.ts b/frontend/src/ui/query-menus.ts new file mode 100644 index 00000000..aad3847f --- /dev/null +++ b/frontend/src/ui/query-menus.ts @@ -0,0 +1,156 @@ +import { atomQueryOps, bondQueryOps, bondTopologyOps, clearStereoGroupOps, groupOf, nextGroupNumber, stereoGroupOps, type GroupKind } from '../app/chem-edits'; +import type { CommandDef } from '../commands/registry'; +import type { AtomQuery, BondQuery, BondTopology, Fragment, Id, QueryGeneric } from '../engine/model'; +import type { Op } from '../engine/ops'; +import { t } from '../i18n'; +import type { SubMenu } from './menu'; + +export type TempCommand = Omit & { id: string }; +export type Commit = (label: string, ops: Op[]) => void; + +export interface BondTarget { frag: Fragment; bonds: Id[] } +export interface AtomTarget { frag: Fragment; atoms: Id[] } + +export const BOND_QUERY_LABELS: ReadonlyArray<[BondQuery, string]> = [ + ['any', 'Any Bond'], + ['single_or_double', 'Single or Double'], + ['single_or_aromatic', 'Single or Aromatic'], + ['double_or_aromatic', 'Double or Aromatic'], +]; + +export const TOPOLOGY_LABELS: ReadonlyArray<[BondTopology | null, string]> = [ + [null, 'Ring or Chain'], + ['ring', 'In a Ring'], + ['chain', 'In a Chain'], +]; + +export const GENERIC_LABELS: ReadonlyArray<[QueryGeneric, string]> = [ + ['A', 'Any Atom (A)'], + ['Q', 'Any Heteroatom (Q)'], + ['X', 'Any Halogen (X)'], + ['M', 'Any Metal (M)'], +]; + +const every = (ids: readonly Id[], get: (id: Id) => T | undefined, test: (v: T) => boolean): boolean => ids.length > 0 && ids.every((id) => { const v = get(id); return v !== undefined && test(v); }); + +export function queryBondSubmenu(prefix: string, look: () => BondTarget | null, commit: Commit, temp: TempCommand[]): SubMenu { + const items: string[] = []; + const allBonds = (test: (b: Fragment['bonds'][string]) => boolean): boolean => { + const l = look(); + return !!l && every(l.bonds, (id) => l.frag.bonds[id], test); + }; + for (const [q, name] of BOND_QUERY_LABELS) { + const id = `${prefix}qbond-${q}`; + temp.push({ + id, label: () => t(name), mutates: true, + checked: () => allBonds((b) => b.query === q), + run: () => { const l = look(); if (l) commit(t('Set Query Bond'), bondQueryOps(l.frag, l.bonds, allBonds((b) => b.query === q) ? null : q)); }, + }); + items.push(id); + } + items.push('-'); + for (const [topo, name] of TOPOLOGY_LABELS) { + const id = `${prefix}qtopo-${topo ?? 'either'}`; + temp.push({ + id, label: () => t(name), mutates: true, + checked: () => allBonds((b) => (b.topology ?? null) === topo), + run: () => { const l = look(); if (l) commit(t('Set Bond Topology'), bondTopologyOps(l.frag, l.bonds, topo)); }, + }); + items.push(id); + } + items.push('-'); + const clear = `${prefix}qbond-clear`; + temp.push({ + id: clear, label: () => t('Clear Bond Query'), mutates: true, + enabled: () => { const l = look(); return !!l && l.bonds.some((b) => l.frag.bonds[b]?.query || l.frag.bonds[b]?.topology); }, + run: () => { const l = look(); if (l) commit(t('Clear Bond Query'), [...bondQueryOps(l.frag, l.bonds, null), ...bondTopologyOps(l.frag, l.bonds, null)]); }, + }); + items.push(clear); + return { label: 'Query Bond', items }; +} + +export function atomQuerySubmenu(prefix: string, look: () => AtomTarget | null, commit: Commit, temp: TempCommand[], openList: () => void): SubMenu { + const items: string[] = []; + const allAtoms = (test: (q: AtomQuery) => boolean): boolean => { + const l = look(); + return !!l && every(l.atoms, (id) => l.frag.atoms[id]?.query ?? {}, test); + }; + const list = `${prefix}qatom-list`; + temp.push({ id: list, label: () => t('Atom List...'), icon: 'atomList', mutates: true, run: openList }); + items.push(list, '-'); + for (const [g, name] of GENERIC_LABELS) { + const id = `${prefix}qatom-generic-${g}`; + temp.push({ + id, label: () => t(name), mutates: true, + checked: () => allAtoms((q) => q.generic === g), + run: () => { const l = look(); if (l) commit(t('Set Atom Query'), atomQueryOps(l.frag, l.atoms, allAtoms((q) => q.generic === g) ? { generic: undefined } : { generic: g, list: undefined, not: undefined })); }, + }); + items.push(id); + } + items.push('-'); + const flags: Array<[string, string, (q: AtomQuery) => boolean, (on: boolean) => Partial]> = [ + ['aromatic', 'Aromatic', (q) => q.aromatic === true, (on) => ({ aromatic: on ? true : undefined })], + ['aliphatic', 'Aliphatic', (q) => q.aromatic === false, (on) => ({ aromatic: on ? false : undefined })], + ['unsat', 'Unsaturated', (q) => !!q.unsat, (on) => ({ unsat: on || undefined })], + ['subst', 'Substitution as Drawn', (q) => q.subst === -2, (on) => ({ subst: on ? -2 : undefined })], + ['ring', 'Ring Bonds as Drawn', (q) => q.ring_bonds === -2, (on) => ({ ring_bonds: on ? -2 : undefined })], + ]; + for (const [key, name, test, patch] of flags) { + const id = `${prefix}qatom-${key}`; + temp.push({ + id, label: () => t(name), mutates: true, + checked: () => allAtoms(test), + run: () => { const l = look(); if (l) commit(t('Set Atom Query'), atomQueryOps(l.frag, l.atoms, patch(!allAtoms(test)))); }, + }); + items.push(id); + } + items.push('-'); + const clear = `${prefix}qatom-clear`; + temp.push({ + id: clear, label: () => t('Clear Atom Query'), mutates: true, + enabled: () => { const l = look(); return !!l && l.atoms.some((a) => !!l.frag.atoms[a]?.query); }, + run: () => { const l = look(); if (l) commit(t('Clear Atom Query'), atomQueryOps(l.frag, l.atoms, null)); }, + }); + items.push(clear); + return { label: 'Atom Query', items }; +} + +export function stereoGroupSubmenu(prefix: string, look: () => AtomTarget | null, commit: Commit, temp: TempCommand[], openPopover?: () => void): SubMenu { + const items: string[] = []; + const current = (): string | null => { + const l = look(); + if (!l || !l.atoms.length) return null; + const keys = new Set(l.atoms.map((a) => { const g = groupOf(l.frag, a); return g ? `${g.kind}${g.kind === 'abs' ? '' : g.n ?? 1}` : ''; })); + return keys.size === 1 ? [...keys][0] : null; + }; + const add = (id: string, label: () => string, kind: GroupKind, n: (f: Fragment) => number | undefined, key: (f: Fragment) => string): void => { + temp.push({ + id, label, mutates: true, + checked: () => { const l = look(); return !!l && current() === key(l.frag); }, + run: () => { const l = look(); if (l) commit(t('Set Stereo Group'), stereoGroupOps(l.frag, l.atoms, kind, n(l.frag))); }, + }); + items.push(id); + }; + add(`${prefix}sg-abs`, () => t('Absolute (abs)'), 'abs', () => undefined, () => 'abs'); + const existing = (): Array<{ kind: GroupKind; n: number }> => { + const l = look(); + return (l?.frag.stereo_groups ?? []).filter((g) => g.kind !== 'abs').map((g) => ({ kind: g.kind, n: g.n ?? 1 })); + }; + for (const g of existing()) add(`${prefix}sg-${g.kind}${g.n}`, () => `${g.kind === 'and' ? t('AND group') : t('OR group')} ${g.n} (${g.kind}${g.n})`, g.kind, () => g.n, () => `${g.kind}${g.n}`); + add(`${prefix}sg-and-new`, () => t('New AND Group'), 'and', (f) => nextGroupNumber(f, 'and'), () => ''); + add(`${prefix}sg-or-new`, () => t('New OR Group'), 'or', (f) => nextGroupNumber(f, 'or'), () => ''); + items.push('-'); + const clear = `${prefix}sg-clear`; + temp.push({ + id: clear, label: () => t('Clear Stereo Group'), mutates: true, + enabled: () => { const l = look(); return !!l && l.atoms.some((a) => l.frag.stereo_groups?.some((g) => g.atoms?.includes(a))); }, + run: () => { const l = look(); if (l) commit(t('Clear Stereo Group'), clearStereoGroupOps(l.frag, l.atoms)); }, + }); + items.push(clear); + if (openPopover) { + const more = `${prefix}sg-more`; + temp.push({ id: more, label: () => t('Stereo Group...'), icon: 'stereoGroup', run: openPopover }); + items.push('-', more); + } + return { label: 'Enhanced Stereo', items }; +} diff --git a/frontend/src/ui/rgroup-dialog.ts b/frontend/src/ui/rgroup-dialog.ts new file mode 100644 index 00000000..1bfac217 --- /dev/null +++ b/frontend/src/ui/rgroup-dialog.ts @@ -0,0 +1,138 @@ +import type { Id, RGroupDef } from '../engine/model'; +import { t } from '../i18n'; +import { Dialog } from './dialogs'; +import { el, patchList, q, setChecked, setClass, setDisabled, setHidden, setText } from './dom'; + +export interface RGroupCandidate { id: Id; label: string; detail?: string } + +export interface RGroupRequest { + n: number; + def: RGroupDef | null; + candidates: RGroupCandidate[]; + others: number[]; +} + +export interface RGroupAnswer { n: number; def: RGroupDef | null } + +const OCCURRENCE = /^\s*(?:\d+|[<>]\d+|\d+\s*-\s*\d+)(?:\s*,\s*(?:\d+|[<>]\d+|\d+\s*-\s*\d+))*\s*$/; +const MAX_R = 32; + +export const validOccurrence = (s: string): boolean => !s.trim() || OCCURRENCE.test(s); + +class RGroupDialog extends Dialog { + private readonly num: HTMLSelectElement; + private readonly members: HTMLElement; + private readonly none: HTMLElement; + private readonly occ: HTMLInputElement; + private readonly occNote: HTMLElement; + private readonly restH: HTMLInputElement; + private readonly ifThen: HTMLSelectElement; + private readonly save: HTMLButtonElement; + private readonly remove: HTMLButtonElement; + private chosen = new Set(); + private resolve: ((v: RGroupAnswer | null) => void) | null = null; + + constructor() { + super(t('R-Group Definition'), 480); + this.num = el(''); + for (let i = 1; i <= MAX_R; i++) this.num.appendChild(el(``)); + this.field(t('R-group'), this.num); + + const box = el(`

`); + setText(box.firstElementChild, t('Members')); + this.members = q(box, '.fc-rgroup-members'); + this.none = q(box, '.fc-rgroup-none'); + setText(this.none, t('Draw each member as its own structure with an attachment point (*), then open this dialog again.')); + this.members.addEventListener('change', (e) => { + const cb = e.target as HTMLInputElement; + const id = cb.closest('[data-key]')?.dataset.key; + if (!id) return; + if (cb.checked) this.chosen.add(id); + else this.chosen.delete(id); + this.validate(); + }); + this.body.appendChild(box); + + this.occ = el(''); + this.field(t('Occurrence'), this.occ); + this.occNote = el('

'); + this.body.appendChild(this.occNote); + this.occ.addEventListener('input', () => this.validate()); + + this.restH = el(''); + const rest = el(``); + rest.appendChild(this.restH); + rest.appendChild(document.createTextNode(t('Rest H (unsubstituted positions are hydrogen)'))); + this.body.appendChild(rest); + + this.ifThen = el(''); + this.field(t('If present, then'), this.ifThen); + + this.remove = this.button(t('Remove Definition'), 'ghost', () => this.finish({ n: Number(this.num.value), def: null })); + this.remove.classList.add('fc-btn-apart'); + this.button(t('Cancel'), 'ghost', () => this.finish(null)); + this.save = this.button(t('Save'), 'primary', () => this.finish({ n: Number(this.num.value), def: this.value() })); + this.onClose = () => this.finish(null); + } + + ask(req: RGroupRequest): Promise { + this.resolve?.(null); + this.num.value = String(req.n); + this.chosen = new Set((req.def?.members ?? []).filter((m) => req.candidates.some((c) => c.id === m))); + patchList(this.members, req.candidates, { + key: (c) => c.id, + create: (c) => { + const row = el(``); + this.paintMember(row, c); + return row; + }, + update: (row, c) => this.paintMember(row, c), + }); + setHidden(this.none, req.candidates.length > 0); + this.occ.value = req.def?.occurrence ?? ''; + setChecked(this.restH, !!req.def?.rest_h); + const opts = [``, ...req.others.filter((o) => o !== req.n).map((o) => ``)]; + this.ifThen.innerHTML = opts.join(''); + this.ifThen.value = req.def?.if_then ? String(req.def.if_then) : ''; + setHidden(this.remove, !req.def); + this.validate(); + this.open(req.candidates.length ? this.members.querySelector('input') : this.save); + return new Promise((r) => { this.resolve = r; }); + } + + private paintMember(row: HTMLElement, c: RGroupCandidate): void { + setChecked(q(row, 'input'), this.chosen.has(c.id)); + setText(q(row, '.fc-rgroup-member-label'), c.label); + setText(q(row, '.fc-rgroup-member-detail'), c.detail ?? ''); + } + + private value(): RGroupDef { + const def: RGroupDef = { members: [...this.chosen] }; + const occ = this.occ.value.trim(); + if (occ && occ !== '>0') def.occurrence = occ; + if (this.restH.checked) def.rest_h = true; + if (this.ifThen.value) def.if_then = Number(this.ifThen.value); + return def; + } + + private validate(): void { + const ok = validOccurrence(this.occ.value); + setText(this.occNote, ok ? t('A count, range or bound: 1, 1-3, >0. Several may be joined with commas.') : t('Use a count, a range such as 1-3, or a bound such as >0.')); + setClass(this.occNote, 'is-error', !ok); + setDisabled(this.save, !ok || this.chosen.size === 0); + } + + private finish(v: RGroupAnswer | null): void { + const r = this.resolve; + this.resolve = null; + if (this.isOpen) this.close(); + r?.(v); + } +} + +let dialog: RGroupDialog | null = null; + +export function askRGroup(req: RGroupRequest): Promise { + dialog ??= new RGroupDialog(); + return dialog.ask(req); +} 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); + }); +} diff --git a/frontend/src/ui/stereo-popover.ts b/frontend/src/ui/stereo-popover.ts new file mode 100644 index 00000000..9ff8fba8 --- /dev/null +++ b/frontend/src/ui/stereo-popover.ts @@ -0,0 +1,152 @@ +import { clearStereoGroupOps, groupOf, nextGroupNumber, stereoGroupOps, type GroupKind } from '../app/chem-edits'; +import { t } from '../i18n'; +import { segOn, segSet } from './dialogs'; +import { el, overlayRoot, patchList, q, setDisabled, setHidden, setText } from './dom'; +import { icon } from './icons'; +import type { AtomTarget, Commit } from './query-menus'; + +export interface StereoPopoverHost { + target(): AtomTarget | null; + commit: Commit; +} + +const MARGIN = 8; + +class StereoPopover { + readonly root: HTMLElement; + private readonly seg: HTMLElement; + private readonly numRow: HTMLElement; + private readonly num: HTMLInputElement; + private readonly chips: HTMLElement; + private readonly summary: HTMLElement; + private readonly clear: HTMLButtonElement; + private readonly apply: HTMLButtonElement; + private host: StereoPopoverHost | null = null; + private kind: GroupKind = 'abs'; + private back: HTMLElement | null = null; + + constructor() { + this.root = el(``); + setText(q(this.root, '.fc-sgpop-title'), t('Enhanced Stereo')); + setText(q(this.root, '.fc-sgpop-num-label'), t('Group')); + this.seg = q(this.root, '.fc-sgpop-seg'); + this.numRow = q(this.root, '.fc-sgpop-num'); + this.num = q(this.root, '.fc-sgpop-n'); + this.chips = q(this.root, '.fc-sgpop-chips'); + this.summary = q(this.root, '.fc-sgpop-summary'); + this.clear = q(this.root, '[data-act="clear"]'); + this.apply = q(this.root, '[data-act="apply"]'); + setText(this.clear, t('Clear')); + setText(this.apply, t('Apply')); + segOn(this.seg, (v) => { + this.kind = v as GroupKind; + const l = this.host?.target(); + if (l && this.kind !== 'abs') this.num.value = String(nextGroupNumber(l.frag, this.kind)); + this.paint(); + }); + this.numRow.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('[data-step]'); + if (!b) return; + this.num.value = String(Math.max(1, Math.min(99, (Number(this.num.value) || 1) + Number(b.dataset.step)))); + }); + this.chips.addEventListener('click', (e) => { + const b = (e.target as HTMLElement).closest('[data-key]'); + const m = b?.dataset.key?.match(/^(and|or)(\d+)$/); + if (m) this.commit(m[1] as GroupKind, Number(m[2])); + }); + this.clear.addEventListener('click', () => { + const l = this.host?.target(); + if (l) this.host!.commit(t('Clear Stereo Group'), clearStereoGroupOps(l.frag, l.atoms)); + this.paint(); + }); + this.apply.addEventListener('click', () => this.commit(this.kind, this.kind === 'abs' ? undefined : Math.max(1, Number(this.num.value) || 1))); + this.num.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); this.apply.click(); } }); + this.root.addEventListener('keydown', (e) => { + e.stopPropagation(); + if (e.key === 'Escape') { e.preventDefault(); this.close(); } + }); + document.addEventListener('pointerdown', (e) => { if (!this.root.hidden && !this.root.contains(e.target as Node)) this.close(); }, true); + window.addEventListener('blur', () => this.close()); + overlayRoot().appendChild(this.root); + } + + open(x: number, y: number, host: StereoPopoverHost): void { + this.host = host; + const l = host.target(); + const g = l && l.atoms.length ? groupOf(l.frag, l.atoms[0]) : null; + this.kind = g?.kind ?? 'abs'; + this.num.value = String(g && g.kind !== 'abs' ? g.n ?? 1 : l ? nextGroupNumber(l.frag, 'and') : 1); + this.paint(); + if (this.root.hidden) this.back = document.activeElement instanceof HTMLElement ? document.activeElement : null; + this.root.style.visibility = 'hidden'; + setHidden(this.root, false); + const r = this.root.getBoundingClientRect(); + const left = Math.max(MARGIN, Math.min(x, window.innerWidth - r.width - MARGIN)); + const top = y + r.height + MARGIN > window.innerHeight ? Math.max(MARGIN, y - r.height) : y; + this.root.style.left = `${Math.round(left)}px`; + this.root.style.top = `${Math.round(top)}px`; + this.root.style.visibility = ''; + this.apply.focus({ preventScroll: true }); + } + + close(): void { + if (this.root.hidden) return; + setHidden(this.root, true); + this.host = null; + if (this.root.contains(document.activeElement) && this.back?.isConnected) this.back.focus(); + this.back = null; + } + + get isOpen(): boolean { return !this.root.hidden; } + + private commit(kind: GroupKind, n?: number): void { + const l = this.host?.target(); + if (!l) return; + this.host!.commit(t('Set Stereo Group'), stereoGroupOps(l.frag, l.atoms, kind, n)); + this.kind = kind; + if (n) this.num.value = String(n); + this.paint(); + } + + private paint(): void { + segSet(this.seg, this.kind); + setHidden(this.numRow, this.kind === 'abs'); + const l = this.host?.target() ?? null; + const count = l?.atoms.length ?? 0; + const g = l && count ? groupOf(l.frag, l.atoms[0]) : null; + const now = g ? (g.kind === 'abs' ? 'abs' : `${g.kind}${g.n ?? 1}`) : t('none'); + setText(this.summary, count === 1 ? `${t('Centre group')}: ${now}` : `${count} ${t('centres')}`); + const groups = (l?.frag.stereo_groups ?? []).filter((x) => x.kind !== 'abs').map((x) => `${x.kind}${x.n ?? 1}`); + patchList(this.chips, groups, { + key: (k) => k, + create: (k) => { + const b = el(``); + setText(b, k); + b.title = t('Add the selected centres to this group'); + return b; + }, + update: () => undefined, + }); + setHidden(this.chips, !groups.length); + setDisabled(this.apply, !count); + setDisabled(this.clear, !l || !l.atoms.some((a) => l.frag.stereo_groups?.some((x) => x.atoms?.includes(a)))); + } +} + +let popover: StereoPopover | null = null; + +export function openStereoPopover(x: number, y: number, host: StereoPopoverHost): void { + popover ??= new StereoPopover(); + popover.open(x, y, host); +} + +export function closeStereoPopover(): void { popover?.close(); } + +export const stereoPopoverOpen = (): boolean => !!popover?.isOpen; diff --git a/frontend/src/ui/stoich-panel.ts b/frontend/src/ui/stoich-panel.ts new file mode 100644 index 00000000..3414c084 --- /dev/null +++ b/frontend/src/ui/stoich-panel.ts @@ -0,0 +1,433 @@ +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, 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'; +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'; + +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 => `
`; + +function markup(): string { + return `
+
+${escapeHtml(t('Stoichiometry'))} + + + + +
+
+

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

+
+

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.

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.

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.
${escapeHtml(t(c.label))}${c.unit ? ` ${escapeHtml(c.unit)}` : ''}
+${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); + 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"]'); + 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; + } + 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 { + 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]'); + 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 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, { + 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/documents/${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); +} diff --git a/frontend/src/ui/structure-check.ts b/frontend/src/ui/structure-check.ts new file mode 100644 index 00000000..86f0b294 --- /dev/null +++ b/frontend/src/ui/structure-check.ts @@ -0,0 +1,182 @@ +import type { Severity } from '../engine/analysis-api'; +import type { Id } from '../engine/model'; +import { t } from '../i18n'; +import { el, overlayRoot, patchList, pendingClass, q, setClass, setDisabled, setHidden, setText, setTitle } from './dom'; +import { icon } from './icons'; + +export interface CheckRow { + key: string; + frag: Id; + severity: Severity; + code: string; + text: string; + atoms: Id[]; + bonds: Id[]; + fixable: boolean; +} + +export interface CheckPanelHost { + run(): Promise; + select(row: CheckRow): void; + fix?(row: CheckRow): Promise | void; + scopeLabel?(): string; +} + +const ORDER: Record = { error: 0, warning: 1, info: 2 }; +const ICONS: Record = { error: 'error', warning: 'warning', info: 'info' }; + +class CheckPanel { + readonly root: HTMLElement; + private readonly list: HTMLElement; + private readonly status: HTMLElement; + private readonly scope: HTMLElement; + private readonly refresh: HTMLButtonElement; + private readonly counts: Record; + private host: CheckPanelHost | null = null; + private rows: CheckRow[] = []; + private ticket = 0; + private active: string | null = null; + + constructor() { + this.root = el(``); + setText(q(this.root, '.fc-check-title'), t('Check Structure')); + this.root.setAttribute('aria-label', t('Check Structure')); + this.list = q(this.root, '.fc-check-items'); + this.status = q(this.root, '.fc-check-status'); + this.scope = q(this.root, '.fc-check-scope'); + this.refresh = q(this.root, '[data-act="refresh"]'); + const close = q(this.root, '[data-act="close"]'); + setTitle(this.refresh, t('Check Again')); + this.refresh.setAttribute('aria-label', t('Check Again')); + setTitle(close, t('Close')); + close.setAttribute('aria-label', t('Close')); + this.counts = { + error: q(this.root, '.fc-check-count.is-error b'), + warning: q(this.root, '.fc-check-count.is-warning b'), + info: q(this.root, '.fc-check-count.is-info b'), + }; + this.refresh.addEventListener('click', () => void this.run()); + close.addEventListener('click', () => this.close()); + this.list.addEventListener('click', (e) => { + const target = e.target as HTMLElement; + const item = target.closest('.fc-check-item'); + const row = this.rows.find((r) => r.key === item?.dataset.key); + if (!row || !this.host) return; + if (target.closest('[data-act="fix"]')) { + void Promise.resolve(this.host.fix?.(row)).then(() => this.run()); + return; + } + this.active = row.key; + this.host.select(row); + this.paintActive(); + }); + this.root.addEventListener('keydown', (e) => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopPropagation(); + this.close(); + }); + overlayRoot().appendChild(this.root); + } + + get isOpen(): boolean { return !this.root.hidden; } + + show(host: CheckPanelHost): void { + this.host = host; + setHidden(this.root, false); + void this.run(); + } + + close(): void { + setHidden(this.root, true); + this.host = null; + this.ticket++; + } + + async run(): Promise { + const host = this.host; + if (!host) return; + const ticket = ++this.ticket; + setText(this.scope, host.scopeLabel?.() ?? ''); + setHidden(this.scope, !this.scope.textContent); + setDisabled(this.refresh, true); + setClass(this.root, 'is-stale', true); + const done = pendingClass(this.status, 200, 250); + setText(this.status, t('Checking...')); + let rows: CheckRow[] | null = null; + let failed = ''; + try { + rows = await host.run(); + } catch (e) { + failed = e instanceof Error ? e.message : String(e); + } + done(); + if (ticket !== this.ticket) return; + setDisabled(this.refresh, false); + setClass(this.root, 'is-stale', false); + if (rows) this.setRows(rows); + setText(this.status, failed ? `${t('The check could not run')}: ${failed}` : rows && !rows.length ? t('No problems found.') : ''); + setClass(this.status, 'is-error', !!failed); + } + + private setRows(rows: CheckRow[]): void { + this.rows = [...rows].sort((a, b) => ORDER[a.severity] - ORDER[b.severity]); + const n: Record = { error: 0, warning: 0, info: 0 }; + for (const r of this.rows) n[r.severity]++; + for (const s of Object.keys(n) as Severity[]) { + setText(this.counts[s], String(n[s])); + setClass(this.counts[s].parentElement, 'is-zero', n[s] === 0); + } + if (this.active && !this.rows.some((r) => r.key === this.active)) this.active = null; + patchList(this.list, this.rows, { + key: (r) => r.key, + create: (r) => { + const item = el(`
`); + setText(q(item, '[data-act="fix"]'), t('Fix')); + this.paintRow(item, r); + return item; + }, + update: (item, r) => this.paintRow(item, r), + }); + this.paintActive(); + } + + private paintRow(item: HTMLElement, r: CheckRow): void { + const iconHost = q(item, '.fc-check-icon'); + if (iconHost.dataset.sev !== r.severity) { + iconHost.dataset.sev = r.severity; + iconHost.innerHTML = icon(ICONS[r.severity], 14); + } + for (const s of ['error', 'warning', 'info'] as Severity[]) setClass(item, `is-${s}`, r.severity === s); + setText(q(item, '.fc-check-msg'), r.text); + setText(q(item, '.fc-check-code'), r.code); + const main = q(item, '.fc-check-main'); + setDisabled(main, !r.atoms.length && !r.bonds.length); + setTitle(main, r.atoms.length || r.bonds.length ? t('Select on the canvas') : ''); + setHidden(q(item, '[data-act="fix"]'), !r.fixable || !this.host?.fix); + } + + private paintActive(): void { + for (const item of Array.from(this.list.children) as HTMLElement[]) setClass(item, 'is-active', item.dataset.key === this.active); + } +} + +let panel: CheckPanel | null = null; + +export function showStructureCheck(host: CheckPanelHost): void { + panel ??= new CheckPanel(); + panel.show(host); +} + +export function refreshStructureCheck(): void { if (panel?.isOpen) void panel.run(); } + +export function closeStructureCheck(): void { panel?.close(); } + +export const structureCheckOpen = (): boolean => !!panel?.isOpen; 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); +} 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 ``; +} 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 }, diff --git a/frontend/src/version.ts b/frontend/src/version.ts index 465e390c..cc337735 100644 --- a/frontend/src/version.ts +++ b/frontend/src/version.ts @@ -1 +1 @@ -export const VERSION = '0.4.0'; +export const VERSION = '0.6.0'; 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" 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 diff --git a/setup/i18n_tool.py b/setup/i18n_tool.py index 18b91c5a..f1f055e0 100644 --- a/setup/i18n_tool.py +++ b/setup/i18n_tool.py @@ -61,7 +61,7 @@ def keep(s: str) -> str | None: return None if re.search(r"[<>]|\$\{|''\}", s) or s.count("{") != s.count("}"): return None - if re.search(r"rgba?\(|color-mix\(|:not\(|\[[a-z-]+(=[^\]]*)?\]|\b(fill|stroke)=\"|^\[[a-z_]+\]", s): + if re.search(r"rgba?\(|color-mix\(|:not\(|\[[a-z-]+(=[^\]]*)?\]|\b[a-z]+(-[a-z]+)*=\"|^\[[a-z_]+\]|^-?\d+(px|%)( -?\d+(px|%))*$", s): return None return s diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 8fd614f7..5e8527b5 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1163,7 +1163,7 @@ dependencies = [ [[package]] name = "formchem" -version = "0.4.0" +version = "0.6.0" dependencies = [ "fontdb", "gtk", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 78bb2a69..2faa408c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formchem" -version = "0.4.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 3db030a9..4b0ec2a5 100644 --- a/src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml +++ b/src-tauri/flatpak/ai.nodemode.formchem.metainfo.xml @@ -15,6 +15,8 @@ https://formai.tools/download/?utm_source=github + + diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 00e131c9..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.4.0", + "version": "0.6.0", "identifier": "ai.nodemode.formchem", "build": { "frontendDist": "../frontend/dist"