@datagrok/helm 3.0.4 → 3.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/489.js +1 -1
- package/dist/489.js.map +1 -1
- package/dist/package-test.js +1 -1
- package/dist/package-test.js.map +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/package.json +11 -2
- package/src/constants.ts +12 -0
- package/src/package-api.ts +8 -0
- package/src/package-test.ts +1 -0
- package/src/package-utils.ts +37 -0
- package/src/package.g.ts +9 -0
- package/src/package.ts +20 -0
- package/src/tests/helm-input-tests.ts +31 -0
- package/src/tests/wrap-width-tests.ts +132 -0
- package/src/utils/wrap-width.ts +18 -0
- package/src/widgets/helm-input.ts +4 -1
- package/src/widgets/wrap-width-widget.ts +73 -0
- package/test-console-output-1.log +138 -104
- package/test-playwright-report.json +20 -20
- package/test-record-1.mp4 +0 -0
package/dist/package.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var helm;(()=>{var e={130(e,t,i){"use strict";i.d(t,{A:()=>a});var n=i(354),o=i.n(n),r=i(314),s=i.n(r)()(o());s.push([e.id,'/* T-0609 / Phase 19 (T-1902) / Phase 28 (T-2801, T-2804) --\n * Default editor stylesheet. SINGLE source of truth.\n *\n * Build pipeline:\n * 1. tsup copies this file byte-for-byte to `dist/editor.css`\n * (see `tsup.config.ts` -- onSuccess hook).\n * 2. `package.json#exports."./styles.css"` maps the public import\n * `@datagrok-libraries/hwe/styles.css` to `dist/editor.css`, so\n * library consumers do `import \'@datagrok-libraries/hwe/styles.css\';`\n * via their bundler (vite, webpack, rollup, etc.).\n * 3. apps/demo imports this file directly with a relative path\n * (`import \'../../../src/editor/styles/editor.css\';` in main.ts)\n * so vite serves source CSS in dev and bundles it in prod.\n *\n * Phase 28 removed the previous runtime injection path\n * (`injectAppStyles` + `editor-css.generated.ts` TS mirror). Reason:\n * dual delivery was a recurring drift hazard. The bundler is now the\n * SINGLE CSS-delivery channel; tests use `mountEditorCss` (in\n * `tests/helpers/load-css.ts`) to read this file directly when\n * stylesheet-text or `getComputedStyle` checks are needed in linkedom.\n */\n\n.hw-app {\n --hw-bg: #ffffff;\n --hw-fg: #1a1a1a;\n --hw-muted: #6c757d;\n --hw-accent: #1f5fcd;\n --hw-selection: #FFD29B;\n --hw-border: #d8d8d8;\n --hw-border-subtle: #e9ecef;\n --hw-tile-hover: #f1f3f5;\n --hw-toolbar-bg: #f4f5f7;\n --hw-pane-bg: #fafbfc;\n --hw-error: #cc0000;\n /* T-3517 -- toolbar icon stroke colour. Datagrok-style neutral grey\n (icons read as quiet chrome until hovered, then darken to --hw-fg). */\n --hw-icon: #6b7178;\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-sizing: border-box;\n}\n.hw-app--dark {\n --hw-bg: #1a1d23;\n --hw-fg: #e0e0e0;\n --hw-muted: #9aa1a8;\n --hw-accent: #6699ff;\n --hw-selection: #FFD29B;\n --hw-border: #3a3f47;\n --hw-border-subtle: #2c3037;\n --hw-tile-hover: #262a31;\n --hw-toolbar-bg: #22252b;\n --hw-pane-bg: #1f2228;\n --hw-error: #ff5050;\n --hw-icon: #9aa1a8;\n}\n.hw-app *, .hw-app *::before, .hw-app *::after { box-sizing: border-box; }\n\n.hw-app__toolbar { flex: 0 0 auto; }\n.hw-app__main {\n flex: 1 1 auto;\n display: flex;\n flex-direction: row;\n min-height: 0;\n border-top: 1px solid var(--hw-border);\n}\n.hw-app__palette {\n flex: 0 0 220px;\n border-right: 1px solid var(--hw-border);\n overflow: auto;\n background: var(--hw-pane-bg);\n}\n.hw-app__canvas { flex: 1 1 auto; position: relative; min-width: 0; overflow: hidden; }\n.hw-app__panes { flex: 0 0 auto; border-top: 1px solid var(--hw-border); }\n.hw-app__tabs { display: flex; flex-direction: row; background: var(--hw-toolbar-bg); }\n.hw-app__tab {\n padding: 6px 14px;\n cursor: pointer;\n border: none;\n background: transparent;\n color: var(--hw-fg);\n border-right: 1px solid var(--hw-border);\n font-size: 12px;\n}\n.hw-app__tab--active { background: var(--hw-bg); border-bottom: 2px solid var(--hw-accent); }\n/* Cap the active pane\'s height; taller content scrolls within the pane. */\n.hw-app__pane-body { padding: 8px; min-height: 80px; max-height: 300px; overflow: auto; background: var(--hw-bg); }\n\n.hw-toolbar {\n display: flex;\n flex-direction: row;\n align-items: center;\n gap: 4px;\n padding: 4px 6px;\n background: var(--hw-toolbar-bg);\n}\n.hw-toolbar__btn {\n /* T-3517 -- Datagrok-style flat, borderless icon buttons. The icon\n stroke uses the neutral grey --hw-icon; hover darkens it to --hw-fg\n and adds a soft rounded background, matching Datagrok\'s toolbar. */\n border: 1px solid transparent;\n background: transparent;\n color: var(--hw-icon);\n border-radius: 4px;\n padding: 5px;\n cursor: pointer;\n font-size: 13px;\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: background 120ms, color 120ms;\n}\n.hw-toolbar__btn-icon {\n display: inline-block;\n width: 100%;\n height: 100%;\n color: inherit;\n}\n.hw-toolbar__btn-icon > svg {\n width: 100%;\n height: 100%;\n display: block;\n}\n.hw-toolbar__btn:hover { background: var(--hw-tile-hover, var(--hw-toolbar-bg)); color: var(--hw-fg); }\n.hw-toolbar__btn[disabled] { opacity: 0.4; cursor: default; }\n.hw-toolbar__btn--active {\n border-color: var(--hw-accent);\n background: var(--hw-accent);\n color: #ffffff;\n}\n.hw-toolbar__separator {\n display: inline-block;\n width: 1px;\n height: 18px;\n background: var(--hw-border);\n margin: 0 4px;\n}\n\n.hw-palette {\n display: flex;\n flex-direction: column;\n height: 100%;\n padding: 4px;\n}\n.hw-palette__search {\n width: 100%;\n padding: 4px;\n margin-bottom: 6px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-size: 12px;\n flex: 0 0 auto;\n}\n/* T-1421 / T-1423 -- tab list: horizontal row above the panes. Active\n tab gets a 2 px accent underline that absorbs the 1 px container\n border below via a negative bottom margin so the layout does not\n shift when the active tab changes.\n\n Phase 24 (T-2404): when a library exposes many polymer types\n (Favorites + PEPTIDE + RNA + CHEM + BLOB + G = 6 tabs), they can no\n longer fit horizontally inside the 200 px palette pane and the\n browser shows an unobvious horizontal scrollbar. Switch to\n `flex-wrap: wrap` so overflow tabs wrap onto a second (or third)\n row -- no hidden scrollbar, every tab is always visible. The\n per-tab padding shrinks too so more tabs fit per row before\n wrapping. */\n.hw-palette__tabs {\n display: flex;\n flex-wrap: wrap;\n gap: 2px 4px;\n border-bottom: 1px solid var(--hw-border);\n flex: 0 0 auto;\n /* Defensively: no overflow scrolling -- wrapping is the answer. */\n overflow: hidden;\n}\n.hw-palette__tab {\n /* Phase 24 (T-2404): compact padding + min-width so 6 tabs still fit\n in two rows max within a 200 px palette pane. */\n flex: 0 0 auto;\n padding: 6px 8px;\n cursor: pointer;\n border: none;\n background: transparent;\n font-size: 12px;\n color: var(--hw-muted);\n user-select: none;\n white-space: nowrap;\n min-width: 0;\n}\n.hw-palette__tab:hover {\n color: var(--hw-fg);\n background: var(--hw-tile-hover);\n}\n.hw-palette__tab[aria-selected="true"] {\n color: var(--hw-fg);\n border-bottom: 2px solid var(--hw-accent);\n margin-bottom: -1px;\n font-weight: 600;\n}\n.hw-palette__panes {\n flex: 1 1 auto;\n min-height: 0;\n}\n.hw-palette__pane {\n overflow-y: auto;\n max-height: 100%;\n padding: 4px 6px;\n}\n.hw-palette__pane[hidden] { display: none; }\n.hw-palette__placeholder {\n padding: 12px 6px;\n color: var(--hw-muted);\n font-size: 12px;\n font-style: italic;\n}\n/* T-1423 -- bolder, more separated group headers. */\n.hw-palette__group { margin-bottom: 12px; }\n.hw-palette__group-header {\n font-size: 13px;\n font-weight: 700;\n color: var(--hw-muted);\n padding: 8px 4px 4px;\n margin: 8px 0 4px;\n border-bottom: 1px solid var(--hw-border-subtle);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-palette__group-tiles {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 6px;\n padding: 2px;\n}\n.hw-palette__tiles { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px; }\n.hw-palette__tile {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 48px;\n max-width: none;\n height: 40px;\n padding: 4px 6px;\n border: 2px solid var(--hw-border);\n border-radius: 8px;\n background: #ffffff;\n cursor: grab;\n font-size: 13px;\n font-weight: 600;\n user-select: none;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms, box-shadow 120ms;\n box-sizing: border-box;\n}\n.hw-palette__tile:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);\n}\n.hw-palette__tile[aria-pressed="true"],\n.hw-palette__tile--primed {\n border-color: var(--hw-accent);\n box-shadow: 0 0 0 2px rgba(31, 95, 205, 0.18);\n}\n.hw-palette__tile--favorite { outline: 1px dashed var(--hw-accent); outline-offset: -3px; }\n.hw-palette__tile--low-contrast {\n box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.08);\n}\n.hw-palette__star {\n position: absolute;\n top: 2px;\n right: 4px;\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-palette__tile--favorite .hw-palette__star { color: var(--hw-accent); }\n.hw-palette__label {\n font-weight: 600;\n letter-spacing: 0.02em;\n display: inline-block;\n max-width: 80px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/* Phase 18 (T-1806) / Phase 19 (T-1903) / Phase 20 (T-2002) -- RNA Builder.\n Phase 20 redesign: SVG triplet visualization. Sugar (square),\n linker (circle), base (diamond) -- each clickable to enter pick\n mode. Fills come from the resolved monomer colour palette so the\n preview matches the canvas rendering. */\n.hw-rna-builder {\n display: block;\n /* Phase 21 (T-2101): horizontal margin nudges the builder rightward\n so it visually aligns with the palette tile column below. The\n user reported the SVG sat too far left vs. the tile rows. */\n margin: 4px 8px 12px;\n padding: 8px;\n background: var(--hw-pane-bg, #fafbfc);\n border: 1px solid var(--hw-border-subtle, #e9ecef);\n border-radius: 6px;\n}\n/* T-3513 -- header row holds the title plus the favorite star. */\n.hw-rna-builder__header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n}\n.hw-rna-builder__title {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-rna-builder__header .hw-rna-builder__title {\n margin-bottom: 0;\n}\n/* T-3513 -- favorite star toggling the composed triplet. */\n.hw-rna-builder__fav {\n font-size: 15px;\n line-height: 1;\n cursor: pointer;\n color: var(--hw-muted);\n user-select: none;\n}\n.hw-rna-builder__fav--active { color: var(--hw-accent); }\n.hw-rna-builder__fav--disabled { opacity: 0.35; cursor: default; }\n/* Phase 29 (T-2901) -- Pick-mode hint shown directly under the "RNA\n builder" title while a slot is in pick mode. Replaces the Phase 24\n palette-level reserved-space hint above the search box. The hint\n carries the `hidden` HTML attribute when idle so the SVG triplet\n sits flush against the title (no wasted vertical space). User\n request 2026-05-19: "lets not have that empty space, and just\n display that text in bold below \'RNA BUILDER\' header, inside the\n builder itself." */\n.hw-rna-builder__hint {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-accent);\n margin: 4px 0 -14px;\n}\n.hw-rna-builder__hint[hidden] {\n display: none;\n}\n.hw-rna-builder__triplet {\n display: block;\n width: 100%;\n max-width: 180px;\n height: auto;\n max-height: 10vh;\n margin: 0 auto 6px;\n}\n.hw-rna-builder__bond {\n stroke: var(--hw-fg, #1a1a1a);\n stroke-width: 1.5;\n fill: none;\n}\n.hw-rna-builder__slot {\n cursor: pointer;\n}\n.hw-rna-builder__slot-shape {\n stroke-width: 1.5;\n transition: filter 120ms;\n}\n.hw-rna-builder__slot:hover .hw-rna-builder__slot-shape {\n filter: brightness(1.08);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot-label {\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n /* Phase 21 (T-2102): font-size is set per-label inline via\n setAttribute(\'font-size\', ...) so a long symbol like `[5meC]`\n can scale down. The CSS default below is a safety net for\n pre-T-2102 markup. */\n font-size: 12px;\n font-weight: 700;\n user-select: none;\n pointer-events: none;\n}\n.hw-rna-builder__slot--active .hw-rna-builder__slot-shape,\n.hw-rna-builder__slot[aria-pressed="true"] .hw-rna-builder__slot-shape {\n /* Yellow halo via filter so per-monomer fill / stroke stays intact. */\n filter: drop-shadow(0 0 3px #ffeb3b) drop-shadow(0 0 2px #ffeb3b);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot:focus {\n outline: none;\n}\n.hw-rna-builder__slot:focus-visible .hw-rna-builder__slot-shape {\n stroke: var(--hw-accent);\n stroke-width: 2.5;\n}\n.hw-rna-builder__preview {\n margin: 6px 0;\n font-size: 11px;\n color: var(--hw-fg);\n font-family: ui-monospace, Menlo, Consolas, monospace;\n text-align: center;\n}\n.hw-rna-builder__add {\n display: block;\n width: 100%;\n padding: 4px 8px;\n background: var(--hw-accent);\n color: #ffffff;\n border: 1px solid var(--hw-accent);\n border-radius: 3px;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n}\n.hw-rna-builder__add:hover { opacity: 0.9; }\n.hw-rna-builder__add:active { transform: translateY(1px); }\n\n/* T-3513 -- RNA triplet chips. Small, monospace, wrap into a tight row.\n Used by the RNA pane\'s default-nucleotide row (r(A)p ... r(T)p) and by\n triplet favorites in the Favorites pane. Kept compact because the RNA\n pane\'s vertical space is constrained by the RNA builder above it. */\n.hw-triplet-chips {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n padding: 2px;\n}\n.hw-triplet-chips--defaults {\n margin: 0 0 8px;\n}\n.hw-triplet-chip {\n position: relative;\n display: inline-flex;\n align-items: center;\n gap: 2px;\n height: 22px;\n padding: 0 6px;\n border: 1px solid var(--hw-border);\n border-radius: 11px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 11px;\n font-weight: 600;\n line-height: 1;\n cursor: pointer;\n user-select: none;\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms;\n}\n.hw-triplet-chip:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n}\n.hw-triplet-chip--favorite { border-color: var(--hw-accent); }\n.hw-triplet-chip__star {\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-triplet-chip--favorite .hw-triplet-chip__star { color: var(--hw-accent); }\n.hw-triplet-chip__label { letter-spacing: 0.02em; }\n\n/* Phase 29 (T-2901) -- The Phase 24 palette-level pick-mode hint\n container has been REMOVED. The hint now lives inside the RNA\n Builder as `.hw-rna-builder__hint` (see the rules under the RNA\n Builder block above). The user explicitly reported the\n reserved-space hint above the search box as "wasted space". */\n\n.hw-pane { display: block; }\n.hw-pane__content { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; }\n.hw-pane__notation {\n outline: none;\n border: 1px solid var(--hw-border);\n padding: 4px;\n background: var(--hw-bg);\n}\n.hw-pane__error { color: var(--hw-error); font-size: 11px; margin-top: 4px; display: none; }\n.hw-pane__error--visible { display: block; }\n.hw-pane__prop-row { display: flex; gap: 8px; padding: 2px 0; }\n.hw-pane__prop-label { color: var(--hw-muted); width: 180px; }\n.hw-pane__prop-value { color: var(--hw-fg); }\n.hw-pane__placeholder { color: var(--hw-muted); font-style: italic; }\n\n.hw-pane__content.hw-pane__sequence, .hw-pane__content.hw-pane__notation {\n max-height: 100px;\n overflow: scroll;\n}\n\n.hw-modal-backdrop {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.3);\n display: flex; align-items: center; justify-content: center;\n z-index: 1000;\n}\n.hw-modal {\n background: var(--hw-bg);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 4px;\n min-width: 320px;\n max-width: 600px;\n padding: 12px;\n}\n.hw-modal__header { font-weight: bold; padding-bottom: 8px; border-bottom: 1px solid var(--hw-border); }\n.hw-modal__body { padding-top: 8px; }\n.hw-modal__row { display: flex; gap: 8px; align-items: center; padding: 4px 0; }\n.hw-modal__label { color: var(--hw-fg); min-width: 100px; }\n.hw-modal__input, .hw-modal__select {\n flex: 1;\n padding: 4px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n}\n.hw-modal__check { transform: scale(1.1); }\n.hw-modal__actions { display: flex; justify-content: flex-end; gap: 6px; padding-top: 10px; }\n.hw-modal__ok, .hw-modal__cancel, .hw-modal__find-next, .hw-modal__replace, .hw-modal__replace-all {\n padding: 4px 10px;\n border: 1px solid var(--hw-border);\n background: var(--hw-bg);\n color: var(--hw-fg);\n border-radius: 3px;\n cursor: pointer;\n}\n.hw-modal__ok { background: var(--hw-accent); color: #ffffff; border-color: var(--hw-accent); }\n.hw-modal__result { color: var(--hw-muted); font-size: 11px; padding-top: 6px; }\n\n/* Phase 23 (T-2304) -- Bond editor endpoint preview row. Renders two\n monomer structures (atom A1 and atom A2) flanking a `↔` arrow so the\n user can see what they\'re connecting while picking R-groups. The\n SVG inside each cell stretches via the .hw-bond-props__atom-rdkit\n svg rule below (matches the tooltip pattern). */\n.hw-bond-props__atoms {\n display: flex;\n align-items: center;\n gap: 16px;\n margin: 12px 0;\n}\n.hw-bond-props__atom {\n flex: 1;\n text-align: center;\n}\n.hw-bond-props__atom-label {\n font-weight: 600;\n margin-bottom: 6px;\n color: var(--hw-fg);\n}\n.hw-bond-props__atom-rdkit {\n width: 180px;\n height: 120px;\n margin: 0 auto 8px;\n background: #fafafa;\n border: 1px solid #f3f4f6;\n border-radius: 4px;\n padding: 4px;\n box-sizing: border-box;\n}\n.hw-bond-props__atom-rdkit svg {\n display: block;\n width: 100%;\n height: 100%;\n}\n.hw-bond-props__bond-arrow {\n font-size: 24px;\n color: var(--hw-muted);\n flex: 0 0 auto;\n}\n\n.hw-editor-view {\n width: 100%;\n height: 100%;\n position: relative;\n --hw-hover: #ff8c00;\n}\n.hw-editor-view svg { width: 100%; height: 100%; }\n\n/* T-1103 / Phase 19 (T-1901) -- Cursor affordance only. We removed\n the :hover rules that recoloured the atom\'s own outline because\n they ran in PARALLEL with the real highlight ring painted by the\n renderer (teal #26A69A), producing the wrong colour the user\n reported as "yellow on hover" (the CSS rule re-stroked the atom in\n var(--hw-hover) = #ff8c00, an orange-yellow). The renderer\'s\n highlight layer is now the single source of truth for hover\n feedback. */\n.hw-atom { cursor: pointer; }\n.hw-bond { cursor: pointer; }\n\n/* Mode-specific cursors on the canvas wrapper. The editor adds an\n hw-editor-view--<mode> class via the option:change handler. */\n.hw-editor-view--select svg { cursor: default; }\n.hw-editor-view--eraser svg { cursor: not-allowed; }\n.hw-editor-view--hbond svg { cursor: crosshair; }\n.hw-editor-view--move svg { cursor: grab; }\n.hw-editor-view--move:active svg { cursor: grabbing; }\n\n/* Phase 22 (T-2201) -- Unified tooltip styling. Three tooltip variants\n share the same look-and-feel: atom hover (canvas), bond hover\n (canvas), palette-tile hover (left pane), and rna-builder slot hover.\n Pre-Phase 22 the tooltips were absolutely-positioned, dark, and\n z-index 100 -- the gallery panel (z-index higher) ate into them and\n the dark background looked heavy. Phase 22 mounts the tooltip at\n `document.body` (escaping every parent stacking context), pins\n `z-index: 99999`, and paints them white with a soft drop shadow and\n darker body text so they read clearly over any backdrop. */\n/* Phase 32 (T-3003) -- Ghost cursor preview that follows the mouse\n when a palette tile is primed in select mode. `pointer-events:\n none` so the underlying canvas keeps receiving clicks / drags. The\n z-index sits just below the tooltips (99998 vs 99999) so a real\n tooltip can still overlay the ghost if both happen to be visible. */\n.hw-next-add-cursor {\n position: fixed;\n pointer-events: none;\n z-index: 99998;\n opacity: 0.7;\n display: none;\n}\n.hw-next-add-cursor__svg {\n display: block;\n}\n\n.hw-atom-tooltip,\n.hw-bond-tooltip,\n.hw-palette-tooltip,\n.hw-builder-tooltip,\n.hw-toolbar-tooltip {\n position: fixed;\n pointer-events: none;\n background: #ffffff;\n color: #1f2937;\n border: 1px solid #e5e7eb;\n border-radius: 6px;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12), 0 2px 4px rgba(0, 0, 0, 0.08);\n padding: 10px 12px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 12px;\n line-height: 1.4;\n max-width: 240px;\n z-index: 99999;\n}\n/* T-3516 -- toolbar button tooltip: a single compact line, no wrap. */\n.hw-toolbar-tooltip {\n padding: 5px 8px;\n white-space: nowrap;\n font-weight: 500;\n}\n.hw-tooltip__symbol {\n font-weight: 700;\n color: #111827;\n}\n/* T-3514 -- RNA triplet tooltip: three monomer structures side by side.\n Wider than the single-structure tooltip so all three columns fit. */\n.hw-triplet-tooltip { max-width: 420px; }\n.hw-tooltip__triplet {\n display: flex;\n gap: 8px;\n margin-top: 6px;\n}\n.hw-tooltip__triplet-part {\n flex: 1 1 0;\n min-width: 0;\n text-align: center;\n}\n.hw-tooltip__triplet-role {\n font-weight: 600;\n color: #111827;\n font-size: 11px;\n}\n.hw-tooltip__name {\n color: #4b5563;\n}\n.hw-tooltip__hint {\n color: #6b7280;\n font-style: italic;\n font-size: 11px;\n margin-top: 6px;\n}\n.hw-tooltip__rdkit {\n display: block;\n margin-top: 8px;\n /* padding-top: 8px; */\n border-top: 1px solid #f3f4f6;\n background: #fafafa;\n border-radius: 4px;\n}\n/* Phase 23 (T-2303) -- The user reported "molecules do not take the full\n space" in the tooltip. RDKit emits an svg with a `viewBox`, so\n `width: 100%; height: auto` lets the structure stretch responsively\n to whatever width the parent tooltip column has. `max-height` caps\n tall structures so they never blow up the tooltip vertically. */\n.hw-tooltip__rdkit svg,\n[data-testid="atom-tooltip-rdkit-svg"] svg,\n[data-testid="palette-tooltip-rdkit-svg"] svg,\n[data-testid="builder-tooltip-rdkit-svg"] svg {\n display: block;\n width: 100%;\n height: auto;\n max-height: 180px;\n margin: 0 auto;\n}\n/* Legacy aliases (kept so Phase 21 atom-tooltip text styling still\n resolves). The body text colour is now driven by the parent tooltip\n rule above; the legacy classes keep the line-wrap behaviour. */\n.hw-atom-tooltip__text {\n display: block;\n}\n\n/* Status indicator (T-1106) -- small badge in the bottom-left of the canvas. */\n.hw-status-bar {\n position: absolute;\n left: 6px;\n bottom: 6px;\n padding: 2px 8px;\n background: rgba(255, 255, 255, 0.85);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n font-size: 11px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n pointer-events: none;\n z-index: 50;\n}\n.hw-app--dark .hw-status-bar { background: rgba(34, 36, 41, 0.85); }\n\n.hw-status-bar__mode {\n display: inline-flex;\n align-items: center;\n gap: 0;\n}\n.hw-status-bar__message {\n display: inline-block;\n margin-left: 8px;\n font-weight: 500;\n}\n.hw-status-bar__message[data-severity="info"] { color: var(--hw-fg); }\n.hw-status-bar__message[data-severity="warn"] { color: #b8860b; }\n.hw-status-bar__message[data-severity="error"] { color: #c0392b; }\n.hw-app--dark .hw-status-bar__message[data-severity="warn"] { color: #f7c948; }\n.hw-app--dark .hw-status-bar__message[data-severity="error"] { color: #ff6b6b; }\n\n/* Phase 25 (T-2504) -- "Next add: X [x]" clear button. The status bar\n itself sets `pointer-events: none` (it floats above the canvas as a\n non-interactive badge), so the button explicitly re-enables hits on\n itself only. Visible only when `nextAdd` is primed because the\n element is conditionally appended in `_refreshStatus`. */\n.hw-status-bar__next-add-symbol {\n display: inline-block;\n font-weight: 600;\n}\n.hw-status-bar__next-add-clear {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 16px;\n height: 16px;\n margin-left: 6px;\n padding: 0;\n background: transparent;\n border: 1px solid #d1d5db;\n border-radius: 50%;\n color: #6b7280;\n font-size: 12px;\n line-height: 1;\n cursor: pointer;\n pointer-events: auto;\n}\n.hw-status-bar__next-add-clear:hover {\n background: #f3f4f6;\n color: #1f2937;\n border-color: #9ca3af;\n}\n\n.hw-bond-preview { pointer-events: none; opacity: 0.85; }\n\n.hw-help-modal-backdrop {\n position: fixed; left: 0; top: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.4);\n display: flex; align-items: center; justify-content: center;\n z-index: 2000;\n}\n.hw-help-modal {\n background: #ffffff;\n color: #1a1a1a;\n padding: 16px 20px;\n border-radius: 4px;\n max-width: 480px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-shadow: 0 10px 20px rgba(0,0,0,0.3);\n}\n.hw-help-modal h2 { margin: 0 0 8px 0; font-size: 16px; }\n.hw-help-modal ul { padding-left: 20px; line-height: 1.6; }\n.hw-help-modal kbd {\n background: #eef0f3;\n border: 1px solid #cbd0d6;\n border-radius: 3px;\n padding: 1px 4px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 12px;\n}\n.hw-help-modal__close {\n margin-top: 12px;\n padding: 4px 12px;\n border: 1px solid #cbd0d6;\n background: #f5f6f8;\n cursor: pointer;\n border-radius: 3px;\n}\n',"",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/hwe/dist/editor.css"],names:[],mappings:"AAAA;;;;;;;;;;;;;;;;;;;;EAoBE;;AAEF;EACE,gBAAgB;EAChB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,uBAAuB;EACvB,oBAAoB;EACpB,2BAA2B;EAC3B,wBAAwB;EACxB,wBAAwB;EACxB,qBAAqB;EACrB,mBAAmB;EACnB;0EACwE;EACxE,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,WAAW;EACX,YAAY;EACZ,wBAAwB;EACxB,mBAAmB;EACnB,2DAA2D;EAC3D,eAAe;EACf,sBAAsB;AACxB;AACA;EACE,gBAAgB;EAChB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,uBAAuB;EACvB,oBAAoB;EACpB,2BAA2B;EAC3B,wBAAwB;EACxB,wBAAwB;EACxB,qBAAqB;EACrB,mBAAmB;EACnB,kBAAkB;AACpB;AACA,iDAAiD,sBAAsB,EAAE;;AAEzE,mBAAmB,cAAc,EAAE;AACnC;EACE,cAAc;EACd,aAAa;EACb,mBAAmB;EACnB,aAAa;EACb,sCAAsC;AACxC;AACA;EACE,eAAe;EACf,wCAAwC;EACxC,cAAc;EACd,6BAA6B;AAC/B;AACA,kBAAkB,cAAc,EAAE,kBAAkB,EAAE,YAAY,EAAE,gBAAgB,EAAE;AACtF,iBAAiB,cAAc,EAAE,sCAAsC,EAAE;AACzE,gBAAgB,aAAa,EAAE,mBAAmB,EAAE,gCAAgC,EAAE;AACtF;EACE,iBAAiB;EACjB,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,mBAAmB;EACnB,wCAAwC;EACxC,eAAe;AACjB;AACA,uBAAuB,wBAAwB,EAAE,yCAAyC,EAAE;AAC5F,0EAA0E;AAC1E,qBAAqB,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,cAAc,EAAE,wBAAwB,EAAE;;AAElH;EACE,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;EACR,gBAAgB;EAChB,gCAAgC;AAClC;AACA;EACE;;uEAEqE;EACrE,6BAA6B;EAC7B,uBAAuB;EACvB,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,eAAe;EACf,eAAe;EACf,WAAW;EACX,YAAY;EACZ,oBAAoB;EACpB,mBAAmB;EACnB,uBAAuB;EACvB,yCAAyC;AAC3C;AACA;EACE,qBAAqB;EACrB,WAAW;EACX,YAAY;EACZ,cAAc;AAChB;AACA;EACE,WAAW;EACX,YAAY;EACZ,cAAc;AAChB;AACA,yBAAyB,sDAAsD,EAAE,mBAAmB,EAAE;AACtG,6BAA6B,YAAY,EAAE,eAAe,EAAE;AAC5D;EACE,8BAA8B;EAC9B,4BAA4B;EAC5B,cAAc;AAChB;AACA;EACE,qBAAqB;EACrB,UAAU;EACV,YAAY;EACZ,4BAA4B;EAC5B,aAAa;AACf;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,YAAY;EACZ,YAAY;AACd;AACA;EACE,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,kCAAkC;EAClC,kBAAkB;EAClB,wBAAwB;EACxB,mBAAmB;EACnB,eAAe;EACf,cAAc;AAChB;AACA;;;;;;;;;;;;cAYc;AACd;EACE,aAAa;EACb,eAAe;EACf,YAAY;EACZ,yCAAyC;EACzC,cAAc;EACd,kEAAkE;EAClE,gBAAgB;AAClB;AACA;EACE;oDACkD;EAClD,cAAc;EACd,gBAAgB;EAChB,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,eAAe;EACf,sBAAsB;EACtB,iBAAiB;EACjB,mBAAmB;EACnB,YAAY;AACd;AACA;EACE,mBAAmB;EACnB,gCAAgC;AAClC;AACA;EACE,mBAAmB;EACnB,yCAAyC;EACzC,mBAAmB;EACnB,gBAAgB;AAClB;AACA;EACE,cAAc;EACd,aAAa;AACf;AACA;EACE,gBAAgB;EAChB,gBAAgB;EAChB,gBAAgB;AAClB;AACA,4BAA4B,aAAa,EAAE;AAC3C;EACE,iBAAiB;EACjB,sBAAsB;EACtB,eAAe;EACf,kBAAkB;AACpB;AACA,oDAAoD;AACpD,qBAAqB,mBAAmB,EAAE;AAC1C;EACE,eAAe;EACf,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,iBAAiB;EACjB,gDAAgD;EAChD,yBAAyB;EACzB,sBAAsB;AACxB;AACA;EACE,aAAa;EACb,qCAAqC;EACrC,QAAQ;EACR,YAAY;AACd;AACA,qBAAqB,aAAa,EAAE,eAAe,EAAE,QAAQ,EAAE,YAAY,EAAE;AAC7E;EACE,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,mBAAmB;EACnB,uBAAuB;EACvB,WAAW;EACX,eAAe;EACf,eAAe;EACf,YAAY;EACZ,gBAAgB;EAChB,kCAAkC;EAClC,kBAAkB;EAClB,mBAAmB;EACnB,YAAY;EACZ,eAAe;EACf,gBAAgB;EAChB,iBAAiB;EACjB,gBAAgB;EAChB,uBAAuB;EACvB,yCAAyC;EACzC,iEAAiE;EACjE,sBAAsB;AACxB;AACA;EACE,8BAA8B;EAC9B,2BAA2B;EAC3B,yCAAyC;AAC3C;AACA;;EAEE,8BAA8B;EAC9B,6CAA6C;AAC/C;AACA,8BAA8B,oCAAoC,EAAE,oBAAoB,EAAE;AAC1F;EACE,6EAA6E;AAC/E;AACA;EACE,kBAAkB;EAClB,QAAQ;EACR,UAAU;EACV,eAAe;EACf,eAAe;EACf,sBAAsB;AACxB;AACA,gDAAgD,uBAAuB,EAAE;AACzE;EACE,gBAAgB;EAChB,sBAAsB;EACtB,qBAAqB;EACrB,eAAe;EACf,mBAAmB;EACnB,gBAAgB;EAChB,uBAAuB;AACzB;;AAEA;;;;0CAI0C;AAC1C;EACE,cAAc;EACd;;gEAE8D;EAC9D,oBAAoB;EACpB,YAAY;EACZ,sCAAsC;EACtC,kDAAkD;EAClD,kBAAkB;AACpB;AACA,iEAAiE;AACjE;EACE,aAAa;EACb,mBAAmB;EACnB,8BAA8B;EAC9B,kBAAkB;AACpB;AACA;EACE,gBAAgB;EAChB,eAAe;EACf,sBAAsB;EACtB,yBAAyB;EACzB,sBAAsB;AACxB;AACA;EACE,gBAAgB;AAClB;AACA,2DAA2D;AAC3D;EACE,eAAe;EACf,cAAc;EACd,eAAe;EACf,sBAAsB;EACtB,iBAAiB;AACnB;AACA,+BAA+B,uBAAuB,EAAE;AACxD,iCAAiC,aAAa,EAAE,eAAe,EAAE;AACjE;;;;;;;qBAOqB;AACrB;EACE,gBAAgB;EAChB,eAAe;EACf,uBAAuB;EACvB,mBAAmB;AACrB;AACA;EACE,aAAa;AACf;AACA;EACE,cAAc;EACd,WAAW;EACX,gBAAgB;EAChB,YAAY;EACZ,gBAAgB;EAChB,kBAAkB;AACpB;AACA;EACE,6BAA6B;EAC7B,iBAAiB;EACjB,UAAU;AACZ;AACA;EACE,eAAe;AACjB;AACA;EACE,iBAAiB;EACjB,wBAAwB;AAC1B;AACA;EACE,wBAAwB;EACxB,iBAAiB;AACnB;AACA;EACE,2DAA2D;EAC3D;;;yBAGuB;EACvB,eAAe;EACf,gBAAgB;EAChB,iBAAiB;EACjB,oBAAoB;AACtB;AACA;;EAEE,sEAAsE;EACtE,iEAAiE;EACjE,iBAAiB;AACnB;AACA;EACE,aAAa;AACf;AACA;EACE,wBAAwB;EACxB,iBAAiB;AACnB;AACA;EACE,aAAa;EACb,eAAe;EACf,mBAAmB;EACnB,qDAAqD;EACrD,kBAAkB;AACpB;AACA;EACE,cAAc;EACd,WAAW;EACX,gBAAgB;EAChB,4BAA4B;EAC5B,cAAc;EACd,kCAAkC;EAClC,kBAAkB;EAClB,eAAe;EACf,gBAAgB;EAChB,eAAe;AACjB;AACA,6BAA6B,YAAY,EAAE;AAC3C,8BAA8B,0BAA0B,EAAE;;AAE1D;;;sEAGsE;AACtE;EACE,aAAa;EACb,eAAe;EACf,QAAQ;EACR,YAAY;AACd;AACA;EACE,eAAe;AACjB;AACA;EACE,kBAAkB;EAClB,oBAAoB;EACpB,mBAAmB;EACnB,QAAQ;EACR,YAAY;EACZ,cAAc;EACd,kCAAkC;EAClC,mBAAmB;EACnB,qDAAqD;EACrD,eAAe;EACf,gBAAgB;EAChB,cAAc;EACd,eAAe;EACf,iBAAiB;EACjB,yCAAyC;EACzC,+CAA+C;AACjD;AACA;EACE,8BAA8B;EAC9B,2BAA2B;AAC7B;AACA,6BAA6B,8BAA8B,EAAE;AAC7D;EACE,eAAe;EACf,eAAe;EACf,sBAAsB;AACxB;AACA,oDAAoD,uBAAuB,EAAE;AAC7E,0BAA0B,sBAAsB,EAAE;;AAElD;;;;gEAIgE;;AAEhE,WAAW,cAAc,EAAE;AAC3B,oBAAoB,qDAAqD,EAAE,eAAe,EAAE,qBAAqB,EAAE,qBAAqB,EAAE;AAC1I;EACE,aAAa;EACb,kCAAkC;EAClC,YAAY;EACZ,wBAAwB;AAC1B;AACA,kBAAkB,sBAAsB,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE;AAC3F,2BAA2B,cAAc,EAAE;AAC3C,qBAAqB,aAAa,EAAE,QAAQ,EAAE,cAAc,EAAE;AAC9D,uBAAuB,sBAAsB,EAAE,YAAY,EAAE;AAC7D,uBAAuB,mBAAmB,EAAE;AAC5C,wBAAwB,sBAAsB,EAAE,kBAAkB,EAAE;;AAEpE;EACE,iBAAiB;EACjB,gBAAgB;AAClB;;AAEA;EACE,kBAAkB;EAClB,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS;EACpC,2BAA2B;EAC3B,aAAa,EAAE,mBAAmB,EAAE,uBAAuB;EAC3D,aAAa;AACf;AACA;EACE,wBAAwB;EACxB,mBAAmB;EACnB,kCAAkC;EAClC,kBAAkB;EAClB,gBAAgB;EAChB,gBAAgB;EAChB,aAAa;AACf;AACA,oBAAoB,iBAAiB,EAAE,mBAAmB,EAAE,yCAAyC,EAAE;AACvG,kBAAkB,gBAAgB,EAAE;AACpC,iBAAiB,aAAa,EAAE,QAAQ,EAAE,mBAAmB,EAAE,cAAc,EAAE;AAC/E,mBAAmB,mBAAmB,EAAE,gBAAgB,EAAE;AAC1D;EACE,OAAO;EACP,YAAY;EACZ,kCAAkC;EAClC,kBAAkB;EAClB,wBAAwB;EACxB,mBAAmB;AACrB;AACA,mBAAmB,qBAAqB,EAAE;AAC1C,qBAAqB,aAAa,EAAE,yBAAyB,EAAE,QAAQ,EAAE,iBAAiB,EAAE;AAC5F;EACE,iBAAiB;EACjB,kCAAkC;EAClC,wBAAwB;EACxB,mBAAmB;EACnB,kBAAkB;EAClB,eAAe;AACjB;AACA,gBAAgB,4BAA4B,EAAE,cAAc,EAAE,8BAA8B,EAAE;AAC9F,oBAAoB,sBAAsB,EAAE,eAAe,EAAE,gBAAgB,EAAE;;AAE/E;;;;kDAIkD;AAClD;EACE,aAAa;EACb,mBAAmB;EACnB,SAAS;EACT,cAAc;AAChB;AACA;EACE,OAAO;EACP,kBAAkB;AACpB;AACA;EACE,gBAAgB;EAChB,kBAAkB;EAClB,mBAAmB;AACrB;AACA;EACE,YAAY;EACZ,aAAa;EACb,kBAAkB;EAClB,mBAAmB;EACnB,yBAAyB;EACzB,kBAAkB;EAClB,YAAY;EACZ,sBAAsB;AACxB;AACA;EACE,cAAc;EACd,WAAW;EACX,YAAY;AACd;AACA;EACE,eAAe;EACf,sBAAsB;EACtB,cAAc;AAChB;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,mBAAmB;AACrB;AACA,sBAAsB,WAAW,EAAE,YAAY,EAAE;;AAEjD;;;;;;;cAOc;AACd,WAAW,eAAe,EAAE;AAC5B,WAAW,eAAe,EAAE;;AAE5B;gEACgE;AAChE,8BAA8B,eAAe,EAAE;AAC/C,8BAA8B,mBAAmB,EAAE;AACnD,6BAA6B,iBAAiB,EAAE;AAChD,4BAA4B,YAAY,EAAE;AAC1C,mCAAmC,gBAAgB,EAAE;;AAErD;;;;;;;;6DAQ6D;AAC7D;;;;sEAIsE;AACtE;EACE,eAAe;EACf,oBAAoB;EACpB,cAAc;EACd,YAAY;EACZ,aAAa;AACf;AACA;EACE,cAAc;AAChB;;AAEA;;;;;EAKE,eAAe;EACf,oBAAoB;EACpB,mBAAmB;EACnB,cAAc;EACd,yBAAyB;EACzB,kBAAkB;EAClB,yEAAyE;EACzE,kBAAkB;EAClB,2DAA2D;EAC3D,eAAe;EACf,gBAAgB;EAChB,gBAAgB;EAChB,cAAc;AAChB;AACA,sEAAsE;AACtE;EACE,gBAAgB;EAChB,mBAAmB;EACnB,gBAAgB;AAClB;AACA;EACE,gBAAgB;EAChB,cAAc;AAChB;AACA;sEACsE;AACtE,sBAAsB,gBAAgB,EAAE;AACxC;EACE,aAAa;EACb,QAAQ;EACR,eAAe;AACjB;AACA;EACE,WAAW;EACX,YAAY;EACZ,kBAAkB;AACpB;AACA;EACE,gBAAgB;EAChB,cAAc;EACd,eAAe;AACjB;AACA;EACE,cAAc;AAChB;AACA;EACE,cAAc;EACd,kBAAkB;EAClB,eAAe;EACf,eAAe;AACjB;AACA;EACE,cAAc;GACb,eAAe;EAChB,sBAAsB;EACtB,6BAA6B;EAC7B,mBAAmB;EACnB,kBAAkB;AACpB;AACA;;;;kEAIkE;AAClE;;;;EAIE,cAAc;EACd,WAAW;EACX,YAAY;EACZ,iBAAiB;EACjB,cAAc;AAChB;AACA;;iEAEiE;AACjE;EACE,cAAc;AAChB;;AAEA,+EAA+E;AAC/E;EACE,kBAAkB;EAClB,SAAS;EACT,WAAW;EACX,gBAAgB;EAChB,qCAAqC;EACrC,mBAAmB;EACnB,kCAAkC;EAClC,kBAAkB;EAClB,eAAe;EACf,2DAA2D;EAC3D,oBAAoB;EACpB,WAAW;AACb;AACA,+BAA+B,kCAAkC,EAAE;;AAEnE;EACE,oBAAoB;EACpB,mBAAmB;EACnB,MAAM;AACR;AACA;EACE,qBAAqB;EACrB,gBAAgB;EAChB,gBAAgB;AAClB;AACA,gDAAgD,mBAAmB,EAAE;AACrE,gDAAgD,cAAc,EAAE;AAChE,iDAAiD,cAAc,EAAE;AACjE,8DAA8D,cAAc,EAAE;AAC9E,+DAA+D,cAAc,EAAE;;AAE/E;;;;2DAI2D;AAC3D;EACE,qBAAqB;EACrB,gBAAgB;AAClB;AACA;EACE,oBAAoB;EACpB,mBAAmB;EACnB,uBAAuB;EACvB,WAAW;EACX,YAAY;EACZ,gBAAgB;EAChB,UAAU;EACV,uBAAuB;EACvB,yBAAyB;EACzB,kBAAkB;EAClB,cAAc;EACd,eAAe;EACf,cAAc;EACd,eAAe;EACf,oBAAoB;AACtB;AACA;EACE,mBAAmB;EACnB,cAAc;EACd,qBAAqB;AACvB;;AAEA,mBAAmB,oBAAoB,EAAE,aAAa,EAAE;;AAExD;EACE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS;EACrD,2BAA2B;EAC3B,aAAa,EAAE,mBAAmB,EAAE,uBAAuB;EAC3D,aAAa;AACf;AACA;EACE,mBAAmB;EACnB,cAAc;EACd,kBAAkB;EAClB,kBAAkB;EAClB,gBAAgB;EAChB,2DAA2D;EAC3D,eAAe;EACf,uCAAuC;AACzC;AACA,oBAAoB,iBAAiB,EAAE,eAAe,EAAE;AACxD,oBAAoB,kBAAkB,EAAE,gBAAgB,EAAE;AAC1D;EACE,mBAAmB;EACnB,yBAAyB;EACzB,kBAAkB;EAClB,gBAAgB;EAChB,qDAAqD;EACrD,eAAe;AACjB;AACA;EACE,gBAAgB;EAChB,iBAAiB;EACjB,yBAAyB;EACzB,mBAAmB;EACnB,eAAe;EACf,kBAAkB;AACpB",sourcesContent:['/* T-0609 / Phase 19 (T-1902) / Phase 28 (T-2801, T-2804) --\n * Default editor stylesheet. SINGLE source of truth.\n *\n * Build pipeline:\n * 1. tsup copies this file byte-for-byte to `dist/editor.css`\n * (see `tsup.config.ts` -- onSuccess hook).\n * 2. `package.json#exports."./styles.css"` maps the public import\n * `@datagrok-libraries/hwe/styles.css` to `dist/editor.css`, so\n * library consumers do `import \'@datagrok-libraries/hwe/styles.css\';`\n * via their bundler (vite, webpack, rollup, etc.).\n * 3. apps/demo imports this file directly with a relative path\n * (`import \'../../../src/editor/styles/editor.css\';` in main.ts)\n * so vite serves source CSS in dev and bundles it in prod.\n *\n * Phase 28 removed the previous runtime injection path\n * (`injectAppStyles` + `editor-css.generated.ts` TS mirror). Reason:\n * dual delivery was a recurring drift hazard. The bundler is now the\n * SINGLE CSS-delivery channel; tests use `mountEditorCss` (in\n * `tests/helpers/load-css.ts`) to read this file directly when\n * stylesheet-text or `getComputedStyle` checks are needed in linkedom.\n */\n\n.hw-app {\n --hw-bg: #ffffff;\n --hw-fg: #1a1a1a;\n --hw-muted: #6c757d;\n --hw-accent: #1f5fcd;\n --hw-selection: #FFD29B;\n --hw-border: #d8d8d8;\n --hw-border-subtle: #e9ecef;\n --hw-tile-hover: #f1f3f5;\n --hw-toolbar-bg: #f4f5f7;\n --hw-pane-bg: #fafbfc;\n --hw-error: #cc0000;\n /* T-3517 -- toolbar icon stroke colour. Datagrok-style neutral grey\n (icons read as quiet chrome until hovered, then darken to --hw-fg). */\n --hw-icon: #6b7178;\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-sizing: border-box;\n}\n.hw-app--dark {\n --hw-bg: #1a1d23;\n --hw-fg: #e0e0e0;\n --hw-muted: #9aa1a8;\n --hw-accent: #6699ff;\n --hw-selection: #FFD29B;\n --hw-border: #3a3f47;\n --hw-border-subtle: #2c3037;\n --hw-tile-hover: #262a31;\n --hw-toolbar-bg: #22252b;\n --hw-pane-bg: #1f2228;\n --hw-error: #ff5050;\n --hw-icon: #9aa1a8;\n}\n.hw-app *, .hw-app *::before, .hw-app *::after { box-sizing: border-box; }\n\n.hw-app__toolbar { flex: 0 0 auto; }\n.hw-app__main {\n flex: 1 1 auto;\n display: flex;\n flex-direction: row;\n min-height: 0;\n border-top: 1px solid var(--hw-border);\n}\n.hw-app__palette {\n flex: 0 0 220px;\n border-right: 1px solid var(--hw-border);\n overflow: auto;\n background: var(--hw-pane-bg);\n}\n.hw-app__canvas { flex: 1 1 auto; position: relative; min-width: 0; overflow: hidden; }\n.hw-app__panes { flex: 0 0 auto; border-top: 1px solid var(--hw-border); }\n.hw-app__tabs { display: flex; flex-direction: row; background: var(--hw-toolbar-bg); }\n.hw-app__tab {\n padding: 6px 14px;\n cursor: pointer;\n border: none;\n background: transparent;\n color: var(--hw-fg);\n border-right: 1px solid var(--hw-border);\n font-size: 12px;\n}\n.hw-app__tab--active { background: var(--hw-bg); border-bottom: 2px solid var(--hw-accent); }\n/* Cap the active pane\'s height; taller content scrolls within the pane. */\n.hw-app__pane-body { padding: 8px; min-height: 80px; max-height: 300px; overflow: auto; background: var(--hw-bg); }\n\n.hw-toolbar {\n display: flex;\n flex-direction: row;\n align-items: center;\n gap: 4px;\n padding: 4px 6px;\n background: var(--hw-toolbar-bg);\n}\n.hw-toolbar__btn {\n /* T-3517 -- Datagrok-style flat, borderless icon buttons. The icon\n stroke uses the neutral grey --hw-icon; hover darkens it to --hw-fg\n and adds a soft rounded background, matching Datagrok\'s toolbar. */\n border: 1px solid transparent;\n background: transparent;\n color: var(--hw-icon);\n border-radius: 4px;\n padding: 5px;\n cursor: pointer;\n font-size: 13px;\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: background 120ms, color 120ms;\n}\n.hw-toolbar__btn-icon {\n display: inline-block;\n width: 100%;\n height: 100%;\n color: inherit;\n}\n.hw-toolbar__btn-icon > svg {\n width: 100%;\n height: 100%;\n display: block;\n}\n.hw-toolbar__btn:hover { background: var(--hw-tile-hover, var(--hw-toolbar-bg)); color: var(--hw-fg); }\n.hw-toolbar__btn[disabled] { opacity: 0.4; cursor: default; }\n.hw-toolbar__btn--active {\n border-color: var(--hw-accent);\n background: var(--hw-accent);\n color: #ffffff;\n}\n.hw-toolbar__separator {\n display: inline-block;\n width: 1px;\n height: 18px;\n background: var(--hw-border);\n margin: 0 4px;\n}\n\n.hw-palette {\n display: flex;\n flex-direction: column;\n height: 100%;\n padding: 4px;\n}\n.hw-palette__search {\n width: 100%;\n padding: 4px;\n margin-bottom: 6px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-size: 12px;\n flex: 0 0 auto;\n}\n/* T-1421 / T-1423 -- tab list: horizontal row above the panes. Active\n tab gets a 2 px accent underline that absorbs the 1 px container\n border below via a negative bottom margin so the layout does not\n shift when the active tab changes.\n\n Phase 24 (T-2404): when a library exposes many polymer types\n (Favorites + PEPTIDE + RNA + CHEM + BLOB + G = 6 tabs), they can no\n longer fit horizontally inside the 200 px palette pane and the\n browser shows an unobvious horizontal scrollbar. Switch to\n `flex-wrap: wrap` so overflow tabs wrap onto a second (or third)\n row -- no hidden scrollbar, every tab is always visible. The\n per-tab padding shrinks too so more tabs fit per row before\n wrapping. */\n.hw-palette__tabs {\n display: flex;\n flex-wrap: wrap;\n gap: 2px 4px;\n border-bottom: 1px solid var(--hw-border);\n flex: 0 0 auto;\n /* Defensively: no overflow scrolling -- wrapping is the answer. */\n overflow: hidden;\n}\n.hw-palette__tab {\n /* Phase 24 (T-2404): compact padding + min-width so 6 tabs still fit\n in two rows max within a 200 px palette pane. */\n flex: 0 0 auto;\n padding: 6px 8px;\n cursor: pointer;\n border: none;\n background: transparent;\n font-size: 12px;\n color: var(--hw-muted);\n user-select: none;\n white-space: nowrap;\n min-width: 0;\n}\n.hw-palette__tab:hover {\n color: var(--hw-fg);\n background: var(--hw-tile-hover);\n}\n.hw-palette__tab[aria-selected="true"] {\n color: var(--hw-fg);\n border-bottom: 2px solid var(--hw-accent);\n margin-bottom: -1px;\n font-weight: 600;\n}\n.hw-palette__panes {\n flex: 1 1 auto;\n min-height: 0;\n}\n.hw-palette__pane {\n overflow-y: auto;\n max-height: 100%;\n padding: 4px 6px;\n}\n.hw-palette__pane[hidden] { display: none; }\n.hw-palette__placeholder {\n padding: 12px 6px;\n color: var(--hw-muted);\n font-size: 12px;\n font-style: italic;\n}\n/* T-1423 -- bolder, more separated group headers. */\n.hw-palette__group { margin-bottom: 12px; }\n.hw-palette__group-header {\n font-size: 13px;\n font-weight: 700;\n color: var(--hw-muted);\n padding: 8px 4px 4px;\n margin: 8px 0 4px;\n border-bottom: 1px solid var(--hw-border-subtle);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-palette__group-tiles {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 6px;\n padding: 2px;\n}\n.hw-palette__tiles { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px; }\n.hw-palette__tile {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 48px;\n max-width: none;\n height: 40px;\n padding: 4px 6px;\n border: 2px solid var(--hw-border);\n border-radius: 8px;\n background: #ffffff;\n cursor: grab;\n font-size: 13px;\n font-weight: 600;\n user-select: none;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms, box-shadow 120ms;\n box-sizing: border-box;\n}\n.hw-palette__tile:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);\n}\n.hw-palette__tile[aria-pressed="true"],\n.hw-palette__tile--primed {\n border-color: var(--hw-accent);\n box-shadow: 0 0 0 2px rgba(31, 95, 205, 0.18);\n}\n.hw-palette__tile--favorite { outline: 1px dashed var(--hw-accent); outline-offset: -3px; }\n.hw-palette__tile--low-contrast {\n box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.08);\n}\n.hw-palette__star {\n position: absolute;\n top: 2px;\n right: 4px;\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-palette__tile--favorite .hw-palette__star { color: var(--hw-accent); }\n.hw-palette__label {\n font-weight: 600;\n letter-spacing: 0.02em;\n display: inline-block;\n max-width: 80px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/* Phase 18 (T-1806) / Phase 19 (T-1903) / Phase 20 (T-2002) -- RNA Builder.\n Phase 20 redesign: SVG triplet visualization. Sugar (square),\n linker (circle), base (diamond) -- each clickable to enter pick\n mode. Fills come from the resolved monomer colour palette so the\n preview matches the canvas rendering. */\n.hw-rna-builder {\n display: block;\n /* Phase 21 (T-2101): horizontal margin nudges the builder rightward\n so it visually aligns with the palette tile column below. The\n user reported the SVG sat too far left vs. the tile rows. */\n margin: 4px 8px 12px;\n padding: 8px;\n background: var(--hw-pane-bg, #fafbfc);\n border: 1px solid var(--hw-border-subtle, #e9ecef);\n border-radius: 6px;\n}\n/* T-3513 -- header row holds the title plus the favorite star. */\n.hw-rna-builder__header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n}\n.hw-rna-builder__title {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-rna-builder__header .hw-rna-builder__title {\n margin-bottom: 0;\n}\n/* T-3513 -- favorite star toggling the composed triplet. */\n.hw-rna-builder__fav {\n font-size: 15px;\n line-height: 1;\n cursor: pointer;\n color: var(--hw-muted);\n user-select: none;\n}\n.hw-rna-builder__fav--active { color: var(--hw-accent); }\n.hw-rna-builder__fav--disabled { opacity: 0.35; cursor: default; }\n/* Phase 29 (T-2901) -- Pick-mode hint shown directly under the "RNA\n builder" title while a slot is in pick mode. Replaces the Phase 24\n palette-level reserved-space hint above the search box. The hint\n carries the `hidden` HTML attribute when idle so the SVG triplet\n sits flush against the title (no wasted vertical space). User\n request 2026-05-19: "lets not have that empty space, and just\n display that text in bold below \'RNA BUILDER\' header, inside the\n builder itself." */\n.hw-rna-builder__hint {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-accent);\n margin: 4px 0 -14px;\n}\n.hw-rna-builder__hint[hidden] {\n display: none;\n}\n.hw-rna-builder__triplet {\n display: block;\n width: 100%;\n max-width: 180px;\n height: auto;\n max-height: 10vh;\n margin: 0 auto 6px;\n}\n.hw-rna-builder__bond {\n stroke: var(--hw-fg, #1a1a1a);\n stroke-width: 1.5;\n fill: none;\n}\n.hw-rna-builder__slot {\n cursor: pointer;\n}\n.hw-rna-builder__slot-shape {\n stroke-width: 1.5;\n transition: filter 120ms;\n}\n.hw-rna-builder__slot:hover .hw-rna-builder__slot-shape {\n filter: brightness(1.08);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot-label {\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n /* Phase 21 (T-2102): font-size is set per-label inline via\n setAttribute(\'font-size\', ...) so a long symbol like `[5meC]`\n can scale down. The CSS default below is a safety net for\n pre-T-2102 markup. */\n font-size: 12px;\n font-weight: 700;\n user-select: none;\n pointer-events: none;\n}\n.hw-rna-builder__slot--active .hw-rna-builder__slot-shape,\n.hw-rna-builder__slot[aria-pressed="true"] .hw-rna-builder__slot-shape {\n /* Yellow halo via filter so per-monomer fill / stroke stays intact. */\n filter: drop-shadow(0 0 3px #ffeb3b) drop-shadow(0 0 2px #ffeb3b);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot:focus {\n outline: none;\n}\n.hw-rna-builder__slot:focus-visible .hw-rna-builder__slot-shape {\n stroke: var(--hw-accent);\n stroke-width: 2.5;\n}\n.hw-rna-builder__preview {\n margin: 6px 0;\n font-size: 11px;\n color: var(--hw-fg);\n font-family: ui-monospace, Menlo, Consolas, monospace;\n text-align: center;\n}\n.hw-rna-builder__add {\n display: block;\n width: 100%;\n padding: 4px 8px;\n background: var(--hw-accent);\n color: #ffffff;\n border: 1px solid var(--hw-accent);\n border-radius: 3px;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n}\n.hw-rna-builder__add:hover { opacity: 0.9; }\n.hw-rna-builder__add:active { transform: translateY(1px); }\n\n/* T-3513 -- RNA triplet chips. Small, monospace, wrap into a tight row.\n Used by the RNA pane\'s default-nucleotide row (r(A)p ... r(T)p) and by\n triplet favorites in the Favorites pane. Kept compact because the RNA\n pane\'s vertical space is constrained by the RNA builder above it. */\n.hw-triplet-chips {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n padding: 2px;\n}\n.hw-triplet-chips--defaults {\n margin: 0 0 8px;\n}\n.hw-triplet-chip {\n position: relative;\n display: inline-flex;\n align-items: center;\n gap: 2px;\n height: 22px;\n padding: 0 6px;\n border: 1px solid var(--hw-border);\n border-radius: 11px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 11px;\n font-weight: 600;\n line-height: 1;\n cursor: pointer;\n user-select: none;\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms;\n}\n.hw-triplet-chip:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n}\n.hw-triplet-chip--favorite { border-color: var(--hw-accent); }\n.hw-triplet-chip__star {\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-triplet-chip--favorite .hw-triplet-chip__star { color: var(--hw-accent); }\n.hw-triplet-chip__label { letter-spacing: 0.02em; }\n\n/* Phase 29 (T-2901) -- The Phase 24 palette-level pick-mode hint\n container has been REMOVED. The hint now lives inside the RNA\n Builder as `.hw-rna-builder__hint` (see the rules under the RNA\n Builder block above). The user explicitly reported the\n reserved-space hint above the search box as "wasted space". */\n\n.hw-pane { display: block; }\n.hw-pane__content { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; }\n.hw-pane__notation {\n outline: none;\n border: 1px solid var(--hw-border);\n padding: 4px;\n background: var(--hw-bg);\n}\n.hw-pane__error { color: var(--hw-error); font-size: 11px; margin-top: 4px; display: none; }\n.hw-pane__error--visible { display: block; }\n.hw-pane__prop-row { display: flex; gap: 8px; padding: 2px 0; }\n.hw-pane__prop-label { color: var(--hw-muted); width: 180px; }\n.hw-pane__prop-value { color: var(--hw-fg); }\n.hw-pane__placeholder { color: var(--hw-muted); font-style: italic; }\n\n.hw-pane__content.hw-pane__sequence, .hw-pane__content.hw-pane__notation {\n max-height: 100px;\n overflow: scroll;\n}\n\n.hw-modal-backdrop {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.3);\n display: flex; align-items: center; justify-content: center;\n z-index: 1000;\n}\n.hw-modal {\n background: var(--hw-bg);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 4px;\n min-width: 320px;\n max-width: 600px;\n padding: 12px;\n}\n.hw-modal__header { font-weight: bold; padding-bottom: 8px; border-bottom: 1px solid var(--hw-border); }\n.hw-modal__body { padding-top: 8px; }\n.hw-modal__row { display: flex; gap: 8px; align-items: center; padding: 4px 0; }\n.hw-modal__label { color: var(--hw-fg); min-width: 100px; }\n.hw-modal__input, .hw-modal__select {\n flex: 1;\n padding: 4px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n}\n.hw-modal__check { transform: scale(1.1); }\n.hw-modal__actions { display: flex; justify-content: flex-end; gap: 6px; padding-top: 10px; }\n.hw-modal__ok, .hw-modal__cancel, .hw-modal__find-next, .hw-modal__replace, .hw-modal__replace-all {\n padding: 4px 10px;\n border: 1px solid var(--hw-border);\n background: var(--hw-bg);\n color: var(--hw-fg);\n border-radius: 3px;\n cursor: pointer;\n}\n.hw-modal__ok { background: var(--hw-accent); color: #ffffff; border-color: var(--hw-accent); }\n.hw-modal__result { color: var(--hw-muted); font-size: 11px; padding-top: 6px; }\n\n/* Phase 23 (T-2304) -- Bond editor endpoint preview row. Renders two\n monomer structures (atom A1 and atom A2) flanking a `↔` arrow so the\n user can see what they\'re connecting while picking R-groups. The\n SVG inside each cell stretches via the .hw-bond-props__atom-rdkit\n svg rule below (matches the tooltip pattern). */\n.hw-bond-props__atoms {\n display: flex;\n align-items: center;\n gap: 16px;\n margin: 12px 0;\n}\n.hw-bond-props__atom {\n flex: 1;\n text-align: center;\n}\n.hw-bond-props__atom-label {\n font-weight: 600;\n margin-bottom: 6px;\n color: var(--hw-fg);\n}\n.hw-bond-props__atom-rdkit {\n width: 180px;\n height: 120px;\n margin: 0 auto 8px;\n background: #fafafa;\n border: 1px solid #f3f4f6;\n border-radius: 4px;\n padding: 4px;\n box-sizing: border-box;\n}\n.hw-bond-props__atom-rdkit svg {\n display: block;\n width: 100%;\n height: 100%;\n}\n.hw-bond-props__bond-arrow {\n font-size: 24px;\n color: var(--hw-muted);\n flex: 0 0 auto;\n}\n\n.hw-editor-view {\n width: 100%;\n height: 100%;\n position: relative;\n --hw-hover: #ff8c00;\n}\n.hw-editor-view svg { width: 100%; height: 100%; }\n\n/* T-1103 / Phase 19 (T-1901) -- Cursor affordance only. We removed\n the :hover rules that recoloured the atom\'s own outline because\n they ran in PARALLEL with the real highlight ring painted by the\n renderer (teal #26A69A), producing the wrong colour the user\n reported as "yellow on hover" (the CSS rule re-stroked the atom in\n var(--hw-hover) = #ff8c00, an orange-yellow). The renderer\'s\n highlight layer is now the single source of truth for hover\n feedback. */\n.hw-atom { cursor: pointer; }\n.hw-bond { cursor: pointer; }\n\n/* Mode-specific cursors on the canvas wrapper. The editor adds an\n hw-editor-view--<mode> class via the option:change handler. */\n.hw-editor-view--select svg { cursor: default; }\n.hw-editor-view--eraser svg { cursor: not-allowed; }\n.hw-editor-view--hbond svg { cursor: crosshair; }\n.hw-editor-view--move svg { cursor: grab; }\n.hw-editor-view--move:active svg { cursor: grabbing; }\n\n/* Phase 22 (T-2201) -- Unified tooltip styling. Three tooltip variants\n share the same look-and-feel: atom hover (canvas), bond hover\n (canvas), palette-tile hover (left pane), and rna-builder slot hover.\n Pre-Phase 22 the tooltips were absolutely-positioned, dark, and\n z-index 100 -- the gallery panel (z-index higher) ate into them and\n the dark background looked heavy. Phase 22 mounts the tooltip at\n `document.body` (escaping every parent stacking context), pins\n `z-index: 99999`, and paints them white with a soft drop shadow and\n darker body text so they read clearly over any backdrop. */\n/* Phase 32 (T-3003) -- Ghost cursor preview that follows the mouse\n when a palette tile is primed in select mode. `pointer-events:\n none` so the underlying canvas keeps receiving clicks / drags. The\n z-index sits just below the tooltips (99998 vs 99999) so a real\n tooltip can still overlay the ghost if both happen to be visible. */\n.hw-next-add-cursor {\n position: fixed;\n pointer-events: none;\n z-index: 99998;\n opacity: 0.7;\n display: none;\n}\n.hw-next-add-cursor__svg {\n display: block;\n}\n\n.hw-atom-tooltip,\n.hw-bond-tooltip,\n.hw-palette-tooltip,\n.hw-builder-tooltip,\n.hw-toolbar-tooltip {\n position: fixed;\n pointer-events: none;\n background: #ffffff;\n color: #1f2937;\n border: 1px solid #e5e7eb;\n border-radius: 6px;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12), 0 2px 4px rgba(0, 0, 0, 0.08);\n padding: 10px 12px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 12px;\n line-height: 1.4;\n max-width: 240px;\n z-index: 99999;\n}\n/* T-3516 -- toolbar button tooltip: a single compact line, no wrap. */\n.hw-toolbar-tooltip {\n padding: 5px 8px;\n white-space: nowrap;\n font-weight: 500;\n}\n.hw-tooltip__symbol {\n font-weight: 700;\n color: #111827;\n}\n/* T-3514 -- RNA triplet tooltip: three monomer structures side by side.\n Wider than the single-structure tooltip so all three columns fit. */\n.hw-triplet-tooltip { max-width: 420px; }\n.hw-tooltip__triplet {\n display: flex;\n gap: 8px;\n margin-top: 6px;\n}\n.hw-tooltip__triplet-part {\n flex: 1 1 0;\n min-width: 0;\n text-align: center;\n}\n.hw-tooltip__triplet-role {\n font-weight: 600;\n color: #111827;\n font-size: 11px;\n}\n.hw-tooltip__name {\n color: #4b5563;\n}\n.hw-tooltip__hint {\n color: #6b7280;\n font-style: italic;\n font-size: 11px;\n margin-top: 6px;\n}\n.hw-tooltip__rdkit {\n display: block;\n margin-top: 8px;\n /* padding-top: 8px; */\n border-top: 1px solid #f3f4f6;\n background: #fafafa;\n border-radius: 4px;\n}\n/* Phase 23 (T-2303) -- The user reported "molecules do not take the full\n space" in the tooltip. RDKit emits an svg with a `viewBox`, so\n `width: 100%; height: auto` lets the structure stretch responsively\n to whatever width the parent tooltip column has. `max-height` caps\n tall structures so they never blow up the tooltip vertically. */\n.hw-tooltip__rdkit svg,\n[data-testid="atom-tooltip-rdkit-svg"] svg,\n[data-testid="palette-tooltip-rdkit-svg"] svg,\n[data-testid="builder-tooltip-rdkit-svg"] svg {\n display: block;\n width: 100%;\n height: auto;\n max-height: 180px;\n margin: 0 auto;\n}\n/* Legacy aliases (kept so Phase 21 atom-tooltip text styling still\n resolves). The body text colour is now driven by the parent tooltip\n rule above; the legacy classes keep the line-wrap behaviour. */\n.hw-atom-tooltip__text {\n display: block;\n}\n\n/* Status indicator (T-1106) -- small badge in the bottom-left of the canvas. */\n.hw-status-bar {\n position: absolute;\n left: 6px;\n bottom: 6px;\n padding: 2px 8px;\n background: rgba(255, 255, 255, 0.85);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n font-size: 11px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n pointer-events: none;\n z-index: 50;\n}\n.hw-app--dark .hw-status-bar { background: rgba(34, 36, 41, 0.85); }\n\n.hw-status-bar__mode {\n display: inline-flex;\n align-items: center;\n gap: 0;\n}\n.hw-status-bar__message {\n display: inline-block;\n margin-left: 8px;\n font-weight: 500;\n}\n.hw-status-bar__message[data-severity="info"] { color: var(--hw-fg); }\n.hw-status-bar__message[data-severity="warn"] { color: #b8860b; }\n.hw-status-bar__message[data-severity="error"] { color: #c0392b; }\n.hw-app--dark .hw-status-bar__message[data-severity="warn"] { color: #f7c948; }\n.hw-app--dark .hw-status-bar__message[data-severity="error"] { color: #ff6b6b; }\n\n/* Phase 25 (T-2504) -- "Next add: X [x]" clear button. The status bar\n itself sets `pointer-events: none` (it floats above the canvas as a\n non-interactive badge), so the button explicitly re-enables hits on\n itself only. Visible only when `nextAdd` is primed because the\n element is conditionally appended in `_refreshStatus`. */\n.hw-status-bar__next-add-symbol {\n display: inline-block;\n font-weight: 600;\n}\n.hw-status-bar__next-add-clear {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 16px;\n height: 16px;\n margin-left: 6px;\n padding: 0;\n background: transparent;\n border: 1px solid #d1d5db;\n border-radius: 50%;\n color: #6b7280;\n font-size: 12px;\n line-height: 1;\n cursor: pointer;\n pointer-events: auto;\n}\n.hw-status-bar__next-add-clear:hover {\n background: #f3f4f6;\n color: #1f2937;\n border-color: #9ca3af;\n}\n\n.hw-bond-preview { pointer-events: none; opacity: 0.85; }\n\n.hw-help-modal-backdrop {\n position: fixed; left: 0; top: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.4);\n display: flex; align-items: center; justify-content: center;\n z-index: 2000;\n}\n.hw-help-modal {\n background: #ffffff;\n color: #1a1a1a;\n padding: 16px 20px;\n border-radius: 4px;\n max-width: 480px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-shadow: 0 10px 20px rgba(0,0,0,0.3);\n}\n.hw-help-modal h2 { margin: 0 0 8px 0; font-size: 16px; }\n.hw-help-modal ul { padding-left: 20px; line-height: 1.6; }\n.hw-help-modal kbd {\n background: #eef0f3;\n border: 1px solid #cbd0d6;\n border-radius: 3px;\n padding: 1px 4px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 12px;\n}\n.hw-help-modal__close {\n margin-top: 12px;\n padding: 4px 12px;\n border: 1px solid #cbd0d6;\n background: #f5f6f8;\n cursor: pointer;\n border-radius: 3px;\n}\n'],sourceRoot:""}]);const a=s},314(e){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var i="",n=void 0!==t[5];return t[4]&&(i+="@supports (".concat(t[4],") {")),t[2]&&(i+="@media ".concat(t[2]," {")),n&&(i+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),i+=e(t),n&&(i+="}"),t[2]&&(i+="}"),t[4]&&(i+="}"),i}).join("")},t.i=function(e,i,n,o,r){"string"==typeof e&&(e=[[null,e,void 0]]);var s={};if(n)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(s[l]=!0)}for(var h=0;h<e.length;h++){var d=[].concat(e[h]);n&&s[d[0]]||(void 0!==r&&(void 0===d[5]||(d[1]="@layer".concat(d[5].length>0?" ".concat(d[5]):""," {").concat(d[1],"}")),d[5]=r),i&&(d[2]?(d[1]="@media ".concat(d[2]," {").concat(d[1],"}"),d[2]=i):d[2]=i),o&&(d[4]?(d[1]="@supports (".concat(d[4],") {").concat(d[1],"}"),d[4]=o):d[4]="".concat(o)),t.push(d))}},t}},354(e){"use strict";e.exports=function(e){var t=e[1],i=e[3];if(!i)return t;if("function"==typeof btoa){var n=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),o="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(n),r="/*# ".concat(o," */");return[t].concat([r]).join("\n")}return[t].join("\n")}},982(e,t,i){var n;!function(){var t={};!function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,i,n,o,r){for(var s,a,l,h,d,c,u,p,m,f,b,g,A;r>=64;){for(s=i[0],a=i[1],l=i[2],h=i[3],d=i[4],c=i[5],u=i[6],p=i[7],f=0;f<16;f++)b=o+4*f,e[f]=(255&n[b])<<24|(255&n[b+1])<<16|(255&n[b+2])<<8|255&n[b+3];for(f=16;f<64;f++)g=((m=e[f-2])>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,A=((m=e[f-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,e[f]=(g+e[f-7]|0)+(A+e[f-16]|0);for(f=0;f<64;f++)g=(((d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7))+(d&c^~d&u)|0)+(p+(t[f]+e[f]|0)|0)|0,A=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&a^s&l^a&l)|0,p=u,u=c,c=d,d=h+g|0,h=l,l=a,a=s,s=g+A|0;i[0]+=s,i[1]+=a,i[2]+=l,i[3]+=h,i[4]+=d,i[5]+=c,i[6]+=u,i[7]+=p,o+=64,r-=64}return o}var n=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[n++],t--;64===this.bufferLength&&(i(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(n=i(this.temp,this.state,e,n,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[n++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,n=this.bufferLength,o=t/536870912|0,r=t<<3,s=t%64<56?64:128;this.buffer[n]=128;for(var a=n+1;a<s-8;a++)this.buffer[a]=0;this.buffer[s-8]=o>>>24&255,this.buffer[s-7]=o>>>16&255,this.buffer[s-6]=o>>>8&255,this.buffer[s-5]=o>>>0&255,this.buffer[s-4]=r>>>24&255,this.buffer[s-3]=r>>>16&255,this.buffer[s-2]=r>>>8&255,this.buffer[s-1]=r>>>0&255,i(this.temp,this.state,this.buffer,0,s),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var i=0;i<this.state.length;i++)this.state[i]=e[i];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=n;var o=function(){function e(e){this.inner=new n,this.outer=new n,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new n).update(e).finish(t).clean();else for(var i=0;i<e.length;i++)t[i]=e[i];for(i=0;i<t.length;i++)t[i]^=54;for(this.inner.update(t),i=0;i<t.length;i++)t[i]^=106;for(this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),i=0;i<t.length;i++)t[i]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function r(e){var t=(new n).update(e),i=t.digest();return t.clean(),i}function s(e,t){var i=new o(e).update(t),n=i.digest();return i.clean(),n}function a(e,t,i,n){var o=n[0];if(0===o)throw new Error("hkdf: cannot expand more");t.reset(),o>1&&t.update(e),i&&t.update(i),t.update(n),t.finish(e),n[0]++}e.HMAC=o,e.hash=r,e.default=r,e.hmac=s;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,i,n){void 0===t&&(t=l),void 0===n&&(n=32);for(var r=new Uint8Array([1]),h=s(t,e),d=new o(h),c=new Uint8Array(d.digestLength),u=c.length,p=new Uint8Array(n),m=0;m<n;m++)u===c.length&&(a(c,d,i,r),u=0),p[m]=c[u++];return d.clean(),c.fill(0),r.fill(0),p},e.pbkdf2=function(e,t,i,n){for(var r=new o(e),s=r.digestLength,a=new Uint8Array(4),l=new Uint8Array(s),h=new Uint8Array(s),d=new Uint8Array(n),c=0;c*s<n;c++){var u=c+1;a[0]=u>>>24&255,a[1]=u>>>16&255,a[2]=u>>>8&255,a[3]=u>>>0&255,r.reset(),r.update(t),r.update(a),r.finish(h);for(var p=0;p<s;p++)l[p]=h[p];for(p=2;p<=i;p++){r.reset(),r.update(h).finish(h);for(var m=0;m<s;m++)l[m]^=h[m]}for(p=0;p<s&&c*s+p<n;p++)d[c*s+p]=l[p]}for(c=0;c<s;c++)l[c]=h[c]=0;for(c=0;c<4;c++)a[c]=0;return r.clean(),d}}(t);var o=t.default;for(var r in t)o[r]=t[r];"object"==typeof e.exports?e.exports=o:void 0===(n=function(){return o}.call(t,i,t,e))||(e.exports=n)}()},72(e){"use strict";var t=[];function i(e){for(var i=-1,n=0;n<t.length;n++)if(t[n].identifier===e){i=n;break}return i}function n(e,n){for(var r={},s=[],a=0;a<e.length;a++){var l=e[a],h=n.base?l[0]+n.base:l[0],d=r[h]||0,c="".concat(h," ").concat(d);r[h]=d+1;var u=i(c),p={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==u)t[u].references++,t[u].updater(p);else{var m=o(p,n);n.byIndex=a,t.splice(a,0,{identifier:c,updater:m,references:1})}s.push(c)}return s}function o(e,t){var i=t.domAPI(t);return i.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;i.update(e=t)}else i.remove()}}e.exports=function(e,o){var r=n(e=e||[],o=o||{});return function(e){e=e||[];for(var s=0;s<r.length;s++){var a=i(r[s]);t[a].references--}for(var l=n(e,o),h=0;h<r.length;h++){var d=i(r[h]);0===t[d].references&&(t[d].updater(),t.splice(d,1))}r=l}}},659(e){"use strict";var t={};e.exports=function(e,i){var n=function(e){if(void 0===t[e]){var i=document.querySelector(e);if(window.HTMLIFrameElement&&i instanceof window.HTMLIFrameElement)try{i=i.contentDocument.head}catch(e){i=null}t[e]=i}return t[e]}(e);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");n.appendChild(i)}},540(e){"use strict";e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},56(e,t,i){"use strict";e.exports=function(e){var t=i.nc;t&&e.setAttribute("nonce",t)}},825(e){"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(i){!function(e,t,i){var n="";i.supports&&(n+="@supports (".concat(i.supports,") {")),i.media&&(n+="@media ".concat(i.media," {"));var o=void 0!==i.layer;o&&(n+="@layer".concat(i.layer.length>0?" ".concat(i.layer):""," {")),n+=i.css,o&&(n+="}"),i.media&&(n+="}"),i.supports&&(n+="}");var r=i.sourceMap;r&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),t.styleTagTransform(n,e,t.options)}(t,e,i)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},113(e){"use strict";e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}}},t={};function i(n){var o=t[n];if(void 0!==o)return o.exports;var r=t[n]={id:n,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.exports}i.m=e,i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.u=e=>e+".js",i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;i.g.importScripts&&(e=i.g.location+"");var t=i.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var o=n.length-1;o>-1&&(!e||!/^http(s?):/.test(e));)e=n[o--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),i.p=e})(),i.b="undefined"!=typeof document&&document.baseURI||self.location.href,i.nc=void 0;var n={};(()=>{"use strict";i.r(n),i.d(n,{PackageFunctions:()=>ps,_package:()=>ds,editMoleculeCell:()=>Jr,getHelmHelper:()=>os,getMolfiles:()=>is,helmCellRenderer:()=>Zr,helmInput:()=>ns,highlightMonomers:()=>ss,initHelm:()=>Qr,measureCellRenderer:()=>rs,openEditor:()=>es,propertiesWidget:()=>ts});const e=grok,t=ui,o=DG,r=$;var s=i.n(r);i(982),DG.DataFrame.fromCsv('countries,fasta,smiles,molregno,LON,Zip Code,Street Address Line 1,ImageUrl,user_id,error_message,xray,flag,magnitude,CS-id,pdb_id,accel_a,time_offset,chart,fit,Questions,empty_number,empty_string\nBelgium,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C(=O)OCCCc1cccnc1)c2cccc(c2)C(=O)c3ccccc3,1480014,36.276729583740234,995042300,14016 ROUTE 31W,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,1,1,1QBS,1,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.497360340644872, 1.7058694986686864, 5.278052678195135, 0.16000320889028383],""points"":[{""x"":0.10000000149011612,""y"":2.374499797821045},{""x"":0.6000000238418579,""y"":2.6242473125457764},{""x"":1.100000023841858,""y"":2.367267608642578},{""x"":1.600000023841858,""y"":2.6723148822784424},{""x"":2.0999999046325684,""y"":2.6537344455718994},{""x"":2.5999999046325684,""y"":2.3651671409606934},{""x"":3.0999999046325684,""y"":2.5654284954071045},{""x"":3.5999999046325684,""y"":2.4160959720611572},{""x"":4.099999904632568,""y"":2.286726713180542},{""x"":4.599999904632568,""y"":2.5100042819976807},{""x"":5.099999904632568,""y"":1.6676985025405884},{""x"":5.599999904632568,""y"":0.680136501789093},{""x"":6.099999904632568,""y"":0.3391543924808502},{""x"":6.599999904632568,""y"":0.09038983285427094},{""x"":7.099999904632568,""y"":0.19802775979042053}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[7.525235855508179, 1.3186911876809984, 5.335672608564294, 0.7860743343958098],""points"":[{""x"":0.10000000149011612,""y"":7.988070487976074},{""x"":0.6000000238418579,""y"":7.018453121185303},{""x"":1.100000023841858,""y"":8.115279197692871},{""x"":1.600000023841858,""y"":7.486658096313477},{""x"":2.0999999046325684,""y"":7.396438121795654},{""x"":2.5999999046325684,""y"":7.477052211761475},{""x"":3.0999999046325684,""y"":6.913095474243164},{""x"":3.5999999046325684,""y"":8.01385498046875},{""x"":4.099999904632568,""y"":6.985900402069092},{""x"":4.599999904632568,""y"":6.970335960388184},{""x"":5.099999904632568,""y"":5.448817253112793},{""x"":5.599999904632568,""y"":2.5534818172454834},{""x"":6.099999904632568,""y"":1.893947958946228},{""x"":6.599999904632568,""y"":0.6340042352676392},{""x"":7.099999904632568,""y"":0.8403874039649963}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,100,abc\nBurundi,MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW,COc1ccc2cc(ccc2c1)C(C)C(=O)Oc3ccc(C)cc3OC,1480015,36.276729583740234,995073444,80 STATE HIGHWAY 310,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,2,2,1ZP8,2,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.431460753103398, 2.1691498799246745, 5.266445597102774, 0.7825762827017926],""points"":[{""x"":0.10000000149011612,""y"":4.751083850860596},{""x"":0.6000000238418579,""y"":4.203000068664551},{""x"":1.100000023841858,""y"":4.415858745574951},{""x"":1.600000023841858,""y"":4.68414306640625},{""x"":2.0999999046325684,""y"":4.198400974273682},{""x"":2.5999999046325684,""y"":4.179222106933594},{""x"":3.0999999046325684,""y"":4.638473987579346},{""x"":3.5999999046325684,""y"":4.708553314208984},{""x"":4.099999904632568,""y"":4.291589260101318},{""x"":4.599999904632568,""y"":4.038082599639893},{""x"":5.099999904632568,""y"":3.4349939823150635},{""x"":5.599999904632568,""y"":1.2194708585739136},{""x"":6.099999904632568,""y"":1.1920831203460693},{""x"":6.599999904632568,""y"":0.5352635979652405},{""x"":7.099999904632568,""y"":0.3346920311450958}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.339458017970126, -1.0734184310171178, 4.746332950550934, 0.2482416857595658],""points"":[{""x"":0.10000000149011612,""y"":0.2139337658882141},{""x"":0.6000000238418579,""y"":0.4269562065601349},{""x"":1.100000023841858,""y"":0.2441573292016983},{""x"":1.600000023841858,""y"":0.146635964512825},{""x"":2.0999999046325684,""y"":0.08818462491035461},{""x"":2.5999999046325684,""y"":0.2560656666755676},{""x"":3.0999999046325684,""y"":0.42434045672416687},{""x"":3.5999999046325684,""y"":0.37111231684684753},{""x"":4.099999904632568,""y"":0.5581737160682678},{""x"":4.599999904632568,""y"":1.183590054512024},{""x"":5.099999904632568,""y"":1.5629843473434448},{""x"":5.599999904632568,""y"":2.3211288452148438},{""x"":6.099999904632568,""y"":2.229961633682251},{""x"":6.599999904632568,""y"":2.2560226917266846},{""x"":7.099999904632568,""y"":2.2142398357391357}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCameroon,MIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL,COc1ccc2cc(ccc2c1)C(C)C(=O)OCCCc3cccnc3,1480016,36.26095962524414,995153596,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,3,3,2BDJ,3,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.6760652578642325, 0.9046956320756703, 5.651408971856738, 0.07738846012184185],""points"":[{""x"":0.10000000149011612,""y"":4.32425594329834},{""x"":0.6000000238418579,""y"":4.668442249298096},{""x"":1.100000023841858,""y"":4.379785060882568},{""x"":1.600000023841858,""y"":5.0345139503479},{""x"":2.0999999046325684,""y"":4.878653526306152},{""x"":2.5999999046325684,""y"":4.3451313972473145},{""x"":3.0999999046325684,""y"":4.336992263793945},{""x"":3.5999999046325684,""y"":5.037430286407471},{""x"":4.099999904632568,""y"":5.0092692375183105},{""x"":4.599999904632568,""y"":4.151902675628662},{""x"":5.099999904632568,""y"":3.4066951274871826},{""x"":5.599999904632568,""y"":2.3732759952545166},{""x"":6.099999904632568,""y"":1.673728108406067},{""x"":6.599999904632568,""y"":0.48574790358543396},{""x"":7.099999904632568,""y"":0.2783052325248718}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.938395863010111, -1.4658480661392117, 5.462702751996584, 0.3473139023615039],""points"":[{""x"":0.10000000149011612,""y"":0.4941710829734802},{""x"":0.6000000238418579,""y"":0.15323974192142487},{""x"":1.100000023841858,""y"":0.46373432874679565},{""x"":1.600000023841858,""y"":0.3370431363582611},{""x"":2.0999999046325684,""y"":0.5179030299186707},{""x"":2.5999999046325684,""y"":0.27899765968322754},{""x"":3.0999999046325684,""y"":0.22075064480304718},{""x"":3.5999999046325684,""y"":0.5789918899536133},{""x"":4.099999904632568,""y"":0.21169911324977875},{""x"":4.599999904632568,""y"":0.27857646346092224},{""x"":5.099999904632568,""y"":1.0906332731246948},{""x"":5.599999904632568,""y"":1.8520300388336182},{""x"":6.099999904632568,""y"":2.7177059650421143},{""x"":6.599999904632568,""y"":2.8680918216705322},{""x"":7.099999904632568,""y"":3.2413077354431152}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCanada,MMELVLKTIIGPIVVGVVLRIVDKWLNKDK,CC(C(=O)NCCS)c1cccc(c1)C(=O)c2ccccc2,1480017,36.26095962524414,99515,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,4,4,1IAN,4,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[0.8597390975430008, 1.0957625732481946, 5.260537067987958, 0.07974187998177736],""points"":[{""x"":0.10000000149011612,""y"":0.8190152645111084},{""x"":0.6000000238418579,""y"":0.8421689867973328},{""x"":1.100000023841858,""y"":0.8740922212600708},{""x"":1.600000023841858,""y"":0.8924275040626526},{""x"":2.0999999046325684,""y"":0.8249067664146423},{""x"":2.5999999046325684,""y"":0.9327669143676758},{""x"":3.0999999046325684,""y"":0.8522974252700806},{""x"":3.5999999046325684,""y"":0.8174492716789246},{""x"":4.099999904632568,""y"":0.8394647240638733},{""x"":4.599999904632568,""y"":0.7139387726783752},{""x"":5.099999904632568,""y"":0.5561167597770691},{""x"":5.599999904632568,""y"":0.3276226818561554},{""x"":6.099999904632568,""y"":0.12479474395513535},{""x"":6.599999904632568,""y"":0.13006797432899475},{""x"":7.099999904632568,""y"":0.059702079743146896}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.760930219582546, 1.6591793293833013, 4.667155929720851, 0.7858109544121652],""points"":[{""x"":0.10000000149011612,""y"":6.156993389129639},{""x"":0.6000000238418579,""y"":5.236701965332031},{""x"":1.100000023841858,""y"":6.010560512542725},{""x"":1.600000023841858,""y"":5.495512962341309},{""x"":2.0999999046325684,""y"":6.087770462036133},{""x"":2.5999999046325684,""y"":5.79986572265625},{""x"":3.0999999046325684,""y"":5.597546577453613},{""x"":3.5999999046325684,""y"":5.520902156829834},{""x"":4.099999904632568,""y"":5.360654354095459},{""x"":4.599999904632568,""y"":3.5539746284484863},{""x"":5.099999904632568,""y"":1.577236294746399},{""x"":5.599999904632568,""y"":1.0001264810562134},{""x"":6.099999904632568,""y"":0.9305797815322876},{""x"":6.599999904632568,""y"":0.6033638715744019},{""x"":7.099999904632568,""y"":0.4203685522079468}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nColombia,MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN,FC(F)(F)c1ccc(OC2CCNCC2)cc1,1480029,36.3309440612793,995152050,1 COURT HOUSE SQUARE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,5,5,4UJ1,5,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[6.4995088314153655, 2.4270351004539914, 5.178659535348579, 0.625653346241577],""points"":[{""x"":0.10000000149011612,""y"":6.496231555938721},{""x"":0.6000000238418579,""y"":6.42543363571167},{""x"":1.100000023841858,""y"":7.040063858032227},{""x"":1.600000023841858,""y"":6.1115403175354},{""x"":2.0999999046325684,""y"":6.680728435516357},{""x"":2.5999999046325684,""y"":6.406774520874023},{""x"":3.0999999046325684,""y"":6.611269474029541},{""x"":3.5999999046325684,""y"":5.889094352722168},{""x"":4.099999904632568,""y"":6.75344705581665},{""x"":4.599999904632568,""y"":6.361435890197754},{""x"":5.099999904632568,""y"":4.1666975021362305},{""x"":5.599999904632568,""y"":1.172118902206421},{""x"":6.099999904632568,""y"":0.801048994064331},{""x"":6.599999904632568,""y"":0.4640021026134491},{""x"":7.099999904632568,""y"":0.0010357667924836278}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[1.4734381347446401, 1.1649805188074196, 4.82958608866421, 0.09500545496710007],""points"":[{""x"":0.10000000149011612,""y"":1.5279096364974976},{""x"":0.6000000238418579,""y"":1.3559974431991577},{""x"":1.100000023841858,""y"":1.5246378183364868},{""x"":1.600000023841858,""y"":1.5567657947540283},{""x"":2.0999999046325684,""y"":1.4114240407943726},{""x"":2.5999999046325684,""y"":1.4045010805130005},{""x"":3.0999999046325684,""y"":1.4769829511642456},{""x"":3.5999999046325684,""y"":1.4875500202178955},{""x"":4.099999904632568,""y"":1.2991987466812134},{""x"":4.599999904632568,""y"":0.922961413860321},{""x"":5.099999904632568,""y"":0.6520044803619385},{""x"":5.599999904632568,""y"":0.15350978076457977},{""x"":6.099999904632568,""y"":0.1078903079032898},{""x"":6.599999904632568,""y"":0.17276449501514435},{""x"":7.099999904632568,""y"":0.14066608250141144}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCosta Rica,MKSTKEEIQTIKTLLKDSRTAKYHKRLQIVL,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCCc3ccccc3,1480018,36.3309440612793,995084218,4041 SOUTHWESTERN BLVD,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,6,6,2BPW,6,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.4833641843311227, -1.8945978742090062, 4.671127708092568, 0.24159861311815153],""points"":[{""x"":0.10000000149011612,""y"":0.0969524160027504},{""x"":0.6000000238418579,""y"":0.028483040630817413},{""x"":1.100000023841858,""y"":0.22087176144123077},{""x"":1.600000023841858,""y"":0.0068915546871721745},{""x"":2.0999999046325684,""y"":0.4305879771709442},{""x"":2.5999999046325684,""y"":0.44774115085601807},{""x"":3.0999999046325684,""y"":0.45346319675445557},{""x"":3.5999999046325684,""y"":0.2370593100786209},{""x"":4.099999904632568,""y"":0.4657953977584839},{""x"":4.599999904632568,""y"":1.155200719833374},{""x"":5.099999904632568,""y"":2.2294070720672607},{""x"":5.599999904632568,""y"":2.4311530590057373},{""x"":6.099999904632568,""y"":2.33846116065979},{""x"":6.599999904632568,""y"":2.608201026916504},{""x"":7.099999904632568,""y"":2.8136143684387207}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.224573521642033, 1.4454033924198528, 5.6014197746076535, 0.2823216054197577],""points"":[{""x"":0.10000000149011612,""y"":4.95027494430542},{""x"":0.6000000238418579,""y"":5.1754679679870605},{""x"":1.100000023841858,""y"":5.276752948760986},{""x"":1.600000023841858,""y"":5.589294910430908},{""x"":2.0999999046325684,""y"":5.616994857788086},{""x"":2.5999999046325684,""y"":5.120813846588135},{""x"":3.0999999046325684,""y"":5.340766906738281},{""x"":3.5999999046325684,""y"":4.876471042633057},{""x"":4.099999904632568,""y"":4.94999361038208},{""x"":4.599999904632568,""y"":5.162564754486084},{""x"":5.099999904632568,""y"":4.399557590484619},{""x"":5.599999904632568,""y"":2.7977969646453857},{""x"":6.099999904632568,""y"":1.0229872465133667},{""x"":6.599999904632568,""y"":0.48275601863861084},{""x"":7.099999904632568,""y"":0.10408931970596313}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCuba,MHAILRYFIRRLFYHIFYKIYSLISKKHQSLPSDVRQF,COc1ccc2c(c1)c(CC(=O)N3CCCC3C(=O)Oc4ccc(C)cc4OC)c(C)n2C(=O)c5ccc(Cl)cc5,1480019,36.33115768432617,995081928,1227 US HIGHWAY 11,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,7,7,1QBS,7,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.320838679713925, -1.2421619987316728, 4.831325425225256, 0.3236011098403072],""points"":[{""x"":0.10000000149011612,""y"":0.3727470338344574},{""x"":0.6000000238418579,""y"":0.12365014106035233},{""x"":1.100000023841858,""y"":0.48422467708587646},{""x"":1.600000023841858,""y"":0.2264465093612671},{""x"":2.0999999046325684,""y"":0.16821794211864471},{""x"":2.5999999046325684,""y"":0.3879014551639557},{""x"":3.0999999046325684,""y"":0.5470244884490967},{""x"":3.5999999046325684,""y"":0.3419053554534912},{""x"":4.099999904632568,""y"":0.7655120491981506},{""x"":4.599999904632568,""y"":1.2346516847610474},{""x"":5.099999904632568,""y"":2.453336715698242},{""x"":5.599999904632568,""y"":2.9565491676330566},{""x"":6.099999904632568,""y"":3.335299491882324},{""x"":6.599999904632568,""y"":3.240290880203247},{""x"":7.099999904632568,""y"":3.1107218265533447}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.6401853521511094, 1.26211588875013, 5.399028074402744, 0.5089580830068091],""points"":[{""x"":0.10000000149011612,""y"":3.8585598468780518},{""x"":0.6000000238418579,""y"":3.6077206134796143},{""x"":1.100000023841858,""y"":3.855252265930176},{""x"":1.600000023841858,""y"":3.619039297103882},{""x"":2.0999999046325684,""y"":3.839388370513916},{""x"":2.5999999046325684,""y"":3.335283041000366},{""x"":3.0999999046325684,""y"":3.571141481399536},{""x"":3.5999999046325684,""y"":3.4155046939849854},{""x"":4.099999904632568,""y"":3.7316646575927734},{""x"":4.599999904632568,""y"":3.0680155754089355},{""x"":5.099999904632568,""y"":2.891066551208496},{""x"":5.599999904632568,""y"":1.6022753715515137},{""x"":6.099999904632568,""y"":0.7652576565742493},{""x"":6.599999904632568,""y"":0.6875326037406921},{""x"":7.099999904632568,""y"":0.5828871726989746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nItaly,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO[N+](=O)[O-],1480020,36.33115768432617,99502,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,8,8,1ZP8,8,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.293592105923809, 1.3781586549141835, 5.1025898038676605, 0.03493851245291291],""points"":[{""x"":0.10000000149011612,""y"":2.1287283897399902},{""x"":0.6000000238418579,""y"":2.267972230911255},{""x"":1.100000023841858,""y"":2.398442506790161},{""x"":1.600000023841858,""y"":2.5130622386932373},{""x"":2.0999999046325684,""y"":2.3255116939544678},{""x"":2.5999999046325684,""y"":2.127340793609619},{""x"":3.0999999046325684,""y"":2.47259783744812},{""x"":3.5999999046325684,""y"":2.131181478500366},{""x"":4.099999904632568,""y"":2.090421438217163},{""x"":4.599999904632568,""y"":2.02299165725708},{""x"":5.099999904632568,""y"":1.1105059385299683},{""x"":5.599999904632568,""y"":0.4494485855102539},{""x"":6.099999904632568,""y"":0.1375635862350464},{""x"":6.599999904632568,""y"":0.036351121962070465},{""x"":7.099999904632568,""y"":0.1619771122932434}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.953125499439879, 1.2528620255306528, 5.187637440149802, 0.3110348753260886],""points"":[{""x"":0.10000000149011612,""y"":5.6585283279418945},{""x"":0.6000000238418579,""y"":5.911152362823486},{""x"":1.100000023841858,""y"":5.924920082092285},{""x"":1.600000023841858,""y"":5.8469438552856445},{""x"":2.0999999046325684,""y"":5.929472923278809},{""x"":2.5999999046325684,""y"":6.190037727355957},{""x"":3.0999999046325684,""y"":6.236179828643799},{""x"":3.5999999046325684,""y"":6.141019344329834},{""x"":4.099999904632568,""y"":5.295210838317871},{""x"":4.599999904632568,""y"":5.265801906585693},{""x"":5.099999904632568,""y"":3.3722851276397705},{""x"":5.599999904632568,""y"":1.8299226760864258},{""x"":6.099999904632568,""y"":0.32690900564193726},{""x"":6.599999904632568,""y"":0.6274543404579163},{""x"":7.099999904632568,""y"":0.8441857099533081}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nRwanda,MPNSEPASLLELFNSIATQGELVRSLKAGNASK,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO,1480021,36.33137130737305,995037247,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,9,2BDJ,9,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.8209972202654474, 1.3779216716448506, 5.299882228439686, 0.06040645519069608],""points"":[{""x"":0.10000000149011612,""y"":3.7821109294891357},{""x"":0.6000000238418579,""y"":3.542433023452759},{""x"":1.100000023841858,""y"":3.7008674144744873},{""x"":1.600000023841858,""y"":3.717301607131958},{""x"":2.0999999046325684,""y"":4.024452209472656},{""x"":2.5999999046325684,""y"":4.013899326324463},{""x"":3.0999999046325684,""y"":3.945094347000122},{""x"":3.5999999046325684,""y"":3.866621971130371},{""x"":4.099999904632568,""y"":3.7461626529693604},{""x"":4.599999904632568,""y"":3.3454740047454834},{""x"":5.099999904632568,""y"":2.61944317817688},{""x"":5.599999904632568,""y"":0.999405026435852},{""x"":6.099999904632568,""y"":0.46259793639183044},{""x"":6.599999904632568,""y"":0.054134611040353775},{""x"":7.099999904632568,""y"":0.05711187422275543}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.6318079657726035, 1.8495493770000595, 5.391793312471116, 0.17060707587348442],""points"":[{""x"":0.10000000149011612,""y"":5.458079814910889},{""x"":0.6000000238418579,""y"":5.554427146911621},{""x"":1.100000023841858,""y"":5.799983024597168},{""x"":1.600000023841858,""y"":5.364140033721924},{""x"":2.0999999046325684,""y"":5.864485740661621},{""x"":2.5999999046325684,""y"":5.4509806632995605},{""x"":3.0999999046325684,""y"":5.702574729919434},{""x"":3.5999999046325684,""y"":5.7314534187316895},{""x"":4.099999904632568,""y"":5.5123443603515625},{""x"":4.599999904632568,""y"":5.724395751953125},{""x"":5.099999904632568,""y"":4.354506969451904},{""x"":5.599999904632568,""y"":1.7307666540145874},{""x"":6.099999904632568,""y"":0.6305936574935913},{""x"":6.599999904632568,""y"":0.035183437168598175},{""x"":7.099999904632568,""y"":0.7575169205665588}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nSwitzerland,IRVVGRYLIEVWKAAGMDMDKVLFLWSSDEI,CN1CCC(CC1)Oc2ccc(cc2)C(F)(F)F,1480028,36.33137130737305,99504,92-11 179TH PLACE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,10,1IAN,10,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[1.1190255865097471, 2.3163895161544437, 5.4968866182279195, 0.2035204047289052],""points"":[{""x"":0.10000000149011612,""y"":1.1057683229446411},{""x"":0.6000000238418579,""y"":1.1019697189331055},{""x"":1.100000023841858,""y"":1.0818607807159424},{""x"":1.600000023841858,""y"":1.062997817993164},{""x"":2.0999999046325684,""y"":1.046447515487671},{""x"":2.5999999046325684,""y"":1.1217249631881714},{""x"":3.0999999046325684,""y"":1.2166996002197266},{""x"":3.5999999046325684,""y"":1.215477705001831},{""x"":4.099999904632568,""y"":1.0581893920898438},{""x"":4.599999904632568,""y"":1.1747995615005493},{""x"":5.099999904632568,""y"":1.0181127786636353},{""x"":5.599999904632568,""y"":0.5344523191452026},{""x"":6.099999904632568,""y"":0.2569526433944702},{""x"":6.599999904632568,""y"":0.1912207305431366},{""x"":7.099999904632568,""y"":0.15060538053512573}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.1038581025805785, 2.0032224204185245, 5.087602825989163, 0.13277988512492753],""points"":[{""x"":0.10000000149011612,""y"":3.0498509407043457},{""x"":0.6000000238418579,""y"":2.805217742919922},{""x"":1.100000023841858,""y"":3.3415253162384033},{""x"":1.600000023841858,""y"":3.0549843311309814},{""x"":2.0999999046325684,""y"":3.250074863433838},{""x"":2.5999999046325684,""y"":3.0432586669921875},{""x"":3.0999999046325684,""y"":3.265852451324463},{""x"":3.5999999046325684,""y"":2.9475724697113037},{""x"":4.099999904632568,""y"":3.1929898262023926},{""x"":4.599999904632568,""y"":2.7460060119628906},{""x"":5.099999904632568,""y"":1.6175861358642578},{""x"":5.599999904632568,""y"":0.3006608486175537},{""x"":6.099999904632568,""y"":0.3444803059101105},{""x"":6.599999904632568,""y"":0.015537971630692482},{""x"":7.099999904632568,""y"":0.5527358055114746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\n,,,,,,,,,,,,,,,,,,,,,').columns.add(DG.Column.fromList(DG.TYPE.BYTE_ARRAY,"BinaryImage",Array.from(new Uint8Array(11))));var a,l,h,d;function c(e,t,i,n=0,o="timeout"){return function(e,t,i,n){return new(i||(i=Promise))(function(o,r){function s(e){try{l(n.next(e))}catch(e){r(e)}}function a(e){try{l(n.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,a)}l((n=n.apply(e,t||[])).next())})}(this,void 0,void 0,function*(){return new Promise((r,s)=>{const a=e.subscribe(e=>{try{t(e),r("OK")}catch(e){s(e)}finally{a.unsubscribe(),clearTimeout(l)}}),l=setTimeout(()=>{a.unsubscribe(),s(o)},n);i()})})}function u(e){return"string"==typeof e||e instanceof String?e:"StateError"===e.constructor.name?e.message:"StateError"===e.constructor.name&&"$thrownJsError"in e?u(e.$thrownJsError):e instanceof Error?e.message:e.toString()}function p(e){return e instanceof Error?e.stack:"StateError"===e.constructor.name&&"$thrownJsError"in e?p(e.$thrownJsError):void 0}function m(e){return[u(e),p(e)]}console.log.bind(console),console.info.bind(console),console.warn.bind(console),console.error.bind(console),function(e){e.notNull=function(e,t){if(null==e)throw new Error(`${t??"Value"} not defined`)}}(a||(a={})),DG.DataFrame.fromColumns([DG.Column.fromStrings("col",["val1","val2","val3"])]);class f{constructor(e,t,i){this.name=e,this.alphabet=t,this.cutoff=i}}!function(e){e.FASTA="fasta",e.SEPARATOR="separator",e.HELM="helm",e.CUSTOM="custom",e.BILN="biln"}(l||(l={})),function(e){e.DNA="DNA",e.RNA="RNA",e.PT="PT",e.UN="UN"}(h||(h={})),function(e){e.aligned="aligned",e.alphabet="alphabet",e.alphabetSize=".alphabetSize",e.alphabetIsMultichar=".alphabetIsMultichar",e.separator="separator",e.isHelmCompatible=".isHelmCompatible",e.positionNames=".positionNames",e.positionLabels=".positionLabels",e.regions=".regions",e.positionShift=".positionShift",e.selectedPosition=".selectedPosition",e.polymerTypeColumnName=".polymerTypeColumnName",e.annotations=".annotations",e.numberingScheme=".numberingScheme",e.annotationColumnName=".annotationColumnName"}(d||(d={}));const b=new class{constructor(){this.fasta={peptide:new Set(["G","L","Y","S","E","Q","D","N","F","A","K","R","H","C","V","P","W","I","M","T"]),dna:new Set(["A","C","G","T"]),rna:new Set(["A","C","G","U"])}}};new f(h.PT,b.fasta.peptide,.5),new f(h.DNA,b.fasta.dna,.55),new f(h.RNA,b.fasta.rna,.55),l.FASTA,l.SEPARATOR,l.HELM,l.BILN,wu;class g{static makePalette(e,t=!1,i=g){const n={};return e.forEach(e=>{const i=e[0],o=e[1];i.forEach((e,i)=>{n[e]=this.colourPalette[o][t?0:i]})}),new i(n)}constructor(e){this._palette=e}get(e,t){return this._palette[e]}}g.undefinedColor="rgb(100,100,100)",g.colourPalette={orange:["rgb(255,187,120)","rgb(245,167,100)","rgb(235,137,70)","rgb(205, 111, 71)"],all_green:["rgb(44,160,44)","rgb(74,160,74)","rgb(23,103,57)","rgb(30,110,96)","rgb(60,131,95)","rgb(24,110,79)","rgb(152,223,138)","rgb(182, 223, 138)","rgb(152, 193, 138)"],all_blue:["rgb(31,119,180)","rgb(23,190,207)","rgb(122, 102, 189)","rgb(158,218,229)","rgb(141, 124, 217)","rgb(31, 120, 150)"],magenta:["rgb(162,106,192)","rgb(197,165,224)","rgb(208,113,218)"],red:["rgb(214,39,40)","rgb(255,152,150)"],st_blue:["rgb(23,190,207)","rgb(158,218,229)","rgb(31,119,180)"],dark_blue:["rgb(31,119,180)","rgb(31, 120, 150)"],light_blue:["rgb(23,190,207)","rgb(158,218,229)","rgb(108, 218, 229)","rgb(23,190,227)"],lilac_blue:["rgb(124,102,211)","rgb(149,134,217)","rgb(97, 81, 150)"],dark_green:["rgb(23,103,57)","rgb(30,110,96)","rgb(60,131,95)","rgb(24,110,79)"],green:["rgb(44,160,44)","rgb(74,160,74)"],light_green:["rgb(152,223,138)","rgb(182, 223, 138)","rgb(152, 193, 138)"],st_green:["rgb(44,160,44)","rgb(152,223,138)","rgb(39, 174, 96)","rgb(74,160,74)"],pink:["rgb(247,182,210)"],brown:["rgb(140,86,75)","rgb(102, 62, 54)"],gray:["rgb(127,127,127)","rgb(199,199,199)","rgb(196,156,148)","rgb(222, 222, 180)"],yellow:["rgb(188,189,34)"],white:["rgb(230,230,230)"]};class A extends g{static get Lesk(){return void 0===this.lesk&&(this.lesk=this.makePalette([[["G","A","S","T"],"orange"],[["C","V","I","L","P","F","Y","M","W"],"all_green"],[["N","Q","H"],"magenta"],[["D","E"],"red"],[["K","R"],"all_blue"]],!1,A)),this.lesk}static get GrokGroups(){return void 0===this.grokGroups&&(this.grokGroups=this.makePalette([[["C","U"],"yellow"],[["G","P"],"red"],[["A","V","I","L","M","F","Y","W"],"all_green"],[["R","H","K"],"light_blue"],[["D","E"],"dark_blue"],[["S","T","N","Q"],"orange"]],!1,A)),this.grokGroups}static get RasMol(){return void 0===this.rasMol&&(this.rasMol=new A({D:"#E60A0A",E:"#E60A0A",C:"#E6E600",M:"#E6E600",K:"#145AFF",R:"#145AFF",S:"#FA9600",T:"#FA9600",F:"#3232AA",Y:"#3232AA",N:"#00DCDC",Q:"#00DCDC",G:"#EBEBEB",L:"#0F820F",V:"#0F820F",I:"#0F820F",A:"#C8C8C8",W:"#B45AB4",H:"#8282D2",P:"#DC9682",others:"#BEA06E"})),this.rasMol}get(e){const t=e in A.aaSynonyms?A.aaSynonyms[e]:e;return super.get(t)}}A.aaSynonyms={MeNle:"L",MeA:"A",MeG:"G",MeF:"F"};class _{static getPalette(e="grok"){switch(e){case"grok":return A.GrokGroups;case"lesk":return A.Lesk;default:throw new Error(`ChemPalette: scheme \`${e}\` does not exist`)}}static getInnerOuter(e){let t=0,i="",n="";for(const o of e)"("==o?t++:")"==o?t--:t?i+=o:n+=o;return isNaN(parseInt(i))?[n,i]:[n,""]}static getColorAAPivot(e="",t="grok"){const i=this.getPalette(t);let[n,o]=this.getInnerOuter(e);if(n=n.length>6?`${n.slice(0,3)}...`:n,o=o.length>6?`${o.slice(0,3)}...`:o,1==e.length||"("==e[1]){const t=e[0]?.toUpperCase();return t in i?[i.get(t),t,o,1]:[this.undefinedColor,n,o,1]}if("d"==e[0]&&e[1]in i&&(2==e.length||"("==e[2])){const t=e[1]?.toUpperCase();return t in i?[i.get(t),t,o,2]:[this.undefinedColor,n,o,2]}if(e.substring(0,3)in this.AAFullNames&&(3==e.length||"("==e[3])){const t=this.AAFullNames[e.substring(0,3)];return t in i?[i.get(t),t,o,3]:[this.undefinedColor,n,o,3]}if(e[0]?.toLowerCase()==e[0]&&e.substring(1,3)in this.AAFullNames&&(4==e.length||"("==e[4])){const t=this.AAFullNames[e.substring(1,3)];return t in i?[i.get(t),t,o,4]:[this.undefinedColor,n,o,4]}return[this.undefinedColor,n,o,0]}}_.SemType="Aminoacids",_.SemTypeMultipleAlignment="AminoacidsMultipleAlignment",_.undefinedColor="rgb(100,100,100)",_.Names={G:"Glycine",L:"Leucine",Y:"Tyrosine",S:"Serine",E:"Glutamic acid",Q:"Glutamine",D:"Aspartic acid",N:"Asparagine",F:"Phenylalanine",A:"Alanine",K:"Lysine",R:"Arginine",H:"Histidine",C:"Cysteine",V:"Valine",P:"Proline",W:"Tryptophan",I:"Isoleucine",M:"Methionine",T:"Threonine"},_.AASmiles={G:"NCC(=O)O",L:"N[C@H](CC(C)C)C(=O)O",Y:"NC(CC1=CC=C(O)C=C1)C(=O)O",S:"NC(CO)C(=O)O",E:"N[C@@H](CCC(O)=O)C(=O)O",Q:"N[C@@H](CCC(N)=O)C(=O)O",D:"N[C@@H](CC(O)=O)C(=O)O",N:"N[C@@H](CC(N)=O)C(=O)O",F:"NC(CC1=CC=CC=C1)C(=O)O",A:"N[C@H](C)C(=O)O",K:"NC(CCCCN)C(=O)O",R:"N[C@H](CCCNC(=N)C)C(=O)O",H:"NC(CC1=CN=C[N]1)C(=O)O",C:"N[C@@H](CS)C(=O)O",V:"NC(C(C)C)C(=O)O",P:"N(CCC1)C1C(=O)O",W:"N[C@@H](Cc1c2ccccc2n([H])c1)C(=O)O",I:"N[C@H]([C@H](C)CC)C(=O)O",M:"NC(CCSC)C(=O)O",T:"NC(C(O)C)C(=O)O"},_.AASmilesTruncated={G:"*C*",L:"CC(C)C[C@H](*)*",Y:"C1=CC(=CC=C1CC(*)*)O",S:"OCC(*)C*",E:"*[C@@H](CCC(O)=O)*",Q:"*N[C@@H](CCC(N)=O)*",D:"*[C@@H](CC(O)=O)*",N:"*[C@@H](CC(N)=O)*",F:"C1=CC=C(C=C1)CC(*)*",A:"C[C@H](*)*",K:"C(CCN)CC(*)*",R:"*[C@H](CCCNC(=N)C)*",H:"C1=C(NC=N1)CC(*)*",C:"C([C@@H](*)*)S",V:"CC(C)C(*)*",P:"C1CCN(*)C1*",W:"*[C@@H](Cc1c2ccccc2n([H])c1)*",I:"CC[C@H](C)[C@H](*)*",M:"CSCCC(*)*",T:"CC(O)C(*)*"},_.AAFullNames={Ala:"A",Arg:"R",Asn:"N",Asp:"D",Cys:"C",Gln:"Q",Glu:"E",Gly:"G",His:"H",Ile:"I",Leu:"L",Lys:"K",Met:"M",Phe:"F",Pro:"P",Ser:"S",Thr:"T",Trp:"W",Tyr:"Y",Val:"V"};class y{}async function v(){const e=o.Func.find({package:"Bio",name:"getMonomerLibHelper"});if(0===e.length)throw new Error('Package "Bio" must be installed for MonomerLibHelper.');return(await e[0].prepare().call()).getOutputParamValue()}y.SemType="Nucleotides",y.SemTypeMultipleAlignment="NucleotidesMultipleAlignment",y.Names={A:"Adenine",C:"Cytosine",G:"Guanine",T:"Thymine",U:"Uracil"};const w="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,x=new Set,C="object"==typeof process&&process?process:{},E=(e,t,i,n)=>{"function"==typeof C.emitWarning?C.emitWarning(e,t,i,n):console.error(`[${i}] ${t}: ${e}`)};let k=globalThis.AbortController,B=globalThis.AbortSignal;if(void 0===k){B=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},k=class{constructor(){t()}signal=new B;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==C.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,E("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const S=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),M=e=>S(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?T:null:null;class T extends Array{constructor(e){super(e),this.fill(0)}}class I{heap;length;static#e=!1;static create(e){const t=M(e);if(!t)return[];I.#e=!0;const i=new I(e,t);return I.#e=!1,i}constructor(e,t){if(!I.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class L{#t;#i;#n;#o;#r;#s;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#l;#h;#d;#c;#u;#p;#m;#f;#b;#g;#A;#_;#y;#v;#w;#x;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#y,sizes:e.#A,keyMap:e.#h,keyList:e.#d,valList:e.#c,next:e.#u,prev:e.#p,get head(){return e.#m},get tail(){return e.#f},free:e.#b,isBackgroundFetch:t=>e.#C(t),backgroundFetch:(t,i,n,o)=>e.#E(t,i,n,o),moveToTail:t=>e.#k(t),indexes:t=>e.#B(t),rindexes:t=>e.#S(t),isStale:t=>e.#M(t)}}get max(){return this.#t}get maxSize(){return this.#i}get calculatedSize(){return this.#l}get size(){return this.#a}get fetchMethod(){return this.#r}get memoMethod(){return this.#s}get dispose(){return this.#n}get disposeAfter(){return this.#o}constructor(e){const{max:t=0,ttl:i,ttlResolution:n=1,ttlAutopurge:o,updateAgeOnGet:r,updateAgeOnHas:s,allowStale:a,dispose:l,disposeAfter:h,noDisposeOnSet:d,noUpdateTTL:c,maxSize:u=0,maxEntrySize:p=0,sizeCalculation:m,fetchMethod:f,memoMethod:b,noDeleteOnFetchRejection:g,noDeleteOnStaleGet:A,allowStaleOnFetchRejection:_,allowStaleOnFetchAbort:y,ignoreFetchAbort:v}=e;if(0!==t&&!S(t))throw new TypeError("max option must be a nonnegative integer");const w=t?M(t):Array;if(!w)throw new Error("invalid max value: "+t);if(this.#t=t,this.#i=u,this.maxEntrySize=p||this.#i,this.sizeCalculation=m,this.sizeCalculation){if(!this.#i&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==b&&"function"!=typeof b)throw new TypeError("memoMethod must be a function if defined");if(this.#s=b,void 0!==f&&"function"!=typeof f)throw new TypeError("fetchMethod must be a function if specified");if(this.#r=f,this.#w=!!f,this.#h=new Map,this.#d=new Array(t).fill(void 0),this.#c=new Array(t).fill(void 0),this.#u=new w(t),this.#p=new w(t),this.#m=0,this.#f=0,this.#b=I.create(t),this.#a=0,this.#l=0,"function"==typeof l&&(this.#n=l),"function"==typeof h?(this.#o=h,this.#g=[]):(this.#o=void 0,this.#g=void 0),this.#v=!!this.#n,this.#x=!!this.#o,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!c,this.noDeleteOnFetchRejection=!!g,this.allowStaleOnFetchRejection=!!_,this.allowStaleOnFetchAbort=!!y,this.ignoreFetchAbort=!!v,0!==this.maxEntrySize){if(0!==this.#i&&!S(this.#i))throw new TypeError("maxSize must be a positive integer if specified");if(!S(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#T()}if(this.allowStale=!!a,this.noDeleteOnStaleGet=!!A,this.updateAgeOnGet=!!r,this.updateAgeOnHas=!!s,this.ttlResolution=S(n)||0===n?n:1,this.ttlAutopurge=!!o,this.ttl=i||0,this.ttl){if(!S(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#I()}if(0===this.#t&&0===this.ttl&&0===this.#i)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#i){const e="LRU_CACHE_UNBOUNDED";(e=>!x.has(e))(e)&&(x.add(e),E("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,L))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#I(){const e=new T(this.#t),t=new T(this.#t);this.#y=e,this.#_=t,this.#L=(i,n,o=w.now())=>{if(t[i]=0!==n?o:0,e[i]=n,0!==n&&this.ttlAutopurge){const e=setTimeout(()=>{this.#M(i)&&this.#$(this.#d[i],"expire")},n+1);e.unref&&e.unref()}},this.#P=i=>{t[i]=0!==e[i]?w.now():0},this.#R=(o,r)=>{if(e[r]){const s=e[r],a=t[r];if(!s||!a)return;o.ttl=s,o.start=a,o.now=i||n();const l=o.now-a;o.remainingTTL=s-l}};let i=0;const n=()=>{const e=w.now();if(this.ttlResolution>0){i=e;const t=setTimeout(()=>i=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=o=>{const r=this.#h.get(o);if(void 0===r)return 0;const s=e[r],a=t[r];return s&&a?s-((i||n())-a):1/0},this.#M=o=>{const r=t[o],s=e[o];return!!s&&!!r&&(i||n())-r>s}}#P=()=>{};#R=()=>{};#L=()=>{};#M=()=>!1;#T(){const e=new T(this.#t);this.#l=0,this.#A=e,this.#H=t=>{this.#l-=e[t],e[t]=0},this.#N=(e,t,i,n)=>{if(this.#C(t))return 0;if(!S(i)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(i=n(t,e),!S(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return i},this.#D=(t,i,n)=>{if(e[t]=i,this.#i){const i=this.#i-e[t];for(;this.#l>i;)this.#F(!0)}this.#l+=e[t],n&&(n.entrySize=i,n.totalCalculatedSize=this.#l)}}#H=e=>{};#D=(e,t,i)=>{};#N=(e,t,i,n)=>{if(i||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#B({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#f;this.#O(t)&&(!e&&this.#M(t)||(yield t),t!==this.#m);)t=this.#p[t]}*#S({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#m;this.#O(t)&&(!e&&this.#M(t)||(yield t),t!==this.#f);)t=this.#u[t]}#O(e){return void 0!==e&&this.#h.get(this.#d[e])===e}*entries(){for(const e of this.#B())void 0===this.#c[e]||void 0===this.#d[e]||this.#C(this.#c[e])||(yield[this.#d[e],this.#c[e]])}*rentries(){for(const e of this.#S())void 0===this.#c[e]||void 0===this.#d[e]||this.#C(this.#c[e])||(yield[this.#d[e],this.#c[e]])}*keys(){for(const e of this.#B()){const t=this.#d[e];void 0===t||this.#C(this.#c[e])||(yield t)}}*rkeys(){for(const e of this.#S()){const t=this.#d[e];void 0===t||this.#C(this.#c[e])||(yield t)}}*values(){for(const e of this.#B())void 0===this.#c[e]||this.#C(this.#c[e])||(yield this.#c[e])}*rvalues(){for(const e of this.#S())void 0===this.#c[e]||this.#C(this.#c[e])||(yield this.#c[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const i of this.#B()){const n=this.#c[i],o=this.#C(n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,this.#d[i],this))return this.get(this.#d[i],t)}}forEach(e,t=this){for(const i of this.#B()){const n=this.#c[i],o=this.#C(n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,this.#d[i],this)}}rforEach(e,t=this){for(const i of this.#S()){const n=this.#c[i],o=this.#C(n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,this.#d[i],this)}}purgeStale(){let e=!1;for(const t of this.#S({allowStale:!0}))this.#M(t)&&(this.#$(this.#d[t],"expire"),e=!0);return e}info(e){const t=this.#h.get(e);if(void 0===t)return;const i=this.#c[t],n=this.#C(i)?i.__staleWhileFetching:i;if(void 0===n)return;const o={value:n};if(this.#y&&this.#_){const e=this.#y[t],i=this.#_[t];if(e&&i){const t=e-(w.now()-i);o.ttl=t,o.start=Date.now()}}return this.#A&&(o.size=this.#A[t]),o}dump(){const e=[];for(const t of this.#B({allowStale:!0})){const i=this.#d[t],n=this.#c[t],o=this.#C(n)?n.__staleWhileFetching:n;if(void 0===o||void 0===i)continue;const r={value:o};if(this.#y&&this.#_){r.ttl=this.#y[t];const e=w.now()-this.#_[t];r.start=Math.floor(Date.now()-e)}this.#A&&(r.size=this.#A[t]),e.unshift([i,r])}return e}load(e){this.clear();for(const[t,i]of e){if(i.start){const e=Date.now()-i.start;i.start=w.now()-e}this.set(t,i.value,i)}}set(e,t,i={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:o,noDisposeOnSet:r=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=i;let{noUpdateTTL:l=this.noUpdateTTL}=i;const h=this.#N(e,t,i.size||0,s);if(this.maxEntrySize&&h>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#$(e,"set"),this;let d=0===this.#a?void 0:this.#h.get(e);if(void 0===d)d=0===this.#a?this.#f:0!==this.#b.length?this.#b.pop():this.#a===this.#t?this.#F(!1):this.#a,this.#d[d]=e,this.#c[d]=t,this.#h.set(e,d),this.#u[this.#f]=d,this.#p[d]=this.#f,this.#f=d,this.#a++,this.#D(d,h,a),a&&(a.set="add"),l=!1;else{this.#k(d);const i=this.#c[d];if(t!==i){if(this.#w&&this.#C(i)){i.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=i;void 0===t||r||(this.#v&&this.#n?.(t,e,"set"),this.#x&&this.#g?.push([t,e,"set"]))}else r||(this.#v&&this.#n?.(i,e,"set"),this.#x&&this.#g?.push([i,e,"set"]));if(this.#H(d),this.#D(d,h,a),this.#c[d]=t,a){a.set="replace";const e=i&&this.#C(i)?i.__staleWhileFetching:i;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update")}if(0===n||this.#y||this.#I(),this.#y&&(l||this.#L(d,n,o),a&&this.#R(a,d)),!r&&this.#x&&this.#g){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}return this}pop(){try{for(;this.#a;){const e=this.#c[this.#m];if(this.#F(!0),this.#C(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#x&&this.#g){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}}}#F(e){const t=this.#m,i=this.#d[t],n=this.#c[t];return this.#w&&this.#C(n)?n.__abortController.abort(new Error("evicted")):(this.#v||this.#x)&&(this.#v&&this.#n?.(n,i,"evict"),this.#x&&this.#g?.push([n,i,"evict"])),this.#H(t),e&&(this.#d[t]=void 0,this.#c[t]=void 0,this.#b.push(t)),1===this.#a?(this.#m=this.#f=0,this.#b.length=0):this.#m=this.#u[t],this.#h.delete(i),this.#a--,t}has(e,t={}){const{updateAgeOnHas:i=this.updateAgeOnHas,status:n}=t,o=this.#h.get(e);if(void 0!==o){const e=this.#c[o];if(this.#C(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#M(o))return i&&this.#P(o),n&&(n.has="hit",this.#R(n,o)),!0;n&&(n.has="stale",this.#R(n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:i=this.allowStale}=t,n=this.#h.get(e);if(void 0===n||!i&&this.#M(n))return;const o=this.#c[n];return this.#C(o)?o.__staleWhileFetching:o}#E(e,t,i,n){const o=void 0===t?void 0:this.#c[t];if(this.#C(o))return o;const r=new k,{signal:s}=i;s?.addEventListener("abort",()=>r.abort(s.reason),{signal:r.signal});const a={signal:r.signal,options:i,context:n},l=(n,o=!1)=>{const{aborted:s}=r.signal,l=i.ignoreFetchAbort&&void 0!==n;if(i.status&&(s&&!o?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,l&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),s&&!l&&!o)return h(r.signal.reason);const c=d;return this.#c[t]===d&&(void 0===n?c.__staleWhileFetching?this.#c[t]=c.__staleWhileFetching:this.#$(e,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(e,n,a.options))),n},h=n=>{const{aborted:o}=r.signal,s=o&&i.allowStaleOnFetchAbort,a=s||i.allowStaleOnFetchRejection,l=a||i.noDeleteOnFetchRejection,h=d;if(this.#c[t]===d&&(l&&void 0!==h.__staleWhileFetching?s||(this.#c[t]=h.__staleWhileFetching):this.#$(e,"fetch")),a)return i.status&&void 0!==h.__staleWhileFetching&&(i.status.returnedStale=!0),h.__staleWhileFetching;if(h.__returned===h)throw n};i.status&&(i.status.fetchDispatched=!0);const d=new Promise((t,n)=>{const s=this.#r?.(e,o,a);s&&s instanceof Promise&&s.then(e=>t(void 0===e?void 0:e),n),r.signal.addEventListener("abort",()=>{i.ignoreFetchAbort&&!i.allowStaleOnFetchAbort||(t(void 0),i.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=e),h(e))),c=Object.assign(d,{__abortController:r,__staleWhileFetching:o,__returned:void 0});return void 0===t?(this.set(e,c,{...a.options,status:void 0}),t=this.#h.get(e)):this.#c[t]=c,c}#C(e){if(!this.#w)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof k}async fetch(e,t={}){const{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:c=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:f=!1,status:b,signal:g}=t;if(!this.#w)return b&&(b.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:b});const A={allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:r,noDisposeOnSet:s,size:a,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:c,allowStaleOnFetchAbort:p,ignoreFetchAbort:u,status:b,signal:g};let _=this.#h.get(e);if(void 0===_){b&&(b.fetch="miss");const t=this.#E(e,_,A,m);return t.__returned=t}{const t=this.#c[_];if(this.#C(t)){const e=i&&void 0!==t.__staleWhileFetching;return b&&(b.fetch="inflight",e&&(b.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=this.#M(_);if(!f&&!o)return b&&(b.fetch="hit"),this.#k(_),n&&this.#P(_),b&&this.#R(b,_),t;const r=this.#E(e,_,A,m),s=void 0!==r.__staleWhileFetching&&i;return b&&(b.fetch=o?"stale":"refresh",s&&o&&(b.returnedStale=!0)),s?r.__staleWhileFetching:r.__returned=r}}async forceFetch(e,t={}){const i=await this.fetch(e,t);if(void 0===i)throw new Error("fetch() returned undefined");return i}memo(e,t={}){const i=this.#s;if(!i)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o,...r}=t,s=this.get(e,r);if(!o&&void 0!==s)return s;const a=i(e,s,{options:r,context:n});return this.set(e,a,r),a}get(e,t={}){const{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:r}=t,s=this.#h.get(e);if(void 0!==s){const t=this.#c[s],a=this.#C(t);return r&&this.#R(r,s),this.#M(s)?(r&&(r.get="stale"),a?(r&&i&&void 0!==t.__staleWhileFetching&&(r.returnedStale=!0),i?t.__staleWhileFetching:void 0):(o||this.#$(e,"expire"),r&&i&&(r.returnedStale=!0),i?t:void 0)):(r&&(r.get="hit"),a?t.__staleWhileFetching:(this.#k(s),n&&this.#P(s),t))}r&&(r.get="miss")}#z(e,t){this.#p[t]=e,this.#u[e]=t}#k(e){e!==this.#f&&(e===this.#m?this.#m=this.#u[e]:this.#z(this.#p[e],this.#u[e]),this.#z(this.#f,e),this.#f=e)}delete(e){return this.#$(e,"delete")}#$(e,t){let i=!1;if(0!==this.#a){const n=this.#h.get(e);if(void 0!==n)if(i=!0,1===this.#a)this.#G(t);else{this.#H(n);const i=this.#c[n];if(this.#C(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#x)&&(this.#v&&this.#n?.(i,e,t),this.#x&&this.#g?.push([i,e,t])),this.#h.delete(e),this.#d[n]=void 0,this.#c[n]=void 0,n===this.#f)this.#f=this.#p[n];else if(n===this.#m)this.#m=this.#u[n];else{const e=this.#p[n];this.#u[e]=this.#u[n];const t=this.#u[n];this.#p[t]=this.#p[n]}this.#a--,this.#b.push(n)}}if(this.#x&&this.#g?.length){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}return i}clear(){return this.#G("delete")}#G(e){for(const t of this.#S({allowStale:!0})){const i=this.#c[t];if(this.#C(i))i.__abortController.abort(new Error("deleted"));else{const n=this.#d[t];this.#v&&this.#n?.(i,n,e),this.#x&&this.#g?.push([i,n,e])}}if(this.#h.clear(),this.#c.fill(void 0),this.#d.fill(void 0),this.#y&&this.#_&&(this.#y.fill(0),this.#_.fill(0)),this.#A&&this.#A.fill(0),this.#m=0,this.#f=0,this.#b.length=0,this.#l=0,this.#a=0,this.#x&&this.#g){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}}}var P=class extends Error{constructor(e,t,i){super(t),this.name="HwError",this.code=e,void 0!==i&&(this.context=Object.freeze({...i})),Object.setPrototypeOf(this,new.target.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,new.target)}},R=class extends P{constructor(e,t,i){super(e,t,i?.context),this.name="HelmParseError",void 0!==i?.span&&(this.span={...i.span}),Object.setPrototypeOf(this,new.target.prototype)}},H=class extends P{constructor(e,t){let i=Object.freeze([...e]),n=t??function(e){if(0===e.length)return"HELM validation failed";let t=e[0],i=e.length>1?` (+${e.length-1} more)`:"";return`HELM validation failed: ${t.code} — ${t.message}${i}`}(i);super("helm-validation-failed",n),this.name="HelmValidationError",this.diagnostics=i,Object.setPrototypeOf(this,new.target.prototype)}},N=class extends P{constructor(e,t,i){super(e,t??`HELM operation not supported: ${e}`,i),this.name="HelmNotSupportedError",Object.setPrototypeOf(this,new.target.prototype)}},D=class{constructor(e){if(!Number.isInteger(e.max)||e.max<=0)throw new RangeError(`LruCache: max must be a positive integer (got ${e.max})`);let t=e.onEvict;this._cache=new L(void 0===t?{max:e.max}:{max:e.max,dispose:(e,i,n)=>{t(i,e)}})}get(e){return this._cache.get(e)}set(e,t){this._cache.set(e,t)}has(e){return this._cache.has(e)}delete(e){return this._cache.delete(e)}clear(){this._cache.clear()}get size(){return this._cache.size}keys(){return this._cache.keys()}entries(){return this._cache.entries()}},F=class{debug(e,t){}info(e,t){}warn(e,t){}error(e,t){}};function O(e){return e>=65&&e<=90||e>=97&&e<=122}function z(e){return e>=48&&e<=57}function G(e){return 32===e||9===e||10===e||13===e}var q=class{constructor(e){this.src=e,this.len=e.length,this.pos=0,this.tokens=[]}tokenize(){for(;this.pos<this.len;){let e=this.pos,t=this.src.charCodeAt(this.pos);if(G(t))throw new R("unexpected-whitespace",`Unexpected whitespace at offset ${e}`,{span:{start:e,end:e+1}});if(91===t){this.scanBracket(e);continue}if(34===t){this.scanQuote(e);continue}if(O(t)){this.scanIdentifier(e);continue}if(z(t)){this.scanNumber(e);continue}let i=j.get(t);if(void 0===i)throw new R("unexpected-char",`Unexpected character ${JSON.stringify(this.src.charAt(e))} at offset ${e}`,{span:{start:e,end:e+1}});this.pos+=1,this.push(i,this.src.charAt(e),e,this.pos)}return this.push("eof","",this.len,this.len),{tokens:this.tokens,source:this.src}}scanBracket(e){let t=1,i=!1,n=!1,o=e+1;for(;o<this.len;){let r=this.src.charCodeAt(o);if(i){if(92===r&&o+1<this.len){o+=2;continue}if(34===r){i=!1,o+=1;continue}if(10===r||13===r)throw new R("unexpected-newline",`Newline inside bracket at offset ${o}`,{span:{start:o,end:o+1}});o+=1}else if(n){if(36===r&&o+1<this.len){let e=this.src.charCodeAt(o+1);if(124===e){n=!1,o+=2;continue}if(93===e){n=!1,o+=1;continue}}if(10===r||13===r)throw new R("unexpected-newline",`Newline inside bracket at offset ${o}`,{span:{start:o,end:o+1}});o+=1}else{if(10===r||13===r)throw new R("unexpected-newline",`Newline inside bracket at offset ${o}`,{span:{start:o,end:o+1}});if(34!==r)if(124===r&&o+1<this.len&&36===this.src.charCodeAt(o+1))n=!0,o+=2;else if(91!==r)if(93!==r)o+=1;else{if(t-=1,0===t){let t=o+1,i=this.src.slice(e+1,o);return this.pos=t,void this.push("inline-smiles",i,e,t)}o+=1}else t+=1,o+=1;else i=!0,o+=1}}throw new R("unterminated-bracket",`Unterminated '[' starting at offset ${e}`,{span:{start:e,end:this.len}})}scanQuote(e){let t=[],i=e+1;for(;i<this.len;){let n=this.src.charCodeAt(i);if(34===n){let n=i+1;return this.pos=n,void this.push("quote-string",t.join(""),e,n)}if(92===n&&i+1<this.len){let e=this.src.charCodeAt(i+1);34===e?t.push('"'):92===e?t.push("\\"):110===e?t.push("\n"):114===e?t.push("\r"):116===e?t.push("\t"):(t.push("\\"),t.push(this.src.charAt(i+1))),i+=2;continue}if(10===n||13===n)throw new R("unexpected-newline",`Newline inside quote at offset ${i}`,{span:{start:i,end:i+1}});t.push(this.src.charAt(i)),i+=1}throw new R("unterminated-quote",`Unterminated '"' starting at offset ${e}`,{span:{start:e,end:this.len}})}scanIdentifier(e){let t=e+1;for(;t<this.len;){let e=this.src.charCodeAt(t);if(O(e)||z(e)||95===e)t+=1;else{if(!(45===e&&t+1<this.len&&O(this.src.charCodeAt(t+1))))break;t+=2}}let i=this.src.slice(e,t);this.pos=t,this.push("identifier",i,e,t)}scanNumber(e){let t=e+1;for(;t<this.len&&z(this.src.charCodeAt(t));)t+=1;if(t+1<this.len&&46===this.src.charCodeAt(t)&&z(this.src.charCodeAt(t+1))){for(t+=2;t<this.len&&z(this.src.charCodeAt(t));)t+=1;let i=this.src.slice(e,t);return this.pos=t,void this.push("decimal",i,e,t)}let i=this.src.slice(e,t);this.pos=t,this.push("integer",i,e,t)}push(e,t,i,n){this.tokens.push({kind:e,value:t,span:{start:i,end:n}})}},j=new Map([[123,"lbrace"],[125,"rbrace"],[40,"lparen"],[41,"rparen"],[93,"rbracket"],[124,"pipe"],[46,"dot"],[44,"comma"],[43,"plus"],[58,"colon"],[45,"dash"],[36,"dollar"],[62,"gt"],[63,"question"],[42,"asterisk"],[95,"underscore"],[39,"apos"]]);var V={perPolymer:new Map,version:""};function Y(){return{atoms:[],bonds:[],chains:[],groups:[],annotations:V}}function W(e,t){for(let i of e.atoms)if(i.id===t)return i}function U(e,t){for(let i of e.bonds)if(i.id===t)return i}function K(e,t){if(void 0===t)return e.bio.positionInChain;let i=0;for(let n=0;n<t.backboneAtoms.length;n++){let o=t.backboneAtoms[n];if(void 0!==o&&(i+=1,o.id===e.id||void 0!==o.branchAtom&&(i+=1,o.branchAtom.id===e.id)))return i}return 0}var X="HELM_AA",Q="HELM_SUGAR",Z="HELM_BASE",J="HELM_LINKER",ee="HELM_CHEM",te="HELM_BLOB",ie="HELM_NUCLEOTIDE",ne={PEPTIDE:"PEPTIDE",RNA:"RNA",CHEM:"CHEM",BLOB:"BLOB",G:"G"},oe=class{constructor(){this._counter=0}next(){return this._counter+=1,this._counter}reset(){this._counter=0}get current(){return this._counter}};function re(e){let t=new Map,i=0;for(let n of e.chains)for(let e of n.backboneAtoms)i+=1,t.set(e.id,i),void 0!==e.branchAtom&&(i+=1,t.set(e.branchAtom.id,i));return t}function se(e){let t=e.trim();if(/^\[[a-zA-Z_][a-zA-Z0-9_]*\]$/.test(t))return!1;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e);if(40===i||91===i||61===i||47===i||92===i||42===i)return!0}return!1}var ae=class{constructor(){this._listeners=new Set,this._completed=!1}subscribe(e){return this._completed?()=>{}:(this._listeners.add(e),()=>{this._listeners.delete(e)})}next(e){if(!this._completed)for(let t of[...this._listeners])t(e)}complete(){this._completed=!0,this._listeners.clear()}get observerCount(){return this._listeners.size}};function le(e){return{line:"#202020",text:"#000000",background:e}}function he(e){return{line:"#e0e0e0",text:"#ffffff",background:ye(e,.25)}}function de(e){let t=/^#([0-9a-fA-F]{6})$/.exec(e),i=/^#([0-9a-fA-F]{3})$/.exec(e);if(null!==t){let e=t[1];return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}if(null!==i){let e=i[1];return[parseInt(e[0]+e[0],16),parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16)]}return null}function ce(e){return e.toString(16).padStart(2,"0")}function ue(e,t,i){return`#${ce(e)}${ce(t)}${ce(i)}`}function pe(e,t,i){let n=e/255,o=t/255,r=i/255,s=Math.max(n,o,r),a=Math.min(n,o,r),l=(s+a)/2;if(s===a)return[0,0,l];let h,d=s-a;return h=s===n?60*((o-r)/d+(o<r?6:0)):s===o?60*((r-n)/d+2):60*((n-o)/d+4),[h,l>.5?d/(2-s-a):d/(s+a),l]}function me(e,t,i){let n=i;return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function fe(e,t,i){if(0===t){let e=Math.round(255*i);return[e,e,e]}let n=i<.5?i*(1+t):i+t-i*t,o=2*i-n,r=e/360;return[Math.round(255*me(o,n,r+1/3)),Math.round(255*me(o,n,r)),Math.round(255*me(o,n,r-1/3))]}function be(e,t=.3,i=.1){let n=de(e);if(null===n)return e;let[o,r,s]=pe(n[0],n[1],n[2]),a=Math.max(0,Math.min(1,r*(1-t))),l=Math.max(0,Math.min(.95,s+i*(1-s))),[h,d,c]=fe(o,a,l);return ue(h,d,c)}function ge(e){let t=de(e);if(null===t)return 0;let i=e=>{let t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(t[0])+.7152*i(t[1])+.0722*i(t[2])}function Ae(e){let t=de(e);if(null===t)return"#1f2937";let[i,n,o]=pe(t[0],t[1],t[2]);if(o>.85||n<.15&&o>.7)return"#1f2937";let r=Math.max(.08,o-.3);return function(e){let t=(e.h%360+360)%360,i=Math.max(0,Math.min(1,e.s)),n=Math.max(0,Math.min(1,e.l)),[o,r,s]=fe(t,i,n);return ue(o,r,s)}({h:i,s:Math.min(1,n+.1),l:r})}function _e(e){let t=function(e){let t=de(e);return null===t?null:{r:t[0]/255,g:t[1]/255,b:t[2]/255}}(e);if(null===t)return"#1f2937";let i=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4),n=.2126*i(t.r)+.7152*i(t.g)+.0722*i(t.b);return 1.05/(n+.05)>(n+.05)/.05?"#ffffff":"#1f2937"}function ye(e,t){let i=de(e);if(null===i)return e;let n=1-t;return ue(Math.max(0,Math.min(255,Math.round(i[0]*n))),Math.max(0,Math.min(255,Math.round(i[1]*n))),Math.max(0,Math.min(255,Math.round(i[2]*n))))}var ve={A:le("#A0A0FF"),G:le("#FF7070"),T:le("#A0FFA0"),C:le("#FF8C4B"),U:le("#FF8080")},we={R:le("#7a85c1"),r:le("#7a85c1")},xe={P:le("#9aa5e1"),p:le("#9aa5e1")},Ce={A:le("#C8C8C8"),R:le("#145AFF"),N:le("#00DCDC"),D:le("#E60A0A"),C:le("#E6E600"),E:le("#00DCDC"),Q:le("#E60A0A"),G:le("#EBEBEB"),H:le("#8282D2"),I:le("#0F820F"),L:le("#0F820F"),K:le("#145AFF"),M:le("#E6E600"),F:le("#3232AA"),P:le("#DC9682"),S:le("#FA9600"),T:le("#FA9600"),W:le("#B45AB4"),Y:le("#3232AA"),V:le("#0F820F")},Ee={R:le("#eeeeee")},ke={B:le("#999999"),G:le("#e2e2e2")},Be={P:le("#9aa5e1")},Se={name:"light",fallback:{line:"#202020",text:"#000000",background:"#eeeeee"},errorTriple:{line:"#cc0000",text:"#000000",background:"#FFFF00"},palette:{[Z]:ve,[Q]:we,[J]:xe,[X]:Ce,[ee]:Ee,[te]:ke,[ie]:Be}};function Me(e){let t={};for(let[i,n]of Object.entries(e))t[i]=he(n.background);return t}var Te={name:"dark",fallback:{line:"#e0e0e0",text:"#ffffff",background:ye("#eeeeee",.5)},errorTriple:{line:"#ff5050",text:"#ffffff",background:ye("#FFFF00",.4)},palette:{[Z]:Me(ve),[Q]:Me(we),[J]:Me(xe),[X]:Me(Ce),[ee]:Me(Ee),[te]:Me(ke),[ie]:Me(Be)}};function Ie(e,t,i=Se){if(null===e)return{...i.errorTriple};let n=e.meta?.colors;if(void 0!==n){let e="light"===i.name?n.light:"dark"===i.name?n.dark:void 0;if(void 0!==e)return{...e,line:Ae(e.background)};if(void 0!==n.default)return{...n.default,line:Ae(n.default.background)}}let o=e.naturalAnalog;if(void 0!==o&&""!==o){let e=i.palette[t];if(void 0!==e){let t=e[o];if(void 0!==t)return{...t,line:Ae(t.background),text:_e(t.background)}}}return{...i.fallback,line:Ae(i.fallback.background),text:_e(i.fallback.background)}}function Le(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&"capgroupsmiles"===t.toLowerCase()){let i=e[t];if("string"==typeof i)return i}}function $e(e){switch(e.polymerType){case ne.PEPTIDE:return X;case ne.CHEM:return ee;case ne.BLOB:return te;case ne.RNA:if("Branch"===e.monomerType)return Z;if("Backbone"===e.monomerType){let t=e.naturalAnalog;return"P"===t||"p"===t?J:Q}return null;default:return null}}function Pe(e,t,i){return new Ne(e,t,i??{}).run()}new Set(["PEPTIDE","RNA","CHEM","BLOB"]),new Set(["Backbone","Branch","Terminal","Undefined"]);var Re=new Set(["?","*","_","X","N"]),He=/^R([1-9][0-9]*)$/,Ne=class{constructor(e,t,i){this.diagnostics=[],this.oldToNew=new Map,this.placeholderCache=new Map,this.mol=e,this.lib=t,this.options=i}run(){let e=new Map;for(let t of this.mol.chains)e.set(t.id,t.polymerType);for(let t of this.mol.atoms){let i=e.get(t.bio.chainId)??null,n=this.resolveAtom(t,i);this.oldToNew.set(t.id,n)}for(let e of this.mol.atoms){let t=this.oldToNew.get(e.id);if(void 0===t||void 0===e.branchAtom)continue;let i=this.oldToNew.get(e.branchAtom.id);void 0!==i&&(t.branchAtom=i)}let t=[];for(let e of this.mol.bonds){let i=this.oldToNew.get(e.a1.id),n=this.oldToNew.get(e.a2.id);void 0===i||void 0===n||t.push({...e,a1:i,a2:n})}let i=new Map;for(let e of t)i.set(e.id,e);let n=[];for(let e of this.mol.chains){let t=[];for(let i of e.backboneAtoms){let e=this.oldToNew.get(i.id);void 0!==e&&t.push(e)}let o=[];for(let t of e.bonds){let e=i.get(t.id);void 0!==e&&o.push(e)}n.push({id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:o,...void 0!==e.annotation?{annotation:e.annotation}:{},...void 0!==e.strandType?{strandType:e.strandType}:{}})}return{mol:{atoms:this.mol.atoms.map(e=>this.oldToNew.get(e.id)),bonds:t,chains:n,groups:this.mol.groups,annotations:this.mol.annotations},diagnostics:this.diagnostics}}resolveAtom(e,t){let i=null,n=e.biotype;if(null!==t){let o=this.lib.getMonomer(t,e.symbol);if(null!==o)i=this.toResolved(o),n=$e(o)??e.biotype;else if(this.isAmbiguitySymbol(e))i=this.synthesizeAmbiguity(t,e),this.emit("info","ambiguous-monomer",`Ambiguous monomer '${e.symbol}' on chain '${e.bio.chainId}'`,e);else if(se(e.symbol))i=this.registerInlineSmilesFallback(t,e);else if(!0===this.options.legacyCaseFallback&&"RNA"===t){let o=this.findCaseInsensitiveMatch(t,e.symbol);null!==o&&(i=this.toResolved(o),n=$e(o)??e.biotype,this.emit("info","case-mismatch",`Symbol '${e.symbol}' matched library entry '${o.symbol}' only after case fold`,e))}null===i&&(i=this.synthesizeMissing(t,e),this.emit("warning","unresolved-monomer",`Monomer '${e.symbol}' not found in library for ${t}`,e))}return{...e,monomer:i,biotype:n}}toResolved(e){let t=this.lib.getResolved?.(e);if(void 0!==t)return t;let i=new Map;for(let t of e.rgroups){let e=He.exec(t.label);null!==e&&i.set(parseInt(e[1],10),t)}return Object.assign({},e,{rs:e.rgroups.length,rgroupMap:i})}isAmbiguitySymbol(e){return!(!Re.has(e.symbol)&&void 0===e.bio.ambiguity)}synthesizeAmbiguity(e,t){let i=`ambig:${e}:${t.symbol}`,n=this.placeholderCache.get(i);return void 0===n&&(n={symbol:t.symbol,polymerType:e,monomerType:"Undefined",molfile:"",rgroups:[{label:"R1",capGroupName:"H",capGroupSMILES:""},{label:"R2",capGroupName:"H",capGroupSMILES:""}],meta:{ambiguous:!0}},this.placeholderCache.set(i,n)),this.toResolved(n)}synthesizeMissing(e,t){let i=`missing:${e}:${t.symbol}`,n=this.placeholderCache.get(i);return void 0===n&&(n={symbol:t.symbol,polymerType:e,monomerType:"Undefined",molfile:"",rgroups:[{label:"R1",capGroupName:"H",capGroupSMILES:""},{label:"R2",capGroupName:"H",capGroupSMILES:""}],meta:{missing:!0}},this.placeholderCache.set(i,n)),this.toResolved(n)}registerInlineSmilesFallback(e,t){if("function"==typeof this.lib.registerInlineSmilesMonomer)try{let i=this.lib.registerInlineSmilesMonomer(e,t.symbol);return this.toResolved(i)}catch{this.emit("warning","inline-smiles-without-r-groups",`Inline SMILES '${i=t.symbol,i.length<=40?i:i.slice(0,39)+"…"}' has no detectable R-groups`,t)}else this.emit("warning","inline-smiles-without-r-groups","Inline SMILES seen but lib has no registerInlineSmilesMonomer",t);var i;return this.synthesizeMissing(e,t)}findCaseInsensitiveMatch(e,t){let i=t.toLowerCase();for(let n of this.lib.getMonomerSymbolsByType(e))if(n.toLowerCase()===i&&n!==t){let t=this.lib.getMonomer(e,n);if(null!==t)return t}return null}emit(e,t,i,n){let o={chainId:n.bio.chainId,atomId:n.id,symbol:n.symbol};this.diagnostics.push({severity:e,code:t,message:i,context:o})}};function De(e,t,i){let n,o=i?.mode??"lenient";try{n=function(e){let t=new q(e).tokenize();return function(e){let t=null;for(let i of e.tokens)if("apos"===i.kind)t=null===t?i.span:null;else if("eof"===i.kind&&null!==t)throw new R("unterminated-apostrophe",`Unterminated apostrophe block starting at offset ${t.start}`,{span:{start:t.start,end:e.source.length}})}(t),t}(e)}catch(e){if(e instanceof R){if("strict"===o)throw e;let t={severity:"error",code:e.code,message:e.message,...void 0!==e.span?{span:{start:e.span.start,end:e.span.end}}:{}};return{mol:Y(),diagnostics:[t]}}throw e}return function(e,t,i){let n=new Ge(e,t,i?.mode??"lenient").parseDocument();if(null===t||!1===i?.resolveMonomers)return n;let o=Pe(n.mol,t,{mode:i?.mode??"lenient",...!0===i?.legacyCaseFallback?{legacyCaseFallback:!0}:{}});return{mol:o.mol,diagnostics:[...n.diagnostics,...o.diagnostics]}}(n,t,i)}var Fe=class{constructor(e){this.tokens=e.tokens,this.len=e.tokens.length,this.eof=e.tokens[e.tokens.length-1],this.idx=0}peek(e=0){let t=this.idx+e;return t>=this.len?this.eof:this.tokens[t]}advance(){let e=this.idx<this.len?this.tokens[this.idx]:this.eof;return"eof"!==e.kind&&(this.idx+=1),e}optional(e){let t=this.idx<this.len?this.tokens[this.idx]:this.eof;return t.kind===e?("eof"!==t.kind&&(this.idx+=1),t):null}at(e){return(this.idx<this.len?this.tokens[this.idx]:this.eof).kind===e}at2(e,t){let i=(this.idx<this.len?this.tokens[this.idx]:this.eof).kind;return i===e||i===t}at3(e,t,i){let n=(this.idx<this.len?this.tokens[this.idx]:this.eof).kind;return n===e||n===t||n===i}currentSpan(){return(this.idx<this.len?this.tokens[this.idx]:this.eof).span}position(){return this.idx}setPosition(e){this.idx=e}isAtEnd(){return"eof"===(this.idx<this.len?this.tokens[this.idx]:this.eof).kind}},Oe=/^(PEPTIDE|RNA|DNA|CHEM|BLOB|G)([0-9]+)$/;function ze(e){let t=Oe.exec(e);if(null===t)return null;let i=t[1],n=parseInt(t[2],10);switch(i){case"PEPTIDE":return{rawTypeName:"PEPTIDE",polymerType:ne.PEPTIDE,number:n,isDnaShim:!1,isGroup:!1};case"RNA":return{rawTypeName:"RNA",polymerType:ne.RNA,number:n,isDnaShim:!1,isGroup:!1};case"DNA":return{rawTypeName:"DNA",polymerType:ne.RNA,number:n,isDnaShim:!0,isGroup:!1};case"CHEM":return{rawTypeName:"CHEM",polymerType:ne.CHEM,number:n,isDnaShim:!1,isGroup:!1};case"BLOB":return{rawTypeName:"BLOB",polymerType:ne.BLOB,number:n,isDnaShim:!1,isGroup:!1};case"G":return{rawTypeName:"G",polymerType:ne.PEPTIDE,number:n,isDnaShim:!1,isGroup:!0};default:return null}}var Ge=class{constructor(e,t,i){this.diagnostics=[],this.chains=[],this.chainById=new Map,this.pendingBonds=[],this.groups=[],this.atomIds=new oe,this.bondIds=new oe,this.cursor=new Fe(e),this.source=e.source,this.lib=t,this.mode=i,this.annotations={perPolymer:new Map,version:""}}parseDocument(){if(this.cursor.isAtEnd())return this.emit("warning","empty-helm","Empty HELM string"),{mol:Y(),diagnostics:this.diagnostics};if(this.parseSimplePolymers(),this.expectDollarSeparator(1),this.parseConnections(),this.expectDollarSeparator(2),this.parseGroupsSection(),this.expectDollarSeparator(3),this.parseAnnotationsSection(),this.cursor.at("dollar")&&(this.cursor.advance(),this.parseVersionTrailer()),!this.cursor.isAtEnd())for(this.emit("warning","extra-section-separator","Unexpected trailing tokens after HELM document",this.cursor.currentSpan());!this.cursor.isAtEnd();)this.cursor.advance();return{mol:this.finalize(),diagnostics:this.diagnostics}}expectDollarSeparator(e){this.cursor.at("dollar")?this.cursor.advance():this.emit("error","missing-section-separator",`Expected '$' separator before section ${e+1}`,this.cursor.currentSpan())}parseSimplePolymers(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd())for(this.parsePolymer();this.cursor.at("pipe");){if(this.cursor.advance(),this.cursor.at("dollar")||this.cursor.isAtEnd())return void this.emit("warning","empty-polymer-body","Empty polymer after '|'",this.cursor.currentSpan());this.parsePolymer()}}parsePolymer(){let e=this.cursor.currentSpan(),t=this.cursor.optional("identifier");if(null===t)return this.emit("error","unexpected-token",`Expected polymer id, got '${this.cursor.peek().value}'`,this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let i=ze(t.value);if(null===i)return this.emit("error","unknown-polymer-type",`Unknown polymer type '${t.value}'`,t.span),void this.skipUntil(["pipe","dollar","eof"]);if(this.chainById.has(t.value)&&this.emit("warning","duplicate-polymer-id",`Duplicate polymer id '${t.value}'`,t.span),null===this.cursor.optional("lbrace"))return void this.emit("error","unexpected-token",`Expected '{' after polymer id '${t.value}'`,this.cursor.currentSpan());let n={id:t.value,polymerType:i.polymerType,rawTypeName:i.rawTypeName,rawNumber:i.number,backboneAtoms:[],allAtoms:[],bonds:[],span:{start:e.start,end:e.end}};if(this.chains.push(n),this.chainById.set(n.id,n),this.cursor.at("rbrace"))this.emit("warning","empty-polymer-body",`Empty body for polymer '${n.id}'`,this.cursor.currentSpan());else if(i.isGroup)this.parseGroupBody(n);else switch(i.polymerType){case ne.PEPTIDE:this.parsePeptideBody(n);break;case ne.RNA:this.parseRnaBody(n,i.isDnaShim),i.isDnaShim&&this.emit("info","dna-emitted-as-rna",`DNA polymer '${n.id}' will be emitted as RNA on canonicalize`,t.span);break;case ne.CHEM:this.parseChemBody(n);break;case ne.BLOB:this.parseBlobBody(n)}if(null===this.cursor.optional("rbrace"))return this.emit("error","unterminated-brace",`Expected '}' to close polymer '${n.id}'`,this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let o=this.cursor.optional("quote-string");null!==o&&(n.annotation=o.value)}parsePeptideBody(e){for(this.parsePeptideItem(e);this.cursor.at("dot")&&(this.cursor.advance(),!this.cursor.at("rbrace")&&!this.cursor.at("gt"));)this.parsePeptideItem(e);if(this.cursor.at("gt")){let t=this.cursor.currentSpan();this.cursor.advance(),this.emit("warning","peptide-cyclic-without-closure",`Peptide '${e.id}' marked cyclic with '>' — no explicit closure connection emitted`,t)}}parsePeptideItem(e){if(this.cursor.at("lparen"))this.parsePeptideAlternation(e);else{let t=this.parsePeptideAtom(e);this.maybeRepeatBracket(e,[t])}this.maybeAttachAnnotation(e)}parsePeptideAtom(e){let t=this.consumeMonomerSymbol(!1),{symbol:i,annotation:n,ambiguity:o,ambiguityKind:r,isInlineSmiles:s,rawPayload:a,inlineSource:l,span:h}=t,d=this.makeAtom(e,X,i);void 0!==n&&(d.tag=n),void 0!==o&&(d.bio.ambiguity=o),void 0!==r&&(d.bio.ambiguityKind=r),void 0!==l&&(d.inlineSource=l),s&&this.registerInlineSmiles(a,h,ne.PEPTIDE),this.addToChain(e,d,!0);let c=e.backboneAtoms[e.backboneAtoms.length-2];return void 0!==c&&this.addBond(e,c,d,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),d}parsePeptideAlternation(e){let t=this.cursor.currentSpan();if(this.cursor.advance(),this.peptideContentIsSubsequence()){let t=e.backboneAtoms.length;for(this.parsePeptideItem(e);this.cursor.at("dot")&&(this.cursor.advance(),!this.cursor.at("rparen")&&!this.cursor.isAtEnd());)this.parsePeptideItem(e);null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' to close repeat sub-sequence",this.cursor.currentSpan());let i=e.backboneAtoms.slice(t);return this.maybeRepeatBracket(e,i),void this.maybeAttachAnnotation(e)}let i=[],n=null;for(;!this.cursor.at("rparen")&&!this.cursor.isAtEnd();){let e=this.parseAlternationCandidate(ne.PEPTIDE);if(i.push(e),this.cursor.at("comma"))"and"===n&&this.emit("warning","mixed-separator-in-alternation","Mixed ',' and '+' separators in alternation",this.cursor.currentSpan()),n="or",this.cursor.advance();else{if(!this.cursor.at("plus"))break;"or"===n&&this.emit("warning","mixed-separator-in-alternation","Mixed ',' and '+' separators in alternation",this.cursor.currentSpan()),n="and",this.cursor.advance()}}null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' to close alternation",this.cursor.currentSpan());let o="and"===n?"+":",",r=`(${i.map(e=>e.symbol+(void 0!==e.ratio?`:${String(e.ratio)}`:"")).join(o)})`,s=this.makeAtom(e,X,"?");s.bio.ambiguity=r,s.bio.ambiguityKind="and"===n?"and":"or",this.addToChain(e,s,!0);let a=e.backboneAtoms[e.backboneAtoms.length-2];if(void 0!==a&&this.addBond(e,a,s,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),"and"===n)for(let e of i)"number"==typeof e.ratio&&e.ratio<0&&this.emit("error","ratio-and-negative",`Negative ratio ${e.ratio} in AND mixture`,t);this.maybeRepeatBracket(e,[s]),this.maybeAttachAnnotation(e)}peptideContentIsSubsequence(){let e=1,t=0;for(;;){let i=this.cursor.peek(t);if("eof"===i.kind)return!1;if("lparen"!==i.kind)if("rparen"!==i.kind){if(1===e){if("dot"===i.kind)return!0;if("comma"===i.kind||"plus"===i.kind||"colon"===i.kind)return!1}if(t+=1,t>1024)return!1}else{if(e-=1,0===e)return!0;t+=1}else e+=1,t+=1}}parseAlternationCandidate(e){let t,{symbol:i,isInlineSmiles:n,rawPayload:o,span:r}=this.consumeMonomerSymbol(!0);if(n&&this.registerInlineSmiles(o,r,e),null!==this.cursor.optional("colon")){let e=this.cursor.peek();"integer"===e.kind||"decimal"===e.kind?(this.cursor.advance(),t=parseFloat(e.value)):"question"===e.kind?(this.cursor.advance(),t="?"):this.emit("error","unexpected-token","Expected ratio after ':' in alternation",e.span)}return void 0===t?{symbol:i}:{symbol:i,ratio:t}}parseRnaBody(e,t){for(this.parseRnaItem(e,t);this.cursor.at("dot")&&(this.cursor.advance(),!(this.cursor.at("rbrace")||this.cursor.at("dollar")||this.cursor.isAtEnd()));)this.parseRnaItem(e,t)}parseRnaItem(e,t){if(this.cursor.at("lparen"))return void this.parseRnaAlternation(e,t);if(this.cursor.at("asterisk")){this.cursor.currentSpan(),this.cursor.advance();let t=this.makeAtom(e,ie,"*");this.addToChain(e,t,!0);let i=e.backboneAtoms[e.backboneAtoms.length-2];return void 0!==i&&this.addBond(e,i,t,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),this.maybeRepeatBracket(e,[t]),void this.maybeAttachAnnotation(e)}let i,n,o=this.parseRnaSugar(e,t);this.maybeAttachAnnotation(e),this.cursor.at("lparen")&&(this.cursor.advance(),this.cursor.at("rparen")||(i=this.parseRnaBaseSymbol(e),this.maybeAttachAnnotationTo(i)),null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' after RNA base",this.cursor.currentSpan()),void 0!==i&&(this.addBond(e,o,i,"branch",{kind:"numeric",r:3},{kind:"numeric",r:1}),o.branchAtom=i)),this.canStartRnaLinker()&&(n=this.parseRnaLinker(e),this.maybeAttachAnnotationTo(n)),void 0!==n&&this.addBond(e,o,n,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1});let r=e.backboneAtoms.indexOf(o);if(r>0){let t=e.backboneAtoms[r-1];this.addBond(e,t,o,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1})}let s=[o];void 0!==i&&s.push(i),void 0!==n&&s.push(n),this.maybeRepeatBracket(e,s)}canStartRnaLinker(){let e=this.cursor.peek().kind;return"identifier"===e||"inline-smiles"===e||"asterisk"===e}parseRnaSugar(e,t){let{symbol:i,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(!1),a=this.makeAtom(e,Q,i);return void 0!==r&&(a.inlineSource=r),n&&this.registerInlineSmiles(o,s,ne.RNA),this.addToChain(e,a,!0),a}parseRnaBaseSymbol(e){let{symbol:t,isInlineSmiles:i,rawPayload:n,inlineSource:o,span:r}=this.consumeMonomerSymbol(!1),s=this.makeAtom(e,Z,t);return void 0!==o&&(s.inlineSource=o),i&&this.registerInlineSmiles(n,r,ne.RNA),this.addToChain(e,s,!1),s}parseRnaLinker(e){if(this.cursor.at("asterisk")){this.cursor.currentSpan(),this.cursor.advance();let t=this.makeAtom(e,J,"*");return this.addToChain(e,t,!0),t}let{symbol:t,isInlineSmiles:i,rawPayload:n,inlineSource:o,span:r}=this.consumeMonomerSymbol(!1),s=this.makeAtom(e,J,t);return void 0!==o&&(s.inlineSource=o),i&&this.registerInlineSmiles(n,r,ne.RNA),this.addToChain(e,s,!0),s}parseRnaAlternation(e,t){let i=e.backboneAtoms.length;if(this.cursor.advance(),this.looksLikeFlatAlternation()){let t=[],i=null;for(;!this.cursor.at("rparen")&&!this.cursor.isAtEnd();)if(t.push(this.parseAlternationCandidate(ne.RNA)),this.cursor.at("comma"))i="or",this.cursor.advance();else{if(!this.cursor.at("plus"))break;i="and",this.cursor.advance()}null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' in RNA alternation",this.cursor.currentSpan());let n="and"===i?"+":",",o=`(${t.map(e=>e.symbol+(void 0!==e.ratio?`:${String(e.ratio)}`:"")).join(n)})`,r=this.makeAtom(e,Z,"?");r.bio.ambiguity=o,r.bio.ambiguityKind="and"===i?"and":"or",this.addToChain(e,r,!0);let s=e.backboneAtoms[e.backboneAtoms.length-2];return void 0!==s&&this.addBond(e,s,r,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),this.maybeRepeatBracket(e,[r]),void this.maybeAttachAnnotation(e)}for(this.parseRnaItem(e,t);this.cursor.at("dot")&&(this.cursor.advance(),!this.cursor.at("rparen")&&!this.cursor.isAtEnd());)this.parseRnaItem(e,t);null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' in RNA repeat",this.cursor.currentSpan());let n=e.backboneAtoms.slice(i);this.maybeRepeatBracket(e,n),this.maybeAttachAnnotation(e)}looksLikeFlatAlternation(){let e=1,t=0,i=!1;for(;;){let n=this.cursor.peek(t);if("eof"===n.kind)return i;if("rparen"===n.kind){if(e-=1,0===e)return i}else{if("lparen"===n.kind)return!1;if("dot"===n.kind)return!1;1===e&&("comma"===n.kind||"plus"===n.kind)&&(i=!0)}if(t+=1,t>256)return i}}parseChemBody(e){let t;if(this.cursor.at("asterisk"))this.cursor.advance(),t=this.makeAtom(e,ee,"*"),this.addToChain(e,t,!0);else{let{symbol:i,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(!1);t=this.makeAtom(e,ee,i),void 0!==r&&(t.inlineSource=r),n&&this.registerInlineSmiles(o,s,ne.CHEM),this.addToChain(e,t,!0)}this.maybeAttachAnnotation(e),this.cursor.at("apos")&&this.maybeRepeatBracket(e,[t]),this.cursor.at("rbrace")||(this.emit("error","chem-multiple-monomers",`CHEM polymer '${e.id}' must contain exactly one monomer`,this.cursor.currentSpan()),this.skipUntil(["rbrace","eof"]))}parseBlobBody(e){let t,i,n,o=!1,r="",s=this.cursor.currentSpan();if(this.cursor.at("inline-smiles")){let e=this.cursor.advance();o=se(e.value),r=e.value,t=e.value,i=e.value,n=e.value,s=e.span}else if(this.cursor.at("identifier")){let e=this.cursor.advance();t=e.value,i=e.value,s=e.span}else this.emit("error","unknown-blobtype","Expected BLOB identifier",this.cursor.currentSpan()),t="?",i="?";let a=this.makeAtom(e,te,t);a.bio.blobtype=i,void 0!==n&&(a.inlineSource=n),o&&this.registerInlineSmiles(r,s,ne.BLOB),this.addToChain(e,a,!0),this.maybeAttachAnnotation(e)}parseGroupBody(e){let t=0;for(;;){let e=this.cursor.peek();if("eof"===e.kind||0===t&&"rbrace"===e.kind)break;"lbrace"===e.kind&&(t+=1),"rbrace"===e.kind&&(t-=1),this.cursor.advance()}}parseConnections(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd())for(this.parseConnection();this.cursor.at("pipe")&&(this.cursor.advance(),!this.cursor.at("dollar")&&!this.cursor.isAtEnd());)this.parseConnection()}parseConnection(){let e=this.cursor.currentSpan(),t=this.cursor.optional("identifier");if(null===t)return this.emit("error","unexpected-token","Expected chain id in connection",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);if(null===this.cursor.optional("comma"))return this.emit("error","unexpected-token","Expected ',' in connection",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let i=this.cursor.optional("identifier");if(null===i)return this.emit("error","unexpected-token","Expected second chain id in connection",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);if(null===this.cursor.optional("comma"))return this.emit("error","unexpected-token","Expected ',' before connection position",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let n=this.parsePosition();if(null===this.cursor.optional("colon"))return this.emit("error","unexpected-token","Expected ':' between position and R-group",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let o=this.parseRGroupSpec();if(null===this.cursor.optional("dash"))return this.emit("error","unexpected-token","Expected '-' between connection endpoints",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let r=this.parsePosition();if(null===this.cursor.optional("colon"))return this.emit("error","unexpected-token","Expected ':' before second R-group",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let s=this.parseRGroupSpec(),a=this.cursor.optional("quote-string"),l="pair"===o.kind&&"pair"===s.kind?"hbond":"cross-polymer",h={chain1:t.value,pos1:n,r1:o,chain2:i.value,pos2:r,r2:s,kind:l,span:{start:e.start,end:a?.span.end??this.cursor.peek().span.start},...null!==a?{tag:a.value}:{}};this.pendingBonds.push(h)}parsePosition(){let e=this.cursor.peek();return"integer"===e.kind?(this.cursor.advance(),{kind:"index",value:parseInt(e.value,10)}):"question"===e.kind?(this.cursor.advance(),{kind:"any"}):"identifier"===e.kind?(this.cursor.advance(),this.emit("info","symbol-position-reference",`Connection position uses monomer symbol '${e.value}' as chain-level ambiguity`,e.span),{kind:"symbol",value:e.value}):(this.emit("error","invalid-position",`Expected position (integer, '?', or symbol), got '${e.value}'`,e.span),{kind:"any"})}parseRGroupSpec(){let e=this.cursor.peek();if("question"===e.kind)return this.cursor.advance(),{kind:"unspecified"};if("asterisk"===e.kind)return this.cursor.advance(),{kind:"wildcard"};if("identifier"===e.kind){if(this.cursor.advance(),"pair"===e.value)return{kind:"pair"};let t=/^R([1-9][0-9]*)$/.exec(e.value);return null===t?(this.emit("error","invalid-rgroup",`Expected R-group label, got '${e.value}'`,e.span),{kind:"unspecified"}):{kind:"numeric",r:parseInt(t[1],10)}}return this.emit("error","invalid-rgroup",`Expected R-group label, got '${e.value}'`,e.span),{kind:"unspecified"}}parseGroupsSection(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd())for(this.parseGroupOrBondRatio();this.cursor.at("pipe")&&(this.cursor.advance(),!this.cursor.at("dollar")&&!this.cursor.isAtEnd());)this.parseGroupOrBondRatio()}parseGroupOrBondRatio(){let e=this.cursor.optional("identifier");if(null===e)return this.emit("error","unexpected-token","Expected group or bond-ratio identifier",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);this.cursor.at("lparen")?this.parseGroupAfterId(e):this.cursor.at("plus")?this.parseBondRatioAfterId(e):(this.emit("warning","unexpected-token",`Expected '(' or '+' after id '${e.value}' in section 3`,this.cursor.currentSpan()),this.skipUntil(["pipe","dollar","eof"]))}parseGroupAfterId(e){let t=ze(e.value);(null===t||!t.isGroup)&&this.emit("error","unknown-group-reference",`Group id must be 'G<n>', got '${e.value}'`,e.span),this.cursor.advance();let i=[],n="or",o=null;for(;!this.cursor.at("rparen")&&!this.cursor.isAtEnd();){let e=this.parseGroupMember();if(null!==e&&i.push(e),this.cursor.at("comma"))null===o&&(o="or",n="or"),this.cursor.advance();else{if(!this.cursor.at("plus"))break;null===o&&(o="and",n="and"),this.cursor.advance()}}null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' to close group",this.cursor.currentSpan()),this.groups.push({id:e.value,kind:n,members:i})}parseGroupMember(){let e,t=this.cursor.optional("identifier");return null===t?(this.emit("error","unexpected-token","Expected group member id",this.cursor.currentSpan()),null):(null!==this.cursor.optional("colon")&&(e=this.parseRatio()),void 0===e?{target:t.value}:{target:t.value,ratio:e})}parseRatio(){let e=this.cursor.peek();if("integer"===e.kind||"decimal"===e.kind){this.cursor.advance();let t=parseFloat(e.value);if(this.cursor.at("dash")&&(this.cursor.peek(),"integer"===this.cursor.peek(1).kind)){this.cursor.advance();let t=this.cursor.advance();this.emit("info","ratio-range",`Ratio range ${e.value}-${t.value}; using lower bound`,{start:e.span.start,end:t.span.end})}return t}return"question"===e.kind?(this.cursor.advance(),"?"):(this.emit("error","unexpected-token",`Expected ratio after ':', got '${e.value}'`,e.span),0)}parseBondRatioAfterId(e){this.cursor.advance();let t,i=this.cursor.optional("identifier");if(null===i)return void this.emit("error","unexpected-token","Expected second chain id in bond-ratio",this.cursor.currentSpan());if(null!==this.cursor.optional("colon")){let e=this.parseRatio();"number"==typeof e&&(t=e)}let n=this.pendingBonds.find(t=>t.chain1===e.value&&t.chain2===i.value||t.chain1===i.value&&t.chain2===e.value);void 0!==n?void 0!==t&&(n.ratio={numerator:t}):this.emit("warning","bond-ratio-no-matching-bond",`Bond-ratio for ${e.value}+${i.value} has no matching cross-polymer bond`,e.span)}parseAnnotationsSection(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd()){if(this.cursor.position(),this.cursor.at("lbrace"))return this.parseAnnotation20(),void(this.cursor.at("pipe")&&(this.emit("info","annotation-mixed-versions","Mixed HELM 2.0 JSON and HELM 1.0 pipe annotations",this.cursor.currentSpan()),this.cursor.advance(),this.parseAnnotation10Entries()));this.parseAnnotation10Entries()}}parseAnnotation20(){let e=this.cursor.currentSpan(),t=0,i=e.end;for(;!this.cursor.isAtEnd();){let e=this.cursor.peek();if("lbrace"===e.kind)t+=1;else if("rbrace"===e.kind&&(t-=1,0===t)){i=e.span.end,this.cursor.advance();break}this.cursor.advance()}let n=this.source.slice(e.start,i),o=null;try{o=JSON.parse(n)}catch{return this.emit("warning","annotation-malformed-json","Annotation block is not valid JSON",{start:e.start,end:i}),void(this.annotations={perPolymer:this.annotations.perPolymer,version:this.annotations.version,raw:n})}if(null===o||"object"!=typeof o||Array.isArray(o))this.emit("warning","annotation-malformed-json","Annotation block parsed but is not an object",{start:e.start,end:i}),this.annotations={perPolymer:this.annotations.perPolymer,version:this.annotations.version,raw:n};else{let t=new Map(this.annotations.perPolymer);for(let[i,n]of Object.entries(o))null===n||"object"!=typeof n||Array.isArray(n)?t.set(i,{value:n}):(t.set(i,{...n}),this.chainById.has(i)||this.emit("warning","annotation-unknown-polymer",`Annotation references unknown polymer '${i}'`,e));this.annotations={perPolymer:t,version:this.annotations.version}}}parseAnnotation10Entries(){for(this.parseAnnotation10One();this.cursor.at("pipe")&&(this.cursor.advance(),!this.cursor.at("dollar")&&!this.cursor.isAtEnd());)this.parseAnnotation10One()}parseAnnotation10One(){let e=this.cursor.optional("identifier");if(null===e)return this.emit("warning","annotation-malformed-json","Expected polymer-id in HELM 1.0 annotation",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);if(null===this.cursor.optional("lbrace"))return this.emit("warning","annotation-malformed-json","Expected '{' after polymer-id",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let t=[];for(;!this.cursor.at("rbrace")&&!this.cursor.isAtEnd();)t.push(this.cursor.advance().value);if(null===this.cursor.optional("rbrace"))return void this.emit("error","unterminated-brace","Expected '}' to close annotation",this.cursor.currentSpan());let i=t.join("").trim(),n=new Map(this.annotations.perPolymer),o=n.get(e.value)??{};"ss"===i||"as"===i?n.set(e.value,{...o,strandtype:i}):n.set(e.value,{...o,[i]:!0}),this.chainById.has(e.value)||this.emit("warning","annotation-unknown-polymer",`Annotation references unknown polymer '${e.value}'`,e.span),this.annotations={perPolymer:n,version:this.annotations.version}}parseVersionTrailer(){let e=this.cursor.optional("identifier");if(null===e)return void(this.annotations={...this.annotations,version:""});let t=e.value;if(this.cursor.at("dot")&&"integer"===this.cursor.peek(1).kind){this.cursor.advance();let i=this.cursor.advance();t=`${e.value}.${i.value}`}this.annotations={...this.annotations,version:t}}skipUntil(e){for(;!this.cursor.isAtEnd();){if(e.includes(this.cursor.peek().kind))return;this.cursor.advance()}}consumeMonomerSymbol(e){let t=this.cursor.peek();if("inline-smiles"===t.kind){this.cursor.advance();let e=se(t.value);return{symbol:t.value,isInlineSmiles:e,rawPayload:t.value,inlineSource:t.value,span:t.span}}if("identifier"===t.kind){this.cursor.advance();let e=t.value,i=t.span;for(;"dash"===this.cursor.peek().kind&&"integer"===this.cursor.peek(1).kind&&("identifier"===this.cursor.peek(2).kind||"dash"===this.cursor.peek(2).kind);){this.cursor.advance();let t=this.cursor.advance();if(e=`${e}-${t.value}`,i=t.span,"identifier"===this.cursor.peek().kind){let t=this.cursor.advance();e=`${e}${t.value}`,i=t.span}}return{symbol:e,isInlineSmiles:!1,rawPayload:e,span:{start:t.span.start,end:i.end}}}if("asterisk"===t.kind||"underscore"===t.kind||"question"===t.kind)return this.cursor.advance(),{symbol:t.value,isInlineSmiles:!1,rawPayload:t.value,span:t.span};if("integer"===t.kind&&"identifier"===this.cursor.peek(1).kind){let e=this.cursor.advance(),t=this.cursor.advance(),i=`${e.value}${t.value}`;return{symbol:i,isInlineSmiles:!1,rawPayload:i,span:{start:e.span.start,end:t.span.end}}}return this.emit("error","unexpected-token",`Expected monomer symbol, got '${t.value}'`,t.span),{symbol:"?",isInlineSmiles:!1,rawPayload:"",span:t.span}}maybeRepeatBracket(e,t){if(!this.cursor.at("apos"))return;let i=this.cursor.currentSpan();this.cursor.advance();let n=this.cursor.optional("integer");if(null===n)return this.emit("error","unexpected-token","Expected integer in repeat bracket",this.cursor.currentSpan()),void this.cursor.optional("apos");let o=parseInt(n.value,10),r=o;if(this.cursor.at("dash")){this.cursor.advance();let e=this.cursor.optional("integer");null===e?this.emit("error","unexpected-token","Expected integer after '-' in repeat bracket",this.cursor.currentSpan()):r=parseInt(e.value,10)}if(null===this.cursor.optional("apos")&&this.emit("error","unterminated-apostrophe","Expected closing apostrophe",this.cursor.currentSpan()),0!==t.length){if(r<o){this.emit("warning","repeat-range-inverted",`Repeat range ${o}-${r} has max < min; swapping`,i);let e=o;o=r,r=e}0!==o||0!==r?(r>1e4&&this.emit("warning","bracket-repeat-too-large",`Repeat range upper bound ${r} > 10000`,i),e.polymerType===ne.CHEM&&this.emit("error","repeat-on-non-iterable-polymer",`Repeat bracket not allowed on CHEM polymer '${e.id}'`,i),this.groups.push({id:`${e.id}/bracket@${t[0]?.id??0}`,kind:"bracket",members:t.map(e=>({target:String(e.id)})),repeat:{min:o,max:r}})):this.emit("warning","repeat-zero-count","Repeat bracket with zero count",i)}else this.emit("warning","repeat-on-empty-bracket","Repeat bracket applied to empty content",i)}maybeAttachAnnotation(e){let t=e.backboneAtoms[e.backboneAtoms.length-1];void 0!==t&&this.maybeAttachAnnotationTo(t)}maybeAttachAnnotationTo(e){if(void 0===e)return;let t=this.cursor.optional("quote-string");null!==t&&(e.tag=t.value)}registerInlineSmiles(e,t,i){if(se(e)){if(null===this.lib)return void this.emit("info","inline-smiles-no-lib","Inline SMILES seen but no monomer library available for registration",t);try{this.lib.addMonomer;let t=this.lib.registerInlineSmilesMonomer;"function"==typeof t&&t.call(this.lib,i,e)}catch(e){let i=e instanceof Error?e.message:String(e);this.emit("warning","inline-smiles-without-r-groups",`Inline SMILES registration failed: ${i}`,t)}}}makeAtom(e,t,i){return{id:this.atomIds.next(),p:{x:0,y:0},biotype:t,symbol:i,monomer:null,bio:{chainId:e.id,positionInChain:0,continuousId:0},hidden:!1,selected:!1,highlighted:!1}}addToChain(e,t,i){e.allAtoms.push(t),i&&(e.backboneAtoms.push(t),t.bio.positionInChain=e.backboneAtoms.length)}addBond(e,t,i,n,o,r){let s=this.bondIds.next();e.bonds.push({id:s,a1:t,a2:i,kind:n,r1:o,r2:r})}finalize(){let e=[];for(let t of this.pendingBonds){let i=this.chainById.get(t.chain1),n=this.chainById.get(t.chain2);if(void 0===i){this.emit("error","unknown-chain-reference",`Connection references unknown chain '${t.chain1}'`,t.span);continue}if(void 0===n){this.emit("error","unknown-chain-reference",`Connection references unknown chain '${t.chain2}'`,t.span);continue}let o=this.resolveAtomByPosition(i,t.pos1,t.span),r=this.resolveAtomByPosition(n,t.pos2,t.span);if(null===o||null===r)continue;"pair"===t.r1.kind&&void 0!==o.branchAtom&&(o=o.branchAtom),"pair"===t.r2.kind&&void 0!==r.branchAtom&&(r=r.branchAtom);let s={id:this.bondIds.next(),a1:o,a2:r,kind:t.kind,r1:t.r1,r2:t.r2,...void 0!==t.tag?{tag:t.tag}:{},...void 0!==t.ratio?{ratio:t.ratio}:{}};e.push(s)}let t=[],i=[],n=[];for(let e of this.chains){for(let i of e.allAtoms)t.push(i);for(let t of e.bonds)i.push(t);let o=this.annotations.perPolymer.get(e.id),r=void 0===o?void 0:o.strandtype,s="ss"===r||"as"===r?r:void 0;n.push({id:e.id,polymerType:e.polymerType,backboneAtoms:e.backboneAtoms,bonds:e.bonds,...void 0!==e.annotation?{annotation:e.annotation}:{},...void 0!==s?{strandType:s}:{}})}for(let t of e)i.push(t);let o=0;for(let e of this.chains)for(let t of e.backboneAtoms)o+=1,t.bio.continuousId=o,void 0!==t.branchAtom&&(o+=1,t.branchAtom.bio.continuousId=o);let r=[];for(let e of this.groups)r.push({id:e.id,kind:e.kind,members:e.members,...void 0!==e.repeat?{repeat:e.repeat}:{}});return{atoms:t,bonds:i,chains:n,groups:r,annotations:this.annotations}}sourceOrderAtoms(e){let t=[];for(let i of e.backboneAtoms)t.push(i),void 0!==i.branchAtom&&t.push(i.branchAtom);return t}resolveAtomByPosition(e,t,i){if("any"===t.kind)return e.backboneAtoms[0]??null;if("symbol"===t.kind){let n=e.backboneAtoms.find(e=>e.symbol===t.value);if(void 0===n){let n=e.allAtoms.find(e=>e.symbol===t.value);return void 0===n?(this.emit("warning","position-out-of-range",`Chain '${e.id}' has no monomer with symbol '${t.value}'`,i),e.backboneAtoms[0]??null):n}return n}let n=this.sourceOrderAtoms(e),o=t.value;return o<1||o>n.length?(this.emit("error","position-out-of-range",`Position ${o} out of range for chain '${e.id}' (length ${n.length})`,i),e.backboneAtoms[0]??null):n[o-1]}emit(e,t,i,n){let o={severity:e,code:t,message:i,...void 0!==n?{span:{start:n.start,end:n.end}}:{}};if(this.diagnostics.push(o),"strict"===this.mode&&"error"===e)throw new R(t,i,{...void 0!==n?{span:{start:n.start,end:n.end}}:{}})}};function qe(e,t){let i=function(e){let t=(t,i)=>t.polymerType===ne.CHEM||t.polymerType===ne.BLOB||!function(e,t,i){for(let n of i){if("backbone"!==n.kind||"numeric"!==n.r1.kind||"numeric"!==n.r2.kind)continue;let i=n.a1.id===e.id&&n.a2.id===t.id&&2===n.r1.r&&1===n.r2.r,o=n.a1.id===t.id&&n.a2.id===e.id&&2===n.r1.r&&1===n.r2.r;if(i||o)return!0}return!1}(t.backboneAtoms[i],t.backboneAtoms[i+1],e.bonds),i=!1;for(let n of e.chains){for(let e=0;e<n.backboneAtoms.length-1;e++)if(t(n,e)){i=!0;break}if(i)break}if(!i)return e;let n=new Set(e.chains.map(e=>e.id)),o=e=>{let t=1;for(;n.has(`${e}${t}`);)t+=1;let i=`${e}${t}`;return n.add(i),i},r=[];for(let i of e.chains){let e=[[]],n=e[0];for(let o=0;o<i.backboneAtoms.length;o++){let r=i.backboneAtoms[o];n.push(r),o<i.backboneAtoms.length-1&&t(i,o)&&(n=[],e.push(n))}for(let t=0;t<e.length;t++){let n={id:0===t?i.id:o(i.polymerType),polymerType:i.polymerType,atoms:e[t]};0===t&&void 0!==i.annotation&&(n.annotation=i.annotation),r.push(n)}}let s=new Map;for(let e of r)for(let t=0;t<e.atoms.length;t++){let i=e.atoms[t];s.set(i.id,{chainId:e.id,pos:t+1}),void 0!==i.branchAtom&&s.set(i.branchAtom.id,{chainId:e.id,pos:t+1})}let a=new Map;for(let t of e.atoms){let e=s.get(t.id);void 0===e||t.bio.chainId===e.chainId&&t.bio.positionInChain===e.pos?a.set(t.id,t):a.set(t.id,{...t,bio:{...t.bio,chainId:e.chainId,positionInChain:e.pos}})}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=a.get(t.id),i=a.get(t.branchAtom.id);void 0===e||void 0===i||(e.branchAtom=i)}let l=e.bonds.map(e=>{let t=a.get(e.a1.id)??e.a1,i=a.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}}),h=r.map(e=>{let t=e.atoms.map(e=>a.get(e.id)??e),i=new Set;for(let t of e.atoms)i.add(t.id),void 0!==t.branchAtom&&i.add(t.branchAtom.id);let n=[];for(let e of l)i.has(e.a1.id)&&i.has(e.a2.id)&&n.push(e);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>a.get(e.id)??e),bonds:l,chains:h,groups:e.groups,annotations:e.annotations}}(e);return new je(i,t??{}).emit()}var je=class{constructor(e,t){this.mol=e,this.options=t}emit(){return`${this.orderedChains().map(e=>this.emitPolymer(e)).join("|")}$${this.emitConnections()}$${this.emitGroupsAndBondRatios()}$${this.emitAnnotations()}${this.versionTrailer()}`}orderedChains(){if(!0!==this.options.canonicalize)return this.mol.chains;let e=this.mol.chains.slice();return e.sort((e,t)=>e.polymerType!==t.polymerType?e.polymerType<t.polymerType?-1:1:e.id<t.id?-1:e.id>t.id?1:0),e}emitPolymer(e){let t=this.emitChainBody(e),i=void 0!==e.annotation?`"${Ve(e.annotation)}"`:"";return`${e.id}{${t}}${i}`}emitChainBody(e){switch(e.polymerType){case"PEPTIDE":return this.emitPeptideBody(e);case"RNA":return this.emitRnaBody(e);case"CHEM":return this.emitChemBody(e);case"BLOB":return this.emitBlobBody(e);default:return""}}emitPeptideBody(e){let t=this.bracketsForChain(e.id),i=[],n=0,o=0,r=null;for(;n<e.backboneAtoms.length;){let s=e.backboneAtoms[n],a=t.find(e=>e.startAtomId===s.id);void 0!==a&&null===r&&(i.push("("),r=a,o+=1),i.push(this.emitMonomerToken(s));let l=void 0!==s.tag?`"${Ve(s.tag)}"`:"";i.push(l),null!==r&&r.endAtomId===s.id&&(i.push(`)${Ye(r.min,r.max)}`),r=null,o-=1),n+=1,n<e.backboneAtoms.length&&i.push(".")}return i.join("")}emitRnaBody(e){let t=this.bracketsForChain(e.id),i=[],n=0,o=!0,r=null,s=e=>{null!==r&&r.endAtomId===e&&(i.push(`)${Ye(r.min,r.max)}`),r=null)},a=e=>{let n=t.find(t=>t.startAtomId===e);void 0!==n&&null===r&&(i.push("("),r=n)};for(;n<e.backboneAtoms.length;){let t=e.backboneAtoms[n];if(o||i.push("."),o=!1,t.biotype!==ie){if(t.biotype===Q){a(t.id),i.push(this.emitMonomerToken(t)),void 0!==t.tag&&i.push(`"${Ve(t.tag)}"`),void 0!==t.branchAtom&&(i.push("("),i.push(this.emitMonomerToken(t.branchAtom)),void 0!==t.branchAtom.tag&&i.push(`"${Ve(t.branchAtom.tag)}"`),i.push(")"));let o=e.backboneAtoms[n+1];void 0!==o&&o.biotype===J?(i.push(this.emitMonomerToken(o)),void 0!==o.tag&&i.push(`"${Ve(o.tag)}"`),s(o.id),n+=2):(s(t.id),n+=1);continue}a(t.id),i.push(this.emitMonomerToken(t)),void 0!==t.tag&&i.push(`"${Ve(t.tag)}"`),s(t.id),n+=1}else a(t.id),i.push(this.emitMonomerToken(t)),void 0!==t.tag&&i.push(`"${Ve(t.tag)}"`),s(t.id),n+=1}return i.join("")}emitChemBody(e){let t=e.backboneAtoms[0];if(void 0===t)return"";let i=void 0!==t.tag?`"${Ve(t.tag)}"`:"";return`${this.emitMonomerToken(t)}${i}`}emitBlobBody(e){let t=e.backboneAtoms[0];if(void 0===t)return"";let i=void 0!==t.tag?`"${Ve(t.tag)}"`:"";return`${this.emitMonomerToken(t)}${i}`}emitMonomerToken(e){let t;return t=void 0!==e.inlineSource?`[${e.inlineSource}]`:void 0===e.bio.ambiguity||"?"!==e.symbol&&!e.bio.ambiguity.startsWith("(")?e.symbol:e.bio.ambiguity,!0===this.options.includeHighlights&&e.selected?`<span style='background:#bbf;'>${t}</span>`:t}emitConnections(){let e=[];for(let t of this.crossPolymerBonds())e.push(this.emitConnection(t));return e.join("|")}*crossPolymerBonds(){let e=new Map;for(let t of this.mol.chains){let i=new Map;for(let e=0;e<t.backboneAtoms.length;e++)i.set(t.backboneAtoms[e].id,e);e.set(t.id,i)}for(let t of this.mol.bonds)if("backbone"!==t.kind)if("branch"!==t.kind)yield t;else{if(void 0!==t.a1.branchAtom&&t.a1.branchAtom.id===t.a2.id||void 0!==t.a2.branchAtom&&t.a2.branchAtom.id===t.a1.id)continue;yield t}else{if(t.a1.bio.chainId===t.a2.bio.chainId){let i=e.get(t.a1.bio.chainId);if(void 0!==i){let e=i.get(t.a1.id),n=i.get(t.a2.id);if(void 0!==e&&void 0!==n&&1===Math.abs(e-n))continue}}yield t}}emitConnection(e){let t=We(e.r1,e.kind),i=We(e.r2,e.kind),n=void 0!==e.tag?`"${Ve(e.tag)}"`:"",o=String(this.connectionPosition(e.a1)),r=String(this.connectionPosition(e.a2));return`${e.a1.bio.chainId},${e.a2.bio.chainId},${o}:${t}-${r}:${i}${n}`}connectionPosition(e){return K(e,this.mol.chains.find(t=>t.id===e.bio.chainId))}emitGroupsAndBondRatios(){let e=[];for(let t of this.mol.groups)"bracket"!==t.kind&&e.push(this.emitGroup(t));for(let t of this.mol.bonds){if("cross-polymer"!==t.kind||void 0===t.ratio)continue;let i=void 0!==t.ratio.denominator?`${t.ratio.numerator}/${t.ratio.denominator}`:`${t.ratio.numerator}`;e.push(`${t.a1.bio.chainId}+${t.a2.bio.chainId}:${i}`)}return e.join("|")}emitGroup(e){let t="and"===e.kind?"+":",",i=e.members.map(e=>{return void 0===(t=e).ratio?t.target:`${t.target}:${t.ratio}`;var t}).join(t);return`${e.id}(${i})`}emitAnnotations(){let e=this.mol.annotations.perPolymer;if(0===e.size)return"";let t={};for(let[i,n]of e)t[i]=n;return JSON.stringify(t)}versionTrailer(){let e=this.options.version??"V2.0";if("none"===e)return"";if("preserve"===e){let e=this.mol.annotations.version;return""===e?"":`$${e}`}return`$${e}`}bracketsForChain(e){let t=[],i=new Map;for(let e of this.mol.atoms)i.set(e.id,e.bio.chainId);for(let n of this.mol.groups){if("bracket"!==n.kind)continue;let o=[];for(let e of n.members){let t=parseInt(e.target,10);Number.isFinite(t)&&o.push(t)}if(0===o.length)continue;let r=new Set;for(let e of o){let t=i.get(e);void 0!==t&&r.add(t)}if(!r.has(e)||r.size>1)continue;let s=n.repeat??{min:1,max:1};t.push({members:o,min:s.min,max:s.max,set:new Set(o),startAtomId:o[0],endAtomId:o[o.length-1]})}return t}};function Ve(e){let t="";for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t+=34!==n?92!==n?10!==n?13!==n?9!==n?e.charAt(i):"\\t":"\\r":"\\n":"\\\\":'\\"'}return t}function Ye(e,t){return e===t?`'${e}'`:`'${e}-${t}'`}function We(e,t){switch(e.kind){case"numeric":return`R${e.r}`;case"unspecified":default:return"?";case"wildcard":return"*";case"pair":return"pair";case"positional":return`${e.position}:R${e.r}`}}var Ue=class{constructor(e){this.chainIdMap=new Map,this.mol=e}run(){let e=this.mol.chains.slice().sort((e,t)=>e.polymerType!==t.polymerType?e.polymerType<t.polymerType?-1:1:Qe(e.id,t.id)),t={},i=[];for(let n of e){let e=Ke(n.polymerType);t[e]=(t[e]??0)+1;let o=`${e}${t[e]}`;this.chainIdMap.set(n.id,o),i.push(n)}let n=new Map;for(let e of this.mol.atoms){let t=this.chainIdMap.get(e.bio.chainId)??e.bio.chainId;n.set(e.id,{...e,bio:{...e.bio,chainId:t}})}for(let e of this.mol.atoms){if(void 0===e.branchAtom)continue;let t=n.get(e.id),i=n.get(e.branchAtom.id);void 0!==t&&void 0!==i&&(t.branchAtom=i)}let o=this.mol.bonds.map(e=>({...e,a1:n.get(e.a1.id)??e.a1,a2:n.get(e.a2.id)??e.a2})),r=new Map;for(let e of o)r.set(e.id,e);let s=i.map(e=>{let t=this.chainIdMap.get(e.id)??e.id,i=[];for(let t of e.backboneAtoms){let e=n.get(t.id);void 0!==e&&i.push(e)}let o=[];for(let t of e.bonds){let e=r.get(t.id);void 0!==e&&o.push(e)}return{id:t,polymerType:e.polymerType,backboneAtoms:i,bonds:o,...void 0!==e.annotation&&e.annotation.length>0?{annotation:e.annotation}:{}}}),a=new Map;for(let e of s)a.set(e.id,e);o.sort((e,t)=>{let i=Xe(e.kind),n=Xe(t.kind);if(i&&!n)return 1;if(!i&&n)return-1;if(!i&&!n)return e.id-t.id;let o=e.a1.bio.chainId,r=t.a1.bio.chainId;if(o!==r)return o<r?-1:1;let s=e.a2.bio.chainId,l=t.a2.bio.chainId;if(s!==l)return s<l?-1:1;let h=K(e.a1,a.get(e.a1.bio.chainId)),d=K(t.a1,a.get(t.a1.bio.chainId));return h!==d?h-d:K(e.a2,a.get(e.a2.bio.chainId))-K(t.a2,a.get(t.a2.bio.chainId))});let l=this.renumberGroups(this.mol.groups),h=this.rekeyAnnotations(this.mol.annotations);return{atoms:this.mol.atoms.map(e=>n.get(e.id)),bonds:o,chains:s,groups:l,annotations:h}}renumberGroups(e){let t=[],i=[];for(let n of e)"bracket"===n.kind?t.push(this.rekeyBracket(n)):i.push(n);i.sort((e,t)=>Qe(e.id,t.id));let n={G:0};return i.map(e=>{n.G+=1;let t=`G${n.G}`;return{...e,id:t,members:e.members.map(e=>this.rekeyMember(e))}}).concat(t)}rekeyBracket(e){return e}rekeyMember(e){let t=this.chainIdMap.get(e.target);return void 0===t?e:void 0===e.ratio?{target:t}:{target:t,ratio:e.ratio}}rekeyAnnotations(e){let t=new Map;for(let[i,n]of e.perPolymer){let e=this.chainIdMap.get(i)??i;0!==Object.keys(n).length&&t.set(e,n)}return{perPolymer:t,version:e.version}}};function Ke(e){switch(e){case"PEPTIDE":return"PEPTIDE";case"RNA":return"RNA";case"CHEM":return"CHEM";default:return"BLOB"}}function Xe(e){return"cross-polymer"===e||"hbond"===e}function Qe(e,t){let i=/^([A-Z]+)([0-9]+)$/.exec(e),n=/^([A-Z]+)([0-9]+)$/.exec(t);return null===i||null===n?e<t?-1:e>t?1:0:i[1]!==n[1]?i[1]<n[1]?-1:1:parseInt(i[2],10)-parseInt(n[2],10)}function Ze(e,t){let i=[...e.atoms],n=i[0];for(let e of i)for(let i of t.get(e)??[])if("hbond"===i.kind)throw new N("gap-at-complex-junction",`Gap atom ${e} participates in a hydrogen bond`,{atomId:e});if(e.boundary.length>2)throw new N("gap-at-complex-junction",`Gap atom ${n} sits at a junction of ${e.boundary.length} connections (max 2 allowed)`,{atomId:n,bondCount:e.boundary.length});if(2===e.boundary.length){let t=Je(e,e.boundary[0]),i=Je(e,e.boundary[1]);if(t.atom.id===i.atom.id)throw new N("gap-at-complex-junction",`Removing gap atom ${n} would bond monomer '${t.atom.symbol}' to itself`,{atomId:n})}}function Je(e,t){return e.atoms.has(t.a1.id)?{atom:t.a2,r:t.r2}:{atom:t.a1,r:t.r1}}function et(e,t){return"numeric"===e.kind&&e.r===t}var tt=[function(e,t){let i=[],n=new Set(e.chains.map(e=>e.id));for(let t of e.bonds)"cross-polymer"!==t.kind&&"hbond"!==t.kind||(n.has(t.a1.bio.chainId)||i.push({severity:"error",code:"unknown-chain-reference",message:`Connection references unknown chain '${t.a1.bio.chainId}'`,context:{chainId:t.a1.bio.chainId,bondId:t.id}}),n.has(t.a2.bio.chainId)||i.push({severity:"error",code:"unknown-chain-reference",message:`Connection references unknown chain '${t.a2.bio.chainId}'`,context:{chainId:t.a2.bio.chainId,bondId:t.id}}));for(let t of e.chains)for(let n of e.bonds){if("cross-polymer"!==n.kind&&"hbond"!==n.kind)continue;let e=0;for(let i of t.backboneAtoms)e+=void 0!==i.branchAtom?2:1;for(let o of[n.a1,n.a2]){if(o.bio.chainId!==t.id)continue;let n=K(o,t);(n<1||n>e)&&i.push({severity:"error",code:"position-out-of-range",message:`Position ${n} out of range for chain '${t.id}' (length ${e})`,context:{chainId:t.id,atomId:o.id,found:n}})}}let o=new Set;for(let t of e.groups)"bracket"!==t.kind&&o.add(t.id);for(let t of e.groups)if("bracket"!==t.kind)for(let e of t.members)n.has(e.target)||o.has(e.target)||i.push({severity:"error",code:"unknown-group-reference",message:`Group '${t.id}' references unknown id '${e.target}'`,context:{found:e.target}});let r=new Map;for(let t of e.groups){if("bracket"===t.kind)continue;let e=[];for(let i of t.members)o.has(i.target)&&e.push(i.target);r.set(t.id,e)}for(let e of r.keys()){let t=new Set,n=[e];for(;n.length>0;){let o=n.pop();if(t.has(o))continue;t.add(o);let s=r.get(o)??[];for(let o of s)o===e?i.push({severity:"error",code:"group-cycle",message:`Group cycle detected involving '${e}'`,context:{found:e}}):t.has(o)||n.push(o)}}return i},function(e,t){let i=[];if(null===t)return i;let n=new Map;for(let t of e.chains)n.set(t.id,t.polymerType);for(let t of e.atoms){let e=n.get(t.bio.chainId);if(void 0===e)continue;let o=t.monomer,r=o?.meta;null!==o&&!0!==r?.missing?!0!==r?.ambiguous&&void 0!==o.smiles&&o.smiles.length>0&&(0===o.rgroups.length?i.push({severity:"warning",code:"inline-smiles-without-r-groups",message:`Inline-SMILES monomer '${o.symbol}' has no R-groups`,context:{atomId:t.id,found:o.symbol}}):o.rgroups.length>4&&i.push({severity:"warning",code:"inline-smiles-too-many-rs",message:`Inline-SMILES monomer '${o.symbol}' has ${o.rgroups.length} R-groups (max 4 expected)`,context:{atomId:t.id,found:o.rgroups.length}})):i.push({severity:"warning",code:"unresolved-monomer",message:`Monomer '${t.symbol}' not found in library for ${e}`,context:{chainId:t.bio.chainId,atomId:t.id,found:t.symbol}})}for(let o of e.atoms){let e=n.get(o.bio.chainId);if(void 0!==e&&null===t.getMonomer(e,o.symbol))for(let n of t.getMonomerSymbolsByType(e))if(n!==o.symbol&&n.toLowerCase()===o.symbol.toLowerCase()){i.push({severity:"info",code:"case-mismatch",message:`Symbol '${o.symbol}' differs from library entry '${n}' only in case`,context:{atomId:o.id,found:o.symbol,expected:n}});break}}return i},function(e,t){let i=[],n=new Map;for(let t of e.bonds)for(let[e,o]of[[t.a1,t.r1],[t.a2,t.r2]]){if("numeric"!==o.kind)continue;let r=n.get(e.id)??new Set;r.has(o.r)&&i.push({severity:"error",code:"rgroup-already-bonded",message:`R-group R${o.r} on atom ${e.id} already bonded`,context:{atomId:e.id,bondId:t.id,found:o.r}}),r.add(o.r),n.set(e.id,r)}for(let t of e.bonds){for(let[e,n]of[[t.a1,t.r1],[t.a2,t.r2]]){if("numeric"!==n.kind||null===e.monomer)continue;let o=e.monomer.rs;(n.r<1||n.r>o)&&i.push({severity:"error",code:"rgroup-not-on-monomer",message:`R-group R${n.r} not defined on monomer '${e.symbol}' (rs=${o})`,context:{atomId:e.id,bondId:t.id,found:n.r,expected:`R1..R${o}`}})}"backbone"===t.kind&&"numeric"===t.r1.kind&&"numeric"===t.r2.kind&&(2===t.r1.r&&1===t.r2.r||i.push({severity:"warning",code:"backbone-rgroup-misaligned",message:`Backbone bond uses R${t.r1.r}->R${t.r2.r} (expected R2->R1)`,context:{bondId:t.id,found:`R${t.r1.r}->R${t.r2.r}`}})),"branch"===t.kind&&"numeric"===t.r1.kind&&3!==t.r1.r&&i.push({severity:"warning",code:"branch-rgroup-misaligned",message:`Branch bond uses R${t.r1.r} (expected R3 on parent)`,context:{bondId:t.id,found:`R${t.r1.r}`}})}for(let t of e.atoms){if(null===t.monomer)continue;let e=n.get(t.id)?.size??0;if(t.monomer.rs>e){let n=t.monomer.rs-e;n>0&&t.monomer.rs>0&&i.push({severity:"info",code:"unmatched-r-group",message:`Monomer '${t.symbol}' on atom ${t.id} has ${n} unused R-group(s); default cap applied`,context:{atomId:t.id,found:n}})}}return i},function(e,t){let i=[];for(let t of e.chains){if("CHEM"===t.polymerType&&t.backboneAtoms.length>1&&i.push({severity:"error",code:"chem-multiple-monomers",message:`CHEM polymer '${t.id}' has ${t.backboneAtoms.length} monomers (expected 1)`,context:{chainId:t.id,found:t.backboneAtoms.length}}),"BLOB"===t.polymerType)for(let e of t.backboneAtoms)void 0===e.bio.blobtype&&"Bead"!==e.symbol&&"Group"!==e.symbol&&i.push({severity:"error",code:"blob-non-blob-symbol",message:`BLOB '${t.id}' contains non-blob symbol '${e.symbol}'`,context:{chainId:t.id,atomId:e.id,found:e.symbol}});if("RNA"===t.polymerType){let e=!1;for(let n=0;n<t.backboneAtoms.length;n++){let o=t.backboneAtoms[n];o.biotype===Z&&!e&&i.push({severity:"error",code:"rna-bare-base",message:`Bare base '${o.symbol}' without parent sugar in '${t.id}'`,context:{chainId:t.id,atomId:o.id}}),o.biotype===J&&(t.backboneAtoms.slice(0,n).some(e=>e.biotype===Q)||i.push({severity:"warning",code:"rna-bare-linker",message:`Bare linker '${o.symbol}' before any sugar in '${t.id}'`,context:{chainId:t.id,atomId:o.id}})),e=o.biotype===Q||o.biotype===J}}}return i},function(e,t){let i=[],n=new Map;for(let t of e.chains)n.set(t.id,t.polymerType);let o=new Map;for(let t of e.bonds){if("hbond"!==t.kind)continue;o.set(t.a1.id,(o.get(t.a1.id)??0)+1),o.set(t.a2.id,(o.get(t.a2.id)??0)+1);let e=n.get(t.a1.bio.chainId),r=n.get(t.a2.bio.chainId);("RNA"!==e||"RNA"!==r)&&i.push({severity:"error",code:"pair-non-rna",message:`Hydrogen-bond connects non-RNA chains (${e}/${r})`,context:{bondId:t.id}}),(t.a1.biotype!==Z||t.a2.biotype!==Z)&&i.push({severity:"warning",code:"pair-position-not-base",message:"Hydrogen-bond endpoints are not both bases",context:{bondId:t.id,found:`${t.a1.biotype}/${t.a2.biotype}`}}),it(t.a1.symbol,t.a2.symbol)||i.push({severity:"warning",code:"pair-non-canonical",message:`Non-canonical pair ${t.a1.symbol}-${t.a2.symbol}`,context:{bondId:t.id,found:`${t.a1.symbol}-${t.a2.symbol}`}})}for(let[e,t]of o)t>1&&i.push({severity:"warning",code:"pair-already-paired",message:`Base atom ${e} participates in ${t} pair bonds`,context:{atomId:e,found:t}});return i},function(e,t){let i=[];for(let t of e.atoms){let e=t.bio.ambiguity;if(void 0!==e)if("and"===t.bio.ambiguityKind){let n=nt(e,"+");for(let e of n)void 0!==e.ratio&&e.ratio<0&&i.push({severity:"error",code:"ratio-and-negative",message:`AND ratio for '${e.symbol}' is negative (${e.ratio})`,context:{atomId:t.id,found:e.ratio}})}else if("or"===t.bio.ambiguityKind){let n=nt(e,","),o=0,r=!1;for(let e of n)"number"==typeof e.ratio&&(o+=e.ratio,r=!0);r&&Math.abs(o-1)>.001&&Math.abs(o-100)>.5&&i.push({severity:"info",code:"ratio-doesnt-sum-to-1",message:`OR ratios sum to ${o} (expected 1.0 or 100)`,context:{atomId:t.id,found:o}})}}return i},function(e,t){let i=[],n=new Set(e.chains.map(e=>e.id));for(let t of e.annotations.perPolymer.keys())n.has(t)||i.push({severity:"warning",code:"annotation-unknown-polymer",message:`Annotation references unknown polymer '${t}'`,context:{found:t}});return i},function(e,t){let i=[];for(let t of e.chains)t.backboneAtoms.length>1e4&&i.push({severity:"info",code:"polymer-too-long",message:`Polymer '${t.id}' has ${t.backboneAtoms.length} atoms (> 10000); renderer may switch to rows layout`,context:{chainId:t.id,found:t.backboneAtoms.length}});let n=0;for(let t of e.bonds)("cross-polymer"===t.kind||"hbond"===t.kind)&&(n+=1);n>1e3&&i.push({severity:"info",code:"connection-count-high",message:`${n} cross-polymer/hbond connections (> 1000); rendering may be slow`,context:{found:n}});for(let t of e.groups)"bracket"===t.kind&&void 0!==t.repeat&&t.repeat.max>1e4&&i.push({severity:"warning",code:"bracket-repeat-too-large",message:`Bracket repeat upper bound ${t.repeat.max} > 10000`,context:{found:t.repeat.max}});return i}];function it(e,t){let i=e.toUpperCase(),n=t.toUpperCase();return new Set(["A:T","T:A","A:U","U:A","G:C","C:G"]).has(`${i}:${n}`)}function nt(e,t){let i=e.trim();i.startsWith("(")&&i.endsWith(")")&&(i=i.slice(1,-1));let n=i.split(t),o=[];for(let e of n){let t=e.trim();if(0===t.length)continue;let i=t.indexOf(":");if(i<0){o.push({symbol:t});continue}let n=t.slice(0,i),r=t.slice(i+1),s=parseFloat(r);Number.isFinite(s)?o.push({symbol:n,ratio:s}):o.push({symbol:n})}return o}function ot(e){let t=new Map;for(let i of e)t.set(i.polymerType,(t.get(i.polymerType)??0)+i.backbone.length);let i=e[0].polymerType,n=-1;for(let o of e){let e=t.get(o.polymerType);e>n&&(i=o.polymerType,n=e)}return i}function rt(e,t,i){let n=(e,t)=>"numeric"===e.kind&&e.r===t,o=[[e.a1,e.r1,e.a2,e.r2],[e.a2,e.r2,e.a1,e.r1]];for(let[e,r,s,a]of o){if(!n(r,2)||!n(a,1))continue;let o=i.get(e.id),l=i.get(s.id);if(void 0===o||void 0===l)continue;let h=t[o],d=t[l];if(h.backbone[h.backbone.length-1].id===e.id&&d.backbone[0].id===s.id)return{tail:o,head:l}}return null}function st(e,t,i){let n=new Set,o=t;for(;void 0!==o&&!n.has(o);){if(o===i)return!0;n.add(o),o=e.get(o)}return!1}function at(e){switch(e){case ne.PEPTIDE:return"PEPTIDE";case ne.RNA:return"RNA";case ne.CHEM:return"CHEM";default:return"BLOB"}}function lt(e,t,i,n){if(i.length<2)return!1;let o=i[0],r=i[i.length-1];for(let i of e.bonds){if("backbone"===i.kind||"branch"===i.kind)continue;let e=n.get(i.a1.id),s=n.get(i.a2.id);if(e!==t||s!==t||!(i.a1.id===r.id&&i.a2.id===o.id||i.a2.id===r.id&&i.a1.id===o.id))continue;let a=i.a1.id===o.id?i.r1:i.r2,l=i.a1.id===r.id?i.r1:i.r2,h="numeric"===a.kind&&1===a.r,d="numeric"===l.kind&&2===l.r;if(h&&d)return!0}return!1}var ht=44.800000000000004,dt=42/ht,ct=42/ht,ut=42/ht;function pt(e,t){let i=t?.bondLength??28,n=t?.origin??{x:0,y:0},o=1.6*i,r=new Map;for(let t=0;t<e.backbone.length;t++){let i=e.backbone[t];r.set(i.id,{x:n.x+t*o,y:n.y})}return r}var mt=Math.PI/180;function ft(e,t){let i=e.backbone.length;if(i<=2){let i={};return void 0!==t?.bondLength&&(i.bondLength=t.bondLength),void 0!==t?.origin&&(i.origin=t.origin),pt(e,i)}let n=t?.bondLength??28,o=t?.origin??{x:0,y:0},r=t?.startDegrees??-90,s=1.6*n/(2*Math.sin(Math.PI/i)),a=new Map;for(let t=0;t<i;t++){let n=e.backbone[t],l=(r+360*t/i)*mt;a.set(n.id,{x:o.x+s*Math.cos(l),y:o.y+s*Math.sin(l)})}return a}function bt(e,t){let i=new Map;for(let t=0;t<e.backbone.length;t++)i.set(e.backbone[t].id,t);let n=e.backbone.length-1,o=[];for(let e of t.bonds){if("backbone"===e.kind||"branch"===e.kind)continue;let t=i.get(e.a1.id),r=i.get(e.a2.id);if(void 0===t||void 0===r)continue;let s=Math.min(t,r),a=Math.max(t,r);a-s<2||0===s&&a===n&>(e)||o.push({lo:s,hi:a})}return o}function gt(e){let t=[e.r1,e.r2].filter(e=>"numeric"===e.kind).map(e=>e.r);return 2===t.length&&t.includes(1)&&t.includes(2)}function At(e,t,i){if(null===t)return pt(e,i);let n=i?.bondLength??28,o=i?.origin??{x:0,y:0},r=1.6*n,s=bt(e,t);if(0===s.length)return pt(e,i);let a=s[0].lo,l=s[0].hi;for(let e of s)e.lo<a&&(a=e.lo),e.hi>l&&(l=e.hi);let h=e.backbone.slice(a,l+1),d=h.length,c=r/(2*Math.sin(Math.PI/d)),u={id:e.id,polymerType:e.polymerType,segments:e.segments,backbone:h,bases:new Array(d).fill(null),baseBonds:new Array(d).fill(null)},p=a,m={x:o.x+p*r+c,y:o.y},f=ft(u,{bondLength:n,origin:m,startDegrees:180}),b=new Map;for(let t=0;t<a;t++){let i=e.backbone[t];b.set(i.id,{x:o.x+t*r,y:o.y})}for(let[e,t]of f)b.set(e,t);let g=h[d-1],A=f.get(g.id)??m,_=A.x-m.x,y=A.y-m.y,v=Math.hypot(_,y);v<1e-6&&(_=0,y=1,v=1);let w=_/v,x=y/v,C={x:A.x+w*r,y:A.y+x*r},E=Math.sign(A.x-m.x);if(0===E&&d>=2){let e=f.get(h[d-2].id);void 0!==e&&(E=Math.sign(A.x-e.x))}0===E&&(E=1);for(let t=l+1;t<e.backbone.length;t++){let i=e.backbone[t],n=t-(l+1);b.set(i.id,0===n?C:{x:C.x+E*r*n,y:C.y})}return b}function _t(e){let t=new Map,i=new Map;for(let n=0;n<e.backbone.length;n++){t.set(e.backbone[n].id,n);let o=e.bases[n];null!=o&&i.set(o.id,n)}return{sugarToIdx:t,baseToIdx:i}}function yt(e,t,i){let n=t.get(e);if(void 0!==n)return n;let o=i.get(e);return void 0!==o?o:null}function vt(e,t,i){let n="hbond"===e.kind,o="cross-polymer"===e.kind&&"object"==typeof e.r1&&null!==e.r1&&"pair"===e.r1.kind&&"object"==typeof e.r2&&null!==e.r2&&"pair"===e.r2.kind;if(!n&&!o)return null;let r=yt(e.a1.id,t,i),s=yt(e.a2.id,t,i);return null===r||null===s||r===s?null:{lo:Math.min(r,s),hi:Math.max(r,s)}}function wt(e){let t=Math.hypot(e.x,e.y);return 0===t?{x:1,y:0}:{x:e.x/t,y:e.y/t}}function xt(e,t,i){return{x:e.x+t*Math.cos(i),y:e.y+t*Math.sin(i)}}function Ct(e,t,i,n,o){let r=o.chain.bases[e];null!=r&&o.out.set(r.id,{x:t.x+n*i.x,y:t.y+n*i.y})}function Et(e,t,i){let{chain:n,step:o,rail:r,baseInwardHang:s,out:a}=i,l=2*e.numPairs-1,h={x:t.normal.x,y:t.normal.y},d={x:-t.normal.x,y:-t.normal.y};for(let c=0;c<l;c++){let l=n.backbone[e.fromIdx+c],u=n.backbone[e.toIdx-c],p=c*o,m={x:t.origin.x+p*t.tangent.x,y:t.origin.y+p*t.tangent.y},f={x:t.origin.x+p*t.tangent.x+r*t.normal.x,y:t.origin.y+p*t.tangent.y+r*t.normal.y};a.set(l.id,m),a.set(u.id,f),Ct(e.fromIdx+c,m,h,s,i),Ct(e.toIdx-c,f,d,s,i)}let c=(l-1)*o;return{origin:{x:t.origin.x+c*t.tangent.x,y:t.origin.y+c*t.tangent.y},tangent:t.tangent,normal:t.normal}}function kt(e,t,i,n){if(null===e.closingPair)return;let{step:o,rail:r,out:s}=i,a=0,l=0;for(let t of e.nodes)"unpaired"===t.kind?a+=t.to-t.from+1:l+=1;let h=function(e,t,i,n){let o=i+n+1;if(o<=0)return Math.max(e/2+1,t);let r=n+1,s=o*t,a=Math.max(s/(2*Math.PI),e/2+1);for(let t=0;t<64;t++){let t=e/(2*a),i=2*Math.asin(Math.min(.9999,Math.max(-.9999,t))),n=(2*Math.PI-r*i)*a-s,o=t,l=-e/(2*a*a)/Math.sqrt(Math.max(1e-12,1-o*o))*2,h=2*Math.PI-r*i-r*a*l;if(!Number.isFinite(h)||Math.abs(h)<1e-12)break;let d=n/h,c=a-d;if(!Number.isFinite(c)||c<e/2+.001){a=e/2+.001;break}if(a=c,Math.abs(d)<1e-9)break}return Math.max(a,e/2+.001)}(r,o,a,l),d=s.get(i.chain.backbone[e.closingPair[0]].id),c=s.get(i.chain.backbone[e.closingPair[1]].id),u=(d.x+c.x)/2,p=(d.y+c.y)/2,m=Math.sqrt(Math.max(0,h*h-r/2*(r/2))),f={x:u+m*t.tangent.x,y:p+m*t.tangent.y},b=Math.atan2(d.y-f.y,d.x-f.x),g=Math.atan2(c.y-f.y,c.x-f.x)-b;for(;g>Math.PI;)g-=2*Math.PI;for(;g<=-Math.PI;)g+=2*Math.PI;let A=g>0?-1:1,_=2*Math.asin(Math.min(.9999,Math.max(-.9999,r/(2*h)))),y=o/h,v=b;for(let t of e.nodes)if("unpaired"===t.kind)for(let e=t.from;e<=t.to;e++){v+=A*y;let t=xt(f,h,v);s.set(i.chain.backbone[e].id,t),Ct(e,t,wt({x:t.x-f.x,y:t.y-f.y}),i.step,i)}else{v+=A*y;let e=xt(f,h,v);v+=A*_;let n=xt(f,h,v);s.set(i.chain.backbone[t.fromIdx].id,e),s.set(i.chain.backbone[t.toIdx].id,n);let o=Et(t,{origin:e,tangent:wt({x:(e.x+n.x)/2-f.x,y:(e.y+n.y)/2-f.y}),normal:wt({x:n.x-e.x,y:n.y-e.y})},i);kt(t.child,o,i)}}function Bt(e,t,i){let n=1.6*(i?.bondLength??28);for(let i=0;i<e.backbone.length;i++){let o=e.bases[i];if(null==o||t.has(o.id))continue;let r=e.backbone[i],s=t.get(r.id);if(void 0===s)continue;let a=St(e,i,t);t.set(o.id,{x:s.x+n*a.x,y:s.y+n*a.y})}return t}function St(e,t,i){let n=e.backbone[t],o=i.get(n.id);if(void 0===o)return{x:0,y:1};let r=t>0?e.backbone[t-1]:void 0,s=t<e.backbone.length-1?e.backbone[t+1]:void 0,a=void 0!==r?i.get(r.id):void 0,l=void 0!==s?i.get(s.id):void 0,h=e=>{let t=e.x-o.x,i=e.y-o.y,n=Math.hypot(t,i);return n<1e-9?null:{x:t/n,y:i/n}},d=void 0!==a?h(a):null,c=void 0!==l?h(l):null;if(null!==d&&null!==c){let e=d.x+c.x,t=d.y+c.y,i=Math.hypot(e,t);if(i>.05)return{x:-e/i,y:-t/i}}let u=c??d;if(null===u)return{x:0,y:1};let p={x:u.y,y:-u.x},m={x:-u.y,y:u.x};return p.y>=m.y?p:m}function Mt(e,t,i,n,o,r){let s=It(t.atomIds,o);if(null===s)return e;let a=null;for(let e of i){let t=n.get(e);if(void 0===t)continue;let i=Lt(t.atomIds,o);null!==i&&(null===a||i>a)&&(a=i)}if(null===a)return e;let l=a+r;return s+e<l?l-s:e}function Tt(e,t){let i=new Set;for(let n of e){let e=t.get(n);if(void 0!==e)for(let t of e.atomIds)i.add(t)}return i}function It(e,t){let i=null;for(let n of e){let e=t.get(n);void 0!==e&&(null===i||e.y<i)&&(i=e.y)}return i}function Lt(e,t){let i=null;for(let n of e){let e=t.get(n);void 0!==e&&(null===i||e.y>i)&&(i=e.y)}return i}function $t(e,t,i,n){for(let o of e){let e=t.get(o);void 0!==e&&t.set(o,{x:e.x+i,y:e.y+n})}}function Pt(e,t){let i=0,n=0;for(let o of e){let e=t.get(o);void 0!==e&&(i+=e.x,n+=1)}if(0===n)return;let o=i/n;for(let i of e){let e=t.get(i);void 0!==e&&t.set(i,{x:2*o-e.x,y:e.y})}}function Rt(e,t){let i=0,n=0;for(let o of e){let e=t.get(o);void 0!==e&&(i+=e.y,n+=1)}if(0===n)return;let o=i/n;for(let i of e){let e=t.get(i);void 0!==e&&t.set(i,{x:e.x,y:2*o-e.y})}}function Ht(e,t){let i=0,n=0,o=0;for(let r of e){let e=t.get(r);void 0!==e&&(i+=e.x,n+=e.y,o+=1)}return 0===o?{x:0,y:0}:{x:i/o,y:n/o}}function Nt(e,t,i,n,o,r){let s=Ht(i,r),a=n.x-s.x,l=n.y-s.y,h=Math.hypot(a,l);h<1e-6&&(a=0,l=1,h=1);let d=a/h,c=l/h,u=n.x+d*o,p=n.y+c*o;$t(e,r,u-t.x,p-t.y)}function Dt(e,t,i,n,o){let r=Math.cos(n),s=Math.sin(n),a=new Map;for(let n of e){let e=o.get(n);if(void 0===e)continue;let l=e.x-t.x,h=e.y-t.y;a.set(n,{x:i.x+l*r-h*s,y:i.y+l*s+h*r})}return a}function Ft(e,t,i,n,o,r){let s=.72*r,a=.45*r,l=i.map(e=>({a:e,end:t.get(e.movingAtomId)})).filter(e=>void 0!==e.end);for(let i of n){if(e.has(i))continue;let n=o.get(i);if(void 0!==n){for(let e of t.values())if(Math.hypot(e.x-n.x,e.y-n.y)<s)return!1;for(let e of l)if(i!==e.a.fixedAtomId&&zt(n,e.a.fixedPos,e.end)<a)return!1}}for(let[e,i]of t)for(let t of l)if(e!==t.a.movingAtomId&&zt(i,t.a.fixedPos,t.end)<a)return!1;return!0}function Ot(e,t){let i=0;for(let n of e){let e=t.get(n.movingAtomId);void 0!==e&&(i+=Math.hypot(e.x-n.fixedPos.x,e.y-n.fixedPos.y))}return i}function zt(e,t,i){let n=i.x-t.x,o=i.y-t.y,r=n*n+o*o;if(0===r)return Math.hypot(e.x-t.x,e.y-t.y);let s=((e.x-t.x)*n+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),Math.hypot(e.x-(t.x+s*n),e.y-(t.y+s*o))}function Gt(e,t,i,n,o,r,s,a,l){let h=function(e,t,i,n){let o=[];for(let r of i.get(e.id)??[]){if("hbond"===r.kind)continue;let i=r.a1.id===e.id?r.a2:r.a1;if(i.id===e.id||i.id===t)continue;let s=n.get(i.id);void 0!==s&&o.push(s)}return o}(i,n.movingAtomId,r,l),d=function(e,t){let i=[],n=e=>{let t=Math.hypot(e.x,e.y);if(t<1e-6)return;let n={x:e.x/t,y:e.y/t};for(let e of i)if(Math.hypot(e.x-n.x,e.y-n.y)<.001)return;i.push(n)};if(t.length>1){let i=0,o=0;for(let e of t)i+=e.x,o+=e.y;i/=t.length,o/=t.length;let r={x:e.x-i,y:e.y-o};Math.hypot(r.x,r.y)>.05&&n(r)}if(t.length>0){let i={x:t[0].x-e.x,y:t[0].y-e.y},o={x:i.y,y:-i.x},r={x:-i.y,y:i.x};n(o.y>=r.y?o:r),n(o.y>=r.y?r:o)}n({x:0,y:1}),n({x:0,y:-1});for(let[e,t]of[[1,1],[-1,1],[1,-1],[-1,-1],[1,0],[-1,0]])n({x:e,y:t});return i}(n.fixedPos,h),c=function(e,t,i){if(e.size<2)return null;let n=Ht(e,i),o=n.x-t.x,r=n.y-t.y;if(Math.hypot(o,r)<.001){let n=0;for(let s of e){let e=i.get(s);if(void 0===e)continue;let a=Math.hypot(e.x-t.x,e.y-t.y);a>n&&(n=a,o=e.x-t.x,r=e.y-t.y)}}let s=Math.hypot(o,r);return s<1e-6?null:{x:o/s,y:r/s}}(e,t,l),u=[n.fixedPos];if(o.length>1){let e=0,t=0;for(let i of o)e+=i.fixedPos.x,t+=i.fixedPos.y;u.unshift({x:e/o.length,y:t/o.length})}let p=null===c?[0]:[0,1],m=function(e){let t=[...e];for(let e=0;e<24;e++){let i=e*Math.PI*2/24,n={x:Math.cos(i),y:Math.sin(i)};t.some(e=>Math.hypot(e.x-n.x,e.y-n.y)<.001)||t.push(n)}return t}(d);for(let i of[a,2*a,3*a,4*a]){let n=qt(i===a?d:m,i,u,p,c,e,t,o,s,l,a);if(null!==n)return Vt(e,t,n.target,n.angle,l),!0}return!1}function qt(e,t,i,n,o,r,s,a,l,h,d){let c=null;for(let u of n)for(let n of i)for(let i of e){let e={x:n.x+i.x*t,y:n.y+i.y*t},p=0===u||null===o?0:Math.atan2(i.y,i.x)-Math.atan2(o.y,o.x),m=Dt(r,s,e,p,h);if(!Ft(r,m,a,l,h,d))continue;let f=Ot(a,m);if(1===a.length)return{target:e,angle:p,cost:f};(null===c||f<c.cost)&&(c={target:e,angle:p,cost:f})}return c}function jt(e,t,i,n,o,r){let s=[t];for(let a of i.bonds)if("cross-polymer"===a.kind)for(let[i,l]of[[a.a1,a.a2],[a.a2,a.a1]]){if(!e.has(i.id)||e.has(l.id)||!n.has(l.id)||l.id===t.fixedAtomId&&i.id===t.movingAtomId||!r(l.id))continue;let a=o.get(l.id);void 0!==a&&s.push({fixedAtomId:l.id,fixedPos:a,movingAtomId:i.id})}return s}function Vt(e,t,i,n,o){0!==n&&Yt(e,o,t,n),$t(e,o,i.x-t.x,i.y-t.y)}function Yt(e,t,i,n){let o=Math.cos(n),r=Math.sin(n);for(let n of e){let e=t.get(n);if(void 0===e)continue;let s=e.x-i.x,a=e.y-i.y;t.set(n,{x:i.x+s*o-a*r,y:i.y+s*r+a*o})}}function Wt(e,t,i,n,o,r){let s=Ht(i,r),a=n.x-s.x,l=n.y-s.y,h=Math.hypot(a,l);h<1e-6&&(a=1,l=0,h=1);let d=a/h,c=l/h,u=Ht(e,r),p=Math.hypot(t.x-u.x,t.y-u.y),m=Math.atan2(t.y-u.y,t.x-u.x);Yt(e,r,u,Math.atan2(-c,-d)-m);let f=n.x+d*(o+p),b=n.y+c*(o+p);$t(e,r,f-u.x,b-u.y)}function Ut(e,t){let i=t?.bondLength??28,n=t?.perRow,o=t?.rowsThreshold,r=t?.circleThreshold??50,s=function(e){let t=[];for(let i of e.chains){let e=at(i.polymerType),n=i.backboneAtoms,o=[],r=[],s=[];for(let e of i.bonds)"backbone"===e.kind&&s.push(e);for(let e of n){if(e.biotype!==Q){o.push(null),r.push(null);continue}let t=null,n=null;for(let o of i.bonds){if("branch"!==o.kind)continue;let i=o.a1.id===e.id?o.a2:o.a2.id===e.id?o.a1:null;if(null!==i&&i.biotype===Z){t=i,n=o;break}}o.push(t),r.push(n)}t.push({id:i.id,polymerType:e,backbone:n,bases:o,backboneBonds:s,baseBonds:r,...void 0!==i.strandType?{strandType:i.strandType}:{}})}let i=function(e,t){let i=new Map;e.forEach((e,t)=>{for(let n of e.backbone)i.set(n.id,t)});let n=new Map,o=new Map;for(let r of t.bonds){if("cross-polymer"!==r.kind)continue;let t=rt(r,e,i);if(null===t)continue;let{tail:s,head:a}=t;s!==a&&(n.has(s)||o.has(a)||st(n,a,s)||(n.set(s,a),o.set(a,s)))}let r=[],s=new Set;for(let t=0;t<e.length;t++){if(s.has(t)||o.has(t))continue;let i=[],a=t;for(;void 0!==a&&!s.has(a);)s.add(a),i.push(e[a]),a=n.get(a);r.push(i)}for(let t=0;t<e.length;t++)s.has(t)||(s.add(t),r.push([e[t]]));let a=new Map;e.forEach((e,t)=>a.set(e,t));let l=e=>Math.min(...e.map(e=>a.get(e)));return r.sort((e,t)=>l(e)-l(t))}(t,e),n=new Set,o=i.map(e=>{let t=e[0].id;for(let i=2;n.has(t);i++)t=`${e[0].id}#${i}`;return n.add(t),t}),r=new Map;return i.forEach((e,t)=>{for(let i of e)for(let e of i.backbone)r.set(e.id,o[t]),void 0!==e.branchAtom&&r.set(e.branchAtom.id,o[t])}),i.map((t,i)=>function(e,t,i,n){let o=[],r=[],s=[],a=[];for(let t of e)o.push(...t.backbone),r.push(...t.bases),s.push(...t.backboneBonds),a.push(...t.baseBonds);let l=e.find(e=>void 0!==e.strandType)?.strandType;return{id:t,polymerType:ot(e),segments:e.map(e=>e.id),backbone:o,bases:r,backboneBonds:s,baseBonds:a,isCyclic:lt(i,t,o,n),...void 0!==l?{strandType:l}:{}}}(t,o[i],e,r))}(e),a=new Map;for(let t of s){let s=Kt(t,e,i,n,o,r);for(let[e,t]of s)a.set(e,t);Bt(t,a,{bondLength:i})}let l=function(e,t,i,n){let o=1.6*(n?.bondLength??28),r=new Map,s=new Map;for(let t of e){let e=new Set;for(let i of t.backbone)e.add(i.id);for(let i of t.bases)null!==i&&e.add(i.id);s.set(t.id,{chain:t,atomIds:e});for(let i of e)r.set(i,t)}let a=new Map;for(let e of i.bonds)for(let t of[e.a1,e.a2]){let i=a.get(t.id);void 0===i?a.set(t.id,[e]):i.push(e)}let l=new Set;if(e.length>0){let t=e.find(e=>"ss"===e.strandType);l.add((t??e[0]).id)}let h=new Map;for(let t of e)h.set(t.id,t.id);let d=e=>{let t=e;for(;h.get(t)!==t;)t=h.get(t);let i=e;for(;h.get(i)!==t;){let e=h.get(i);h.set(i,t),i=e}return t},c=(e,t)=>{h.set(d(e),d(t))},u=e=>{let t=d(e),i=0;for(let e of h.keys())d(e)===t&&(i+=1);return i},p=e=>{let t=r.get(e),i=void 0===t?void 0:d(t.id);return e=>{let t=r.get(e);return void 0!==t&&void 0!==i&&d(t.id)===i}},m=e=>{let t=d(e),i=new Set;for(let[e,n]of s)if(d(e)===t)for(let e of n.atomIds)i.add(e);return i};for(let e of i.bonds){if("backbone"===e.kind||"branch"===e.kind)continue;let n=r.get(e.a1.id),h=r.get(e.a2.id);if(void 0===n||void 0===h||n.id===h.id)continue;if("hbond"===e.kind&&("as"===n.strandType&&"ss"===h.strandType?l.add(h.id):"as"===h.strandType&&"ss"===n.strandType?l.add(n.id):"as"!==n.strandType||l.has(h.id)?"as"===h.strandType&&!l.has(n.id)&&l.add(n.id):l.add(h.id)),"cross-polymer"===e.kind){let e=l.has(n.id)!==l.has(h.id)?l.has(n.id)?n:h:void 0,t=void 0===e?void 0:e===n?h:n;void 0!==e&&void 0!==t&&1===u(e.id)&&t.backbone.length>e.backbone.length&&(l.delete(e.id),l.add(t.id))}let f=h,b=e.a1,g=e.a2;if(l.has(h.id)&&!l.has(n.id))f=n,b=e.a2,g=e.a1;else if(l.has(n.id)||l.has(h.id)){if(l.has(n.id)&&l.has(h.id)){if(d(n.id)===d(h.id)||"cross-polymer"!==e.kind)continue;let r=m(n.id),u=m(h.id),f=r.size<=u.size,b=f?r:u,g=f?u:r,A=f?e.a1:e.a2,_=f?e.a2:e.a1,y=t.get(A.id),v=t.get(_.id);if(void 0!==y&&void 0!==v){let e={fixedAtomId:_.id,fixedPos:v,movingAtomId:A.id},n=Tt(l,s);Gt(b,y,_,e,jt(b,e,i,n,t,p(_.id)),a,n,o,t)||Nt(b,y,g,v,o,t)}c(n.id,h.id);continue}}else{if(l.size>0){let e=Lt(Tt(l,s),t),i=s.get(n.id),r=It(i.atomIds,t);if(null!==e&&null!==r){let n=e+o*dt-r;n>0&&$t(i.atomIds,t,0,n)}}l.add(n.id),f=h,b=e.a1,g=e.a2}let A=t.get(b.id),_=t.get(g.id);if(void 0!==A&&void 0!==_){if("hbond"===e.kind){let e=s.get(f.id);Pt(e.atomIds,t),Rt(e.atomIds,t);let i=t.get(g.id),n=A.x-i.x,r=A.y+o*ct-i.y;r=Mt(r,e,l,s,t,o*ct),$t(e.atomIds,t,n,r)}else{let e=s.get(f.id),r=Tt(l,s),d={fixedAtomId:b.id,fixedPos:A,movingAtomId:g.id},u=jt(e.atomIds,d,i,r,t,p(b.id));if(f.isCyclic&&f.backbone.length>=3&&1===u.length){let i=f.id===n.id?h:n,r=s.get(i.id);Wt(e.atomIds,_,r.atomIds,A,o,t),l.add(f.id),c(n.id,h.id);continue}if(!Gt(e.atomIds,_,b,d,u,a,r,o,t)){let i=A.x-_.x,n=A.y+o*ut-_.y;n=Mt(n,e,l,s,t,o*ut),$t(e.atomIds,t,i,n)}}l.add(f.id),c(n.id,h.id)}}return l}(s,a,e,{bondLength:i});!function(e,t,i,n){let o=n?.bondLength??28,r=(n?.gap??dt)*(1.6*o),s=0,a=!1;for(let n of e)if(i.has(n.id)){for(let e of n.backbone){let i=t.get(e.id);void 0!==i&&(a?i.y>s&&(s=i.y):(s=i.y,a=!0))}for(let e of n.bases){if(null===e)continue;let i=t.get(e.id);void 0!==i&&i.y>s&&(s=i.y)}}a||(s=0);let l=s+r;for(let n of e){if(i.has(n.id))continue;let e=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let i of n.backbone){let n=t.get(i.id);void 0!==n&&(n.y<e&&(e=n.y),n.y>o&&(o=n.y))}for(let i of n.bases){if(null===i)continue;let n=t.get(i.id);void 0!==n&&(n.y<e&&(e=n.y),n.y>o&&(o=n.y))}if(e===Number.POSITIVE_INFINITY){i.add(n.id);continue}let s=l-e;for(let e of n.backbone){let i=t.get(e.id);void 0!==i&&t.set(e.id,{x:i.x,y:i.y+s})}for(let e of n.bases){if(null===e)continue;let i=t.get(e.id);void 0!==i&&t.set(e.id,{x:i.x,y:i.y+s})}l=o+s+r,i.add(n.id)}}(s,a,l,{bondLength:i});for(let t of e.atoms)a.has(t.id)||a.set(t.id,{x:0,y:0});return function(e,t){let i=new Map,n=[];for(let o of e.atoms){let e=t.get(o.id)??o.p,r={...o,p:{x:e.x,y:e.y}};i.set(o.id,r),n.push(r)}for(let t=0;t<n.length;t++){let o=e.atoms[t];if(void 0!==o.branchAtom){let e=i.get(o.branchAtom.id);void 0!==e&&(n[t]={...n[t],branchAtom:e}),i.set(n[t].id,n[t])}}let o=[];for(let t of e.bonds){let e=i.get(t.a1.id),n=i.get(t.a2.id);void 0===e||void 0===n||o.push({...t,a1:e,a2:n})}let r=[];for(let t of e.chains){let e=t.backboneAtoms.map(e=>i.get(e.id)??e),n=t.bonds.map(e=>{let t=i.get(e.a1.id)??e.a1,n=i.get(e.a2.id)??e.a2;return{...e,a1:t,a2:n}});r.push({id:t.id,polymerType:t.polymerType,backboneAtoms:e,bonds:n,...void 0!==t.annotation?{annotation:t.annotation}:{},...void 0!==t.strandType?{strandType:t.strandType}:{}})}return{atoms:n,bonds:o,chains:r,groups:e.groups,annotations:e.annotations}}(e,a)}function Kt(e,t,i,n,o,r){let s=e.backbone.length;if(0===s)return new Map;let a="RNA"===e.polymerType||e.bases.some(e=>null!==e),l=n??function(e,t){let i=1,n=250;for(;t>n;)i*=2,n*=4;return e*i}(a?40:20,s),h=o??l;if("RNA"===e.polymerType&&function(e,t){if("RNA"!==e.polymerType||0===e.backbone.length)return!1;let{sugarToIdx:i,baseToIdx:n}=_t(e);for(let e of t.bonds)if(null!==vt(e,i,n))return!0;return!1}(e,t))return function(e,t,i){let n=i?.bondLength??28,o=1.6*n,r=o/2,s=n/28*42+2*r,a=i?.origin??{x:0,y:0},l=wt(i?.rootDirection??{x:1,y:0}),h=function(e){return{x:-e.y,y:e.x}}(l),d=new Map;if(0===e.backbone.length)return d;let c=function(e,t){let i=e.backbone.length,n=new Int32Array(i).fill(-1);if(0===i)return n;let{sugarToIdx:o,baseToIdx:r}=_t(e),s=[];for(let e of t.bonds){let t=vt(e,o,r);null!==t&&s.push([t.lo,t.hi])}s.sort((e,t)=>e[0]-t[0]||t[1]-e[1]);let a=[];for(let e of s){let[t,i]=e,o=!1;for(let[e,n]of a)if(!(i<e||t>n||t>e&&i<n||t<e&&i>n)){o=!0;break}o||-1!==n[t]||-1!==n[i]||(n[t]=i,n[i]=t,a.push(e))}return n}(e,t),u=function(e){return function t(i,n,o){let r=[],s=-1,a=i;for(;a<=n;){let i=e[a];if(i>a&&i<=n){-1!==s&&(r.push({kind:"unpaired",from:s,to:a-1}),s=-1);let n=1;for(;a+2*n<i-2*n&&e[a+2*n]===i-2*n&&-1===e[a+2*n-1]&&-1===e[i-2*n+1];)n+=1;let o=a+2*(n-1),l=i-2*(n-1),h=t(o+1,l-1,[o,l]);r.push({kind:"stem",fromIdx:a,toIdx:i,numPairs:n,child:h}),a=i+1}else-1===s&&(s=a),a+=1}return-1!==s&&r.push({kind:"unpaired",from:s,to:n}),{kind:"loop",nodes:r,closingPair:o}}(0,e.length-1,null)}(c);!function(e,t,i){let{step:n,rail:o,out:r}=i,s={x:t.origin.x,y:t.origin.y},a={x:t.tangent.x,y:t.tangent.y},l={x:-t.normal.x,y:-t.normal.y};for(let h of e.nodes)if("unpaired"===h.kind)for(let e=h.from;e<=h.to;e++){let o={x:s.x,y:s.y};r.set(i.chain.backbone[e].id,o),Ct(e,o,{x:t.normal.x,y:t.normal.y},i.step,i),s={x:s.x+n*a.x,y:s.y+n*a.y}}else{let e=Et(h,{origin:{x:s.x,y:s.y},tangent:l,normal:a},i);kt(h.child,e,i),s={x:s.x+(o+n)*a.x,y:s.y+(o+n)*a.y}}}(u,{origin:a,tangent:l,normal:h},{chain:e,step:o,rail:s,baseInwardHang:r,out:d});for(let t of e.backbone)d.has(t.id)||d.set(t.id,{x:a.x,y:a.y});return d}(e,t,{bondLength:i});if(e.isCyclic&&s<=r)return ft(e,{bondLength:i});if(!e.isCyclic&&function(e,t){return null!==t&&bt(e,t).length>0}(e,t))return At(e,t,{bondLength:i});if(s>h){let t=a?2:void 0;return function(e,t){let i=t?.bondLength??28,n=t?.origin??{x:0,y:0},o=Math.max(1,t?.perRow??10),r=1.6*i,s=(t?.rowSpacing??.9375)*r,a=new Map;for(let t=0;t<e.backbone.length;t++){let i=e.backbone[t],l=Math.floor(t/o),h=t%o,d=l%2==0?n.x+h*r:n.x+(o-1-h)*r,c=n.y+l*s;a.set(i.id,{x:d,y:c})}return a}(e,void 0!==t?{bondLength:i,perRow:l,rowSpacing:t}:{bondLength:i,perRow:l})}return e.isCyclic?pt(e,{bondLength:i}):At(e,t,{bondLength:i})}function Xt(e,t){let i=Math.min(e.x,t.x),n=Math.min(e.y,t.y);return{x:i,y:n,width:Math.max(e.x+e.width,t.x+t.width)-i,height:Math.max(e.y+e.height,t.y+t.height)-n}}function Qt(e){if(Number.isInteger(e))return 0===e?"0":e.toString();if(!Number.isFinite(e)||Object.is(e,-0))return"0";let t=Math.round(1e3*e)/1e3;return 0===t?"0":t.toString()}function Zt(e){if(0===e.length)return"";let t=e[0],i=`M ${Qt(t.x)} ${Qt(t.y)}`;for(let t=1;t<e.length;t++){let n=e[t];i+=` L ${Qt(n.x)} ${Qt(n.y)}`}return i+=` L ${Qt(t.x)} ${Qt(t.y)} Z`,i}function Jt(e,t,i,n){let o=[],r=360/t;for(let s=0;s<t;s++){let t=(n+s*r)*Math.PI/180;o.push({x:e.x+i*Math.cos(t),y:e.y+i*Math.sin(t)})}return o}function ei(e,t,i,n){let o=Math.abs(t)/2,r=Math.abs(i)/2,s=Math.max(0,Math.min(n,o,r)),a=e.x-o,l=e.y-r,h=a+2*o,d=l+2*r,c=`M ${Qt(a+s)} ${Qt(l)}`;return c+=` L ${Qt(h-s)} ${Qt(l)}`,c+=` A ${Qt(s)} ${Qt(s)} 0 0 1 ${Qt(h)} ${Qt(l+s)}`,c+=` L ${Qt(h)} ${Qt(d-s)}`,c+=` A ${Qt(s)} ${Qt(s)} 0 0 1 ${Qt(h-s)} ${Qt(d)}`,c+=` L ${Qt(a+s)} ${Qt(d)}`,c+=` A ${Qt(s)} ${Qt(s)} 0 0 1 ${Qt(a)} ${Qt(d-s)}`,c+=` L ${Qt(a)} ${Qt(l+s)}`,c+=` A ${Qt(s)} ${Qt(s)} 0 0 1 ${Qt(a+s)} ${Qt(l)}`,c+=" Z",c}function ti(e,t){return`M ${Qt(e.x)} ${Qt(e.y)} L ${Qt(t.x)} ${Qt(t.y)}`}function ii(e,t,i=6){let n=t.x-e.x,o=t.y-e.y,r=Math.sqrt(n*n+o*o);if(0===r)return`M ${Qt(e.x)} ${Qt(e.y)} L ${Qt(e.x)} ${Qt(e.y)}`;let s=n/r,a=o/r,l=-a,h=s,d=(e.x+t.x)/2,c=(e.y+t.y)/2,u=i/2,p=Math.min(.6*i,.25*r),m=d-s*p,f=c-a*p,b=d+s*p,g=c+a*p;return`M ${Qt(m-l*u)} ${Qt(f-h*u)} L ${Qt(m+l*u)} ${Qt(f+h*u)} M ${Qt(b-l*u)} ${Qt(g-h*u)} L ${Qt(b+l*u)} ${Qt(g+h*u)}`}function ni(e,t,i,n){switch(e){case"hexagon":{let e=i*Math.sqrt(3)/2,n=i;return{x:t.x-e,y:t.y-n,width:2*e,height:2*n}}case"diamond":return{x:t.x-i,y:t.y-i,width:2*i,height:2*i};case"pentagon":{let e=Math.cos(18*Math.PI/180)*i,n=-i,o=Math.sin(54*Math.PI/180)*i;return{x:t.x-e,y:t.y+n,width:2*e,height:o-n}}case"rounded-rect":case"blob":{let e=n??i,o=Math.abs(i)/2,r=Math.abs(e)/2;return{x:t.x-o,y:t.y-r,width:2*o,height:2*r}}case"ellipse":{let e=Math.abs(i),o=Math.abs(n??i);return{x:t.x-e,y:t.y-o,width:2*e,height:2*o}}case"circle":{let e=Math.abs(i);return{x:t.x-e,y:t.y-e,width:2*e,height:2*e}}}}var oi='"Helvetica Neue", Helvetica, Arial, sans-serif';function ri(e){return{aa:{size:.72*e,strokeWidth:5},sugar:{size:1.39*e,strokeWidth:5,cornerRadius:.3*e},base:{size:.88*e,strokeWidth:5},linker:{size:.63*e,strokeWidth:5},chem:{size:1.49*e,strokeWidth:5,cornerRadius:.5*e},blob:{size:1.64*e,strokeWidth:5,cornerRadius:.8*e},nucleotide:{size:.98*e,strokeWidth:5}}}var si={name:"light",background:"#ffffff",defaultStroke:"#202020",defaultFill:"#ffffff",selectionColor:"#FFC107",highlightColor:"#A4E2DC",errorColor:"#cc0000",fontSize:14,fontFamily:oi,bondLength:28,textColor:"#000000",idColor:"#00aa00",annotationColor:"#FFA500",tagDotColor:"#dd2222",hbondColor:"#888888",nonCanonicalHbondColor:"#cc8800",crossPolymerBondColor:"#1f5fcd",colorTheme:Se,palette:{softenCanvas:!1},shapes:ri(14)},ai={name:"dark",background:"#1a1d23",defaultStroke:"#e0e0e0",defaultFill:"#2b2f37",selectionColor:"#FFD54F",highlightColor:"#7DD8CC",errorColor:"#ff5050",fontSize:14,fontFamily:oi,bondLength:28,textColor:"#ffffff",idColor:"#33ff33",annotationColor:"#FFB84D",tagDotColor:"#ff6464",hbondColor:"#aaaaaa",nonCanonicalHbondColor:"#ffaa44",crossPolymerBondColor:"#6699ff",colorTheme:Te,palette:{softenCanvas:!1},shapes:ri(14)};function li(e,t){switch(t){case X:return e.shapes.aa;case Q:return e.shapes.sugar;case Z:return e.shapes.base;case J:return e.shapes.linker;case ee:return e.shapes.chem;case te:return e.shapes.blob;case ie:return e.shapes.nucleotide}}function hi(e){switch(e){case X:return"hexagon";case Q:return"rounded-rect";case Z:return"diamond";case J:return"circle";case ee:return"rounded-rect";case te:return"blob";case ie:return"pentagon"}}function di(e,t,i=0){let n=li(t,e.biotype);switch(hi(e.biotype)){case"hexagon":{let t=0===i?0:i/Math.cos(Math.PI/6);return function(e,t,i=-30){return Zt(Jt(e,6,t,i))}(e.p,n.size+t)}case"diamond":{let t=0===i?0:i/Math.cos(Math.PI/4);return function(e,t){return Zt([{x:e.x,y:e.y-t},{x:e.x+t,y:e.y},{x:e.x,y:e.y+t},{x:e.x-t,y:e.y}])}(e.p,n.size+t)}case"pentagon":{let t=0===i?0:i/Math.cos(Math.PI/5);return function(e,t,i=-90){return Zt(Jt(e,5,t,i))}(e.p,n.size+t)}case"rounded-rect":return ei(e.p,n.size+2*i,n.size+2*i,(n.cornerRadius??0)+i);case"blob":return function(e,t,i,n){return ei(e,t,i,n)}(e.p,n.size+2*i,n.size+2*i,(n.cornerRadius??0)+i);case"circle":return function(e,t,i){let n=Math.abs(t),o=Math.abs(i);return`M ${Qt(e.x-n)} ${Qt(e.y)} A ${Qt(n)} ${Qt(o)} 0 1 0 ${Qt(e.x+n)} ${Qt(e.y)} A ${Qt(n)} ${Qt(o)} 0 1 0 ${Qt(e.x-n)} ${Qt(e.y)} Z`}(e.p,n.size+i,n.size+i)}}function ci(e,t){let i,n=li(t,e.biotype),o=hi(e.biotype);switch(o){case"hexagon":case"diamond":case"pentagon":case"circle":i=ni(o,e.p,n.size);break;case"rounded-rect":case"blob":i=ni(o,e.p,n.size,n.size)}let r=n.strokeWidth/2;return{x:i.x-r,y:i.y-r,width:i.width+2*r,height:i.height+2*r}}function pi(e,t){return li(t,e.biotype).size}function mi(e,t){return li(t,e.biotype)}var fi=/[&"'<>]/,bi=/[&<>]/;function gi(e){return fi.test(e)?e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"):e}function Ai(e){return bi.test(e)?e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):e}function _i(e){if(Number.isInteger(e))return 0===e?"0":e.toString();if(!Number.isFinite(e)||Object.is(e,-0))return"0";let t=Math.round(1e3*e)/1e3;return 0===t?"0":t.toString()}function yi(e,t,i){let n=`<${e}`;if(void 0!==t)for(let e in t){let i=t[e];if(void 0!==i&&!1!==i){if(!0===i){n+=` ${e}`;continue}n+="number"==typeof i?` ${e}="${_i(i)}"`:` ${e}="${gi(i)}"`}}return void 0===i?`${n}/>`:"string"==typeof i?`${n}>${i}</${e}>`:`${n}>${i.join("")}</${e}>`}var vi=[["A","T"],["A","U"],["G","C"]];function wi(e,t={}){let i=t.theme??si,n=t.width??400,o=t.height??100,r=t.padding??16,s=t.backColor??i.background,a=t.showIds??!1,l=t.showAnnotations??!0,h=t.fontSize??i.fontSize,d=t.selectedAtomIds??new Set,c=t.highlightedAtomIds??new Set;t.documentImpl??(typeof globalThis<"u"&&typeof globalThis.document<"u"&&globalThis.document);let u=t.fixedModelBbox??xi(e,i),p=function(e,t,i,n,o=1){let r=Math.max(0,t-2*n),s=Math.max(0,i-2*n),a=1;if(e.width>0||e.height>0){let t=e.width>0?r/e.width:Number.POSITIVE_INFINITY,i=e.height>0?s/e.height:Number.POSITIVE_INFINITY;a=Math.min(t,i,o),(!Number.isFinite(a)||a<=0)&&(a=1)}let l=e.width*a,h=e.height*a;return{x:(t-l)/2,y:(i-h)/2,width:l,height:h,scale:a}}(u,n,o,r,t.maxScale??1),m=p.x-u.x*p.scale,f=p.y-u.y*p.scale,b=Ei(e,i,c),g=ki(e,i,d),A=function(e,t){let i=[];for(let n of e.bonds)i.push(Bi(n,t));return yi("g",{class:"hw-layer hw-bonds"},i.join(""))}(e,i),_=function(e,t,i,n,o=t.bondLength){let r=[];for(let s of e.atoms)s.hidden||r.push(Mi(s,t,i,n,o));return yi("g",{class:"hw-layer hw-atoms"},r.join(""))}(e,i,h,a,t.bondLength??i.bondLength),y=l?function(e,t,i){let n=[];for(let o of e.bonds){if(void 0===o.ratio)continue;let e=(o.a1.p.x+o.a2.p.x)/2,r=(o.a1.p.y+o.a2.p.y)/2,s=void 0!==o.ratio.denominator?`${o.ratio.numerator}/${o.ratio.denominator}`:`${o.ratio.numerator}`;n.push(yi("text",{class:"hw-annotation hw-annotation--bond-ratio",x:e,y:r-.4*i,"text-anchor":"middle","font-size":.7*i,"font-family":t.fontFamily,fill:t.annotationColor},Ai(s)))}for(let o of e.atoms){let e=o.bio.annotation;if(void 0===e||""===e)continue;let r=mi(o,t);n.push(yi("text",{class:"hw-annotation hw-annotation--atom",x:o.p.x+r.size+2,y:o.p.y-r.size,"font-size":.7*i,"font-family":t.fontFamily,fill:t.annotationColor},Ai(e)))}for(let o of e.chains){if(void 0===o.annotation||""===o.annotation)continue;let e=o.backboneAtoms[0];void 0!==e&&n.push(yi("text",{class:"hw-annotation hw-annotation--chain",x:e.p.x,y:e.p.y-1.4*t.fontSize,"font-size":.8*i,"font-family":t.fontFamily,fill:t.annotationColor},Ai(o.annotation)))}for(let o of e.chains){if("RNA"!==o.polymerType)continue;let e=o.backboneAtoms;if(e.length<2)continue;let r=e[0],s=e[e.length-1],a=e.length>=2?e[1]:null,l=e.length>=2?e[e.length-2]:null,h=1.4*t.fontSize,d=Ti(r.p,a?.p??null,h),c=Ti(s.p,l?.p??null,h),u=void 0!==o.strandType?`5'${o.strandType}`:"5'",p=void 0!==o.strandType?`3'${o.strandType}`:"3'";n.push(yi("text",{class:"hw-annotation hw-annotation--prime hw-annotation--prime-5","data-testid":`prime-5-${o.id}`,x:d.x,y:d.y,"text-anchor":"middle","dominant-baseline":"central","font-size":.85*i,"font-family":t.fontFamily,"font-weight":"bold",fill:t.annotationColor},Ai(u))),n.push(yi("text",{class:"hw-annotation hw-annotation--prime hw-annotation--prime-3","data-testid":`prime-3-${o.id}`,x:c.x,y:c.y,"text-anchor":"middle","dominant-baseline":"central","font-size":.85*i,"font-family":t.fontFamily,"font-weight":"bold",fill:t.annotationColor},Ai(p)))}return yi("g",{class:"hw-layer hw-annotations"},n.join(""))}(e,i,h):"",v=yi("g",{class:"hw-content",transform:`translate(${_i(m)} ${_i(f)}) scale(${_i(p.scale)})`},[A,_,y,b,g].join("")),w=yi("defs",void 0,"<style>.hw-atom{transition:stroke-width 120ms,filter 120ms;}.hw-atom:focus{outline:none;}.hw-atom__shape{shape-rendering:geometricPrecision;}.hw-bond__stroke{stroke-linecap:round;}</style>"),x=yi("rect",{class:"hw-bg",x:0,y:0,width:n,height:o,fill:s});return{svg:yi("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:`0 0 ${_i(n)} ${_i(o)}`,width:n,height:o,"data-hw-theme":i.name},[w,x,v].join("")),bbox:{x:u.x,y:u.y,width:u.width,height:u.height},drawBox:{x:p.x,y:p.y,width:p.width,height:p.height,scale:p.scale}}}function xi(e,t=si){if(0===e.atoms.length)return{x:0,y:0,width:0,height:0};let i=ci(e.atoms[0],t);for(let n=1;n<e.atoms.length;n++)i=Xt(i,ci(e.atoms[n],t));return i}var Ci=3;function Ei(e,t,i){if(0===i.size)return yi("g",{class:"hw-layer hw-highlights"},"");let n=[];for(let o of e.atoms){if(!i.has(o.id))continue;let e=di(o,t,(mi(o,t).strokeWidth+Ci)/2);n.push(yi("path",{d:e,class:"hw-highlight",fill:"none",stroke:t.highlightColor,"stroke-width":Ci,"stroke-linejoin":"round","stroke-linecap":"round","data-symbol":o.symbol,"data-ring-atom-id":o.id,"data-testid":`highlight-ring-${o.id}`}))}return yi("g",{class:"hw-layer hw-highlights"},n.join(""))}function ki(e,t,i){if(0===i.size)return yi("g",{class:"hw-layer hw-selections"},"");let n=[];for(let o of e.atoms){if(!i.has(o.id))continue;let e=di(o,t,(mi(o,t).strokeWidth+Ci)/2);n.push(yi("path",{d:e,class:"hw-selection",fill:"none",stroke:t.selectionColor,"stroke-width":Ci,"stroke-linejoin":"round","stroke-linecap":"round","data-symbol":o.symbol,"data-ring-atom-id":o.id,"data-testid":`selection-ring-${o.id}`}))}return yi("g",{class:"hw-layer hw-selections"},n.join(""))}function Bi(e,t){let i=e.a1.p,n=e.a2.p,o=function(e,t){switch(e.kind){case"backbone":case"branch":case"group":return t.defaultStroke;case"cross-polymer":return t.crossPolymerBondColor;case"hbond":return function(e){if(e.a1.biotype!==Z||e.a2.biotype!==Z)return!1;let t=Si(e.a1),i=Si(e.a2);for(let[e,n]of vi)if(t===e&&i===n||t===n&&i===e)return!0;return!1}(e)?t.hbondColor:t.nonCanonicalHbondColor}}(e,t),r=function(e){if("hbond"===e.kind)return"4 3"}(e),s={d:ti(i,n),class:"hw-bond__stroke",fill:"none",stroke:o,"stroke-width":1.125};void 0!==r&&(s["stroke-dasharray"]=r);let a=[yi("path",s)];return"hbond"===e.kind&&a.push(yi("path",{d:ii(i,n,.6*t.fontSize),class:"hw-bond__hash",fill:"none",stroke:o,"stroke-width":1.125})),yi("g",{class:`hw-bond hw-bond--${e.kind}`,"data-bond-id":e.id,"data-kind":e.kind,"data-testid":`canvas-bond-${e.id}`},a.join(""))}function Si(e){let t=e.monomer?.naturalAnalog,i=void 0!==t&&""!==t?t:e.symbol;return 0===i.length?"":i.charAt(0).toUpperCase()}function Mi(e,t,i,n,o=t.bondLength){let r=mi(e,t),s=di(e,t),a=Ie(e.monomer,e.biotype,t.colorTheme),l=a.background,h=a.text,d="*"===e.symbol?"3 3":void 0,c={d:s,class:"hw-atom__shape",fill:l,stroke:l,"stroke-width":r.strokeWidth,"stroke-linejoin":"round","stroke-linecap":"round"};void 0!==d&&(c["stroke-dasharray"]=d);let u=[yi("path",c)],p=e.monomer?.symbol??e.symbol;if(""!==p){let n=i*(p.length<=1?1:Math.min(1,2/p.length));u.push(yi("text",{class:"hw-atom__label",x:e.p.x,y:e.p.y+.35*n,"text-anchor":"middle","font-size":n,"font-family":t.fontFamily,fill:h},Ai(p)))}if(void 0!==e.bio.ambiguity&&""!==e.bio.ambiguity&&u.push(yi("text",{class:"hw-atom__ambiguity",x:e.p.x,y:e.p.y+r.size+.7*i,"text-anchor":"middle","font-size":.7*i,"font-family":t.fontFamily,fill:h},Ai(e.bio.ambiguity))),n){let n=.525*o;u.push(yi("text",{class:"hw-atom__id",x:e.p.x-n,y:e.p.y-n,"font-size":.8*i,"font-family":t.fontFamily,fill:t.idColor},Ai(String(e.bio.continuousId))))}void 0!==e.tag&&""!==e.tag&&u.push(yi("circle",{class:"hw-atom__tag-dot",cx:e.p.x+.7*r.size,cy:e.p.y-.7*r.size,r:Math.max(2,.18*i),fill:t.tagDotColor}));let m=function(e){let t=""===e.symbol?"?":e.symbol,i=""===e.bio.chainId?"unknown chain":e.bio.chainId;return`${t} at position ${e.bio.positionInChain} of ${i}`}(e);return yi("g",{class:"hw-atom","data-atom-id":e.id,"data-symbol":e.symbol,"data-chain-id":e.bio.chainId,"data-biotype":e.biotype,"data-testid":`canvas-atom-${e.id}`,tabindex:0,role:"button","aria-label":m},u.join(""))}function Ti(e,t,i){if(null===t)return{x:e.x-i,y:e.y};let n=e.x-t.x,o=e.y-t.y,r=Math.hypot(n,o);return 0===r?{x:e.x-i,y:e.y}:{x:e.x+i*(n/r),y:e.y+i*(o/r)}}function Ii(e,t,i,n={}){let o=n.theme??si,r=n.padding??16,s=function(e,t){if(0===e.atoms.length)return{x:0,y:0,width:0,height:0};let i=ci(e.atoms[0],t);for(let n=1;n<e.atoms.length;n++)i=Xt(i,ci(e.atoms[n],t));return i}(t,o),a=function(e,t,i,n,o=1){let r=Math.max(0,t-2*n),s=Math.max(0,i-2*n),a=1;if(e.width>0||e.height>0){let t=e.width>0?r/e.width:Number.POSITIVE_INFINITY,i=e.height>0?s/e.height:Number.POSITIVE_INFINITY;a=Math.min(t,i,o),(!Number.isFinite(a)||a<=0)&&(a=1)}let l=e.width*a,h=e.height*a;return{x:(t-l)/2,y:(i-h)/2,width:l,height:h,scale:a}}(s,i.width,i.height,r,n.maxScale??1),l=i.x+a.x,h=i.y+a.y;return e.save(),e.beginPath(),e.rect(i.x,i.y,i.width,i.height),e.clip(),void 0!==n.backColor&&(e.fillStyle=n.backColor,e.fillRect(i.x,i.y,i.width,i.height)),e.translate(l,h),e.scale(a.scale,a.scale),e.translate(-s.x,-s.y),function(e,t,i){for(let n of t.bonds)e.save(),e.strokeStyle=Ri(n,i),e.lineWidth=Hi(),"hbond"===n.kind?e.setLineDash([4,3]):e.setLineDash([]),e.beginPath(),e.moveTo(n.a1.p.x,n.a1.p.y),e.lineTo(n.a2.p.x,n.a2.p.y),e.stroke(),e.restore()}(e,t,o),function(e,t,i,n,o=!1,r=i.bondLength){for(let s of t.atoms){if(s.hidden)continue;let t=mi(s,i),a=Ie(s.monomer,s.biotype,i.colorTheme);e.save(),e.fillStyle=a.background,e.strokeStyle=a.background,e.lineWidth=t.strokeWidth,e.lineJoin="round",e.lineCap="round","*"===s.symbol?e.setLineDash([3,3]):e.setLineDash([]),$i(e,s,t.size,t.cornerRadius??0),e.fill(),e.stroke(),e.restore();let l=s.monomer?.symbol??s.symbol;if(""!==l){let t=n*(l.length<=1?1:Math.min(1,2/l.length));e.save(),e.fillStyle=a.text,e.font=`${t}px ${i.fontFamily}`,e.textAlign="center",e.textBaseline="middle",e.fillText(l,s.p.x,s.p.y),e.restore()}if(o){let t=.525*r;e.save(),e.fillStyle=i.idColor,e.font=`${.8*n}px ${i.fontFamily}`,e.textAlign="right",e.textBaseline="bottom",e.fillText(String(s.bio.continuousId),s.p.x-t,s.p.y-t),e.restore()}}}(e,t,o,n.fontSize??o.fontSize,n.showIds??!1,n.bondLength??o.bondLength),!1!==n.showAnnotations&&function(e,t,i,n){e.save(),e.fillStyle=i.annotationColor,e.font=`${.7*n}px ${i.fontFamily}`,e.textAlign="left",e.textBaseline="alphabetic";for(let n of t.atoms){let t=n.bio.annotation;if(void 0===t||""===t)continue;let o=mi(n,i);e.fillText(t,n.p.x+o.size+2,n.p.y-o.size)}e.font=`${.8*n}px ${i.fontFamily}`;for(let n of t.chains){if(void 0===n.annotation||""===n.annotation)continue;let t=n.backboneAtoms[0];void 0!==t&&e.fillText(n.annotation,t.p.x,t.p.y-1.4*i.fontSize)}e.font=`bold ${.85*n}px ${i.fontFamily}`,e.textAlign="center",e.textBaseline="middle";let o=1.4*i.fontSize;for(let i of t.chains){if("RNA"!==i.polymerType)continue;let t=i.backboneAtoms;if(t.length<2)continue;let n=t[0],r=t[t.length-1],s=t.length>=2?t[1]:null,a=t.length>=2?t[t.length-2]:null,l=Li(n.p,s?.p??null,o),h=Li(r.p,a?.p??null,o),d=void 0!==i.strandType?`5'${i.strandType}`:"5'",c=void 0!==i.strandType?`3'${i.strandType}`:"3'";e.fillText(d,l.x,l.y),e.fillText(c,h.x,h.y)}e.restore()}(e,t,o,n.fontSize??o.fontSize),e.restore(),{bbox:{x:s.x,y:s.y,width:s.width,height:s.height},drawBox:{x:l,y:h,width:a.width,height:a.height}}}function Li(e,t,i){if(null===t)return{x:e.x-i,y:e.y};let n=e.x-t.x,o=e.y-t.y,r=Math.hypot(n,o);return 0===r?{x:e.x-i,y:e.y}:{x:e.x+i*(n/r),y:e.y+i*(o/r)}}function $i(e,t,i,n){let o=t.p,r=hi(t.biotype);switch(e.beginPath(),r){case"hexagon":Pi(e,o,6,i,-30);break;case"diamond":e.moveTo(o.x,o.y-i),e.lineTo(o.x+i,o.y),e.lineTo(o.x,o.y+i),e.lineTo(o.x-i,o.y),e.closePath();break;case"pentagon":Pi(e,o,5,i,-90);break;case"rounded-rect":case"blob":{let t=i/2,r=Math.max(0,Math.min(n,t)),s=o.x-t,a=o.y-t,l=2*t,h=2*t;e.moveTo(s+r,a),e.lineTo(s+l-r,a),e.quadraticCurveTo(s+l,a,s+l,a+r),e.lineTo(s+l,a+h-r),e.quadraticCurveTo(s+l,a+h,s+l-r,a+h),e.lineTo(s+r,a+h),e.quadraticCurveTo(s,a+h,s,a+h-r),e.lineTo(s,a+r),e.quadraticCurveTo(s,a,s+r,a),e.closePath();break}case"circle":e.ellipse(o.x,o.y,i,i,0,0,2*Math.PI)}}function Pi(e,t,i,n,o){let r=360/i;for(let s=0;s<i;s++){let i=(o+s*r)*Math.PI/180,a=t.x+n*Math.cos(i),l=t.y+n*Math.sin(i);0===s?e.moveTo(a,l):e.lineTo(a,l)}e.closePath()}function Ri(e,t){switch(e.kind){case"backbone":case"branch":case"group":return t.defaultStroke;case"cross-polymer":return t.crossPolymerBondColor;case"hbond":return function(e){if(e.a1.biotype!==Z||e.a2.biotype!==Z)return!1;let t=Di(e.a1),i=Di(e.a2);for(let[e,n]of Ni)if(t===e&&i===n||t===n&&i===e)return!0;return!1}(e)?t.hbondColor:t.nonCanonicalHbondColor}}function Hi(e){return 1.125}var Ni=[["A","T"],["A","U"],["G","C"]];function Di(e){let t=e.monomer?.naturalAnalog,i=void 0!==t&&""!==t?t:e.symbol;return 0===i.length?"":i.charAt(0).toUpperCase()}function Fi(e){let t=new Map,i=new Map;for(let t of e.bonds){let e=t.a1.id,n=t.a2.id,o=i.get(e);void 0===o&&(o=[],i.set(e,o)),o.push(t);let r=i.get(n);void 0===r&&(r=[],i.set(n,r)),r.push(t)}for(let n of e.atoms)Gi(t,n,i.get(n.id)??[]);for(let n of e.groups){if("bracket"!==n.kind)continue;let o=n.repeat?.min??1;if(1===o)continue;let r=new Set(n.members.map(e=>e.target)),s=new Map;for(let t of e.atoms){if(!r.has(t.bio.chainId))continue;let e=new Map;Gi(e,t,i.get(t.id)??[]);for(let[t,i]of e)s.set(t,(s.get(t)??0)+i*(o-1))}for(let[e,i]of s)t.set(e,(t.get(e)??0)+i)}for(let[e,i]of[...t])0===i&&t.delete(e);let n=function(e){let t=0;for(let[i,n]of e){let e=Oi[i];void 0!==e&&(t+=e*n)}return Math.round(1e3*t)/1e3}(t);return{elements:t,mw:n}}var Oi={H:1.008,C:12.011,N:14.007,O:15.999,F:18.998,Na:22.99,Mg:24.305,P:30.974,S:32.06,Cl:35.45,K:39.098,Ca:40.078,Br:79.904,I:126.904,Fe:55.845,Zn:65.38,Cu:63.546},zi={C:4,N:3,O:2,S:2,P:3,F:1,Cl:1,Br:1,I:1,H:1};function Gi(e,t,i){if(null===t.monomer)return;let n=function(e){let t=Vi.get(e);if(void 0!==t)return t;let i=function(e){let t=new Map;if(void 0===e.molfile||""===e.molfile)return{elements:t};let i=function(e){let t=e.split(/\r\n|\n|\r/);if(t.length<5)return null;let i=t[3];if(void 0===i||i.length<6)return null;let n=parseInt(i.slice(0,3),10),o=parseInt(i.slice(3,6),10);if(!Number.isFinite(n)||!Number.isFinite(o)||t.length<4+n+o)return null;let r=[];for(let e=0;e<n;e++){let i=t[4+e];if(void 0===i)return null;let n=i.slice(31,34).trim();r.push(n)}let s=new Array(n).fill(0);for(let e=0;e<o;e++){let i=t[4+n+e];if(void 0===i)return null;let o=parseInt(i.slice(0,3),10),r=parseInt(i.slice(3,6),10),a=parseInt(i.slice(6,9),10);if(!Number.isFinite(o)||!Number.isFinite(r)||!Number.isFinite(a))continue;let l=4===a?1:a;o>=1&&o<=n&&(s[o-1]=(s[o-1]??0)+l),r>=1&&r<=n&&(s[r-1]=(s[r-1]??0)+l)}return{atoms:r,bondOrders:s}}(e.molfile);if(null===i)return{elements:t};let{atoms:n,bondOrders:o}=i;for(let e=0;e<n.length;e++){let i=n[e];if("R"===i||"R#"===i||"*"===i)continue;t.set(i,(t.get(i)??0)+1);let r=zi[i];if(void 0===r)continue;let s=r-(o[e]??0);s>0&&t.set("H",(t.get("H")??0)+s)}for(let i of e.rgroups){let e=i.capGroupName;if(void 0===e)continue;let n=ji(e);for(let[e,i]of n)t.set(e,(t.get(e)??0)+i)}return{elements:t}}(e);return Vi.set(e,i),i}(t.monomer);for(let[t,i]of n.elements)e.set(t,(e.get(t)??0)+i);for(let n of i){if("hbond"===n.kind||"group"===n.kind)continue;let i=n.a1.id===t.id?n.r1:n.r2,o=qi(t.monomer,i);if(void 0===o)continue;let r=ji(o);for(let[t,i]of r)e.set(t,(e.get(t)??0)-i)}}function qi(e,t){if("numeric"!==t.kind&&"positional"!==t.kind)return;let i=(t.kind,t.r);for(let t of e.rgroups){let e=/^R([1-9][0-9]*)$/.exec(t.label);if(null!==e&&parseInt(e[1],10)===i)return t.capGroupName}}function ji(e){let t=new Map;switch(e){case"H":t.set("H",1);break;case"OH":t.set("H",1),t.set("O",1)}return t}var Vi=new WeakMap;function Yi(e){return Fi(e).mw}var Wi={AA:13.65,AC:10.67,AG:12.79,AU:12.14,CA:10.67,CC:7.52,CG:9.39,CU:8.37,GA:12.79,GC:9.39,GG:11.77,GU:10.21,UA:12.14,UC:8.37,UG:10.21,UU:8.99},Ui={A:15.4,C:7.4,G:11.7,U:10,T:8.8};function Ki(e){let t=0;for(let i of e.chains)"PEPTIDE"===i.polymerType?t+=Xi(i.backboneAtoms):"RNA"===i.polymerType&&(t+=Qi(i.backboneAtoms));return Math.round(1e4*t)/1e4}function Xi(e){let t=0,i=0,n=0;for(let o of e){let e=Zi(o);"W"===e?t++:"Y"===e?i++:"C"===e&&n++}return 5.5*t+1.49*i+.0625*n}function Qi(e){let t=[];for(let i of e)if(void 0!==i.branchAtom&&i.branchAtom.biotype===Z){let e=Zi(i.branchAtom);"T"===e&&(e="U"),""!==e&&t.push(e)}if(0===t.length)return 0;if(1===t.length){let e=t[0];return Ui[e]??0}let i=0;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1],r=Wi[n+o];void 0!==r&&(i+=r)}let n=0;for(let e=1;e<t.length-1;e++){let i=t[e];n+=Ui[i]??0}return 2*i-n}function Zi(e){let t=e.monomer;return null!==t&&void 0!==t.naturalAnalog&&""!==t.naturalAnalog?t.naturalAnalog.charAt(0).toUpperCase():""===e.symbol?"":e.symbol.charAt(0).toUpperCase()}function Ji(e){let t=[];t.push("HWE pseudo-molfile"),t.push(" HWE 2D"),t.push("");let i=e.atoms.length,n=e.bonds.length;t.push(function(e,t){return nn(e)+nn(t)+" 0 0 0 0 0 0 0 0999 V2000"}(i,n));for(let i of e.atoms)t.push(en(i));let o=new Map;for(let t=0;t<e.atoms.length;t++)o.set(e.atoms[t].id,t+1);for(let i of e.bonds){let e=o.get(i.a1.id),n=o.get(i.a2.id);void 0===e||void 0===n||t.push(tn(e,n))}return t.push("M END"),t.join("\n")+"\n"}function en(e){let t=function(e){let t=e.monomer;return null!==t&&""!==t.symbol?t.symbol:""!==e.symbol?e.symbol:null!==t&&void 0!==t.naturalAnalog&&""!==t.naturalAnalog?t.naturalAnalog:"X"}(e);return on(e.p.x)+on(e.p.y)+on(0)+" "+function(e){return e.length>=3?e:e+" ".repeat(3-e.length)}(t)+" 0 0 0 0 0 0 0 0 0 0 0 0"}function tn(e,t){return nn(e)+nn(t)+nn(1)+nn(0)}function nn(e){let t=String(e);return t.length>=3?t:" ".repeat(3-t.length)+t}function on(e){let t=e.toFixed(4);return t.length>=10?t.slice(0,10):" ".repeat(10-t.length)+t}var rn=new Map,sn=class{constructor(e){if(this._destroyed=!1,this._parseHits=0,this._parseMisses=0,this._layoutHits=0,this._layoutMisses=0,this._renderHits=0,this._renderMisses=0,void 0===e.monomerLib||null===e.monomerLib)throw new TypeError("HelmService: options.monomerLib is required");this.monomerLib=e.monomerLib,this.theme=e.theme??si,this.logger=e.logger??new F,this.options=Object.freeze({...e});let t=e.cacheSize??256;this._parseCache=new D({max:t}),this._layoutCache=new D({max:t}),this._renderCache=new D({max:t}),this._libUnsub=this.monomerLib.onChanged.subscribe(()=>{this.clearCaches()})}parse(e,t){this._ensureLive(),e=this._normalizeHelm(e);let i=t?.mode??"lenient",n=!1!==t?.resolveMonomers,o=`${(s={mode:i,resolveMonomers:n,helm:e}).mode}|${s.resolveMonomers?1:0}|${s.helm}`,r=this._parseCache.get(o);var s;if(void 0!==r)return this._parseHits+=1,r;this._parseMisses+=1;let a={mode:i,resolveMonomers:n},l=De(e,this.monomerLib,a),h={mol:l.mol,diagnostics:Object.freeze([...l.diagnostics])};return this._parseCache.set(o,h),h}serialize(e,t){return this._ensureLive(),qe(e,{...void 0!==t?.canonicalize?{canonicalize:t.canonicalize}:{},...void 0!==t?.includeHighlights?{includeHighlights:t.includeHighlights}:{},...void 0!==t?.version?{version:t.version}:{}})}validate(e,t){this._ensureLive(),e=this._normalizeHelm(e);let{mol:i,diagnostics:n}=this.parse(e,{mode:"lenient"}),o=void 0!==t?.mode?{mode:t.mode}:{},r=function(e,t,i){let n=i?.mode??"lenient",o=[];for(let i of tt)o.push(...i(e,t));let r="pedantic"===n?o.map(e=>"warning"===e.severity?{...e,severity:"error"}:e):o;if("strict"===n||"pedantic"===n){let e=r.filter(e=>"error"===e.severity);if(e.length>0)throw new H(e)}return r}(i,this.monomerLib,o);return[...n,...r]}canonicalize(e){this._ensureLive(),e=this._normalizeHelm(e);let{mol:t}=this.parse(e,{mode:"lenient"});return qe(new Ue(t).run(),{canonicalize:!0,version:"V2.0"})}removeGaps(e){return this._ensureLive(),function(e,t){let i=function(e){let t=new Map;for(let i of e.atoms)t.set(i.bio.continuousId,i.id);let i=new Set;for(let t of e.atoms)"*"===t.symbol&&i.add(t.id);if(0===i.size)return{mol:e,survivorByOldContinuousId:t};let n=new Map;for(let t of e.atoms)n.set(t.id,[]);for(let t of e.bonds)n.get(t.a1.id)?.push(t),t.a2.id!==t.a1.id&&n.get(t.a2.id)?.push(t);let o=function(e,t){let i=[],n=new Set;for(let o of e){if(n.has(o))continue;let r=new Set,s=[o];for(;s.length>0;){let i=s.pop();if(!r.has(i)){r.add(i),n.add(i);for(let n of t.get(i)??[]){let t=n.a1.id===i?n.a2.id:n.a1.id;e.has(t)&&!r.has(t)&&s.push(t)}}}let a=[],l=new Set;for(let e of r)for(let i of t.get(e)??[])l.has(i.id)||r.has(i.a1.id)!==r.has(i.a2.id)&&(l.add(i.id),a.push(i));i.push({atoms:r,boundary:a})}return i}(i,n);for(let e of o)Ze(e,n);let r=e.atoms.filter(e=>!i.has(e.id)),s=e.chains.map(e=>({chain:e,backbone:e.backboneAtoms.filter(e=>!i.has(e.id))})).filter(e=>e.backbone.length>0||0===e.chain.backboneAtoms.length),a=new Map,l=new Map;for(let e of s)e.backbone.forEach((t,i)=>{a.set(t.id,e.chain.id),l.set(t.id,i+1)});let h=1;for(let t of e.bonds)t.id>=h&&(h=t.id+1);let d=new Map;for(let e of o){if(2!==e.boundary.length)continue;let t=Je(e,e.boundary[0]),i=Je(e,e.boundary[1]);et(t.r,1)&&et(i.r,2)&&([t,i]=[i,t]);let n=a.get(t.atom.id)===a.get(i.atom.id),o=l.get(t.atom.id),r=l.get(i.atom.id),s=n&&void 0!==o&&void 0!==r&&o+1===r&&et(t.r,2)&&et(i.r,1)?"backbone":"cross-polymer",c=Math.min(...e.boundary.map(e=>e.id));d.set(c,{id:h++,a1:t.atom,a2:i.atom,kind:s,r1:t.r,r2:i.r})}let c=[];for(let t of e.bonds){let e=d.get(t.id);void 0!==e&&c.push(e),!i.has(t.a1.id)&&!i.has(t.a2.id)&&c.push(t)}let u=s.map(e=>({id:e.chain.id,polymerType:e.chain.polymerType,backboneAtoms:e.backbone,bonds:c.filter(t=>a.get(t.a1.id)===e.chain.id&&a.get(t.a2.id)===e.chain.id),...void 0!==e.chain.annotation?{annotation:e.chain.annotation}:{}})),p=new Map;for(let e of u){let t=0;for(let i of e.backboneAtoms)t+=1,p.set(i.id,{...i,bio:{...i.bio,positionInChain:t}})}for(let e of r)p.has(e.id)||p.set(e.id,e);for(let[e,t]of p)if(void 0!==t.branchAtom&&i.has(t.branchAtom.id)){let{branchAtom:i,...n}=t;p.set(e,n)}let m=u.map(e=>{let t=e.backboneAtoms.map(e=>p.get(e.id)),i=e.bonds.map(e=>({...e,a1:p.get(e.a1.id),a2:p.get(e.a2.id)}));return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:i,...void 0!==e.annotation?{annotation:e.annotation}:{}}}),f=c.map(e=>({...e,a1:p.get(e.a1.id),a2:p.get(e.a2.id)}));return{mol:{atoms:r.map(e=>p.get(e.id)),bonds:f,chains:m,groups:e.groups,annotations:e.annotations},survivorByOldContinuousId:t}}(De(e,t??null,{mode:"lenient",resolveMonomers:!1}).mol),n=function(e){let t=re(e),i=new Map;for(let n of e.atoms){let e=t.get(n.id);void 0!==e&&e!==n.bio.continuousId?i.set(n.id,{...n,bio:{...n.bio,continuousId:e}}):i.set(n.id,n)}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=i.get(t.id),n=i.get(t.branchAtom.id);void 0===e||void 0===n||(e.branchAtom=n)}let n=e.bonds.map(e=>{let t=i.get(e.a1.id),n=i.get(e.a2.id);return void 0===t||void 0===n||t===e.a1&&n===e.a2?e:{...e,a1:t,a2:n}}),o=new Map;for(let e of n)o.set(e.id,e);let r=e.chains.map(e=>{let t=[];for(let n of e.backboneAtoms){let e=i.get(n.id);t.push(e??n)}let n=[];for(let t of e.bonds){let e=o.get(t.id);n.push(e??t)}return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>i.get(e.id)??e),bonds:n,chains:r,groups:e.groups,annotations:e.annotations}}(i.mol),o=new Map;for(let e of n.atoms)o.set(e.id,e.bio.continuousId);let r=new Map;for(let[e,t]of i.survivorByOldContinuousId){let i=o.get(t);void 0!==i&&r.set(e,i)}return{srcHelm:e,resHelm:qe(n,{version:"V2.0"}),monomerMap:r}}(this._normalizeHelm(e),this.monomerLib)}renderToSvg(e,t){this._ensureLive(),e=this._normalizeHelm(e);let i=this._resolveRenderOptions(t),n=this._renderKey(e,i),o=this._renderCache.get(n);if(void 0!==o)return this._renderHits+=1,o;this._renderMisses+=1;let{mol:r}=this.parse(e,{mode:"lenient"}),s=this._layout(r,i.bondLength),{svg:a}=wi(s,i);return this._renderCache.set(n,a),a}renderMol(e,t){this._ensureLive();let i=this._resolveRenderOptions(t),{svg:n}=wi(e,i);return n}renderMolResult(e,t){return this._ensureLive(),wi(e,this._resolveRenderOptions(t))}async renderToPng(e,t){if(this._ensureLive(),e=this._normalizeHelm(e),"function"!=typeof globalThis.OffscreenCanvas)throw new N("png-rendering-requires-browser","HelmService.renderToPng requires OffscreenCanvas (browser-only).");let i=this._resolveRenderOptions(t),{mol:n}=this.parse(e,{mode:"lenient"});return async function(e,t={}){let i=function(){let e=globalThis;return"function"==typeof e.OffscreenCanvas?e.OffscreenCanvas:null}();if(null===i&&void 0===t.canvas)throw new Error("renderToPng: OffscreenCanvas is not available in this environment");let n=t.theme??si,o=t.width??400,r=t.height??100,s=t.pixelRatio??1,a=t.canvas??new i(Math.max(1,Math.round(o*s)),Math.max(1,Math.round(r*s))),l=a.getContext("2d");if(null===l)throw new Error("renderToPng: failed to acquire 2D context");l.save(),l.scale(s,s),Ii(l,e,{x:0,y:0,width:o,height:r},{...t,backColor:t.backColor??n.background}),l.restore();let h=a;if("function"!=typeof h.convertToBlob)throw new Error("renderToPng: canvas.convertToBlob is not available");let d=await(await h.convertToBlob({type:"image/png"})).arrayBuffer();return new Uint8Array(d)}(this._layout(n,i.bondLength),i)}renderToCanvas(e,t,i,n){this._ensureLive(),t=this._normalizeHelm(t);let o=this._resolveRenderOptions(n),{mol:r}=this.parse(t,{mode:"lenient"}),s=this._layout(r,o.bondLength),{bbox:a,drawBox:l}=Ii(e,s,i,o);return{mol:s,bbox:a,drawBox:l}}renderMolToCanvas(e,t,i,n){this._ensureLive();let o=this._resolveRenderOptions(n),{bbox:r,drawBox:s}=Ii(e,t,i,o);return{mol:t,bbox:r,drawBox:s}}*renderMany(e,t){for(let i of e??[]){let e=this.renderToSvg(i.helm,t);yield{id:i.id,svg:e}}}getFormula(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return Fi(t)}getMolWeight(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return Yi(t)}getExtinctionCoefficient(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return Ki(t)}getMolfile(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return Ji(t)}hasAtomicMolfileProvider(){return"function"==typeof this.options.atomicMolfileProvider}async getAtomicMolfile(e){this._ensureLive(),e=this._normalizeHelm(e);let t=this.options.atomicMolfileProvider;if("function"!=typeof t)throw new N("atomic-molfile-not-configured","Set HelmServiceOptions.atomicMolfileProvider to enable atomic-level expansion.");return await t(e,this.monomerLib)}hasExtraPanes(){let e=this.options.extraPanes;return void 0!==e&&e.size>0}getExtraPanes(){return this.options.extraPanes??rn}invalidate(e){if(void 0!==e)for(let t of[this._parseCache,this._layoutCache,this._renderCache]){let i=[];for(let n of t.keys())e(n)&&i.push(n);for(let e of i)t.delete(e)}else this.clearCaches()}clearCaches(){this._parseCache.clear(),this._layoutCache.clear(),this._renderCache.clear(),this._parseHits=0,this._parseMisses=0,this._layoutHits=0,this._layoutMisses=0,this._renderHits=0,this._renderMisses=0}destroy(){this._destroyed||(this._destroyed=!0,this._libUnsub(),this.clearCaches())}_ensureLive(){if(this._destroyed)throw new N("service-destroyed","HelmService instance has been destroyed.")}_normalizeHelm(e){return null==e?"":"string"==typeof e?e:String(e)}_resolveRenderOptions(e){let t={},i=e?.theme??this.theme;return t.theme=i,void 0!==e?.width&&(t.width=e.width),void 0!==e?.height&&(t.height=e.height),void 0!==e?.backColor&&(t.backColor=e.backColor),void 0!==e?.padding&&(t.padding=e.padding),void 0!==e?.showIds&&(t.showIds=e.showIds),void 0!==e?.showAnnotations&&(t.showAnnotations=e.showAnnotations),void 0!==e?.bondLength&&(t.bondLength=e.bondLength),void 0!==e?.fontSize&&(t.fontSize=e.fontSize),void 0!==e?.maxScale&&(t.maxScale=e.maxScale),void 0!==e?.showRGroupLabels&&(t.showRGroupLabels=e.showRGroupLabels),void 0!==e?.selectedAtomIds&&(t.selectedAtomIds=e.selectedAtomIds),void 0!==e?.highlightedAtomIds&&(t.highlightedAtomIds=e.highlightedAtomIds),void 0!==e?.fixedModelBbox&&(t.fixedModelBbox=e.fixedModelBbox),t}_renderKey(e,t){let i=(t.theme??this.theme).name;return`${this._libCacheTag()}|${i}|${t.width??0}x${t.height??0}|p${t.padding??-1}|b${t.bondLength??-1}|bg${t.backColor??""}|i${!0===t.showIds?1:0}a${!1===t.showAnnotations?0:1}|s${t.maxScale??1}|${e}`}_layout(e,t){let i=`${(r=e).chains.map(e=>`${e.id}:${e.polymerType}:${e.backboneAtoms.length}`).join(",")}#${r.atoms.map(e=>`${e.id}@${e.symbol}@${e.bio.chainId}`).join(";")}#${r.bonds.map(e=>`${e.id}:${e.a1.id}-${e.a2.id}:${e.kind}`).join(";")}`,n=`${this._libCacheTag()}|${t??"d"}|${i}`,o=this._layoutCache.get(n);var r;if(void 0!==o)return this._layoutHits+=1,o;this._layoutMisses+=1;let s=void 0!==t?Ut(e,{bondLength:t}):Ut(e);return this._layoutCache.set(n,s),s}get stats(){return{parseHits:this._parseHits,parseMisses:this._parseMisses,layoutHits:this._layoutHits,layoutMisses:this._layoutMisses,renderHits:this._renderHits,renderMisses:this._renderMisses}}_libCacheTag(){let e=this.monomerLib,t="number"==typeof e.version?e.version:0;return`${this.monomerLib.source}@${t}`}},an=class{constructor(e,t){this.atoms=e,this.bonds=t,this.isEmpty=0===e.size&&0===t.size,Object.freeze(this)}},ln=new an(new Set,new Set),hn={empty:()=>ln,fromAtoms:e=>new an(new Set(e),new Set),fromBonds:e=>new an(new Set,new Set(e)),fromAtomsAndBonds:(e,t)=>new an(new Set(e),new Set(t)),union(...e){if(0===e.length)return ln;let t=new Set,i=new Set;for(let n of e){for(let e of n.atoms)t.add(e);for(let e of n.bonds)i.add(e)}return new an(t,i)},difference(e,t){let i=new Set,n=new Set;for(let n of e.atoms)t.atoms.has(n)||i.add(n);for(let i of e.bonds)t.bonds.has(i)||n.add(i);return new an(i,n)},intersect(e,t){let i=new Set,n=new Set;for(let n of e.atoms)t.atoms.has(n)&&i.add(n);for(let i of e.bonds)t.bonds.has(i)&&n.add(i);return new an(i,n)},toggle(e,t){if("atom"===t.kind){let i=new Set(e.atoms);return i.has(t.id)?i.delete(t.id):i.add(t.id),new an(i,new Set(e.bonds))}let i=new Set(e.bonds);return i.has(t.id)?i.delete(t.id):i.add(t.id),new an(new Set(e.atoms),i)},hasAtom:(e,t)=>e.atoms.has(t),hasBond:(e,t)=>e.bonds.has(t),equals(e,t){if(e===t)return!0;if(e.atoms.size!==t.atoms.size||e.bonds.size!==t.bonds.size)return!1;for(let i of e.atoms)if(!t.atoms.has(i))return!1;for(let i of e.bonds)if(!t.bonds.has(i))return!1;return!0}};function dn(e){let t=e.monomer;return null===t?0:t.rgroups.length}function cn(e,t){let i=dn(e);if(0===i)return[];let n=new Set(function(e,t){let i=new Set;for(let n of t)n.a1.id===e.id&&"numeric"===n.r1.kind&&i.add(n.r1.r),n.a2.id===e.id&&"numeric"===n.r2.kind&&i.add(n.r2.r);let n=[],o=Array.from(i).sort((e,t)=>e-t);for(let e of o)n.push(e);return n}(e,t)),o=[];for(let e=1;e<=i;e++)n.has(e)||o.push(e);return o}function un(e,t){let i=[];for(let n of t)if(n.a1.id===e.id){let e="numeric"===n.r1.kind?n.r1.r:0;i.push({bond:n,side:"r1",rNumber:e})}else if(n.a2.id===e.id){let e="numeric"===n.r2.kind?n.r2.r:0;i.push({bond:n,side:"r2",rNumber:e})}return i}function pn(e,t){return e.kind===t.kind&&("numeric"===e.kind&&"numeric"===t.kind?e.r===t.r:"positional"!==e.kind||"positional"!==t.kind||e.position===t.position&&e.r===t.r)}var mn=class{constructor(e){this._atoms=new Map,this._atomOrder=[],this._bonds=new Map,this._bondOrder=[],this._chains=new Map,this._chainOrder=[],this._addedAtoms=new Set,this._removedAtoms=new Set,this._modifiedAtoms=new Set,this._addedBonds=new Set,this._removedBonds=new Set,this._modifiedBonds=new Set,this._topologyDirty=!1,this._idgen=new oe;let t=function(e){let t=0;for(let i of e.atoms)i.id>t&&(t=i.id);for(let i of e.bonds)i.id>t&&(t=i.id);return t}(e);for(let e=0;e<t;e++)this._idgen.next();for(let t of e.chains)this._chains.set(t.id,{id:t.id,polymerType:t.polymerType,backboneAtomIds:t.backboneAtoms.map(e=>e.id),bondIds:t.bonds.map(e=>e.id),annotation:t.annotation}),this._chainOrder.push(t.id);for(let t of e.atoms)this._atoms.set(t.id,{id:t.id,p:{x:t.p.x,y:t.p.y},biotype:t.biotype,symbol:t.symbol,monomer:t.monomer,bio:{...t.bio},hidden:t.hidden,selected:t.selected,highlighted:t.highlighted,tag:t.tag,branchAtomId:t.branchAtom?.id,inlineSource:t.inlineSource}),this._atomOrder.push(t.id);for(let t of e.bonds)this._bonds.set(t.id,{id:t.id,a1Id:t.a1.id,a2Id:t.a2.id,kind:t.kind,r1:t.r1,r2:t.r2,ratio:t.ratio,tag:t.tag}),this._bondOrder.push(t.id);this._groups=[...e.groups],this._annotations=e.annotations}addAtom(e){let t=this._idgen.next(),i=function(e){switch(e){case X:return ne.PEPTIDE;case Q:case Z:case J:case ie:return ne.RNA;case ee:return ne.CHEM;case te:return ne.BLOB}}(e.biotype),n=e.chainId??this._pickChainId(i),o=this._chains.get(n);void 0===o&&(o={id:n,polymerType:i,backboneAtomIds:[],bondIds:[],annotation:void 0},this._chains.set(n,o),this._chainOrder.push(n));let r=e.positionInChain??o.backboneAtomIds.length+1,s={id:t,p:{x:e.p.x,y:e.p.y},biotype:e.biotype,symbol:e.symbol,monomer:null,bio:{chainId:n,positionInChain:r,continuousId:0},hidden:!1,selected:!1,highlighted:!1,tag:void 0,branchAtomId:void 0,inlineSource:void 0};this._atoms.set(t,s),this._atomOrder.push(t);let a=Math.max(0,Math.min(r-1,o.backboneAtomIds.length));return o.backboneAtomIds.splice(a,0,t),this._addedAtoms.add(t),this._topologyDirty=!0,t}removeAtom(e){let t=this._atoms.get(e);if(void 0===t)return;let i=[];for(let t of this._bonds.values())(t.a1Id===e||t.a2Id===e)&&i.push(t.id);for(let e of i)this._removeBondInternal(e);for(let t of this._atoms.values())t.branchAtomId===e&&(t.branchAtomId=void 0);let n=this._chains.get(t.bio.chainId);if(void 0!==n){let t=n.backboneAtomIds.indexOf(e);t>=0&&n.backboneAtomIds.splice(t,1)}this._atoms.delete(e);let o=this._atomOrder.indexOf(e);o>=0&&this._atomOrder.splice(o,1),this._addedAtoms.has(e)?this._addedAtoms.delete(e):this._removedAtoms.add(e),this._modifiedAtoms.delete(e),this._topologyDirty=!0}updateAtom(e,t){let i=this._atoms.get(e);void 0!==i&&(void 0!==t.p&&(i.p={x:t.p.x,y:t.p.y}),void 0!==t.symbol&&(i.symbol=t.symbol),void 0!==t.selected&&(i.selected=t.selected),void 0!==t.highlighted&&(i.highlighted=t.highlighted),"tag"in t&&(i.tag=t.tag),void 0!==t.hidden&&(i.hidden=t.hidden),this._addedAtoms.has(e)||this._modifiedAtoms.add(e))}addBond(e){if(!this._atoms.has(e.a1))throw new Error(`Transaction.addBond: atom ${e.a1} does not exist`);if(!this._atoms.has(e.a2))throw new Error(`Transaction.addBond: atom ${e.a2} does not exist`);for(let t of this._bonds.values()){let i=t.a1Id===e.a1&&t.a2Id===e.a2&&pn(t.r1,e.r1)&&pn(t.r2,e.r2),n=t.a1Id===e.a2&&t.a2Id===e.a1&&pn(t.r1,e.r2)&&pn(t.r2,e.r1);if(i||n)throw new Error(`Transaction.addBond: duplicate bond ${e.a1}:${fn(e.r1)}-${e.a2}:${fn(e.r2)}`)}let t=this._idgen.next();this._bonds.set(t,{id:t,a1Id:e.a1,a2Id:e.a2,kind:e.kind,r1:e.r1,r2:e.r2,ratio:void 0,tag:void 0}),this._bondOrder.push(t);let i=this._atoms.get(e.a1),n=this._atoms.get(e.a2);if(void 0!==i&&void 0!==n&&i.bio.chainId===n.bio.chainId){let e=this._chains.get(i.bio.chainId);void 0!==e&&e.bondIds.push(t)}return this._addedBonds.add(t),this._topologyDirty=!0,t}removeBond(e){this._bonds.has(e)&&(this._removeBondInternal(e),this._topologyDirty=!0)}updateBond(e,t){let i=this._bonds.get(e);void 0!==i&&("tag"in t&&(i.tag=t.tag),"ratio"in t&&(i.ratio=t.ratio),this._addedBonds.has(e)||this._modifiedBonds.add(e))}commit(){let e=new Map;for(let t of this._atomOrder){let i=this._atoms.get(t);if(void 0===i)continue;let n={id:i.id,p:{x:i.p.x,y:i.p.y},biotype:i.biotype,symbol:i.symbol,monomer:i.monomer,bio:{...i.bio},hidden:i.hidden,selected:i.selected,highlighted:i.highlighted,...void 0!==i.tag?{tag:i.tag}:{},...void 0!==i.inlineSource?{inlineSource:i.inlineSource}:{}};e.set(t,n)}for(let t of this._atomOrder){let i=this._atoms.get(t);if(void 0===i||void 0===i.branchAtomId)continue;let n=e.get(t),o=e.get(i.branchAtomId);void 0===n||void 0===o||(n.branchAtom=o)}let t=new Map;for(let i of this._bondOrder){let n=this._bonds.get(i);if(void 0===n)continue;let o=e.get(n.a1Id),r=e.get(n.a2Id);if(void 0===o||void 0===r)continue;let s={id:n.id,a1:o,a2:r,kind:n.kind,r1:n.r1,r2:n.r2,...void 0!==n.ratio?{ratio:{...n.ratio}}:{},...void 0!==n.tag?{tag:n.tag}:{}};t.set(i,s)}let i=[];for(let n of this._chainOrder){let o=this._chains.get(n);if(void 0===o||0===o.backboneAtomIds.length&&0===o.bondIds.length)continue;let r=[];for(let t of o.backboneAtomIds){let i=e.get(t);void 0!==i&&r.push(i)}let s=[];for(let e of o.bondIds){let i=t.get(e);void 0!==i&&s.push(i)}i.push({id:o.id,polymerType:o.polymerType,backboneAtoms:r,bonds:s,...void 0!==o.annotation?{annotation:o.annotation}:{}})}let n={atoms:this._atomOrder.map(t=>e.get(t)).filter(e=>void 0!==e),bonds:this._bondOrder.map(e=>t.get(e)).filter(e=>void 0!==e),chains:i,groups:[...this._groups],annotations:this._annotations};this._topologyDirty&&(n=function(e){let t=re(e),i=new Map;for(let n of e.atoms){let e=t.get(n.id);void 0!==e&&e!==n.bio.continuousId?i.set(n.id,{...n,bio:{...n.bio,continuousId:e}}):i.set(n.id,n)}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=i.get(t.id),n=i.get(t.branchAtom.id);void 0===e||void 0===n||(e.branchAtom=n)}let n=e.bonds.map(e=>{let t=i.get(e.a1.id),n=i.get(e.a2.id);return void 0===t||void 0===n||t===e.a1&&n===e.a2?e:{...e,a1:t,a2:n}}),o=new Map;for(let e of n)o.set(e.id,e);let r=e.chains.map(e=>{let t=[];for(let n of e.backboneAtoms)t.push(i.get(n.id)??n);let n=[];for(let t of e.bonds)n.push(o.get(t.id)??t);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>i.get(e.id)??e),bonds:n,chains:r,groups:e.groups,annotations:e.annotations}}(n));let o=Object.freeze({addedAtomIds:new Set(this._addedAtoms),removedAtomIds:new Set(this._removedAtoms),addedBondIds:new Set(this._addedBonds),removedBondIds:new Set(this._removedBonds),modifiedAtomIds:new Set(this._modifiedAtoms),modifiedBondIds:new Set(this._modifiedBonds)});return this._addedAtoms.clear(),this._removedAtoms.clear(),this._modifiedAtoms.clear(),this._addedBonds.clear(),this._removedBonds.clear(),this._modifiedBonds.clear(),this._topologyDirty=!1,{mol:n,changes:o}}_removeBondInternal(e){if(void 0===this._bonds.get(e))return;this._bonds.delete(e);let t=this._bondOrder.indexOf(e);t>=0&&this._bondOrder.splice(t,1);for(let t of this._chains.values()){let i=t.bondIds.indexOf(e);i>=0&&t.bondIds.splice(i,1)}this._addedBonds.has(e)?this._addedBonds.delete(e):this._removedBonds.add(e),this._modifiedBonds.delete(e)}_pickChainId(e){let t=function(e){switch(e){case ne.PEPTIDE:return"PEPTIDE";case ne.RNA:return"RNA";case ne.CHEM:return"CHEM";case ne.BLOB:return"BLOB";case ne.G:return"G"}}(e),i=1;for(;this._chains.has(`${t}${i}`);)i+=1;return`${t}${i}`}};function fn(e){switch(e.kind){case"numeric":return`R${e.r}`;case"unspecified":return"?";case"wildcard":return"*";case"pair":return"pair";case"positional":return`${e.position}pos:R${e.r}`}}var bn=class{constructor(e,t,i){this.atoms=[],this.bonds=[],this.bondHitWidth=i?.bondHitWidth??4,this.rebuild(e,t)}rebuild(e,t){let i=[];for(let n of e.atoms)n.hidden||i.push({atom:n,bbox:ci(n,t),hitRadius:pi(n,t)});let n=[];for(let t of e.bonds)n.push({bond:t,a:t.a1.p,b:t.a2.p});this.atoms=i,this.bonds=n}test(e){let t=null,i=null;for(let n of this.atoms){if(!gn(e,n.bbox))continue;let o=e.x-n.atom.p.x,r=e.y-n.atom.p.y,s=Math.sqrt(o*o+r*r);s>n.hitRadius||(null===t||s<t.d?(i=t,t={entry:n,d:s}):(null===i||s<i.d)&&(i={entry:n,d:s}))}if(null!==t)return{atom:t.entry.atom};let n=null;for(let t of this.bonds){let i=An(e,t.a,t.b);i>this.bondHitWidth||(null===n||i<n.d)&&(n={entry:t,d:i})}return null!==n?{bond:n.entry.bond}:null}testRect(e){let t=[];for(let i of this.atoms)gn(i.atom.p,e)&&t.push(i.atom);let i=[];for(let t of this.bonds)gn(t.a,e)&&gn(t.b,e)&&i.push(t.bond);return{atoms:t,bonds:i}}atomCount(){return this.atoms.length}bondCount(){return this.bonds.length}};function gn(e,t){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}function An(e,t,i){let n=i.x-t.x,o=i.y-t.y,r=n*n+o*o;if(0===r){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}let s=((e.x-t.x)*n+(e.y-t.y)*o)/r;s<0?s=0:s>1&&(s=1);let a=t.x+s*n,l=t.y+s*o,h=e.x-a,d=e.y-l;return Math.sqrt(h*h+d*d)}var _n=class{constructor(){this._handlers=new Map}on(e,t){let i=this._handlers.get(e);void 0===i&&(i=new Set,this._handlers.set(e,i));let n=t;return i.add(n),()=>{let t=this._handlers.get(e);void 0!==t&&t.delete(n)}}off(e,t){let i=this._handlers.get(e);void 0!==i&&i.delete(t)}fire(e,t){let i=this._handlers.get(e);if(void 0===i||0===i.size)return;let n=[...i];for(let e of n)e(t)}clear(){this._handlers.clear()}observerCount(e){if(void 0===e){let e=0;for(let t of this._handlers.values())e+=t.size;return e}return this._handlers.get(e)?.size??0}},yn=class{constructor(e){this._entries=[],this._idx=-1;let t=e?.maxEntries??100;if(t<=0)throw new RangeError("HistoryStack: maxEntries must be > 0");this._max=t}push(e){for(this._idx<this._entries.length-1&&(this._entries=this._entries.slice(0,this._idx+1)),this._entries.push(e),this._idx=this._entries.length-1;this._entries.length>this._max;)this._entries.shift(),this._idx-=1}canUndo(){return this._idx>0}canRedo(){return this._idx>=0&&this._idx<this._entries.length-1}undo(){return this.canUndo()?(this._idx-=1,this._entries[this._idx]??null):null}redo(){return this.canRedo()?(this._idx+=1,this._entries[this._idx]??null):null}clear(){this._entries=[],this._idx=-1}get size(){return this._entries.length}current(){return this._idx<0?null:this._entries[this._idx]??null}};function vn(e){let t=e.ownerDocument;if(null!=t)return t;let i=globalThis;if(void 0!==i.document)return i.document;throw new Error("EditorView: no Document available (host.ownerDocument is null).")}function wn(e,t,i,n){let o=e.createElement(t);if(void 0!==i)for(let e of Object.keys(i)){let t=i[e];!1===t||void 0===t||o.setAttribute(e,!0===t?"":String(t))}if(void 0!==n)for(let t of n)"string"==typeof t?o.appendChild(e.createTextNode(t)):o.appendChild(t);return o}function xn(e,t,i=220,n=140){if(null==e||""===t)return null;try{let o=e.get_mol(t);if(null===o)return null;let r=o.get_svg(i,n);return o.delete(),r}catch{return null}}function Cn(e,t,i){let n="data-testid";for(let i=0;i<e.body.children.length;i++){let o=e.body.children[i];if(void 0!==o&&o.getAttribute(n)===t)return o}let o=wn(e,"div",{class:i,[n]:t});return o.style.display="none",e.body.appendChild(o),o}function En(e,t,i){for(;null!==t.firstChild;)t.removeChild(t.firstChild);if(t.appendChild(wn(e,"div",{class:"hw-tooltip__symbol"},[i.symbol])),void 0!==i.name&&""!==i.name&&i.name!==i.symbol&&t.appendChild(wn(e,"div",{class:"hw-tooltip__name"},[i.name])),void 0!==i.rdkitSvg&&null!==i.rdkitSvg&&""!==i.rdkitSvg){let n={class:"hw-tooltip__rdkit"};void 0!==i.rdkitTestid&&(n["data-testid"]=i.rdkitTestid);let o=wn(e,"div",n);o.innerHTML=i.rdkitSvg,t.appendChild(o)}void 0!==i.hint&&""!==i.hint&&t.appendChild(wn(e,"div",{class:"hw-tooltip__hint"},[i.hint]))}function kn(e,t,i){let n=e.style;n.display="block",n.left=`${t+12}px`,n.top=`${i+12}px`}function Bn(e){null!==e&&(e.style.display="none")}function Sn(e){let t=e.body;if(null!=t)for(let e=0;e<t.children.length;e++){let i=t.children[e];if(void 0===i)continue;let n=void 0===i.getAttribute?null:i.getAttribute("data-testid");null!=n&&n.endsWith("-tooltip")&&Bn(i)}}var Mn=class e{constructor(e,t,i){this._baseTransform="",this._viewport={scale:1,offset:{x:0,y:0}},this._pinnedBbox=null,this._tooltip=null,this._bondTooltip=null,this._rdkitSvgCache=new Map,this._unsubs=[],this._destroyed=!1,this.host=e,this._editor=t,this._doc=i?.documentImpl??vn(e),this._width=i?.width??400,this._height=i?.height??200,function(e){let t=vn(e);if(null!==t.querySelector("style[data-hw-editor-view-styles]"))return;let i=t.createElement("style");i.setAttribute("data-hw-editor-view-styles",""),i.textContent=".hw-editor-view{position:relative;display:block;overflow:hidden;outline:none;}.hw-editor-view svg{display:block;user-select:none;}.hw-editor-view.hw-view-only{cursor:default;}";let n=t.head??t.documentElement;null!==n&&n.appendChild(i)}(e);let n=this._doc.createElement("div");n.setAttribute("class","hw-editor-view"),e.appendChild(n),this._tooltip=Cn(this._doc,"atom-tooltip","hw-atom-tooltip"),this._bondTooltip=Cn(this._doc,"bond-tooltip","hw-bond-tooltip"),this._svgRoot=this._renderFresh(),this._unsubs.push(t.on("mol:changed",e=>{this._hideTooltip(),this._hideBondTooltip(),("setHelm"===e.reason||"cleanLayout"===e.reason||"initial"===e.reason)&&(this._pinnedBbox=null),this._renderFresh()})),this._unsubs.push(t.on("selection:change",e=>{this._refreshOverlays(e)})),this._unsubs.push(t.on("highlight:change",e=>{this._refreshOverlays(e)})),this._unsubs.push(t.on("theme:change",()=>{this._renderFresh()})),this._unsubs.push(t.on("view:resize",e=>{this._applyResize(e.width,e.height)})),this._unsubs.push(t.on("view:viewport-change",e=>{this._viewport=e.viewport,this._applyViewport(e.viewport)})),this._unsubs.push(t.on("view:fit-to-content",()=>{this._pinnedBbox=null,this._renderFresh()})),this._unsubs.push(t.on("monomer:hover",e=>{this._showTooltip(e.atom,e.clientX,e.clientY)})),this._unsubs.push(t.on("monomer:hover-end",()=>{this._hideTooltip()})),this._unsubs.push(t.on("bond:hover",e=>{this._showBondTooltip(e.bond,e.clientX,e.clientY)})),this._unsubs.push(t.on("bond:hover-end",()=>{this._hideBondTooltip()})),this._unsubs.push(t.on("bond:preview",e=>{this._paintBondPreview(e.start.p,e.cursor,null!==e.candidate)})),this._unsubs.push(t.on("bond:preview-end",()=>{this._clearBondPreview()})),this._unsubs.push(t.on("bond:cancel",()=>{this._clearBondPreview()})),this._unsubs.push(t.on("selection:rectangle-start",e=>{this._paintSelectionRect(e.origin,e.origin)})),this._unsubs.push(t.on("selection:rectangle-update",e=>{this._paintSelectionRectFromRect(e.rect)})),this._unsubs.push(t.on("selection:rectangle-end",()=>{this._clearSelectionRect()}))}get svgRoot(){return this._svgRoot}get width(){return this._width}get height(){return this._height}resize(e,t){this._destroyed||(this._width=e,this._height=t,this._renderFresh())}redraw(){this._destroyed||this._renderFresh()}destroy(){if(this._destroyed)return;this._destroyed=!0;for(let e of this._unsubs)e();this._unsubs.length=0;let e=this.host.querySelector(".hw-editor-view");null!==e&&null!==e.parentNode&&e.parentNode.removeChild(e),Bn(this._tooltip),Bn(this._bondTooltip),this._tooltip=null,this._bondTooltip=null}_renderFresh(){let e=this._editor.getService(),t=this._currentTheme(),i=this._editor.getMol();null===this._pinnedBbox&&(this._pinnedBbox=xi(i,t));let n=e.renderMol(i,{width:this._width,height:this._height,theme:t,fixedModelBbox:this._pinnedBbox});this._svgRoot=function(e,t){let i=vn(e),n=e.querySelector(".hw-editor-view");if(null===n)throw new Error("EditorView.replaceSvg: missing .hw-editor-view wrapper.");let o=i.createElement("div");o.innerHTML=t;let r=o.querySelector("svg");if(null===r)throw new Error("EditorView.replaceSvg: rendered output contained no <svg>.");for(;null!==n.firstChild;)n.removeChild(n.firstChild);return n.appendChild(r),r}(this.host,n);let o=this._svgRoot.querySelector(".hw-content");return this._baseTransform=null!==o?o.getAttribute("transform")??"":"",this._svgRoot.setAttribute("data-testid","editor-svg"),this._applyOverlaysToCurrent(),(1!==this._viewport.scale||0!==this._viewport.offset.x||0!==this._viewport.offset.y)&&this._applyViewport(this._viewport),this._svgRoot}_refreshOverlays(e){this._applyOverlaysToCurrent()}_applyOverlaysToCurrent(){let e=this._editor.getMol(),t=this._editor.getSelection(),i=function(e,t={}){let i=t.theme??si,n=t.selectedAtomIds??new Set;return{highlightLayer:Ei(e,i,t.highlightedAtomIds??new Set),selectionLayer:ki(e,i,n)}}(e,{theme:this._currentTheme(),selectedAtomIds:t.atoms,highlightedAtomIds:this._editorHighlights()});this._spliceLayer("hw-highlights",i.highlightLayer),this._spliceLayer("hw-selections",i.selectionLayer)}_spliceLayer(e,t){let i=this._svgRoot.querySelector(`.${e}`);if(null===i||null===i.parentNode)return;let n=this._doc.createElementNS("http://www.w3.org/2000/svg","svg");n.innerHTML=t;let o=n.querySelector(`.${e}`);null!==o&&i.parentNode.replaceChild(o,i)}_editorHighlights(){let e=this._editor;return"function"==typeof e._currentHighlights?e._currentHighlights():new Set}_currentTheme(){let e=this._editor;return"function"==typeof e._currentTheme?e._currentTheme():this._editor.getService().theme}_applyResize(e,t){this._width=e,this._height=t,this._pinnedBbox=null,this._renderFresh()}_applyViewport(e){let t=this._svgRoot.querySelector(".hw-content");if(null===t)return;let i=`translate(${e.offset.x} ${e.offset.y}) scale(${e.scale})`,n=""===this._baseTransform?i:`${i} ${this._baseTransform}`;t.setAttribute("transform",n)}_showTooltip(e,t,i){let n=this._tooltip;if(null===n)return;let o=""===e.symbol?"?":e.symbol,r=e.monomer?.name??"",s=e.bio.positionInChain,a=""===e.bio.chainId?"?":e.bio.chainId,l=""!==r&&r!==o?`${r} @ ${a}:${s}`:`${o} @ ${a}:${s}`,h=this._renderRdkitTooltipSvg(e);En(this._doc,n,{symbol:o,name:l,rdkitSvg:h,rdkitTestid:"atom-tooltip-rdkit-svg"});let d=""!==r&&r!==o?`${o} — ${r} @ ${a}:${s}`:`${o} @ ${a}:${s}`,c=this._doc.createElement("div");c.setAttribute("class","hw-atom-tooltip__text"),c.style.display="none",c.appendChild(this._doc.createTextNode(d)),n.appendChild(c),kn(n,t,i)}_renderRdkitTooltipSvg(t){let i=this._editor.getService().options.rdkitModule;if(null==i)return null;let n=t.monomer;if(null===n)return null;let o=n.smiles;if(void 0===o||""===o)return null;let r=`${n.polymerType}:${n.symbol}`;if(this._rdkitSvgCache.has(r))return this._rdkitSvgCache.get(r)??null;let s=xn(i,o,220,140);if(this._rdkitSvgCache.size>=e._RDKIT_CACHE_LIMIT){let e=this._rdkitSvgCache.keys().next().value;void 0!==e&&this._rdkitSvgCache.delete(e)}return this._rdkitSvgCache.set(r,s),s}_hideTooltip(){Bn(this._tooltip)}_showBondTooltip(e,t,i){let n=this._bondTooltip;if(null===n)return;let o=In(e.r1),r=In(e.r2),s=`${e.a1.symbol}@${e.a1.bio.chainId}:${e.a1.bio.positionInChain}`,a=`${e.a2.symbol}@${e.a2.bio.chainId}:${e.a2.bio.positionInChain}`;En(this._doc,n,{symbol:`${o}-${r} (${e.kind})`,name:`${s} ↔ ${a}`}),kn(n,t,i)}_hideBondTooltip(){Bn(this._bondTooltip)}_paintBondPreview(e,t,i){let n=this._svgRoot.querySelector(".hw-content");if(null===n)return;let o=n.querySelector(".hw-bond-preview");null===o&&(o=this._doc.createElementNS("http://www.w3.org/2000/svg","line"),o.setAttribute("class","hw-bond-preview"),o.setAttribute("data-testid","bond-preview"),o.setAttribute("stroke-dasharray","6 4"),o.setAttribute("stroke-width","2"),o.setAttribute("fill","none"),o.setAttribute("pointer-events","none"),n.appendChild(o)),o.setAttribute("x1",String(e.x)),o.setAttribute("y1",String(e.y)),o.setAttribute("x2",String(t.x)),o.setAttribute("y2",String(t.y)),o.setAttribute("stroke",i?"#1f5fcd":"#999999")}_clearBondPreview(){let e=this._svgRoot.querySelector(".hw-bond-preview");null!==e&&null!==e.parentNode&&e.parentNode.removeChild(e)}_paintSelectionRect(e,t){let i=Math.min(e.x,t.x),n=Math.min(e.y,t.y),o=Math.abs(e.x-t.x),r=Math.abs(e.y-t.y);this._paintSelectionRectAt(i,n,o,r)}_paintSelectionRectFromRect(e){this._paintSelectionRectAt(e.x,e.y,e.width,e.height)}_paintSelectionRectAt(e,t,i,n){let o=this._svgRoot.querySelector(".hw-content");if(null===o)return;let r=o.querySelector(".hw-selection-rect");null===r&&(r=this._doc.createElementNS("http://www.w3.org/2000/svg","rect"),r.setAttribute("class","hw-selection-rect"),r.setAttribute("data-testid","selection-rect"),r.setAttribute("fill","rgba(31, 95, 205, 0.08)"),r.setAttribute("stroke","#1f5fcd"),r.setAttribute("stroke-width","1"),r.setAttribute("stroke-dasharray","4 3"),r.setAttribute("pointer-events","none"),o.appendChild(r)),r.setAttribute("x",String(e)),r.setAttribute("y",String(t)),r.setAttribute("width",String(i)),r.setAttribute("height",String(n))}_clearSelectionRect(){let e=this._svgRoot.querySelector(".hw-selection-rect");null!==e&&null!==e.parentNode&&e.parentNode.removeChild(e)}};Mn._RDKIT_CACHE_LIMIT=256;var Tn=Mn;function In(e){switch(e.kind){case"numeric":return`R${e.r}`;case"unspecified":return"?";case"wildcard":return"*";case"pair":return"pair";case"positional":return`${e.position}pos:R${e.r}`}}var Ln=class e{constructor(e,t){this._onClose=null,this._primaryAction=null,this._host=e,this._doc=t.documentImpl??vn(e);let i=this._doc,n={class:"hw-modal-backdrop",role:"presentation"};void 0!==t.testId&&(n["data-testid"]=`dialog-${t.testId}`);let o=wn(i,"div",n),r={class:"hw-modal",role:"dialog","aria-modal":"true","aria-label":t.title};void 0!==t.testId&&(r["data-testid"]=`dialog-${t.testId}-frame`);let s=wn(i,"div",r),a=wn(i,"div",{class:"hw-modal__header"},[t.title]),l=wn(i,"div",{class:"hw-modal__body"});s.appendChild(a),s.appendChild(l),o.appendChild(s);let h=e=>{e.stopPropagation()};for(let e of["mousedown","mousemove","mouseup","mouseover","mouseenter","mouseleave","wheel","contextmenu","dblclick","keydown","keyup","keypress"])o.addEventListener(e,h);s.addEventListener("keydown",e=>{let t=e;if("Enter"!==t.key||"TEXTAREA"===t.target?.tagName)return;let i=this._primaryAction;null!==i&&(t.preventDefault?.(),t.stopImmediatePropagation?.(),i())}),o.addEventListener("click",e=>{e.target!==o?e.stopPropagation():this.close()}),this.root=o,this.body=l}static anyOpen(){return e._openStack.length>0}static closeTopmost(){let t=e._openStack[e._openStack.length-1];return void 0!==t&&(t.close(),!0)}open(t){this._onClose=t??null,null===this.root.parentNode&&this._host.appendChild(this.root),e._openStack.includes(this)||e._openStack.push(this),Sn(this._doc)}close(){let t=e._openStack.indexOf(this);t>=0&&e._openStack.splice(t,1),null!==this.root.parentNode&&this.root.parentNode.removeChild(this.root);let i=this._onClose;this._onClose=null,null!==i&&i()}setPrimaryAction(e){this._primaryAction=e}get isOpen(){return null!==this.root.parentNode}};Ln._openStack=[];var $n=Ln;function Pn(e,t,i,n){let o=`hw-input-${Math.random().toString(36).slice(2,9)}`,r=wn(e,"label",{for:o,class:"hw-modal__label"},[t]),s=e.createElement("input");return s.setAttribute("id",o),s.setAttribute("type","text"),s.setAttribute("class","hw-modal__input"),void 0!==n&&s.setAttribute("data-testid",n),s.value=i,{row:wn(e,"div",{class:"hw-modal__row"},[r,s]),input:s}}function Rn(e,t,i,n,o){let r=`hw-sel-${Math.random().toString(36).slice(2,9)}`,s=wn(e,"label",{for:r,class:"hw-modal__label"},[t]),a=e.createElement("select");a.setAttribute("id",r),a.setAttribute("class","hw-modal__select"),void 0!==o&&a.setAttribute("data-testid",o);for(let t of i){let i=e.createElement("option");i.setAttribute("value",t.value),t.value===n&&i.setAttribute("selected",""),i.appendChild(e.createTextNode(t.label)),a.appendChild(i)}return{row:wn(e,"div",{class:"hw-modal__row"},[s,a]),select:a}}function Hn(e,t){let i=e.createElement("button");i.setAttribute("class","hw-modal__ok"),i.setAttribute("type","button"),void 0!==t&&i.setAttribute("data-testid",`${t}-ok`),i.appendChild(e.createTextNode("OK"));let n=e.createElement("button");return n.setAttribute("class","hw-modal__cancel"),n.setAttribute("type","button"),void 0!==t&&n.setAttribute("data-testid",`${t}-cancel`),n.appendChild(e.createTextNode("Cancel")),{row:wn(e,"div",{class:"hw-modal__actions"},[i,n]),ok:i,cancel:n}}var Nn=class{constructor(e,t){this._modal=null,this._editor=e;let i=e._getHost();if(null===i)throw new Error("ChooseRDialog: editor has no host element.");this._doc=t?.documentImpl??vn(i)}open(e,t,i){this.close();let n=this._editor._getHost();if(null===n)return Promise.resolve(null);let o=new $n(n,{documentImpl:this._doc,title:"Choose R-Groups",testId:"choose-r"});this._modal=o;let r=Fn(e,i?.freeR1,i?.currentR1,this._editor),s=Fn(t,i?.freeR2,i?.currentR2,this._editor),a=wn(this._doc,"div",{class:"hw-modal__info"},[`${e.symbol} (${e.bio.chainId})`]),l=void 0!==i?.currentR1?String(i.currentR1):r[0]?.value??"1",h=void 0!==i?.currentR2?String(i.currentR2):s[0]?.value??"1",d=Rn(this._doc,"R-group on side A",r,l,"choose-r-r1"),c=wn(this._doc,"div",{class:"hw-modal__info"},[`${t.symbol} (${t.bio.chainId})`]),u=Rn(this._doc,"R-group on side B",s,h,"choose-r-r2"),p=Hn(this._doc,"choose-r"),m=[];return 0===r.length&&m.push(wn(this._doc,"div",{class:"hw-modal__info hw-modal__note-fully-booked"},[`All R-groups on ${e.symbol} are in use.`])),0===s.length&&m.push(wn(this._doc,"div",{class:"hw-modal__info hw-modal__note-fully-booked"},[`All R-groups on ${t.symbol} are in use.`])),new Promise(e=>{let t=!1,i=i=>{t||(t=!0,e(i))},n=e=>{i(e),this.close()},r=()=>n({r1:Dn(d.select),r2:Dn(u.select)});p.ok.addEventListener("click",r),p.cancel.addEventListener("click",()=>n(null)),o.setPrimaryAction(r),o.body.appendChild(a),o.body.appendChild(d.row),o.body.appendChild(c),o.body.appendChild(u.row);for(let e of m)o.body.appendChild(e);o.body.appendChild(p.row),o.open(()=>i(null))})}get isOpen(){return null!==this._modal&&this._modal.isOpen}close(){null!==this._modal&&(this._modal.close(),this._modal=null)}};function Dn(e){let t=e.value;if("string"==typeof t&&t.length>0){let e=Number(t);if(Number.isFinite(e)&&e>=1)return e}let i=e.querySelectorAll("option");for(let e of Array.from(i))if(null!==e.getAttribute("selected")){let t=e.getAttribute("value")??"",i=Number(t);if(Number.isFinite(i)&&i>=1)return i}let n=i[0];if(void 0!==n){let e=n.getAttribute("value")??"",t=Number(e);if(Number.isFinite(t)&&t>=1)return t}return 1}function Fn(e,t,i,n){let o,r=e.monomer?.rgroups;if(void 0===r||0===r.length)return[{value:"1",label:"R1"},{value:"2",label:"R2"},{value:"3",label:"R3"}];if(void 0!==t)o=new Set(t);else if(o=new Set(cn(e,n.getMol().bonds)),0===o.size)for(let e=1;e<=r.length;e++)o.add(e);void 0!==i&&i>=1&&i<=r.length&&o.add(i);let s=[],a=Array.from(o).sort((e,t)=>e-t);for(let e of a){let t=r[e-1];if(void 0===t)continue;let i=void 0!==t.capGroupName&&""!==t.capGroupName?` (${t.capGroupName})`:"";s.push({value:String(e),label:`${t.label}${i}`})}return s}var On="next-add-cursor";function zn(e){null!==e&&(e.style.display="none")}var Gn=class{constructor(e,t,i){this._hoverAtom=null,this._hoverBond=null,this._dragOrigin=null,this._bondStart=null,this._bondDragMoved=!1,this._rectDragHappened=!1,this._chooseRDialog=null,this._panStart=null,this._atomDragState=null,this._panMoved=!1,this._atomDragMoved=!1,this._nextAddCursorEl=null,this._destroyed=!1,this._unsubs=[],this._host=e,this._editor=t,this._enableContextMenu=i?.enableContextMenu??!0,this._tester=new bn(t.getMol(),t._currentTheme()),this._unsubs.push(t.on("mol:changed",()=>{this._tester=new bn(this._editor.getMol(),this._editor._currentTheme()),this._hoverAtom=null,this._hoverBond=null})),this._unsubs.push(t.on("option:change",e=>{("mode"===e.key||"nextAdd"===e.key)&&zn(this._nextAddCursorEl)})),this._onMove=e=>this._handleMove(e),this._onClick=e=>this._handleClick(e),this._onDblClick=e=>this._handleDblClick(e),this._onContextMenu=e=>this._handleContextMenu(e),this._onMouseDown=e=>this._handleMouseDown(e),this._onMouseUp=e=>this._handleMouseUp(e),this._onMouseLeave=e=>this._handleMouseLeave(e),this._onWheel=e=>this._handleWheel(e),e.addEventListener("mousemove",this._onMove),e.addEventListener("click",this._onClick),e.addEventListener("dblclick",this._onDblClick),e.addEventListener("contextmenu",this._onContextMenu),e.addEventListener("mousedown",this._onMouseDown),e.addEventListener("mouseup",this._onMouseUp),e.addEventListener("mouseleave",this._onMouseLeave),e.addEventListener("wheel",this._onWheel,{passive:!1})}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();this._host.removeEventListener("mousemove",this._onMove),this._host.removeEventListener("click",this._onClick),this._host.removeEventListener("dblclick",this._onDblClick),this._host.removeEventListener("contextmenu",this._onContextMenu),this._host.removeEventListener("mousedown",this._onMouseDown),this._host.removeEventListener("mouseup",this._onMouseUp),this._host.removeEventListener("mouseleave",this._onMouseLeave),this._host.removeEventListener("wheel",this._onWheel),null!==this._chooseRDialog&&(this._chooseRDialog.close(),this._chooseRDialog=null),zn(this._nextAddCursorEl),this._nextAddCursorEl=null}}_handleMove(e){if(null!==this._panStart){let t=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),i=t.x-this._panStart.origin.x,n=t.y-this._panStart.origin.y;return this._editor.panTo({x:this._panStart.initialOffset.x+i,y:this._panStart.initialOffset.y+n}),void(this._panMoved=!0)}if(null!==this._atomDragState){let t=this._toModel(e),i=t.x-this._atomDragState.pointerDownModel.x,n=t.y-this._atomDragState.pointerDownModel.y,o=[];for(let e of this._atomDragState.atomIds){let t=this._atomDragState.initialPositions.get(e);void 0!==t&&o.push({atomId:e,p:{x:t.x+i,y:t.y+n}})}return this._editor.moveAtoms(o),void(this._atomDragMoved=!0)}let t=this._toModel(e),i=this._tester.test(t),n=i?.atom??null,o=i?.bond??null;if(null!==this._bondStart){this._bondDragMoved=!0;let e=null!==n&&n.id!==this._bondStart.id?n:null;this._editor.fire("bond:preview",{start:this._bondStart,cursor:t,candidate:e,kind:"hbond"===this._editor.getMode()?"hbond":"backbone"})}if(null!==this._hoverAtom&&(null===n||n.id!==this._hoverAtom.id)&&(this._editor.fire("monomer:hover-end",{atom:this._hoverAtom}),this._hoverAtom=null),null!==n&&(null===this._hoverAtom||this._hoverAtom.id!==n.id)&&(this._hoverAtom=n,this._editor.fire("monomer:hover",{atom:n,clientX:e.clientX,clientY:e.clientY,modelX:t.x,modelY:t.y})),null!==this._hoverBond&&(null===o||o.id!==this._hoverBond.id)&&(this._editor.fire("bond:hover-end",{bond:this._hoverBond}),this._hoverBond=null),null!==o&&(null===this._hoverBond||this._hoverBond.id!==o.id)&&(this._hoverBond=o,this._editor.fire("bond:hover",{bond:o,clientX:e.clientX,clientY:e.clientY})),null!==this._dragOrigin){let e=Wn(this._dragOrigin,t);this._editor.fire("selection:rectangle-update",{rect:e})}this._updateNextAddCursor(e)}_handleClick(e){if(this._bondDragMoved)return void(this._bondDragMoved=!1);if(this._rectDragHappened)return void(this._rectDragHappened=!1);if(this._panMoved)return void(this._panMoved=!1);if(this._atomDragMoved)return void(this._atomDragMoved=!1);let t=this._toModel(e),i=this._tester.test(t),n=Yn(e),o=this._editor.getMode();if("eraser"===o)return void 0!==i?.atom?void this._editor.removeAtom(i.atom):void 0!==i?.bond?void this._editor.removeBond(i.bond):void 0;if(void 0===i?.atom)if(void 0===i?.bond){if(this._addsEnabled()){let e=this._editor.getNextAddSymbol();if(null!==e)return void this._editor.addAtom(t,e.biotype,e.symbol)}!n.shift&&!n.ctrl&&!n.meta&&this._editor.clearSelection()}else this._editor.fire("bond:click",{bond:i.bond,modifiers:n});else{if("select"===o&&!n.ctrl&&!n.shift&&!n.meta){let e=this._editor.getNextAddSymbol();if(null!==e)return i.atom.biotype===e.biotype?void this._editor.replaceMonomer(i.atom,e.symbol):void this._editor.fire("editor:status",{message:`Cannot replace: ${i.atom.biotype} is incompatible with ${e.biotype}`,severity:"warn",durationMs:3e3})}this._editor.fire("monomer:click",{atom:i.atom,modifiers:n,clientX:e.clientX,clientY:e.clientY})}}_handleDblClick(e){let t=this._toModel(e),i=this._tester.test(t),n=Yn(e);void 0===i?.atom?null===i&&this._editor.fitToContent():this._editor.fire("monomer:dblclick",{atom:i.atom,modifiers:n})}_handleContextMenu(e){this._enableContextMenu||e.preventDefault();let t=this._toModel(e),i=this._tester.test(t),n=()=>{e.preventDefault()};void 0!==i?.atom?this._editor.fire("monomer:contextmenu",{atom:i.atom,clientX:e.clientX,clientY:e.clientY,preventDefault:n}):void 0!==i?.bond&&this._editor.fire("bond:contextmenu",{bond:i.bond,clientX:e.clientX,clientY:e.clientY,preventDefault:n})}_handleMouseDown(e){if(0!==e.button)return;let t=this._toModel(e),i=this._tester.test(t),n=this._editor.getMode(),o=!0===e.ctrlKey||!0===e.metaKey,r=!0===e.shiftKey;if(void 0!==i?.atom){if("move"===n||"select"===n&&o){let e=this._editor.getSelection(),n=e.atoms.has(i.atom.id)?Array.from(e.atoms):[i.atom.id],o=this._editor.getMol(),r=new Map;for(let e of n){let t=o.atoms.find(t=>t.id===e);void 0!==t&&r.set(e,{x:t.p.x,y:t.p.y})}return this._atomDragState={atomIds:n,pointerDownModel:{x:t.x,y:t.y},initialPositions:r},void(this._atomDragMoved=!1)}return this._bondStart=i.atom,void(this._bondDragMoved=!1)}if(null===i){if("move"===n||"select"===n&&!r){let t=this._editor.getViewport();return this._panStart={origin:this._toViewBox({clientX:e.clientX,clientY:e.clientY}),initialOffset:{x:t.offset.x,y:t.offset.y}},void(this._panMoved=!1)}"select"===n&&r&&(this._dragOrigin=t,this._editor.fire("selection:rectangle-start",{origin:t}))}}_handleMouseUp(e){if(null!==this._panStart)return void(this._panStart=null);if(null!==this._atomDragState)return void(this._atomDragState=null);if(null!==this._bondStart){let t=this._bondStart,i=this._bondDragMoved;this._bondStart=null;let n=this._toModel(e),o=this._tester.test(n)?.atom;if(i&&void 0!==o&&o.id!==t.id){if(this._editor.fire("bond:preview-end",{start:t}),"hbond"===this._editor.getMode()){try{this._editor.addHydrogenBond(t,o)}catch{this._editor.fire("bond:cancel",{start:t})}return}let e=t.bio.chainId===o.bio.chainId&&Vn(t,o,this._editor.getMol())?"backbone":"cross-polymer",i=qn(t,o,this._editor.getMol().bonds,e);if("fail"===i.mode)return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("editor:status",{message:i.reason,severity:"error",durationMs:3e3});if("auto"===i.mode){try{this._editor.addBond(t,o,i.r1,i.r2,i.kind)}catch{this._editor.fire("bond:cancel",{start:t})}return}return void this._openChooseR(t,o,e,i.freeR1,i.freeR2)}if(i){let e=this._addsEnabled()?this._editor.getNextAddSymbol():null;if(null!==e){let i;try{i=this._editor.addAtom(n,e.biotype,e.symbol)}catch{return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("bond:preview-end",{start:t})}let o=this._editor.getMol().atoms.find(e=>e.id===t.id);if(void 0===o)return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("bond:preview-end",{start:t});let r=o.bio.chainId===i.bio.chainId&&Vn(o,i,this._editor.getMol())?"backbone":"cross-polymer",s=cn(o,this._editor.getMol().bonds),a=cn(i,this._editor.getMol().bonds);if(s.includes(2)&&a.includes(1)){try{this._editor.addBond(o,i,2,1,r)}catch{this._editor.fire("bond:cancel",{start:t})}return void this._editor.fire("bond:preview-end",{start:t})}let l=qn(o,i,this._editor.getMol().bonds,r);if("fail"===l.mode)return this._editor.fire("bond:cancel",{start:t}),this._editor.fire("editor:status",{message:l.reason,severity:"error",durationMs:3e3}),void this._editor.fire("bond:preview-end",{start:t});if("auto"===l.mode){try{this._editor.addBond(o,i,l.r1,l.r2,l.kind)}catch{this._editor.fire("bond:cancel",{start:t})}return void this._editor.fire("bond:preview-end",{start:t})}return this._editor.fire("bond:preview-end",{start:t}),void this._openChooseR(o,i,r,l.freeR1,l.freeR2)}return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("bond:preview-end",{start:t})}return}if(null===this._dragOrigin)return;let t=this._toModel(e),i=Wn(this._dragOrigin,t);this._dragOrigin=null;let n=this._tester.testRect(i),o=hn.fromAtomsAndBonds(n.atoms.map(e=>e.id),n.bonds.map(e=>e.id)),r=hn.union(this._editor.getSelection(),o);this._editor.setSelection(r),this._editor.fire("selection:rectangle-end",{rect:i,selection:r}),this._rectDragHappened=!0,r.atoms.size>0&&"select"===this._editor.getMode()&&this._editor.setMode("move")}_handleMouseLeave(e){null!==this._hoverAtom&&(this._editor.fire("monomer:hover-end",{atom:this._hoverAtom}),this._hoverAtom=null),null!==this._hoverBond&&(this._editor.fire("bond:hover-end",{bond:this._hoverBond}),this._hoverBond=null),null!==this._bondStart&&(this._editor.fire("bond:cancel",{start:this._bondStart}),this._editor.fire("bond:preview-end",{start:this._bondStart}),this._bondStart=null,this._bondDragMoved=!1),this._dragOrigin=null,this._panStart=null,this._atomDragState=null,this._panMoved=!1,this._atomDragMoved=!1,zn(this._nextAddCursorEl)}_openChooseR(e,t,i,n,o){null===this._chooseRDialog&&(this._chooseRDialog=new Nn(this._editor)),this._chooseRDialog.open(e,t,{freeR1:n,freeR2:o}).then(n=>{if(!this._destroyed){if(null===n)return void this._editor.fire("bond:cancel",{start:e});try{this._editor.addBond(e,t,n.r1,n.r2,i)}catch{this._editor.fire("bond:cancel",{start:e})}}})}_updateNextAddCursor(e){let t=this._editor.getNextAddSymbol(),i=this._editor.getMode(),n=null!==this._hoverAtom,o=null!==this._bondStart||null!==this._dragOrigin||null!==this._panStart||null!==this._atomDragState;if("select"!==i||null===t||n||o)return void(null!==this._nextAddCursorEl&&zn(this._nextAddCursorEl));let r=this._host.ownerDocument;if(null===r)return;null===this._nextAddCursorEl&&(this._nextAddCursorEl=function(e){let t="data-testid";for(let i=0;i<e.body.children.length;i++){let n=e.body.children[i];if(void 0!==n&&n.getAttribute(t)===On)return n}let i=e.createElement("div");return i.className="hw-next-add-cursor",i.setAttribute(t,On),i.style.display="none",e.body.appendChild(i),i}(r));let s=this._editor.getService().monomerLib,a=null;for(let e of s.getPolymerTypes()){let i=s.getMonomer(e,t.symbol);if(null!==i){a=i;break}}!function(e,t,i,n,o,r,s){let a=di({p:{x:0,y:0},biotype:i},o),l=Ie(n,i,o.colorTheme).background,h=_e(l),d=t.length,c=d<=1?1:Math.min(1,2/d),u=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="-28 -28 56 56" width="56" height="56" class="hw-next-add-cursor__svg" aria-hidden="true"><path d="${a}" fill="${l}" stroke="${l}" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"/><text x="0" y="0" text-anchor="middle" dominant-baseline="central" font-family="Helvetica Neue, Helvetica, Arial, sans-serif" font-size="${o.fontSize*c}" fill="${h}">${function(e){let t="";for(let i=0;i<e.length;i++){let n=e.charAt(i);t+="<"===n?"<":">"===n?">":"&"===n?"&":n}return t}(t)}</text></svg>`;e.innerHTML=u;let p=e.style;p.left=r-28+"px",p.top=s-28+"px",p.display="block"}(this._nextAddCursorEl,t.symbol,t.biotype,a,this._editor._currentTheme(),e.clientX,e.clientY)}_addsEnabled(){return"select"===this._editor.getMode()}_handleWheel(e){let t=!0===e.ctrlKey||!0===e.metaKey;if(e.preventDefault(),t)return void this._wheelPan(e);let i=e.deltaY<0?1.1:1/1.1,n=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),o=this._editor.getViewport(),r=0===o.scale?n:{x:(n.x-o.offset.x)/o.scale,y:(n.y-o.offset.y)/o.scale};this._editor.zoom(i,r)}_wheelPan(e){let t=e.deltaX??0,i=e.deltaY??0;if(0===t&&0===i)return;let n=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),o=this._toViewBox({clientX:e.clientX+t,clientY:e.clientY+i}),r=o.x-n.x,s=o.y-n.y,a=this._editor.getViewport();this._editor.panTo({x:a.offset.x-r,y:a.offset.y-s})}_toModel(e){let t=this._host.querySelector("svg"),i=null!==t?t.querySelector(".hw-content"):null;if(null!==t&&null!==i){let t=jn(i,e.clientX,e.clientY);if(null!==t)return t;let n=this._host.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,s=function(e){if(""===e)return null;let t,i=0,n=0,o=1,r=/(translate|scale)\(([^)]+)\)/g,s=!1;for(;null!==(t=r.exec(e));){s=!0;let e=t[1],r=(t[2]??"").split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e));"translate"===e?(i+=o*(r[0]??0),n+=o*(r[1]??0)):"scale"===e&&(o*=r[0]??1)}return s?{tx:i,ty:n,scale:o}:null}(i.getAttribute("transform")??"");return null!==s?{x:(o-s.tx)/(0===s.scale?1:s.scale),y:(r-s.ty)/(0===s.scale?1:s.scale)}:{x:o,y:r}}let n=this._host.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}_toViewBox(e){let t=this._host.querySelector("svg");if(null!==t){let i=jn(t,e.clientX,e.clientY);if(null!==i)return i;let n=this._host.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,s=function(e){if(null===e||""===e)return null;let t=e.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e));if(t.length<4)return null;let i=t[2],n=t[3];return i<=0||n<=0?null:{w:i,h:n}}(t.getAttribute("viewBox"));return null!==s&&n.width>0&&n.height>0?{x:o*(s.w/n.width),y:r*(s.h/n.height)}:{x:o,y:r}}let i=this._host.getBoundingClientRect();return{x:e.clientX-i.left,y:e.clientY-i.top}}};function qn(e,t,i,n){let o=dn(e),r=dn(t);if(0===o||0===r)return{mode:"auto",r1:2,r2:1,kind:n};let s=cn(e,i),a=cn(t,i);return 0===s.length?{mode:"fail",reason:`${e.symbol} has no free R-groups (max ${o}).`}:0===a.length?{mode:"fail",reason:`${t.symbol} has no free R-groups (max ${r}).`}:s.includes(2)&&a.includes(1)&&(1===s.length||1===a.length)?{mode:"auto",r1:2,r2:1,kind:n}:1===s.length&&1===a.length?{mode:"auto",r1:s[0],r2:a[0],kind:n}:{mode:"choose",freeR1:s,freeR2:a}}function jn(e,t,i){let n=e;if("function"!=typeof n.getScreenCTM)return null;let o=n.getScreenCTM();if(null===o)return null;let r=null;try{let e=o;"function"==typeof e.inverse&&(r=e.inverse())}catch{return null}if(null===r)return null;let s=n.ownerSVGElement;if(null!=s&&"function"==typeof s.createSVGPoint){let e=s.createSVGPoint();e.x=t,e.y=i;let n=e.matrixTransform(r);return{x:n.x,y:n.y}}let a=r;return{x:a.a*t+a.c*i+a.e,y:a.b*t+a.d*i+a.f}}function Vn(e,t,i){if(e.bio.chainId!==t.bio.chainId)return!1;let n=i.chains.find(t=>t.id===e.bio.chainId);if(void 0===n)return!1;let o=-1,r=-1;for(let i=0;i<n.backboneAtoms.length;i++){let s=n.backboneAtoms[i];s.id===e.id&&(o=i),s.id===t.id&&(r=i)}return!(o<0||r<0)&&1===Math.abs(o-r)}function Yn(e){return{shift:!0===e.shiftKey,alt:!0===e.altKey,ctrl:!0===e.ctrlKey,meta:!0===e.metaKey}}function Wn(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)}}var Un=class{constructor(e,t,i){this._destroyed=!1,this._host=e,this._editor=t,this._enabled=!1!==i?.enableKeyboard,this._enabled&&null===e.getAttribute("tabindex")&&e.setAttribute("tabindex","0"),this._onKey=e=>this._handleKey(e),e.addEventListener("keydown",this._onKey)}destroy(){this._destroyed||(this._destroyed=!0,this._host.removeEventListener("keydown",this._onKey))}_handleKey(e){if(!this._enabled)return;let t=this._classify(e),i={shift:!0===(n=e).shiftKey,alt:!0===n.altKey,ctrl:!0===n.ctrlKey,meta:!0===n.metaKey};var n;if(null===t)return void this._editor.fire("key:unhandled",{key:e.key,modifiers:i,preventDefault:()=>e.preventDefault()});let o=!1;this._editor.fire("key:command",{command:t,preventDefault:()=>{o=!0,e.preventDefault()}}),!o&&(e.preventDefault(),"clearSelection"!==t&&(e.stopPropagation(),e.stopImmediatePropagation?.()),this._execute(t))}_classify(e){let t=e.key,i=e.ctrlKey||e.metaKey;return"Delete"===t||"Backspace"===t?"delete":!i||"z"!==t&&"Z"!==t||e.shiftKey?i&&(("z"===t||"Z"===t)&&e.shiftKey||"y"===t||"Y"===t)?"redo":!i||"a"!==t&&"A"!==t?!i||"c"!==t&&"C"!==t?!i||"v"!==t&&"V"!==t?!i||"x"!==t&&"X"!==t?"Escape"===t?"clearSelection":"+"===t||"="===t?"zoomIn":"-"===t||"_"===t?"zoomOut":"0"===t?"fitToContent":"ArrowUp"===t?"nudgeUp":"ArrowDown"===t?"nudgeDown":"ArrowLeft"===t?"nudgeLeft":"ArrowRight"===t?"nudgeRight":null:"cut":"paste":"copy":"selectAll":"undo"}_execute(e){switch(e){case"delete":return void this._editor.deleteSelection();case"undo":return void this._editor.undo();case"redo":return void this._editor.redo();case"selectAll":return void this._editor.selectAll();case"clearSelection":return void this._editor.clearSelection();case"zoomIn":return void this._editor.zoom(1.1);case"zoomOut":return void this._editor.zoom(1/1.1);case"fitToContent":return void this._editor.fitToContent();case"nudgeUp":return void this._editor.nudgeSelection(0,-5);case"nudgeDown":return void this._editor.nudgeSelection(0,5);case"nudgeLeft":return void this._editor.nudgeSelection(-5,0);case"nudgeRight":return void this._editor.nudgeSelection(5,0);case"copy":{let e=this._editor.getHelm();return void this._editor.fire("clipboard:copy",{format:"helm",payload:e})}case"cut":{let e=this._editor.getHelm();return this._editor.fire("clipboard:copy",{format:"helm",payload:e}),void this._editor.deleteSelection()}case"paste":return void this._editor.fire("clipboard:paste",{format:"helm"});default:return}}},Kn=class{constructor(e,t){this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._destroyed=!1,this._unsubs=[],this._host=e,this._editor=t,this._tester=new bn(t.getMol(),t._currentTheme()),this._unsubs.push(t.on("mol:changed",()=>{this._tester=new bn(this._editor.getMol(),this._editor._currentTheme())})),this._onDragOver=e=>this._handleDragOver(e),this._onDrop=e=>this._handleDrop(e),this._onDragStart=e=>this._handleDragStart(e),this._onDragEnd=e=>this._handleDragEnd(e),this._onDragEnter=e=>this._handleDragEnter(e),this._onDragLeave=e=>this._handleDragLeave(e),e.addEventListener("dragover",this._onDragOver),e.addEventListener("drop",this._onDrop),e.addEventListener("dragstart",this._onDragStart),e.addEventListener("dragend",this._onDragEnd),e.addEventListener("dragenter",this._onDragEnter),e.addEventListener("dragleave",this._onDragLeave)}startPaletteDrag(e,t){this._currentPaletteSymbol=e,this._currentPaletteBiotype=t,this._editor.fire("dnd:start",{source:"palette",symbol:e})}cancelPaletteDrag(){null!==this._currentPaletteSymbol&&(this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._editor.fire("dnd:cancel",{source:"palette"}))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();this._host.removeEventListener("dragover",this._onDragOver),this._host.removeEventListener("drop",this._onDrop),this._host.removeEventListener("dragstart",this._onDragStart),this._host.removeEventListener("dragend",this._onDragEnd),this._host.removeEventListener("dragenter",this._onDragEnter),this._host.removeEventListener("dragleave",this._onDragLeave)}}_activePaletteSymbol(e){if(null!==this._currentPaletteSymbol&&null!==this._currentPaletteBiotype)return{symbol:this._currentPaletteSymbol,biotype:this._currentPaletteBiotype};let t=e.dataTransfer;if(null==t)return null;try{let e="function"==typeof t.getData?t.getData("application/x-hwe-monomer"):"";if(""===e)return null;let i=JSON.parse(e);return"string"!=typeof i.symbol||"string"!=typeof i.biotype?null:{symbol:i.symbol,biotype:i.biotype}}catch{return null}}_handleDragEnter(e){if(null!==this._activePaletteSymbol(e)&&(e.preventDefault(),null!==e.dataTransfer&&void 0!==e.dataTransfer))try{e.dataTransfer.dropEffect="copy"}catch{}}_handleDragLeave(e){}_handleDragOver(e){if(null===this._activePaletteSymbol(e))return;if(e.preventDefault(),null!==e.dataTransfer&&void 0!==e.dataTransfer)try{e.dataTransfer.dropEffect="copy"}catch{}let t=this._toModel(e),i=this._tester.test(t),n=void 0!==i?.atom?i.atom:void 0!==i?.bond?i.bond:void 0,o={clientX:e.clientX,clientY:e.clientY};void 0!==n&&(o.target=n),this._editor.fire("dnd:over",o)}_handleDrop(e){let t=this._activePaletteSymbol(e);if(null===t)return;e.preventDefault();let{symbol:i,biotype:n}=t,o=this._toModel(e),r=this._tester.test(o),s=void 0!==r?.atom?r.atom:void 0!==r?.bond?r.bond:void 0,a={symbol:i,biotype:n,clientX:e.clientX,clientY:e.clientY};void 0!==s&&(a.target=s),this._editor.fire("dnd:drop",a),void 0!==r?.atom?this._editor.replaceMonomer(r.atom,i):this._editor.addAtom(o,n,i),this._currentPaletteSymbol=null,this._currentPaletteBiotype=null}_handleDragStart(e){this._editor.fire("dnd:start",{source:"canvas"})}_handleDragEnd(e){null!==this._currentPaletteSymbol&&(this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._editor.fire("dnd:cancel",{source:"palette"}))}_toModel(e){let t=this._host.querySelector("svg"),i=null!==t?t.querySelector(".hw-content"):null;if(null!==t&&null!==i){let t=function(e,t,i){let n=e;if("function"!=typeof n.getScreenCTM)return null;let o=n.getScreenCTM();if(null===o)return null;let r=null;try{let e=o;"function"==typeof e.inverse&&(r=e.inverse())}catch{return null}if(null===r)return null;let s=n.ownerSVGElement;if(null!=s&&"function"==typeof s.createSVGPoint){let e=s.createSVGPoint();e.x=t,e.y=i;let n=e.matrixTransform(r);return{x:n.x,y:n.y}}let a=r;return{x:a.a*t+a.c*i+a.e,y:a.b*t+a.d*i+a.f}}(i,e.clientX,e.clientY);if(null!==t)return t;let n=this._host.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,s=function(e){if(""===e)return null;let t,i=0,n=0,o=1,r=/(translate|scale)\(([^)]+)\)/g,s=!1;for(;null!==(t=r.exec(e));){s=!0;let e=t[1],r=(t[2]??"").split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e));"translate"===e?(i+=o*(r[0]??0),n+=o*(r[1]??0)):"scale"===e&&(o*=r[0]??1)}return s?{tx:i,ty:n,scale:o}:null}(i.getAttribute("transform")??"");return null!==s?{x:(o-s.tx)/(0===s.scale?1:s.scale),y:(r-s.ty)/(0===s.scale?1:s.scale)}:{x:o,y:r}}let n=this._host.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}},Xn=class{constructor(e,t){this._modal=null,this._atom=null,this._editor=e;let i=e._getHost();if(null===i)throw new Error("AtomPropsDialog: editor has no host element.");this._doc=t?.documentImpl??vn(i)}get isOpen(){return null!==this._modal&&this._modal.isOpen}open(e){this.close(),this._atom=e;let t=this._editor._getHost();if(null===t)return;let i=new $n(t,{documentImpl:this._doc,title:"Monomer Properties",testId:"atom-props"});this._modal=i;let n=wn(this._doc,"div",{class:"hw-modal__info"},[`Position ${e.bio.continuousId} in ${e.bio.chainId}`]),o=Pn(this._doc,"Symbol",e.symbol,"atom-props-symbol"),r=Pn(this._doc,"Annotation",e.bio.annotation??"","atom-props-annotation"),s=Hn(this._doc,"atom-props"),a=()=>this._commit(o.input.value,r.input.value);s.ok.addEventListener("click",a),s.cancel.addEventListener("click",()=>this.close()),i.setPrimaryAction(a),i.body.appendChild(n),i.body.appendChild(o.row),i.body.appendChild(r.row),i.body.appendChild(s.row),i.open()}close(){null!==this._modal&&(this._modal.close(),this._modal=null),this._atom=null}_commit(e,t){let i=this._atom;if(null===i)return void this.close();let n=e.trim(),o=(i.bio.annotation??"")!==t;if(n.length>0&&n!==i.symbol&&this._editor.replaceMonomer(i,n),o){let e=new mn(this._editor.getMol()),n={};n.tag=""===t?void 0:t,e.updateAtom(i.id,n);let{mol:o}=e.commit();this._editor.setMol(o);let r=o.atoms.find(e=>e.id===i.id);if(void 0!==r){let e={atom:r};void 0!==i.bio.annotation&&(e.oldAnnotation=i.bio.annotation),""!==t&&(e.newAnnotation=t),this._editor.fire("monomer:annotate",e)}}this.close()}},Qn=class{constructor(e,t){this._modal=null,this._bond=null,this._editor=e;let i=e._getHost();if(null===i)throw new Error("BondPropsDialog: editor has no host element.");this._doc=t?.documentImpl??vn(i)}get isOpen(){return null!==this._modal&&this._modal.isOpen}open(e){this.close(),this._bond=e;let t=this._editor._getHost();if(null===t)return;let i=new $n(t,{documentImpl:this._doc,title:"Bond Properties",testId:"bond-props"});this._modal=i;let n=wn(this._doc,"div",{class:"hw-modal__info"},[`Kind: ${e.kind}`]),o=this._buildAtomsPreviewRow(e),r="numeric"===e.r1.kind,s="numeric"===e.r2.kind,a=r&&s,l=this._editor.getMol().bonds,h=a?Zn(e.r1,e.a1,l):[],d=a?Zn(e.r2,e.a2,l):[],c=null,u=null;if(a){let t=String(e.r1.r),i=String(e.r2.r);c=Rn(this._doc,`R-group on ${e.a1.symbol} (${e.a1.bio.chainId}:${e.a1.bio.positionInChain})`,h,t,"bond-props-r1"),u=Rn(this._doc,`R-group on ${e.a2.symbol} (${e.a2.bio.chainId}:${e.a2.bio.positionInChain})`,d,i,"bond-props-r2")}let p=Hn(this._doc,"bond-props"),m=()=>{let t=null!==c?Number(Jn(c.select,e.r1.r)):null,i=null!==u?Number(Jn(u.select,e.r2.r)):null;this._commit(t,i)};p.ok.addEventListener("click",m),p.cancel.addEventListener("click",()=>this.close()),i.setPrimaryAction(m),i.body.appendChild(n),null!==o&&i.body.appendChild(o),null!==c&&i.body.appendChild(c.row),null!==u&&i.body.appendChild(u.row),i.body.appendChild(p.row),i.open()}_buildAtomsPreviewRow(e){let t=this._rdkit(),i=this._buildAtomCell(e.a1,t,"bond-props-atom-a1"),n=this._buildAtomCell(e.a2,t,"bond-props-atom-a2"),o=wn(this._doc,"div",{class:"hw-bond-props__bond-arrow"},["↔"]);return wn(this._doc,"div",{class:"hw-bond-props__atoms","data-testid":"bond-props-atoms"},[i,o,n])}_buildAtomCell(e,t,i){let n=e.monomer?.name??e.symbol,o=e.symbol===n?e.symbol:`${e.symbol} — ${n}`,r=wn(this._doc,"div",{class:"hw-bond-props__atom-label"},[o]),s={class:"hw-bond-props__atom-rdkit","data-testid":`${i}-rdkit`},a=wn(this._doc,"div",s),l=e.monomer?.smiles;if(null!==t&&void 0!==l&&""!==l){let e=xn(t,l,220,140);null!==e&&""!==e&&(a.innerHTML=e)}return wn(this._doc,"div",{class:"hw-bond-props__atom","data-testid":i},[r,a])}_rdkit(){let e=this._editor.getService().options?.rdkitModule;return e??null}close(){null!==this._modal&&(this._modal.close(),this._modal=null),this._bond=null}_commit(e,t){let i=this._bond;if(null===i)return void this.close();let n="numeric"===i.r1.kind?i.r1.r:null,o="numeric"===i.r2.kind?i.r2.r:null;if(null===e||null===t||e===n&&t===o)this.close();else{if(null!==e&&null!==t){let r=i.kind,s=i.a1,a=i.a2;this._editor.removeBond(i);try{this._editor.addBond(s,a,e,t,r)}catch(e){if(null!==n&&null!==o)try{this._editor.addBond(s,a,n,o,i.kind)}catch{}}}this.close()}}};function Zn(e,t,i){let n=t.monomer?.rgroups;if(void 0===n||0===n.length)return[{value:"1",label:"R1"},{value:"2",label:"R2"},{value:"3",label:"R3"}];let o=new Set(cn(t,i));o.add(e.r);let r=Array.from(o).sort((e,t)=>e-t),s=[];for(let e of r){let t=n[e-1];if(void 0===t)continue;let i=void 0!==t.capGroupName&&""!==t.capGroupName?` (${t.capGroupName})`:"";s.push({value:String(e),label:`${t.label}${i}`})}return s}function Jn(e,t){let i=e.value;if("string"==typeof i&&i.length>0){let e=Number(i);if(Number.isFinite(e)&&e>=1)return e}let n=e.querySelectorAll("option");for(let e of Array.from(n))if(null!==e.getAttribute("selected")){let t=e.getAttribute("value")??"",i=Number(t);if(Number.isFinite(i)&&i>=1)return i}return t}var eo=class{constructor(e,t){this._modal=null,this._result=null,this._findInput=null,this._replaceInput=null,this._matches=[],this._cursor=-1,this._editor=e;let i=e._getHost();if(null===i)throw new Error("FindReplaceDialog: editor has no host element.");this._doc=t?.documentImpl??vn(i)}get isOpen(){return null!==this._modal&&this._modal.isOpen}open(){this.close();let e=this._editor._getHost();if(null===e)return;let t=new $n(e,{documentImpl:this._doc,title:"Find / Replace",testId:"find-replace"});this._modal=t;let i=Pn(this._doc,"Find","","find-replace-find"),n=Pn(this._doc,"Replace with","","find-replace-replace");this._findInput=i.input,this._replaceInput=n.input;let o=this._doc.createElement("button");o.setAttribute("class","hw-modal__find-next"),o.setAttribute("type","button"),o.setAttribute("data-testid","find-replace-next"),o.appendChild(this._doc.createTextNode("Find Next")),o.addEventListener("click",()=>this._findNext());let r=this._doc.createElement("button");r.setAttribute("class","hw-modal__replace"),r.setAttribute("type","button"),r.setAttribute("data-testid","find-replace-replace-one"),r.appendChild(this._doc.createTextNode("Replace")),r.addEventListener("click",()=>this._replaceOne());let s=this._doc.createElement("button");s.setAttribute("class","hw-modal__replace-all"),s.setAttribute("type","button"),s.setAttribute("data-testid","find-replace-replace-all"),s.appendChild(this._doc.createTextNode("Replace All")),s.addEventListener("click",()=>this._replaceAll());let a=this._doc.createElement("button");a.setAttribute("class","hw-modal__cancel"),a.setAttribute("type","button"),a.setAttribute("data-testid","find-replace-close"),a.appendChild(this._doc.createTextNode("Close")),a.addEventListener("click",()=>this.close());let l=wn(this._doc,"div",{class:"hw-modal__actions"},[o,r,s,a]),h=wn(this._doc,"div",{class:"hw-modal__result","data-testid":"find-replace-result"},["0 matches"]);this._result=h,t.setPrimaryAction(()=>this._findNext()),t.body.appendChild(i.row),t.body.appendChild(n.row),t.body.appendChild(l),t.body.appendChild(h),t.open()}close(){null!==this._modal&&(this._modal.close(),this._modal=null),this._result=null,this._findInput=null,this._replaceInput=null,this._matches=[],this._cursor=-1}_findNext(){let e=this._findInput?.value.trim()??"";if(""===e)return void this._setResultText("Enter a symbol to find");let t=this._editor.findMonomers(e);if(this._matches=t.map(e=>e.id),0===this._matches.length)return this._cursor=-1,this._editor.setHighlights([]),void this._setResultText("No matches");this._cursor=(this._cursor+1)%this._matches.length;let i=this._matches[this._cursor];void 0!==i&&this._editor.setHighlights([i]),this._setResultText(`${this._cursor+1} / ${this._matches.length} matches`)}_replaceOne(){let e=this._findInput?.value.trim()??"",t=this._replaceInput?.value.trim()??"";if(""===e||""===t)return void this._setResultText("Both Find and Replace fields are required");if(0===this._matches.length||this._cursor<0)return void this._findNext();let i=this._matches[this._cursor];if(void 0===i)return;let n=this._editor.getMol().atoms.find(e=>e.id===i);if(void 0!==n)if(this._editor.replaceMonomer(n,t),this._matches.splice(this._cursor,1),0===this._matches.length)this._cursor=-1,this._editor.setHighlights([]),this._setResultText("Replaced; no further matches");else{this._cursor=this._cursor%this._matches.length;let e=this._matches[this._cursor];void 0!==e&&this._editor.setHighlights([e]),this._setResultText(`${this._matches.length} matches remaining`)}}_replaceAll(){let e=this._findInput?.value.trim()??"",t=this._replaceInput?.value.trim()??"";if(""===e||""===t)return void this._setResultText("Both Find and Replace fields are required");let i=this._editor.replaceMonomers(e,t);this._matches=[],this._cursor=-1,this._editor.setHighlights([]),this._setResultText(`${i} replacement${1===i?"":"s"} made`)}_setResultText(e){if(null!==this._result){for(;null!==this._result.firstChild;)this._result.removeChild(this._result.firstChild);this._result.appendChild(this._doc.createTextNode(e))}}},to=Object.freeze(new Set),io=class{constructor(e,t){if(this._events=new _n,this._destroyed=!1,this._view=null,this._pointer=null,this._keyboard=null,this._dnd=null,this._atomDialog=null,this._bondDialog=null,this._findReplaceDialog=null,this._viewBootstrapped=!1,this._mode="select",this._nextAdd=null,this._lastAction=null,this._lastTripletSugarPos=null,void 0===t.service||null===t.service)throw new TypeError("HelmEditor: options.service is required");this._host=e,this._service=t.service,this._options=Object.freeze({...t}),this._mol=Y(),this._selection=hn.empty(),this._highlights=to,this._theme=t.service.theme??si,this._viewport={scale:1,offset:{x:0,y:0}},this._viewOnly=t.viewOnly??!1,this._history=new yn({maxEntries:100}),this._history.push({mol:this._mol,label:"initial"}),this._libUnsub=this._service.monomerLib.onChanged.subscribe(e=>{let t=this._service.monomerLib,i="number"==typeof t.version?t.version:0,n="reload"===e.type?"replace":"update";this._events.fire("monomer-lib:change",{source:this._service.monomerLib.source,version:i,reason:n})}),void 0!==t.initialHelm&&this.setHelm(t.initialHelm),this._bootstrapWaveB()}_bootstrapWaveB(){if(this._viewBootstrapped||null===this._host)return;let e=this._resolveDocument(this._host);if(null===e)return;this._viewBootstrapped=!0;let t={documentImpl:e};void 0!==this._options.width&&(t.width=this._options.width),void 0!==this._options.height&&(t.height=this._options.height),this._view=new Tn(this._host,this,t),!0!==this._viewOnly&&(this._pointer=new Gn(this._host,this,{enableContextMenu:this._options.enableContextMenu??!0})),!1!==this._options.enableKeyboard&&(this._keyboard=new Un(this._host,this,{enableKeyboard:!0})),!1!==this._options.enableDragDrop&&(this._dnd=new Kn(this._host,this)),this._events.on("monomer:hover",e=>{this.setHighlights([e.atom.id])}),this._events.on("monomer:hover-end",()=>{this.clearHighlights()}),this._events.on("monomer:click",e=>{let t=e.modifiers;!0!==t.ctrl&&!0!==t.meta?!0!==t.shift?this.setSelection(hn.fromAtoms([e.atom.id])):this.setSelection(hn.union(this._selection,hn.fromAtoms([e.atom.id]))):this.setSelection(hn.toggle(this._selection,{kind:"atom",id:e.atom.id}))})}_resolveDocument(e){let t=e.ownerDocument;if(null!=t)return t;let i=globalThis;return void 0!==i.document?i.document:null}destroy(){this._destroyed||(this._destroyed=!0,null!==this._atomDialog&&(this._atomDialog.close(),this._atomDialog=null),null!==this._bondDialog&&(this._bondDialog.close(),this._bondDialog=null),null!==this._findReplaceDialog&&(this._findReplaceDialog.close(),this._findReplaceDialog=null),null!==this._dnd&&(this._dnd.destroy(),this._dnd=null),null!==this._keyboard&&(this._keyboard.destroy(),this._keyboard=null),null!==this._pointer&&(this._pointer.destroy(),this._pointer=null),null!==this._view&&(this._view.destroy(),this._view=null),this._libUnsub(),this._events.clear(),this._history.clear())}resize(e,t){this._ensureLive(),null!==this._view&&this._view.resize(e,t),this._events.fire("view:resize",{width:e,height:t})}redraw(){this._ensureLive(),null===this._view?this._events.fire("render:skip",{reason:"no-view-mounted"}):this._view.redraw()}setHelm(e,t){this._ensureLive();let i=t?.canonicalize??this._options.canonicalize??!1,n=this._service.parse(e,{mode:"lenient"}),o=n.diagnostics;o.filter(e=>"error"===e.severity).length>0&&this._events.fire("helm:parse-error",{helm:e,diagnostics:o});for(let e of o)"error"===e.severity?this._events.fire("validation:error",{diagnostic:e}):"warning"===e.severity&&this._events.fire("validation:warning",{diagnostic:e});let r=n.mol;if(i){let t=this._service.canonicalize(e);r=this._service.parse(t,{mode:"lenient"}).mol}let s=Ut(r,void 0!==this._options.bondLength?{bondLength:this._options.bondLength}:void 0);return this._replaceMol(s,"setHelm","api"),{mol:s,diagnostics:o}}getHelm(e){this._ensureLive();let t={};return void 0!==e?.canonicalize&&(t.canonicalize=e.canonicalize),void 0!==e?.includeHighlights&&(t.includeHighlights=e.includeHighlights),this._service.serialize(this._mol,t)}setMol(e){this._ensureLive(),this._replaceMol(e,"setMol","api")}getMol(){return this._mol}getService(){return this._service}getSelection(){return this._selection}setSelection(e){if(this._ensureLive(),hn.equals(this._selection,e))return;let t=hn.difference(e,this._selection),i=hn.difference(this._selection,e);this._selection=e,this._events.fire("selection:change",{selection:e,addedAtomIds:t.atoms,removedAtomIds:i.atoms,addedBondIds:t.bonds,removedBondIds:i.bonds})}selectAll(){this._ensureLive();let e=this._mol.atoms.map(e=>e.id),t=this._mol.bonds.map(e=>e.id);this.setSelection(hn.fromAtomsAndBonds(e,t))}clearSelection(){this._ensureLive(),!this._selection.isEmpty&&this.setSelection(hn.empty())}setHighlights(e){this._ensureLive();let t=new Set(e);this._highlights=t,this._events.fire("highlight:change",{atomIds:t,bondIds:to})}clearHighlights(){this._ensureLive(),0!==this._highlights.size&&(this._highlights=to,this._events.fire("highlight:change",{atomIds:to,bondIds:to}))}addAtom(e,t,i){this._ensureLive();let n=new mn(this._mol),o=n.addAtom({p:e,biotype:t,symbol:i}),{mol:r}=n.commit(),s=Pe(r,this._service.monomerLib,{mode:"lenient"}).mol;this._replaceMol(s,`addAtom:${i}`,"api");let a=W(s,o);if(void 0===a)throw new Error("HelmEditor.addAtom: lost atom after commit");return this._events.fire("monomer:add",{atom:a,source:"api"}),a}removeAtom(e){this._ensureLive();let t="number"==typeof e?e:e.id,i=W(this._mol,t);if(void 0===i)return;let n=new mn(this._mol);n.removeAtom(t);let{mol:o}=n.commit();this._replaceMol(o,`removeAtom:${i.symbol}`,"api"),this._events.fire("monomer:remove",{atom:i,source:"api"})}addBond(e,t,i,n,o){let r,s;this._ensureLive();try{this._validateAddBondConstraints(e,t,i,n);let a=o??"backbone",l=this._maybeMergeForLinearExtend(e,t,i,n,a);if(null!==l)({id:r,mol:s}=l);else{let a=new mn(this._mol);r=a.addBond({a1:e.id,a2:t.id,kind:o??"backbone",r1:{kind:"numeric",r:i},r2:{kind:"numeric",r:n}}),({mol:s}=a.commit())}}catch(o){let r=o instanceof P?o.message:this._friendlyBondError(o instanceof Error?o.message:String(o),e,t,i,n);throw this._events.fire("editor:status",{message:`Could not add bond: ${r}`,severity:"error",durationMs:3e3}),o}this._replaceMol(s,"addBond","api");let a=U(s,r);if(void 0===a)throw new Error("HelmEditor.addBond: lost bond after commit");return this._events.fire("bond:add",{bond:a,source:"api"}),a}_maybeMergeForLinearExtend(e,t,i,n,o){if(e.bio.chainId===t.bio.chainId||"backbone"!==o&&"cross-polymer"!==o)return null;let r=this._mol.chains.find(t=>t.id===e.bio.chainId),s=this._mol.chains.find(e=>e.id===t.bio.chainId);if(void 0===r||void 0===s||r.polymerType!==s.polymerType||r.polymerType===ne.CHEM||r.polymerType===ne.BLOB)return null;if(2===i&&1===n){let i=r.backboneAtoms[r.backboneAtoms.length-1],n=s.backboneAtoms[0];if(void 0!==i&&void 0!==n&&i.id===e.id&&n.id===t.id)return this._mergeChains(r,s,o)}if(1===i&&2===n){let i=r.backboneAtoms[0],n=s.backboneAtoms[s.backboneAtoms.length-1];if(void 0!==i&&void 0!==n&&i.id===e.id&&n.id===t.id)return this._mergeChains(s,r,o)}return null}_mergeChains(e,t,i){let n=e.backboneAtoms.length,o=new Set;for(let e of t.backboneAtoms)o.add(e.id),void 0!==e.branchAtom&&o.add(e.branchAtom.id);let r=new Map,s=n;for(let i of t.backboneAtoms){s+=1;let t={...i,bio:{...i.bio,chainId:e.id,positionInChain:s}};if(r.set(i.id,t),void 0!==i.branchAtom){let t=i.branchAtom,n={...t,bio:{...t.bio,chainId:e.id,positionInChain:s}};r.set(t.id,n)}}for(let e of t.backboneAtoms){let t=r.get(e.id);if(void 0===t||void 0===e.branchAtom)continue;let i=r.get(e.branchAtom.id);void 0!==i&&(t.branchAtom=i)}for(let e of this._mol.atoms)r.has(e.id)||r.set(e.id,e);let a=0;for(let e of this._mol.atoms)e.id>a&&(a=e.id);for(let e of this._mol.bonds)e.id>a&&(a=e.id);let l=a+1,h={id:l,a1:r.get(e.backboneAtoms[e.backboneAtoms.length-1].id),a2:r.get(t.backboneAtoms[0].id),kind:"backbone",r1:{kind:"numeric",r:2},r2:{kind:"numeric",r:1}},d=[];for(let e of this._mol.bonds){let t=r.get(e.a1.id)??e.a1,i=r.get(e.a2.id)??e.a2;t===e.a1&&i===e.a2?d.push(e):d.push({...e,a1:t,a2:i})}d.push(h);let c=[],u=[...e.backboneAtoms];for(let e of t.backboneAtoms)u.push(r.get(e.id));for(let i of this._mol.chains)if(i.id!==t.id)if(i.id===e.id){let e=i.bonds.map(e=>{let t=r.get(e.a1.id)??e.a1,i=r.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}});for(let i of t.bonds){let t=r.get(i.a1.id)??i.a1,n=r.get(i.a2.id)??i.a2;e.push(t===i.a1&&n===i.a2?i:{...i,a1:t,a2:n})}e.push(h),c.push({id:i.id,polymerType:i.polymerType,backboneAtoms:u,bonds:e,...void 0!==i.annotation?{annotation:i.annotation}:{}})}else{let e=i.backboneAtoms.map(e=>r.get(e.id)??e),t=i.bonds.map(e=>{let t=r.get(e.a1.id)??e.a1,i=r.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}});c.push({id:i.id,polymerType:i.polymerType,backboneAtoms:e,bonds:t,...void 0!==i.annotation?{annotation:i.annotation}:{}})}let p={atoms:this._mol.atoms.map(e=>r.get(e.id)??e),bonds:d,chains:c,groups:this._mol.groups,annotations:this._mol.annotations};return p=this._refreshContinuousIdsLocal(p),{id:l,mol:p}}_refreshContinuousIdsLocal(e){let t=re(e),i=new Map;for(let n of e.atoms){let e=t.get(n.id);void 0!==e&&e!==n.bio.continuousId?i.set(n.id,{...n,bio:{...n.bio,continuousId:e}}):i.set(n.id,n)}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=i.get(t.id),n=i.get(t.branchAtom.id);void 0===e||void 0===n||(e.branchAtom=n)}let n=e.bonds.map(e=>{let t=i.get(e.a1.id)??e.a1,n=i.get(e.a2.id)??e.a2;return t===e.a1&&n===e.a2?e:{...e,a1:t,a2:n}}),o=new Map;for(let e of n)o.set(e.id,e);let r=e.chains.map(e=>{let t=e.backboneAtoms.map(e=>i.get(e.id)??e),n=e.bonds.map(e=>o.get(e.id)??e);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>i.get(e.id)??e),bonds:n,chains:r,groups:e.groups,annotations:e.annotations}}_friendlyBondError(e,t,i,n,o){return e.includes("duplicate bond")?`bond ${t.symbol}:R${n} ↔ ${i.symbol}:R${o} already exists`:e.includes("does not exist")?"one of the endpoint atoms is missing":e}_validateAddBondConstraints(e,t,i,n){let o=this._mol.bonds,r=dn(e);if(r>0&&(i<1||i>r))throw new P("rgroup-not-on-monomer",`R-group R${i} is not defined on monomer '${e.symbol}' (has R1..R${r})`,{atomId:e.id,requested:i,total:r});let s=dn(t);if(s>0&&(n<1||n>s))throw new P("rgroup-not-on-monomer",`R-group R${n} is not defined on monomer '${t.symbol}' (has R1..R${s})`,{atomId:t.id,requested:n,total:s});if(r>0){let t=un(e,o).find(e=>e.rNumber===i);if(void 0!==t){let n="r1"===t.side?t.bond.a2:t.bond.a1;throw new P("rgroup-already-bonded",`R-group R${i} on '${e.symbol}' is already bonded to '${n.symbol}' (${n.bio.chainId}:${n.bio.positionInChain})`,{atomId:e.id,requested:i,conflictingBondId:t.bond.id})}}if(s>0){let e=un(t,o).find(e=>e.rNumber===n);if(void 0!==e){let i="r1"===e.side?e.bond.a2:e.bond.a1;throw new P("rgroup-already-bonded",`R-group R${n} on '${t.symbol}' is already bonded to '${i.symbol}' (${i.bio.chainId}:${i.bio.positionInChain})`,{atomId:t.id,requested:n,conflictingBondId:e.bond.id})}}for(let r of o){if("numeric"!==r.r1.kind||"numeric"!==r.r2.kind)continue;let o=r.a1.id===e.id&&r.a2.id===t.id&&r.r1.r===i&&r.r2.r===n,s=r.a1.id===t.id&&r.a2.id===e.id&&r.r1.r===n&&r.r2.r===i;if(o||s)throw new P("duplicate-bond",`bond ${e.symbol}:R${i} ↔ ${t.symbol}:R${n} already exists`,{atomId:e.id,bondId:r.id})}}_freeRgroupsOn(e){return cn(e,this._mol.bonds)}addHydrogenBond(e,t){this._ensureLive();let i=new mn(this._mol),n={kind:"pair"},o=i.addBond({a1:e.id,a2:t.id,kind:"hbond",r1:n,r2:n}),{mol:r}=i.commit();this._replaceMol(r,"addHydrogenBond","api");let s=U(r,o);if(void 0===s)throw new Error("HelmEditor.addHydrogenBond: lost bond after commit");return this._events.fire("bond:add",{bond:s,source:"api"}),s}removeBond(e){this._ensureLive();let t="number"==typeof e?e:e.id,i=U(this._mol,t);if(void 0===i)return;let n=new mn(this._mol);n.removeBond(t);let{mol:o}=n.commit();this._replaceMol(o,"removeBond","api"),this._events.fire("bond:remove",{bond:i,source:"api"})}replaceMonomer(e,t){this._ensureLive();let i=W(this._mol,e.id);if(void 0===i)return;let n=i.symbol;if(n===t)return;let o=new mn(this._mol);o.updateAtom(e.id,{symbol:t});let{mol:r}=o.commit(),s=Pe(r,this._service.monomerLib,{mode:"lenient"}).mol;this._replaceMol(s,`replaceMonomer:${n}->${t}`,"api");let a=W(s,e.id);void 0!==a&&this._events.fire("monomer:replace",{atom:a,oldSymbol:n,newSymbol:t})}hitTest(e,t){this._ensureLive();let i=new bn(this._mol,this._theme).test({x:e,y:t});return null===i?null:void 0!==i.atom?{atom:i.atom}:void 0!==i.bond?{bond:i.bond}:null}moveAtom(e,t){this._ensureLive();let i=W(this._mol,e);if(void 0===i||i.p.x===t.x&&i.p.y===t.y)return;let n=new mn(this._mol);n.updateAtom(e,{p:{x:t.x,y:t.y}});let{mol:o}=n.commit();this._replaceMol(o,"moveAtom","user")}moveAtoms(e){if(this._ensureLive(),0===e.length)return;let t=new mn(this._mol),i=0;for(let n of e){let e=W(this._mol,n.atomId);void 0!==e&&(e.p.x===n.p.x&&e.p.y===n.p.y||(t.updateAtom(n.atomId,{p:{x:n.p.x,y:n.p.y}}),i+=1))}if(0===i)return;let{mol:n}=t.commit();this._replaceMol(n,"moveAtom","user")}cleanLayout(e){this._ensureLive(),this._resetLastAction();let t=Ut(this._mol,void 0!==this._options.bondLength?{bondLength:this._options.bondLength}:void 0);this._mol=t,this._history.push({mol:t,label:"cleanLayout"}),this._events.fire("layout:change",{mol:t,strategy:"auto"}),this._events.fire("mol:changed",{mol:t,changedAtomIds:new Set(t.atoms.map(e=>e.id)),changedBondIds:to,reason:"cleanLayout"})}canUndo(){return this._history.canUndo()}canRedo(){return this._history.canRedo()}undo(){this._ensureLive();let e=this._history.undo();null!==e&&this._restoreFromHistory(e.mol,"undo")}redo(){this._ensureLive();let e=this._history.redo();null!==e&&this._restoreFromHistory(e.mol,"redo")}on(e,t){return this._events.on(e,t)}off(e,t){this._events.off(e,t)}fire(e,t){this._events.fire(e,t)}zoom(e,t){if(this._ensureLive(),!Number.isFinite(e)||e<=0)return;let i=this._viewport.scale,n=Math.min(8,Math.max(.2,i*e));if(n===i)return;let o={...this._viewport.offset},r=o;void 0!==t&&(r={x:o.x+(i-n)*t.x,y:o.y+(i-n)*t.y});let s={scale:n,offset:r};this._viewport=s;let a=t??{x:0,y:0};this._events.fire("view:zoom",{scale:n,center:a,previousScale:i}),this._events.fire("view:viewport-change",{viewport:s})}panTo(e){this._ensureLive();let t={...this._viewport.offset},i={scale:this._viewport.scale,offset:{...e}};this._viewport=i,this._events.fire("view:pan",{offset:i.offset,previousOffset:t}),this._events.fire("view:viewport-change",{viewport:i})}getViewport(){return{scale:this._viewport.scale,offset:{...this._viewport.offset}}}fitToContent(e){this._ensureLive();let t=0,i=0,n=0,o=0,r=!1;for(let e of this._mol.atoms)r?(e.p.x<t&&(t=e.p.x),e.p.x>n&&(n=e.p.x),e.p.y<i&&(i=e.p.y),e.p.y>o&&(o=e.p.y)):(t=n=e.p.x,i=o=e.p.y,r=!0);let s=r?{x:t,y:i,width:n-t,height:o-i}:{x:0,y:0,width:0,height:0},a={...this._viewport.offset},l=this._viewport.scale,h={scale:1,offset:{x:0,y:0}};this._viewport=h,1!==l&&this._events.fire("view:zoom",{scale:1,center:{x:0,y:0},previousScale:l}),(0!==a.x||0!==a.y)&&this._events.fire("view:pan",{offset:h.offset,previousOffset:a}),this._events.fire("view:viewport-change",{viewport:h}),this._events.fire("view:fit-to-content",{bbox:s})}setViewOnly(e){this._ensureLive();let t=this._viewOnly;t!==e&&(this._viewOnly=e,this._events.fire("option:change",{key:"viewOnly",oldValue:t,newValue:e}))}setTheme(e){this._ensureLive();let t=this._theme;t!==e&&(this._theme=e,this._events.fire("theme:change",{theme:e,previousTheme:t}))}toSvg(e){this._ensureLive();let t=this.getHelm(),i={};return void 0!==e?.width&&(i.width=e.width),void 0!==e?.height&&(i.height=e.height),this._service.renderToSvg(t,i)}async toPng(e){this._ensureLive();let t=this.getHelm(),i={};return void 0!==e?.width&&(i.width=e.width),void 0!==e?.height&&(i.height=e.height),this._service.renderToPng(t,i)}_getHost(){return this._host}_observerCount(){return this._events.observerCount()}_currentHighlights(){return this._highlights}_currentTheme(){return this._theme}_getView(){return this._view}_getViewport(){return this._viewport}openAtomProps(e){this._ensureLive(),null!==this._host&&(null===this._atomDialog&&(this._atomDialog=new Xn(this)),this._atomDialog.open(e))}openBondProps(e){this._ensureLive(),null!==this._host&&(null===this._bondDialog&&(this._bondDialog=new Qn(this)),this._bondDialog.open(e))}openFindReplace(){this._ensureLive(),null!==this._host&&(null===this._findReplaceDialog&&(this._findReplaceDialog=new eo(this)),this._findReplaceDialog.open())}getMode(){return this._mode}setMode(e){this._ensureLive();let t=this._mode;t!==e&&(this._mode=e,this._events.fire("option:change",{key:"mode",oldValue:t,newValue:e}))}getNextAddSymbol(){return this._nextAdd}setNextAddSymbol(e,t){this._ensureLive();let i=this._nextAdd;if(null===e)this._nextAdd=null;else{if(void 0===t)return;this._nextAdd={symbol:e,biotype:t}}this._events.fire("option:change",{key:"nextAdd",oldValue:i,newValue:this._nextAdd})}startPaletteDrag(e,t){this._ensureLive(),null!==this._dnd?this._dnd.startPaletteDrag(e,t):this._events.fire("dnd:start",{source:"palette",symbol:e})}findMonomers(e){this._ensureLive();let t=[];for(let i of this._mol.atoms)i.symbol===e&&t.push(i);return t}replaceMonomers(e,t){let i,n;if(this._ensureLive(),"string"==typeof e){let o=e,r=t;if(i=this.findMonomers(o),0===i.length)return 0;if(o===r)return i.length;n=`${o}->${r}`}else{let o=t,r=new Set,s=[];for(let t of e){if(r.has(t.id))continue;r.add(t.id);let e=W(this._mol,t.id);void 0!==e&&e.symbol!==o&&s.push(e)}if(0===s.length)return 0;i=s,n=`atoms[${s.length}]->${o}`}let o=t,r=new mn(this._mol);for(let e of i)r.updateAtom(e.id,{symbol:o});let{mol:s}=r.commit(),a=Pe(s,this._service.monomerLib,{mode:"lenient"}).mol;return this._replaceMol(a,`replaceMonomers:${n}`,"api"),i.length}nudgeSelection(e,t){this._ensureLive();let i=this._selection;if(0===i.atoms.size)return;let n=new mn(this._mol);for(let o of i.atoms){let i=W(this._mol,o);void 0!==i&&n.updateAtom(o,{p:{x:i.p.x+e,y:i.p.y+t}})}let{mol:o}=n.commit();this._replaceMol(o,"nudge","user")}deleteSelection(){this._ensureLive();let e=this._selection;if(0===e.atoms.size&&0===e.bonds.size)return;let t=new mn(this._mol);for(let i of e.atoms)t.removeAtom(i);for(let i of e.bonds)t.removeBond(i);let{mol:i}=t.commit();this._selection=hn.empty(),this._replaceMol(i,"delete-selection","user"),this._events.fire("selection:change",{selection:this._selection,addedAtomIds:to,removedAtomIds:e.atoms,addedBondIds:to,removedBondIds:e.bonds})}appendRnaTriplet(e,t,i){this._ensureLive();let n=oo(e,t,i),o=function(e,t){if(""===e)return`RNA1{${t}}$$$$V2.0`;let i,n=/(^|\|)(RNA\d+)\{([^}]*)\}/g,o=null;for(;null!==(i=n.exec(e));)o={name:i[2],body:i[3],matchText:i[0]};if(null!==o){let i=""===o.body?"":".",n=`${o.matchText.startsWith("|")?"|":""}${o.name}{${o.body}${i}${t}}`,r=e.lastIndexOf(o.matchText);return e.slice(0,r)+n+e.slice(r+o.matchText.length)}let r,s=new Set,a=/RNA(\d+)\{/g;for(;null!==(r=a.exec(e));)s.add(Number(r[1]));let l=1;for(;s.has(l);)l+=1;let h=`RNA${l}{${t}}`,d=e.indexOf("$");if(d<0)return`${e}|${h}$$$$V2.0`;let c=e.slice(0,d);return`${c}${""===c?"":"|"}${h}${e.slice(d)}`}(this.getHelm(),n);this.setHelm(o)}placeRnaTriplet(e,t,i){this._ensureLive();let n,o=1.6*(this._options.bondLength??28),r=this._mol.atoms;if("add-triplet"===this._lastAction&&null!==this._lastTripletSugarPos)n={x:this._lastTripletSugarPos.x+2*o,y:this._lastTripletSugarPos.y};else if(0===r.length)n={x:0,y:0};else{let e=r[0].p.x,t=r[0].p.y;for(let i of r)i.p.x<e&&(e=i.p.x),i.p.y>t&&(t=i.p.y);n={x:e,y:t+o}}let s={x:n.x+o,y:n.y},a={x:n.x,y:n.y+o},l=new Set;for(let e of this._mol.chains)l.add(e.id);let h=1;for(;l.has(`RNA${h}`);)h+=1;let d=`RNA${h}`,c=new mn(this._mol),u=c.addAtom({p:n,biotype:Q,symbol:e,chainId:d,positionInChain:1}),p=c.addAtom({p:s,biotype:J,symbol:i,chainId:d,positionInChain:2}),m=c.addAtom({p:a,biotype:Z,symbol:t,chainId:d,positionInChain:0});c.addBond({a1:u,a2:m,kind:"branch",r1:{kind:"numeric",r:3},r2:{kind:"numeric",r:1}}),c.addBond({a1:u,a2:p,kind:"backbone",r1:{kind:"numeric",r:2},r2:{kind:"numeric",r:1}});let{mol:f}=c.commit(),b=Pe(this._postProcessTripletMol(f,u,m,d),this._service.monomerLib,{mode:"lenient"}).mol;this._replaceMol(b,"placeRnaTriplet","user"),this._lastAction="add-triplet",this._lastTripletSugarPos=n}_postProcessTripletMol(e,t,i,n){let o=new Map,r=W(e,i),s=W(e,t);if(void 0===r||void 0===s)return e;let a={...s,branchAtom:r};o.set(t,a);let l=e.bonds.map(e=>{let t=o.get(e.a1.id)??e.a1,i=o.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}}),h=new Map;for(let e of l)h.set(e.id,e);let d=e.chains.map(e=>{let t=[];for(let r of e.backboneAtoms)e.id===n&&r.id===i||t.push(o.get(r.id)??r);let r=e.bonds.map(e=>h.get(e.id)??e);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:r,...void 0!==e.annotation?{annotation:e.annotation}:{}}}),c={atoms:e.atoms.map(e=>o.get(e.id)??e),bonds:l,chains:d,groups:e.groups,annotations:e.annotations};return c=this._refreshContinuousIdsLocal(c),c}_resetLastAction(){this._lastAction="other",this._lastTripletSugarPos=null}_ensureLive(){if(this._destroyed)throw new Error("HelmEditor: this instance has been destroyed.")}_replaceMol(e,t,i){let n=this._service.serialize(this._mol),o=this._service.serialize(e);this._mol=e,this._history.push({mol:e,label:t}),this._resetLastAction(),this._events.fire("mol:changed",{mol:e,changedAtomIds:new Set(e.atoms.map(e=>e.id)),changedBondIds:new Set(e.bonds.map(e=>e.id)),reason:t}),n!==o&&this._events.fire("helm:changed",{helm:o,mol:e,source:i})}_restoreFromHistory(e,t){let i=this._service.serialize(this._mol),n=this._service.serialize(e);this._mol=e,this._resetLastAction(),this._events.fire("mol:changed",{mol:e,changedAtomIds:new Set(e.atoms.map(e=>e.id)),changedBondIds:new Set(e.bonds.map(e=>e.id)),reason:t}),i!==n&&this._events.fire("helm:changed",{helm:n,mol:e,source:t})}};function no(e){return e.startsWith("[")&&e.endsWith("]")||1===e.length&&/^[A-Za-z]$/.test(e)?e:`[${e}]`}function oo(e,t,i){return`${no(e)}(${no(t)})${no(i)}`}var ro="http://www.w3.org/2000/svg",so={sugar:Q,base:Z,linker:J},ao={sugar:["r","R"],base:["A"],linker:["p","P"]},lo={x:70,y:60},ho={x:140,y:60},co={x:70,y:130},uo=class e{constructor(e,t,i){this.onValueSet=new ae,this.onPickModeChange=new ae,this._slots=new Map,this._favStar=null,this._pickMode=null,this._destroyed=!1,this._builderRdkitCache=new Map,this._editor=t,this._doc=i?.documentImpl??vn(e),this._hooks=i?.paletteHooks??null,this._favHooks=i?.favoriteHooks??null,this.element=wn(this._doc,"div",{class:"hw-rna-builder","data-testid":"rna-builder"});let n=wn(this._doc,"div",{class:"hw-rna-builder__header"});if(n.appendChild(wn(this._doc,"div",{class:"hw-rna-builder__title"},["RNA builder"])),null!==this._favHooks){let e=wn(this._doc,"span",{class:"hw-rna-builder__fav hw-rna-builder__fav--disabled",role:"button",tabindex:"0","data-testid":"rna-builder-fav-star",title:"Favorite this triplet","aria-pressed":"false","aria-disabled":"true"},["☆"]),t=e=>{e.stopPropagation();let t=this.getSelection();""===t.preview||null===this._favHooks||this._favHooks.toggleFavoriteTriplet(t.sugar,t.base,t.linker)};e.addEventListener("click",t),e.addEventListener("keydown",e=>{let i=e;("Enter"===i.key||" "===i.key)&&t(e)}),this._favStar=e,n.appendChild(e)}this.element.appendChild(n),this._hintEl=wn(this._doc,"div",{class:"hw-rna-builder__hint","data-testid":"rna-builder-hint",hidden:!0}),this.element.appendChild(this._hintEl);let o=this._buildSvg();this.element.appendChild(o),this._preview=wn(this._doc,"div",{class:"hw-rna-builder__preview","data-testid":"rna-builder-preview"}),this.element.appendChild(this._preview),this._addBtn=wn(this._doc,"button",{class:"hw-rna-builder__add",type:"button","data-testid":"rna-builder-add-btn"},["Add triplet"]),this._addBtn.addEventListener("click",()=>this._onAddClicked()),this.element.appendChild(this._addBtn),e.appendChild(this.element);let r=t.getService().monomerLib.onChanged.subscribe(()=>{this._destroyed||this.refresh()}),s=t.on("theme:change",()=>{this._destroyed||this._repaintSlotColors()});this._libUnsub=()=>{try{r()}catch{}try{s()}catch{}},this._populateDefaults(),this._updatePreview(),this._repaintSlotColors()}refresh(){this._populateDefaults(),this._updatePreview(),this._repaintSlotColors()}getSelection(){let e=this._slots.get("sugar")?.value??"",t=this._slots.get("base")?.value??"",i=this._slots.get("linker")?.value??"";return{sugar:e,base:t,linker:i,preview:""!==e&&""!==t&&""!==i?oo(e,t,i):""}}setField(e,t){let i=this._slots.get(e);void 0!==i&&(i.value=t,this._setLabelText(i.labelEl,t),this._repaintSlot(i),this._updatePreview(),this.onValueSet.next({field:e,symbol:t}))}startPickMode(e){this._pickMode!==e?(null!==this._pickMode&&this._setSlotPressed(this._pickMode,!1),this._pickMode=e,this._setSlotPressed(e,!0),this._setHintActive(e),this.onPickModeChange.next({field:e}),null!==this._hooks&&this._hooks.beginBiotypeFilter(so[e],t=>{this.setField(e,t),this._exitPickMode()},()=>{this._exitPickMode()})):this.cancelPickMode()}cancelPickMode(){null!==this._pickMode&&(null!==this._hooks&&this._hooks.endBiotypeFilter(),this._exitPickMode())}getPickMode(){return this._pickMode}triggerAdd(){this._onAddClicked()}destroy(){this._destroyed||(this._destroyed=!0,null!==this._pickMode&&null!==this._hooks&&this._hooks.endBiotypeFilter(),this._libUnsub(),this.onValueSet.complete(),this.onPickModeChange.complete(),null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element))}_buildSvg(){let e=this._doc.createElementNS(ro,"svg");e.setAttribute("class","hw-rna-builder__triplet"),e.setAttribute("viewBox","0 0 200 180"),e.setAttribute("data-testid","rna-builder-triplet-svg"),e.setAttribute("role","group"),e.setAttribute("aria-label","Triplet preview");let t=this._doc.createElementNS(ro,"line");t.setAttribute("class","hw-rna-builder__bond"),t.setAttribute("x1",String(lo.x+18)),t.setAttribute("y1",String(lo.y)),t.setAttribute("x2",String(ho.x-18)),t.setAttribute("y2",String(ho.y)),e.appendChild(t);let i=this._doc.createElementNS(ro,"line");i.setAttribute("class","hw-rna-builder__bond"),i.setAttribute("x1",String(lo.x)),i.setAttribute("y1",String(lo.y+18)),i.setAttribute("x2",String(co.x)),i.setAttribute("y2",String(co.y-22)),e.appendChild(i);let n=this._doc.createElementNS(ro,"rect");n.setAttribute("class","hw-rna-builder__slot-shape"),n.setAttribute("x",String(-18)),n.setAttribute("y",String(-18)),n.setAttribute("width",String(36)),n.setAttribute("height",String(36)),n.setAttribute("rx","8"),n.setAttribute("ry","8");let o=this._buildSlot("sugar","Pick sugar (backbone)",lo,n),r=this._doc.createElementNS(ro,"circle");r.setAttribute("class","hw-rna-builder__slot-shape"),r.setAttribute("cx","0"),r.setAttribute("cy","0"),r.setAttribute("r",String(18));let s=this._buildSlot("linker","Pick linker",ho,r),a=this._doc.createElementNS(ro,"path");a.setAttribute("class","hw-rna-builder__slot-shape"),a.setAttribute("d","M -22 0 L 0 -22 L 22 0 L 0 22 Z");let l=this._buildSlot("base","Pick base",co,a);return e.appendChild(s.groupEl),e.appendChild(o.groupEl),e.appendChild(l.groupEl),this._slots.set("sugar",o),this._slots.set("linker",s),this._slots.set("base",l),e}_buildSlot(e,t,i,n){let o=this._doc.createElementNS(ro,"g");o.setAttribute("class","hw-rna-builder__slot"),o.setAttribute("data-slot",e),o.setAttribute("data-testid",`rna-builder-slot-${e}`),o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.setAttribute("aria-label",t),o.setAttribute("aria-pressed","false"),o.setAttribute("transform",`translate(${i.x} ${i.y})`),o.appendChild(n);let r=this._doc.createElementNS(ro,"text");r.setAttribute("class","hw-rna-builder__slot-label"),r.setAttribute("data-testid",`rna-builder-${e}-value`),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("text-anchor","middle"),r.setAttribute("dominant-baseline","central"),o.appendChild(r);let s=t=>{t.stopPropagation(),this.startPickMode(e)};return o.addEventListener("click",s),o.addEventListener("keydown",e=>{let t=e;("Enter"===t.key||" "===t.key)&&s(e)}),o.addEventListener("mouseenter",t=>this._showSlotTooltip(e,t)),o.addEventListener("mouseleave",()=>this._hideSlotTooltip()),o.addEventListener("focus",()=>this._showSlotTooltip(e,null)),o.addEventListener("blur",()=>this._hideSlotTooltip()),{id:e,biotype:so[e],groupEl:o,shapeEl:n,labelEl:r,value:""}}_setLabelText(e,t){let i=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)"title"===t.nodeName||"TITLE"===t.nodeName||i.push(t);for(let t of i)e.removeChild(t);let n=function(e){let t=e.length;return t<=2?16:t<=4?11:t<=7?8:t<=10?6:5}(t);e.setAttribute("font-size",String(n)),e.setAttribute("text-anchor","middle"),e.setAttribute("dominant-baseline","central");let o=t.length>10?`${t.slice(0,9)}…`:t;e.appendChild(this._doc.createTextNode(o));let r=e.parentNode;if(null!==r){let e=null;for(let t=r.firstChild;null!==t;t=t.nextSibling)if("title"===t.nodeName||"TITLE"===t.nodeName){e=t;break}for(null===e&&(e=this._doc.createElementNS(ro,"title"),r.insertBefore(e,r.firstChild));null!==e.firstChild;)e.removeChild(e.firstChild);e.appendChild(this._doc.createTextNode(t))}}_repaintSlotColors(){for(let e of this._slots.values())this._repaintSlot(e)}_repaintSlot(e){let t=this._editor.getService().monomerLib,i=this._theme(),n=""===e.value?null:function(e,t,i){return e.getMonomerSet(t).get(i)??null}(t,e.biotype,e.value),o=Ie(n,e.biotype,i.colorTheme);e.shapeEl.style.fill=o.background,e.shapeEl.style.stroke=o.line,e.labelEl.style.fill=o.text}_populateDefaults(){let e=this._editor.getService().monomerLib;for(let[t,i]of this._slots.entries()){let n=mo(e,i.biotype),o=fo(n,ao[t]),r=""!==i.value&&n.some(e=>e.symbol===i.value)?i.value:o??n[0]?.symbol??"";i.value=r,this._setLabelText(i.labelEl,r)}}_updatePreview(){let e=this.getSelection();for(;null!==this._preview.firstChild;)this._preview.removeChild(this._preview.firstChild);this._preview.appendChild(this._doc.createTextNode(""===e.preview?"-":e.preview)),this._updateFavStar(e)}_updateFavStar(e){if(null===this._favStar||null===this._favHooks)return;let t=""!==e.preview,i=t&&this._favHooks.isFavoriteTriplet(e.sugar,e.base,e.linker);for(;null!==this._favStar.firstChild;)this._favStar.removeChild(this._favStar.firstChild);this._favStar.appendChild(this._doc.createTextNode(i?"★":"☆")),this._favStar.setAttribute("aria-pressed",i?"true":"false"),t?this._favStar.removeAttribute("aria-disabled"):this._favStar.setAttribute("aria-disabled","true");let n="hw-rna-builder__fav"+(i?" hw-rna-builder__fav--active":"")+(t?"":" hw-rna-builder__fav--disabled");this._favStar.setAttribute("class",n)}_onAddClicked(){let e=this.getSelection();""!==e.preview&&this._editor.placeRnaTriplet(e.sugar,e.base,e.linker)}_exitPickMode(){if(null===this._pickMode)return;let e=this._pickMode;this._setSlotPressed(e,!1),this._pickMode=null,this._setHintActive(null),this.onPickModeChange.next({field:null})}_setHintActive(e){let t=this._hintEl;for(;null!==t.firstChild;)t.removeChild(t.firstChild);if(null===e)return void t.setAttribute("hidden","");t.removeAttribute("hidden");let i="sugar"===e?"sugar":"base"===e?"base":"linker";t.appendChild(this._doc.createTextNode(`Pick ${i} from palette`))}_setSlotPressed(e,t){let i=this._slots.get(e);if(void 0===i)return;i.groupEl.setAttribute("aria-pressed",t?"true":"false");let n=(i.groupEl.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-rna-builder__slot--active"!==e).join(" ");i.groupEl.setAttribute("class",t?`${n} hw-rna-builder__slot--active`:n)}_theme(){let e=this._editor;return"function"==typeof e._currentTheme?e._currentTheme():this._editor.getService().theme}_rdkit(){let e=this._editor.getService().options?.rdkitModule;return e??null}_builderRdkitSvgFor(t){if(null===t)return null;let i=t.smiles;if(void 0===i||""===i)return null;let n=this._rdkit();if(null===n)return null;let o=`${t.polymerType}:${t.symbol}`;if(this._builderRdkitCache.has(o))return this._builderRdkitCache.get(o)??null;let r=xn(n,i,220,140);if(this._builderRdkitCache.size>=e._BUILDER_RDKIT_CACHE_LIMIT){let e=this._builderRdkitCache.keys().next().value;void 0!==e&&this._builderRdkitCache.delete(e)}return this._builderRdkitCache.set(o,r),r}_slotHint(e){switch(e){case"sugar":return"Click to choose a different sugar";case"base":return"Click to choose a different base";case"linker":return"Click to choose a different linker"}}_slotTitle(e,t){let i=""===t?"?":t;switch(e){case"sugar":return`Sugar: ${i}`;case"base":return`Base: ${i}`;case"linker":return`Linker: ${i}`}}_showSlotTooltip(e,t){let i=this._slots.get(e);if(void 0===i)return;let n=this._editor.getService().monomerLib.getMonomerSet(i.biotype),o=""===i.value?null:n.get(i.value)??null,r=Cn(this._doc,"builder-tooltip","hw-builder-tooltip");En(this._doc,r,{symbol:this._slotTitle(e,i.value),name:o?.name??"",rdkitSvg:this._builderRdkitSvgFor(o),rdkitTestid:"builder-tooltip-rdkit-svg",hint:this._slotHint(e)});let s=t;if(null!==s&&"number"==typeof s.clientX&&"number"==typeof s.clientY)kn(r,s.clientX,s.clientY);else{let e=i.groupEl,t="function"==typeof e.getBoundingClientRect?e.getBoundingClientRect():null;null!==t?kn(r,t.left+t.width/2,t.top+t.height/2):kn(r,0,0)}}_hideSlotTooltip(){Bn(this._doc.body.querySelector('[data-testid="builder-tooltip"]'))}};uo._BUILDER_RDKIT_CACHE_LIMIT=256;var po=uo;function mo(e,t){let i=e.getMonomerSet(t),n=[];for(let e of i.values())n.push(e);return n.sort((e,t)=>e.symbol.localeCompare(t.symbol)),n}function fo(e,t){let i=new Set;for(let t of e)i.add(t.symbol);for(let e of t)if(i.has(e))return e;return null}var bo="Favorites",go={[bo]:"★ Favorites",[ne.PEPTIDE]:"Peptides",[ne.RNA]:"RNA",[ne.CHEM]:"CHEM",[ne.BLOB]:"BLOB",G:"G"},Ao=[bo,ne.PEPTIDE,ne.RNA,ne.CHEM,ne.BLOB,"G"],_o="hwe:palette:favorites",yo="hwe:palette:active-tab";function vo(e){return`${e.sugar}|${e.base}|${e.linker}`}var wo=class e{constructor(e,t,i){this.favoritesChanged=new ae,this._nextAddUnsub=()=>{},this._favorites=new Set,this._favoriteTriplets=[],this._pendingRnaSelection=null,this._visibleTabs=[bo],this._activeTab=bo,this._searchInput=null,this._filter="",this._destroyed=!1,this._rnaBuilder=null,this._activeBiotypeFilter=null,this._pickResolver=null,this._pickCanceller=null,this._pickEscapeListener=null,this._pickOutsideClickListener=null,this._paletteRdkitCache=new Map,this._editor=t,this._doc=i?.documentImpl??vn(e),this._opts={documentImpl:this._doc,groupByNaturalAnalog:i?.groupByNaturalAnalog??!0,allowFavorites:i?.allowFavorites??!0},this._loadFavorites(),this._activeTab=this._resolveInitialTab(i?.initialTab),this.element=wn(this._doc,"div",{class:"hw-palette","data-testid":"palette"}),e.appendChild(this.element),this._render(),this._libUnsub=t.getService().monomerLib.onChanged.subscribe(()=>{this._destroyed||this.refresh()}),this._themeUnsub=t.on("theme:change",()=>{this._destroyed||this.refresh()}),this._nextAddUnsub=t.on("option:change",e=>{this._destroyed||"nextAdd"===e.key&&this._updatePrimedClasses()})}refresh(){this._render()}setFilter(e){this._filter=e.trim().toLowerCase(),null!==this._searchInput&&this._searchInput.value!==e&&(this._searchInput.value=e),this._applyFilter()}setActiveTab(e){this._visibleTabs.includes(e)&&(this._activeTab=e,this._persistActiveTab(),this._applyActiveTabClasses(),this._applyFilter())}getActiveTab(){return this._activeTab}getFavorites(){let e=this._editor.getService().monomerLib,t=[];for(let i of this._favorites)null!==this._findMonomer(e,i)&&t.push(i);return t}setFavorite(e,t){t!==this._favorites.has(e)&&(t?this._favorites.add(e):this._favorites.delete(e),this._saveFavorites(),this._hidePaletteTooltips(),this._render(),this._emitFavoritesChanged())}clearFavorites(){0===this._favorites.size&&0===this._favoriteTriplets.length||(this._favorites.clear(),this._favoriteTriplets.length=0,this._saveFavorites(),this._render(),this._emitFavoritesChanged())}getFavoriteTriplets(){return this._favoriteTriplets.map(e=>({...e}))}isFavoriteTriplet(e,t,i){let n=vo({sugar:e,base:t,linker:i});return this._favoriteTriplets.some(e=>vo(e)===n)}setFavoriteTriplet(e,t,i,n){let o=vo({sugar:e,base:t,linker:i}),r=this._favoriteTriplets.findIndex(e=>vo(e)===o);n!==r>=0&&(n?this._favoriteTriplets.push({sugar:e,base:t,linker:i}):this._favoriteTriplets.splice(r,1),this._saveFavorites(),this._hidePaletteTooltips(),this._render(),this._emitFavoritesChanged())}_hidePaletteTooltips(){let e=this._doc.body;Bn(e.querySelector('[data-testid="palette-tooltip"]')),Bn(e.querySelector('[data-testid="palette-triplet-tooltip"]'))}_emitFavoritesChanged(){this.favoritesChanged.next({favorites:this.getFavorites(),triplets:this.getFavoriteTriplets()})}destroy(){this._destroyed||(this._destroyed=!0,null!==this._rnaBuilder&&(this._rnaBuilder.destroy(),this._rnaBuilder=null),this._libUnsub(),this._themeUnsub(),this._nextAddUnsub(),null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element))}getRnaBuilder(){return this._rnaBuilder}hasActiveBiotypeFilter(){return null!==this._activeBiotypeFilter}getActiveBiotypeFilter(){return this._activeBiotypeFilter}cancelBiotypeFilter(){if(null===this._activeBiotypeFilter)return;let e=this._pickCanceller;this._teardownPickMode(),e?.()}_buildPaletteFilterHooks(){return{beginBiotypeFilter:(e,t,i)=>{null!==this._activeBiotypeFilter&&this._teardownPickMode(),this._activeBiotypeFilter=e,this._pickResolver=t,this._pickCanceller=i,this._applyFilter();let n=e=>{"Escape"===e.key&&this.cancelBiotypeFilter()};this._pickEscapeListener=n,this._doc.defaultView?.addEventListener("keydown",n);let o=e=>{if(null===this._activeBiotypeFilter)return;let t=e.target;if(null==t)return;let i=this._activeBiotypeFilter,n=t;for(;null!==n;){let e=void 0===n.getAttribute?null:n.getAttribute("class");if(null!==e){let t=e.split(/\s+/);if(t.includes("hw-palette__tile")){if((n.getAttribute("data-biotype")??"")===i)return;break}if(t.includes("hw-rna-builder__slot")){if(this._isInsideOwnPalette(n))return;break}}n=n.parentElement}this.cancelBiotypeFilter()};this._pickOutsideClickListener=o,this._doc.addEventListener("mousedown",o,!0)},endBiotypeFilter:()=>this._teardownPickMode()}}_scrollActivePaneToTop(){let e=this.element.querySelector(`.hw-palette__pane[data-tab="${this._activeTab}"]`);if(null===e)return;let t=e;try{if("function"==typeof t.scrollTo)return void t.scrollTo({top:0,behavior:"smooth"})}catch{}"number"==typeof t.scrollTop&&(t.scrollTop=0)}_isInsideOwnPalette(e){let t=e;for(;null!==t;){if(t===this.element)return!0;t=t.parentElement}return!1}_teardownPickMode(){null!==this._activeBiotypeFilter&&(this._activeBiotypeFilter=null,this._pickResolver=null,this._pickCanceller=null,null!==this._pickEscapeListener&&(this._doc.defaultView?.removeEventListener("keydown",this._pickEscapeListener),this._pickEscapeListener=null),null!==this._pickOutsideClickListener&&(this._doc.removeEventListener("mousedown",this._pickOutsideClickListener,!0),this._pickOutsideClickListener=null),this._applyFilter())}_render(){for(null!==this._rnaBuilder&&(this._pendingRnaSelection=this._rnaBuilder.getSelection(),this._rnaBuilder.destroy(),this._rnaBuilder=null);null!==this.element.firstChild;)this.element.removeChild(this.element.firstChild);let e=this._doc.createElement("input");e.setAttribute("type","search"),e.setAttribute("class","hw-palette__search"),e.setAttribute("placeholder","Search monomers..."),e.setAttribute("data-testid","palette-search"),""!==this._filter&&(e.value=this._filter),e.addEventListener("input",()=>this.setFilter(e.value)),this._searchInput=e,this.element.appendChild(e),this._visibleTabs=this._computeVisibleTabs(),this._visibleTabs.includes(this._activeTab)||(this._activeTab=bo);let t=wn(this._doc,"div",{class:"hw-palette__tabs",role:"tablist","data-testid":"palette-tabs"});for(let e of this._visibleTabs){let i=e===this._activeTab,n=wn(this._doc,"button",{class:"hw-palette__tab",type:"button",role:"tab","aria-controls":`hw-palette-pane-${e}`,"aria-selected":i?"true":"false","data-testid":`palette-tab-${e}`,"data-tab":e,title:go[e]},[go[e]]);n.addEventListener("click",()=>this.setActiveTab(e)),t.appendChild(n)}this.element.appendChild(t);let i=wn(this._doc,"div",{class:"hw-palette__panes"}),n=this._theme(),o=this._editor.getService().monomerLib;for(let e of this._visibleTabs){let t=e===this._activeTab,r=wn(this._doc,"div",{class:"hw-palette__pane",id:`hw-palette-pane-${e}`,role:"tabpanel","data-testid":`palette-pane-${e}`,"data-tab":e,hidden:!t});e===bo?this._buildFavoritesPane(r,o,n):this._buildPolymerPane(r,e,o,n),i.appendChild(r)}this.element.appendChild(i),this._applyFilter()}_computeVisibleTabs(){let e=this._editor.getService().monomerLib,t=new Set;for(let i of e.getPolymerTypes())t.add(i);let i=[];i.push(bo);for(let e of Ao)e!==bo&&t.has(e)&&i.push(e);return i}_buildFavoritesPane(e,t,i){let n=this._resolveFavoriteMonomers(t),o=this._favoriteTriplets;if(0===n.length&&0===o.length){let t=wn(this._doc,"div",{class:"hw-palette__placeholder","data-testid":"palette-favorites-empty"},["No favorites yet — click the ☆ on any tile to add one."]);return void e.appendChild(t)}for(let[t,i]of this._groupByPolymerAndType(n))e.appendChild(this._renderGroup(t,i));o.length>0&&e.appendChild(this._renderTripletGroup("RNA · Triplets",o,t))}_groupByPolymerAndType(e){let t=new Map;for(let i of e){let e=i.polymerType,n=i.monomerType??"Undefined",o=`${e}|${n}`,r=t.get(o);void 0===r&&(r={pt:e,mt:n,list:[]},t.set(o,r)),r.list.push(i)}let i=e=>{let t=Ao.indexOf(e);return t<0?99:t},n={Backbone:0,Branch:1,Terminal:2,Undefined:3};return Array.from(t.values()).sort((e,t)=>i(e.pt)-i(t.pt)||(n[e.mt]??9)-(n[t.mt]??9)||e.mt.localeCompare(t.mt)).map(e=>[`${this._polymerLabel(e.pt)} · ${e.mt}`,e.list])}_polymerLabel(e){return go[e]??e}_renderTripletGroup(e,t,i){let n=wn(this._doc,"div",{class:"hw-palette__group","data-natural-analog":e}),o=wn(this._doc,"div",{class:"hw-palette__group-header","data-testid":`palette-group-${e}`},[e]),r=wn(this._doc,"div",{class:"hw-triplet-chips","data-testid":"palette-triplet-favorites"});for(let e of t)r.appendChild(this._renderTripletChip(e,i));return n.appendChild(o),n.appendChild(r),n}_renderTripletChip(e,t){let i=oo(e.sugar,e.base,e.linker),n=t.getMonomerSet(Z).get(e.base)??null,o=Ie(n,Z,this._theme().colorTheme),r=this.isFavoriteTriplet(e.sugar,e.base,e.linker),s=void 0!==n?.name&&""!==n.name?`${i} — ${n.name}`:i,{root:a}=function(e,t){let i=!1!==t.showStar,n=wn(e,"span",{class:"hw-triplet-chip__star"},[t.favorite?"★":"☆"]),o=wn(e,"span",{class:"hw-triplet-chip__label"},[t.label]),r=["hw-triplet-chip"];t.favorite&&r.push("hw-triplet-chip--favorite");let s=i?[n,o]:[o];return{root:wn(e,"div",{class:r.join(" "),role:"button",tabindex:"0","aria-label":t.title,"data-sugar":t.sugar,"data-base":t.base,"data-linker":t.linker,"data-triplet":t.label,"data-testid":`palette-triplet-${t.label}`,title:t.title,style:`background:${t.background};color:${t.textColor};`},s),star:n}}(this._doc,{sugar:e.sugar,base:e.base,linker:e.linker,label:i,title:s,background:be(o.background),textColor:o.text,favorite:r,showStar:this._opts.allowFavorites});return this._wireTripletChip(a,e),a}_wireTripletChip(e,t){e.addEventListener("mouseenter",e=>{let i=e,n=Cn(this._doc,"palette-triplet-tooltip","hw-palette-tooltip hw-triplet-tooltip");(function(e,t,i){for(;null!==t.firstChild;)t.removeChild(t.firstChild);t.appendChild(wn(e,"div",{class:"hw-tooltip__symbol"},[i.title]));let n=wn(e,"div",{class:"hw-tooltip__triplet"});for(let t of i.parts){let o=wn(e,"div",{class:"hw-tooltip__triplet-part"});if(o.appendChild(wn(e,"div",{class:"hw-tooltip__triplet-role"},[`${t.role}: ${t.symbol}`])),void 0!==t.name&&""!==t.name&&t.name!==t.symbol&&o.appendChild(wn(e,"div",{class:"hw-tooltip__name"},[t.name])),void 0!==t.rdkitSvg&&null!==t.rdkitSvg&&""!==t.rdkitSvg){let n={class:"hw-tooltip__rdkit"};void 0!==i.rdkitTestid&&(n["data-testid"]=i.rdkitTestid);let r=wn(e,"div",n);r.innerHTML=t.rdkitSvg,o.appendChild(r)}n.appendChild(o)}t.appendChild(n),void 0!==i.hint&&""!==i.hint&&t.appendChild(wn(e,"div",{class:"hw-tooltip__hint"},[i.hint]))})(this._doc,n,{title:oo(t.sugar,t.base,t.linker),parts:this._tripletTooltipParts(t),hint:"Click to add this triplet",rdkitTestid:"palette-triplet-tooltip-rdkit-svg"}),kn(n,"number"==typeof i.clientX?i.clientX:0,"number"==typeof i.clientY?i.clientY:0)}),e.addEventListener("mouseleave",()=>{Bn(this._doc.body.querySelector('[data-testid="palette-triplet-tooltip"]'))}),e.addEventListener("click",e=>{let i=e.target;if(this._opts.allowFavorites&&!0===i?.classList?.contains("hw-triplet-chip__star"))return this.setFavoriteTriplet(t.sugar,t.base,t.linker,!this.isFavoriteTriplet(t.sugar,t.base,t.linker)),void e.stopPropagation();this._editor.placeRnaTriplet(t.sugar,t.base,t.linker)}),e.addEventListener("keydown",e=>{let i=e;("Enter"===i.key||" "===i.key)&&this._editor.placeRnaTriplet(t.sugar,t.base,t.linker)})}_buildRnaDefaultChips(t){let i=this._pickSymbol(t.getMonomerSet(Q),["r","R"]),n=this._pickSymbol(t.getMonomerSet(J),["p","P"]),o=t.getMonomerSet(Z);if(null===i||null===n)return null;let r=e._DEFAULT_TRIPLET_BASES.filter(e=>o.has(e));if(0===r.length)return null;let s=wn(this._doc,"div",{class:"hw-triplet-chips hw-triplet-chips--defaults","data-testid":"rna-default-triplets"});for(let e of r)s.appendChild(this._renderTripletChip({sugar:i,base:e,linker:n},t));return s}_tripletTooltipParts(e){let t=this._editor.getService().monomerLib,i=(e,i,n)=>{let o=t.getMonomerSet(i).get(n)??null;return{role:e,symbol:n,...void 0!==o?.name?{name:o.name}:{},rdkitSvg:null===o?null:this._paletteRdkitSvg(o)}};return[i("Sugar",Q,e.sugar),i("Base",Z,e.base),i("Linker",J,e.linker)]}_pickSymbol(e,t){for(let i of t)if(e.has(i))return i;let i=e.keys().next();return!0===i.done?null:i.value}_restoreRnaSelection(){let e=this._pendingRnaSelection;if(this._pendingRnaSelection=null,null===e||null===this._rnaBuilder)return;let t=this._editor.getService().monomerLib;""!==e.sugar&&t.getMonomerSet(Q).has(e.sugar)&&this._rnaBuilder.setField("sugar",e.sugar),""!==e.base&&t.getMonomerSet(Z).has(e.base)&&this._rnaBuilder.setField("base",e.base),""!==e.linker&&t.getMonomerSet(J).has(e.linker)&&this._rnaBuilder.setField("linker",e.linker)}_resolveFavoriteMonomers(e){let t=[];for(let i of this._favorites){let n=this._findMonomer(e,i);null!==n&&t.push(n)}return t}_findMonomer(e,t){for(let i of e.getPolymerTypes()){let n=e.getMonomer(i,t);if(null!==n)return n}return null}_buildPolymerPane(e,t,i,n){let o=t,r=this._monomersForPolymer(o,i);if(0===r.length)return;if(o===ne.RNA){this._rnaBuilder=new po(e,this._editor,{documentImpl:this._doc,paletteHooks:this._buildPaletteFilterHooks(),favoriteHooks:this._opts.allowFavorites?{isFavoriteTriplet:(e,t,i)=>this.isFavoriteTriplet(e,t,i),toggleFavoriteTriplet:(e,t,i)=>this.setFavoriteTriplet(e,t,i,!this.isFavoriteTriplet(e,t,i))}:null}),this._restoreRnaSelection();let t=this._buildRnaDefaultChips(i);null!==t&&e.appendChild(t);let n=this._groupRna(r);for(let[t,i]of n)0!==i.length&&e.appendChild(this._renderGroup(t,i));return}if(o===ne.PEPTIDE&&this._opts.groupByNaturalAnalog){let t=this._groupByAnalog(r);for(let[i,n]of t){let t=""===i?"Other":i;e.appendChild(this._renderGroup(t,n))}return}let s=wn(this._doc,"div",{class:"hw-palette__group-tiles"}),a=this._editor.getNextAddSymbol(),l=this._sortByColor(r);for(let e of l){let t=this._biotype(e,o);s.appendChild(this._renderTile(e,t,a))}e.appendChild(s)}_renderGroup(e,t){let i=wn(this._doc,"div",{class:"hw-palette__group","data-natural-analog":e}),n=wn(this._doc,"div",{class:"hw-palette__group-header","data-testid":`palette-group-${e}`},[e]),o=wn(this._doc,"div",{class:"hw-palette__group-tiles"}),r=this._editor.getNextAddSymbol(),s=this._sortByColor(t);for(let e of s){let t=this._biotype(e,e.polymerType);o.appendChild(this._renderTile(e,t,r))}return i.appendChild(n),i.appendChild(o),i}_sortByColor(e){let t=this._theme(),i=e.map((e,i)=>{let n=function(e){let t=de(e);if(null===t)return{h:0,s:0,l:0};let[i,n,o]=pe(t[0],t[1],t[2]);return{h:i,s:n,l:o}}(Ie(e,this._biotype(e,e.polymerType),t.colorTheme).background),o=0===n.s?1:0;return{m:e,idx:i,h:n.h,s:n.s,l:n.l,isGrey:o}});return i.sort((e,t)=>e.isGrey!==t.isGrey?e.isGrey-t.isGrey:e.h!==t.h?e.h-t.h:e.s!==t.s?e.s-t.s:e.l!==t.l?e.l-t.l:e.idx-t.idx),i.map(e=>e.m)}_monomersForPolymer(e,t){let i=t.getMonomerSymbolsByType(e),n=[];for(let o of i){let i=t.getMonomer(e,o);null!==i&&n.push(i)}return n.sort((e,t)=>e.symbol.localeCompare(t.symbol)),n}_groupByAnalog(e){let t=new Map;for(let i of e){let e=i.naturalAnalog??"",n=t.get(e);void 0===n&&(n=[],t.set(e,n)),n.push(i)}let i=[],n=Array.from(t.keys()).sort((e,t)=>""===e&&""!==t?1:""===t&&""!==e?-1:e.localeCompare(t));for(let e of n)i.push([e,t.get(e)]);return new Map(i)}_groupRna(e){let t=[],i=[],n=[],o=[];for(let r of e){let e=$e(r);e===Q?t.push(r):e===Z?i.push(r):e===J?n.push(r):o.push(r)}let r=new Map;return r.set("Backbones",t),r.set("Bases",i),r.set("Linkers",n),o.length>0&&r.set("Other",o),r}_renderTile(e,t,i){let n=this._favorites.has(e.symbol),o=null!==i&&i.symbol===e.symbol&&i.biotype===t,{root:r,star:s}=function(e,t){let i=Ie(t.monomer,t.biotype,t.theme.colorTheme),n=be(i.background),o=i.text,r=function(e,t){let i=ge(e),n=ge(t);return(Math.max(i,n)+.05)/(Math.min(i,n)+.05)}(o,n)<5,s=t.monomer.symbol,a=function(e){return e<=3?14:e<=6?11:e<=9?9:8}(s.length),l=`font-size:${a}px;${s.length>=10?"line-height:1.1;letter-spacing:-0.02em;":""}white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:80px;display:inline-block;`,h=wn(e,"span",{class:"hw-palette__star"},[t.favorite?"★":"☆"]),d=wn(e,"span",{class:"hw-palette__label",style:l},[s]),c=["hw-palette__tile"];t.primed&&c.push("hw-palette__tile--primed"),t.favorite&&c.push("hw-palette__tile--favorite"),r&&c.push("hw-palette__tile--low-contrast");let u=void 0!==t.monomer.name?`${s} — ${t.monomer.name}`:s,p=`background:${n};color:${o};width:100%;min-width:48px;padding:4px 6px;height:40px;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;`;return{root:wn(e,"div",{class:c.join(" "),draggable:"true",role:"button","aria-pressed":t.primed?"true":"false","aria-label":u,"data-symbol":s,"data-biotype":t.biotype,"data-bg":n,"data-raw-bg":i.background,"data-testid":`palette-tile-${s}`,title:u,style:p},[h,d]),star:h}}(this._doc,{monomer:e,biotype:t,theme:this._theme(),favorite:n,primed:o});return this._wireTile(r,s,e,t),r}_rdkit(){let e=this._editor.getService().options?.rdkitModule;return e??null}_paletteRdkitSvg(t){let i=t.smiles;if(void 0===i||""===i)return null;let n=this._rdkit();if(null===n)return null;let o=`${t.polymerType}:${t.symbol}`;if(this._paletteRdkitCache.has(o))return this._paletteRdkitCache.get(o)??null;let r=xn(n,i,220,140);if(this._paletteRdkitCache.size>=e._PALETTE_RDKIT_CACHE_LIMIT){let e=this._paletteRdkitCache.keys().next().value;void 0!==e&&this._paletteRdkitCache.delete(e)}return this._paletteRdkitCache.set(o,r),r}_wireTile(e,t,i,n){e.addEventListener("mouseenter",e=>{let t=e,n=Cn(this._doc,"palette-tooltip","hw-palette-tooltip");En(this._doc,n,{symbol:i.symbol,name:i.name??"",rdkitSvg:this._paletteRdkitSvg(i),rdkitTestid:"palette-tooltip-rdkit-svg"}),kn(n,"number"==typeof t.clientX?t.clientX:0,"number"==typeof t.clientY?t.clientY:0)}),e.addEventListener("mouseleave",()=>{Bn(this._doc.body.querySelector('[data-testid="palette-tooltip"]'))}),e.addEventListener("click",e=>{let t=e.target;if(this._opts.allowFavorites&&void 0!==t&&!0===t?.classList?.contains("hw-palette__star"))return this.setFavorite(i.symbol,!this._favorites.has(i.symbol)),void e.stopPropagation();if(null!==this._activeBiotypeFilter&&this._activeBiotypeFilter===n){let t=this._pickResolver;return this._teardownPickMode(),t?.(i.symbol),this._scrollActivePaneToTop(),void e.stopPropagation()}let o=this._editor.getSelection();if(o.atoms.size>0){let t=this._editor.getMol(),r=[];for(let e of o.atoms){let i=t.atoms.find(t=>t.id===e);void 0!==i&&r.push(i)}return r.length>0&&r.every(e=>e.biotype===n)?(this._editor.replaceMonomers(r,i.symbol),void e.stopPropagation()):(this._editor.fire("editor:status",{message:`Cannot bulk-replace ${r.length} selected atom(s) with ${i.symbol}: selection contains incompatible biotypes for ${n}.`,severity:"warn",durationMs:3e3}),void e.stopPropagation())}let r=this._editor.getNextAddSymbol();if(null!==r&&r.symbol===i.symbol&&r.biotype===n)return this._editor.setNextAddSymbol(null),void this._updatePrimedClasses();this._editor.setNextAddSymbol(i.symbol,n),this._updatePrimedClasses()}),e.addEventListener("dragstart",e=>{let t=e.dataTransfer;if(null!=t)try{t.setData("application/x-hwe-monomer",JSON.stringify({symbol:i.symbol,biotype:n})),t.effectAllowed="copy"}catch{}Bn(this._doc.body.querySelector('[data-testid="palette-tooltip"]')),this._editor.startPaletteDrag(i.symbol,n)})}_biotype(e,t){let i=$e(e);if(null!==i)return i;switch(t){case ne.PEPTIDE:return X;case ne.RNA:return Q;case ne.CHEM:return ee;case ne.BLOB:return te;default:return ee}}_theme(){let e=this._editor;return"function"==typeof e._currentTheme?e._currentTheme():this._editor.getService().theme}_applyFilter(){let e=this._filter,t=this._activeBiotypeFilter,i=this.element.querySelector(`.hw-palette__pane[data-tab="${this._activeTab}"]`),n=(i??this.element).querySelectorAll(".hw-palette__tile");for(let i=0;i<n.length;i++){let o=n[i],r=(o.getAttribute("data-symbol")??"").toLowerCase(),s=(o.getAttribute("title")??"").toLowerCase(),a=o.getAttribute("data-biotype")??"",l=(""===e||r.indexOf(e)>=0||s.indexOf(e)>=0)&&(null===t||a===t);o.style.display=l?"":"none"}let o=(i??this.element).querySelectorAll(".hw-triplet-chip");for(let i=0;i<o.length;i++){let n=o[i],r=[n.getAttribute("data-triplet")??"",n.getAttribute("data-sugar")??"",n.getAttribute("data-base")??"",n.getAttribute("data-linker")??""].join(" ").toLowerCase(),s=(""===e||r.indexOf(e)>=0)&&null===t;n.style.display=s?"":"none"}let r=(i??this.element).querySelectorAll(".hw-palette__group");for(let e=0;e<r.length;e++){let t=r[e],i=t.querySelectorAll(".hw-palette__tile, .hw-triplet-chip"),n=!1;for(let e=0;e<i.length;e++)if("none"!==i[e].style.display){n=!0;break}n?(t.removeAttribute("hidden"),t.removeAttribute("data-section-empty")):(t.setAttribute("hidden",""),t.setAttribute("data-section-empty","true"))}}_updatePrimedClasses(){let e=this._editor.getNextAddSymbol(),t=this.element.querySelectorAll(".hw-palette__tile");for(let i=0;i<t.length;i++){let n=t[i],o=n.getAttribute("data-symbol")??"",r=n.getAttribute("data-biotype")??"",s=null!==e&&e.symbol===o&&e.biotype===r,a=(n.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-palette__tile--primed"!==e).join(" ");n.setAttribute("class",s?`${a} hw-palette__tile--primed`:a),n.setAttribute("aria-pressed",s?"true":"false")}}_applyActiveTabClasses(){let e=this.element.querySelectorAll(".hw-palette__tab");for(let t=0;t<e.length;t++){let i=e[t],n=i.getAttribute("data-tab")??"";i.setAttribute("aria-selected",n===this._activeTab?"true":"false")}let t=this.element.querySelectorAll(".hw-palette__pane");for(let e=0;e<t.length;e++){let i=t[e];(i.getAttribute("data-tab")??"")===this._activeTab?i.removeAttribute("hidden"):i.setAttribute("hidden","")}}_localStorage(){if(!this._opts.allowFavorites)return null;let e=this._doc.defaultView;if(null==e)return null;try{return e.localStorage??null}catch{return null}}_resolveInitialTab(e){if(void 0!==e&&Ao.includes(e))return e;let t=this._localStorage();if(null!==t)try{let e=t.getItem(yo);if(null!==e&&Ao.includes(e))return e}catch{}return bo}_persistActiveTab(){let e=this._localStorage();if(null!==e)try{e.setItem(yo,this._activeTab)}catch{}}_loadFavorites(){let e=this._localStorage();if(null!==e){try{let t=e.getItem(_o);if(null!==t&&""!==t){let e=JSON.parse(t),i=this._extractSymbols(e);for(let e of i)this._favorites.add(e);for(let t of this._extractTriplets(e))this._favoriteTriplets.push(t);return}}catch{}try{let t=e.getItem("hwe.palette.favorites");if(null===t||""===t)return;let i=JSON.parse(t);if(Array.isArray(i)){for(let e of i){if("string"!=typeof e)continue;let t=e.indexOf("|"),i=t>=0?e.slice(t+1):e;""!==i&&this._favorites.add(i)}this._saveFavorites()}}catch{}}}_extractSymbols(e){if(Array.isArray(e)){let t=[];for(let i of e)"string"==typeof i&&t.push(i);return t}if(null!==e&&"object"==typeof e){let t=e;if(Array.isArray(t.symbols)){let e=[];for(let i of t.symbols)"string"==typeof i&&e.push(i);return e}}return[]}_extractTriplets(e){if(null===e||"object"!=typeof e)return[];let t=e;if(!Array.isArray(t.triplets))return[];let i=[];for(let e of t.triplets){if(null===e||"object"!=typeof e)continue;let t=e;"string"==typeof t.sugar&&"string"==typeof t.base&&"string"==typeof t.linker&&i.push({sugar:t.sugar,base:t.base,linker:t.linker})}return i}_saveFavorites(){let e=this._localStorage();if(null!==e)try{let t={symbols:Array.from(this._favorites)};this._favoriteTriplets.length>0&&(t.triplets=this._favoriteTriplets.map(e=>({...e}))),e.setItem(_o,JSON.stringify(t))}catch{}}};wo._DEFAULT_TRIPLET_BASES=["A","C","G","U","T"],wo._PALETTE_RDKIT_CACHE_LIMIT=256;var xo=wo,Co='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">',Eo={new:`${Co}<path d="M13 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9z"/><path d="M13 3v6h6"/><line x1="12" y1="12.5" x2="12" y2="17.5"/><line x1="9.5" y1="15" x2="14.5" y2="15"/></svg>`,open:`${Co}<path d="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"/></svg>`,save:`${Co}<rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="m9 14 2 2 4-4"/></svg>`,undo:`${Co}<path d="M3 12a9 9 0 1 0 9-9 9.7 9.7 0 0 0-6.7 2.8L3 8"/><path d="M3 3v5h5"/></svg>`,redo:`${Co}<path d="M21 12a9 9 0 1 1-9-9 9.7 9.7 0 0 1 6.7 2.8L21 8"/><path d="M21 3v5h-5"/></svg>`,eraser:`${Co}<path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>`,select:`${Co}<path d="m4 4 7.07 17 2.51-7.39L21 11.07z"/></svg>`,hbond:`${Co}<path d="M9 17H7A5 5 0 0 1 7 7h2"/><path d="M15 7h2a5 5 0 1 1 0 10h-2"/><line x1="8" y1="12" x2="16" y2="12"/></svg>`,"zoom-in":`${Co}<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>`,"zoom-out":`${Co}<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/></svg>`,fit:`${Co}<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>`,move:`${Co}<polyline points="5 9 2 12 5 15"/><polyline points="9 5 12 2 15 5"/><polyline points="15 19 12 22 9 19"/><polyline points="19 9 22 12 19 15"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="12" y1="2" x2="12" y2="22"/></svg>`,clean:`${Co}<path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z"/><path d="m14 7 3 3"/><path d="M5 6v4"/><path d="M19 14v4"/><path d="M10 2v2"/><path d="M7 8H3"/><path d="M21 16h-4"/><path d="M11 3H9"/></svg>`,find:`${Co}<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>`,theme:`${Co}<circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>`},ko={new:"New — clear the canvas",open:"Open — paste a HELM string",save:"Save — copy HELM string to clipboard",undo:"Undo last action",redo:"Redo last undone action",eraser:"Eraser — click an atom or bond to delete it",select:"Select mode (default)",hbond:"H-Bond mode — drag between two RNA bases to add a Watson-Crick pair","zoom-in":"Zoom in","zoom-out":"Zoom out",fit:"Fit to content — reset zoom and pan",move:"Move/Pan mode — drag the canvas to scroll",clean:"Clean layout — re-run automatic layout",find:"Find / Replace monomer",theme:"Toggle dark / light theme"},Bo=[{id:"new",label:"New",icon:"New"},{id:"open",label:"Open",icon:"Open"},{id:"save",label:"Save",icon:"Save"},{id:"undo",label:"Undo",icon:"↺",shortcut:"Ctrl+Z",separator:!0},{id:"redo",label:"Redo",icon:"↻",shortcut:"Ctrl+Y"},{id:"eraser",label:"Eraser",icon:"Eraser",separator:!0},{id:"select",label:"Select",icon:"Select"},{id:"hbond",label:"H-Bond",icon:"H-Bond"},{id:"zoom-in",label:"Zoom In",icon:"+",shortcut:"Ctrl++",separator:!0},{id:"zoom-out",label:"Zoom Out",icon:"−",shortcut:"Ctrl+−"},{id:"fit",label:"Fit",icon:"Fit",shortcut:"0"},{id:"move",label:"Move",icon:"Move"},{id:"clean",label:"Clean",icon:"Clean",separator:!0},{id:"find",label:"Find",icon:"Find",shortcut:"Ctrl+F"},{id:"theme",label:"Theme",icon:"Theme",separator:!0}],So=class{constructor(e,t,i){this._buttons=new Map,this._unsubs=[],this._destroyed=!1,this._editor=t,this._doc=i?.documentImpl??vn(e);let n=i?.buttons??Bo;this.element=wn(this._doc,"div",{class:"hw-toolbar","data-testid":"toolbar"}),e.appendChild(this.element);for(let e of n){if(!0===e.separator){let e=wn(this._doc,"span",{class:"hw-toolbar__separator"});this.element.appendChild(e)}let t=this._buildButton(e);this.element.appendChild(t),this._buttons.set(e.id,t)}let o=()=>this._refreshHistoryState();this._unsubs.push(t.on("mol:changed",o)),this._unsubs.push(t.on("helm:changed",o)),o(),this._reflectMode(),this._unsubs.push(t.on("option:change",e=>{"mode"===e.key&&this._reflectMode()}))}setButtonEnabled(e,t){let i=this._buttons.get(e);void 0!==i&&(t?i.removeAttribute("disabled"):i.setAttribute("disabled",""))}destroy(){if(!this._destroyed){this._destroyed=!0,this._hideTip();for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_buildButton(e){let t=this._doc.createElement("button");t.setAttribute("class","hw-toolbar__btn"),t.setAttribute("type","button"),t.setAttribute("data-action",e.id),t.setAttribute("data-testid",`toolbar-${e.id}`);let i=ko[e.id]??e.label,n=void 0!==e.shortcut?`${i} (${e.shortcut})`:i;t.setAttribute("data-tooltip",n),t.setAttribute("aria-label",i),t.addEventListener("mouseenter",e=>{let t=e;this._showTip(n,"number"==typeof t.clientX?t.clientX:0,"number"==typeof t.clientY?t.clientY:0)}),t.addEventListener("mouseleave",()=>this._hideTip()),t.addEventListener("click",()=>this._hideTip());let o=Eo[e.id];if(void 0!==o){let e=this._doc.createElement("span");e.setAttribute("class","hw-toolbar__btn-icon"),e.setAttribute("aria-hidden","true"),e.innerHTML=o,t.appendChild(e)}else{let i=e.icon??e.label;t.appendChild(this._doc.createTextNode(i))}return t.addEventListener("click",()=>this._invoke(e.id)),t}_showTip(e,t,i){let n=Cn(this._doc,"toolbar-tooltip","hw-toolbar-tooltip");for(;null!==n.firstChild;)n.removeChild(n.firstChild);n.appendChild(this._doc.createTextNode(e)),kn(n,t,i)}_hideTip(){Bn(this._doc.body.querySelector('[data-testid="toolbar-tooltip"]'))}_invoke(e){let t=!1;this._editor.fire("key:command",{command:e,preventDefault:()=>{t=!0}}),!t&&this._execute(e)}_execute(e){switch(e){case"new":return void this._editor.setHelm("");case"open":{let e=this._doc.defaultView;if(null!=e&&"function"==typeof e.prompt){let t=e.prompt("Enter HELM string");null!==t&&this._editor.setHelm(t)}return}case"save":{let e=this._editor.getHelm();return void this._editor.fire("clipboard:copy",{format:"helm",payload:e})}case"undo":return void this._editor.undo();case"redo":return void this._editor.redo();case"eraser":return this._editor.getSelection().isEmpty?void this._editor.setMode("eraser"):void this._editor.deleteSelection();case"select":case"hbond":case"move":return void this._editor.setMode(e);case"zoom-in":return void this._editor.zoom(1.1,this._molCenterOrUndefined());case"zoom-out":return void this._editor.zoom(1/1.1,this._molCenterOrUndefined());case"fit":return void this._editor.fitToContent();case"clean":return void this._editor.cleanLayout();case"find":return void this._editor.openFindReplace();case"theme":{let e=this._editor,t="function"==typeof e._currentTheme?e._currentTheme():null,i=null!==t&&"dark"===t.name;return void this._editor.setTheme(i?si:ai)}default:return}}_refreshHistoryState(){this.setButtonEnabled("undo",this._editor.canUndo()),this.setButtonEnabled("redo",this._editor.canRedo())}_molCenterOrUndefined(){let e=this._editor.getMol();if(0===e.atoms.length)return;let t=e.atoms[0].p.x,i=t,n=e.atoms[0].p.y,o=n;for(let r=1;r<e.atoms.length;r++){let s=e.atoms[r].p;s.x<t&&(t=s.x),s.x>i&&(i=s.x),s.y<n&&(n=s.y),s.y>o&&(o=s.y)}return{x:(t+i)/2,y:(n+o)/2}}_reflectMode(){let e=this._editor.getMode();for(let t of["select","eraser","hbond","move"]){let i=this._buttons.get(t);if(void 0===i)continue;let n=(i.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-toolbar__btn--active"!==e).join(" ");i.setAttribute("class",t===e?`${n} hw-toolbar__btn--active`:n)}}},Mo=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._editor=t,this._doc=i?.documentImpl??vn(e),this._content=wn(this._doc,"pre",{class:"hw-pane__content hw-pane__sequence","data-testid":"sequence-pane-content"}),this.element=wn(this._doc,"div",{class:"hw-pane hw-pane--sequence","data-testid":"pane-sequence"},[this._content]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on("helm:changed",()=>this.refresh())),this._unsubs.push(t.on("mol:changed",()=>this.refresh()))}refresh(){if(this._destroyed)return;let e=this._compute();for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_compute(){let e,t=this._editor.getMol(),i=[];for(let n of t.atoms){let t=n.bio.chainId;void 0!==e&&t!==e&&i.push("|"),e=t;let o=n.monomer?.naturalAnalog;i.push(void 0!==o&&""!==o?o:n.symbol)}return i.join("")}},To=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._suppressNext=!1,this._editor=t,this._doc=i?.documentImpl??vn(e),this._input=wn(this._doc,"div",{class:"hw-pane__content hw-pane__notation",contenteditable:"true",spellcheck:"false","data-testid":"notation-pane-content"}),this._error=wn(this._doc,"div",{class:"hw-pane__error","data-testid":"notation-pane-error"}),this.element=wn(this._doc,"div",{class:"hw-pane hw-pane--notation","data-testid":"pane-helm"},[this._input,this._error]),e.appendChild(this.element),this.refresh(),this._input.addEventListener("blur",()=>this._commit()),this._input.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this._commit())}),this._unsubs.push(t.on("helm:changed",()=>{this._suppressNext?this._suppressNext=!1:this.refresh()})),this._unsubs.push(t.on("mol:changed",()=>this.refresh()))}refresh(){if(this._destroyed)return;let e=this._editor.getHelm();for(;null!==this._input.firstChild;)this._input.removeChild(this._input.firstChild);this._input.appendChild(this._doc.createTextNode(e)),this._clearError()}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_commit(){if(this._destroyed)return;let e=(this._input.textContent??"").trim();if(e===this._editor.getHelm())return void this._clearError();let t=this._editor.getService().validate(e).filter(e=>"error"===e.severity);t.length>0?this._showError(t.map(e=>e.message).join("; ")):(this._clearError(),this._suppressNext=!0,this._editor.setHelm(e))}_showError(e){for(;null!==this._error.firstChild;)this._error.removeChild(this._error.firstChild);this._error.appendChild(this._doc.createTextNode(e)),this._error.setAttribute("class","hw-pane__error hw-pane__error--visible")}_clearError(){for(;null!==this._error.firstChild;)this._error.removeChild(this._error.firstChild);this._error.setAttribute("class","hw-pane__error")}},Io=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._editor=t,this._doc=i?.documentImpl??vn(e),this._body=wn(this._doc,"div",{class:"hw-pane__content hw-pane__properties","data-testid":"properties-pane-content"}),this.element=wn(this._doc,"div",{class:"hw-pane hw-pane--properties","data-testid":"pane-properties"},[this._body]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on("helm:changed",()=>this.refresh())),this._unsubs.push(t.on("mol:changed",()=>this.refresh()))}refresh(){if(this._destroyed)return;for(;null!==this._body.firstChild;)this._body.removeChild(this._body.firstChild);let e=this._editor.getHelm();if(e.length>1e3)return void this._body.appendChild(wn(this._doc,"div",{class:"hw-pane__placeholder"},["(too long)"]));let t=this._editor.getService(),i="",n=0,o=0;try{let o=t.getFormula(e);i=function(e){let t=Array.from(e.keys()).sort((e,t)=>e===t?0:"C"===e?-1:"C"===t?1:"H"===e?-1:"H"===t?1:e.localeCompare(t)),i="";for(let n of t){let t=e.get(n);void 0===t||0===t||(i+=1===t?n:`${n}${t}`)}return""===i?"—":i}(o.elements),n=o.mw}catch{i="—"}try{n=t.getMolWeight(e)}catch{}try{o=t.getExtinctionCoefficient(e)}catch{}this._body.appendChild(this._makeRow("Formula",i,"formula")),this._body.appendChild(this._makeRow("Molecular Weight",0===n?"—":n.toFixed(2),"mw")),this._body.appendChild(this._makeRow("Extinction Coefficient",0===o?"—":o.toFixed(0),"extinction"))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_makeRow(e,t,i){let n=wn(this._doc,"span",{class:"hw-pane__prop-label"},[e]),o=wn(this._doc,"span",{class:"hw-pane__prop-value","data-testid":`properties-${i}`},[t]);return wn(this._doc,"div",{class:"hw-pane__prop-row"},[n,o])}},Lo=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._refreshToken=0,this._editor=t,this._doc=i?.documentImpl??vn(e),this._content=wn(this._doc,"pre",{class:"hw-pane__content hw-pane__atomic","data-testid":"atomic-pane-content"}),this.element=wn(this._doc,"div",{class:"hw-pane hw-pane--atomic","data-testid":"pane-atomic"},[this._content]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on("helm:changed",()=>{this.refresh()}))}async refresh(){if(this._destroyed)return;let e=++this._refreshToken,t=this._editor.getHelm(),i=this._editor.getService();if(i.hasAtomicMolfileProvider())try{let n=await i.getAtomicMolfile(t);if(this._destroyed||e!==this._refreshToken)return;this._render(n)}catch(t){if(this._destroyed||e!==this._refreshToken)return;let i=t instanceof Error?t.message:String(t);this._render(`Atomic structure unavailable: ${i}`)}else this._render("Atomic structure unavailable")}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_render(e){for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e))}};function $o(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var Po=class{constructor(e,t,i,n,o){this._unsubs=[],this._destroyed=!1,this._active=!1,this._dirty=!0,this._refreshToken=0,this._editor=t,this._provider=n,this.name=i,this._doc=o?.documentImpl??vn(e);let r=$o(i);this._content=wn(this._doc,"div",{class:"hw-pane__content hw-pane__extra","data-testid":`extra-pane-content-${r}`}),this.element=wn(this._doc,"div",{class:"hw-pane hw-pane--extra","data-testid":`pane-extra-${r}`},[this._content]),e.appendChild(this.element),this._unsubs.push(t.on("helm:changed",()=>{this._dirty=!0,this._active&&this.refresh()}))}setActive(e){this._active=e,e&&this._dirty&&this.refresh()}async refresh(){if(this._destroyed)return;let e=++this._refreshToken;this._dirty=!1;let t=this._editor.getHelm();try{let i=await this._provider(t);if(this._destroyed||e!==this._refreshToken)return;this._mount(i)}catch(t){if(this._destroyed||e!==this._refreshToken)return;let i=t instanceof Error?t.message:String(t);this._renderText(`Pane "${this.name}" failed: ${i}`)}}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_mount(e){for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(e)}_renderText(e){for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e))}};function Ro(e){return"extra:"+e}var Ho=[{id:"sequence",label:"Sequence"},{id:"helm",label:"HELM"},{id:"properties",label:"Properties"},{id:"atomic",label:"Atomic Structure"}],No=class{constructor(e,t){this._paneByName=new Map,this._tabsByName=new Map,this._unsubs=[],this._activePane="helm",this._destroyed=!1,this._statusModeNode=null,this._statusMessageNode=null,this._statusMessageTimeout=null,this._host=e,this._doc=t.documentImpl??vn(e);let i="dark"===(t.theme??si).name?"hw-app hw-app--dark":"hw-app";this.element=wn(this._doc,"div",{class:i,"data-testid":"app-root"}),this._toolbarHost=wn(this._doc,"div",{class:"hw-app__toolbar"}),this._paletteHost=wn(this._doc,"div",{class:"hw-app__palette"}),this._canvasHost=wn(this._doc,"div",{class:"hw-app__canvas","data-testid":"canvas-host"});let n=wn(this._doc,"div",{class:"hw-app__main"},[this._paletteHost,this._canvasHost]);this._tabsHost=wn(this._doc,"div",{class:"hw-app__tabs",role:"tablist"}),this._paneBody=wn(this._doc,"div",{class:"hw-app__pane-body"});let o=wn(this._doc,"div",{class:"hw-app__panes"},[this._tabsHost,this._paneBody]);this.element.appendChild(this._toolbarHost),this.element.appendChild(n),this.element.appendChild(o),e.appendChild(this.element);let r={service:t.service};void 0!==t.initialHelm&&(r.initialHelm=t.initialHelm),void 0!==t.width&&(r.width=t.width),void 0!==t.height&&(r.height=t.height),this.canvas=new io(this._canvasHost,r),void 0!==t.theme&&this.canvas.setTheme(t.theme);let s={documentImpl:this._doc};void 0!==t.toolbarButtons&&(s.buttons=t.toolbarButtons),this.toolbar=new So(this._toolbarHost,this.canvas,s),this.palette=new xo(this._paletteHost,this.canvas,{documentImpl:this._doc,...t.paletteOptions}),this.sequencePane=new Mo(this._paneBody,this.canvas,{documentImpl:this._doc}),this.notationPane=new To(this._paneBody,this.canvas,{documentImpl:this._doc}),this.propertiesPane=new Io(this._paneBody,this.canvas,{documentImpl:this._doc}),t.service.hasAtomicMolfileProvider()?this.atomicStructurePane=new Lo(this._paneBody,this.canvas,{documentImpl:this._doc}):this.atomicStructurePane=null,this._paneByName.set("sequence",this.sequencePane.element),this._paneByName.set("helm",this.notationPane.element),this._paneByName.set("properties",this.propertiesPane.element),null!==this.atomicStructurePane&&this._paneByName.set("atomic",this.atomicStructurePane.element);let a=[];for(let[e,i]of t.service.getExtraPanes()){let t=new Po(this._paneBody,this.canvas,e,i,{documentImpl:this._doc});a.push(t),this._paneByName.set(Ro(e),t.element)}this.extraPanes=a;let l=this._resolveVisiblePanes(t),h=[];for(let e of l){let t=Ho.find(t=>t.id===e);void 0!==t&&h.push({id:t.id,label:t.label,testid:`tab-${t.id}`})}for(let e of a)h.push({id:Ro(e.name),label:e.name,testid:`tab-extra-${$o(e.name)}`});for(let{id:e,label:t,testid:i}of h){let n=this._doc.createElement("button");n.setAttribute("type","button"),n.setAttribute("class","hw-app__tab"),n.setAttribute("role","tab"),n.setAttribute("data-pane",e),n.setAttribute("data-testid",i),n.appendChild(this._doc.createTextNode(t)),n.addEventListener("click",()=>this.activatePane(e)),this._tabsHost.appendChild(n),this._tabsByName.set(e,n)}let d=l.includes("helm")?"helm":l[0]??"helm";this.activatePane(d),this._unsubs.push(this.canvas.on("theme:change",e=>this._applyTheme(e.theme))),this._buildStatusBar(),this._applyMode(this.canvas.getMode()),this._unsubs.push(this.canvas.on("option:change",e=>{"mode"===e.key&&this._applyMode(e.newValue),"nextAdd"===e.key&&this._refreshStatus()})),this._unsubs.push(this.canvas.on("mol:changed",()=>this._refreshStatus())),this._unsubs.push(this.canvas.on("helm:changed",()=>this._refreshStatus())),this._unsubs.push(this.canvas.on("editor:status",e=>{this._showStatusMessage(e.message,e.severity,e.durationMs)})),this._unsubs.push(this.canvas.on("monomer:contextmenu",e=>{e.preventDefault(),this.canvas.openAtomProps(e.atom)})),this._unsubs.push(this.canvas.on("bond:contextmenu",e=>{e.preventDefault(),this.canvas.openBondProps(e.bond)})),this._onDocKeydown=e=>this._handleEscape(e),this._doc.addEventListener("keydown",this._onDocKeydown,!0)}_handleEscape(e){let t=e;"Escape"===t.key&&(Sn(this._doc),$n.closeTopmost()&&(t.stopImmediatePropagation?.(),t.preventDefault?.()))}_buildStatusBar(){let e=wn(this._doc,"div",{class:"hw-status-bar","data-testid":"status-bar"}),t=wn(this._doc,"span",{class:"hw-status-bar__mode","data-testid":"status-mode"}),i=wn(this._doc,"span",{class:"hw-status-bar__message","data-testid":"status-message",role:"status","aria-live":"polite"});e.appendChild(t),e.appendChild(i),this._canvasHost.appendChild(e),this._statusModeNode=t,this._statusMessageNode=i,this._refreshStatus()}_refreshStatus(){let e=this._statusModeNode;if(null===e)return;let t=this.canvas.getMode(),i=this.canvas.getNextAddSymbol();for(;null!==e.firstChild;)e.removeChild(e.firstChild);if(null===i)return void e.appendChild(this._doc.createTextNode(`Mode: ${t} | Next add: none`));e.appendChild(this._doc.createTextNode(`Mode: ${t} | Next add: `));let n=wn(this._doc,"span",{class:"hw-status-bar__next-add-symbol","data-testid":"status-next-add-symbol"},[i.symbol]);e.appendChild(n);let o=wn(this._doc,"button",{type:"button",class:"hw-status-bar__next-add-clear","data-testid":"status-next-add-clear","aria-label":"Clear next-add monomer",title:"Clear (Esc)"},["×"]);o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.canvas.setNextAddSymbol(null)}),e.appendChild(o)}_showStatusMessage(e,t,i){let n=this._statusMessageNode;if(null!==n){for(null!==this._statusMessageTimeout&&(clearTimeout(this._statusMessageTimeout),this._statusMessageTimeout=null);null!==n.firstChild;)n.removeChild(n.firstChild);n.appendChild(this._doc.createTextNode(e)),n.setAttribute("data-severity",t),i>0&&(this._statusMessageTimeout=setTimeout(()=>{let e=this._statusMessageNode;if(null!==e){for(;null!==e.firstChild;)e.removeChild(e.firstChild);e.removeAttribute("data-severity"),this._statusMessageTimeout=null}},i))}}_applyMode(e){let t=this._canvasHost.querySelector(".hw-editor-view");if(null===t)return;let i=(t.getAttribute("class")??"").split(/\s+/).filter(e=>!e.startsWith("hw-editor-view--")).join(" ");t.setAttribute("class",`${i} hw-editor-view--${e}`.trim()),this._refreshStatus()}setHelm(e){this.canvas.setHelm(e)}getHelm(){return this.canvas.getHelm()}on(e,t){return this.canvas.on(e,t)}activatePane(e){if(this._paneByName.has(e)||this._tabsByName.has(e)){this._activePane=e;for(let[t,i]of this._paneByName.entries())i.style.display=t===e?"":"none";for(let[t,i]of this._tabsByName.entries()){let n=(i.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-app__tab--active"!==e).join(" ");i.setAttribute("class",t===e?`${n} hw-app__tab--active`:n)}for(let e of this.extraPanes)e.setActive(this._activePane===Ro(e.name))}}getActivePane(){return this._activePane}destroy(){if(!this._destroyed){this._destroyed=!0,null!==this._statusMessageTimeout&&(clearTimeout(this._statusMessageTimeout),this._statusMessageTimeout=null),this._doc.removeEventListener("keydown",this._onDocKeydown,!0);for(let e of this._unsubs)e();for(let e of this.extraPanes)e.destroy();null!==this.atomicStructurePane&&this.atomicStructurePane.destroy(),this.propertiesPane.destroy(),this.notationPane.destroy(),this.sequencePane.destroy(),this.palette.destroy(),this.toolbar.destroy(),this.canvas.destroy(),null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element),this._host}}_resolveVisiblePanes(e){let t=e.service.hasAtomicMolfileProvider(),i=e.visiblePanes??["sequence","helm","properties","atomic"];return t||(i=i.filter(e=>"atomic"!==e)),i}_applyTheme(e){let t="dark"===e.name,i=(this.element.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-app--dark"!==e).join(" ");this.element.setAttribute("class",t?`${i} hw-app--dark`:i)}},Do=class{constructor(e){this.T="ATOM",this.selected=e.selected,this.highlighted=e.highlighted,this.p={x:e.p.x,y:e.p.y},this.elem=e.symbol,this.bio={type:e.biotype,continuousId:e.bio.continuousId,chainId:e.bio.chainId,positionInChain:e.bio.positionInChain,...void 0!==e.bio.annotation?{annotation:e.bio.annotation}:{},...void 0!==e.bio.blobtype?{blobtype:e.bio.blobtype}:{},...void 0!==e.bio.ambiguity?{ambiguity:e.bio.ambiguity}:{},id:e.id},void 0!==e.inlineSource&&(this.inlineSource=e.inlineSource)}biotype(){return this.bio.type}},Fo=class{constructor(e,t,i){this.a1=t,this.a2=i,this.r1=Oo(e.r1),this.r2=Oo(e.r2),this.kind=e.kind}};function Oo(e){switch(e.kind){case"numeric":case"positional":return e.r;default:return 0}}function zo(e){let t=[],i=new Map;for(let n of e.atoms){let e=new Do(n);t.push(e),i.set(n.id,e)}let n=[];for(let t of e.bonds){let e=i.get(t.a1.id),o=i.get(t.a2.id);void 0===e||void 0===o||n.push(new Fo(t,e,o))}return{atoms:t,bonds:n,clone:t=>zo(e),_internalMol:e}}var Go=class{constructor(e,t,i){this._laidMol=null,this._currentHelm="",this._drawOptions={fontsize:14},this._noDraw=!1,this._svgEl=null,this.host=e,this._service=t,this._doc=i?.documentImpl??vn(e),this._width=i?.width??400,this._height=i?.height??100,this._mol=Y(),this._molView=zo(this._mol),this.editor=this._buildEditor()}resizeEditor(e,t){this._width=e,this._height=t,this._redraw()}_buildEditor(){let e=this,t={get noDraw(){return e._noDraw},set noDraw(t){e._noDraw=t},get jsd(){return e.editor}};return{get div(){return e.host},get m(){return e._molView},set m(t){e._molView=t},get helm(){return t},get options(){return{width:e._width,height:e._height}},setData(t,i){if("helm"!==i)throw new Error(`LegacyEditorWrapper: only 'helm' format supported (got '${i}').`);e._setHelm(t)},setHelm(t){e._setHelm(t)},setMol(t){e._mol=t._internalMol,e._molView=e._buildView(e._mol),e._currentHelm=e._service.serialize(e._mol),e._redraw()},getHelm:t=>e._currentHelm,getMolfile:()=>Ji(e._mol),resize(t,i){e._width=t,e._height=i,e._redraw()},setSize(t,i){e._width=t,e._height=i,e._redraw()},redraw(){e._redraw()},reset(){e._mol=Y(),e._laidMol=null,e._molView=zo(e._mol),e._currentHelm="",e._removeSvg()},getFormula:t=>function(e){let t=e=>{let t=qo.indexOf(e);return-1===t?qo.length:t},i=[...e.elements.keys()].sort((e,i)=>{let n=t(e),o=t(i);return n!==o?n-o:e<i?-1:e>i?1:0}),n=[];for(let t of i){let i=e.elements.get(t);n.push(1===i?t:`${t}${i}`)}return n.join("")}(Fi(e._mol)),getMolWeight:()=>Yi(e._mol),getExtinctionCoefficient:()=>Ki(e._mol),getDrawOptions:()=>e._drawOptions}}_setHelm(e){this._currentHelm=e;let t=this._service.parse(e,{mode:"lenient",resolveMonomers:!0});this._mol=t.mol,this._molView=this._buildView(this._mol),this._redraw()}_buildView(e){return this._laidMol=this._noDraw?null:Ut(e),zo(this._laidMol??e)}_redraw(){if(this._noDraw)return void this._removeSvg();if(""===this._currentHelm||null===this._laidMol)return void this._removeSvg();let e=new Set,t=new Set;for(let i of this._molView.atoms){let n=i.bio.id;void 0!==n&&(i.selected&&e.add(n),i.highlighted&&t.add(n))}let i=this._service.renderMolResult(this._laidMol,{width:this._width,height:this._height,maxScale:1/0,showIds:!0,selectedAtomIds:e,highlightedAtomIds:t});this._bakeViewToSurface(i.bbox,i.drawBox),this._mountSvg(i.svg)}_bakeViewToSurface(e,t){if(null===this._laidMol)return;let i=t.scale,n=t.x-e.x*i,o=t.y-e.y*i,r=this._laidMol.atoms,s=this._molView.atoms,a=Math.min(r.length,s.length);for(let e=0;e<a;e++){let t=r[e].p,a=s[e].p;a.x=t.x*i+n,a.y=t.y*i+o}}_mountSvg(e){this._removeSvg();let t=function(e,t,i,n){let o=function(e,t){let i=globalThis.DOMParser;if(void 0===i)return null;try{let n=(new i).parseFromString(t,"image/svg+xml").documentElement;return null==n?null:e.importNode(n,!0)}catch{return null}}(e,t);if(null!==o)return o;let r=e.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(i)),r.setAttribute("height",String(n)),r}(this._doc,e,this._width,this._height);t.setAttribute("pointer-events","none"),null!==this.host.firstChild?this.host.insertBefore(t,this.host.firstChild):this.host.appendChild(t),this._svgEl=t}_removeSvg(){null!==this._svgEl&&null!==this._svgEl.parentNode&&this._svgEl.parentNode.removeChild(this._svgEl),this._svgEl=null}},qo=["C","H","N","O","S","P"],jo=class{constructor(e){this._width=0,this._height=0,this._doc=e}resize(e,t){this._width=e,this._height=t}select(){}dblclick(){}createMonomerDiv(e,t,i){let n=wn(this._doc,"div",{"data-monomer":t,"data-biotype":i,"data-testid":`legacy-mex-monomer-${t}`});return e.appendChild(n),n}getSize(){return{width:this._width,height:this._height}}},Vo=class{constructor(e,t,i){this.toolbarheight=32,this._drawOptions={fontsize:14},this._unsubs=[],this._destroyed=!1,this._host=e,this._service=t,this._doc=i?.documentImpl??vn(e),this._width=i?.width??800,this._height=i?.height??400;let n={service:t};void 0!==i?.initialHelm&&(n.initialHelm=i.initialHelm),void 0!==i?.documentImpl&&(n.documentImpl=i.documentImpl),void 0!==i?.width&&(n.width=i.width),void 0!==i?.height&&(n.height=i.height),this._app=new No(e,n),this.sequence=this._app.sequencePane.element,this.notation=this._app.notationPane.element,this.properties={parent:this._app.propertiesPane.element},this._structureviewHost=wn(this._doc,"div",{class:"hwe-legacy-app__structureview","data-testid":"legacy-app-structureview"}),this._structureviewWrapper=new Go(this._structureviewHost,t,{documentImpl:this._doc}),this.structureview=this._structureviewWrapper,this.mex=new jo(this._doc),this._editorFacade=this._buildEditorFacade();let o=this._editorFacade;this.canvas={get host(){return o.div},get editor(){return o},get helm(){return o.helm},resizeEditor:(e,t)=>{this._resize(e,t)},getHelm:e=>o.getHelm(e),setHelm:e=>{o.setHelm(e)}};let r=()=>{this._structureviewWrapper.editor.setHelm(this._app.getHelm())};this._unsubs.push(this._app.canvas.on("helm:changed",r)),void 0!==i?.initialHelm&&i.initialHelm.length>0&&r()}get editorApp(){return this._app}_buildEditorFacade(){let e=this,t=this._app,i={noDraw:!1,get jsd(){return e._editorFacade}};return{get div(){return t.element},get m(){return e._currentMolView()},set m(e){null!=e&&void 0!==e._internalMol&&t.canvas.setMol(e._internalMol)},get helm(){return i},get options(){return{width:e._width,height:e._height}},setData(e,i){if("helm"!==i)throw new Error(`LegacyAppWrapper: only 'helm' format supported (got '${i}').`);t.setHelm(e)},setHelm(e){t.setHelm(e)},setMol(e){t.canvas.setMol(e._internalMol)},getHelm:e=>t.getHelm(),getMolfile:()=>e._service.getMolfile(t.getHelm()),resize(t,i){e._resize(t,i)},setSize(t,i){e._resize(t,i)},redraw(){t.canvas.redraw()},reset(){t.setHelm("")},getFormula:e=>function(e){let t=[];for(let[i,n]of e.elements.entries())t.push(1===n?i:`${i}${n}`);return t.join("")}(Fi(t.canvas.getMol())),getMolWeight:()=>Yi(t.canvas.getMol()),getExtinctionCoefficient:()=>Ki(t.canvas.getMol()),getDrawOptions:()=>e._drawOptions}}_currentMolView(){let e=zo(this._app.canvas.getMol()),t=this._app.canvas.getSelection();if(!t.isEmpty)for(let i of e.atoms){let e=i.bio.id;"number"==typeof e&&(i.selected=t.atoms.has(e))}return e}_resize(e,t){this._width=e,this._height=t,this._app.canvas.resize(e,t)}calculateSizes(){let e=Yo(this._host.clientWidth,this._width),t=Yo(this._host.clientHeight,this._height);this._resize(e,Math.max(50,t-this.toolbarheight))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();this._unsubs.length=0,this._app.destroy()}}};function Yo(e,t){return"number"!=typeof e||isNaN(e)||e<=0?t:e}var Wo=class{constructor(e,t,i){this._tooltip=null,this._destroyed=!1,this.name=e,this._service=t;let n=i?.documentImpl??globalThis.document??null;if(null===n)throw new Error("LegacyInputWrapper: no Document available.");this._doc=n,this._host=wn(this._doc,"div",{class:"hwe-legacy-input","data-testid":"legacy-input-host"}),this.viewer=new Go(this._host,t,{width:i?.editorOptions?.width??240,height:i?.editorOptions?.height??80,documentImpl:this._doc})}get value(){return this.viewer.editor.getHelm()}set value(e){this._ensureLive(),this.viewer.editor.setHelm(e)}get molValue(){return this.viewer.editor.m}set molValue(e){this._ensureLive(),this.viewer.editor.setMol(e)}redraw(){this._ensureLive(),this.viewer.editor.redraw()}showTooltip(e,t){this._ensureLive(),null!==this._tooltip&&null!==this._tooltip.parentNode&&this._tooltip.parentNode.removeChild(this._tooltip);let i=wn(this._doc,"div",{class:"hwe-legacy-input__tooltip","data-testid":"legacy-input-tooltip",style:`position: absolute; left: ${t.p.x}px; top: ${t.p.y}px;`});"string"==typeof e?i.appendChild(this._doc.createTextNode(e)):i.appendChild(e),this._host.appendChild(i),this._tooltip=i}destroy(){this._destroyed||(this._destroyed=!0,null!==this._tooltip&&null!==this._tooltip.parentNode&&this._tooltip.parentNode.removeChild(this._tooltip),null!==this._host.parentNode&&this._host.parentNode.removeChild(this._host))}getHost(){return this._host}getTooltip(){return this._tooltip}_ensureLive(){if(this._destroyed)throw new Error("LegacyInputWrapper: this instance has been destroyed.");this._service}},Uo=/^R([1-9][0-9]*)$/,Ko=new Set([ne.PEPTIDE,ne.RNA,ne.CHEM,ne.BLOB]),Xo=new Set(["Backbone","Branch","Terminal","Undefined"]);function Qo(e){if("string"!=typeof e.symbol||0===e.symbol.length||"string"!=typeof e.molfile||!Ko.has(e.polymerType)||!Xo.has(e.monomerType))return null;let t=[];for(let i of e.rgroups??[]){if("string"!=typeof i.label||!Uo.test(i.label))continue;let e={label:i.label,capGroupName:"string"==typeof i.capGroupName?i.capGroupName:"",capGroupSMILES:Le(i)??""};"string"==typeof i.alternateId&&(e.alternateId=i.alternateId),t.push(e)}let i={symbol:e.symbol,molfile:e.molfile,polymerType:e.polymerType,monomerType:e.monomerType,rgroups:t};return"string"==typeof e.name&&(i.name=e.name),"string"==typeof e.smiles&&(i.smiles=e.smiles),"string"==typeof e.naturalAnalog&&(i.naturalAnalog=e.naturalAnalog),void 0!==e.meta&&null!==e.meta&&(i.meta={...e.meta}),"string"==typeof e.author&&(i.author=e.author),void 0!==e.createDate&&(i.createDate=e.createDate),"number"==typeof e.id&&(i.id=e.id),i}function Zo(e,t,i){if(e===ne.PEPTIDE)return X;if(e===ne.CHEM)return ee;if(e===ne.BLOB)return te;if(e===ne.RNA){if("Branch"===t)return Z;if("Backbone"===t)return"P"===i||"p"===i?J:Q}return X}var Jo=class{constructor(e,t){this._cache=new Map,this._polymerTypesCache=null,this._version=0,this._base=e,this.source=t??("string"==typeof e.source?e.source:"datagrok-bridge"),this.onChanged=new ae,this._unsub=function(e,t){let i=e.subscribe(t);return()=>{null!=i&&"function"==typeof i.unsubscribe&&i.unsubscribe()}}(e.onChanged,()=>{this._cache.clear(),this._polymerTypesCache=null,this._version+=1,this.onChanged.next({type:"reload"})})}get version(){return this._version}get isEmpty(){return"boolean"==typeof this._base.isEmpty?this._base.isEmpty:0===this.getPolymerTypes().length}getMonomer(e,t){let i=`${e}|${t}`;if(this._cache.has(i))return this._cache.get(i)??null;let n=this._base.getMonomer(e,t),o=null==n?null:this._enrichColors(Qo(n));return this._cache.set(i,o),o}_enrichColors(e){if(null===e)return null;let t=this._base;if("function"!=typeof t.getMonomerColors)return e;let i=Zo(e.polymerType,e.monomerType,e.naturalAnalog),n=null;try{n=t.getMonomerColors(i,e.symbol)}catch{n=null}if(null==n)return e;let o=n.backgroundcolor,r=n.textcolor,s=n.linecolor;if("string"!=typeof o||"string"!=typeof r||"string"!=typeof s)return e;let a={...e.meta??{},colors:{...e.meta?.colors??{},default:{line:s,text:r,background:o}}};return{...e,meta:a}}registerInlineSmilesMonomer(e,t){let i=this._base;var n;"function"==typeof i.getWebEditorMonomer&&i.getWebEditorMonomer((n=e)===ne.PEPTIDE?X:n===ne.RNA?Q:n===ne.CHEM?ee:n===ne.BLOB?te:X,t);let o=i.getMonomer(e,t),r=null==o?null:this._enrichColors(Qo(o));if(null===r)throw new Error(`BridgedMonomerLib: could not register inline SMILES monomer '${t}'`);return this._cache.set(`${e}|${t}`,r),this._cache.set(`${e}|${r.symbol}`,r),r}getMonomerSet(e){let t=new Map;for(let i of this.getPolymerTypes())for(let n of this.getMonomerSymbolsByType(i)){let o=this.getMonomer(i,n);null!==o&&Zo(o.polymerType,o.monomerType,o.naturalAnalog)===e&&t.set(n,o)}return t}getMonomerSymbolsByType(e){return this._base.getMonomerSymbolsByType(e)}getByNaturalAnalog(e,t){let i=[];for(let n of this.getMonomerSymbolsByType(e)){let o=this.getMonomer(e,n);null!==o&&o.naturalAnalog===t&&i.push(o)}return i}getPolymerTypes(){if(null!==this._polymerTypesCache)return this._polymerTypesCache;let e=[],t="function"==typeof this._base.getPolymerTypes?this._base.getPolymerTypes():Object.values(ne);for(let i of t){if(!Ko.has(i))continue;let t=this._base.getMonomerSymbolsByType(i);Array.isArray(t)&&t.length>0&&e.push(i)}return this._polymerTypesCache=e,e}getColors(e,t){let i="dark"===t?Te:Se;return Ie(e,null===e?X:Zo(e.polymerType,e.monomerType,e.naturalAnalog),i)}addMonomer(e){throw new Error("BridgedMonomerLib: mutation is not supported on a Datagrok-bridged library.")}removeMonomer(e,t){return!1}merge(e){throw new Error("BridgedMonomerLib: mutation is not supported on a Datagrok-bridged library.")}toJSON(){let e=[];for(let t of this.getPolymerTypes())for(let i of this.getMonomerSymbolsByType(t)){let n=this.getMonomer(t,i);null!==n&&e.push(n)}return e}destroy(){this._unsub(),this.onChanged.complete(),this._cache.clear()}};function er(e,t){return new Jo(e,t)}var tr=class e{constructor(e){if(this._overriddenFuncs=null,this._originalFuncs=null,this._molfilesEditor=null,this._molfilesEditorHost=null,this._molfilesGcTimer=null,void 0===e.service||null===e.service)throw new TypeError("HelmHelperAdapter: options.service is required");this._service=e.service,this.seqHelper=e.seqHelper??null,this._logger=e.logger??new F,this._bridge=e.monomerLibBridge??(e=>er(e)),this._doc=e.documentImpl??rr()}get service(){return this._service}createHelmInput(e,t){let i={...t};return void 0===i.documentImpl&&null!==this._doc&&(i.documentImpl=this._doc),new Wo(e,this._service,i)}createHelmWebEditor(e,t){let i=e??this._createDetachedHost();return new Go(i,this._service,{...void 0!==t?.width?{width:t.width}:{},...void 0!==t?.height?{height:t.height}:{},...null!==this._doc?{documentImpl:this._doc}:{}})}createWebEditorApp(e,t){return new Vo(e,this._service,{...void 0!==t?{initialHelm:t}:{},...null!==this._doc?{documentImpl:this._doc}:{}})}get originalMonomersFuncs(){return this._originalFuncs}buildMonomersFuncsFromLib(e){let t=this._bridge(e),i=e;return{getMonomer:function(e,n){if("function"==typeof i.getWebEditorMonomer){let t=i.getWebEditorMonomer(e,n);if(null!=t)return t}let{biotype:o,symbol:r}=sr(e,n);if(null===r)return null;let s=(h=r).length>=2&&"["===h.charAt(0)&&"]"===h.charAt(h.length-1)?h.slice(1,h.length-1):h,a=ar(o),l=t.getMonomer(a,s);var h;return null===l?null:lr(l,s)},getMonomerSet:function(e){let{biotype:i}=sr(e,void 0),n=ar(i),o={};for(let e of t.getMonomerSymbolsByType(n)){let i=t.getMonomer(n,e);null!==i&&(o[e]=lr(i,e))}return o}}}overrideMonomersFuncs(e){let t=this._overriddenFuncs;return null===this._originalFuncs&&(this._originalFuncs=t??this._defaultFuncs()),this._overriddenFuncs=e,t??this._originalFuncs}revertOriginalMonomersFuncs(){let e=this._originalFuncs??this._defaultFuncs(),t=this._overriddenFuncs??e;return this._overriddenFuncs=e,this._originalFuncs=null,t}getHoveredAtom(e,t,i,n){let o=new bn(i._internalMol,si).test({x:e,y:t});if(null===o||void 0===o.atom)return null;for(let e of i.atoms)if(e.bio.id===o.atom.id||void 0===e.bio.id&&e.bio.continuousId===o.atom.bio.continuousId)return e;return null}getMolfiles(e){let t=this._ensureMolfilesEditor();t.editor.helm.noDraw=!0;try{let i=[];for(let n of e)"string"==typeof n&&0!==n.length?(t.editor.setHelm(n),i.push(t.editor.getMolfile())):i.push("");return i}finally{t.editor.helm.noDraw=!1,this._scheduleMolfilesEditorGc()}}parse(e,t){return zo(Ut(this._service.parse(e,{mode:"lenient",resolveMonomers:!1}).mol))}removeGaps(e){let t;try{t=this._service.removeGaps(e)}catch(e){throw e instanceof N&&void 0===e.type&&(e.type="HelmNotSupportedError"),e}let i=function(e,t){try{let i=e.parse(t,{mode:"lenient",resolveMonomers:!1});for(let e of i.mol.atoms)if("*"===e.symbol)return!0;return!1}catch{return!1}}(this._service,e);return{srcHelm:t.srcHelm,resHelm:t.resHelm,monomerMap:i?new Map(t.monomerMap):null}}destroy(){null!==this._molfilesGcTimer&&(clearTimeout(this._molfilesGcTimer),this._molfilesGcTimer=null),this._removeMolfilesEditorNow()}_defaultFuncs(){return{getMonomer:(e,t)=>null,getMonomerSet:e=>({})}}_createDetachedHost(){let e=this._doc??rr();if(null===e)throw new Error("HelmHelperAdapter: no Document available");let t=e.createElement("div");return t.style.width="0px",t.style.height="0px",t.style.position="fixed",t}_ensureMolfilesEditor(){if(null!==this._molfilesEditor)return null!==this._molfilesGcTimer&&(clearTimeout(this._molfilesGcTimer),this._molfilesGcTimer=null),this._molfilesEditor;let e=this._createDetachedHost();return this._molfilesEditorHost=e,this._molfilesEditor=new Go(e,this._service,{width:100,height:100,...null!==this._doc?{documentImpl:this._doc}:{}}),this._logger,this._molfilesEditor}_scheduleMolfilesEditorGc(){null!==this._molfilesGcTimer&&clearTimeout(this._molfilesGcTimer),"function"==typeof setTimeout&&(this._molfilesGcTimer=setTimeout(()=>{this._molfilesGcTimer=null,this._removeMolfilesEditorNow()},e._MOLFILES_GC_MS))}_removeMolfilesEditorNow(){this._molfilesEditor=null,null!==this._molfilesEditorHost&&null!==this._molfilesEditorHost.parentNode&&this._molfilesEditorHost.parentNode.removeChild(this._molfilesEditorHost),this._molfilesEditorHost=null}};tr._MOLFILES_GC_MS=1e3;var ir,nr,or=tr;function rr(){return globalThis.document??null}function sr(e,t){if("string"==typeof e)return{biotype:e,symbol:t??null};if(null!==e&&"object"==typeof e&&"ATOM"===e.T){let i=e;return{biotype:i.bio.type,symbol:t??i.elem}}return{biotype:X,symbol:t??null}}function ar(e){switch(e){case X:return ne.PEPTIDE;case Q:case Z:case J:case ie:return ne.RNA;case ee:return ne.CHEM;case te:return ne.BLOB;default:return ne.PEPTIDE}}function lr(e,t){let i={};for(let t of e.rgroups)i[t.label]=t.capGroupName;let n={id:t??e.symbol,m:e.molfile,rs:e.rgroups.length,type:e.polymerType,mt:e.monomerType,at:i};return void 0!==e.name&&(n.n=e.name),void 0!==e.naturalAnalog&&(n.na=e.naturalAnalog),void 0!==e.smiles&&(n.smiles=e.smiles),n}function hr(e,t=!0){if(null==e)return"rgb(100,100,100)";const i=o.Color.fromHtml(e);if(t){const e=o.Color.g(i),t=o.Color.r(i),n=o.Color.b(i),r=Math.sqrt(Math.pow(0-t,2)+Math.pow(0-e,2)+Math.pow(0-n,2));if(r>210)return`rgb(${t/r*210},${e/r*210},${n/r*210})`}return o.Color.toRgb(i)}!function(e){e[e.default=0]="default",e[e.continuous=1]="continuous"}(ir||(ir={})),function(e){e.Sequence="sequence",e.Helm="notation",e.Properties="properties",e.StructureView="structureview"}(nr||(nr={}));class dr{static hashCode(e){let t=0;if(0===e.length)return t;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}}class cr{}class ur extends cr{static get palette(){return ur._pallete||(ur._pallete=ur.buildPalette()),ur._pallete}static buildPalette(){return v().then(e=>{e.awaitLoaded(1/0).then(()=>{const t=e.getMonomerLib();t.onChanged.subscribe(()=>{ur.customMonomerColors={},ur.polymerTypes=t.getPolymerTypes();for(const e of this.polymerTypes){const i=t.getMonomerSymbolsByType(e);for(const n of i){const i=t.getMonomer(e,n);i?.meta?.colors?.default?.background&&(this.customMonomerColors[n]||(this.customMonomerColors[n]={}),this.customMonomerColors[n][e]=hr(i.meta.colors.default.background))}}})})}),[].concat(...Object.values(g.colourPalette))}get(e,t){const i=ur.palette.length,n=ur.customMonomerColors[e],o=t??ne.PEPTIDE;if(n&&n[o])return n[o];const r=dr.hashCode(e)%i;return hr(ur.palette[r])}}ur._pallete=null,ur.customMonomerColors={},ur.polymerTypes=[];class pr extends o.JsInputBase{}async function mr(){const e="Helm",t=o.Func.find({package:e,name:"getHelmHelper"});if(0===t.length)throw new Error(`Package '${e}' must be installed for HelmHelper.`);return(await t[0].prepare().call()).getOutputParamValue()}Error,t.input.helmAsync=async function(e,t){return(await mr()).createHelmInput(e,t)};const fr=/\{(\*\.)+/g,br=/\.(\*\.)+/g,gr=/(\.\*)+\}/g;class Ar extends Error{constructor(e,t){super(e,t)}}const _r=rxjs;class yr{onKeyDown(e,t){}onKeyPress(e,t){}onMouseEnter(e,t){}onMouseLeave(e,t){}onMouseDown(e,t){}onMouseUp(e,t){}onMouseMove(e,t){}onClick(e,t){}onDoubleClick(e,t){}}class vr extends yr{constructor(t,i,n){super(),this.gridCol=t,this.tableCol=i,this.logger=n,this.subs=[],this.dirty=!0,this.destroyed=!1,this.cleanColVersion=-1,this.viewerId=++vr.viewerCounter,this.errors=[],this._onRendered=new _r.Subject,this.tableCol&&this.tableCol.dataFrame&&(this.cleanColVersion=this.tableCol.version,this.subs.push(this.tableCol.dataFrame.onDataChanged.subscribe(()=>{this.tableCol?.version!==this.cleanColVersion&&(this.cleanColVersion=this.tableCol?.version,this.dirty=!0)})),this.subs.push(this.tableCol.dataFrame.onColumnsRemoved.subscribe(e=>{try{this.destroyed||!this.tableCol||this.tableCol.dataFrame||this.destroy()}catch(e){this.logger.error(e)}}))),this.tableCol&&this.subs.push(e.events.onTableRemoved.subscribe(e=>{try{const t=e.args.dataFrame;this.tableCol?.dataFrame.id!==t.id||this.destroyed||this.destroy()}catch(e){this.logger.error(e)}})),this.gridCol&&this.subs.push(e.events.onViewRemoving.subscribe(e=>{try{const t=e.args.view;this.gridCol?.dart&&this.gridCol.grid&&this.gridCol?.grid?.dart&&this.gridCol?.grid?.view?.id===t.id&&!this.destroyed&&this.destroy()}catch(e){this.logger.error(e)}}))}toLog(){return`${this.constructor.name}<${this.viewerId}>`}destroy(){for(const e of this.subs)e.unsubscribe();this.destroyed=!0}invalidateGrid(){this.gridCol&&this.gridCol.dart&&this.gridCol.grid?.invalidate()}reset(){this.dirty=!1}get onRendered(){return this._onRendered}invalidate(e){this.invalidateGrid()}async awaitRendered(e=1e4,t=`${e} timeout`){const i=`${this.toLog()}.awaitRendered()`;if(this.logger.debug(`${i}, start, testEvent before`),await c(this._onRendered,()=>{},()=>{this.invalidate()},e,`${i}, ${t}`),this.errors.length>0){const e=this.errors[0];throw this.errors=[],e}this.logger.debug(`${i}, end`)}}var wr;vr.viewerCounter=-1,new RegExp("[rd]\\((\\w)\\)p?","g"),function(e){e[e.SUGAR=0]="SUGAR",e[e.BASE=1]="BASE",e[e.PHOSPHATE=2]="PHOSPHATE",e[e.TERMINAL_5P=3]="TERMINAL_5P",e[e.TERMINAL_3P=4]="TERMINAL_3P"}(wr||(wr={})),Map;function xr(e,t){try{const i=e.tableColumn;if(!i)return;const n=function(e){return e.temp.MonomerHoverLinks??[]}(i);for(let i=n.length-1;i>=0;--i){const o=n[i],r=e.grid.col(o.targetCol.name);if(r&&!o.handler(e,t,r))break}}catch(e){console.error(e)}}const Cr="bio.macromolecule.highlightMonomers",Er=o.Color.argb(255,255,220,0),kr=o.Color.argb(255,230,140,0);function Br(e,t){return`rgba(${o.Color.r(e)},${o.Color.g(e)},${o.Color.b(e)},${t??.4})`}function Sr(e,t,i,n){function o(n){let o,r;for(let s=0;s<i.atoms.length;++s)if(!n.includes(s)){const n=i.atoms[s].p.x,a=i.atoms[s].p.y,l=Math.sqrt((e-n)**2+(t-a)**2);(void 0===r||r>l)&&(o=s,r=l)}return[o,r]}const[r,s]=o([]),[a,l]=o([r]);let h=null;if(void 0!==r&&void 0!==s){const e=i.atoms[r];void 0!==a&&void 0!==l?s<.45*l&&(h=e):n&&s<.35*n&&(h=e)}return h}function Mr(e,t){const i=t.bio.continuousId-1;let n=t.elem;try{n=e.isDna()||e.isRna()?e.getSplittedWithSugarsAndPhosphates().getCanonical(i):e.getSplitted().getCanonical(i)}catch(e){}return{position:t.bio.continuousId-1,symbol:n,biotype:t.bio.type}}class Tr extends vr{cacheEnabled=!0;sysMonomerLib=null;helmHelper=null;serviceByLib=new Map;auxList=new Map;constructor(e,t){super(e,t,ds.logger)}async init(){await Promise.all([(async()=>{const e=await v();this.sysMonomerLib=e.getMonomerLib()})(),(async()=>{this.helmHelper=await mr()})()]),this.subs.push(this.sysMonomerLib.onChanged.subscribe(()=>{for(const e of this.serviceByLib.values())e.destroy();this.serviceByLib.clear(),this.auxList.clear(),this.dirty=!0,this.invalidateGrid()})),this.subs.push(e.events.onCustomEvent("bio-macromolecule-monomer-highlight").subscribe(e=>this.handleHighlightEvent(e))),this.dirty=!0,this.invalidateGrid()}destroy(){for(const e of this.serviceByLib.values())e.destroy();this.serviceByLib.clear(),this.auxList.clear(),super.destroy()}handleHighlightEvent(e){if(!e||!this.tableCol||!this.tableCol.dataFrame)return;if(e.columnName!==this.tableCol.name)return;const t=this.tableCol.dataFrame;if(e.tableId&&t.id!==e.tableId)return;if(e.tableName&&t.name!==e.tableName)return;const i=this.tableCol.temp[Cr]??=new Map;null==e.monomers||0===e.monomers.length?i.delete(e.rowIdx):i.set(e.rowIdx,{monomers:e.monomers.slice(),fillColor:e.fillColor,strokeColor:e.strokeColor}),this.invalidateGrid()}getHighlightForRow(e){if(null==e)return null;const t=this.tableCol.temp[Cr];return t?.get(e)??null}getMonomerLib(){return this.tableCol.temp[".mm.cellRenderer.overriddenLibrary"]??this.sysMonomerLib}getService(e){const t=e.source;let i=this.serviceByLib.get(t);return void 0===i&&(i=new sn({monomerLib:er(e)}),this.serviceByLib.set(t,i)),i}reset(){super.reset(),this.auxList=new Map,this.invalidateGrid()}render(e,t,i,n,r,s,a){const l=s.cell?.value;if(!l||null===this.sysMonomerLib)return;if(n<5||r<5)return;const h=window.devicePixelRatio,d=this.getService(this.getMonomerLib());e.save();try{e.resetTransform();const a=!(!this.gridCol?.dart||this.gridCol.grid?.canvas!==e.canvas),c={x:(a?s.bounds.x:t)*h,y:(a?s.bounds.y:i)*h,width:n*h,height:r*h},u=d.renderToCanvas(e,l,c,{maxScale:1/0,showIds:!1,showAnnotations:!0}),p={molView:zo(u.mol),bBox:new o.Rect(u.bbox.x,u.bbox.y,u.bbox.width,u.bbox.height),dBox:new o.Rect(u.drawBox.x,u.drawBox.y,u.drawBox.width,u.drawBox.height),cellHDev:r*h};this.auxList.set(l,p),this.drawHighlightOverlay(e,p,s.tableRowIndex)}catch(e){const[t,i]=m(e);this.logger.error(t,void 0,i)}finally{e.restore()}this._onRendered.next()}drawHighlightOverlay(e,t,i){const n=this.getHighlightForRow(i);if(!n||!n.monomers||0===n.monomers.length)return;const o=t.molView?.atoms;if(!o||0===o.length)return;if(t.bBox.width<=0||t.bBox.height<=0)return;const r=t.dBox.width/t.bBox.width,s=t.dBox.height/t.bBox.height,a=(r+s)/2,l=this.estimateMonomerRadiusModel(t),h=Math.max(6,l*a*.7),d=Math.max(1.5,.35*h),c=Br(n.fillColor??Er,.2),u=Br(n.strokeColor??kr);e.save();try{e.lineWidth=d,e.strokeStyle=u,e.fillStyle=c;for(const i of n.monomers){const n=o[i];if(!n||!n.p)continue;const a=t.dBox.x+(n.p.x-t.bBox.x)*r,l=t.dBox.y+(n.p.y-t.bBox.y)*s;e.beginPath(),e.arc(a,l,h,0,2*Math.PI),e.fill(),e.stroke()}}finally{e.restore()}}estimateMonomerRadiusModel(e){const t=e.molView?.bonds,i=[];if(t&&t.length>0)for(const e of t){const t=e?.a1?.p,n=e?.a2?.p;if(!t||!n)continue;const o=Math.hypot(t.x-n.x,t.y-n.y);o>0&&i.push(o)}if(i.length>0)return i.sort((e,t)=>e-t),.55*i[Math.floor(i.length/2)];const n=Math.max(1,e.molView?.atoms?.length??1);return.45*Math.sqrt(e.bBox.width*e.bBox.height/n)}onMouseMove(e,i){if(!e.cell?.value||i.buttons)return;const n=this.auxList.get(e.cell.value);if(!n)return;const o=`${this.toLog()}.onMouseMove()`,r=window.devicePixelRatio,s=e.bounds,a=(i.offsetX-s.x)*r,l=(i.offsetY-s.y)*r,h=n.dBox.x-s.x*r,d=n.dBox.y-s.y*r,c=n.bBox.x+(a-h)*n.bBox.width/n.dBox.width,u=n.bBox.y+(l-d)*n.bBox.height/n.dBox.height,p=n.cellHDev*n.bBox.height/n.dBox.height;if(!n.molView)return void this.logger.warning(`${o}, editorMol of the cell not found.`);const m=Sr(c,u,n.molView,p);let f=null;if(m&&this.helmHelper&&null!=e.tableRowIndex){f=Mr(this.helmHelper.seqHelper.getSeqHandler(this.tableCol).getValue(e.tableRowIndex),m);const n=this.tableCol.temp[".mm.cellRenderer.overriddenLibrary"]??ds.monomerLib,o=n?n.getTooltip(f.biotype,f.symbol):t.divText("Monomer library is not available");t.tooltip.show(o,i.x+16,i.y+16)}else t.tooltip.hide();xr(e,f),i.preventDefault(),i.stopPropagation()}onMouseLeave(e,t){xr(e,null)}static getOrCreate(e){const[t,i,n]=function(e){let t=null,i=null;try{i=e.dart?e.gridColumn:null,t=i?i.temp:null}catch{[i,t]=[null,null]}const n=e.cell.column;if(t=t??(n?n.temp:null),!t)throw new Error("Grid cell renderer back store (GridColumn or Column) not found.");return[i,n,t]}(e);let o=n.rendererBack;return o||(o=n.rendererBack=new Tr(t,i),o.init().then(()=>{})),o}}class Ir extends o.GridCellRenderer{get name(){return"helm"}get cellType(){return"helm"}get defaultWidth(){return 400}get defaultHeight(){return 100}onMouseMove(e,t){try{Tr.getOrCreate(e).onMouseMove(e,t)}catch(e){const[t,i]=m(e);ds.logger.error(t,void 0,i)}}onMouseLeave(e,t){try{Tr.getOrCreate(e).onMouseLeave(e,t)}catch(e){const[t,i]=m(e);ds.logger.error(t,void 0,i)}finally{t.preventDefault(),t.stopPropagation()}}render(e,t,i,n,o,r,s){const a=36/window.devicePixelRatio;n<a||o<a||Tr.getOrCreate(r).render(e,t,i,n,o,r,s)}}function Lr(e){var t;return"string"==typeof e||e instanceof String?e:("object"==typeof e||e instanceof Object)&&"$thrownJsError"in e?Lr(e.$thrownJsError):e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e.toString()}class $r{constructor(e,t,i=""){this.target=e,this.debugEnabled=t,this.prefix=i}error(e,t,i){return this.target.error(this.prefix+e,t,i)}warning(e,t){return this.target.warning(this.prefix+e,t)}info(e,t){return this.target.info(this.prefix+e,t)}debug(e,t){if(this.debugEnabled)return this.target.debug(this.prefix+e,t)}}class Pr extends o.Package{_helmHelper;get helmHelper(){if(!this._helmHelper)throw new Error("Package Helm .helmHelper is not initialized");return this._helmHelper}get seqHelper(){return this.helmHelper.seqHelper}_libHelper;constructor(e={debug:!1}){super(),super._logger=new $r(super.logger,e.debug)}get monomerLib(){if(!this._libHelper)throw new Error("Helm: _package.libHelper is not initialized yet");return this._libHelper.getMonomerLib()}_monomerLibSub;_initialized=!1;completeInit(e,t){this._helmHelper=e,this._libHelper=t;const i=this.monomerLib;this._monomerLibSub=i.onChanged.subscribe(this.monomerLibOnChangedHandler.bind(this)),this._initialized=!0}monomerLibOnChangedHandler(){const t="Helm: _package.monomerLibOnChangedHandler()";try{const i=this.monomerLib.getSummaryObj(),n=0==Object.keys(i).length,o=n?"empty":Object.entries(i).map(([e,t])=>`${e}: ${t}`).join(", ");ds.logger.debug(`${t}, start, lib: { ${o} }`);const r=n?"empty":Object.entries(i).map(([e,t])=>`${e} ${t}`).join("<br />"),s=`Monomer lib updated:<br /> ${r}`;e.shell.info(s)}catch(e){const i=Lr(e);console.error(`${t} error:\n`+i)}}}class Rr extends pr{helmHelper;monomerLib;options;logger;get inputType(){return"Macromolecule"}get dataType(){return o.TYPE.STRING}getInput(){return this.viewerHost}_seqValue;getValue(){return this._seqValue}setValue(e){this._seqValue=e,this.viewer.editor.setHelm(this._seqValue.helm)}getStringValue(){return this._seqValue?.helm??""}setStringValue(e){if(!this._seqValue){let t;o.DataFrame.fromColumns([t=o.Column.fromList(o.COLUMN_TYPE.STRING,"seq",[e])]),t.semType=o.SEMTYPE.MACROMOLECULE,t.meta.units=l.HELM;const i=this.helmHelper.seqHelper.getSeqHandler(t);this._seqValue=i.getValue(0)}this.viewer.editor.setHelm(this._seqValue.value=e)}get molValue(){return this.viewer.editor.m}set molValue(e){this.viewer.editor.setMol(e),this._seqValue.value=this.viewer.editor.getHelm()}get onMouseMove(){return(0,_r.fromEvent)(this.viewer.host,"mousemove")}get onClick(){return(0,_r.fromEvent)(this.viewer.host,"click")}viewerHost;viewer;editHintDiv;helmString="";helmSelection;subs;constructor(e,i,n,o,r=ds.logger){super(),this.helmHelper=e,this.monomerLib=i,this.options=o,this.logger=r,n&&(this.captionLabel.innerText=n);const s=o?.editorOptions?.height??250,a=o?.editorOptions?.width??250;this.viewerHost=t.div([],{classes:"ui-input-editor",style:{width:`${a}px`,height:`${s}px`,minWidth:`${a}px`,minHeight:`${s}px`,overflow:"hidden"}}),this.viewer=this.helmHelper.createHelmWebEditor(this.viewerHost,{...o?.editorOptions,width:a,height:s}),this.editHintDiv=t.divH([t.link("Click to edit",()=>{this.viewer.host.click()},void 0,{})],{style:{display:"none",position:"absolute",top:"0",right:"0"}}),this.subs=[],this.subs.push(this.monomerLib.onChanged.subscribe(()=>this.viewer.editor.redraw())),(0,_r.fromEvent)(this.viewer.host,"mousemove").subscribe(this.viewerOnMouseMove.bind(this)),(0,_r.fromEvent)(this.viewer.host,"mouseenter").subscribe(this.viewerOnMouseEnter.bind(this)),(0,_r.fromEvent)(this.viewer.host,"mouseleave").subscribe(this.viewerOnMouseLeave.bind(this)),(0,_r.fromEvent)(this.viewer.host,"click").subscribe(this.viewerOnClick.bind(this)),this.subs.push(t.onSizeChanged(this.input).subscribe(()=>{const e=this.input.clientWidth,t=this.input.clientHeight;e>0&&t>0&&this.viewer.editor.setSize(e,t)})),this.root.classList.add("ui-input-helm"),this.root.append(this.viewerHost,this.editHintDiv)}detach(){for(const e of this.subs)e.unsubscribe()}toLog(){return"Helm: HelmInput<#>"}static create(e,t,i,n){const o=new Rr(e,t,i,n);return null!=n?.value&&(o.value=n.value),o}redraw(){this.viewer.editor.redraw()}showTooltip(e,i){const n=1.2*this.viewer.editor.getDrawOptions().fontsize,o=this.input.getBoundingClientRect();t.tooltip.show(e,o.left+i.p.x+n,o.top+i.p.y+n)}viewerOnClick(e){t.tooltip.hide(),0!=this.options?.editable&&this.showEditorDialog()}viewerOnMouseMove(e){this.toLog();const i=Sr(e.offsetX,e.offsetY,this.viewer.editor.m,this.viewer.editor.div.clientHeight);if(i){const n=Mr(this.value,i),o=ds.monomerLib,r=o?o.getTooltip(n.biotype,n.symbol):t.divText("Monomer library is not available");this.showTooltip(r,i),e.preventDefault(),e.stopPropagation()}else t.tooltip.hide()}viewerOnMouseEnter(e){0!=this.options?.editable&&this.showEditHint()}viewerOnMouseLeave(e){this.editHintDiv.contains(e.relatedTarget)||0!=this.options?.editable&&this.hideEditHint()}showEditHint(){this.editHintDiv.style.removeProperty("display")}hideEditHint(){this.editHintDiv.style.display="none"}showEditorDialog(){const i=t.div();i.style.height="100%";const n=this.helmHelper.createWebEditorApp(i,this.viewer.editor.getHelm()),o=()=>{s()(i).empty()};t.dialog({showHeader:!1,showFooter:!0}).add(i).onOK(()=>{try{const e=n.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.viewer.editor.setHelm(e),this.helmString=e;const t=n.canvas.helm.jsd.m.atoms;this.helmSelection=[];for(let e=0;e<t.length;e++)t[e].selected&&this.helmSelection.push(e),this.viewer.editor.m.atoms[e].highlighted=t[e].selected;this.viewer.editor.redraw()}catch(t){!function(t){const[i,n]=m(t);ds.logger.error(i,void 0,n),e.shell.error(i)}(t)}finally{o()}}).onCancel(()=>{o()}).show({modal:!0,fullScreen:!0})}}class Hr{seqHelper;logger;rdKitModule;static instanceCount=0;constructor(e,t,i){if(this.seqHelper=e,this.logger=t,this.rdKitModule=i,++Hr.instanceCount>1)throw new Error("HelmHelper must be a single.")}_editorAdapter=null;get editorAdapter(){if(null===this._editorAdapter){const e=ds._libHelper.getMonomerLib(),t=new Map;t.set("FASTA",async e=>this._toFastaProvider(e)),t.set("BILN",async e=>this._toBilnProvider(e)),t.set("Molecular Structure",async e=>this._atomicLevelProvider(e)),t.set("Composition Analysis",async e=>this._compositionAnalysisProvider(e));const i=new sn({monomerLib:er(e),rdkitModule:this.rdKitModule,extraPanes:t});this._editorAdapter=new or({service:i,seqHelper:this.seqHelper})}return this._editorAdapter}createHelmInput(e,t){try{const i=ds._libHelper.getMonomerLib();return Rr.create(this,i,e,t)}catch(e){const[t,i]=m(e);throw this.logger.error(`Helm: HelmHelper.createHelmInput(), Error: ${t}`,void 0,i),e}}createHelmWebEditor(e,t){return this.editorAdapter.createHelmWebEditor(e,{...void 0!==t?.width?{width:t.width}:{},...void 0!==t?.height?{height:t.height}:{}})}createWebEditorApp(e,t){return this.editorAdapter.createWebEditorApp(e,t)}get originalMonomersFuncs(){return this.editorAdapter.originalMonomersFuncs}revertOriginalMonomersFuncs(){return this.editorAdapter.revertOriginalMonomersFuncs()}overrideMonomersFuncs(e){return this.editorAdapter.overrideMonomersFuncs(e)}buildMonomersFuncsFromLib(e){return this.editorAdapter.buildMonomersFuncsFromLib(e)}getHoveredAtom(e,t,i,n){return Sr(e,t,i,n)}getMolfiles(e){return this.editorAdapter.getMolfiles(e)}parse(e,t){return this.editorAdapter.parse(e,t)}removeGaps(e){return this.editorAdapter.removeGaps(e)}_singeHelmDf=null;_getSingleHelmDf(e){if(null===this._singeHelmDf){const t=o.Column.fromStrings("helm",[e]);t.setTag("quality",o.SEMTYPE.MACROMOLECULE),t.setTag("units","helm"),t.setTag(".alphabetIsMultichar","true"),t.setTag("alphabet","UN");const i=Math.floor(.6*window.innerWidth);t.setTag(".toAtomicWidgetWidth",i.toString()),this._singeHelmDf=o.DataFrame.fromColumns([t])}return this._singeHelmDf.col("helm").set(0,e),this._singeHelmDf}_singleHelmSh=null;_getSingleHelmDfSh(e){if(!this._singleHelmSh){const t=this._getSingleHelmDf(e);this._singleHelmSh=this.seqHelper.getSeqHandler(t.col("helm"))}return this._singleHelmSh}async _atomicLevelProvider(t){const i=this._getSingleHelmDf(t),n=o.SemanticValue.fromTableCell(i.cell(0,"helm"));return(await e.functions.call("Bio:toAtomicLevelPanel",{sequence:n})).root}async _compositionAnalysisProvider(t){const i=this._getSingleHelmDf(t),n=o.SemanticValue.fromTableCell(i.cell(0,"helm"));return(await e.functions.call("Bio:compositionAnalysisWidget",{sequence:n})).root}_toBilnProvider(e){const i=this.editorAdapter.service.parse(e);if(i.mol.chains.length<1||i.mol.chains.some(e=>e.polymerType!==ne.PEPTIDE))return t.divText("Unsupported sequence for BILN");const n=this._getSingleHelmDfSh(e),o=t.input.textArea("",{});return o.value=n.getConverter(l.BILN)(e),o.input.setAttribute("disabled","true"),o.input.style.width="100%",o.input}_toFastaProvider(e){const i=this.editorAdapter.service.parse(e);if(1!==i.mol.chains.length||i.mol.atoms.length!==i.mol.bonds.filter(e=>"hbond"!==e.kind).length+1)return t.divText("Unsupported sequence for FASTA");const n=this._getSingleHelmDfSh(e),o=t.input.textArea("",{});return o.value=n.getConverter(l.FASTA)(e),o.input.setAttribute("disabled","true"),o.input.style.width="100%",o.input}}var Nr=i(72),Dr=i.n(Nr),Fr=i(825),Or=i.n(Fr),zr=i(659),Gr=i.n(zr),qr=i(56),jr=i.n(qr),Vr=i(540),Yr=i.n(Vr),Wr=i(113),Ur=i.n(Wr),Kr=i(130),Xr={};async function Qr(){await ps.initHelm()}function Zr(){return ps.helmCellRenderer()}function Jr(e){ps.editMoleculeCell(e)}function es(e){ps.openEditor(e)}async function ts(e){return await ps.propertiesWidget(e)}function is(e){return ps.getMolfiles(e)}function ns(e,t){return ps.helmInput(e,t)}function os(){return ps.getHelmHelper()}async function rs(){await ps.measureCellRenderer()}async function ss(){await ps.highlightMonomers()}Xr.styleTagTransform=Ur(),Xr.setAttributes=jr(),Xr.insert=Gr().bind(null,"head"),Xr.domAPI=Or(),Xr.insertStyleElement=Yr(),Dr()(Kr.A,Xr),Kr.A&&Kr.A.locals&&Kr.A.locals;var as=function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},ls=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},hs=function(e,t){return function(i,n){t(i,n,e)}};const ds=new Pr;e.decorators||(e.decorators={}),["func","init","param","panel","editor","demo","app","appTreeBrowser","fileHandler","fileExporter","model","viewer","filter","cellRenderer","autostart","dashboard","folderViewer","semTypeDetector","packageSettingsEditor","functionAnalysis","converter","fileViewer","model","treeBrowser","polyfill"].forEach(t=>{e.decorators[t]||(e.decorators[t]=function(e){return function(e,t,i){}})});let cs=null;function us(e,i,n){!function(e,i,n){const o=t.div();o.style.height="100%";const r=e.cell.column,a=ds.seqHelper.getSeqHandler(r),l=ds.helmHelper.createWebEditorApp(o,e&&void 0===n?e.cell.value:i),h=t.dialog({showHeader:!1,showFooter:!0});h.add(o).onOK(()=>{const t=l.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");if(e)if(void 0===n)e.setValue(t);else{const i=a.convertHelmToFastaSeparator(t,n,a.separator);e.setValue(i)}}).show({modal:!0,fullScreen:!0});const d=s()(h.root).find("div").get()[0];d.className=d.className.replace("dlg- ui-form","dlg-ui-form")}(e,i,n)}class ps{static async initHelm(){return null===cs&&(cs=async function(){const t="Helm: _package.initHelm()";ds.logger.debug(`${t}, start`);try{const e=await async function(){const e=o.Func.find({package:"Chem",name:"getRdKitModule"});if(0===e.length)throw new Error('Package "Chem" must be installed for getRdKitModule.');return(await e[0].prepare().call()).getOutputParamValue()}(),t=await async function(){const e=o.Func.find({package:"Bio",name:"getSeqHelper"});if(0===e.length)throw new Error("Package 'Bio' must be installed for SeqHelper.");return(await e[0].prepare().call()).getOutputParamValue()}(),i=await v(),n=new Hr(t,ds.logger,e);ds.completeInit(n,i)}catch(i){const[n,o]=m(i);e.shell.error(`Package 'Helm' init error:\n${n}`);const r=new Error(`${t} error:\n ${n}\n${o}`);throw r.stack=o,r}finally{ds.logger.debug(`${t}, finally`)}ds.logger.debug(`${t}, end`)}()),cs}static helmCellRenderer(){return ds.logger.debug("Helm: _package.getHelmCellRenderer(), start"),new Ir}static editMoleculeCell(e){us(e,void 0,void 0)}static openEditor(t){const i=e.shell.tv.grid.dataFrame,n=i.columns.bySemType("Macromolecule"),r=ds.seqHelper.getSeqHandler(n),s=n.meta.units;if(-1===i.currentRowIdx)return;const a=o.GridCell.fromColumnRow(e.shell.tv.grid,n.name,i.currentRowIdx);s===l.HELM?us(a,void 0,void 0):us(a,r.getConverter(l.HELM)(t.value),n.meta.units)}static async propertiesWidget(e){return async function(e){const i=(await mr()).seqHelper.getSeqHandler(e.cell.column);try{const n=await async function(e,i){const n=t.div([],{style:{width:"0",height:"0"}});document.documentElement.appendChild(n);try{if(e.length>1e3)throw new Ar("Too long sequence to calculate molecular properties.");const t=(i.isHelm()?e:i.getConverter(l.HELM)(e)).replaceAll(fr,"{").replaceAll(br,".").replaceAll(gr,"}").replace("{*}","{}"),o=(await mr()).createHelmWebEditor(n).editor;o.setHelm(t);const r=o.getFormula(!0),s=Math.round(100*o.getMolWeight())/100,a=Math.round(100*o.getExtinctionCoefficient())/100;return{formula:r.replace(/<sub>/g,"").replace(/<\/sub>/g,""),"molecular weight":s,"extinction coefficient":a}}finally{s()(n).empty(),n.remove()}}(e.value,i);return new o.Widget(t.tableFromMap(n,!0))}catch(e){if(e instanceof Ar)return new o.Widget(t.divText(e.message));throw e}}(e)}static getMolfiles(e){const t=e.toList(),i=ds.helmHelper.getMolfiles(t);return o.Column.fromStrings("mols",i)}static helmInput(e,t){return ds.helmHelper.createHelmInput(e,t)}static getHelmHelper(){return ds.helmHelper}static async measureCellRenderer(){const t=e.shell.tv.grid,i=t.columns.byName("sequence").temp.rendererBack;let n=0,o=0;for(let e=0;e<20;++e){const e=window.performance.now();let r;i.cacheEnabled?await c(t.onAfterDrawContent,()=>{r=window.performance.now(),ds.logger.info(`measureCellRenderer() cache enabled, ET: ${r-e} ms`)},()=>{t.invalidate()},5e3):await c(i.onRendered,()=>{r=window.performance.now(),ds.logger.info(`measureCellRenderer() cache disabled , ET: ${r-e} ms`)},()=>{i.invalidate()},5e3),n+=r-e,o++}ds.logger.info(`measureCellRenderer(), avg ET: ${n/o} ms`)}static async highlightMonomers(){const t=o.TaskBarProgressIndicator.create("Test app highlight monomers");try{const t=await ds.files.readCsv("tests/peptide.csv");t.name="peptide.csv",await cs;const i=t.columns.byName("helm");await e.data.detectSemanticTypes(t),await e.functions.call("Bio:toAtomicLevel",{table:t,seqCol:i,nonlinear:!0,highlight:!0}),e.shell.addTableView(t)}finally{t.close()}}}as([e.decorators.init({tags:["init"]}),ls("design:type",Function),ls("design:paramtypes",[]),ls("design:returntype",Promise)],ps,"initHelm",null),as([e.decorators.func({meta:{columnTags:"quality=Macromolecule, units=helm",cellType:"helm",role:"cellRenderer"},tags:["cellRenderer"],outputs:[{name:"result",type:"grid_cell_renderer"}]}),ls("design:type",Function),ls("design:paramtypes",[]),ls("design:returntype",o.GridCellRenderer)],ps,"helmCellRenderer",null),as([e.decorators.func({meta:{columnTags:"quality=Macromolecule, units=helm",role:"cellEditor"},tags:["cellEditor"],description:"Macromolecule"}),hs(0,e.decorators.param({type:"grid_cell"})),ls("design:type",Function),ls("design:paramtypes",[o.GridCell]),ls("design:returntype",void 0)],ps,"editMoleculeCell",null),as([e.decorators.func({meta:{action:"Edit Helm..."},name:"Edit Helm...",description:"Adds editor"}),hs(0,e.decorators.param({options:{semType:"Macromolecule"}})),ls("design:type",Function),ls("design:paramtypes",[o.SemanticValue]),ls("design:returntype",void 0)],ps,"openEditor",null),as([e.decorators.panel({name:"Properties",meta:{role:"widgets",domain:"bio"},tags:["panel","widgets","bio"]}),hs(0,e.decorators.param({options:{semType:"Macromolecule"}})),ls("design:type",Function),ls("design:paramtypes",[o.SemanticValue]),ls("design:returntype",Promise)],ps,"propertiesWidget",null),as([e.decorators.func({name:"Get Molfiles from HELM",description:"Convert a column of HELM macromolecules into a column of molfiles"}),hs(0,e.decorators.param({type:"column",options:{semType:"Macromolecule"}})),ls("design:type",Function),ls("design:paramtypes",[o.Column]),ls("design:returntype",o.Column)],ps,"getMolfiles",null),as([e.decorators.func({meta:{propertyType:"string",semType:"Macromolecule",role:"valueEditor"},tags:["valueEditor"],outputs:[{type:"object",name:"result"}]}),hs(0,e.decorators.param({options:{optional:!0}})),hs(1,e.decorators.param({type:"object",options:{optional:!0}})),ls("design:type",Function),ls("design:paramtypes",[String,Object]),ls("design:returntype",pr)],ps,"helmInput",null),as([e.decorators.func({outputs:[{type:"object",name:"result"}]}),ls("design:type",Function),ls("design:paramtypes",[]),ls("design:returntype",Object)],ps,"getHelmHelper",null),as([e.decorators.func(),ls("design:type",Function),ls("design:paramtypes",[]),ls("design:returntype",Promise)],ps,"measureCellRenderer",null),as([e.decorators.func({name:"Highlight Monomers"}),ls("design:type",Function),ls("design:paramtypes",[]),ls("design:returntype",Promise)],ps,"highlightMonomers",null)})(),helm=n})();
|
|
1
|
+
var helm;(()=>{var e={717(e,t,i){"use strict";i.d(t,{j:()=>o});var n=i(82);async function o(){const e=n.Func.find({package:"Chem",name:"getRdKitModule"});if(0===e.length)throw new Error('Package "Chem" must be installed for getRdKitModule.');return(await e[0].prepare().call()).getOutputParamValue()}},599(e,t,i){"use strict";i.d(t,{kC:()=>r.kC});var n,o,r=i(199);!function(e){e[e.default=0]="default",e[e.continuous=1]="continuous"}(n||(n={})),function(e){e.Sequence="sequence",e.Helm="notation",e.Properties="properties",e.StructureView="structureview"}(o||(o={}))},124(e,t,i){"use strict";i.d(t,{KB:()=>r,b2:()=>s});var n=i(389),o=i(82);class r extends o.JsInputBase{}async function s(){const e="Helm",t=o.Func.find({package:e,name:"getHelmHelper"});if(0===t.length)throw new Error(`Package '${e}' must be installed for HelmHelper.`);return(await t[0].prepare().call()).getOutputParamValue()}Error,n.input.helmAsync=async function(e,t){return(await s()).createHelmInput(e,t)}},971(e,t,i){"use strict";i.d(t,{pj:()=>o});var n=i(82);async function o(){const e=n.Func.find({package:"Bio",name:"getMonomerLibHelper"});if(0===e.length)throw new Error('Package "Bio" must be installed for MonomerLibHelper.');return(await e[0].prepare().call()).getOutputParamValue()}},439(e,t,i){"use strict";i.d(t,{Hi:()=>n,_S:()=>l});var n,o,r,s=i(738);!function(e){e.FASTA="fasta",e.SEPARATOR="separator",e.HELM="helm",e.CUSTOM="custom",e.BILN="biln"}(n||(n={})),function(e){e.DNA="DNA",e.RNA="RNA",e.PT="PT",e.UN="UN"}(o||(o={})),function(e){e.aligned="aligned",e.alphabet="alphabet",e.alphabetSize=".alphabetSize",e.alphabetIsMultichar=".alphabetIsMultichar",e.separator="separator",e.isHelmCompatible=".isHelmCompatible",e.positionNames=".positionNames",e.positionLabels=".positionLabels",e.regions=".regions",e.positionShift=".positionShift",e.selectedPosition=".selectedPosition",e.polymerTypeColumnName=".polymerTypeColumnName",e.annotations=".annotations",e.numberingScheme=".numberingScheme",e.annotationColumnName=".annotationColumnName"}(r||(r={}));const a=new class{constructor(){this.fasta={peptide:new Set(["G","L","Y","S","E","Q","D","N","F","A","K","R","H","C","V","P","W","I","M","T"]),dna:new Set(["A","C","G","T"]),rna:new Set(["A","C","G","U"])}}},l=(new s.aD(o.PT,a.fasta.peptide,.5),new s.aD(o.DNA,a.fasta.dna,.55),new s.aD(o.RNA,a.fasta.rna,.55),"");n.FASTA,n.SEPARATOR,n.HELM,n.BILN},3(e,t,i){"use strict";i.d(t,{Hi:()=>n.Hi});var n=i(439);i(291)},738(e,t,i){"use strict";i.d(t,{aD:()=>n}),i(439);class n{constructor(e,t,i){this.name=e,this.alphabet=t,this.cutoff=i}}},291(e,t,i){"use strict";var n=i(82);i(991),i(738),i(439);class o{static makePalette(e,t=!1,i=o){const n={};return e.forEach(e=>{const i=e[0],o=e[1];i.forEach((e,i)=>{n[e]=this.colourPalette[o][t?0:i]})}),new i(n)}constructor(e){this._palette=e}get(e,t){return this._palette[e]}}o.undefinedColor="rgb(100,100,100)",o.colourPalette={orange:["rgb(255,187,120)","rgb(245,167,100)","rgb(235,137,70)","rgb(205, 111, 71)"],all_green:["rgb(44,160,44)","rgb(74,160,74)","rgb(23,103,57)","rgb(30,110,96)","rgb(60,131,95)","rgb(24,110,79)","rgb(152,223,138)","rgb(182, 223, 138)","rgb(152, 193, 138)"],all_blue:["rgb(31,119,180)","rgb(23,190,207)","rgb(122, 102, 189)","rgb(158,218,229)","rgb(141, 124, 217)","rgb(31, 120, 150)"],magenta:["rgb(162,106,192)","rgb(197,165,224)","rgb(208,113,218)"],red:["rgb(214,39,40)","rgb(255,152,150)"],st_blue:["rgb(23,190,207)","rgb(158,218,229)","rgb(31,119,180)"],dark_blue:["rgb(31,119,180)","rgb(31, 120, 150)"],light_blue:["rgb(23,190,207)","rgb(158,218,229)","rgb(108, 218, 229)","rgb(23,190,227)"],lilac_blue:["rgb(124,102,211)","rgb(149,134,217)","rgb(97, 81, 150)"],dark_green:["rgb(23,103,57)","rgb(30,110,96)","rgb(60,131,95)","rgb(24,110,79)"],green:["rgb(44,160,44)","rgb(74,160,74)"],light_green:["rgb(152,223,138)","rgb(182, 223, 138)","rgb(152, 193, 138)"],st_green:["rgb(44,160,44)","rgb(152,223,138)","rgb(39, 174, 96)","rgb(74,160,74)"],pink:["rgb(247,182,210)"],brown:["rgb(140,86,75)","rgb(102, 62, 54)"],gray:["rgb(127,127,127)","rgb(199,199,199)","rgb(196,156,148)","rgb(222, 222, 180)"],yellow:["rgb(188,189,34)"],white:["rgb(230,230,230)"]};class r extends o{static get Lesk(){return void 0===this.lesk&&(this.lesk=this.makePalette([[["G","A","S","T"],"orange"],[["C","V","I","L","P","F","Y","M","W"],"all_green"],[["N","Q","H"],"magenta"],[["D","E"],"red"],[["K","R"],"all_blue"]],!1,r)),this.lesk}static get GrokGroups(){return void 0===this.grokGroups&&(this.grokGroups=this.makePalette([[["C","U"],"yellow"],[["G","P"],"red"],[["A","V","I","L","M","F","Y","W"],"all_green"],[["R","H","K"],"light_blue"],[["D","E"],"dark_blue"],[["S","T","N","Q"],"orange"]],!1,r)),this.grokGroups}static get RasMol(){return void 0===this.rasMol&&(this.rasMol=new r({D:"#E60A0A",E:"#E60A0A",C:"#E6E600",M:"#E6E600",K:"#145AFF",R:"#145AFF",S:"#FA9600",T:"#FA9600",F:"#3232AA",Y:"#3232AA",N:"#00DCDC",Q:"#00DCDC",G:"#EBEBEB",L:"#0F820F",V:"#0F820F",I:"#0F820F",A:"#C8C8C8",W:"#B45AB4",H:"#8282D2",P:"#DC9682",others:"#BEA06E"})),this.rasMol}get(e){const t=e in r.aaSynonyms?r.aaSynonyms[e]:e;return super.get(t)}}r.aaSynonyms={MeNle:"L",MeA:"A",MeG:"G",MeF:"F"};class s{static getPalette(e="grok"){switch(e){case"grok":return r.GrokGroups;case"lesk":return r.Lesk;default:throw new Error(`ChemPalette: scheme \`${e}\` does not exist`)}}static getInnerOuter(e){let t=0,i="",n="";for(const o of e)"("==o?t++:")"==o?t--:t?i+=o:n+=o;return isNaN(parseInt(i))?[n,i]:[n,""]}static getColorAAPivot(e="",t="grok"){const i=this.getPalette(t);let[n,o]=this.getInnerOuter(e);if(n=n.length>6?`${n.slice(0,3)}...`:n,o=o.length>6?`${o.slice(0,3)}...`:o,1==e.length||"("==e[1]){const t=e[0]?.toUpperCase();return t in i?[i.get(t),t,o,1]:[this.undefinedColor,n,o,1]}if("d"==e[0]&&e[1]in i&&(2==e.length||"("==e[2])){const t=e[1]?.toUpperCase();return t in i?[i.get(t),t,o,2]:[this.undefinedColor,n,o,2]}if(e.substring(0,3)in this.AAFullNames&&(3==e.length||"("==e[3])){const t=this.AAFullNames[e.substring(0,3)];return t in i?[i.get(t),t,o,3]:[this.undefinedColor,n,o,3]}if(e[0]?.toLowerCase()==e[0]&&e.substring(1,3)in this.AAFullNames&&(4==e.length||"("==e[4])){const t=this.AAFullNames[e.substring(1,3)];return t in i?[i.get(t),t,o,4]:[this.undefinedColor,n,o,4]}return[this.undefinedColor,n,o,0]}}s.SemType="Aminoacids",s.SemTypeMultipleAlignment="AminoacidsMultipleAlignment",s.undefinedColor="rgb(100,100,100)",s.Names={G:"Glycine",L:"Leucine",Y:"Tyrosine",S:"Serine",E:"Glutamic acid",Q:"Glutamine",D:"Aspartic acid",N:"Asparagine",F:"Phenylalanine",A:"Alanine",K:"Lysine",R:"Arginine",H:"Histidine",C:"Cysteine",V:"Valine",P:"Proline",W:"Tryptophan",I:"Isoleucine",M:"Methionine",T:"Threonine"},s.AASmiles={G:"NCC(=O)O",L:"N[C@H](CC(C)C)C(=O)O",Y:"NC(CC1=CC=C(O)C=C1)C(=O)O",S:"NC(CO)C(=O)O",E:"N[C@@H](CCC(O)=O)C(=O)O",Q:"N[C@@H](CCC(N)=O)C(=O)O",D:"N[C@@H](CC(O)=O)C(=O)O",N:"N[C@@H](CC(N)=O)C(=O)O",F:"NC(CC1=CC=CC=C1)C(=O)O",A:"N[C@H](C)C(=O)O",K:"NC(CCCCN)C(=O)O",R:"N[C@H](CCCNC(=N)C)C(=O)O",H:"NC(CC1=CN=C[N]1)C(=O)O",C:"N[C@@H](CS)C(=O)O",V:"NC(C(C)C)C(=O)O",P:"N(CCC1)C1C(=O)O",W:"N[C@@H](Cc1c2ccccc2n([H])c1)C(=O)O",I:"N[C@H]([C@H](C)CC)C(=O)O",M:"NC(CCSC)C(=O)O",T:"NC(C(O)C)C(=O)O"},s.AASmilesTruncated={G:"*C*",L:"CC(C)C[C@H](*)*",Y:"C1=CC(=CC=C1CC(*)*)O",S:"OCC(*)C*",E:"*[C@@H](CCC(O)=O)*",Q:"*N[C@@H](CCC(N)=O)*",D:"*[C@@H](CC(O)=O)*",N:"*[C@@H](CC(N)=O)*",F:"C1=CC=C(C=C1)CC(*)*",A:"C[C@H](*)*",K:"C(CCN)CC(*)*",R:"*[C@H](CCCNC(=N)C)*",H:"C1=C(NC=N1)CC(*)*",C:"C([C@@H](*)*)S",V:"CC(C)C(*)*",P:"C1CCN(*)C1*",W:"*[C@@H](Cc1c2ccccc2n([H])c1)*",I:"CC[C@H](C)[C@H](*)*",M:"CSCCC(*)*",T:"CC(O)C(*)*"},s.AAFullNames={Ala:"A",Arg:"R",Asn:"N",Asp:"D",Cys:"C",Gln:"Q",Glu:"E",Gly:"G",His:"H",Ile:"I",Leu:"L",Lys:"K",Met:"M",Phe:"F",Pro:"P",Ser:"S",Thr:"T",Trp:"W",Tyr:"Y",Val:"V"};class a{}a.SemType="Nucleotides",a.SemTypeMultipleAlignment="NucleotidesMultipleAlignment",a.Names={A:"Adenine",C:"Cytosine",G:"Guanine",T:"Thymine",U:"Uracil"};var l=i(971),h=i(599);function d(e,t=!0){if(null==e)return"rgb(100,100,100)";const i=n.Color.fromHtml(e);if(t){const e=n.Color.g(i),t=n.Color.r(i),o=n.Color.b(i),r=Math.sqrt(Math.pow(0-t,2)+Math.pow(0-e,2)+Math.pow(0-o,2));if(r>210)return`rgb(${t/r*210},${e/r*210},${o/r*210})`}return n.Color.toRgb(i)}class c{static hashCode(e){let t=0;if(0===e.length)return t;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t|=0;return t}}class u{}class p extends u{static get palette(){return p._pallete||(p._pallete=p.buildPalette()),p._pallete}static buildPalette(){return(0,l.pj)().then(e=>{e.awaitLoaded(1/0).then(()=>{const t=e.getMonomerLib();t.onChanged.subscribe(()=>{p.customMonomerColors={},p.polymerTypes=t.getPolymerTypes();for(const e of this.polymerTypes){const i=t.getMonomerSymbolsByType(e);for(const n of i){const i=t.getMonomer(e,n);i?.meta?.colors?.default?.background&&(this.customMonomerColors[n]||(this.customMonomerColors[n]={}),this.customMonomerColors[n][e]=d(i.meta.colors.default.background))}}})})}),[].concat(...Object.values(o.colourPalette))}get(e,t){const i=p.palette.length,n=p.customMonomerColors[e],o=t??h.kC.PEPTIDE;if(n&&n[o])return n[o];const r=c.hashCode(e)%i;return d(p.palette[r])}}p._pallete=null,p.customMonomerColors={},p.polymerTypes=[]},312(e,t,i){"use strict";i.d(t,{Q:()=>o});var n=i(82);async function o(){const e=n.Func.find({package:"Bio",name:"getSeqHelper"});if(0===e.length)throw new Error("Package 'Bio' must be installed for SeqHelper.");return(await e[0].prepare().call()).getOutputParamValue()}},130(e,t,i){"use strict";i.d(t,{A:()=>a});var n=i(354),o=i.n(n),r=i(314),s=i.n(r)()(o());s.push([e.id,'/* T-0609 / Phase 19 (T-1902) / Phase 28 (T-2801, T-2804) --\n * Default editor stylesheet. SINGLE source of truth.\n *\n * Build pipeline:\n * 1. tsup copies this file byte-for-byte to `dist/editor.css`\n * (see `tsup.config.ts` -- onSuccess hook).\n * 2. `package.json#exports."./styles.css"` maps the public import\n * `@datagrok-libraries/hwe/styles.css` to `dist/editor.css`, so\n * library consumers do `import \'@datagrok-libraries/hwe/styles.css\';`\n * via their bundler (vite, webpack, rollup, etc.).\n * 3. apps/demo imports this file directly with a relative path\n * (`import \'../../../src/editor/styles/editor.css\';` in main.ts)\n * so vite serves source CSS in dev and bundles it in prod.\n *\n * Phase 28 removed the previous runtime injection path\n * (`injectAppStyles` + `editor-css.generated.ts` TS mirror). Reason:\n * dual delivery was a recurring drift hazard. The bundler is now the\n * SINGLE CSS-delivery channel; tests use `mountEditorCss` (in\n * `tests/helpers/load-css.ts`) to read this file directly when\n * stylesheet-text or `getComputedStyle` checks are needed in linkedom.\n */\n\n.hw-app {\n --hw-bg: #ffffff;\n --hw-fg: #1a1a1a;\n --hw-muted: #6c757d;\n --hw-accent: #1f5fcd;\n --hw-selection: #FFD29B;\n --hw-border: #d8d8d8;\n --hw-border-subtle: #e9ecef;\n --hw-tile-hover: #f1f3f5;\n --hw-toolbar-bg: #f4f5f7;\n --hw-pane-bg: #fafbfc;\n --hw-error: #cc0000;\n /* T-3517 -- toolbar icon stroke colour. Datagrok-style neutral grey\n (icons read as quiet chrome until hovered, then darken to --hw-fg). */\n --hw-icon: #6b7178;\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-sizing: border-box;\n}\n.hw-app--dark {\n --hw-bg: #1a1d23;\n --hw-fg: #e0e0e0;\n --hw-muted: #9aa1a8;\n --hw-accent: #6699ff;\n --hw-selection: #FFD29B;\n --hw-border: #3a3f47;\n --hw-border-subtle: #2c3037;\n --hw-tile-hover: #262a31;\n --hw-toolbar-bg: #22252b;\n --hw-pane-bg: #1f2228;\n --hw-error: #ff5050;\n --hw-icon: #9aa1a8;\n}\n.hw-app *, .hw-app *::before, .hw-app *::after { box-sizing: border-box; }\n\n.hw-app__toolbar { flex: 0 0 auto; }\n.hw-app__main {\n flex: 1 1 auto;\n display: flex;\n flex-direction: row;\n min-height: 0;\n border-top: 1px solid var(--hw-border);\n}\n.hw-app__palette {\n flex: 0 0 220px;\n border-right: 1px solid var(--hw-border);\n overflow: auto;\n background: var(--hw-pane-bg);\n}\n.hw-app__canvas { flex: 1 1 auto; position: relative; min-width: 0; overflow: hidden; }\n.hw-app__panes { flex: 0 0 auto; border-top: 1px solid var(--hw-border); }\n.hw-app__tabs { display: flex; flex-direction: row; background: var(--hw-toolbar-bg); }\n.hw-app__tab {\n padding: 6px 14px;\n cursor: pointer;\n border: none;\n background: transparent;\n color: var(--hw-fg);\n border-right: 1px solid var(--hw-border);\n font-size: 12px;\n}\n.hw-app__tab--active { background: var(--hw-bg); border-bottom: 2px solid var(--hw-accent); }\n/* Cap the active pane\'s height; taller content scrolls within the pane. */\n.hw-app__pane-body { padding: 8px; min-height: 80px; max-height: 300px; overflow: auto; background: var(--hw-bg); }\n\n.hw-toolbar {\n display: flex;\n flex-direction: row;\n align-items: center;\n gap: 4px;\n padding: 4px 6px;\n background: var(--hw-toolbar-bg);\n}\n.hw-toolbar__btn {\n /* T-3517 -- Datagrok-style flat, borderless icon buttons. The icon\n stroke uses the neutral grey --hw-icon; hover darkens it to --hw-fg\n and adds a soft rounded background, matching Datagrok\'s toolbar. */\n border: 1px solid transparent;\n background: transparent;\n color: var(--hw-icon);\n border-radius: 4px;\n padding: 5px;\n cursor: pointer;\n font-size: 13px;\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: background 120ms, color 120ms;\n}\n.hw-toolbar__btn-icon {\n display: inline-block;\n width: 100%;\n height: 100%;\n color: inherit;\n}\n.hw-toolbar__btn-icon > svg {\n width: 100%;\n height: 100%;\n display: block;\n}\n.hw-toolbar__btn:hover { background: var(--hw-tile-hover, var(--hw-toolbar-bg)); color: var(--hw-fg); }\n.hw-toolbar__btn[disabled] { opacity: 0.4; cursor: default; }\n.hw-toolbar__btn--active {\n border-color: var(--hw-accent);\n background: var(--hw-accent);\n color: #ffffff;\n}\n.hw-toolbar__separator {\n display: inline-block;\n width: 1px;\n height: 18px;\n background: var(--hw-border);\n margin: 0 4px;\n}\n\n.hw-palette {\n display: flex;\n flex-direction: column;\n height: 100%;\n padding: 4px;\n}\n.hw-palette__search {\n width: 100%;\n padding: 4px;\n margin-bottom: 6px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-size: 12px;\n flex: 0 0 auto;\n}\n/* T-1421 / T-1423 -- tab list: horizontal row above the panes. Active\n tab gets a 2 px accent underline that absorbs the 1 px container\n border below via a negative bottom margin so the layout does not\n shift when the active tab changes.\n\n Phase 24 (T-2404): when a library exposes many polymer types\n (Favorites + PEPTIDE + RNA + CHEM + BLOB + G = 6 tabs), they can no\n longer fit horizontally inside the 200 px palette pane and the\n browser shows an unobvious horizontal scrollbar. Switch to\n `flex-wrap: wrap` so overflow tabs wrap onto a second (or third)\n row -- no hidden scrollbar, every tab is always visible. The\n per-tab padding shrinks too so more tabs fit per row before\n wrapping. */\n.hw-palette__tabs {\n display: flex;\n flex-wrap: wrap;\n gap: 2px 4px;\n border-bottom: 1px solid var(--hw-border);\n flex: 0 0 auto;\n /* Defensively: no overflow scrolling -- wrapping is the answer. */\n overflow: hidden;\n}\n.hw-palette__tab {\n /* Phase 24 (T-2404): compact padding + min-width so 6 tabs still fit\n in two rows max within a 200 px palette pane. */\n flex: 0 0 auto;\n padding: 6px 8px;\n cursor: pointer;\n border: none;\n background: transparent;\n font-size: 12px;\n color: var(--hw-muted);\n user-select: none;\n white-space: nowrap;\n min-width: 0;\n}\n.hw-palette__tab:hover {\n color: var(--hw-fg);\n background: var(--hw-tile-hover);\n}\n.hw-palette__tab[aria-selected="true"] {\n color: var(--hw-fg);\n border-bottom: 2px solid var(--hw-accent);\n margin-bottom: -1px;\n font-weight: 600;\n}\n.hw-palette__panes {\n flex: 1 1 auto;\n min-height: 0;\n}\n.hw-palette__pane {\n overflow-y: auto;\n max-height: 100%;\n padding: 4px 6px;\n}\n.hw-palette__pane[hidden] { display: none; }\n.hw-palette__placeholder {\n padding: 12px 6px;\n color: var(--hw-muted);\n font-size: 12px;\n font-style: italic;\n}\n/* T-1423 -- bolder, more separated group headers. */\n.hw-palette__group { margin-bottom: 12px; }\n.hw-palette__group-header {\n font-size: 13px;\n font-weight: 700;\n color: var(--hw-muted);\n padding: 8px 4px 4px;\n margin: 8px 0 4px;\n border-bottom: 1px solid var(--hw-border-subtle);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-palette__group-tiles {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 6px;\n padding: 2px;\n}\n.hw-palette__tiles { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px; }\n.hw-palette__tile {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 48px;\n max-width: none;\n height: 40px;\n padding: 4px 6px;\n border: 2px solid var(--hw-border);\n border-radius: 8px;\n background: #ffffff;\n cursor: grab;\n font-size: 13px;\n font-weight: 600;\n user-select: none;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms, box-shadow 120ms;\n box-sizing: border-box;\n}\n.hw-palette__tile:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);\n}\n.hw-palette__tile[aria-pressed="true"],\n.hw-palette__tile--primed {\n border-color: var(--hw-accent);\n box-shadow: 0 0 0 2px rgba(31, 95, 205, 0.18);\n}\n.hw-palette__tile--favorite { outline: 1px dashed var(--hw-accent); outline-offset: -3px; }\n.hw-palette__tile--low-contrast {\n box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.08);\n}\n.hw-palette__star {\n position: absolute;\n top: 2px;\n right: 4px;\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-palette__tile--favorite .hw-palette__star { color: var(--hw-accent); }\n.hw-palette__label {\n font-weight: 600;\n letter-spacing: 0.02em;\n display: inline-block;\n max-width: 80px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/* Phase 18 (T-1806) / Phase 19 (T-1903) / Phase 20 (T-2002) -- RNA Builder.\n Phase 20 redesign: SVG triplet visualization. Sugar (square),\n linker (circle), base (diamond) -- each clickable to enter pick\n mode. Fills come from the resolved monomer colour palette so the\n preview matches the canvas rendering. */\n.hw-rna-builder {\n display: block;\n /* Phase 21 (T-2101): horizontal margin nudges the builder rightward\n so it visually aligns with the palette tile column below. The\n user reported the SVG sat too far left vs. the tile rows. */\n margin: 4px 8px 12px;\n padding: 8px;\n background: var(--hw-pane-bg, #fafbfc);\n border: 1px solid var(--hw-border-subtle, #e9ecef);\n border-radius: 6px;\n}\n/* T-3513 -- header row holds the title plus the favorite star. */\n.hw-rna-builder__header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n}\n.hw-rna-builder__title {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-rna-builder__header .hw-rna-builder__title {\n margin-bottom: 0;\n}\n/* T-3513 -- favorite star toggling the composed triplet. */\n.hw-rna-builder__fav {\n font-size: 15px;\n line-height: 1;\n cursor: pointer;\n color: var(--hw-muted);\n user-select: none;\n}\n.hw-rna-builder__fav--active { color: var(--hw-accent); }\n.hw-rna-builder__fav--disabled { opacity: 0.35; cursor: default; }\n/* Phase 29 (T-2901) -- Pick-mode hint shown directly under the "RNA\n builder" title while a slot is in pick mode. Replaces the Phase 24\n palette-level reserved-space hint above the search box. The hint\n carries the `hidden` HTML attribute when idle so the SVG triplet\n sits flush against the title (no wasted vertical space). User\n request 2026-05-19: "lets not have that empty space, and just\n display that text in bold below \'RNA BUILDER\' header, inside the\n builder itself." */\n.hw-rna-builder__hint {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-accent);\n margin: 4px 0 -14px;\n}\n.hw-rna-builder__hint[hidden] {\n display: none;\n}\n.hw-rna-builder__triplet {\n display: block;\n width: 100%;\n max-width: 180px;\n height: auto;\n max-height: 10vh;\n margin: 0 auto 6px;\n}\n.hw-rna-builder__bond {\n stroke: var(--hw-fg, #1a1a1a);\n stroke-width: 1.5;\n fill: none;\n}\n.hw-rna-builder__slot {\n cursor: pointer;\n}\n.hw-rna-builder__slot-shape {\n stroke-width: 1.5;\n transition: filter 120ms;\n}\n.hw-rna-builder__slot:hover .hw-rna-builder__slot-shape {\n filter: brightness(1.08);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot-label {\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n /* Phase 21 (T-2102): font-size is set per-label inline via\n setAttribute(\'font-size\', ...) so a long symbol like `[5meC]`\n can scale down. The CSS default below is a safety net for\n pre-T-2102 markup. */\n font-size: 12px;\n font-weight: 700;\n user-select: none;\n pointer-events: none;\n}\n.hw-rna-builder__slot--active .hw-rna-builder__slot-shape,\n.hw-rna-builder__slot[aria-pressed="true"] .hw-rna-builder__slot-shape {\n /* Yellow halo via filter so per-monomer fill / stroke stays intact. */\n filter: drop-shadow(0 0 3px #ffeb3b) drop-shadow(0 0 2px #ffeb3b);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot:focus {\n outline: none;\n}\n.hw-rna-builder__slot:focus-visible .hw-rna-builder__slot-shape {\n stroke: var(--hw-accent);\n stroke-width: 2.5;\n}\n.hw-rna-builder__preview {\n margin: 6px 0;\n font-size: 11px;\n color: var(--hw-fg);\n font-family: ui-monospace, Menlo, Consolas, monospace;\n text-align: center;\n}\n.hw-rna-builder__add {\n display: block;\n width: 100%;\n padding: 4px 8px;\n background: var(--hw-accent);\n color: #ffffff;\n border: 1px solid var(--hw-accent);\n border-radius: 3px;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n}\n.hw-rna-builder__add:hover { opacity: 0.9; }\n.hw-rna-builder__add:active { transform: translateY(1px); }\n\n/* T-3513 -- RNA triplet chips. Small, monospace, wrap into a tight row.\n Used by the RNA pane\'s default-nucleotide row (r(A)p ... r(T)p) and by\n triplet favorites in the Favorites pane. Kept compact because the RNA\n pane\'s vertical space is constrained by the RNA builder above it. */\n.hw-triplet-chips {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n padding: 2px;\n}\n.hw-triplet-chips--defaults {\n margin: 0 0 8px;\n}\n.hw-triplet-chip {\n position: relative;\n display: inline-flex;\n align-items: center;\n gap: 2px;\n height: 22px;\n padding: 0 6px;\n border: 1px solid var(--hw-border);\n border-radius: 11px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 11px;\n font-weight: 600;\n line-height: 1;\n cursor: pointer;\n user-select: none;\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms;\n}\n.hw-triplet-chip:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n}\n.hw-triplet-chip--favorite { border-color: var(--hw-accent); }\n.hw-triplet-chip__star {\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-triplet-chip--favorite .hw-triplet-chip__star { color: var(--hw-accent); }\n.hw-triplet-chip__label { letter-spacing: 0.02em; }\n\n/* Phase 29 (T-2901) -- The Phase 24 palette-level pick-mode hint\n container has been REMOVED. The hint now lives inside the RNA\n Builder as `.hw-rna-builder__hint` (see the rules under the RNA\n Builder block above). The user explicitly reported the\n reserved-space hint above the search box as "wasted space". */\n\n.hw-pane { display: block; }\n.hw-pane__content { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; }\n.hw-pane__notation {\n outline: none;\n border: 1px solid var(--hw-border);\n padding: 4px;\n background: var(--hw-bg);\n}\n.hw-pane__error { color: var(--hw-error); font-size: 11px; margin-top: 4px; display: none; }\n.hw-pane__error--visible { display: block; }\n.hw-pane__prop-row { display: flex; gap: 8px; padding: 2px 0; }\n.hw-pane__prop-label { color: var(--hw-muted); width: 180px; }\n.hw-pane__prop-value { color: var(--hw-fg); }\n.hw-pane__placeholder { color: var(--hw-muted); font-style: italic; }\n\n.hw-pane__content.hw-pane__sequence, .hw-pane__content.hw-pane__notation {\n max-height: 100px;\n overflow: scroll;\n}\n\n.hw-modal-backdrop {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.3);\n display: flex; align-items: center; justify-content: center;\n z-index: 1000;\n}\n.hw-modal {\n background: var(--hw-bg);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 4px;\n min-width: 320px;\n max-width: 600px;\n padding: 12px;\n}\n.hw-modal__header { font-weight: bold; padding-bottom: 8px; border-bottom: 1px solid var(--hw-border); }\n.hw-modal__body { padding-top: 8px; }\n.hw-modal__row { display: flex; gap: 8px; align-items: center; padding: 4px 0; }\n.hw-modal__label { color: var(--hw-fg); min-width: 100px; }\n.hw-modal__input, .hw-modal__select {\n flex: 1;\n padding: 4px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n}\n.hw-modal__check { transform: scale(1.1); }\n.hw-modal__actions { display: flex; justify-content: flex-end; gap: 6px; padding-top: 10px; }\n.hw-modal__ok, .hw-modal__cancel, .hw-modal__find-next, .hw-modal__replace, .hw-modal__replace-all {\n padding: 4px 10px;\n border: 1px solid var(--hw-border);\n background: var(--hw-bg);\n color: var(--hw-fg);\n border-radius: 3px;\n cursor: pointer;\n}\n.hw-modal__ok { background: var(--hw-accent); color: #ffffff; border-color: var(--hw-accent); }\n.hw-modal__result { color: var(--hw-muted); font-size: 11px; padding-top: 6px; }\n\n/* Phase 23 (T-2304) -- Bond editor endpoint preview row. Renders two\n monomer structures (atom A1 and atom A2) flanking a `↔` arrow so the\n user can see what they\'re connecting while picking R-groups. The\n SVG inside each cell stretches via the .hw-bond-props__atom-rdkit\n svg rule below (matches the tooltip pattern). */\n.hw-bond-props__atoms {\n display: flex;\n align-items: center;\n gap: 16px;\n margin: 12px 0;\n}\n.hw-bond-props__atom {\n flex: 1;\n text-align: center;\n}\n.hw-bond-props__atom-label {\n font-weight: 600;\n margin-bottom: 6px;\n color: var(--hw-fg);\n}\n.hw-bond-props__atom-rdkit {\n width: 180px;\n height: 120px;\n margin: 0 auto 8px;\n background: #fafafa;\n border: 1px solid #f3f4f6;\n border-radius: 4px;\n padding: 4px;\n box-sizing: border-box;\n}\n.hw-bond-props__atom-rdkit svg {\n display: block;\n width: 100%;\n height: 100%;\n}\n.hw-bond-props__bond-arrow {\n font-size: 24px;\n color: var(--hw-muted);\n flex: 0 0 auto;\n}\n\n.hw-editor-view {\n width: 100%;\n height: 100%;\n position: relative;\n --hw-hover: #ff8c00;\n}\n.hw-editor-view svg { width: 100%; height: 100%; }\n\n/* T-1103 / Phase 19 (T-1901) -- Cursor affordance only. We removed\n the :hover rules that recoloured the atom\'s own outline because\n they ran in PARALLEL with the real highlight ring painted by the\n renderer (teal #26A69A), producing the wrong colour the user\n reported as "yellow on hover" (the CSS rule re-stroked the atom in\n var(--hw-hover) = #ff8c00, an orange-yellow). The renderer\'s\n highlight layer is now the single source of truth for hover\n feedback. */\n.hw-atom { cursor: pointer; }\n.hw-bond { cursor: pointer; }\n\n/* Mode-specific cursors on the canvas wrapper. The editor adds an\n hw-editor-view--<mode> class via the option:change handler. */\n.hw-editor-view--select svg { cursor: default; }\n.hw-editor-view--eraser svg { cursor: not-allowed; }\n.hw-editor-view--hbond svg { cursor: crosshair; }\n.hw-editor-view--move svg { cursor: grab; }\n.hw-editor-view--move:active svg { cursor: grabbing; }\n\n/* Phase 22 (T-2201) -- Unified tooltip styling. Three tooltip variants\n share the same look-and-feel: atom hover (canvas), bond hover\n (canvas), palette-tile hover (left pane), and rna-builder slot hover.\n Pre-Phase 22 the tooltips were absolutely-positioned, dark, and\n z-index 100 -- the gallery panel (z-index higher) ate into them and\n the dark background looked heavy. Phase 22 mounts the tooltip at\n `document.body` (escaping every parent stacking context), pins\n `z-index: 99999`, and paints them white with a soft drop shadow and\n darker body text so they read clearly over any backdrop. */\n/* Phase 32 (T-3003) -- Ghost cursor preview that follows the mouse\n when a palette tile is primed in select mode. `pointer-events:\n none` so the underlying canvas keeps receiving clicks / drags. The\n z-index sits just below the tooltips (99998 vs 99999) so a real\n tooltip can still overlay the ghost if both happen to be visible. */\n.hw-next-add-cursor {\n position: fixed;\n pointer-events: none;\n z-index: 99998;\n opacity: 0.7;\n display: none;\n}\n.hw-next-add-cursor__svg {\n display: block;\n}\n\n.hw-atom-tooltip,\n.hw-bond-tooltip,\n.hw-palette-tooltip,\n.hw-builder-tooltip,\n.hw-toolbar-tooltip {\n position: fixed;\n pointer-events: none;\n background: #ffffff;\n color: #1f2937;\n border: 1px solid #e5e7eb;\n border-radius: 6px;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12), 0 2px 4px rgba(0, 0, 0, 0.08);\n padding: 10px 12px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 12px;\n line-height: 1.4;\n max-width: 240px;\n z-index: 99999;\n}\n/* T-3516 -- toolbar button tooltip: a single compact line, no wrap. */\n.hw-toolbar-tooltip {\n padding: 5px 8px;\n white-space: nowrap;\n font-weight: 500;\n}\n.hw-tooltip__symbol {\n font-weight: 700;\n color: #111827;\n}\n/* T-3514 -- RNA triplet tooltip: three monomer structures side by side.\n Wider than the single-structure tooltip so all three columns fit. */\n.hw-triplet-tooltip { max-width: 420px; }\n.hw-tooltip__triplet {\n display: flex;\n gap: 8px;\n margin-top: 6px;\n}\n.hw-tooltip__triplet-part {\n flex: 1 1 0;\n min-width: 0;\n text-align: center;\n}\n.hw-tooltip__triplet-role {\n font-weight: 600;\n color: #111827;\n font-size: 11px;\n}\n.hw-tooltip__name {\n color: #4b5563;\n}\n.hw-tooltip__hint {\n color: #6b7280;\n font-style: italic;\n font-size: 11px;\n margin-top: 6px;\n}\n.hw-tooltip__rdkit {\n display: block;\n margin-top: 8px;\n /* padding-top: 8px; */\n border-top: 1px solid #f3f4f6;\n background: #fafafa;\n border-radius: 4px;\n}\n/* Phase 23 (T-2303) -- The user reported "molecules do not take the full\n space" in the tooltip. RDKit emits an svg with a `viewBox`, so\n `width: 100%; height: auto` lets the structure stretch responsively\n to whatever width the parent tooltip column has. `max-height` caps\n tall structures so they never blow up the tooltip vertically. */\n.hw-tooltip__rdkit svg,\n[data-testid="atom-tooltip-rdkit-svg"] svg,\n[data-testid="palette-tooltip-rdkit-svg"] svg,\n[data-testid="builder-tooltip-rdkit-svg"] svg {\n display: block;\n width: 100%;\n height: auto;\n max-height: 180px;\n margin: 0 auto;\n}\n/* Legacy aliases (kept so Phase 21 atom-tooltip text styling still\n resolves). The body text colour is now driven by the parent tooltip\n rule above; the legacy classes keep the line-wrap behaviour. */\n.hw-atom-tooltip__text {\n display: block;\n}\n\n/* Status indicator (T-1106) -- small badge in the bottom-left of the canvas. */\n.hw-status-bar {\n position: absolute;\n left: 6px;\n bottom: 6px;\n padding: 2px 8px;\n background: rgba(255, 255, 255, 0.85);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n font-size: 11px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n pointer-events: none;\n z-index: 50;\n}\n.hw-app--dark .hw-status-bar { background: rgba(34, 36, 41, 0.85); }\n\n.hw-status-bar__mode {\n display: inline-flex;\n align-items: center;\n gap: 0;\n}\n.hw-status-bar__message {\n display: inline-block;\n margin-left: 8px;\n font-weight: 500;\n}\n.hw-status-bar__message[data-severity="info"] { color: var(--hw-fg); }\n.hw-status-bar__message[data-severity="warn"] { color: #b8860b; }\n.hw-status-bar__message[data-severity="error"] { color: #c0392b; }\n.hw-app--dark .hw-status-bar__message[data-severity="warn"] { color: #f7c948; }\n.hw-app--dark .hw-status-bar__message[data-severity="error"] { color: #ff6b6b; }\n\n/* Phase 25 (T-2504) -- "Next add: X [x]" clear button. The status bar\n itself sets `pointer-events: none` (it floats above the canvas as a\n non-interactive badge), so the button explicitly re-enables hits on\n itself only. Visible only when `nextAdd` is primed because the\n element is conditionally appended in `_refreshStatus`. */\n.hw-status-bar__next-add-symbol {\n display: inline-block;\n font-weight: 600;\n}\n.hw-status-bar__next-add-clear {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 16px;\n height: 16px;\n margin-left: 6px;\n padding: 0;\n background: transparent;\n border: 1px solid #d1d5db;\n border-radius: 50%;\n color: #6b7280;\n font-size: 12px;\n line-height: 1;\n cursor: pointer;\n pointer-events: auto;\n}\n.hw-status-bar__next-add-clear:hover {\n background: #f3f4f6;\n color: #1f2937;\n border-color: #9ca3af;\n}\n\n.hw-bond-preview { pointer-events: none; opacity: 0.85; }\n\n.hw-help-modal-backdrop {\n position: fixed; left: 0; top: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.4);\n display: flex; align-items: center; justify-content: center;\n z-index: 2000;\n}\n.hw-help-modal {\n background: #ffffff;\n color: #1a1a1a;\n padding: 16px 20px;\n border-radius: 4px;\n max-width: 480px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-shadow: 0 10px 20px rgba(0,0,0,0.3);\n}\n.hw-help-modal h2 { margin: 0 0 8px 0; font-size: 16px; }\n.hw-help-modal ul { padding-left: 20px; line-height: 1.6; }\n.hw-help-modal kbd {\n background: #eef0f3;\n border: 1px solid #cbd0d6;\n border-radius: 3px;\n padding: 1px 4px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 12px;\n}\n.hw-help-modal__close {\n margin-top: 12px;\n padding: 4px 12px;\n border: 1px solid #cbd0d6;\n background: #f5f6f8;\n cursor: pointer;\n border-radius: 3px;\n}\n',"",{version:3,sources:["webpack://./node_modules/@datagrok-libraries/hwe/dist/editor.css"],names:[],mappings:"AAAA;;;;;;;;;;;;;;;;;;;;EAoBE;;AAEF;EACE,gBAAgB;EAChB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,uBAAuB;EACvB,oBAAoB;EACpB,2BAA2B;EAC3B,wBAAwB;EACxB,wBAAwB;EACxB,qBAAqB;EACrB,mBAAmB;EACnB;0EACwE;EACxE,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,WAAW;EACX,YAAY;EACZ,wBAAwB;EACxB,mBAAmB;EACnB,2DAA2D;EAC3D,eAAe;EACf,sBAAsB;AACxB;AACA;EACE,gBAAgB;EAChB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,uBAAuB;EACvB,oBAAoB;EACpB,2BAA2B;EAC3B,wBAAwB;EACxB,wBAAwB;EACxB,qBAAqB;EACrB,mBAAmB;EACnB,kBAAkB;AACpB;AACA,iDAAiD,sBAAsB,EAAE;;AAEzE,mBAAmB,cAAc,EAAE;AACnC;EACE,cAAc;EACd,aAAa;EACb,mBAAmB;EACnB,aAAa;EACb,sCAAsC;AACxC;AACA;EACE,eAAe;EACf,wCAAwC;EACxC,cAAc;EACd,6BAA6B;AAC/B;AACA,kBAAkB,cAAc,EAAE,kBAAkB,EAAE,YAAY,EAAE,gBAAgB,EAAE;AACtF,iBAAiB,cAAc,EAAE,sCAAsC,EAAE;AACzE,gBAAgB,aAAa,EAAE,mBAAmB,EAAE,gCAAgC,EAAE;AACtF;EACE,iBAAiB;EACjB,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,mBAAmB;EACnB,wCAAwC;EACxC,eAAe;AACjB;AACA,uBAAuB,wBAAwB,EAAE,yCAAyC,EAAE;AAC5F,0EAA0E;AAC1E,qBAAqB,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,cAAc,EAAE,wBAAwB,EAAE;;AAElH;EACE,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;EACR,gBAAgB;EAChB,gCAAgC;AAClC;AACA;EACE;;uEAEqE;EACrE,6BAA6B;EAC7B,uBAAuB;EACvB,qBAAqB;EACrB,kBAAkB;EAClB,YAAY;EACZ,eAAe;EACf,eAAe;EACf,WAAW;EACX,YAAY;EACZ,oBAAoB;EACpB,mBAAmB;EACnB,uBAAuB;EACvB,yCAAyC;AAC3C;AACA;EACE,qBAAqB;EACrB,WAAW;EACX,YAAY;EACZ,cAAc;AAChB;AACA;EACE,WAAW;EACX,YAAY;EACZ,cAAc;AAChB;AACA,yBAAyB,sDAAsD,EAAE,mBAAmB,EAAE;AACtG,6BAA6B,YAAY,EAAE,eAAe,EAAE;AAC5D;EACE,8BAA8B;EAC9B,4BAA4B;EAC5B,cAAc;AAChB;AACA;EACE,qBAAqB;EACrB,UAAU;EACV,YAAY;EACZ,4BAA4B;EAC5B,aAAa;AACf;;AAEA;EACE,aAAa;EACb,sBAAsB;EACtB,YAAY;EACZ,YAAY;AACd;AACA;EACE,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,kCAAkC;EAClC,kBAAkB;EAClB,wBAAwB;EACxB,mBAAmB;EACnB,eAAe;EACf,cAAc;AAChB;AACA;;;;;;;;;;;;cAYc;AACd;EACE,aAAa;EACb,eAAe;EACf,YAAY;EACZ,yCAAyC;EACzC,cAAc;EACd,kEAAkE;EAClE,gBAAgB;AAClB;AACA;EACE;oDACkD;EAClD,cAAc;EACd,gBAAgB;EAChB,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,eAAe;EACf,sBAAsB;EACtB,iBAAiB;EACjB,mBAAmB;EACnB,YAAY;AACd;AACA;EACE,mBAAmB;EACnB,gCAAgC;AAClC;AACA;EACE,mBAAmB;EACnB,yCAAyC;EACzC,mBAAmB;EACnB,gBAAgB;AAClB;AACA;EACE,cAAc;EACd,aAAa;AACf;AACA;EACE,gBAAgB;EAChB,gBAAgB;EAChB,gBAAgB;AAClB;AACA,4BAA4B,aAAa,EAAE;AAC3C;EACE,iBAAiB;EACjB,sBAAsB;EACtB,eAAe;EACf,kBAAkB;AACpB;AACA,oDAAoD;AACpD,qBAAqB,mBAAmB,EAAE;AAC1C;EACE,eAAe;EACf,gBAAgB;EAChB,sBAAsB;EACtB,oBAAoB;EACpB,iBAAiB;EACjB,gDAAgD;EAChD,yBAAyB;EACzB,sBAAsB;AACxB;AACA;EACE,aAAa;EACb,qCAAqC;EACrC,QAAQ;EACR,YAAY;AACd;AACA,qBAAqB,aAAa,EAAE,eAAe,EAAE,QAAQ,EAAE,YAAY,EAAE;AAC7E;EACE,kBAAkB;EAClB,aAAa;EACb,sBAAsB;EACtB,mBAAmB;EACnB,uBAAuB;EACvB,WAAW;EACX,eAAe;EACf,eAAe;EACf,YAAY;EACZ,gBAAgB;EAChB,kCAAkC;EAClC,kBAAkB;EAClB,mBAAmB;EACnB,YAAY;EACZ,eAAe;EACf,gBAAgB;EAChB,iBAAiB;EACjB,gBAAgB;EAChB,uBAAuB;EACvB,yCAAyC;EACzC,iEAAiE;EACjE,sBAAsB;AACxB;AACA;EACE,8BAA8B;EAC9B,2BAA2B;EAC3B,yCAAyC;AAC3C;AACA;;EAEE,8BAA8B;EAC9B,6CAA6C;AAC/C;AACA,8BAA8B,oCAAoC,EAAE,oBAAoB,EAAE;AAC1F;EACE,6EAA6E;AAC/E;AACA;EACE,kBAAkB;EAClB,QAAQ;EACR,UAAU;EACV,eAAe;EACf,eAAe;EACf,sBAAsB;AACxB;AACA,gDAAgD,uBAAuB,EAAE;AACzE;EACE,gBAAgB;EAChB,sBAAsB;EACtB,qBAAqB;EACrB,eAAe;EACf,mBAAmB;EACnB,gBAAgB;EAChB,uBAAuB;AACzB;;AAEA;;;;0CAI0C;AAC1C;EACE,cAAc;EACd;;gEAE8D;EAC9D,oBAAoB;EACpB,YAAY;EACZ,sCAAsC;EACtC,kDAAkD;EAClD,kBAAkB;AACpB;AACA,iEAAiE;AACjE;EACE,aAAa;EACb,mBAAmB;EACnB,8BAA8B;EAC9B,kBAAkB;AACpB;AACA;EACE,gBAAgB;EAChB,eAAe;EACf,sBAAsB;EACtB,yBAAyB;EACzB,sBAAsB;AACxB;AACA;EACE,gBAAgB;AAClB;AACA,2DAA2D;AAC3D;EACE,eAAe;EACf,cAAc;EACd,eAAe;EACf,sBAAsB;EACtB,iBAAiB;AACnB;AACA,+BAA+B,uBAAuB,EAAE;AACxD,iCAAiC,aAAa,EAAE,eAAe,EAAE;AACjE;;;;;;;qBAOqB;AACrB;EACE,gBAAgB;EAChB,eAAe;EACf,uBAAuB;EACvB,mBAAmB;AACrB;AACA;EACE,aAAa;AACf;AACA;EACE,cAAc;EACd,WAAW;EACX,gBAAgB;EAChB,YAAY;EACZ,gBAAgB;EAChB,kBAAkB;AACpB;AACA;EACE,6BAA6B;EAC7B,iBAAiB;EACjB,UAAU;AACZ;AACA;EACE,eAAe;AACjB;AACA;EACE,iBAAiB;EACjB,wBAAwB;AAC1B;AACA;EACE,wBAAwB;EACxB,iBAAiB;AACnB;AACA;EACE,2DAA2D;EAC3D;;;yBAGuB;EACvB,eAAe;EACf,gBAAgB;EAChB,iBAAiB;EACjB,oBAAoB;AACtB;AACA;;EAEE,sEAAsE;EACtE,iEAAiE;EACjE,iBAAiB;AACnB;AACA;EACE,aAAa;AACf;AACA;EACE,wBAAwB;EACxB,iBAAiB;AACnB;AACA;EACE,aAAa;EACb,eAAe;EACf,mBAAmB;EACnB,qDAAqD;EACrD,kBAAkB;AACpB;AACA;EACE,cAAc;EACd,WAAW;EACX,gBAAgB;EAChB,4BAA4B;EAC5B,cAAc;EACd,kCAAkC;EAClC,kBAAkB;EAClB,eAAe;EACf,gBAAgB;EAChB,eAAe;AACjB;AACA,6BAA6B,YAAY,EAAE;AAC3C,8BAA8B,0BAA0B,EAAE;;AAE1D;;;sEAGsE;AACtE;EACE,aAAa;EACb,eAAe;EACf,QAAQ;EACR,YAAY;AACd;AACA;EACE,eAAe;AACjB;AACA;EACE,kBAAkB;EAClB,oBAAoB;EACpB,mBAAmB;EACnB,QAAQ;EACR,YAAY;EACZ,cAAc;EACd,kCAAkC;EAClC,mBAAmB;EACnB,qDAAqD;EACrD,eAAe;EACf,gBAAgB;EAChB,cAAc;EACd,eAAe;EACf,iBAAiB;EACjB,yCAAyC;EACzC,+CAA+C;AACjD;AACA;EACE,8BAA8B;EAC9B,2BAA2B;AAC7B;AACA,6BAA6B,8BAA8B,EAAE;AAC7D;EACE,eAAe;EACf,eAAe;EACf,sBAAsB;AACxB;AACA,oDAAoD,uBAAuB,EAAE;AAC7E,0BAA0B,sBAAsB,EAAE;;AAElD;;;;gEAIgE;;AAEhE,WAAW,cAAc,EAAE;AAC3B,oBAAoB,qDAAqD,EAAE,eAAe,EAAE,qBAAqB,EAAE,qBAAqB,EAAE;AAC1I;EACE,aAAa;EACb,kCAAkC;EAClC,YAAY;EACZ,wBAAwB;AAC1B;AACA,kBAAkB,sBAAsB,EAAE,eAAe,EAAE,eAAe,EAAE,aAAa,EAAE;AAC3F,2BAA2B,cAAc,EAAE;AAC3C,qBAAqB,aAAa,EAAE,QAAQ,EAAE,cAAc,EAAE;AAC9D,uBAAuB,sBAAsB,EAAE,YAAY,EAAE;AAC7D,uBAAuB,mBAAmB,EAAE;AAC5C,wBAAwB,sBAAsB,EAAE,kBAAkB,EAAE;;AAEpE;EACE,iBAAiB;EACjB,gBAAgB;AAClB;;AAEA;EACE,kBAAkB;EAClB,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS;EACpC,2BAA2B;EAC3B,aAAa,EAAE,mBAAmB,EAAE,uBAAuB;EAC3D,aAAa;AACf;AACA;EACE,wBAAwB;EACxB,mBAAmB;EACnB,kCAAkC;EAClC,kBAAkB;EAClB,gBAAgB;EAChB,gBAAgB;EAChB,aAAa;AACf;AACA,oBAAoB,iBAAiB,EAAE,mBAAmB,EAAE,yCAAyC,EAAE;AACvG,kBAAkB,gBAAgB,EAAE;AACpC,iBAAiB,aAAa,EAAE,QAAQ,EAAE,mBAAmB,EAAE,cAAc,EAAE;AAC/E,mBAAmB,mBAAmB,EAAE,gBAAgB,EAAE;AAC1D;EACE,OAAO;EACP,YAAY;EACZ,kCAAkC;EAClC,kBAAkB;EAClB,wBAAwB;EACxB,mBAAmB;AACrB;AACA,mBAAmB,qBAAqB,EAAE;AAC1C,qBAAqB,aAAa,EAAE,yBAAyB,EAAE,QAAQ,EAAE,iBAAiB,EAAE;AAC5F;EACE,iBAAiB;EACjB,kCAAkC;EAClC,wBAAwB;EACxB,mBAAmB;EACnB,kBAAkB;EAClB,eAAe;AACjB;AACA,gBAAgB,4BAA4B,EAAE,cAAc,EAAE,8BAA8B,EAAE;AAC9F,oBAAoB,sBAAsB,EAAE,eAAe,EAAE,gBAAgB,EAAE;;AAE/E;;;;kDAIkD;AAClD;EACE,aAAa;EACb,mBAAmB;EACnB,SAAS;EACT,cAAc;AAChB;AACA;EACE,OAAO;EACP,kBAAkB;AACpB;AACA;EACE,gBAAgB;EAChB,kBAAkB;EAClB,mBAAmB;AACrB;AACA;EACE,YAAY;EACZ,aAAa;EACb,kBAAkB;EAClB,mBAAmB;EACnB,yBAAyB;EACzB,kBAAkB;EAClB,YAAY;EACZ,sBAAsB;AACxB;AACA;EACE,cAAc;EACd,WAAW;EACX,YAAY;AACd;AACA;EACE,eAAe;EACf,sBAAsB;EACtB,cAAc;AAChB;;AAEA;EACE,WAAW;EACX,YAAY;EACZ,kBAAkB;EAClB,mBAAmB;AACrB;AACA,sBAAsB,WAAW,EAAE,YAAY,EAAE;;AAEjD;;;;;;;cAOc;AACd,WAAW,eAAe,EAAE;AAC5B,WAAW,eAAe,EAAE;;AAE5B;gEACgE;AAChE,8BAA8B,eAAe,EAAE;AAC/C,8BAA8B,mBAAmB,EAAE;AACnD,6BAA6B,iBAAiB,EAAE;AAChD,4BAA4B,YAAY,EAAE;AAC1C,mCAAmC,gBAAgB,EAAE;;AAErD;;;;;;;;6DAQ6D;AAC7D;;;;sEAIsE;AACtE;EACE,eAAe;EACf,oBAAoB;EACpB,cAAc;EACd,YAAY;EACZ,aAAa;AACf;AACA;EACE,cAAc;AAChB;;AAEA;;;;;EAKE,eAAe;EACf,oBAAoB;EACpB,mBAAmB;EACnB,cAAc;EACd,yBAAyB;EACzB,kBAAkB;EAClB,yEAAyE;EACzE,kBAAkB;EAClB,2DAA2D;EAC3D,eAAe;EACf,gBAAgB;EAChB,gBAAgB;EAChB,cAAc;AAChB;AACA,sEAAsE;AACtE;EACE,gBAAgB;EAChB,mBAAmB;EACnB,gBAAgB;AAClB;AACA;EACE,gBAAgB;EAChB,cAAc;AAChB;AACA;sEACsE;AACtE,sBAAsB,gBAAgB,EAAE;AACxC;EACE,aAAa;EACb,QAAQ;EACR,eAAe;AACjB;AACA;EACE,WAAW;EACX,YAAY;EACZ,kBAAkB;AACpB;AACA;EACE,gBAAgB;EAChB,cAAc;EACd,eAAe;AACjB;AACA;EACE,cAAc;AAChB;AACA;EACE,cAAc;EACd,kBAAkB;EAClB,eAAe;EACf,eAAe;AACjB;AACA;EACE,cAAc;GACb,eAAe;EAChB,sBAAsB;EACtB,6BAA6B;EAC7B,mBAAmB;EACnB,kBAAkB;AACpB;AACA;;;;kEAIkE;AAClE;;;;EAIE,cAAc;EACd,WAAW;EACX,YAAY;EACZ,iBAAiB;EACjB,cAAc;AAChB;AACA;;iEAEiE;AACjE;EACE,cAAc;AAChB;;AAEA,+EAA+E;AAC/E;EACE,kBAAkB;EAClB,SAAS;EACT,WAAW;EACX,gBAAgB;EAChB,qCAAqC;EACrC,mBAAmB;EACnB,kCAAkC;EAClC,kBAAkB;EAClB,eAAe;EACf,2DAA2D;EAC3D,oBAAoB;EACpB,WAAW;AACb;AACA,+BAA+B,kCAAkC,EAAE;;AAEnE;EACE,oBAAoB;EACpB,mBAAmB;EACnB,MAAM;AACR;AACA;EACE,qBAAqB;EACrB,gBAAgB;EAChB,gBAAgB;AAClB;AACA,gDAAgD,mBAAmB,EAAE;AACrE,gDAAgD,cAAc,EAAE;AAChE,iDAAiD,cAAc,EAAE;AACjE,8DAA8D,cAAc,EAAE;AAC9E,+DAA+D,cAAc,EAAE;;AAE/E;;;;2DAI2D;AAC3D;EACE,qBAAqB;EACrB,gBAAgB;AAClB;AACA;EACE,oBAAoB;EACpB,mBAAmB;EACnB,uBAAuB;EACvB,WAAW;EACX,YAAY;EACZ,gBAAgB;EAChB,UAAU;EACV,uBAAuB;EACvB,yBAAyB;EACzB,kBAAkB;EAClB,cAAc;EACd,eAAe;EACf,cAAc;EACd,eAAe;EACf,oBAAoB;AACtB;AACA;EACE,mBAAmB;EACnB,cAAc;EACd,qBAAqB;AACvB;;AAEA,mBAAmB,oBAAoB,EAAE,aAAa,EAAE;;AAExD;EACE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS;EACrD,2BAA2B;EAC3B,aAAa,EAAE,mBAAmB,EAAE,uBAAuB;EAC3D,aAAa;AACf;AACA;EACE,mBAAmB;EACnB,cAAc;EACd,kBAAkB;EAClB,kBAAkB;EAClB,gBAAgB;EAChB,2DAA2D;EAC3D,eAAe;EACf,uCAAuC;AACzC;AACA,oBAAoB,iBAAiB,EAAE,eAAe,EAAE;AACxD,oBAAoB,kBAAkB,EAAE,gBAAgB,EAAE;AAC1D;EACE,mBAAmB;EACnB,yBAAyB;EACzB,kBAAkB;EAClB,gBAAgB;EAChB,qDAAqD;EACrD,eAAe;AACjB;AACA;EACE,gBAAgB;EAChB,iBAAiB;EACjB,yBAAyB;EACzB,mBAAmB;EACnB,eAAe;EACf,kBAAkB;AACpB",sourcesContent:['/* T-0609 / Phase 19 (T-1902) / Phase 28 (T-2801, T-2804) --\n * Default editor stylesheet. SINGLE source of truth.\n *\n * Build pipeline:\n * 1. tsup copies this file byte-for-byte to `dist/editor.css`\n * (see `tsup.config.ts` -- onSuccess hook).\n * 2. `package.json#exports."./styles.css"` maps the public import\n * `@datagrok-libraries/hwe/styles.css` to `dist/editor.css`, so\n * library consumers do `import \'@datagrok-libraries/hwe/styles.css\';`\n * via their bundler (vite, webpack, rollup, etc.).\n * 3. apps/demo imports this file directly with a relative path\n * (`import \'../../../src/editor/styles/editor.css\';` in main.ts)\n * so vite serves source CSS in dev and bundles it in prod.\n *\n * Phase 28 removed the previous runtime injection path\n * (`injectAppStyles` + `editor-css.generated.ts` TS mirror). Reason:\n * dual delivery was a recurring drift hazard. The bundler is now the\n * SINGLE CSS-delivery channel; tests use `mountEditorCss` (in\n * `tests/helpers/load-css.ts`) to read this file directly when\n * stylesheet-text or `getComputedStyle` checks are needed in linkedom.\n */\n\n.hw-app {\n --hw-bg: #ffffff;\n --hw-fg: #1a1a1a;\n --hw-muted: #6c757d;\n --hw-accent: #1f5fcd;\n --hw-selection: #FFD29B;\n --hw-border: #d8d8d8;\n --hw-border-subtle: #e9ecef;\n --hw-tile-hover: #f1f3f5;\n --hw-toolbar-bg: #f4f5f7;\n --hw-pane-bg: #fafbfc;\n --hw-error: #cc0000;\n /* T-3517 -- toolbar icon stroke colour. Datagrok-style neutral grey\n (icons read as quiet chrome until hovered, then darken to --hw-fg). */\n --hw-icon: #6b7178;\n display: flex;\n flex-direction: column;\n width: 100%;\n height: 100%;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-sizing: border-box;\n}\n.hw-app--dark {\n --hw-bg: #1a1d23;\n --hw-fg: #e0e0e0;\n --hw-muted: #9aa1a8;\n --hw-accent: #6699ff;\n --hw-selection: #FFD29B;\n --hw-border: #3a3f47;\n --hw-border-subtle: #2c3037;\n --hw-tile-hover: #262a31;\n --hw-toolbar-bg: #22252b;\n --hw-pane-bg: #1f2228;\n --hw-error: #ff5050;\n --hw-icon: #9aa1a8;\n}\n.hw-app *, .hw-app *::before, .hw-app *::after { box-sizing: border-box; }\n\n.hw-app__toolbar { flex: 0 0 auto; }\n.hw-app__main {\n flex: 1 1 auto;\n display: flex;\n flex-direction: row;\n min-height: 0;\n border-top: 1px solid var(--hw-border);\n}\n.hw-app__palette {\n flex: 0 0 220px;\n border-right: 1px solid var(--hw-border);\n overflow: auto;\n background: var(--hw-pane-bg);\n}\n.hw-app__canvas { flex: 1 1 auto; position: relative; min-width: 0; overflow: hidden; }\n.hw-app__panes { flex: 0 0 auto; border-top: 1px solid var(--hw-border); }\n.hw-app__tabs { display: flex; flex-direction: row; background: var(--hw-toolbar-bg); }\n.hw-app__tab {\n padding: 6px 14px;\n cursor: pointer;\n border: none;\n background: transparent;\n color: var(--hw-fg);\n border-right: 1px solid var(--hw-border);\n font-size: 12px;\n}\n.hw-app__tab--active { background: var(--hw-bg); border-bottom: 2px solid var(--hw-accent); }\n/* Cap the active pane\'s height; taller content scrolls within the pane. */\n.hw-app__pane-body { padding: 8px; min-height: 80px; max-height: 300px; overflow: auto; background: var(--hw-bg); }\n\n.hw-toolbar {\n display: flex;\n flex-direction: row;\n align-items: center;\n gap: 4px;\n padding: 4px 6px;\n background: var(--hw-toolbar-bg);\n}\n.hw-toolbar__btn {\n /* T-3517 -- Datagrok-style flat, borderless icon buttons. The icon\n stroke uses the neutral grey --hw-icon; hover darkens it to --hw-fg\n and adds a soft rounded background, matching Datagrok\'s toolbar. */\n border: 1px solid transparent;\n background: transparent;\n color: var(--hw-icon);\n border-radius: 4px;\n padding: 5px;\n cursor: pointer;\n font-size: 13px;\n width: 30px;\n height: 30px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n transition: background 120ms, color 120ms;\n}\n.hw-toolbar__btn-icon {\n display: inline-block;\n width: 100%;\n height: 100%;\n color: inherit;\n}\n.hw-toolbar__btn-icon > svg {\n width: 100%;\n height: 100%;\n display: block;\n}\n.hw-toolbar__btn:hover { background: var(--hw-tile-hover, var(--hw-toolbar-bg)); color: var(--hw-fg); }\n.hw-toolbar__btn[disabled] { opacity: 0.4; cursor: default; }\n.hw-toolbar__btn--active {\n border-color: var(--hw-accent);\n background: var(--hw-accent);\n color: #ffffff;\n}\n.hw-toolbar__separator {\n display: inline-block;\n width: 1px;\n height: 18px;\n background: var(--hw-border);\n margin: 0 4px;\n}\n\n.hw-palette {\n display: flex;\n flex-direction: column;\n height: 100%;\n padding: 4px;\n}\n.hw-palette__search {\n width: 100%;\n padding: 4px;\n margin-bottom: 6px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n font-size: 12px;\n flex: 0 0 auto;\n}\n/* T-1421 / T-1423 -- tab list: horizontal row above the panes. Active\n tab gets a 2 px accent underline that absorbs the 1 px container\n border below via a negative bottom margin so the layout does not\n shift when the active tab changes.\n\n Phase 24 (T-2404): when a library exposes many polymer types\n (Favorites + PEPTIDE + RNA + CHEM + BLOB + G = 6 tabs), they can no\n longer fit horizontally inside the 200 px palette pane and the\n browser shows an unobvious horizontal scrollbar. Switch to\n `flex-wrap: wrap` so overflow tabs wrap onto a second (or third)\n row -- no hidden scrollbar, every tab is always visible. The\n per-tab padding shrinks too so more tabs fit per row before\n wrapping. */\n.hw-palette__tabs {\n display: flex;\n flex-wrap: wrap;\n gap: 2px 4px;\n border-bottom: 1px solid var(--hw-border);\n flex: 0 0 auto;\n /* Defensively: no overflow scrolling -- wrapping is the answer. */\n overflow: hidden;\n}\n.hw-palette__tab {\n /* Phase 24 (T-2404): compact padding + min-width so 6 tabs still fit\n in two rows max within a 200 px palette pane. */\n flex: 0 0 auto;\n padding: 6px 8px;\n cursor: pointer;\n border: none;\n background: transparent;\n font-size: 12px;\n color: var(--hw-muted);\n user-select: none;\n white-space: nowrap;\n min-width: 0;\n}\n.hw-palette__tab:hover {\n color: var(--hw-fg);\n background: var(--hw-tile-hover);\n}\n.hw-palette__tab[aria-selected="true"] {\n color: var(--hw-fg);\n border-bottom: 2px solid var(--hw-accent);\n margin-bottom: -1px;\n font-weight: 600;\n}\n.hw-palette__panes {\n flex: 1 1 auto;\n min-height: 0;\n}\n.hw-palette__pane {\n overflow-y: auto;\n max-height: 100%;\n padding: 4px 6px;\n}\n.hw-palette__pane[hidden] { display: none; }\n.hw-palette__placeholder {\n padding: 12px 6px;\n color: var(--hw-muted);\n font-size: 12px;\n font-style: italic;\n}\n/* T-1423 -- bolder, more separated group headers. */\n.hw-palette__group { margin-bottom: 12px; }\n.hw-palette__group-header {\n font-size: 13px;\n font-weight: 700;\n color: var(--hw-muted);\n padding: 8px 4px 4px;\n margin: 8px 0 4px;\n border-bottom: 1px solid var(--hw-border-subtle);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-palette__group-tiles {\n display: grid;\n grid-template-columns: repeat(3, 1fr);\n gap: 6px;\n padding: 2px;\n}\n.hw-palette__tiles { display: flex; flex-wrap: wrap; gap: 6px; padding: 2px; }\n.hw-palette__tile {\n position: relative;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n width: 100%;\n min-width: 48px;\n max-width: none;\n height: 40px;\n padding: 4px 6px;\n border: 2px solid var(--hw-border);\n border-radius: 8px;\n background: #ffffff;\n cursor: grab;\n font-size: 13px;\n font-weight: 600;\n user-select: none;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms, box-shadow 120ms;\n box-sizing: border-box;\n}\n.hw-palette__tile:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);\n}\n.hw-palette__tile[aria-pressed="true"],\n.hw-palette__tile--primed {\n border-color: var(--hw-accent);\n box-shadow: 0 0 0 2px rgba(31, 95, 205, 0.18);\n}\n.hw-palette__tile--favorite { outline: 1px dashed var(--hw-accent); outline-offset: -3px; }\n.hw-palette__tile--low-contrast {\n box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.08);\n}\n.hw-palette__star {\n position: absolute;\n top: 2px;\n right: 4px;\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-palette__tile--favorite .hw-palette__star { color: var(--hw-accent); }\n.hw-palette__label {\n font-weight: 600;\n letter-spacing: 0.02em;\n display: inline-block;\n max-width: 80px;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n}\n\n/* Phase 18 (T-1806) / Phase 19 (T-1903) / Phase 20 (T-2002) -- RNA Builder.\n Phase 20 redesign: SVG triplet visualization. Sugar (square),\n linker (circle), base (diamond) -- each clickable to enter pick\n mode. Fills come from the resolved monomer colour palette so the\n preview matches the canvas rendering. */\n.hw-rna-builder {\n display: block;\n /* Phase 21 (T-2101): horizontal margin nudges the builder rightward\n so it visually aligns with the palette tile column below. The\n user reported the SVG sat too far left vs. the tile rows. */\n margin: 4px 8px 12px;\n padding: 8px;\n background: var(--hw-pane-bg, #fafbfc);\n border: 1px solid var(--hw-border-subtle, #e9ecef);\n border-radius: 6px;\n}\n/* T-3513 -- header row holds the title plus the favorite star. */\n.hw-rna-builder__header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n margin-bottom: 6px;\n}\n.hw-rna-builder__title {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n}\n.hw-rna-builder__header .hw-rna-builder__title {\n margin-bottom: 0;\n}\n/* T-3513 -- favorite star toggling the composed triplet. */\n.hw-rna-builder__fav {\n font-size: 15px;\n line-height: 1;\n cursor: pointer;\n color: var(--hw-muted);\n user-select: none;\n}\n.hw-rna-builder__fav--active { color: var(--hw-accent); }\n.hw-rna-builder__fav--disabled { opacity: 0.35; cursor: default; }\n/* Phase 29 (T-2901) -- Pick-mode hint shown directly under the "RNA\n builder" title while a slot is in pick mode. Replaces the Phase 24\n palette-level reserved-space hint above the search box. The hint\n carries the `hidden` HTML attribute when idle so the SVG triplet\n sits flush against the title (no wasted vertical space). User\n request 2026-05-19: "lets not have that empty space, and just\n display that text in bold below \'RNA BUILDER\' header, inside the\n builder itself." */\n.hw-rna-builder__hint {\n font-weight: 700;\n font-size: 12px;\n color: var(--hw-accent);\n margin: 4px 0 -14px;\n}\n.hw-rna-builder__hint[hidden] {\n display: none;\n}\n.hw-rna-builder__triplet {\n display: block;\n width: 100%;\n max-width: 180px;\n height: auto;\n max-height: 10vh;\n margin: 0 auto 6px;\n}\n.hw-rna-builder__bond {\n stroke: var(--hw-fg, #1a1a1a);\n stroke-width: 1.5;\n fill: none;\n}\n.hw-rna-builder__slot {\n cursor: pointer;\n}\n.hw-rna-builder__slot-shape {\n stroke-width: 1.5;\n transition: filter 120ms;\n}\n.hw-rna-builder__slot:hover .hw-rna-builder__slot-shape {\n filter: brightness(1.08);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot-label {\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n /* Phase 21 (T-2102): font-size is set per-label inline via\n setAttribute(\'font-size\', ...) so a long symbol like `[5meC]`\n can scale down. The CSS default below is a safety net for\n pre-T-2102 markup. */\n font-size: 12px;\n font-weight: 700;\n user-select: none;\n pointer-events: none;\n}\n.hw-rna-builder__slot--active .hw-rna-builder__slot-shape,\n.hw-rna-builder__slot[aria-pressed="true"] .hw-rna-builder__slot-shape {\n /* Yellow halo via filter so per-monomer fill / stroke stays intact. */\n filter: drop-shadow(0 0 3px #ffeb3b) drop-shadow(0 0 2px #ffeb3b);\n stroke-width: 2.5;\n}\n.hw-rna-builder__slot:focus {\n outline: none;\n}\n.hw-rna-builder__slot:focus-visible .hw-rna-builder__slot-shape {\n stroke: var(--hw-accent);\n stroke-width: 2.5;\n}\n.hw-rna-builder__preview {\n margin: 6px 0;\n font-size: 11px;\n color: var(--hw-fg);\n font-family: ui-monospace, Menlo, Consolas, monospace;\n text-align: center;\n}\n.hw-rna-builder__add {\n display: block;\n width: 100%;\n padding: 4px 8px;\n background: var(--hw-accent);\n color: #ffffff;\n border: 1px solid var(--hw-accent);\n border-radius: 3px;\n font-size: 12px;\n font-weight: 600;\n cursor: pointer;\n}\n.hw-rna-builder__add:hover { opacity: 0.9; }\n.hw-rna-builder__add:active { transform: translateY(1px); }\n\n/* T-3513 -- RNA triplet chips. Small, monospace, wrap into a tight row.\n Used by the RNA pane\'s default-nucleotide row (r(A)p ... r(T)p) and by\n triplet favorites in the Favorites pane. Kept compact because the RNA\n pane\'s vertical space is constrained by the RNA builder above it. */\n.hw-triplet-chips {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n padding: 2px;\n}\n.hw-triplet-chips--defaults {\n margin: 0 0 8px;\n}\n.hw-triplet-chip {\n position: relative;\n display: inline-flex;\n align-items: center;\n gap: 2px;\n height: 22px;\n padding: 0 6px;\n border: 1px solid var(--hw-border);\n border-radius: 11px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 11px;\n font-weight: 600;\n line-height: 1;\n cursor: pointer;\n user-select: none;\n box-shadow: 0 1px 1px rgba(0, 0, 0, 0.08);\n transition: border-color 120ms, transform 120ms;\n}\n.hw-triplet-chip:hover {\n border-color: var(--hw-accent);\n transform: translateY(-1px);\n}\n.hw-triplet-chip--favorite { border-color: var(--hw-accent); }\n.hw-triplet-chip__star {\n font-size: 10px;\n cursor: pointer;\n color: var(--hw-muted);\n}\n.hw-triplet-chip--favorite .hw-triplet-chip__star { color: var(--hw-accent); }\n.hw-triplet-chip__label { letter-spacing: 0.02em; }\n\n/* Phase 29 (T-2901) -- The Phase 24 palette-level pick-mode hint\n container has been REMOVED. The hint now lives inside the RNA\n Builder as `.hw-rna-builder__hint` (see the rules under the RNA\n Builder block above). The user explicitly reported the\n reserved-space hint above the search box as "wasted space". */\n\n.hw-pane { display: block; }\n.hw-pane__content { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; white-space: pre-wrap; word-break: break-all; }\n.hw-pane__notation {\n outline: none;\n border: 1px solid var(--hw-border);\n padding: 4px;\n background: var(--hw-bg);\n}\n.hw-pane__error { color: var(--hw-error); font-size: 11px; margin-top: 4px; display: none; }\n.hw-pane__error--visible { display: block; }\n.hw-pane__prop-row { display: flex; gap: 8px; padding: 2px 0; }\n.hw-pane__prop-label { color: var(--hw-muted); width: 180px; }\n.hw-pane__prop-value { color: var(--hw-fg); }\n.hw-pane__placeholder { color: var(--hw-muted); font-style: italic; }\n\n.hw-pane__content.hw-pane__sequence, .hw-pane__content.hw-pane__notation {\n max-height: 100px;\n overflow: scroll;\n}\n\n.hw-modal-backdrop {\n position: absolute;\n top: 0; left: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.3);\n display: flex; align-items: center; justify-content: center;\n z-index: 1000;\n}\n.hw-modal {\n background: var(--hw-bg);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 4px;\n min-width: 320px;\n max-width: 600px;\n padding: 12px;\n}\n.hw-modal__header { font-weight: bold; padding-bottom: 8px; border-bottom: 1px solid var(--hw-border); }\n.hw-modal__body { padding-top: 8px; }\n.hw-modal__row { display: flex; gap: 8px; align-items: center; padding: 4px 0; }\n.hw-modal__label { color: var(--hw-fg); min-width: 100px; }\n.hw-modal__input, .hw-modal__select {\n flex: 1;\n padding: 4px;\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n background: var(--hw-bg);\n color: var(--hw-fg);\n}\n.hw-modal__check { transform: scale(1.1); }\n.hw-modal__actions { display: flex; justify-content: flex-end; gap: 6px; padding-top: 10px; }\n.hw-modal__ok, .hw-modal__cancel, .hw-modal__find-next, .hw-modal__replace, .hw-modal__replace-all {\n padding: 4px 10px;\n border: 1px solid var(--hw-border);\n background: var(--hw-bg);\n color: var(--hw-fg);\n border-radius: 3px;\n cursor: pointer;\n}\n.hw-modal__ok { background: var(--hw-accent); color: #ffffff; border-color: var(--hw-accent); }\n.hw-modal__result { color: var(--hw-muted); font-size: 11px; padding-top: 6px; }\n\n/* Phase 23 (T-2304) -- Bond editor endpoint preview row. Renders two\n monomer structures (atom A1 and atom A2) flanking a `↔` arrow so the\n user can see what they\'re connecting while picking R-groups. The\n SVG inside each cell stretches via the .hw-bond-props__atom-rdkit\n svg rule below (matches the tooltip pattern). */\n.hw-bond-props__atoms {\n display: flex;\n align-items: center;\n gap: 16px;\n margin: 12px 0;\n}\n.hw-bond-props__atom {\n flex: 1;\n text-align: center;\n}\n.hw-bond-props__atom-label {\n font-weight: 600;\n margin-bottom: 6px;\n color: var(--hw-fg);\n}\n.hw-bond-props__atom-rdkit {\n width: 180px;\n height: 120px;\n margin: 0 auto 8px;\n background: #fafafa;\n border: 1px solid #f3f4f6;\n border-radius: 4px;\n padding: 4px;\n box-sizing: border-box;\n}\n.hw-bond-props__atom-rdkit svg {\n display: block;\n width: 100%;\n height: 100%;\n}\n.hw-bond-props__bond-arrow {\n font-size: 24px;\n color: var(--hw-muted);\n flex: 0 0 auto;\n}\n\n.hw-editor-view {\n width: 100%;\n height: 100%;\n position: relative;\n --hw-hover: #ff8c00;\n}\n.hw-editor-view svg { width: 100%; height: 100%; }\n\n/* T-1103 / Phase 19 (T-1901) -- Cursor affordance only. We removed\n the :hover rules that recoloured the atom\'s own outline because\n they ran in PARALLEL with the real highlight ring painted by the\n renderer (teal #26A69A), producing the wrong colour the user\n reported as "yellow on hover" (the CSS rule re-stroked the atom in\n var(--hw-hover) = #ff8c00, an orange-yellow). The renderer\'s\n highlight layer is now the single source of truth for hover\n feedback. */\n.hw-atom { cursor: pointer; }\n.hw-bond { cursor: pointer; }\n\n/* Mode-specific cursors on the canvas wrapper. The editor adds an\n hw-editor-view--<mode> class via the option:change handler. */\n.hw-editor-view--select svg { cursor: default; }\n.hw-editor-view--eraser svg { cursor: not-allowed; }\n.hw-editor-view--hbond svg { cursor: crosshair; }\n.hw-editor-view--move svg { cursor: grab; }\n.hw-editor-view--move:active svg { cursor: grabbing; }\n\n/* Phase 22 (T-2201) -- Unified tooltip styling. Three tooltip variants\n share the same look-and-feel: atom hover (canvas), bond hover\n (canvas), palette-tile hover (left pane), and rna-builder slot hover.\n Pre-Phase 22 the tooltips were absolutely-positioned, dark, and\n z-index 100 -- the gallery panel (z-index higher) ate into them and\n the dark background looked heavy. Phase 22 mounts the tooltip at\n `document.body` (escaping every parent stacking context), pins\n `z-index: 99999`, and paints them white with a soft drop shadow and\n darker body text so they read clearly over any backdrop. */\n/* Phase 32 (T-3003) -- Ghost cursor preview that follows the mouse\n when a palette tile is primed in select mode. `pointer-events:\n none` so the underlying canvas keeps receiving clicks / drags. The\n z-index sits just below the tooltips (99998 vs 99999) so a real\n tooltip can still overlay the ghost if both happen to be visible. */\n.hw-next-add-cursor {\n position: fixed;\n pointer-events: none;\n z-index: 99998;\n opacity: 0.7;\n display: none;\n}\n.hw-next-add-cursor__svg {\n display: block;\n}\n\n.hw-atom-tooltip,\n.hw-bond-tooltip,\n.hw-palette-tooltip,\n.hw-builder-tooltip,\n.hw-toolbar-tooltip {\n position: fixed;\n pointer-events: none;\n background: #ffffff;\n color: #1f2937;\n border: 1px solid #e5e7eb;\n border-radius: 6px;\n box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12), 0 2px 4px rgba(0, 0, 0, 0.08);\n padding: 10px 12px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 12px;\n line-height: 1.4;\n max-width: 240px;\n z-index: 99999;\n}\n/* T-3516 -- toolbar button tooltip: a single compact line, no wrap. */\n.hw-toolbar-tooltip {\n padding: 5px 8px;\n white-space: nowrap;\n font-weight: 500;\n}\n.hw-tooltip__symbol {\n font-weight: 700;\n color: #111827;\n}\n/* T-3514 -- RNA triplet tooltip: three monomer structures side by side.\n Wider than the single-structure tooltip so all three columns fit. */\n.hw-triplet-tooltip { max-width: 420px; }\n.hw-tooltip__triplet {\n display: flex;\n gap: 8px;\n margin-top: 6px;\n}\n.hw-tooltip__triplet-part {\n flex: 1 1 0;\n min-width: 0;\n text-align: center;\n}\n.hw-tooltip__triplet-role {\n font-weight: 600;\n color: #111827;\n font-size: 11px;\n}\n.hw-tooltip__name {\n color: #4b5563;\n}\n.hw-tooltip__hint {\n color: #6b7280;\n font-style: italic;\n font-size: 11px;\n margin-top: 6px;\n}\n.hw-tooltip__rdkit {\n display: block;\n margin-top: 8px;\n /* padding-top: 8px; */\n border-top: 1px solid #f3f4f6;\n background: #fafafa;\n border-radius: 4px;\n}\n/* Phase 23 (T-2303) -- The user reported "molecules do not take the full\n space" in the tooltip. RDKit emits an svg with a `viewBox`, so\n `width: 100%; height: auto` lets the structure stretch responsively\n to whatever width the parent tooltip column has. `max-height` caps\n tall structures so they never blow up the tooltip vertically. */\n.hw-tooltip__rdkit svg,\n[data-testid="atom-tooltip-rdkit-svg"] svg,\n[data-testid="palette-tooltip-rdkit-svg"] svg,\n[data-testid="builder-tooltip-rdkit-svg"] svg {\n display: block;\n width: 100%;\n height: auto;\n max-height: 180px;\n margin: 0 auto;\n}\n/* Legacy aliases (kept so Phase 21 atom-tooltip text styling still\n resolves). The body text colour is now driven by the parent tooltip\n rule above; the legacy classes keep the line-wrap behaviour. */\n.hw-atom-tooltip__text {\n display: block;\n}\n\n/* Status indicator (T-1106) -- small badge in the bottom-left of the canvas. */\n.hw-status-bar {\n position: absolute;\n left: 6px;\n bottom: 6px;\n padding: 2px 8px;\n background: rgba(255, 255, 255, 0.85);\n color: var(--hw-fg);\n border: 1px solid var(--hw-border);\n border-radius: 3px;\n font-size: 11px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n pointer-events: none;\n z-index: 50;\n}\n.hw-app--dark .hw-status-bar { background: rgba(34, 36, 41, 0.85); }\n\n.hw-status-bar__mode {\n display: inline-flex;\n align-items: center;\n gap: 0;\n}\n.hw-status-bar__message {\n display: inline-block;\n margin-left: 8px;\n font-weight: 500;\n}\n.hw-status-bar__message[data-severity="info"] { color: var(--hw-fg); }\n.hw-status-bar__message[data-severity="warn"] { color: #b8860b; }\n.hw-status-bar__message[data-severity="error"] { color: #c0392b; }\n.hw-app--dark .hw-status-bar__message[data-severity="warn"] { color: #f7c948; }\n.hw-app--dark .hw-status-bar__message[data-severity="error"] { color: #ff6b6b; }\n\n/* Phase 25 (T-2504) -- "Next add: X [x]" clear button. The status bar\n itself sets `pointer-events: none` (it floats above the canvas as a\n non-interactive badge), so the button explicitly re-enables hits on\n itself only. Visible only when `nextAdd` is primed because the\n element is conditionally appended in `_refreshStatus`. */\n.hw-status-bar__next-add-symbol {\n display: inline-block;\n font-weight: 600;\n}\n.hw-status-bar__next-add-clear {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 16px;\n height: 16px;\n margin-left: 6px;\n padding: 0;\n background: transparent;\n border: 1px solid #d1d5db;\n border-radius: 50%;\n color: #6b7280;\n font-size: 12px;\n line-height: 1;\n cursor: pointer;\n pointer-events: auto;\n}\n.hw-status-bar__next-add-clear:hover {\n background: #f3f4f6;\n color: #1f2937;\n border-color: #9ca3af;\n}\n\n.hw-bond-preview { pointer-events: none; opacity: 0.85; }\n\n.hw-help-modal-backdrop {\n position: fixed; left: 0; top: 0; right: 0; bottom: 0;\n background: rgba(0,0,0,0.4);\n display: flex; align-items: center; justify-content: center;\n z-index: 2000;\n}\n.hw-help-modal {\n background: #ffffff;\n color: #1a1a1a;\n padding: 16px 20px;\n border-radius: 4px;\n max-width: 480px;\n font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;\n font-size: 13px;\n box-shadow: 0 10px 20px rgba(0,0,0,0.3);\n}\n.hw-help-modal h2 { margin: 0 0 8px 0; font-size: 16px; }\n.hw-help-modal ul { padding-left: 20px; line-height: 1.6; }\n.hw-help-modal kbd {\n background: #eef0f3;\n border: 1px solid #cbd0d6;\n border-radius: 3px;\n padding: 1px 4px;\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 12px;\n}\n.hw-help-modal__close {\n margin-top: 12px;\n padding: 4px 12px;\n border: 1px solid #cbd0d6;\n background: #f5f6f8;\n cursor: pointer;\n border-radius: 3px;\n}\n'],sourceRoot:""}]);const a=s},314(e){"use strict";e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var i="",n=void 0!==t[5];return t[4]&&(i+="@supports (".concat(t[4],") {")),t[2]&&(i+="@media ".concat(t[2]," {")),n&&(i+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),i+=e(t),n&&(i+="}"),t[2]&&(i+="}"),t[4]&&(i+="}"),i}).join("")},t.i=function(e,i,n,o,r){"string"==typeof e&&(e=[[null,e,void 0]]);var s={};if(n)for(var a=0;a<this.length;a++){var l=this[a][0];null!=l&&(s[l]=!0)}for(var h=0;h<e.length;h++){var d=[].concat(e[h]);n&&s[d[0]]||(void 0!==r&&(void 0===d[5]||(d[1]="@layer".concat(d[5].length>0?" ".concat(d[5]):""," {").concat(d[1],"}")),d[5]=r),i&&(d[2]?(d[1]="@media ".concat(d[2]," {").concat(d[1],"}"),d[2]=i):d[2]=i),o&&(d[4]?(d[1]="@supports (".concat(d[4],") {").concat(d[1],"}"),d[4]=o):d[4]="".concat(o)),t.push(d))}},t}},354(e){"use strict";e.exports=function(e){var t=e[1],i=e[3];if(!i)return t;if("function"==typeof btoa){var n=btoa(unescape(encodeURIComponent(JSON.stringify(i)))),o="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(n),r="/*# ".concat(o," */");return[t].concat([r]).join("\n")}return[t].join("\n")}},982(e,t,i){var n;!function(){var t={};!function(e){"use strict";e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function i(e,i,n,o,r){for(var s,a,l,h,d,c,u,p,m,f,b,g,A;r>=64;){for(s=i[0],a=i[1],l=i[2],h=i[3],d=i[4],c=i[5],u=i[6],p=i[7],f=0;f<16;f++)b=o+4*f,e[f]=(255&n[b])<<24|(255&n[b+1])<<16|(255&n[b+2])<<8|255&n[b+3];for(f=16;f<64;f++)g=((m=e[f-2])>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,A=((m=e[f-15])>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,e[f]=(g+e[f-7]|0)+(A+e[f-16]|0);for(f=0;f<64;f++)g=(((d>>>6|d<<26)^(d>>>11|d<<21)^(d>>>25|d<<7))+(d&c^~d&u)|0)+(p+(t[f]+e[f]|0)|0)|0,A=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&a^s&l^a&l)|0,p=u,u=c,c=d,d=h+g|0,h=l,l=a,a=s,s=g+A|0;i[0]+=s,i[1]+=a,i[2]+=l,i[3]+=h,i[4]+=d,i[5]+=c,i[6]+=u,i[7]+=p,o+=64,r-=64}return o}var n=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(void 0===t&&(t=e.length),this.finished)throw new Error("SHA256: can't update because hash was finished.");var n=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[n++],t--;64===this.bufferLength&&(i(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(n=i(this.temp,this.state,e,n,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[n++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,n=this.bufferLength,o=t/536870912|0,r=t<<3,s=t%64<56?64:128;this.buffer[n]=128;for(var a=n+1;a<s-8;a++)this.buffer[a]=0;this.buffer[s-8]=o>>>24&255,this.buffer[s-7]=o>>>16&255,this.buffer[s-6]=o>>>8&255,this.buffer[s-5]=o>>>0&255,this.buffer[s-4]=r>>>24&255,this.buffer[s-3]=r>>>16&255,this.buffer[s-2]=r>>>8&255,this.buffer[s-1]=r>>>0&255,i(this.temp,this.state,this.buffer,0,s),this.finished=!0}for(a=0;a<8;a++)e[4*a+0]=this.state[a]>>>24&255,e[4*a+1]=this.state[a]>>>16&255,e[4*a+2]=this.state[a]>>>8&255,e[4*a+3]=this.state[a]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var i=0;i<this.state.length;i++)this.state[i]=e[i];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=n;var o=function(){function e(e){this.inner=new n,this.outer=new n,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)(new n).update(e).finish(t).clean();else for(var i=0;i<e.length;i++)t[i]=e[i];for(i=0;i<t.length;i++)t[i]^=54;for(this.inner.update(t),i=0;i<t.length;i++)t[i]^=106;for(this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate),i=0;i<t.length;i++)t[i]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();function r(e){var t=(new n).update(e),i=t.digest();return t.clean(),i}function s(e,t){var i=new o(e).update(t),n=i.digest();return i.clean(),n}function a(e,t,i,n){var o=n[0];if(0===o)throw new Error("hkdf: cannot expand more");t.reset(),o>1&&t.update(e),i&&t.update(i),t.update(n),t.finish(e),n[0]++}e.HMAC=o,e.hash=r,e.default=r,e.hmac=s;var l=new Uint8Array(e.digestLength);e.hkdf=function(e,t,i,n){void 0===t&&(t=l),void 0===n&&(n=32);for(var r=new Uint8Array([1]),h=s(t,e),d=new o(h),c=new Uint8Array(d.digestLength),u=c.length,p=new Uint8Array(n),m=0;m<n;m++)u===c.length&&(a(c,d,i,r),u=0),p[m]=c[u++];return d.clean(),c.fill(0),r.fill(0),p},e.pbkdf2=function(e,t,i,n){for(var r=new o(e),s=r.digestLength,a=new Uint8Array(4),l=new Uint8Array(s),h=new Uint8Array(s),d=new Uint8Array(n),c=0;c*s<n;c++){var u=c+1;a[0]=u>>>24&255,a[1]=u>>>16&255,a[2]=u>>>8&255,a[3]=u>>>0&255,r.reset(),r.update(t),r.update(a),r.finish(h);for(var p=0;p<s;p++)l[p]=h[p];for(p=2;p<=i;p++){r.reset(),r.update(h).finish(h);for(var m=0;m<s;m++)l[m]^=h[m]}for(p=0;p<s&&c*s+p<n;p++)d[c*s+p]=l[p]}for(c=0;c<s;c++)l[c]=h[c]=0;for(c=0;c<4;c++)a[c]=0;return r.clean(),d}}(t);var o=t.default;for(var r in t)o[r]=t[r];"object"==typeof e.exports?e.exports=o:void 0===(n=function(){return o}.call(t,i,t,e))||(e.exports=n)}()},72(e){"use strict";var t=[];function i(e){for(var i=-1,n=0;n<t.length;n++)if(t[n].identifier===e){i=n;break}return i}function n(e,n){for(var r={},s=[],a=0;a<e.length;a++){var l=e[a],h=n.base?l[0]+n.base:l[0],d=r[h]||0,c="".concat(h," ").concat(d);r[h]=d+1;var u=i(c),p={css:l[1],media:l[2],sourceMap:l[3],supports:l[4],layer:l[5]};if(-1!==u)t[u].references++,t[u].updater(p);else{var m=o(p,n);n.byIndex=a,t.splice(a,0,{identifier:c,updater:m,references:1})}s.push(c)}return s}function o(e,t){var i=t.domAPI(t);return i.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;i.update(e=t)}else i.remove()}}e.exports=function(e,o){var r=n(e=e||[],o=o||{});return function(e){e=e||[];for(var s=0;s<r.length;s++){var a=i(r[s]);t[a].references--}for(var l=n(e,o),h=0;h<r.length;h++){var d=i(r[h]);0===t[d].references&&(t[d].updater(),t.splice(d,1))}r=l}}},659(e){"use strict";var t={};e.exports=function(e,i){var n=function(e){if(void 0===t[e]){var i=document.querySelector(e);if(window.HTMLIFrameElement&&i instanceof window.HTMLIFrameElement)try{i=i.contentDocument.head}catch(e){i=null}t[e]=i}return t[e]}(e);if(!n)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");n.appendChild(i)}},540(e){"use strict";e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},56(e,t,i){"use strict";e.exports=function(e){var t=i.nc;t&&e.setAttribute("nonce",t)}},825(e){"use strict";e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(i){!function(e,t,i){var n="";i.supports&&(n+="@supports (".concat(i.supports,") {")),i.media&&(n+="@media ".concat(i.media," {"));var o=void 0!==i.layer;o&&(n+="@layer".concat(i.layer.length>0?" ".concat(i.layer):""," {")),n+=i.css,o&&(n+="}"),i.media&&(n+="}"),i.supports&&(n+="}");var r=i.sourceMap;r&&"undefined"!=typeof btoa&&(n+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(r))))," */")),t.styleTagTransform(n,e,t.options)}(t,e,i)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},113(e){"use strict";e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},921(e,t,i){"use strict";i.d(t,{KP:()=>n});const n=20},333(e,t,i){"use strict";i.r(t),i.d(t,{PackageFunctions:()=>Ae,_package:()=>fe,editMoleculeCell:()=>ne,getHelmHelper:()=>he,getMolfiles:()=>ae,helmCellRenderer:()=>ie,helmInput:()=>le,helmPanel:()=>oe,highlightMonomers:()=>ce,initHelm:()=>te,measureCellRenderer:()=>de,openEditor:()=>re,propertiesWidget:()=>se});var n=i(328),o=i(389),r=i(82),s=i(757),a=i.n(s);i(982),DG.DataFrame.fromCsv('countries,fasta,smiles,molregno,LON,Zip Code,Street Address Line 1,ImageUrl,user_id,error_message,xray,flag,magnitude,CS-id,pdb_id,accel_a,time_offset,chart,fit,Questions,empty_number,empty_string\nBelgium,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C(=O)OCCCc1cccnc1)c2cccc(c2)C(=O)c3ccccc3,1480014,36.276729583740234,995042300,14016 ROUTE 31W,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,1,1,1QBS,1,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.497360340644872, 1.7058694986686864, 5.278052678195135, 0.16000320889028383],""points"":[{""x"":0.10000000149011612,""y"":2.374499797821045},{""x"":0.6000000238418579,""y"":2.6242473125457764},{""x"":1.100000023841858,""y"":2.367267608642578},{""x"":1.600000023841858,""y"":2.6723148822784424},{""x"":2.0999999046325684,""y"":2.6537344455718994},{""x"":2.5999999046325684,""y"":2.3651671409606934},{""x"":3.0999999046325684,""y"":2.5654284954071045},{""x"":3.5999999046325684,""y"":2.4160959720611572},{""x"":4.099999904632568,""y"":2.286726713180542},{""x"":4.599999904632568,""y"":2.5100042819976807},{""x"":5.099999904632568,""y"":1.6676985025405884},{""x"":5.599999904632568,""y"":0.680136501789093},{""x"":6.099999904632568,""y"":0.3391543924808502},{""x"":6.599999904632568,""y"":0.09038983285427094},{""x"":7.099999904632568,""y"":0.19802775979042053}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[7.525235855508179, 1.3186911876809984, 5.335672608564294, 0.7860743343958098],""points"":[{""x"":0.10000000149011612,""y"":7.988070487976074},{""x"":0.6000000238418579,""y"":7.018453121185303},{""x"":1.100000023841858,""y"":8.115279197692871},{""x"":1.600000023841858,""y"":7.486658096313477},{""x"":2.0999999046325684,""y"":7.396438121795654},{""x"":2.5999999046325684,""y"":7.477052211761475},{""x"":3.0999999046325684,""y"":6.913095474243164},{""x"":3.5999999046325684,""y"":8.01385498046875},{""x"":4.099999904632568,""y"":6.985900402069092},{""x"":4.599999904632568,""y"":6.970335960388184},{""x"":5.099999904632568,""y"":5.448817253112793},{""x"":5.599999904632568,""y"":2.5534818172454834},{""x"":6.099999904632568,""y"":1.893947958946228},{""x"":6.599999904632568,""y"":0.6340042352676392},{""x"":7.099999904632568,""y"":0.8403874039649963}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,100,abc\nBurundi,MDYKETLLMPKTDFPMRGGLPNKEPQIQEKW,COc1ccc2cc(ccc2c1)C(C)C(=O)Oc3ccc(C)cc3OC,1480015,36.276729583740234,995073444,80 STATE HIGHWAY 310,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,2,2,1ZP8,2,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.431460753103398, 2.1691498799246745, 5.266445597102774, 0.7825762827017926],""points"":[{""x"":0.10000000149011612,""y"":4.751083850860596},{""x"":0.6000000238418579,""y"":4.203000068664551},{""x"":1.100000023841858,""y"":4.415858745574951},{""x"":1.600000023841858,""y"":4.68414306640625},{""x"":2.0999999046325684,""y"":4.198400974273682},{""x"":2.5999999046325684,""y"":4.179222106933594},{""x"":3.0999999046325684,""y"":4.638473987579346},{""x"":3.5999999046325684,""y"":4.708553314208984},{""x"":4.099999904632568,""y"":4.291589260101318},{""x"":4.599999904632568,""y"":4.038082599639893},{""x"":5.099999904632568,""y"":3.4349939823150635},{""x"":5.599999904632568,""y"":1.2194708585739136},{""x"":6.099999904632568,""y"":1.1920831203460693},{""x"":6.599999904632568,""y"":0.5352635979652405},{""x"":7.099999904632568,""y"":0.3346920311450958}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.339458017970126, -1.0734184310171178, 4.746332950550934, 0.2482416857595658],""points"":[{""x"":0.10000000149011612,""y"":0.2139337658882141},{""x"":0.6000000238418579,""y"":0.4269562065601349},{""x"":1.100000023841858,""y"":0.2441573292016983},{""x"":1.600000023841858,""y"":0.146635964512825},{""x"":2.0999999046325684,""y"":0.08818462491035461},{""x"":2.5999999046325684,""y"":0.2560656666755676},{""x"":3.0999999046325684,""y"":0.42434045672416687},{""x"":3.5999999046325684,""y"":0.37111231684684753},{""x"":4.099999904632568,""y"":0.5581737160682678},{""x"":4.599999904632568,""y"":1.183590054512024},{""x"":5.099999904632568,""y"":1.5629843473434448},{""x"":5.599999904632568,""y"":2.3211288452148438},{""x"":6.099999904632568,""y"":2.229961633682251},{""x"":6.599999904632568,""y"":2.2560226917266846},{""x"":7.099999904632568,""y"":2.2142398357391357}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCameroon,MIEVFLFGIVLGLIPITLAGLFVTAYLQYRRGDQLDL,COc1ccc2cc(ccc2c1)C(C)C(=O)OCCCc3cccnc3,1480016,36.26095962524414,995153596,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,3,3,2BDJ,3,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[4.6760652578642325, 0.9046956320756703, 5.651408971856738, 0.07738846012184185],""points"":[{""x"":0.10000000149011612,""y"":4.32425594329834},{""x"":0.6000000238418579,""y"":4.668442249298096},{""x"":1.100000023841858,""y"":4.379785060882568},{""x"":1.600000023841858,""y"":5.0345139503479},{""x"":2.0999999046325684,""y"":4.878653526306152},{""x"":2.5999999046325684,""y"":4.3451313972473145},{""x"":3.0999999046325684,""y"":4.336992263793945},{""x"":3.5999999046325684,""y"":5.037430286407471},{""x"":4.099999904632568,""y"":5.0092692375183105},{""x"":4.599999904632568,""y"":4.151902675628662},{""x"":5.099999904632568,""y"":3.4066951274871826},{""x"":5.599999904632568,""y"":2.3732759952545166},{""x"":6.099999904632568,""y"":1.673728108406067},{""x"":6.599999904632568,""y"":0.48574790358543396},{""x"":7.099999904632568,""y"":0.2783052325248718}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[2.938395863010111, -1.4658480661392117, 5.462702751996584, 0.3473139023615039],""points"":[{""x"":0.10000000149011612,""y"":0.4941710829734802},{""x"":0.6000000238418579,""y"":0.15323974192142487},{""x"":1.100000023841858,""y"":0.46373432874679565},{""x"":1.600000023841858,""y"":0.3370431363582611},{""x"":2.0999999046325684,""y"":0.5179030299186707},{""x"":2.5999999046325684,""y"":0.27899765968322754},{""x"":3.0999999046325684,""y"":0.22075064480304718},{""x"":3.5999999046325684,""y"":0.5789918899536133},{""x"":4.099999904632568,""y"":0.21169911324977875},{""x"":4.599999904632568,""y"":0.27857646346092224},{""x"":5.099999904632568,""y"":1.0906332731246948},{""x"":5.599999904632568,""y"":1.8520300388336182},{""x"":6.099999904632568,""y"":2.7177059650421143},{""x"":6.599999904632568,""y"":2.8680918216705322},{""x"":7.099999904632568,""y"":3.2413077354431152}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCanada,MMELVLKTIIGPIVVGVVLRIVDKWLNKDK,CC(C(=O)NCCS)c1cccc(c1)C(=O)c2ccccc2,1480017,36.26095962524414,99515,30-56 WHITESTONE EXPY,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,4,4,1IAN,4,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[0.8597390975430008, 1.0957625732481946, 5.260537067987958, 0.07974187998177736],""points"":[{""x"":0.10000000149011612,""y"":0.8190152645111084},{""x"":0.6000000238418579,""y"":0.8421689867973328},{""x"":1.100000023841858,""y"":0.8740922212600708},{""x"":1.600000023841858,""y"":0.8924275040626526},{""x"":2.0999999046325684,""y"":0.8249067664146423},{""x"":2.5999999046325684,""y"":0.9327669143676758},{""x"":3.0999999046325684,""y"":0.8522974252700806},{""x"":3.5999999046325684,""y"":0.8174492716789246},{""x"":4.099999904632568,""y"":0.8394647240638733},{""x"":4.599999904632568,""y"":0.7139387726783752},{""x"":5.099999904632568,""y"":0.5561167597770691},{""x"":5.599999904632568,""y"":0.3276226818561554},{""x"":6.099999904632568,""y"":0.12479474395513535},{""x"":6.599999904632568,""y"":0.13006797432899475},{""x"":7.099999904632568,""y"":0.059702079743146896}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.760930219582546, 1.6591793293833013, 4.667155929720851, 0.7858109544121652],""points"":[{""x"":0.10000000149011612,""y"":6.156993389129639},{""x"":0.6000000238418579,""y"":5.236701965332031},{""x"":1.100000023841858,""y"":6.010560512542725},{""x"":1.600000023841858,""y"":5.495512962341309},{""x"":2.0999999046325684,""y"":6.087770462036133},{""x"":2.5999999046325684,""y"":5.79986572265625},{""x"":3.0999999046325684,""y"":5.597546577453613},{""x"":3.5999999046325684,""y"":5.520902156829834},{""x"":4.099999904632568,""y"":5.360654354095459},{""x"":4.599999904632568,""y"":3.5539746284484863},{""x"":5.099999904632568,""y"":1.577236294746399},{""x"":5.599999904632568,""y"":1.0001264810562134},{""x"":6.099999904632568,""y"":0.9305797815322876},{""x"":6.599999904632568,""y"":0.6033638715744019},{""x"":7.099999904632568,""y"":0.4203685522079468}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nColombia,MDRTDEVSNHTHDKPTLTWFEEIFEEYHSPFHN,FC(F)(F)c1ccc(OC2CCNCC2)cc1,1480029,36.3309440612793,995152050,1 COURT HOUSE SQUARE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,5,5,4UJ1,5,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[6.4995088314153655, 2.4270351004539914, 5.178659535348579, 0.625653346241577],""points"":[{""x"":0.10000000149011612,""y"":6.496231555938721},{""x"":0.6000000238418579,""y"":6.42543363571167},{""x"":1.100000023841858,""y"":7.040063858032227},{""x"":1.600000023841858,""y"":6.1115403175354},{""x"":2.0999999046325684,""y"":6.680728435516357},{""x"":2.5999999046325684,""y"":6.406774520874023},{""x"":3.0999999046325684,""y"":6.611269474029541},{""x"":3.5999999046325684,""y"":5.889094352722168},{""x"":4.099999904632568,""y"":6.75344705581665},{""x"":4.599999904632568,""y"":6.361435890197754},{""x"":5.099999904632568,""y"":4.1666975021362305},{""x"":5.599999904632568,""y"":1.172118902206421},{""x"":6.099999904632568,""y"":0.801048994064331},{""x"":6.599999904632568,""y"":0.4640021026134491},{""x"":7.099999904632568,""y"":0.0010357667924836278}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[1.4734381347446401, 1.1649805188074196, 4.82958608866421, 0.09500545496710007],""points"":[{""x"":0.10000000149011612,""y"":1.5279096364974976},{""x"":0.6000000238418579,""y"":1.3559974431991577},{""x"":1.100000023841858,""y"":1.5246378183364868},{""x"":1.600000023841858,""y"":1.5567657947540283},{""x"":2.0999999046325684,""y"":1.4114240407943726},{""x"":2.5999999046325684,""y"":1.4045010805130005},{""x"":3.0999999046325684,""y"":1.4769829511642456},{""x"":3.5999999046325684,""y"":1.4875500202178955},{""x"":4.099999904632568,""y"":1.2991987466812134},{""x"":4.599999904632568,""y"":0.922961413860321},{""x"":5.099999904632568,""y"":0.6520044803619385},{""x"":5.599999904632568,""y"":0.15350978076457977},{""x"":6.099999904632568,""y"":0.1078903079032898},{""x"":6.599999904632568,""y"":0.17276449501514435},{""x"":7.099999904632568,""y"":0.14066608250141144}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCosta Rica,MKSTKEEIQTIKTLLKDSRTAKYHKRLQIVL,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCCc3ccccc3,1480018,36.3309440612793,995084218,4041 SOUTHWESTERN BLVD,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,6,6,2BPW,6,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.4833641843311227, -1.8945978742090062, 4.671127708092568, 0.24159861311815153],""points"":[{""x"":0.10000000149011612,""y"":0.0969524160027504},{""x"":0.6000000238418579,""y"":0.028483040630817413},{""x"":1.100000023841858,""y"":0.22087176144123077},{""x"":1.600000023841858,""y"":0.0068915546871721745},{""x"":2.0999999046325684,""y"":0.4305879771709442},{""x"":2.5999999046325684,""y"":0.44774115085601807},{""x"":3.0999999046325684,""y"":0.45346319675445557},{""x"":3.5999999046325684,""y"":0.2370593100786209},{""x"":4.099999904632568,""y"":0.4657953977584839},{""x"":4.599999904632568,""y"":1.155200719833374},{""x"":5.099999904632568,""y"":2.2294070720672607},{""x"":5.599999904632568,""y"":2.4311530590057373},{""x"":6.099999904632568,""y"":2.33846116065979},{""x"":6.599999904632568,""y"":2.608201026916504},{""x"":7.099999904632568,""y"":2.8136143684387207}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.224573521642033, 1.4454033924198528, 5.6014197746076535, 0.2823216054197577],""points"":[{""x"":0.10000000149011612,""y"":4.95027494430542},{""x"":0.6000000238418579,""y"":5.1754679679870605},{""x"":1.100000023841858,""y"":5.276752948760986},{""x"":1.600000023841858,""y"":5.589294910430908},{""x"":2.0999999046325684,""y"":5.616994857788086},{""x"":2.5999999046325684,""y"":5.120813846588135},{""x"":3.0999999046325684,""y"":5.340766906738281},{""x"":3.5999999046325684,""y"":4.876471042633057},{""x"":4.099999904632568,""y"":4.94999361038208},{""x"":4.599999904632568,""y"":5.162564754486084},{""x"":5.099999904632568,""y"":4.399557590484619},{""x"":5.599999904632568,""y"":2.7977969646453857},{""x"":6.099999904632568,""y"":1.0229872465133667},{""x"":6.599999904632568,""y"":0.48275601863861084},{""x"":7.099999904632568,""y"":0.10408931970596313}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nCuba,MHAILRYFIRRLFYHIFYKIYSLISKKHQSLPSDVRQF,COc1ccc2c(c1)c(CC(=O)N3CCCC3C(=O)Oc4ccc(C)cc4OC)c(C)n2C(=O)c5ccc(Cl)cc5,1480019,36.33115768432617,995081928,1227 US HIGHWAY 11,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,7,7,1QBS,7,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.320838679713925, -1.2421619987316728, 4.831325425225256, 0.3236011098403072],""points"":[{""x"":0.10000000149011612,""y"":0.3727470338344574},{""x"":0.6000000238418579,""y"":0.12365014106035233},{""x"":1.100000023841858,""y"":0.48422467708587646},{""x"":1.600000023841858,""y"":0.2264465093612671},{""x"":2.0999999046325684,""y"":0.16821794211864471},{""x"":2.5999999046325684,""y"":0.3879014551639557},{""x"":3.0999999046325684,""y"":0.5470244884490967},{""x"":3.5999999046325684,""y"":0.3419053554534912},{""x"":4.099999904632568,""y"":0.7655120491981506},{""x"":4.599999904632568,""y"":1.2346516847610474},{""x"":5.099999904632568,""y"":2.453336715698242},{""x"":5.599999904632568,""y"":2.9565491676330566},{""x"":6.099999904632568,""y"":3.335299491882324},{""x"":6.599999904632568,""y"":3.240290880203247},{""x"":7.099999904632568,""y"":3.1107218265533447}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.6401853521511094, 1.26211588875013, 5.399028074402744, 0.5089580830068091],""points"":[{""x"":0.10000000149011612,""y"":3.8585598468780518},{""x"":0.6000000238418579,""y"":3.6077206134796143},{""x"":1.100000023841858,""y"":3.855252265930176},{""x"":1.600000023841858,""y"":3.619039297103882},{""x"":2.0999999046325684,""y"":3.839388370513916},{""x"":2.5999999046325684,""y"":3.335283041000366},{""x"":3.0999999046325684,""y"":3.571141481399536},{""x"":3.5999999046325684,""y"":3.4155046939849854},{""x"":4.099999904632568,""y"":3.7316646575927734},{""x"":4.599999904632568,""y"":3.0680155754089355},{""x"":5.099999904632568,""y"":2.891066551208496},{""x"":5.599999904632568,""y"":1.6022753715515137},{""x"":6.099999904632568,""y"":0.7652576565742493},{""x"":6.599999904632568,""y"":0.6875326037406921},{""x"":7.099999904632568,""y"":0.5828871726989746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nItaly,MSNFHNEHVMQFYRNNLKTKGVFGRQ,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO[N+](=O)[O-],1480020,36.33115768432617,99502,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,8,8,1ZP8,8,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[2.293592105923809, 1.3781586549141835, 5.1025898038676605, 0.03493851245291291],""points"":[{""x"":0.10000000149011612,""y"":2.1287283897399902},{""x"":0.6000000238418579,""y"":2.267972230911255},{""x"":1.100000023841858,""y"":2.398442506790161},{""x"":1.600000023841858,""y"":2.5130622386932373},{""x"":2.0999999046325684,""y"":2.3255116939544678},{""x"":2.5999999046325684,""y"":2.127340793609619},{""x"":3.0999999046325684,""y"":2.47259783744812},{""x"":3.5999999046325684,""y"":2.131181478500366},{""x"":4.099999904632568,""y"":2.090421438217163},{""x"":4.599999904632568,""y"":2.02299165725708},{""x"":5.099999904632568,""y"":1.1105059385299683},{""x"":5.599999904632568,""y"":0.4494485855102539},{""x"":6.099999904632568,""y"":0.1375635862350464},{""x"":6.599999904632568,""y"":0.036351121962070465},{""x"":7.099999904632568,""y"":0.1619771122932434}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.953125499439879, 1.2528620255306528, 5.187637440149802, 0.3110348753260886],""points"":[{""x"":0.10000000149011612,""y"":5.6585283279418945},{""x"":0.6000000238418579,""y"":5.911152362823486},{""x"":1.100000023841858,""y"":5.924920082092285},{""x"":1.600000023841858,""y"":5.8469438552856445},{""x"":2.0999999046325684,""y"":5.929472923278809},{""x"":2.5999999046325684,""y"":6.190037727355957},{""x"":3.0999999046325684,""y"":6.236179828643799},{""x"":3.5999999046325684,""y"":6.141019344329834},{""x"":4.099999904632568,""y"":5.295210838317871},{""x"":4.599999904632568,""y"":5.265801906585693},{""x"":5.099999904632568,""y"":3.3722851276397705},{""x"":5.599999904632568,""y"":1.8299226760864258},{""x"":6.099999904632568,""y"":0.32690900564193726},{""x"":6.599999904632568,""y"":0.6274543404579163},{""x"":7.099999904632568,""y"":0.8441857099533081}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nRwanda,MPNSEPASLLELFNSIATQGELVRSLKAGNASK,CC(C)Cc1ccc(cc1)C(C)C(=O)N2CCCC2C(=O)OCCO,1480021,36.33137130737305,995037247,"168-46 91ST AVE., 2ND FLR",https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,9,2BDJ,9,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[3.8209972202654474, 1.3779216716448506, 5.299882228439686, 0.06040645519069608],""points"":[{""x"":0.10000000149011612,""y"":3.7821109294891357},{""x"":0.6000000238418579,""y"":3.542433023452759},{""x"":1.100000023841858,""y"":3.7008674144744873},{""x"":1.600000023841858,""y"":3.717301607131958},{""x"":2.0999999046325684,""y"":4.024452209472656},{""x"":2.5999999046325684,""y"":4.013899326324463},{""x"":3.0999999046325684,""y"":3.945094347000122},{""x"":3.5999999046325684,""y"":3.866621971130371},{""x"":4.099999904632568,""y"":3.7461626529693604},{""x"":4.599999904632568,""y"":3.3454740047454834},{""x"":5.099999904632568,""y"":2.61944317817688},{""x"":5.599999904632568,""y"":0.999405026435852},{""x"":6.099999904632568,""y"":0.46259793639183044},{""x"":6.599999904632568,""y"":0.054134611040353775},{""x"":7.099999904632568,""y"":0.05711187422275543}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[5.6318079657726035, 1.8495493770000595, 5.391793312471116, 0.17060707587348442],""points"":[{""x"":0.10000000149011612,""y"":5.458079814910889},{""x"":0.6000000238418579,""y"":5.554427146911621},{""x"":1.100000023841858,""y"":5.799983024597168},{""x"":1.600000023841858,""y"":5.364140033721924},{""x"":2.0999999046325684,""y"":5.864485740661621},{""x"":2.5999999046325684,""y"":5.4509806632995605},{""x"":3.0999999046325684,""y"":5.702574729919434},{""x"":3.5999999046325684,""y"":5.7314534187316895},{""x"":4.099999904632568,""y"":5.5123443603515625},{""x"":4.599999904632568,""y"":5.724395751953125},{""x"":5.099999904632568,""y"":4.354506969451904},{""x"":5.599999904632568,""y"":1.7307666540145874},{""x"":6.099999904632568,""y"":0.6305936574935913},{""x"":6.599999904632568,""y"":0.035183437168598175},{""x"":7.099999904632568,""y"":0.7575169205665588}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\nSwitzerland,IRVVGRYLIEVWKAAGMDMDKVLFLWSSDEI,CN1CCC(CC1)Oc2ccc(cc2)C(F)(F)F,1480028,36.33137130737305,99504,92-11 179TH PLACE,https://datagrok.ai/img/slides/access-db-connect.png,id,ErrorMessage,"COMPND \nATOM \nEND",flag,9,10,1IAN,10,1.23,<chart></chart>,"{""series"":[{""name"":""Run:2023-08-08"",""fitFunction"":""sigmoid"",""fitLineColor"":""#1f77b4"",""pointColor"":""#1f77b4"",""showPoints"":""points"",""parameters"":[1.1190255865097471, 2.3163895161544437, 5.4968866182279195, 0.2035204047289052],""points"":[{""x"":0.10000000149011612,""y"":1.1057683229446411},{""x"":0.6000000238418579,""y"":1.1019697189331055},{""x"":1.100000023841858,""y"":1.0818607807159424},{""x"":1.600000023841858,""y"":1.062997817993164},{""x"":2.0999999046325684,""y"":1.046447515487671},{""x"":2.5999999046325684,""y"":1.1217249631881714},{""x"":3.0999999046325684,""y"":1.2166996002197266},{""x"":3.5999999046325684,""y"":1.215477705001831},{""x"":4.099999904632568,""y"":1.0581893920898438},{""x"":4.599999904632568,""y"":1.1747995615005493},{""x"":5.099999904632568,""y"":1.0181127786636353},{""x"":5.599999904632568,""y"":0.5344523191452026},{""x"":6.099999904632568,""y"":0.2569526433944702},{""x"":6.599999904632568,""y"":0.1912207305431366},{""x"":7.099999904632568,""y"":0.15060538053512573}]},{""name"":""Run:2023-08-08"",""fitLineColor"":""#ffbb78"",""pointColor"":""#ffbb78"",""showPoints"":""points"",""parameters"":[3.1038581025805785, 2.0032224204185245, 5.087602825989163, 0.13277988512492753],""points"":[{""x"":0.10000000149011612,""y"":3.0498509407043457},{""x"":0.6000000238418579,""y"":2.805217742919922},{""x"":1.100000023841858,""y"":3.3415253162384033},{""x"":1.600000023841858,""y"":3.0549843311309814},{""x"":2.0999999046325684,""y"":3.250074863433838},{""x"":2.5999999046325684,""y"":3.0432586669921875},{""x"":3.0999999046325684,""y"":3.265852451324463},{""x"":3.5999999046325684,""y"":2.9475724697113037},{""x"":4.099999904632568,""y"":3.1929898262023926},{""x"":4.599999904632568,""y"":2.7460060119628906},{""x"":5.099999904632568,""y"":1.6175861358642578},{""x"":5.599999904632568,""y"":0.3006608486175537},{""x"":6.099999904632568,""y"":0.3444803059101105},{""x"":6.599999904632568,""y"":0.015537971630692482},{""x"":7.099999904632568,""y"":0.5527358055114746}]}],""chartOptions"":{""xAxisName"":""Conc."",""yAxisName"":""Activity"",""title"":""Dose-Response curves""}}",text,,\n,,,,,,,,,,,,,,,,,,,,,').columns.add(DG.Column.fromList(DG.TYPE.BYTE_ARRAY,"BinaryImage",Array.from(new Uint8Array(11))));var l;function h(e,t,i,n=0,o="timeout"){return r=this,s=void 0,l=function*(){return new Promise((r,s)=>{const a=e.subscribe(e=>{try{t(e),r("OK")}catch(e){s(e)}finally{a.unsubscribe(),clearTimeout(l)}}),l=setTimeout(()=>{a.unsubscribe(),s(o)},n);i()})},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{o(l.next(e))}catch(e){t(e)}}function n(e){try{o(l.throw(e))}catch(e){t(e)}}function o(t){var o;t.done?e(t.value):(o=t.value,o instanceof a?o:new a(function(e){e(o)})).then(i,n)}o((l=l.apply(r,s||[])).next())});var r,s,a,l}function d(e){return"string"==typeof e||e instanceof String?e:"StateError"===e.constructor.name?e.message:"StateError"===e.constructor.name&&"$thrownJsError"in e?d(e.$thrownJsError):e instanceof Error?e.message:e.toString()}function c(e){return e instanceof Error?e.stack:"StateError"===e.constructor.name&&"$thrownJsError"in e?c(e.$thrownJsError):void 0}function u(e){return[d(e),c(e)]}console.log.bind(console),console.info.bind(console),console.warn.bind(console),console.error.bind(console),function(e){e.notNull=function(e,t){if(null==e)throw new Error(`${t??"Value"} not defined`)}}(l||(l={})),DG.DataFrame.fromColumns([DG.Column.fromStrings("col",["val1","val2","val3"])]);var p=i(3),m=i(312),f=i(124),b=i(971),g=i(478),A=i(582),_=i(858);class y{onKeyDown(e,t){}onKeyPress(e,t){}onMouseEnter(e,t){}onMouseLeave(e,t){}onMouseDown(e,t){}onMouseUp(e,t){}onMouseMove(e,t){}onClick(e,t){}onDoubleClick(e,t){}}class v extends y{constructor(e,t,i){super(),this.gridCol=e,this.tableCol=t,this.logger=i,this.subs=[],this.dirty=!0,this.destroyed=!1,this.cleanColVersion=-1,this.viewerId=++v.viewerCounter,this.errors=[],this._onRendered=new _.Subject,this.tableCol&&this.tableCol.dataFrame&&(this.cleanColVersion=this.tableCol.version,this.subs.push(this.tableCol.dataFrame.onDataChanged.subscribe(()=>{this.tableCol?.version!==this.cleanColVersion&&(this.cleanColVersion=this.tableCol?.version,this.dirty=!0)})),this.subs.push(this.tableCol.dataFrame.onColumnsRemoved.subscribe(e=>{try{this.destroyed||!this.tableCol||this.tableCol.dataFrame||this.destroy()}catch(e){this.logger.error(e)}}))),this.tableCol&&this.subs.push(n.events.onTableRemoved.subscribe(e=>{try{const t=e.args.dataFrame;this.tableCol?.dataFrame.id!==t.id||this.destroyed||this.destroy()}catch(e){this.logger.error(e)}})),this.gridCol&&this.subs.push(n.events.onViewRemoving.subscribe(e=>{try{const t=e.args.view;this.gridCol?.dart&&this.gridCol.grid&&this.gridCol?.grid?.dart&&this.gridCol?.grid?.view?.id===t.id&&!this.destroyed&&this.destroy()}catch(e){this.logger.error(e)}}))}toLog(){return`${this.constructor.name}<${this.viewerId}>`}destroy(){for(const e of this.subs)e.unsubscribe();this.destroyed=!0}invalidateGrid(){this.gridCol&&this.gridCol.dart&&this.gridCol.grid?.invalidate()}reset(){this.dirty=!1}get onRendered(){return this._onRendered}invalidate(e){this.invalidateGrid()}async awaitRendered(e=1e4,t=`${e} timeout`){const i=`${this.toLog()}.awaitRendered()`;if(this.logger.debug(`${i}, start, testEvent before`),await h(this._onRendered,()=>{},()=>{this.invalidate()},e,`${i}, ${t}`),this.errors.length>0){const e=this.errors[0];throw this.errors=[],e}this.logger.debug(`${i}, end`)}}v.viewerCounter=-1,i(991),i(303);var w,x=i(599);new RegExp("[rd]\\((\\w)\\)p?","g"),i(439),x.kC.RNA,x.kC.RNA,x.kC.RNA,function(e){e[e.SUGAR=0]="SUGAR",e[e.BASE=1]="BASE",e[e.PHOSPHATE=2]="PHOSPHATE",e[e.TERMINAL_5P=3]="TERMINAL_5P",e[e.TERMINAL_3P=4]="TERMINAL_3P"}(w||(w={})),Map;function C(e,t){try{const i=e.tableColumn;if(!i)return;const n=function(e){return e.temp.MonomerHoverLinks??[]}(i);for(let i=n.length-1;i>=0;--i){const o=n[i],r=e.grid.col(o.targetCol.name);if(r&&!o.handler(e,t,r))break}}catch(e){console.error(e)}}const k="bio.macromolecule.highlightMonomers",E=r.Color.argb(255,255,220,0),B=r.Color.argb(255,230,140,0);function S(e,t){return`rgba(${r.Color.r(e)},${r.Color.g(e)},${r.Color.b(e)},${t??.4})`}var M=i(199);function T(e,t,i,n){function o(n){let o,r;for(let s=0;s<i.atoms.length;++s)if(!n.includes(s)){const n=i.atoms[s].p.x,a=i.atoms[s].p.y,l=Math.sqrt((e-n)**2+(t-a)**2);(void 0===r||r>l)&&(o=s,r=l)}return[o,r]}const[r,s]=o([]),[a,l]=o([r]);let h=null;if(void 0!==r&&void 0!==s){const e=i.atoms[r];void 0!==a&&void 0!==l?s<.45*l&&(h=e):n&&s<.35*n&&(h=e)}return h}function I(e,t){const i=t.bio.continuousId-1;let n=t.elem;try{n=e.isDna()||e.isRna()?e.getSplittedWithSugarsAndPhosphates().getCanonical(i):e.getSplitted().getCanonical(i)}catch(e){}return{position:t.bio.continuousId-1,symbol:n,biotype:t.bio.type}}class L extends v{cacheEnabled=!0;sysMonomerLib=null;helmHelper=null;serviceByLib=new Map;auxList=new Map;constructor(e,t){super(e,t,fe.logger)}async init(){await Promise.all([(async()=>{const e=await(0,b.pj)();this.sysMonomerLib=e.getMonomerLib()})(),(async()=>{this.helmHelper=await(0,f.b2)()})()]),this.subs.push(this.sysMonomerLib.onChanged.subscribe(()=>{for(const e of this.serviceByLib.values())e.destroy();this.serviceByLib.clear(),this.auxList.clear(),this.dirty=!0,this.invalidateGrid()})),this.subs.push(n.events.onCustomEvent("bio-macromolecule-monomer-highlight").subscribe(e=>this.handleHighlightEvent(e))),this.dirty=!0,this.invalidateGrid()}destroy(){for(const e of this.serviceByLib.values())e.destroy();this.serviceByLib.clear(),this.auxList.clear(),super.destroy()}handleHighlightEvent(e){if(!e||!this.tableCol||!this.tableCol.dataFrame)return;if(e.columnName!==this.tableCol.name)return;const t=this.tableCol.dataFrame;if(e.tableId&&t.id!==e.tableId)return;if(e.tableName&&t.name!==e.tableName)return;const i=this.tableCol.temp[k]??=new Map;null==e.monomers||0===e.monomers.length?i.delete(e.rowIdx):i.set(e.rowIdx,{monomers:e.monomers.slice(),fillColor:e.fillColor,strokeColor:e.strokeColor}),this.invalidateGrid()}getHighlightForRow(e){if(null==e)return null;const t=this.tableCol.temp[k];return t?.get(e)??null}getMonomerLib(){return this.tableCol.temp[".mm.cellRenderer.overriddenLibrary"]??this.sysMonomerLib}getService(e){const t=e.source;let i=this.serviceByLib.get(t);return void 0===i&&(i=new M.Cs({monomerLib:(0,M.a)(e)}),this.serviceByLib.set(t,i)),i}reset(){super.reset(),this.auxList=new Map,this.invalidateGrid()}render(e,t,i,n,o,s,a){const l=s.cell?.value;if(!l||null===this.sysMonomerLib)return;if(n<5||o<5)return;const h=window.devicePixelRatio,d=this.getService(this.getMonomerLib());e.save();try{e.resetTransform();const a=!(!this.gridCol?.dart||this.gridCol.grid?.canvas!==e.canvas),c={x:(a?s.bounds.x:t)*h,y:(a?s.bounds.y:i)*h,width:n*h,height:o*h},u=d.renderToCanvas(e,l,c,{maxScale:1/0,showIds:!1,showAnnotations:!0}),p={molView:(0,M.sT)(u.mol),bBox:new r.Rect(u.bbox.x,u.bbox.y,u.bbox.width,u.bbox.height),dBox:new r.Rect(u.drawBox.x,u.drawBox.y,u.drawBox.width,u.drawBox.height),cellHDev:o*h};this.auxList.set(l,p),this.drawHighlightOverlay(e,p,s.tableRowIndex)}catch(e){const[t,i]=u(e);this.logger.error(t,void 0,i)}finally{e.restore()}this._onRendered.next()}drawHighlightOverlay(e,t,i){const n=this.getHighlightForRow(i);if(!n||!n.monomers||0===n.monomers.length)return;const o=t.molView?.atoms;if(!o||0===o.length)return;if(t.bBox.width<=0||t.bBox.height<=0)return;const r=t.dBox.width/t.bBox.width,s=t.dBox.height/t.bBox.height,a=(r+s)/2,l=this.estimateMonomerRadiusModel(t),h=Math.max(6,l*a*.7),d=Math.max(1.5,.35*h),c=S(n.fillColor??E,.2),u=S(n.strokeColor??B);e.save();try{e.lineWidth=d,e.strokeStyle=u,e.fillStyle=c;for(const i of n.monomers){const n=o[i];if(!n||!n.p)continue;const a=t.dBox.x+(n.p.x-t.bBox.x)*r,l=t.dBox.y+(n.p.y-t.bBox.y)*s;e.beginPath(),e.arc(a,l,h,0,2*Math.PI),e.fill(),e.stroke()}}finally{e.restore()}}estimateMonomerRadiusModel(e){const t=e.molView?.bonds,i=[];if(t&&t.length>0)for(const e of t){const t=e?.a1?.p,n=e?.a2?.p;if(!t||!n)continue;const o=Math.hypot(t.x-n.x,t.y-n.y);o>0&&i.push(o)}if(i.length>0)return i.sort((e,t)=>e-t),.55*i[Math.floor(i.length/2)];const n=Math.max(1,e.molView?.atoms?.length??1);return.45*Math.sqrt(e.bBox.width*e.bBox.height/n)}onMouseMove(e,t){if(!e.cell?.value||t.buttons)return;const i=this.auxList.get(e.cell.value);if(!i)return;const n=`${this.toLog()}.onMouseMove()`,r=window.devicePixelRatio,s=e.bounds,a=(t.offsetX-s.x)*r,l=(t.offsetY-s.y)*r,h=i.dBox.x-s.x*r,d=i.dBox.y-s.y*r,c=i.bBox.x+(a-h)*i.bBox.width/i.dBox.width,u=i.bBox.y+(l-d)*i.bBox.height/i.dBox.height,p=i.cellHDev*i.bBox.height/i.dBox.height;if(!i.molView)return void this.logger.warning(`${n}, editorMol of the cell not found.`);const m=T(c,u,i.molView,p);let f=null;if(m&&this.helmHelper&&null!=e.tableRowIndex){f=I(this.helmHelper.seqHelper.getSeqHandler(this.tableCol).getValue(e.tableRowIndex),m);const i=this.tableCol.temp[".mm.cellRenderer.overriddenLibrary"]??fe.monomerLib,n=i?i.getTooltip(f.biotype,f.symbol):o.divText("Monomer library is not available");o.tooltip.show(n,t.x+16,t.y+16)}else o.tooltip.hide();C(e,f),t.preventDefault(),t.stopPropagation()}onMouseLeave(e,t){C(e,null)}static getOrCreate(e){const[t,i,n]=function(e){let t=null,i=null;try{i=e.dart?e.gridColumn:null,t=i?i.temp:null}catch{[i,t]=[null,null]}const n=e.cell.column;if(t=t??(n?n.temp:null),!t)throw new Error("Grid cell renderer back store (GridColumn or Column) not found.");return[i,n,t]}(e);let o=n.rendererBack;return o||(o=n.rendererBack=new L(t,i),o.init().then(()=>{})),o}}class $ extends r.GridCellRenderer{get name(){return"helm"}get cellType(){return"helm"}get defaultWidth(){return 400}get defaultHeight(){return 100}onMouseMove(e,t){try{L.getOrCreate(e).onMouseMove(e,t)}catch(e){const[t,i]=u(e);fe.logger.error(t,void 0,i)}}onMouseLeave(e,t){try{L.getOrCreate(e).onMouseLeave(e,t)}catch(e){const[t,i]=u(e);fe.logger.error(t,void 0,i)}finally{t.preventDefault(),t.stopPropagation()}}render(e,t,i,n,o,r,s){const a=36/window.devicePixelRatio;n<a||o<a||L.getOrCreate(r).render(e,t,i,n,o,r,s)}}function P(e){var t;return"string"==typeof e||e instanceof String?e:("object"==typeof e||e instanceof Object)&&"$thrownJsError"in e?P(e.$thrownJsError):e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e.toString()}class R{constructor(e,t,i=""){this.target=e,this.debugEnabled=t,this.prefix=i}error(e,t,i){return this.target.error(this.prefix+e,t,i)}warning(e,t){return this.target.warning(this.prefix+e,t)}info(e,t){return this.target.info(this.prefix+e,t)}debug(e,t){if(this.debugEnabled)return this.target.debug(this.prefix+e,t)}}var H=i(413);class N extends r.Package{_helmHelper;get helmHelper(){if(!this._helmHelper)throw new Error("Package Helm .helmHelper is not initialized");return this._helmHelper}get seqHelper(){return this.helmHelper.seqHelper}_libHelper;constructor(e={debug:!1}){super(),super._logger=new R(super.logger,e.debug)}get monomerLib(){if(!this._libHelper)throw new Error("Helm: _package.libHelper is not initialized yet");return this._libHelper.getMonomerLib()}_monomerLibSub;_initialized=!1;get defaultMonomersPerRow(){let e;try{e=this.settings?.MonomersPerRow}catch{e=void 0}return(0,H.U)(e)}applyDefaultMonomersPerRow(){(0,M.Y$)(this.defaultMonomersPerRow)}completeInit(e,t){this._helmHelper=e,this._libHelper=t;const i=this.monomerLib;this._monomerLibSub=i.onChanged.subscribe(this.monomerLibOnChangedHandler.bind(this)),this._initialized=!0}monomerLibOnChangedHandler(){const e="Helm: _package.monomerLibOnChangedHandler()";try{const t=this.monomerLib.getSummaryObj(),i=0==Object.keys(t).length,o=i?"empty":Object.entries(t).map(([e,t])=>`${e}: ${t}`).join(", ");fe.logger.debug(`${e}, start, lib: { ${o} }`);const r=`Monomer lib updated:<br /> ${i?"empty":Object.entries(t).map(([e,t])=>`${e} ${t}`).join("<br />")}`;n.shell.info(r)}catch(t){const i=P(t);console.error(`${e} error:\n`+i)}}}class D extends f.KB{helmHelper;monomerLib;options;logger;get inputType(){return"Macromolecule"}get dataType(){return r.TYPE.STRING}getInput(){return this.viewerHost}_seqValue;getValue(){return this._seqValue}setValue(e){this._seqValue=e,this.viewer.editor.setHelm(this._seqValue.helm)}getStringValue(){return this._seqValue?.helm??""}setStringValue(e){if(!this._seqValue){let t;r.DataFrame.fromColumns([t=r.Column.fromList(r.COLUMN_TYPE.STRING,"seq",[e])]),t.semType=r.SEMTYPE.MACROMOLECULE,t.meta.units=p.Hi.HELM;const i=this.helmHelper.seqHelper.getSeqHandler(t);this._seqValue=i.getValue(0)}this.viewer.editor.setHelm(this._seqValue.value=e)}get molValue(){return this.viewer.editor.m}set molValue(e){this.viewer.editor.setMol(e),this._seqValue.value=this.viewer.editor.getHelm()}get onMouseMove(){return(0,_.fromEvent)(this.viewer.host,"mousemove")}get onClick(){return(0,_.fromEvent)(this.viewer.host,"click")}viewerHost;viewer;editHintDiv;helmString="";helmSelection;subs;constructor(e,t,i,n,r=fe.logger){super(),this.helmHelper=e,this.monomerLib=t,this.options=n,this.logger=r,i&&(this.captionLabel.innerText=i);const s=n?.editorOptions?.height??250,a=n?.editorOptions?.width??250;this.viewerHost=o.div([],{classes:"ui-input-editor",style:{width:`${a}px`,height:`${s}px`,minWidth:`${a}px`,minHeight:`${s}px`,overflow:"hidden"}}),this.viewer=this.helmHelper.createHelmWebEditor(this.viewerHost,{...n?.editorOptions,width:a,height:s}),this.editHintDiv=o.divH([o.link("Click to edit",()=>{this.viewer.host.click()},void 0,{})],{style:{display:"none",position:"absolute",top:"0",right:"0"}}),this.subs=[],this.subs.push(this.monomerLib.onChanged.subscribe(()=>this.viewer.editor.redraw())),(0,_.fromEvent)(this.viewer.host,"mousemove").subscribe(this.viewerOnMouseMove.bind(this)),(0,_.fromEvent)(this.viewer.host,"mouseenter").subscribe(this.viewerOnMouseEnter.bind(this)),(0,_.fromEvent)(this.viewer.host,"mouseleave").subscribe(this.viewerOnMouseLeave.bind(this)),(0,_.fromEvent)(this.viewer.host,"click").subscribe(this.viewerOnClick.bind(this)),this.subs.push(o.onSizeChanged(this.input).subscribe(()=>{const e=this.input.clientWidth,t=this.input.clientHeight;e>0&&t>0&&this.viewer.editor.setSize(e,t)})),this.root.classList.add("ui-input-helm"),this.root.append(this.viewerHost,this.editHintDiv)}detach(){for(const e of this.subs)e.unsubscribe()}toLog(){return"Helm: HelmInput<#>"}static create(e,t,i,n){const o=new D(e,t,i,n);return null!=n?.value&&(o.value=n.value),o}redraw(){this.viewer.editor.redraw()}showTooltip(e,t){const i=1.2*this.viewer.editor.getDrawOptions().fontsize,n=this.input.getBoundingClientRect();o.tooltip.show(e,n.left+t.p.x+i,n.top+t.p.y+i)}viewerOnClick(e){o.tooltip.hide(),0!=this.options?.editable&&this.showEditorDialog()}viewerOnMouseMove(e){this.toLog();const t=T(e.offsetX,e.offsetY,this.viewer.editor.m,this.viewer.editor.div.clientHeight);if(t){const i=I(this.value,t),n=fe.monomerLib,r=n?n.getTooltip(i.biotype,i.symbol):o.divText("Monomer library is not available");this.showTooltip(r,t),e.preventDefault(),e.stopPropagation()}else o.tooltip.hide()}viewerOnMouseEnter(e){0!=this.options?.editable&&this.showEditHint()}viewerOnMouseLeave(e){this.editHintDiv.contains(e.relatedTarget)||0!=this.options?.editable&&this.hideEditHint()}showEditHint(){this.editHintDiv.style.removeProperty("display")}hideEditHint(){this.editHintDiv.style.display="none"}showEditorDialog(){const e=o.div();e.style.height="100%";const t=this.helmHelper.createWebEditorApp(e,this.viewer.editor.getHelm()),i=()=>{a()(e).empty()};o.dialog({showHeader:!1,showFooter:!0}).add(e).onOK(()=>{try{const e=t.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");this.setStringValue(e),this.helmString=e;const i=t.canvas.helm.jsd.m.atoms;this.helmSelection=[];for(let e=0;e<i.length;e++)i[e].selected&&this.helmSelection.push(e),this.viewer.editor.m.atoms[e].highlighted=i[e].selected;this.viewer.editor.redraw(),this.fireChanged()}catch(e){!function(e){const[t,i]=u(e);fe.logger.error(t,void 0,i),n.shell.error(t)}(e)}finally{i()}}).onCancel(()=>{i()}).show({modal:!0,fullScreen:!0})}}class F{seqHelper;logger;rdKitModule;static instanceCount=0;constructor(e,t,i){if(this.seqHelper=e,this.logger=t,this.rdKitModule=i,++F.instanceCount>1)throw new Error("HelmHelper must be a single.")}_editorAdapter=null;get editorAdapter(){if(null===this._editorAdapter){const e=fe._libHelper.getMonomerLib(),t=new Map;t.set("FASTA",async e=>this._toFastaProvider(e)),t.set("BILN",async e=>this._toBilnProvider(e)),t.set("Molecular Structure",async e=>this._atomicLevelProvider(e)),t.set("Composition Analysis",async e=>this._compositionAnalysisProvider(e));const i=new M.Cs({monomerLib:(0,M.a)(e),rdkitModule:this.rdKitModule,extraPanes:t});this._editorAdapter=new M.eo({service:i,seqHelper:this.seqHelper})}return this._editorAdapter}createHelmInput(e,t){try{const i=fe._libHelper.getMonomerLib();return D.create(this,i,e,t)}catch(e){const[t,i]=u(e);throw this.logger.error(`Helm: HelmHelper.createHelmInput(), Error: ${t}`,void 0,i),e}}createHelmWebEditor(e,t){return this.editorAdapter.createHelmWebEditor(e,{...void 0!==t?.width?{width:t.width}:{},...void 0!==t?.height?{height:t.height}:{}})}createWebEditorApp(e,t){return this.editorAdapter.createWebEditorApp(e,t)}get originalMonomersFuncs(){return this.editorAdapter.originalMonomersFuncs}revertOriginalMonomersFuncs(){return this.editorAdapter.revertOriginalMonomersFuncs()}overrideMonomersFuncs(e){return this.editorAdapter.overrideMonomersFuncs(e)}buildMonomersFuncsFromLib(e){return this.editorAdapter.buildMonomersFuncsFromLib(e)}getHoveredAtom(e,t,i,n){return T(e,t,i,n)}getMolfiles(e){return this.editorAdapter.getMolfiles(e)}parse(e,t){return this.editorAdapter.parse(e,t)}removeGaps(e){return this.editorAdapter.removeGaps(e)}_singeHelmDf=null;_getSingleHelmDf(e){if(null===this._singeHelmDf){const t=r.Column.fromStrings("helm",[e]);t.setTag("quality",r.SEMTYPE.MACROMOLECULE),t.setTag("units","helm"),t.setTag(".alphabetIsMultichar","true"),t.setTag("alphabet","UN");const i=Math.floor(.6*window.innerWidth);t.setTag(".toAtomicWidgetWidth",i.toString()),this._singeHelmDf=r.DataFrame.fromColumns([t])}return this._singeHelmDf.col("helm").set(0,e),this._singeHelmDf}_singleHelmSh=null;_getSingleHelmDfSh(e){if(!this._singleHelmSh){const t=this._getSingleHelmDf(e);this._singleHelmSh=this.seqHelper.getSeqHandler(t.col("helm"))}return this._singleHelmSh}async _atomicLevelProvider(e){const t=this._getSingleHelmDf(e),i=r.SemanticValue.fromTableCell(t.cell(0,"helm"));return(await n.functions.call("Bio:toAtomicLevelPanel",{sequence:i})).root}async _compositionAnalysisProvider(e){const t=this._getSingleHelmDf(e),i=r.SemanticValue.fromTableCell(t.cell(0,"helm"));return(await n.functions.call("Bio:compositionAnalysisWidget",{sequence:i})).root}_toBilnProvider(e){const t=this.editorAdapter.service.parse(e);if(t.mol.chains.length<1||t.mol.chains.some(e=>e.polymerType!==M.kC.PEPTIDE))return o.divText("Unsupported sequence for BILN");const i=this._getSingleHelmDfSh(e),n=o.input.textArea("",{});return n.value=i.getConverter(p.Hi.BILN)(e),n.input.setAttribute("disabled","true"),n.input.style.width="100%",n.input}_toFastaProvider(e){const t=this.editorAdapter.service.parse(e);if(1!==t.mol.chains.length||t.mol.atoms.length!==t.mol.bonds.filter(e=>"hbond"!==e.kind).length+1)return o.divText("Unsupported sequence for FASTA");const i=this._getSingleHelmDfSh(e),n=o.input.textArea("",{});return n.value=i.getConverter(p.Hi.FASTA)(e),n.input.setAttribute("disabled","true"),n.input.style.width="100%",n.input}}var O=i(717),z=i(72),G=i.n(z),q=i(825),j=i.n(q),Y=i(659),V=i.n(Y),W=i(56),U=i.n(W),K=i(540),X=i.n(K),Q=i(113),Z=i.n(Q),J=i(130),ee={};async function te(){await Ae.initHelm()}function ie(){return Ae.helmCellRenderer()}function ne(e){Ae.editMoleculeCell(e)}async function oe(e){return await Ae.helmPanel(e)}function re(e){Ae.openEditor(e)}async function se(e){return await Ae.propertiesWidget(e)}function ae(e){return Ae.getMolfiles(e)}function le(e,t){return Ae.helmInput(e,t)}function he(){return Ae.getHelmHelper()}async function de(){await Ae.measureCellRenderer()}async function ce(){await Ae.highlightMonomers()}ee.styleTagTransform=Z(),ee.setAttributes=U(),ee.insert=V().bind(null,"head"),ee.domAPI=j(),ee.insertStyleElement=X(),G()(J.A,ee),J.A&&J.A.locals&&J.A.locals;var ue=function(e,t,i,n){var o,r=arguments.length,s=r<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,i):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,n);else for(var a=e.length-1;a>=0;a--)(o=e[a])&&(s=(r<3?o(s):r>3?o(t,i,s):o(t,i))||s);return r>3&&s&&Object.defineProperty(t,i,s),s},pe=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},me=function(e,t){return function(i,n){t(i,n,e)}};const fe=new N;n.decorators||(n.decorators={}),["func","init","param","panel","editor","demo","app","appTreeBrowser","fileHandler","fileExporter","model","viewer","filter","cellRenderer","autostart","dashboard","folderViewer","semTypeDetector","packageSettingsEditor","functionAnalysis","converter","fileViewer","model","treeBrowser","polyfill"].forEach(e=>{n.decorators[e]||(n.decorators[e]=function(e){return function(e,t,i){}})});let be=null;function ge(e,t,i){!function(e,t,i){const n=o.div();n.style.height="100%";const r=e.cell.column,s=fe.seqHelper.getSeqHandler(r),l=fe.helmHelper.createWebEditorApp(n,e&&void 0===i?e.cell.value:t),h=o.dialog({showHeader:!1,showFooter:!0});h.add(n).onOK(()=>{const t=l.canvas.getHelm(!0).replace(/<\/span>/g,"").replace(/<span style='background:#bbf;'>/g,"");if(e)if(void 0===i)e.setValue(t);else{const n=s.convertHelmToFastaSeparator(t,i,s.separator);e.setValue(n)}}).show({modal:!0,fullScreen:!0});const d=a()(h.root).find("div").get()[0];d.className=d.className.replace("dlg- ui-form","dlg-ui-form")}(e,t,i)}class Ae{static async initHelm(){return null===be&&(be=async function(){const e="Helm: _package.initHelm()";fe.logger.debug(`${e}, start`);try{const e=await(0,O.j)(),t=await(0,m.Q)(),i=await(0,b.pj)(),n=new F(t,fe.logger,e);fe.completeInit(n,i),fe.applyDefaultMonomersPerRow()}catch(t){const[i,o]=u(t);n.shell.error(`Package 'Helm' init error:\n${i}`);const r=new Error(`${e} error:\n ${i}\n${o}`);throw r.stack=o,r}finally{fe.logger.debug(`${e}, finally`)}fe.logger.debug(`${e}, end`)}()),be}static helmCellRenderer(){return fe.logger.debug("Helm: _package.getHelmCellRenderer(), start"),new $}static editMoleculeCell(e){ge(e,void 0,void 0)}static async helmPanel(e){return e.meta.units!==p.Hi.HELM?new r.Widget(o.divText("These settings apply only to HELM columns")):(0,A.P)()}static openEditor(e){const t=n.shell.tv.grid.dataFrame,i=t.columns.bySemType("Macromolecule"),o=fe.seqHelper.getSeqHandler(i),s=i.meta.units;if(-1===t.currentRowIdx)return;const a=r.GridCell.fromColumnRow(n.shell.tv.grid,i.name,t.currentRowIdx);s===p.Hi.HELM?ge(a,void 0,void 0):ge(a,o.getConverter(p.Hi.HELM)(e.value),i.meta.units)}static async propertiesWidget(e){return(0,g.AY)(e)}static getMolfiles(e){const t=e.toList(),i=fe.helmHelper.getMolfiles(t);return r.Column.fromStrings("mols",i)}static helmInput(e,t){return fe.helmHelper.createHelmInput(e,t)}static getHelmHelper(){return fe.helmHelper}static async measureCellRenderer(){const e=n.shell.tv.grid,t=e.columns.byName("sequence").temp.rendererBack;let i=0,o=0;for(let n=0;n<20;++n){const n=window.performance.now();let r;t.cacheEnabled?await h(e.onAfterDrawContent,()=>{r=window.performance.now(),fe.logger.info(`measureCellRenderer() cache enabled, ET: ${r-n} ms`)},()=>{e.invalidate()},5e3):await h(t.onRendered,()=>{r=window.performance.now(),fe.logger.info(`measureCellRenderer() cache disabled , ET: ${r-n} ms`)},()=>{t.invalidate()},5e3),i+=r-n,o++}fe.logger.info(`measureCellRenderer(), avg ET: ${i/o} ms`)}static async highlightMonomers(){const e=r.TaskBarProgressIndicator.create("Test app highlight monomers");try{const e=await fe.files.readCsv("tests/peptide.csv");e.name="peptide.csv",await be;const t=e.columns.byName("helm");await n.data.detectSemanticTypes(e),await n.functions.call("Bio:toAtomicLevel",{table:e,seqCol:t,nonlinear:!0,highlight:!0}),n.shell.addTableView(e)}finally{e.close()}}}ue([n.decorators.init({tags:["init"]}),pe("design:type",Function),pe("design:paramtypes",[]),pe("design:returntype",Promise)],Ae,"initHelm",null),ue([n.decorators.func({meta:{columnTags:"quality=Macromolecule, units=helm",cellType:"helm",role:"cellRenderer"},tags:["cellRenderer"],outputs:[{name:"result",type:"grid_cell_renderer"}]}),pe("design:type",Function),pe("design:paramtypes",[]),pe("design:returntype",r.GridCellRenderer)],Ae,"helmCellRenderer",null),ue([n.decorators.func({meta:{columnTags:"quality=Macromolecule, units=helm",role:"cellEditor"},tags:["cellEditor"],description:"Macromolecule"}),me(0,n.decorators.param({type:"grid_cell"})),pe("design:type",Function),pe("design:paramtypes",[r.GridCell]),pe("design:returntype",void 0)],Ae,"editMoleculeCell",null),ue([n.decorators.panel({name:"HELM Renderer",meta:{role:"widgets"},tags:["widgets","panel"]}),me(0,n.decorators.param({options:{semType:"Macromolecule",units:"helm"}})),pe("design:type",Function),pe("design:paramtypes",[r.Column]),pe("design:returntype",Promise)],Ae,"helmPanel",null),ue([n.decorators.func({meta:{action:"Edit Helm..."},name:"Edit Helm...",description:"Adds editor"}),me(0,n.decorators.param({options:{semType:"Macromolecule"}})),pe("design:type",Function),pe("design:paramtypes",[r.SemanticValue]),pe("design:returntype",void 0)],Ae,"openEditor",null),ue([n.decorators.panel({name:"Properties",meta:{role:"widgets",domain:"bio"},tags:["panel","widgets","bio"]}),me(0,n.decorators.param({options:{semType:"Macromolecule"}})),pe("design:type",Function),pe("design:paramtypes",[r.SemanticValue]),pe("design:returntype",Promise)],Ae,"propertiesWidget",null),ue([n.decorators.func({name:"Get Molfiles from HELM",description:"Convert a column of HELM macromolecules into a column of molfiles"}),me(0,n.decorators.param({type:"column",options:{semType:"Macromolecule"}})),pe("design:type",Function),pe("design:paramtypes",[r.Column]),pe("design:returntype",r.Column)],Ae,"getMolfiles",null),ue([n.decorators.func({meta:{propertyType:"string",semType:"Macromolecule",role:"valueEditor"},tags:["valueEditor"],outputs:[{type:"object",name:"result"}]}),me(0,n.decorators.param({options:{optional:!0}})),me(1,n.decorators.param({type:"object",options:{optional:!0}})),pe("design:type",Function),pe("design:paramtypes",[String,Object]),pe("design:returntype",f.KB)],Ae,"helmInput",null),ue([n.decorators.func({outputs:[{type:"object",name:"result"}]}),pe("design:type",Function),pe("design:paramtypes",[]),pe("design:returntype",Object)],Ae,"getHelmHelper",null),ue([n.decorators.func(),pe("design:type",Function),pe("design:paramtypes",[]),pe("design:returntype",Promise)],Ae,"measureCellRenderer",null),ue([n.decorators.func({name:"Highlight Monomers"}),pe("design:type",Function),pe("design:paramtypes",[]),pe("design:returntype",Promise)],Ae,"highlightMonomers",null)},266(e,t,i){"use strict";i.d(t,{e6:()=>s});const n=/\{(\*\.)+/g,o=/\.(\*\.)+/g,r=/(\.\*)+\}/g;function s(e){return e.replaceAll(n,"{").replaceAll(o,".").replaceAll(r,"}").replace("{*}","{}")}},413(e,t,i){"use strict";i.d(t,{U:()=>o});var n=i(921);function o(e){const t="number"==typeof e?e:Number.parseInt(String(e??""),10);return Number.isFinite(t)&&t>=1?Math.round(t):n.KP}},478(e,t,i){"use strict";i.d(t,{AY:()=>c});var n=i(389),o=i(82),r=i(757),s=i.n(r),a=i(3),l=i(124),h=i(266);class d extends Error{constructor(e,t){super(e,t)}}async function c(e){const t=(await(0,l.b2)()).seqHelper.getSeqHandler(e.cell.column);try{const i=await async function(e,t){const i=n.div([],{style:{width:"0",height:"0"}});document.documentElement.appendChild(i);try{if(e.length>1e3)throw new d("Too long sequence to calculate molecular properties.");const n=t.isHelm()?e:t.getConverter(a.Hi.HELM)(e),o=(0,h.e6)(n),r=(await(0,l.b2)()).createHelmWebEditor(i).editor;r.setHelm(o);const s=r.getFormula(!0),c=Math.round(100*r.getMolWeight())/100,u=Math.round(100*r.getExtinctionCoefficient())/100;return{formula:s.replace(/<sub>/g,"").replace(/<\/sub>/g,""),"molecular weight":c,"extinction coefficient":u}}finally{s()(i).empty(),i.remove()}}(e.value,t);return new o.Widget(n.tableFromMap(i,!0))}catch(e){if(e instanceof d)return new o.Widget(n.divText(e.message));throw e}}},582(e,t,i){"use strict";i.d(t,{P:()=>d});var n=i(328),o=i(389),r=i(82),s=i(858),a=i(199),l=i(333);function h(){for(const e of n.shell.tableViews)try{e.grid?.invalidate()}catch(e){}}function d(){const e=o.input.int("Monomers per row",{value:(0,a.O9)().monomersPerRow,min:1,max:100,tooltipText:"Number of monomers drawn per row before the structure wraps. Counts nucleotides for RNA/DNA. Applies to this session only. The default comes from the Helm package property",onValueChanged:e=>{null!==e&&Number.isFinite(e)&&((0,a.Y$)(e),h())}}),t=l._package.defaultMonomersPerRow,i=o.link("Reset to package default",()=>{(0,a.Y$)(t),h()},`Back to ${t} — the MonomersPerRow package property`,{style:{marginTop:"4px"}}),n=new r.Widget(o.divV([e.root,i])),d=(0,a.vi)(t=>{e.value!==t.monomersPerRow&&(e.value=t.monomersPerRow)});return n.sub(new s.Subscription(d)),n}},757(e){"use strict";e.exports=$},82(e){"use strict";e.exports=DG},328(e){"use strict";e.exports=grok},858(e){"use strict";e.exports=rxjs},389(e){"use strict";e.exports=ui},991(e){"use strict";e.exports=wu},199(e,t,i){"use strict";i.d(t,{Cs:()=>Ri,O9:()=>wt,Y$:()=>Ct,a:()=>To,eo:()=>Lo,kC:()=>B,sT:()=>go,vi:()=>kt});var n=i(303),o=class extends Error{constructor(e,t,i){super(t),this.name="HwError",this.code=e,void 0!==i&&(this.context=Object.freeze({...i})),Object.setPrototypeOf(this,new.target.prototype),"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,new.target)}},r=class extends o{constructor(e,t,i){super(e,t,i?.context),this.name="HelmParseError",void 0!==i?.span&&(this.span={...i.span}),Object.setPrototypeOf(this,new.target.prototype)}},s=class extends o{constructor(e,t){let i=Object.freeze([...e]),n=t??function(e){if(0===e.length)return"HELM validation failed";let t=e[0],i=e.length>1?` (+${e.length-1} more)`:"";return`HELM validation failed: ${t.code} — ${t.message}${i}`}(i);super("helm-validation-failed",n),this.name="HelmValidationError",this.diagnostics=i,Object.setPrototypeOf(this,new.target.prototype)}},a=class extends o{constructor(e,t,i){super(e,t??`HELM operation not supported: ${e}`,i),this.name="HelmNotSupportedError",Object.setPrototypeOf(this,new.target.prototype)}},l=class{constructor(e){if(!Number.isInteger(e.max)||e.max<=0)throw new RangeError(`LruCache: max must be a positive integer (got ${e.max})`);let t=e.onEvict;this._cache=void 0===t?new n.q({max:e.max}):new n.q({max:e.max,dispose:(e,i,n)=>{t(i,e)}})}get(e){return this._cache.get(e)}set(e,t){this._cache.set(e,t)}has(e){return this._cache.has(e)}delete(e){return this._cache.delete(e)}clear(){this._cache.clear()}get size(){return this._cache.size}keys(){return this._cache.keys()}entries(){return this._cache.entries()}},h=class{debug(e,t){}info(e,t){}warn(e,t){}error(e,t){}};function d(e){return e>=65&&e<=90||e>=97&&e<=122}function c(e){return e>=48&&e<=57}function u(e){return 32===e||9===e||10===e||13===e}var p=class{constructor(e){this.src=e,this.len=e.length,this.pos=0,this.tokens=[]}tokenize(){for(;this.pos<this.len;){let e=this.pos,t=this.src.charCodeAt(this.pos);if(u(t))throw new r("unexpected-whitespace",`Unexpected whitespace at offset ${e}`,{span:{start:e,end:e+1}});if(91===t){this.scanBracket(e);continue}if(34===t){this.scanQuote(e);continue}if(d(t)){this.scanIdentifier(e);continue}if(c(t)){this.scanNumber(e);continue}let i=m.get(t);if(void 0===i)throw new r("unexpected-char",`Unexpected character ${JSON.stringify(this.src.charAt(e))} at offset ${e}`,{span:{start:e,end:e+1}});this.pos+=1,this.push(i,this.src.charAt(e),e,this.pos)}return this.push("eof","",this.len,this.len),{tokens:this.tokens,source:this.src}}scanBracket(e){let t=1,i=!1,n=!1,o=e+1;for(;o<this.len;){let s=this.src.charCodeAt(o);if(i){if(92===s&&o+1<this.len){o+=2;continue}if(34===s){i=!1,o+=1;continue}if(10===s||13===s)throw new r("unexpected-newline",`Newline inside bracket at offset ${o}`,{span:{start:o,end:o+1}});o+=1}else if(n){if(36===s&&o+1<this.len){let e=this.src.charCodeAt(o+1);if(124===e){n=!1,o+=2;continue}if(93===e){n=!1,o+=1;continue}}if(10===s||13===s)throw new r("unexpected-newline",`Newline inside bracket at offset ${o}`,{span:{start:o,end:o+1}});o+=1}else{if(10===s||13===s)throw new r("unexpected-newline",`Newline inside bracket at offset ${o}`,{span:{start:o,end:o+1}});if(34!==s)if(124===s&&o+1<this.len&&36===this.src.charCodeAt(o+1))n=!0,o+=2;else if(91!==s)if(93!==s)o+=1;else{if(t-=1,0===t){let t=o+1,i=this.src.slice(e+1,o);return this.pos=t,void this.push("inline-smiles",i,e,t)}o+=1}else t+=1,o+=1;else i=!0,o+=1}}throw new r("unterminated-bracket",`Unterminated '[' starting at offset ${e}`,{span:{start:e,end:this.len}})}scanQuote(e){let t=[],i=e+1;for(;i<this.len;){let n=this.src.charCodeAt(i);if(34===n){let n=i+1;return this.pos=n,void this.push("quote-string",t.join(""),e,n)}if(92===n&&i+1<this.len){let e=this.src.charCodeAt(i+1);34===e?t.push('"'):92===e?t.push("\\"):110===e?t.push("\n"):114===e?t.push("\r"):116===e?t.push("\t"):(t.push("\\"),t.push(this.src.charAt(i+1))),i+=2;continue}if(10===n||13===n)throw new r("unexpected-newline",`Newline inside quote at offset ${i}`,{span:{start:i,end:i+1}});t.push(this.src.charAt(i)),i+=1}throw new r("unterminated-quote",`Unterminated '"' starting at offset ${e}`,{span:{start:e,end:this.len}})}scanIdentifier(e){let t=e+1;for(;t<this.len;){let e=this.src.charCodeAt(t);if(d(e)||c(e)||95===e)t+=1;else{if(!(45===e&&t+1<this.len&&d(this.src.charCodeAt(t+1))))break;t+=2}}let i=this.src.slice(e,t);this.pos=t,this.push("identifier",i,e,t)}scanNumber(e){let t=e+1;for(;t<this.len&&c(this.src.charCodeAt(t));)t+=1;if(t+1<this.len&&46===this.src.charCodeAt(t)&&c(this.src.charCodeAt(t+1))){for(t+=2;t<this.len&&c(this.src.charCodeAt(t));)t+=1;let i=this.src.slice(e,t);return this.pos=t,void this.push("decimal",i,e,t)}let i=this.src.slice(e,t);this.pos=t,this.push("integer",i,e,t)}push(e,t,i,n){this.tokens.push({kind:e,value:t,span:{start:i,end:n}})}},m=new Map([[123,"lbrace"],[125,"rbrace"],[40,"lparen"],[41,"rparen"],[93,"rbracket"],[124,"pipe"],[46,"dot"],[44,"comma"],[43,"plus"],[58,"colon"],[45,"dash"],[36,"dollar"],[62,"gt"],[63,"question"],[42,"asterisk"],[95,"underscore"],[39,"apos"]]);var f={perPolymer:new Map,version:""};function b(){return{atoms:[],bonds:[],chains:[],groups:[],annotations:f}}function g(e,t){for(let i of e.atoms)if(i.id===t)return i}function A(e,t){for(let i of e.bonds)if(i.id===t)return i}function _(e,t){if(void 0===t)return e.bio.positionInChain;let i=0;for(let n=0;n<t.backboneAtoms.length;n++){let o=t.backboneAtoms[n];if(void 0!==o&&(i+=1,o.id===e.id||void 0!==o.branchAtom&&(i+=1,o.branchAtom.id===e.id)))return i}return 0}var y="HELM_AA",v="HELM_SUGAR",w="HELM_BASE",x="HELM_LINKER",C="HELM_CHEM",k="HELM_BLOB",E="HELM_NUCLEOTIDE",B={PEPTIDE:"PEPTIDE",RNA:"RNA",CHEM:"CHEM",BLOB:"BLOB",G:"G"},S=class{constructor(){this._counter=0}next(){return this._counter+=1,this._counter}reset(){this._counter=0}get current(){return this._counter}};function M(e){let t=new Map,i=0;for(let n of e.chains)for(let e of n.backboneAtoms)i+=1,t.set(e.id,i),void 0!==e.branchAtom&&(i+=1,t.set(e.branchAtom.id,i));return t}function T(e){let t=e.trim();if(/^\[[a-zA-Z_][a-zA-Z0-9_]*\]$/.test(t))return!1;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e);if(40===i||91===i||61===i||47===i||92===i||42===i)return!0}return!1}var I=class{constructor(){this._listeners=new Set,this._completed=!1}subscribe(e){return this._completed?()=>{}:(this._listeners.add(e),()=>{this._listeners.delete(e)})}next(e){if(!this._completed)for(let t of[...this._listeners])t(e)}complete(){this._completed=!0,this._listeners.clear()}get observerCount(){return this._listeners.size}};function L(e){return{line:"#202020",text:"#000000",background:e}}function $(e){return{line:"#e0e0e0",text:"#ffffff",background:j(e,.25)}}function P(e){let t=/^#([0-9a-fA-F]{6})$/.exec(e),i=/^#([0-9a-fA-F]{3})$/.exec(e);if(null!==t){let e=t[1];return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}if(null!==i){let e=i[1];return[parseInt(e[0]+e[0],16),parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16)]}return null}function R(e){return e.toString(16).padStart(2,"0")}function H(e,t,i){return`#${R(e)}${R(t)}${R(i)}`}function N(e,t,i){let n=e/255,o=t/255,r=i/255,s=Math.max(n,o,r),a=Math.min(n,o,r),l=(s+a)/2;if(s===a)return[0,0,l];let h,d=s-a;return h=s===n?60*((o-r)/d+(o<r?6:0)):s===o?60*((r-n)/d+2):60*((n-o)/d+4),[h,l>.5?d/(2-s-a):d/(s+a),l]}function D(e,t,i){let n=i;return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function F(e,t,i){if(0===t){let e=Math.round(255*i);return[e,e,e]}let n=i<.5?i*(1+t):i+t-i*t,o=2*i-n,r=e/360;return[Math.round(255*D(o,n,r+1/3)),Math.round(255*D(o,n,r)),Math.round(255*D(o,n,r-1/3))]}function O(e,t=.3,i=.1){let n=P(e);if(null===n)return e;let[o,r,s]=N(n[0],n[1],n[2]),a=Math.max(0,Math.min(1,r*(1-t))),l=Math.max(0,Math.min(.95,s+i*(1-s))),[h,d,c]=F(o,a,l);return H(h,d,c)}function z(e){let t=P(e);if(null===t)return 0;let i=e=>{let t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(t[0])+.7152*i(t[1])+.0722*i(t[2])}function G(e){let t=P(e);if(null===t)return"#1f2937";let[i,n,o]=N(t[0],t[1],t[2]);if(o>.85||n<.15&&o>.7)return"#1f2937";let r=Math.max(.08,o-.3);return function(e){let t=(e.h%360+360)%360,i=Math.max(0,Math.min(1,e.s)),n=Math.max(0,Math.min(1,e.l)),[o,r,s]=F(t,i,n);return H(o,r,s)}({h:i,s:Math.min(1,n+.1),l:r})}function q(e){let t=function(e){let t=P(e);return null===t?null:{r:t[0]/255,g:t[1]/255,b:t[2]/255}}(e);if(null===t)return"#1f2937";let i=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4),n=.2126*i(t.r)+.7152*i(t.g)+.0722*i(t.b);return 1.05/(n+.05)>(n+.05)/.05?"#ffffff":"#1f2937"}function j(e,t){let i=P(e);if(null===i)return e;let n=1-t;return H(Math.max(0,Math.min(255,Math.round(i[0]*n))),Math.max(0,Math.min(255,Math.round(i[1]*n))),Math.max(0,Math.min(255,Math.round(i[2]*n))))}var Y={A:L("#A0A0FF"),G:L("#FF7070"),T:L("#A0FFA0"),C:L("#FF8C4B"),U:L("#FF8080")},V={R:L("#7a85c1"),r:L("#7a85c1")},W={P:L("#9aa5e1"),p:L("#9aa5e1")},U={A:L("#C8C8C8"),R:L("#145AFF"),N:L("#00DCDC"),D:L("#E60A0A"),C:L("#E6E600"),E:L("#00DCDC"),Q:L("#E60A0A"),G:L("#EBEBEB"),H:L("#8282D2"),I:L("#0F820F"),L:L("#0F820F"),K:L("#145AFF"),M:L("#E6E600"),F:L("#3232AA"),P:L("#DC9682"),S:L("#FA9600"),T:L("#FA9600"),W:L("#B45AB4"),Y:L("#3232AA"),V:L("#0F820F")},K={R:L("#eeeeee")},X={B:L("#999999"),G:L("#e2e2e2")},Q={P:L("#9aa5e1")},Z={name:"light",fallback:{line:"#202020",text:"#000000",background:"#eeeeee"},errorTriple:{line:"#cc0000",text:"#000000",background:"#FFFF00"},palette:{[w]:Y,[v]:V,[x]:W,[y]:U,[C]:K,[k]:X,[E]:Q}};function J(e){let t={};for(let[i,n]of Object.entries(e))t[i]=$(n.background);return t}var ee={name:"dark",fallback:{line:"#e0e0e0",text:"#ffffff",background:j("#eeeeee",.5)},errorTriple:{line:"#ff5050",text:"#ffffff",background:j("#FFFF00",.4)},palette:{[w]:J(Y),[v]:J(V),[x]:J(W),[y]:J(U),[C]:J(K),[k]:J(X),[E]:J(Q)}};function te(e,t,i=Z){if(null===e)return{...i.errorTriple};let n=e.meta?.colors;if(void 0!==n){let e="light"===i.name?n.light:"dark"===i.name?n.dark:void 0;if(void 0!==e)return{...e,line:G(e.background)};if(void 0!==n.default)return{...n.default,line:G(n.default.background)}}let o=e.naturalAnalog;if(void 0!==o&&""!==o){let e=i.palette[t];if(void 0!==e){let t=e[o];if(void 0!==t)return{...t,line:G(t.background),text:q(t.background)}}}return{...i.fallback,line:G(i.fallback.background),text:q(i.fallback.background)}}function ie(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&"capgroupsmiles"===t.toLowerCase()){let i=e[t];if("string"==typeof i)return i}}function ne(e){switch(e.polymerType){case B.PEPTIDE:return y;case B.CHEM:return C;case B.BLOB:return k;case B.RNA:if("Branch"===e.monomerType)return w;if("Backbone"===e.monomerType){let t=e.naturalAnalog;return"P"===t||"p"===t?x:v}return null;default:return null}}function oe(e,t,i){return new ae(e,t,i??{}).run()}new Set(["PEPTIDE","RNA","CHEM","BLOB"]),new Set(["Backbone","Branch","Terminal","Undefined"]);var re=new Set(["?","*","_","X","N"]),se=/^R([1-9][0-9]*)$/,ae=class{constructor(e,t,i){this.diagnostics=[],this.oldToNew=new Map,this.placeholderCache=new Map,this.mol=e,this.lib=t,this.options=i}run(){let e=new Map;for(let t of this.mol.chains)e.set(t.id,t.polymerType);for(let t of this.mol.atoms){let i=e.get(t.bio.chainId)??null,n=this.resolveAtom(t,i);this.oldToNew.set(t.id,n)}for(let e of this.mol.atoms){let t=this.oldToNew.get(e.id);if(void 0===t||void 0===e.branchAtom)continue;let i=this.oldToNew.get(e.branchAtom.id);void 0!==i&&(t.branchAtom=i)}let t=[];for(let e of this.mol.bonds){let i=this.oldToNew.get(e.a1.id),n=this.oldToNew.get(e.a2.id);void 0===i||void 0===n||t.push({...e,a1:i,a2:n})}let i=new Map;for(let e of t)i.set(e.id,e);let n=[];for(let e of this.mol.chains){let t=[];for(let i of e.backboneAtoms){let e=this.oldToNew.get(i.id);void 0!==e&&t.push(e)}let o=[];for(let t of e.bonds){let e=i.get(t.id);void 0!==e&&o.push(e)}n.push({id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:o,...void 0!==e.annotation?{annotation:e.annotation}:{},...void 0!==e.strandType?{strandType:e.strandType}:{}})}return{mol:{atoms:this.mol.atoms.map(e=>this.oldToNew.get(e.id)),bonds:t,chains:n,groups:this.mol.groups,annotations:this.mol.annotations},diagnostics:this.diagnostics}}resolveAtom(e,t){let i=null,n=e.biotype;if(null!==t){let o=this.lib.getMonomer(t,e.symbol);if(null!==o)i=this.toResolved(o),n=ne(o)??e.biotype;else if(this.isAmbiguitySymbol(e))i=this.synthesizeAmbiguity(t,e),this.emit("info","ambiguous-monomer",`Ambiguous monomer '${e.symbol}' on chain '${e.bio.chainId}'`,e);else if(T(e.symbol))i=this.registerInlineSmilesFallback(t,e);else if(!0===this.options.legacyCaseFallback&&"RNA"===t){let o=this.findCaseInsensitiveMatch(t,e.symbol);null!==o&&(i=this.toResolved(o),n=ne(o)??e.biotype,this.emit("info","case-mismatch",`Symbol '${e.symbol}' matched library entry '${o.symbol}' only after case fold`,e))}null===i&&(i=this.synthesizeMissing(t,e),this.emit("warning","unresolved-monomer",`Monomer '${e.symbol}' not found in library for ${t}`,e))}return{...e,monomer:i,biotype:n}}toResolved(e){let t=this.lib.getResolved?.(e);if(void 0!==t)return t;let i=new Map;for(let t of e.rgroups){let e=se.exec(t.label);null!==e&&i.set(parseInt(e[1],10),t)}return Object.assign({},e,{rs:e.rgroups.length,rgroupMap:i})}isAmbiguitySymbol(e){return!(!re.has(e.symbol)&&void 0===e.bio.ambiguity)}synthesizeAmbiguity(e,t){let i=`ambig:${e}:${t.symbol}`,n=this.placeholderCache.get(i);return void 0===n&&(n={symbol:t.symbol,polymerType:e,monomerType:"Undefined",molfile:"",rgroups:[{label:"R1",capGroupName:"H",capGroupSMILES:""},{label:"R2",capGroupName:"H",capGroupSMILES:""}],meta:{ambiguous:!0}},this.placeholderCache.set(i,n)),this.toResolved(n)}synthesizeMissing(e,t){let i=`missing:${e}:${t.symbol}`,n=this.placeholderCache.get(i);return void 0===n&&(n={symbol:t.symbol,polymerType:e,monomerType:"Undefined",molfile:"",rgroups:[{label:"R1",capGroupName:"H",capGroupSMILES:""},{label:"R2",capGroupName:"H",capGroupSMILES:""}],meta:{missing:!0}},this.placeholderCache.set(i,n)),this.toResolved(n)}registerInlineSmilesFallback(e,t){if("function"==typeof this.lib.registerInlineSmilesMonomer)try{let i=this.lib.registerInlineSmilesMonomer(e,t.symbol);return this.toResolved(i)}catch{this.emit("warning","inline-smiles-without-r-groups",`Inline SMILES '${i=t.symbol,i.length<=40?i:i.slice(0,39)+"…"}' has no detectable R-groups`,t)}else this.emit("warning","inline-smiles-without-r-groups","Inline SMILES seen but lib has no registerInlineSmilesMonomer",t);var i;return this.synthesizeMissing(e,t)}findCaseInsensitiveMatch(e,t){let i=t.toLowerCase();for(let n of this.lib.getMonomerSymbolsByType(e))if(n.toLowerCase()===i&&n!==t){let t=this.lib.getMonomer(e,n);if(null!==t)return t}return null}emit(e,t,i,n){let o={chainId:n.bio.chainId,atomId:n.id,symbol:n.symbol};this.diagnostics.push({severity:e,code:t,message:i,context:o})}};function le(e,t,i){let n,o=i?.mode??"lenient";try{n=function(e){let t=new p(e).tokenize();return function(e){let t=null;for(let i of e.tokens)if("apos"===i.kind)t=null===t?i.span:null;else if("eof"===i.kind&&null!==t)throw new r("unterminated-apostrophe",`Unterminated apostrophe block starting at offset ${t.start}`,{span:{start:t.start,end:e.source.length}})}(t),t}(e)}catch(e){if(e instanceof r){if("strict"===o)throw e;let t={severity:"error",code:e.code,message:e.message,...void 0!==e.span?{span:{start:e.span.start,end:e.span.end}}:{}};return{mol:b(),diagnostics:[t]}}throw e}return function(e,t,i){let n=new ue(e,t,i?.mode??"lenient").parseDocument();if(null===t||!1===i?.resolveMonomers)return n;let o=oe(n.mol,t,{mode:i?.mode??"lenient",...!0===i?.legacyCaseFallback?{legacyCaseFallback:!0}:{}});return{mol:o.mol,diagnostics:[...n.diagnostics,...o.diagnostics]}}(n,t,i)}var he=class{constructor(e){this.tokens=e.tokens,this.len=e.tokens.length,this.eof=e.tokens[e.tokens.length-1],this.idx=0}peek(e=0){let t=this.idx+e;return t>=this.len?this.eof:this.tokens[t]}advance(){let e=this.idx<this.len?this.tokens[this.idx]:this.eof;return"eof"!==e.kind&&(this.idx+=1),e}optional(e){let t=this.idx<this.len?this.tokens[this.idx]:this.eof;return t.kind===e?("eof"!==t.kind&&(this.idx+=1),t):null}at(e){return(this.idx<this.len?this.tokens[this.idx]:this.eof).kind===e}at2(e,t){let i=(this.idx<this.len?this.tokens[this.idx]:this.eof).kind;return i===e||i===t}at3(e,t,i){let n=(this.idx<this.len?this.tokens[this.idx]:this.eof).kind;return n===e||n===t||n===i}currentSpan(){return(this.idx<this.len?this.tokens[this.idx]:this.eof).span}position(){return this.idx}setPosition(e){this.idx=e}isAtEnd(){return"eof"===(this.idx<this.len?this.tokens[this.idx]:this.eof).kind}},de=/^(PEPTIDE|RNA|DNA|CHEM|BLOB|G)([0-9]+)$/;function ce(e){let t=de.exec(e);if(null===t)return null;let i=t[1],n=parseInt(t[2],10);switch(i){case"PEPTIDE":return{rawTypeName:"PEPTIDE",polymerType:B.PEPTIDE,number:n,isDnaShim:!1,isGroup:!1};case"RNA":return{rawTypeName:"RNA",polymerType:B.RNA,number:n,isDnaShim:!1,isGroup:!1};case"DNA":return{rawTypeName:"DNA",polymerType:B.RNA,number:n,isDnaShim:!0,isGroup:!1};case"CHEM":return{rawTypeName:"CHEM",polymerType:B.CHEM,number:n,isDnaShim:!1,isGroup:!1};case"BLOB":return{rawTypeName:"BLOB",polymerType:B.BLOB,number:n,isDnaShim:!1,isGroup:!1};case"G":return{rawTypeName:"G",polymerType:B.PEPTIDE,number:n,isDnaShim:!1,isGroup:!0};default:return null}}var ue=class{constructor(e,t,i){this.diagnostics=[],this.chains=[],this.chainById=new Map,this.pendingBonds=[],this.groups=[],this.atomIds=new S,this.bondIds=new S,this.cursor=new he(e),this.source=e.source,this.lib=t,this.mode=i,this.annotations={perPolymer:new Map,version:""}}parseDocument(){if(this.cursor.isAtEnd())return this.emit("warning","empty-helm","Empty HELM string"),{mol:b(),diagnostics:this.diagnostics};if(this.parseSimplePolymers(),this.expectDollarSeparator(1),this.parseConnections(),this.expectDollarSeparator(2),this.parseGroupsSection(),this.expectDollarSeparator(3),this.parseAnnotationsSection(),this.cursor.at("dollar")&&(this.cursor.advance(),this.parseVersionTrailer()),!this.cursor.isAtEnd())for(this.emit("warning","extra-section-separator","Unexpected trailing tokens after HELM document",this.cursor.currentSpan());!this.cursor.isAtEnd();)this.cursor.advance();return{mol:this.finalize(),diagnostics:this.diagnostics}}expectDollarSeparator(e){this.cursor.at("dollar")?this.cursor.advance():this.emit("error","missing-section-separator",`Expected '$' separator before section ${e+1}`,this.cursor.currentSpan())}parseSimplePolymers(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd())for(this.parsePolymer();this.cursor.at("pipe");){if(this.cursor.advance(),this.cursor.at("dollar")||this.cursor.isAtEnd())return void this.emit("warning","empty-polymer-body","Empty polymer after '|'",this.cursor.currentSpan());this.parsePolymer()}}parsePolymer(){let e=this.cursor.currentSpan(),t=this.cursor.optional("identifier");if(null===t)return this.emit("error","unexpected-token",`Expected polymer id, got '${this.cursor.peek().value}'`,this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let i=ce(t.value);if(null===i)return this.emit("error","unknown-polymer-type",`Unknown polymer type '${t.value}'`,t.span),void this.skipUntil(["pipe","dollar","eof"]);if(this.chainById.has(t.value)&&this.emit("warning","duplicate-polymer-id",`Duplicate polymer id '${t.value}'`,t.span),null===this.cursor.optional("lbrace"))return void this.emit("error","unexpected-token",`Expected '{' after polymer id '${t.value}'`,this.cursor.currentSpan());let n={id:t.value,polymerType:i.polymerType,rawTypeName:i.rawTypeName,rawNumber:i.number,backboneAtoms:[],allAtoms:[],bonds:[],span:{start:e.start,end:e.end}};if(this.chains.push(n),this.chainById.set(n.id,n),this.cursor.at("rbrace"))this.emit("warning","empty-polymer-body",`Empty body for polymer '${n.id}'`,this.cursor.currentSpan());else if(i.isGroup)this.parseGroupBody(n);else switch(i.polymerType){case B.PEPTIDE:this.parsePeptideBody(n);break;case B.RNA:this.parseRnaBody(n,i.isDnaShim),i.isDnaShim&&this.emit("info","dna-emitted-as-rna",`DNA polymer '${n.id}' will be emitted as RNA on canonicalize`,t.span);break;case B.CHEM:this.parseChemBody(n);break;case B.BLOB:this.parseBlobBody(n)}if(null===this.cursor.optional("rbrace"))return this.emit("error","unterminated-brace",`Expected '}' to close polymer '${n.id}'`,this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let o=this.cursor.optional("quote-string");null!==o&&(n.annotation=o.value)}parsePeptideBody(e){for(this.parsePeptideItem(e);this.cursor.at("dot")&&(this.cursor.advance(),!this.cursor.at("rbrace")&&!this.cursor.at("gt"));)this.parsePeptideItem(e);if(this.cursor.at("gt")){let t=this.cursor.currentSpan();this.cursor.advance(),this.emit("warning","peptide-cyclic-without-closure",`Peptide '${e.id}' marked cyclic with '>' — no explicit closure connection emitted`,t)}}parsePeptideItem(e){if(this.cursor.at("lparen"))this.parsePeptideAlternation(e);else{let t=this.parsePeptideAtom(e);this.maybeRepeatBracket(e,[t])}this.maybeAttachAnnotation(e)}parsePeptideAtom(e){let t=this.consumeMonomerSymbol(!1),{symbol:i,annotation:n,ambiguity:o,ambiguityKind:r,isInlineSmiles:s,rawPayload:a,inlineSource:l,span:h}=t,d=this.makeAtom(e,y,i);void 0!==n&&(d.tag=n),void 0!==o&&(d.bio.ambiguity=o),void 0!==r&&(d.bio.ambiguityKind=r),void 0!==l&&(d.inlineSource=l),s&&this.registerInlineSmiles(a,h,B.PEPTIDE),this.addToChain(e,d,!0);let c=e.backboneAtoms[e.backboneAtoms.length-2];return void 0!==c&&this.addBond(e,c,d,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),d}parsePeptideAlternation(e){let t=this.cursor.currentSpan();if(this.cursor.advance(),this.peptideContentIsSubsequence()){let t=e.backboneAtoms.length;for(this.parsePeptideItem(e);this.cursor.at("dot")&&(this.cursor.advance(),!this.cursor.at("rparen")&&!this.cursor.isAtEnd());)this.parsePeptideItem(e);null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' to close repeat sub-sequence",this.cursor.currentSpan());let i=e.backboneAtoms.slice(t);return this.maybeRepeatBracket(e,i),void this.maybeAttachAnnotation(e)}let i=[],n=null;for(;!this.cursor.at("rparen")&&!this.cursor.isAtEnd();){let e=this.parseAlternationCandidate(B.PEPTIDE);if(i.push(e),this.cursor.at("comma"))"and"===n&&this.emit("warning","mixed-separator-in-alternation","Mixed ',' and '+' separators in alternation",this.cursor.currentSpan()),n="or",this.cursor.advance();else{if(!this.cursor.at("plus"))break;"or"===n&&this.emit("warning","mixed-separator-in-alternation","Mixed ',' and '+' separators in alternation",this.cursor.currentSpan()),n="and",this.cursor.advance()}}null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' to close alternation",this.cursor.currentSpan());let o="and"===n?"+":",",r=`(${i.map(e=>e.symbol+(void 0!==e.ratio?`:${String(e.ratio)}`:"")).join(o)})`,s=this.makeAtom(e,y,"?");s.bio.ambiguity=r,s.bio.ambiguityKind="and"===n?"and":"or",this.addToChain(e,s,!0);let a=e.backboneAtoms[e.backboneAtoms.length-2];if(void 0!==a&&this.addBond(e,a,s,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),"and"===n)for(let e of i)"number"==typeof e.ratio&&e.ratio<0&&this.emit("error","ratio-and-negative",`Negative ratio ${e.ratio} in AND mixture`,t);this.maybeRepeatBracket(e,[s]),this.maybeAttachAnnotation(e)}peptideContentIsSubsequence(){let e=1,t=0;for(;;){let i=this.cursor.peek(t);if("eof"===i.kind)return!1;if("lparen"!==i.kind)if("rparen"!==i.kind){if(1===e){if("dot"===i.kind)return!0;if("comma"===i.kind||"plus"===i.kind||"colon"===i.kind)return!1}if(t+=1,t>1024)return!1}else{if(e-=1,0===e)return!0;t+=1}else e+=1,t+=1}}parseAlternationCandidate(e){let t,{symbol:i,isInlineSmiles:n,rawPayload:o,span:r}=this.consumeMonomerSymbol(!0);if(n&&this.registerInlineSmiles(o,r,e),null!==this.cursor.optional("colon")){let e=this.cursor.peek();"integer"===e.kind||"decimal"===e.kind?(this.cursor.advance(),t=parseFloat(e.value)):"question"===e.kind?(this.cursor.advance(),t="?"):this.emit("error","unexpected-token","Expected ratio after ':' in alternation",e.span)}return void 0===t?{symbol:i}:{symbol:i,ratio:t}}parseRnaBody(e,t){for(this.parseRnaItem(e,t);this.cursor.at("dot")&&(this.cursor.advance(),!(this.cursor.at("rbrace")||this.cursor.at("dollar")||this.cursor.isAtEnd()));)this.parseRnaItem(e,t)}parseRnaItem(e,t){if(this.cursor.at("lparen"))return void this.parseRnaAlternation(e,t);if(this.cursor.at("asterisk")){this.cursor.currentSpan(),this.cursor.advance();let t=this.makeAtom(e,E,"*");this.addToChain(e,t,!0);let i=e.backboneAtoms[e.backboneAtoms.length-2];return void 0!==i&&this.addBond(e,i,t,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),this.maybeRepeatBracket(e,[t]),void this.maybeAttachAnnotation(e)}let i,n,o=this.parseRnaSugar(e,t);this.maybeAttachAnnotation(e),this.cursor.at("lparen")&&(this.cursor.advance(),this.cursor.at("rparen")||(i=this.parseRnaBaseSymbol(e),this.maybeAttachAnnotationTo(i)),null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' after RNA base",this.cursor.currentSpan()),void 0!==i&&(this.addBond(e,o,i,"branch",{kind:"numeric",r:3},{kind:"numeric",r:1}),o.branchAtom=i)),this.canStartRnaLinker()&&(n=this.parseRnaLinker(e),this.maybeAttachAnnotationTo(n)),void 0!==n&&this.addBond(e,o,n,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1});let r=e.backboneAtoms.indexOf(o);if(r>0){let t=e.backboneAtoms[r-1];this.addBond(e,t,o,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1})}let s=[o];void 0!==i&&s.push(i),void 0!==n&&s.push(n),this.maybeRepeatBracket(e,s)}canStartRnaLinker(){let e=this.cursor.peek().kind;return"identifier"===e||"inline-smiles"===e||"asterisk"===e}parseRnaSugar(e,t){let{symbol:i,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(!1),a=this.makeAtom(e,v,i);return void 0!==r&&(a.inlineSource=r),n&&this.registerInlineSmiles(o,s,B.RNA),this.addToChain(e,a,!0),a}parseRnaBaseSymbol(e){let{symbol:t,isInlineSmiles:i,rawPayload:n,inlineSource:o,span:r}=this.consumeMonomerSymbol(!1),s=this.makeAtom(e,w,t);return void 0!==o&&(s.inlineSource=o),i&&this.registerInlineSmiles(n,r,B.RNA),this.addToChain(e,s,!1),s}parseRnaLinker(e){if(this.cursor.at("asterisk")){this.cursor.currentSpan(),this.cursor.advance();let t=this.makeAtom(e,x,"*");return this.addToChain(e,t,!0),t}let{symbol:t,isInlineSmiles:i,rawPayload:n,inlineSource:o,span:r}=this.consumeMonomerSymbol(!1),s=this.makeAtom(e,x,t);return void 0!==o&&(s.inlineSource=o),i&&this.registerInlineSmiles(n,r,B.RNA),this.addToChain(e,s,!0),s}parseRnaAlternation(e,t){let i=e.backboneAtoms.length;if(this.cursor.advance(),this.looksLikeFlatAlternation()){let t=[],i=null;for(;!this.cursor.at("rparen")&&!this.cursor.isAtEnd();)if(t.push(this.parseAlternationCandidate(B.RNA)),this.cursor.at("comma"))i="or",this.cursor.advance();else{if(!this.cursor.at("plus"))break;i="and",this.cursor.advance()}null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' in RNA alternation",this.cursor.currentSpan());let n="and"===i?"+":",",o=`(${t.map(e=>e.symbol+(void 0!==e.ratio?`:${String(e.ratio)}`:"")).join(n)})`,r=this.makeAtom(e,w,"?");r.bio.ambiguity=o,r.bio.ambiguityKind="and"===i?"and":"or",this.addToChain(e,r,!0);let s=e.backboneAtoms[e.backboneAtoms.length-2];return void 0!==s&&this.addBond(e,s,r,"backbone",{kind:"numeric",r:2},{kind:"numeric",r:1}),this.maybeRepeatBracket(e,[r]),void this.maybeAttachAnnotation(e)}for(this.parseRnaItem(e,t);this.cursor.at("dot")&&(this.cursor.advance(),!this.cursor.at("rparen")&&!this.cursor.isAtEnd());)this.parseRnaItem(e,t);null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' in RNA repeat",this.cursor.currentSpan());let n=e.backboneAtoms.slice(i);this.maybeRepeatBracket(e,n),this.maybeAttachAnnotation(e)}looksLikeFlatAlternation(){let e=1,t=0,i=!1;for(;;){let n=this.cursor.peek(t);if("eof"===n.kind)return i;if("rparen"===n.kind){if(e-=1,0===e)return i}else{if("lparen"===n.kind)return!1;if("dot"===n.kind)return!1;1===e&&("comma"===n.kind||"plus"===n.kind)&&(i=!0)}if(t+=1,t>256)return i}}parseChemBody(e){let t;if(this.cursor.at("asterisk"))this.cursor.advance(),t=this.makeAtom(e,C,"*"),this.addToChain(e,t,!0);else{let{symbol:i,isInlineSmiles:n,rawPayload:o,inlineSource:r,span:s}=this.consumeMonomerSymbol(!1);t=this.makeAtom(e,C,i),void 0!==r&&(t.inlineSource=r),n&&this.registerInlineSmiles(o,s,B.CHEM),this.addToChain(e,t,!0)}this.maybeAttachAnnotation(e),this.cursor.at("apos")&&this.maybeRepeatBracket(e,[t]),this.cursor.at("rbrace")||(this.emit("error","chem-multiple-monomers",`CHEM polymer '${e.id}' must contain exactly one monomer`,this.cursor.currentSpan()),this.skipUntil(["rbrace","eof"]))}parseBlobBody(e){let t,i,n,o=!1,r="",s=this.cursor.currentSpan();if(this.cursor.at("inline-smiles")){let e=this.cursor.advance();o=T(e.value),r=e.value,t=e.value,i=e.value,n=e.value,s=e.span}else if(this.cursor.at("identifier")){let e=this.cursor.advance();t=e.value,i=e.value,s=e.span}else this.emit("error","unknown-blobtype","Expected BLOB identifier",this.cursor.currentSpan()),t="?",i="?";let a=this.makeAtom(e,k,t);a.bio.blobtype=i,void 0!==n&&(a.inlineSource=n),o&&this.registerInlineSmiles(r,s,B.BLOB),this.addToChain(e,a,!0),this.maybeAttachAnnotation(e)}parseGroupBody(e){let t=0;for(;;){let e=this.cursor.peek();if("eof"===e.kind||0===t&&"rbrace"===e.kind)break;"lbrace"===e.kind&&(t+=1),"rbrace"===e.kind&&(t-=1),this.cursor.advance()}}parseConnections(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd())for(this.parseConnection();this.cursor.at("pipe")&&(this.cursor.advance(),!this.cursor.at("dollar")&&!this.cursor.isAtEnd());)this.parseConnection()}parseConnection(){let e=this.cursor.currentSpan(),t=this.cursor.optional("identifier");if(null===t)return this.emit("error","unexpected-token","Expected chain id in connection",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);if(null===this.cursor.optional("comma"))return this.emit("error","unexpected-token","Expected ',' in connection",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let i=this.cursor.optional("identifier");if(null===i)return this.emit("error","unexpected-token","Expected second chain id in connection",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);if(null===this.cursor.optional("comma"))return this.emit("error","unexpected-token","Expected ',' before connection position",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let n=this.parsePosition();if(null===this.cursor.optional("colon"))return this.emit("error","unexpected-token","Expected ':' between position and R-group",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let o=this.parseRGroupSpec();if(null===this.cursor.optional("dash"))return this.emit("error","unexpected-token","Expected '-' between connection endpoints",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let r=this.parsePosition();if(null===this.cursor.optional("colon"))return this.emit("error","unexpected-token","Expected ':' before second R-group",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let s=this.parseRGroupSpec(),a=this.cursor.optional("quote-string"),l="pair"===o.kind&&"pair"===s.kind?"hbond":"cross-polymer",h={chain1:t.value,pos1:n,r1:o,chain2:i.value,pos2:r,r2:s,kind:l,span:{start:e.start,end:a?.span.end??this.cursor.peek().span.start},...null!==a?{tag:a.value}:{}};this.pendingBonds.push(h)}parsePosition(){let e=this.cursor.peek();return"integer"===e.kind?(this.cursor.advance(),{kind:"index",value:parseInt(e.value,10)}):"question"===e.kind?(this.cursor.advance(),{kind:"any"}):"identifier"===e.kind?(this.cursor.advance(),this.emit("info","symbol-position-reference",`Connection position uses monomer symbol '${e.value}' as chain-level ambiguity`,e.span),{kind:"symbol",value:e.value}):(this.emit("error","invalid-position",`Expected position (integer, '?', or symbol), got '${e.value}'`,e.span),{kind:"any"})}parseRGroupSpec(){let e=this.cursor.peek();if("question"===e.kind)return this.cursor.advance(),{kind:"unspecified"};if("asterisk"===e.kind)return this.cursor.advance(),{kind:"wildcard"};if("identifier"===e.kind){if(this.cursor.advance(),"pair"===e.value)return{kind:"pair"};let t=/^R([1-9][0-9]*)$/.exec(e.value);return null===t?(this.emit("error","invalid-rgroup",`Expected R-group label, got '${e.value}'`,e.span),{kind:"unspecified"}):{kind:"numeric",r:parseInt(t[1],10)}}return this.emit("error","invalid-rgroup",`Expected R-group label, got '${e.value}'`,e.span),{kind:"unspecified"}}parseGroupsSection(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd())for(this.parseGroupOrBondRatio();this.cursor.at("pipe")&&(this.cursor.advance(),!this.cursor.at("dollar")&&!this.cursor.isAtEnd());)this.parseGroupOrBondRatio()}parseGroupOrBondRatio(){let e=this.cursor.optional("identifier");if(null===e)return this.emit("error","unexpected-token","Expected group or bond-ratio identifier",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);this.cursor.at("lparen")?this.parseGroupAfterId(e):this.cursor.at("plus")?this.parseBondRatioAfterId(e):(this.emit("warning","unexpected-token",`Expected '(' or '+' after id '${e.value}' in section 3`,this.cursor.currentSpan()),this.skipUntil(["pipe","dollar","eof"]))}parseGroupAfterId(e){let t=ce(e.value);(null===t||!t.isGroup)&&this.emit("error","unknown-group-reference",`Group id must be 'G<n>', got '${e.value}'`,e.span),this.cursor.advance();let i=[],n="or",o=null;for(;!this.cursor.at("rparen")&&!this.cursor.isAtEnd();){let e=this.parseGroupMember();if(null!==e&&i.push(e),this.cursor.at("comma"))null===o&&(o="or",n="or"),this.cursor.advance();else{if(!this.cursor.at("plus"))break;null===o&&(o="and",n="and"),this.cursor.advance()}}null===this.cursor.optional("rparen")&&this.emit("error","unterminated-paren","Expected ')' to close group",this.cursor.currentSpan()),this.groups.push({id:e.value,kind:n,members:i})}parseGroupMember(){let e,t=this.cursor.optional("identifier");return null===t?(this.emit("error","unexpected-token","Expected group member id",this.cursor.currentSpan()),null):(null!==this.cursor.optional("colon")&&(e=this.parseRatio()),void 0===e?{target:t.value}:{target:t.value,ratio:e})}parseRatio(){let e=this.cursor.peek();if("integer"===e.kind||"decimal"===e.kind){this.cursor.advance();let t=parseFloat(e.value);if(this.cursor.at("dash")&&(this.cursor.peek(),"integer"===this.cursor.peek(1).kind)){this.cursor.advance();let t=this.cursor.advance();this.emit("info","ratio-range",`Ratio range ${e.value}-${t.value}; using lower bound`,{start:e.span.start,end:t.span.end})}return t}return"question"===e.kind?(this.cursor.advance(),"?"):(this.emit("error","unexpected-token",`Expected ratio after ':', got '${e.value}'`,e.span),0)}parseBondRatioAfterId(e){this.cursor.advance();let t,i=this.cursor.optional("identifier");if(null===i)return void this.emit("error","unexpected-token","Expected second chain id in bond-ratio",this.cursor.currentSpan());if(null!==this.cursor.optional("colon")){let e=this.parseRatio();"number"==typeof e&&(t=e)}let n=this.pendingBonds.find(t=>t.chain1===e.value&&t.chain2===i.value||t.chain1===i.value&&t.chain2===e.value);void 0!==n?void 0!==t&&(n.ratio={numerator:t}):this.emit("warning","bond-ratio-no-matching-bond",`Bond-ratio for ${e.value}+${i.value} has no matching cross-polymer bond`,e.span)}parseAnnotationsSection(){if(!this.cursor.at("dollar")&&!this.cursor.isAtEnd()){if(this.cursor.position(),this.cursor.at("lbrace"))return this.parseAnnotation20(),void(this.cursor.at("pipe")&&(this.emit("info","annotation-mixed-versions","Mixed HELM 2.0 JSON and HELM 1.0 pipe annotations",this.cursor.currentSpan()),this.cursor.advance(),this.parseAnnotation10Entries()));this.parseAnnotation10Entries()}}parseAnnotation20(){let e=this.cursor.currentSpan(),t=0,i=e.end;for(;!this.cursor.isAtEnd();){let e=this.cursor.peek();if("lbrace"===e.kind)t+=1;else if("rbrace"===e.kind&&(t-=1,0===t)){i=e.span.end,this.cursor.advance();break}this.cursor.advance()}let n=this.source.slice(e.start,i),o=null;try{o=JSON.parse(n)}catch{return this.emit("warning","annotation-malformed-json","Annotation block is not valid JSON",{start:e.start,end:i}),void(this.annotations={perPolymer:this.annotations.perPolymer,version:this.annotations.version,raw:n})}if(null===o||"object"!=typeof o||Array.isArray(o))this.emit("warning","annotation-malformed-json","Annotation block parsed but is not an object",{start:e.start,end:i}),this.annotations={perPolymer:this.annotations.perPolymer,version:this.annotations.version,raw:n};else{let t=new Map(this.annotations.perPolymer);for(let[i,n]of Object.entries(o))null===n||"object"!=typeof n||Array.isArray(n)?t.set(i,{value:n}):(t.set(i,{...n}),this.chainById.has(i)||this.emit("warning","annotation-unknown-polymer",`Annotation references unknown polymer '${i}'`,e));this.annotations={perPolymer:t,version:this.annotations.version}}}parseAnnotation10Entries(){for(this.parseAnnotation10One();this.cursor.at("pipe")&&(this.cursor.advance(),!this.cursor.at("dollar")&&!this.cursor.isAtEnd());)this.parseAnnotation10One()}parseAnnotation10One(){let e=this.cursor.optional("identifier");if(null===e)return this.emit("warning","annotation-malformed-json","Expected polymer-id in HELM 1.0 annotation",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);if(null===this.cursor.optional("lbrace"))return this.emit("warning","annotation-malformed-json","Expected '{' after polymer-id",this.cursor.currentSpan()),void this.skipUntil(["pipe","dollar","eof"]);let t=[];for(;!this.cursor.at("rbrace")&&!this.cursor.isAtEnd();)t.push(this.cursor.advance().value);if(null===this.cursor.optional("rbrace"))return void this.emit("error","unterminated-brace","Expected '}' to close annotation",this.cursor.currentSpan());let i=t.join("").trim(),n=new Map(this.annotations.perPolymer),o=n.get(e.value)??{};"ss"===i||"as"===i?n.set(e.value,{...o,strandtype:i}):n.set(e.value,{...o,[i]:!0}),this.chainById.has(e.value)||this.emit("warning","annotation-unknown-polymer",`Annotation references unknown polymer '${e.value}'`,e.span),this.annotations={perPolymer:n,version:this.annotations.version}}parseVersionTrailer(){let e=this.cursor.optional("identifier");if(null===e)return void(this.annotations={...this.annotations,version:""});let t=e.value;if(this.cursor.at("dot")&&"integer"===this.cursor.peek(1).kind){this.cursor.advance();let i=this.cursor.advance();t=`${e.value}.${i.value}`}this.annotations={...this.annotations,version:t}}skipUntil(e){for(;!this.cursor.isAtEnd();){if(e.includes(this.cursor.peek().kind))return;this.cursor.advance()}}consumeMonomerSymbol(e){let t=this.cursor.peek();if("inline-smiles"===t.kind){this.cursor.advance();let e=T(t.value);return{symbol:t.value,isInlineSmiles:e,rawPayload:t.value,inlineSource:t.value,span:t.span}}if("identifier"===t.kind){this.cursor.advance();let e=t.value,i=t.span;for(;"dash"===this.cursor.peek().kind&&"integer"===this.cursor.peek(1).kind&&("identifier"===this.cursor.peek(2).kind||"dash"===this.cursor.peek(2).kind);){this.cursor.advance();let t=this.cursor.advance();if(e=`${e}-${t.value}`,i=t.span,"identifier"===this.cursor.peek().kind){let t=this.cursor.advance();e=`${e}${t.value}`,i=t.span}}return{symbol:e,isInlineSmiles:!1,rawPayload:e,span:{start:t.span.start,end:i.end}}}if("asterisk"===t.kind||"underscore"===t.kind||"question"===t.kind)return this.cursor.advance(),{symbol:t.value,isInlineSmiles:!1,rawPayload:t.value,span:t.span};if("integer"===t.kind&&"identifier"===this.cursor.peek(1).kind){let e=this.cursor.advance(),t=this.cursor.advance(),i=`${e.value}${t.value}`;return{symbol:i,isInlineSmiles:!1,rawPayload:i,span:{start:e.span.start,end:t.span.end}}}return this.emit("error","unexpected-token",`Expected monomer symbol, got '${t.value}'`,t.span),{symbol:"?",isInlineSmiles:!1,rawPayload:"",span:t.span}}maybeRepeatBracket(e,t){if(!this.cursor.at("apos"))return;let i=this.cursor.currentSpan();this.cursor.advance();let n=this.cursor.optional("integer");if(null===n)return this.emit("error","unexpected-token","Expected integer in repeat bracket",this.cursor.currentSpan()),void this.cursor.optional("apos");let o=parseInt(n.value,10),r=o;if(this.cursor.at("dash")){this.cursor.advance();let e=this.cursor.optional("integer");null===e?this.emit("error","unexpected-token","Expected integer after '-' in repeat bracket",this.cursor.currentSpan()):r=parseInt(e.value,10)}if(null===this.cursor.optional("apos")&&this.emit("error","unterminated-apostrophe","Expected closing apostrophe",this.cursor.currentSpan()),0!==t.length){if(r<o){this.emit("warning","repeat-range-inverted",`Repeat range ${o}-${r} has max < min; swapping`,i);let e=o;o=r,r=e}0!==o||0!==r?(r>1e4&&this.emit("warning","bracket-repeat-too-large",`Repeat range upper bound ${r} > 10000`,i),e.polymerType===B.CHEM&&this.emit("error","repeat-on-non-iterable-polymer",`Repeat bracket not allowed on CHEM polymer '${e.id}'`,i),this.groups.push({id:`${e.id}/bracket@${t[0]?.id??0}`,kind:"bracket",members:t.map(e=>({target:String(e.id)})),repeat:{min:o,max:r}})):this.emit("warning","repeat-zero-count","Repeat bracket with zero count",i)}else this.emit("warning","repeat-on-empty-bracket","Repeat bracket applied to empty content",i)}maybeAttachAnnotation(e){let t=e.backboneAtoms[e.backboneAtoms.length-1];void 0!==t&&this.maybeAttachAnnotationTo(t)}maybeAttachAnnotationTo(e){if(void 0===e)return;let t=this.cursor.optional("quote-string");null!==t&&(e.tag=t.value)}registerInlineSmiles(e,t,i){if(T(e)){if(null===this.lib)return void this.emit("info","inline-smiles-no-lib","Inline SMILES seen but no monomer library available for registration",t);try{this.lib.addMonomer;let t=this.lib.registerInlineSmilesMonomer;"function"==typeof t&&t.call(this.lib,i,e)}catch(e){let i=e instanceof Error?e.message:String(e);this.emit("warning","inline-smiles-without-r-groups",`Inline SMILES registration failed: ${i}`,t)}}}makeAtom(e,t,i){return{id:this.atomIds.next(),p:{x:0,y:0},biotype:t,symbol:i,monomer:null,bio:{chainId:e.id,positionInChain:0,continuousId:0},hidden:!1,selected:!1,highlighted:!1}}addToChain(e,t,i){e.allAtoms.push(t),i&&(e.backboneAtoms.push(t),t.bio.positionInChain=e.backboneAtoms.length)}addBond(e,t,i,n,o,r){let s=this.bondIds.next();e.bonds.push({id:s,a1:t,a2:i,kind:n,r1:o,r2:r})}finalize(){let e=[];for(let t of this.pendingBonds){let i=this.chainById.get(t.chain1),n=this.chainById.get(t.chain2);if(void 0===i){this.emit("error","unknown-chain-reference",`Connection references unknown chain '${t.chain1}'`,t.span);continue}if(void 0===n){this.emit("error","unknown-chain-reference",`Connection references unknown chain '${t.chain2}'`,t.span);continue}let o=this.resolveAtomByPosition(i,t.pos1,t.span),r=this.resolveAtomByPosition(n,t.pos2,t.span);if(null===o||null===r)continue;"pair"===t.r1.kind&&void 0!==o.branchAtom&&(o=o.branchAtom),"pair"===t.r2.kind&&void 0!==r.branchAtom&&(r=r.branchAtom);let s={id:this.bondIds.next(),a1:o,a2:r,kind:t.kind,r1:t.r1,r2:t.r2,...void 0!==t.tag?{tag:t.tag}:{},...void 0!==t.ratio?{ratio:t.ratio}:{}};e.push(s)}let t=[],i=[],n=[];for(let e of this.chains){for(let i of e.allAtoms)t.push(i);for(let t of e.bonds)i.push(t);let o=this.annotations.perPolymer.get(e.id),r=void 0===o?void 0:o.strandtype,s="ss"===r||"as"===r?r:void 0;n.push({id:e.id,polymerType:e.polymerType,backboneAtoms:e.backboneAtoms,bonds:e.bonds,...void 0!==e.annotation?{annotation:e.annotation}:{},...void 0!==s?{strandType:s}:{}})}for(let t of e)i.push(t);let o=0;for(let e of this.chains)for(let t of e.backboneAtoms)o+=1,t.bio.continuousId=o,void 0!==t.branchAtom&&(o+=1,t.branchAtom.bio.continuousId=o);let r=[];for(let e of this.groups)r.push({id:e.id,kind:e.kind,members:e.members,...void 0!==e.repeat?{repeat:e.repeat}:{}});return{atoms:t,bonds:i,chains:n,groups:r,annotations:this.annotations}}sourceOrderAtoms(e){let t=[];for(let i of e.backboneAtoms)t.push(i),void 0!==i.branchAtom&&t.push(i.branchAtom);return t}resolveAtomByPosition(e,t,i){if("any"===t.kind)return e.backboneAtoms[0]??null;if("symbol"===t.kind){let n=e.backboneAtoms.find(e=>e.symbol===t.value);if(void 0===n){let n=e.allAtoms.find(e=>e.symbol===t.value);return void 0===n?(this.emit("warning","position-out-of-range",`Chain '${e.id}' has no monomer with symbol '${t.value}'`,i),e.backboneAtoms[0]??null):n}return n}let n=this.sourceOrderAtoms(e),o=t.value;return o<1||o>n.length?(this.emit("error","position-out-of-range",`Position ${o} out of range for chain '${e.id}' (length ${n.length})`,i),e.backboneAtoms[0]??null):n[o-1]}emit(e,t,i,n){let o={severity:e,code:t,message:i,...void 0!==n?{span:{start:n.start,end:n.end}}:{}};if(this.diagnostics.push(o),"strict"===this.mode&&"error"===e)throw new r(t,i,{...void 0!==n?{span:{start:n.start,end:n.end}}:{}})}};function pe(e,t){let i=function(e){let t=(t,i)=>t.polymerType===B.CHEM||t.polymerType===B.BLOB||!function(e,t,i){for(let n of i){if("backbone"!==n.kind||"numeric"!==n.r1.kind||"numeric"!==n.r2.kind)continue;let i=n.a1.id===e.id&&n.a2.id===t.id&&2===n.r1.r&&1===n.r2.r,o=n.a1.id===t.id&&n.a2.id===e.id&&2===n.r1.r&&1===n.r2.r;if(i||o)return!0}return!1}(t.backboneAtoms[i],t.backboneAtoms[i+1],e.bonds),i=!1;for(let n of e.chains){for(let e=0;e<n.backboneAtoms.length-1;e++)if(t(n,e)){i=!0;break}if(i)break}if(!i)return e;let n=new Set(e.chains.map(e=>e.id)),o=e=>{let t=1;for(;n.has(`${e}${t}`);)t+=1;let i=`${e}${t}`;return n.add(i),i},r=[];for(let i of e.chains){let e=[[]],n=e[0];for(let o=0;o<i.backboneAtoms.length;o++){let r=i.backboneAtoms[o];n.push(r),o<i.backboneAtoms.length-1&&t(i,o)&&(n=[],e.push(n))}for(let t=0;t<e.length;t++){let n={id:0===t?i.id:o(i.polymerType),polymerType:i.polymerType,atoms:e[t]};0===t&&void 0!==i.annotation&&(n.annotation=i.annotation),r.push(n)}}let s=new Map;for(let e of r)for(let t=0;t<e.atoms.length;t++){let i=e.atoms[t];s.set(i.id,{chainId:e.id,pos:t+1}),void 0!==i.branchAtom&&s.set(i.branchAtom.id,{chainId:e.id,pos:t+1})}let a=new Map;for(let t of e.atoms){let e=s.get(t.id);void 0===e||t.bio.chainId===e.chainId&&t.bio.positionInChain===e.pos?a.set(t.id,t):a.set(t.id,{...t,bio:{...t.bio,chainId:e.chainId,positionInChain:e.pos}})}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=a.get(t.id),i=a.get(t.branchAtom.id);void 0===e||void 0===i||(e.branchAtom=i)}let l=e.bonds.map(e=>{let t=a.get(e.a1.id)??e.a1,i=a.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}}),h=r.map(e=>{let t=e.atoms.map(e=>a.get(e.id)??e),i=new Set;for(let t of e.atoms)i.add(t.id),void 0!==t.branchAtom&&i.add(t.branchAtom.id);let n=[];for(let e of l)i.has(e.a1.id)&&i.has(e.a2.id)&&n.push(e);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>a.get(e.id)??e),bonds:l,chains:h,groups:e.groups,annotations:e.annotations}}(e);return new me(i,t??{}).emit()}var me=class{constructor(e,t){this.mol=e,this.options=t}emit(){return`${this.orderedChains().map(e=>this.emitPolymer(e)).join("|")}$${this.emitConnections()}$${this.emitGroupsAndBondRatios()}$${this.emitAnnotations()}${this.versionTrailer()}`}orderedChains(){if(!0!==this.options.canonicalize)return this.mol.chains;let e=this.mol.chains.slice();return e.sort((e,t)=>e.polymerType!==t.polymerType?e.polymerType<t.polymerType?-1:1:e.id<t.id?-1:e.id>t.id?1:0),e}emitPolymer(e){let t=this.emitChainBody(e),i=void 0!==e.annotation?`"${fe(e.annotation)}"`:"";return`${e.id}{${t}}${i}`}emitChainBody(e){switch(e.polymerType){case"PEPTIDE":return this.emitPeptideBody(e);case"RNA":return this.emitRnaBody(e);case"CHEM":return this.emitChemBody(e);case"BLOB":return this.emitBlobBody(e);default:return""}}emitPeptideBody(e){let t=this.bracketsForChain(e.id),i=[],n=0,o=0,r=null;for(;n<e.backboneAtoms.length;){let s=e.backboneAtoms[n],a=t.find(e=>e.startAtomId===s.id);void 0!==a&&null===r&&(i.push("("),r=a,o+=1),i.push(this.emitMonomerToken(s));let l=void 0!==s.tag?`"${fe(s.tag)}"`:"";i.push(l),null!==r&&r.endAtomId===s.id&&(i.push(`)${be(r.min,r.max)}`),r=null,o-=1),n+=1,n<e.backboneAtoms.length&&i.push(".")}return i.join("")}emitRnaBody(e){let t=this.bracketsForChain(e.id),i=[],n=0,o=!0,r=null,s=e=>{null!==r&&r.endAtomId===e&&(i.push(`)${be(r.min,r.max)}`),r=null)},a=e=>{let n=t.find(t=>t.startAtomId===e);void 0!==n&&null===r&&(i.push("("),r=n)};for(;n<e.backboneAtoms.length;){let t=e.backboneAtoms[n];if(o||i.push("."),o=!1,t.biotype!==E){if(t.biotype===v){a(t.id),i.push(this.emitMonomerToken(t)),void 0!==t.tag&&i.push(`"${fe(t.tag)}"`),void 0!==t.branchAtom&&(i.push("("),i.push(this.emitMonomerToken(t.branchAtom)),void 0!==t.branchAtom.tag&&i.push(`"${fe(t.branchAtom.tag)}"`),i.push(")"));let o=e.backboneAtoms[n+1];void 0!==o&&o.biotype===x?(i.push(this.emitMonomerToken(o)),void 0!==o.tag&&i.push(`"${fe(o.tag)}"`),s(o.id),n+=2):(s(t.id),n+=1);continue}a(t.id),i.push(this.emitMonomerToken(t)),void 0!==t.tag&&i.push(`"${fe(t.tag)}"`),s(t.id),n+=1}else a(t.id),i.push(this.emitMonomerToken(t)),void 0!==t.tag&&i.push(`"${fe(t.tag)}"`),s(t.id),n+=1}return i.join("")}emitChemBody(e){let t=e.backboneAtoms[0];if(void 0===t)return"";let i=void 0!==t.tag?`"${fe(t.tag)}"`:"";return`${this.emitMonomerToken(t)}${i}`}emitBlobBody(e){let t=e.backboneAtoms[0];if(void 0===t)return"";let i=void 0!==t.tag?`"${fe(t.tag)}"`:"";return`${this.emitMonomerToken(t)}${i}`}emitMonomerToken(e){let t;return t=void 0!==e.inlineSource?`[${e.inlineSource}]`:void 0===e.bio.ambiguity||"?"!==e.symbol&&!e.bio.ambiguity.startsWith("(")?e.symbol:e.bio.ambiguity,!0===this.options.includeHighlights&&e.selected?`<span style='background:#bbf;'>${t}</span>`:t}emitConnections(){let e=[];for(let t of this.crossPolymerBonds())e.push(this.emitConnection(t));return e.join("|")}*crossPolymerBonds(){let e=new Map;for(let t of this.mol.chains){let i=new Map;for(let e=0;e<t.backboneAtoms.length;e++)i.set(t.backboneAtoms[e].id,e);e.set(t.id,i)}for(let t of this.mol.bonds)if("backbone"!==t.kind)if("branch"!==t.kind)yield t;else{if(void 0!==t.a1.branchAtom&&t.a1.branchAtom.id===t.a2.id||void 0!==t.a2.branchAtom&&t.a2.branchAtom.id===t.a1.id)continue;yield t}else{if(t.a1.bio.chainId===t.a2.bio.chainId){let i=e.get(t.a1.bio.chainId);if(void 0!==i){let e=i.get(t.a1.id),n=i.get(t.a2.id);if(void 0!==e&&void 0!==n&&1===Math.abs(e-n))continue}}yield t}}emitConnection(e){let t=ge(e.r1,e.kind),i=ge(e.r2,e.kind),n=void 0!==e.tag?`"${fe(e.tag)}"`:"",o=String(this.connectionPosition(e.a1)),r=String(this.connectionPosition(e.a2));return`${e.a1.bio.chainId},${e.a2.bio.chainId},${o}:${t}-${r}:${i}${n}`}connectionPosition(e){return _(e,this.mol.chains.find(t=>t.id===e.bio.chainId))}emitGroupsAndBondRatios(){let e=[];for(let t of this.mol.groups)"bracket"!==t.kind&&e.push(this.emitGroup(t));for(let t of this.mol.bonds){if("cross-polymer"!==t.kind||void 0===t.ratio)continue;let i=void 0!==t.ratio.denominator?`${t.ratio.numerator}/${t.ratio.denominator}`:`${t.ratio.numerator}`;e.push(`${t.a1.bio.chainId}+${t.a2.bio.chainId}:${i}`)}return e.join("|")}emitGroup(e){let t="and"===e.kind?"+":",",i=e.members.map(e=>{return void 0===(t=e).ratio?t.target:`${t.target}:${t.ratio}`;var t}).join(t);return`${e.id}(${i})`}emitAnnotations(){let e=this.mol.annotations.perPolymer;if(0===e.size)return"";let t={};for(let[i,n]of e)t[i]=n;return JSON.stringify(t)}versionTrailer(){let e=this.options.version??"V2.0";if("none"===e)return"";if("preserve"===e){let e=this.mol.annotations.version;return""===e?"":`$${e}`}return`$${e}`}bracketsForChain(e){let t=[],i=new Map;for(let e of this.mol.atoms)i.set(e.id,e.bio.chainId);for(let n of this.mol.groups){if("bracket"!==n.kind)continue;let o=[];for(let e of n.members){let t=parseInt(e.target,10);Number.isFinite(t)&&o.push(t)}if(0===o.length)continue;let r=new Set;for(let e of o){let t=i.get(e);void 0!==t&&r.add(t)}if(!r.has(e)||r.size>1)continue;let s=n.repeat??{min:1,max:1};t.push({members:o,min:s.min,max:s.max,set:new Set(o),startAtomId:o[0],endAtomId:o[o.length-1]})}return t}};function fe(e){let t="";for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t+=34!==n?92!==n?10!==n?13!==n?9!==n?e.charAt(i):"\\t":"\\r":"\\n":"\\\\":'\\"'}return t}function be(e,t){return e===t?`'${e}'`:`'${e}-${t}'`}function ge(e,t){switch(e.kind){case"numeric":return`R${e.r}`;case"unspecified":default:return"?";case"wildcard":return"*";case"pair":return"pair";case"positional":return`${e.position}:R${e.r}`}}var Ae=class{constructor(e){this.chainIdMap=new Map,this.mol=e}run(){let e=this.mol.chains.slice().sort((e,t)=>e.polymerType!==t.polymerType?e.polymerType<t.polymerType?-1:1:ve(e.id,t.id)),t={},i=[];for(let n of e){let e=_e(n.polymerType);t[e]=(t[e]??0)+1;let o=`${e}${t[e]}`;this.chainIdMap.set(n.id,o),i.push(n)}let n=new Map;for(let e of this.mol.atoms){let t=this.chainIdMap.get(e.bio.chainId)??e.bio.chainId;n.set(e.id,{...e,bio:{...e.bio,chainId:t}})}for(let e of this.mol.atoms){if(void 0===e.branchAtom)continue;let t=n.get(e.id),i=n.get(e.branchAtom.id);void 0!==t&&void 0!==i&&(t.branchAtom=i)}let o=this.mol.bonds.map(e=>({...e,a1:n.get(e.a1.id)??e.a1,a2:n.get(e.a2.id)??e.a2})),r=new Map;for(let e of o)r.set(e.id,e);let s=i.map(e=>{let t=this.chainIdMap.get(e.id)??e.id,i=[];for(let t of e.backboneAtoms){let e=n.get(t.id);void 0!==e&&i.push(e)}let o=[];for(let t of e.bonds){let e=r.get(t.id);void 0!==e&&o.push(e)}return{id:t,polymerType:e.polymerType,backboneAtoms:i,bonds:o,...void 0!==e.annotation&&e.annotation.length>0?{annotation:e.annotation}:{}}}),a=new Map;for(let e of s)a.set(e.id,e);o.sort((e,t)=>{let i=ye(e.kind),n=ye(t.kind);if(i&&!n)return 1;if(!i&&n)return-1;if(!i&&!n)return e.id-t.id;let o=e.a1.bio.chainId,r=t.a1.bio.chainId;if(o!==r)return o<r?-1:1;let s=e.a2.bio.chainId,l=t.a2.bio.chainId;if(s!==l)return s<l?-1:1;let h=_(e.a1,a.get(e.a1.bio.chainId)),d=_(t.a1,a.get(t.a1.bio.chainId));return h!==d?h-d:_(e.a2,a.get(e.a2.bio.chainId))-_(t.a2,a.get(t.a2.bio.chainId))});let l=this.renumberGroups(this.mol.groups),h=this.rekeyAnnotations(this.mol.annotations);return{atoms:this.mol.atoms.map(e=>n.get(e.id)),bonds:o,chains:s,groups:l,annotations:h}}renumberGroups(e){let t=[],i=[];for(let n of e)"bracket"===n.kind?t.push(this.rekeyBracket(n)):i.push(n);i.sort((e,t)=>ve(e.id,t.id));let n={G:0};return i.map(e=>{n.G+=1;let t=`G${n.G}`;return{...e,id:t,members:e.members.map(e=>this.rekeyMember(e))}}).concat(t)}rekeyBracket(e){return e}rekeyMember(e){let t=this.chainIdMap.get(e.target);return void 0===t?e:void 0===e.ratio?{target:t}:{target:t,ratio:e.ratio}}rekeyAnnotations(e){let t=new Map;for(let[i,n]of e.perPolymer){let e=this.chainIdMap.get(i)??i;0!==Object.keys(n).length&&t.set(e,n)}return{perPolymer:t,version:e.version}}};function _e(e){switch(e){case"PEPTIDE":return"PEPTIDE";case"RNA":return"RNA";case"CHEM":return"CHEM";default:return"BLOB"}}function ye(e){return"cross-polymer"===e||"hbond"===e}function ve(e,t){let i=/^([A-Z]+)([0-9]+)$/.exec(e),n=/^([A-Z]+)([0-9]+)$/.exec(t);return null===i||null===n?e<t?-1:e>t?1:0:i[1]!==n[1]?i[1]<n[1]?-1:1:parseInt(i[2],10)-parseInt(n[2],10)}function we(e,t){let i=[...e.atoms],n=i[0];for(let e of i)for(let i of t.get(e)??[])if("hbond"===i.kind)throw new a("gap-at-complex-junction",`Gap atom ${e} participates in a hydrogen bond`,{atomId:e});if(e.boundary.length>2)throw new a("gap-at-complex-junction",`Gap atom ${n} sits at a junction of ${e.boundary.length} connections (max 2 allowed)`,{atomId:n,bondCount:e.boundary.length});if(2===e.boundary.length){let t=xe(e,e.boundary[0]),i=xe(e,e.boundary[1]);if(t.atom.id===i.atom.id)throw new a("gap-at-complex-junction",`Removing gap atom ${n} would bond monomer '${t.atom.symbol}' to itself`,{atomId:n})}}function xe(e,t){return e.atoms.has(t.a1.id)?{atom:t.a2,r:t.r2}:{atom:t.a1,r:t.r1}}function Ce(e,t){return"numeric"===e.kind&&e.r===t}var ke=[function(e,t){let i=[],n=new Set(e.chains.map(e=>e.id));for(let t of e.bonds)"cross-polymer"!==t.kind&&"hbond"!==t.kind||(n.has(t.a1.bio.chainId)||i.push({severity:"error",code:"unknown-chain-reference",message:`Connection references unknown chain '${t.a1.bio.chainId}'`,context:{chainId:t.a1.bio.chainId,bondId:t.id}}),n.has(t.a2.bio.chainId)||i.push({severity:"error",code:"unknown-chain-reference",message:`Connection references unknown chain '${t.a2.bio.chainId}'`,context:{chainId:t.a2.bio.chainId,bondId:t.id}}));for(let t of e.chains)for(let n of e.bonds){if("cross-polymer"!==n.kind&&"hbond"!==n.kind)continue;let e=0;for(let i of t.backboneAtoms)e+=void 0!==i.branchAtom?2:1;for(let o of[n.a1,n.a2]){if(o.bio.chainId!==t.id)continue;let n=_(o,t);(n<1||n>e)&&i.push({severity:"error",code:"position-out-of-range",message:`Position ${n} out of range for chain '${t.id}' (length ${e})`,context:{chainId:t.id,atomId:o.id,found:n}})}}let o=new Set;for(let t of e.groups)"bracket"!==t.kind&&o.add(t.id);for(let t of e.groups)if("bracket"!==t.kind)for(let e of t.members)n.has(e.target)||o.has(e.target)||i.push({severity:"error",code:"unknown-group-reference",message:`Group '${t.id}' references unknown id '${e.target}'`,context:{found:e.target}});let r=new Map;for(let t of e.groups){if("bracket"===t.kind)continue;let e=[];for(let i of t.members)o.has(i.target)&&e.push(i.target);r.set(t.id,e)}for(let e of r.keys()){let t=new Set,n=[e];for(;n.length>0;){let o=n.pop();if(t.has(o))continue;t.add(o);let s=r.get(o)??[];for(let o of s)o===e?i.push({severity:"error",code:"group-cycle",message:`Group cycle detected involving '${e}'`,context:{found:e}}):t.has(o)||n.push(o)}}return i},function(e,t){let i=[];if(null===t)return i;let n=new Map;for(let t of e.chains)n.set(t.id,t.polymerType);for(let t of e.atoms){let e=n.get(t.bio.chainId);if(void 0===e)continue;let o=t.monomer,r=o?.meta;null!==o&&!0!==r?.missing?!0!==r?.ambiguous&&void 0!==o.smiles&&o.smiles.length>0&&(0===o.rgroups.length?i.push({severity:"warning",code:"inline-smiles-without-r-groups",message:`Inline-SMILES monomer '${o.symbol}' has no R-groups`,context:{atomId:t.id,found:o.symbol}}):o.rgroups.length>4&&i.push({severity:"warning",code:"inline-smiles-too-many-rs",message:`Inline-SMILES monomer '${o.symbol}' has ${o.rgroups.length} R-groups (max 4 expected)`,context:{atomId:t.id,found:o.rgroups.length}})):i.push({severity:"warning",code:"unresolved-monomer",message:`Monomer '${t.symbol}' not found in library for ${e}`,context:{chainId:t.bio.chainId,atomId:t.id,found:t.symbol}})}for(let o of e.atoms){let e=n.get(o.bio.chainId);if(void 0!==e&&null===t.getMonomer(e,o.symbol))for(let n of t.getMonomerSymbolsByType(e))if(n!==o.symbol&&n.toLowerCase()===o.symbol.toLowerCase()){i.push({severity:"info",code:"case-mismatch",message:`Symbol '${o.symbol}' differs from library entry '${n}' only in case`,context:{atomId:o.id,found:o.symbol,expected:n}});break}}return i},function(e,t){let i=[],n=new Map;for(let t of e.bonds)for(let[e,o]of[[t.a1,t.r1],[t.a2,t.r2]]){if("numeric"!==o.kind)continue;let r=n.get(e.id)??new Set;r.has(o.r)&&i.push({severity:"error",code:"rgroup-already-bonded",message:`R-group R${o.r} on atom ${e.id} already bonded`,context:{atomId:e.id,bondId:t.id,found:o.r}}),r.add(o.r),n.set(e.id,r)}for(let t of e.bonds){for(let[e,n]of[[t.a1,t.r1],[t.a2,t.r2]]){if("numeric"!==n.kind||null===e.monomer)continue;let o=e.monomer.rs;(n.r<1||n.r>o)&&i.push({severity:"error",code:"rgroup-not-on-monomer",message:`R-group R${n.r} not defined on monomer '${e.symbol}' (rs=${o})`,context:{atomId:e.id,bondId:t.id,found:n.r,expected:`R1..R${o}`}})}"backbone"===t.kind&&"numeric"===t.r1.kind&&"numeric"===t.r2.kind&&(2===t.r1.r&&1===t.r2.r||i.push({severity:"warning",code:"backbone-rgroup-misaligned",message:`Backbone bond uses R${t.r1.r}->R${t.r2.r} (expected R2->R1)`,context:{bondId:t.id,found:`R${t.r1.r}->R${t.r2.r}`}})),"branch"===t.kind&&"numeric"===t.r1.kind&&3!==t.r1.r&&i.push({severity:"warning",code:"branch-rgroup-misaligned",message:`Branch bond uses R${t.r1.r} (expected R3 on parent)`,context:{bondId:t.id,found:`R${t.r1.r}`}})}for(let t of e.atoms){if(null===t.monomer)continue;let e=n.get(t.id)?.size??0;if(t.monomer.rs>e){let n=t.monomer.rs-e;n>0&&t.monomer.rs>0&&i.push({severity:"info",code:"unmatched-r-group",message:`Monomer '${t.symbol}' on atom ${t.id} has ${n} unused R-group(s); default cap applied`,context:{atomId:t.id,found:n}})}}return i},function(e,t){let i=[];for(let t of e.chains){if("CHEM"===t.polymerType&&t.backboneAtoms.length>1&&i.push({severity:"error",code:"chem-multiple-monomers",message:`CHEM polymer '${t.id}' has ${t.backboneAtoms.length} monomers (expected 1)`,context:{chainId:t.id,found:t.backboneAtoms.length}}),"BLOB"===t.polymerType)for(let e of t.backboneAtoms)void 0===e.bio.blobtype&&"Bead"!==e.symbol&&"Group"!==e.symbol&&i.push({severity:"error",code:"blob-non-blob-symbol",message:`BLOB '${t.id}' contains non-blob symbol '${e.symbol}'`,context:{chainId:t.id,atomId:e.id,found:e.symbol}});if("RNA"===t.polymerType){let e=!1;for(let n=0;n<t.backboneAtoms.length;n++){let o=t.backboneAtoms[n];o.biotype===w&&!e&&i.push({severity:"error",code:"rna-bare-base",message:`Bare base '${o.symbol}' without parent sugar in '${t.id}'`,context:{chainId:t.id,atomId:o.id}}),o.biotype===x&&(t.backboneAtoms.slice(0,n).some(e=>e.biotype===v)||i.push({severity:"warning",code:"rna-bare-linker",message:`Bare linker '${o.symbol}' before any sugar in '${t.id}'`,context:{chainId:t.id,atomId:o.id}})),e=o.biotype===v||o.biotype===x}}}return i},function(e,t){let i=[],n=new Map;for(let t of e.chains)n.set(t.id,t.polymerType);let o=new Map;for(let t of e.bonds){if("hbond"!==t.kind)continue;o.set(t.a1.id,(o.get(t.a1.id)??0)+1),o.set(t.a2.id,(o.get(t.a2.id)??0)+1);let e=n.get(t.a1.bio.chainId),r=n.get(t.a2.bio.chainId);("RNA"!==e||"RNA"!==r)&&i.push({severity:"error",code:"pair-non-rna",message:`Hydrogen-bond connects non-RNA chains (${e}/${r})`,context:{bondId:t.id}}),(t.a1.biotype!==w||t.a2.biotype!==w)&&i.push({severity:"warning",code:"pair-position-not-base",message:"Hydrogen-bond endpoints are not both bases",context:{bondId:t.id,found:`${t.a1.biotype}/${t.a2.biotype}`}}),Ee(t.a1.symbol,t.a2.symbol)||i.push({severity:"warning",code:"pair-non-canonical",message:`Non-canonical pair ${t.a1.symbol}-${t.a2.symbol}`,context:{bondId:t.id,found:`${t.a1.symbol}-${t.a2.symbol}`}})}for(let[e,t]of o)t>1&&i.push({severity:"warning",code:"pair-already-paired",message:`Base atom ${e} participates in ${t} pair bonds`,context:{atomId:e,found:t}});return i},function(e,t){let i=[];for(let t of e.atoms){let e=t.bio.ambiguity;if(void 0!==e)if("and"===t.bio.ambiguityKind){let n=Be(e,"+");for(let e of n)void 0!==e.ratio&&e.ratio<0&&i.push({severity:"error",code:"ratio-and-negative",message:`AND ratio for '${e.symbol}' is negative (${e.ratio})`,context:{atomId:t.id,found:e.ratio}})}else if("or"===t.bio.ambiguityKind){let n=Be(e,","),o=0,r=!1;for(let e of n)"number"==typeof e.ratio&&(o+=e.ratio,r=!0);r&&Math.abs(o-1)>.001&&Math.abs(o-100)>.5&&i.push({severity:"info",code:"ratio-doesnt-sum-to-1",message:`OR ratios sum to ${o} (expected 1.0 or 100)`,context:{atomId:t.id,found:o}})}}return i},function(e,t){let i=[],n=new Set(e.chains.map(e=>e.id));for(let t of e.annotations.perPolymer.keys())n.has(t)||i.push({severity:"warning",code:"annotation-unknown-polymer",message:`Annotation references unknown polymer '${t}'`,context:{found:t}});return i},function(e,t){let i=[];for(let t of e.chains)t.backboneAtoms.length>1e4&&i.push({severity:"info",code:"polymer-too-long",message:`Polymer '${t.id}' has ${t.backboneAtoms.length} atoms (> 10000); renderer may switch to rows layout`,context:{chainId:t.id,found:t.backboneAtoms.length}});let n=0;for(let t of e.bonds)("cross-polymer"===t.kind||"hbond"===t.kind)&&(n+=1);n>1e3&&i.push({severity:"info",code:"connection-count-high",message:`${n} cross-polymer/hbond connections (> 1000); rendering may be slow`,context:{found:n}});for(let t of e.groups)"bracket"===t.kind&&void 0!==t.repeat&&t.repeat.max>1e4&&i.push({severity:"warning",code:"bracket-repeat-too-large",message:`Bracket repeat upper bound ${t.repeat.max} > 10000`,context:{found:t.repeat.max}});return i}];function Ee(e,t){let i=e.toUpperCase(),n=t.toUpperCase();return new Set(["A:T","T:A","A:U","U:A","G:C","C:G"]).has(`${i}:${n}`)}function Be(e,t){let i=e.trim();i.startsWith("(")&&i.endsWith(")")&&(i=i.slice(1,-1));let n=i.split(t),o=[];for(let e of n){let t=e.trim();if(0===t.length)continue;let i=t.indexOf(":");if(i<0){o.push({symbol:t});continue}let n=t.slice(0,i),r=t.slice(i+1),s=parseFloat(r);Number.isFinite(s)?o.push({symbol:n,ratio:s}):o.push({symbol:n})}return o}function Se(e){let t=new Map;for(let i of e)t.set(i.polymerType,(t.get(i.polymerType)??0)+i.backbone.length);let i=e[0].polymerType,n=-1;for(let o of e){let e=t.get(o.polymerType);e>n&&(i=o.polymerType,n=e)}return i}function Me(e,t,i){let n=(e,t)=>"numeric"===e.kind&&e.r===t,o=[[e.a1,e.r1,e.a2,e.r2],[e.a2,e.r2,e.a1,e.r1]];for(let[e,r,s,a]of o){if(!n(r,2)||!n(a,1))continue;let o=i.get(e.id),l=i.get(s.id);if(void 0===o||void 0===l)continue;let h=t[o],d=t[l];if(h.backbone[h.backbone.length-1].id===e.id&&d.backbone[0].id===s.id)return{tail:o,head:l}}return null}function Te(e,t,i){let n=new Set,o=t;for(;void 0!==o&&!n.has(o);){if(o===i)return!0;n.add(o),o=e.get(o)}return!1}function Ie(e){switch(e){case B.PEPTIDE:return"PEPTIDE";case B.RNA:return"RNA";case B.CHEM:return"CHEM";case B.BLOB:default:return"BLOB"}}function Le(e,t,i,n){if(i.length<2)return!1;let o=i[0],r=i[i.length-1];for(let i of e.bonds){if("backbone"===i.kind||"branch"===i.kind)continue;let e=n.get(i.a1.id),s=n.get(i.a2.id);if(e!==t||s!==t||!(i.a1.id===r.id&&i.a2.id===o.id||i.a2.id===r.id&&i.a1.id===o.id))continue;let a=i.a1.id===o.id?i.r1:i.r2,l=i.a1.id===r.id?i.r1:i.r2,h="numeric"===a.kind&&1===a.r,d="numeric"===l.kind&&2===l.r;if(h&&d)return!0}return!1}var $e=44.800000000000004,Pe=42/$e,Re=42/$e,He=42/$e;function Ne(e,t){let i=t?.bondLength??28,n=t?.origin??{x:0,y:0},o=1.6*i,r=new Map;for(let t=0;t<e.backbone.length;t++){let i=e.backbone[t];r.set(i.id,{x:n.x+t*o,y:n.y})}return r}var De=Math.PI/180;function Fe(e,t){let i=e.backbone.length;if(i<=2){let i={};return void 0!==t?.bondLength&&(i.bondLength=t.bondLength),void 0!==t?.origin&&(i.origin=t.origin),Ne(e,i)}let n=t?.bondLength??28,o=t?.origin??{x:0,y:0},r=t?.startDegrees??-90,s=1.6*n/(2*Math.sin(Math.PI/i)),a=new Map;for(let t=0;t<i;t++){let n=e.backbone[t],l=(r+360*t/i)*De;a.set(n.id,{x:o.x+s*Math.cos(l),y:o.y+s*Math.sin(l)})}return a}function Oe(e,t){let i=new Map;for(let t=0;t<e.backbone.length;t++)i.set(e.backbone[t].id,t);let n=e.backbone.length-1,o=[];for(let e of t.bonds){if("backbone"===e.kind||"branch"===e.kind)continue;let t=i.get(e.a1.id),r=i.get(e.a2.id);if(void 0===t||void 0===r)continue;let s=Math.min(t,r),a=Math.max(t,r);a-s<2||0===s&&a===n&&ze(e)||o.push({lo:s,hi:a})}return o}function ze(e){let t=[e.r1,e.r2].filter(e=>"numeric"===e.kind).map(e=>e.r);return 2===t.length&&t.includes(1)&&t.includes(2)}function Ge(e,t,i){if(null===t)return Ne(e,i);let n=i?.bondLength??28,o=i?.origin??{x:0,y:0},r=1.6*n,s=Oe(e,t);if(0===s.length)return Ne(e,i);let a=s[0].lo,l=s[0].hi;for(let e of s)e.lo<a&&(a=e.lo),e.hi>l&&(l=e.hi);let h=e.backbone.slice(a,l+1),d=h.length,c=r/(2*Math.sin(Math.PI/d)),u={id:e.id,polymerType:e.polymerType,segments:e.segments,backbone:h,bases:new Array(d).fill(null),baseBonds:new Array(d).fill(null)},p=a,m={x:o.x+p*r+c,y:o.y},f=Fe(u,{bondLength:n,origin:m,startDegrees:180}),b=new Map;for(let t=0;t<a;t++){let i=e.backbone[t];b.set(i.id,{x:o.x+t*r,y:o.y})}for(let[e,t]of f)b.set(e,t);let g=h[d-1],A=f.get(g.id)??m,_=A.x-m.x,y=A.y-m.y,v=Math.hypot(_,y);v<1e-6&&(_=0,y=1,v=1);let w=_/v,x=y/v,C={x:A.x+w*r,y:A.y+x*r},k=Math.sign(A.x-m.x);if(0===k&&d>=2){let e=f.get(h[d-2].id);void 0!==e&&(k=Math.sign(A.x-e.x))}0===k&&(k=1);for(let t=l+1;t<e.backbone.length;t++){let i=e.backbone[t],n=t-(l+1);b.set(i.id,0===n?C:{x:C.x+k*r*n,y:C.y})}return b}function qe(e){let t=new Map,i=new Map;for(let n=0;n<e.backbone.length;n++){t.set(e.backbone[n].id,n);let o=e.bases[n];null!=o&&i.set(o.id,n)}return{sugarToIdx:t,baseToIdx:i}}function je(e,t,i){let n=t.get(e);if(void 0!==n)return n;let o=i.get(e);return void 0!==o?o:null}function Ye(e,t,i){let n="hbond"===e.kind,o="cross-polymer"===e.kind&&"object"==typeof e.r1&&null!==e.r1&&"pair"===e.r1.kind&&"object"==typeof e.r2&&null!==e.r2&&"pair"===e.r2.kind;if(!n&&!o)return null;let r=je(e.a1.id,t,i),s=je(e.a2.id,t,i);return null===r||null===s||r===s?null:{lo:Math.min(r,s),hi:Math.max(r,s)}}function Ve(e){let t=Math.hypot(e.x,e.y);return 0===t?{x:1,y:0}:{x:e.x/t,y:e.y/t}}function We(e,t,i){return{x:e.x+t*Math.cos(i),y:e.y+t*Math.sin(i)}}function Ue(e,t,i,n,o){let r=o.chain.bases[e];null!=r&&o.out.set(r.id,{x:t.x+n*i.x,y:t.y+n*i.y})}function Ke(e,t,i){let{chain:n,step:o,rail:r,baseInwardHang:s,out:a}=i,l=2*e.numPairs-1,h={x:t.normal.x,y:t.normal.y},d={x:-t.normal.x,y:-t.normal.y};for(let c=0;c<l;c++){let l=n.backbone[e.fromIdx+c],u=n.backbone[e.toIdx-c],p=c*o,m={x:t.origin.x+p*t.tangent.x,y:t.origin.y+p*t.tangent.y},f={x:t.origin.x+p*t.tangent.x+r*t.normal.x,y:t.origin.y+p*t.tangent.y+r*t.normal.y};a.set(l.id,m),a.set(u.id,f),Ue(e.fromIdx+c,m,h,s,i),Ue(e.toIdx-c,f,d,s,i)}let c=(l-1)*o;return{origin:{x:t.origin.x+c*t.tangent.x,y:t.origin.y+c*t.tangent.y},tangent:t.tangent,normal:t.normal}}function Xe(e,t,i,n){if(null===e.closingPair)return;let{step:o,rail:r,out:s}=i,a=0,l=0;for(let t of e.nodes)"unpaired"===t.kind?a+=t.to-t.from+1:l+=1;let h=function(e,t,i,n){let o=i+n+1;if(o<=0)return Math.max(e/2+1,t);let r=n+1,s=o*t,a=Math.max(s/(2*Math.PI),e/2+1);for(let t=0;t<64;t++){let t=e/(2*a),i=2*Math.asin(Math.min(.9999,Math.max(-.9999,t))),n=(2*Math.PI-r*i)*a-s,o=t,l=-e/(2*a*a)/Math.sqrt(Math.max(1e-12,1-o*o))*2,h=2*Math.PI-r*i-r*a*l;if(!Number.isFinite(h)||Math.abs(h)<1e-12)break;let d=n/h,c=a-d;if(!Number.isFinite(c)||c<e/2+.001){a=e/2+.001;break}if(a=c,Math.abs(d)<1e-9)break}return Math.max(a,e/2+.001)}(r,o,a,l),d=s.get(i.chain.backbone[e.closingPair[0]].id),c=s.get(i.chain.backbone[e.closingPair[1]].id),u=(d.x+c.x)/2,p=(d.y+c.y)/2,m=Math.sqrt(Math.max(0,h*h-r/2*(r/2))),f={x:u+m*t.tangent.x,y:p+m*t.tangent.y},b=Math.atan2(d.y-f.y,d.x-f.x),g=Math.atan2(c.y-f.y,c.x-f.x)-b;for(;g>Math.PI;)g-=2*Math.PI;for(;g<=-Math.PI;)g+=2*Math.PI;let A=g>0?-1:1,_=2*Math.asin(Math.min(.9999,Math.max(-.9999,r/(2*h)))),y=o/h,v=b;for(let t of e.nodes)if("unpaired"===t.kind)for(let e=t.from;e<=t.to;e++){v+=A*y;let t=We(f,h,v);s.set(i.chain.backbone[e].id,t),Ue(e,t,Ve({x:t.x-f.x,y:t.y-f.y}),i.step,i)}else{v+=A*y;let e=We(f,h,v);v+=A*_;let n=We(f,h,v);s.set(i.chain.backbone[t.fromIdx].id,e),s.set(i.chain.backbone[t.toIdx].id,n);let o=Ke(t,{origin:e,tangent:Ve({x:(e.x+n.x)/2-f.x,y:(e.y+n.y)/2-f.y}),normal:Ve({x:n.x-e.x,y:n.y-e.y})},i);Xe(t.child,o,i)}}function Qe(e,t,i){let n=1.6*(i?.bondLength??28);for(let i=0;i<e.backbone.length;i++){let o=e.bases[i];if(null==o||t.has(o.id))continue;let r=e.backbone[i],s=t.get(r.id);if(void 0===s)continue;let a=Ze(e,i,t);t.set(o.id,{x:s.x+n*a.x,y:s.y+n*a.y})}return t}function Ze(e,t,i){let n=e.backbone[t],o=i.get(n.id);if(void 0===o)return{x:0,y:1};let r=t>0?e.backbone[t-1]:void 0,s=t<e.backbone.length-1?e.backbone[t+1]:void 0,a=void 0!==r?i.get(r.id):void 0,l=void 0!==s?i.get(s.id):void 0,h=e=>{let t=e.x-o.x,i=e.y-o.y,n=Math.hypot(t,i);return n<1e-9?null:{x:t/n,y:i/n}},d=void 0!==a?h(a):null,c=void 0!==l?h(l):null;if(null!==d&&null!==c){let e=d.x+c.x,t=d.y+c.y,i=Math.hypot(e,t);if(i>.05)return{x:-e/i,y:-t/i}}let u=c??d;if(null===u)return{x:0,y:1};let p={x:u.y,y:-u.x},m={x:-u.y,y:u.x};return p.y>=m.y?p:m}function Je(e,t,i,n,o,r){let s=tt(t.atomIds,o);if(null===s)return e;let a=null;for(let e of i){let t=n.get(e);if(void 0===t)continue;let i=it(t.atomIds,o);null!==i&&(null===a||i>a)&&(a=i)}if(null===a)return e;let l=a+r;return s+e<l?l-s:e}function et(e,t){let i=new Set;for(let n of e){let e=t.get(n);if(void 0!==e)for(let t of e.atomIds)i.add(t)}return i}function tt(e,t){let i=null;for(let n of e){let e=t.get(n);void 0!==e&&(null===i||e.y<i)&&(i=e.y)}return i}function it(e,t){let i=null;for(let n of e){let e=t.get(n);void 0!==e&&(null===i||e.y>i)&&(i=e.y)}return i}function nt(e,t,i,n){for(let o of e){let e=t.get(o);void 0!==e&&t.set(o,{x:e.x+i,y:e.y+n})}}function ot(e,t){let i=0,n=0;for(let o of e){let e=t.get(o);void 0!==e&&(i+=e.x,n+=1)}if(0===n)return;let o=i/n;for(let i of e){let e=t.get(i);void 0!==e&&t.set(i,{x:2*o-e.x,y:e.y})}}function rt(e,t){let i=0,n=0;for(let o of e){let e=t.get(o);void 0!==e&&(i+=e.y,n+=1)}if(0===n)return;let o=i/n;for(let i of e){let e=t.get(i);void 0!==e&&t.set(i,{x:e.x,y:2*o-e.y})}}function st(e,t){let i=0,n=0,o=0;for(let r of e){let e=t.get(r);void 0!==e&&(i+=e.x,n+=e.y,o+=1)}return 0===o?{x:0,y:0}:{x:i/o,y:n/o}}function at(e,t,i,n,o,r){let s=st(i,r),a=n.x-s.x,l=n.y-s.y,h=Math.hypot(a,l);h<1e-6&&(a=0,l=1,h=1);let d=a/h,c=l/h,u=n.x+d*o,p=n.y+c*o;nt(e,r,u-t.x,p-t.y)}function lt(e,t,i,n,o){let r=Math.cos(n),s=Math.sin(n),a=new Map;for(let n of e){let e=o.get(n);if(void 0===e)continue;let l=e.x-t.x,h=e.y-t.y;a.set(n,{x:i.x+l*r-h*s,y:i.y+l*s+h*r})}return a}function ht(e,t,i,n,o,r){let s=.72*r,a=.45*r,l=i.map(e=>({a:e,end:t.get(e.movingAtomId)})).filter(e=>void 0!==e.end);for(let i of n){if(e.has(i))continue;let n=o.get(i);if(void 0!==n){for(let e of t.values())if(Math.hypot(e.x-n.x,e.y-n.y)<s)return!1;for(let e of l)if(i!==e.a.fixedAtomId&&ct(n,e.a.fixedPos,e.end)<a)return!1}}for(let[e,i]of t)for(let t of l)if(e!==t.a.movingAtomId&&ct(i,t.a.fixedPos,t.end)<a)return!1;return!0}function dt(e,t){let i=0;for(let n of e){let e=t.get(n.movingAtomId);void 0!==e&&(i+=Math.hypot(e.x-n.fixedPos.x,e.y-n.fixedPos.y))}return i}function ct(e,t,i){let n=i.x-t.x,o=i.y-t.y,r=n*n+o*o;if(0===r)return Math.hypot(e.x-t.x,e.y-t.y);let s=((e.x-t.x)*n+(e.y-t.y)*o)/r;return s=Math.max(0,Math.min(1,s)),Math.hypot(e.x-(t.x+s*n),e.y-(t.y+s*o))}function ut(e,t,i,n,o,r,s,a,l){let h=function(e,t,i,n){let o=[];for(let r of i.get(e.id)??[]){if("hbond"===r.kind)continue;let i=r.a1.id===e.id?r.a2:r.a1;if(i.id===e.id||i.id===t)continue;let s=n.get(i.id);void 0!==s&&o.push(s)}return o}(i,n.movingAtomId,r,l),d=function(e,t){let i=[],n=e=>{let t=Math.hypot(e.x,e.y);if(t<1e-6)return;let n={x:e.x/t,y:e.y/t};for(let e of i)if(Math.hypot(e.x-n.x,e.y-n.y)<.001)return;i.push(n)};if(t.length>1){let i=0,o=0;for(let e of t)i+=e.x,o+=e.y;i/=t.length,o/=t.length;let r={x:e.x-i,y:e.y-o};Math.hypot(r.x,r.y)>.05&&n(r)}if(t.length>0){let i={x:t[0].x-e.x,y:t[0].y-e.y},o={x:i.y,y:-i.x},r={x:-i.y,y:i.x};n(o.y>=r.y?o:r),n(o.y>=r.y?r:o)}n({x:0,y:1}),n({x:0,y:-1});for(let[e,t]of[[1,1],[-1,1],[1,-1],[-1,-1],[1,0],[-1,0]])n({x:e,y:t});return i}(n.fixedPos,h),c=function(e,t,i){if(e.size<2)return null;let n=st(e,i),o=n.x-t.x,r=n.y-t.y;if(Math.hypot(o,r)<.001){let n=0;for(let s of e){let e=i.get(s);if(void 0===e)continue;let a=Math.hypot(e.x-t.x,e.y-t.y);a>n&&(n=a,o=e.x-t.x,r=e.y-t.y)}}let s=Math.hypot(o,r);return s<1e-6?null:{x:o/s,y:r/s}}(e,t,l),u=[n.fixedPos];if(o.length>1){let e=0,t=0;for(let i of o)e+=i.fixedPos.x,t+=i.fixedPos.y;u.unshift({x:e/o.length,y:t/o.length})}let p=null===c?[0]:[0,1],m=function(e){let t=[...e];for(let e=0;e<24;e++){let i=e*Math.PI*2/24,n={x:Math.cos(i),y:Math.sin(i)};t.some(e=>Math.hypot(e.x-n.x,e.y-n.y)<.001)||t.push(n)}return t}(d);for(let i of[a,2*a,3*a,4*a]){let n=pt(i===a?d:m,i,u,p,c,e,t,o,s,l,a);if(null!==n)return ft(e,t,n.target,n.angle,l),!0}return!1}function pt(e,t,i,n,o,r,s,a,l,h,d){let c=null;for(let u of n)for(let n of i)for(let i of e){let e={x:n.x+i.x*t,y:n.y+i.y*t},p=0===u||null===o?0:Math.atan2(i.y,i.x)-Math.atan2(o.y,o.x),m=lt(r,s,e,p,h);if(!ht(r,m,a,l,h,d))continue;let f=dt(a,m);if(1===a.length)return{target:e,angle:p,cost:f};(null===c||f<c.cost)&&(c={target:e,angle:p,cost:f})}return c}function mt(e,t,i,n,o,r){let s=[t];for(let a of i.bonds)if("cross-polymer"===a.kind)for(let[i,l]of[[a.a1,a.a2],[a.a2,a.a1]]){if(!e.has(i.id)||e.has(l.id)||!n.has(l.id)||l.id===t.fixedAtomId&&i.id===t.movingAtomId||!r(l.id))continue;let a=o.get(l.id);void 0!==a&&s.push({fixedAtomId:l.id,fixedPos:a,movingAtomId:i.id})}return s}function ft(e,t,i,n,o){0!==n&&bt(e,o,t,n),nt(e,o,i.x-t.x,i.y-t.y)}function bt(e,t,i,n){let o=Math.cos(n),r=Math.sin(n);for(let n of e){let e=t.get(n);if(void 0===e)continue;let s=e.x-i.x,a=e.y-i.y;t.set(n,{x:i.x+s*o-a*r,y:i.y+s*r+a*o})}}function gt(e,t,i,n,o,r){let s=st(i,r),a=n.x-s.x,l=n.y-s.y,h=Math.hypot(a,l);h<1e-6&&(a=1,l=0,h=1);let d=a/h,c=l/h,u=st(e,r),p=Math.hypot(t.x-u.x,t.y-u.y),m=Math.atan2(t.y-u.y,t.x-u.x);bt(e,r,u,Math.atan2(-c,-d)-m);let f=n.x+d*(o+p),b=n.y+c*(o+p);nt(e,r,f-u.x,b-u.y)}var At=Object.freeze({monomersPerRow:20,adaptive:!0}),_t=Symbol.for("@datagrok-libraries/hwe.wrapSettings");function yt(){let e=globalThis,t=e[_t];return void 0===t&&(t={settings:At,version:0,listeners:new Set},e[_t]=t),t}function vt(e){if("number"!=typeof e||!Number.isFinite(e))throw new TypeError(`wrap settings: monomersPerRow must be a finite number, got ${String(e)}`);return Math.max(1,Math.round(e))}function wt(){return yt().settings}function xt(){return yt().version}function Ct(e){return function(e){let t=yt(),i=t.settings,n=Object.freeze({monomersPerRow:void 0!==e.monomersPerRow?vt(e.monomersPerRow):i.monomersPerRow,adaptive:void 0!==e.adaptive?!0===e.adaptive:i.adaptive});if(n.monomersPerRow===i.monomersPerRow&&n.adaptive===i.adaptive)return i;t.settings=n,t.version+=1;for(let e of[...t.listeners])e(n);return n}({monomersPerRow:vt(e)})}function kt(e){let{listeners:t}=yt();return t.add(e),()=>{t.delete(e)}}function Et(e,t){let i=t?.bondLength??28,n=t?.perRow,o=t?.monomersPerRow,r=t?.rowsThreshold,s=t?.circleThreshold??50,a=function(e){let t=[];for(let i of e.chains){let e=Ie(i.polymerType),n=i.backboneAtoms,o=[],r=[],s=[];for(let e of i.bonds)"backbone"===e.kind&&s.push(e);for(let e of n){if(e.biotype!==v){o.push(null),r.push(null);continue}let t=null,n=null;for(let o of i.bonds){if("branch"!==o.kind)continue;let i=o.a1.id===e.id?o.a2:o.a2.id===e.id?o.a1:null;if(null!==i&&i.biotype===w){t=i,n=o;break}}o.push(t),r.push(n)}t.push({id:i.id,polymerType:e,backbone:n,bases:o,backboneBonds:s,baseBonds:r,...void 0!==i.strandType?{strandType:i.strandType}:{}})}let i=function(e,t){let i=new Map;e.forEach((e,t)=>{for(let n of e.backbone)i.set(n.id,t)});let n=new Map,o=new Map;for(let r of t.bonds){if("cross-polymer"!==r.kind)continue;let t=Me(r,e,i);if(null===t)continue;let{tail:s,head:a}=t;s!==a&&(n.has(s)||o.has(a)||Te(n,a,s)||(n.set(s,a),o.set(a,s)))}let r=[],s=new Set;for(let t=0;t<e.length;t++){if(s.has(t)||o.has(t))continue;let i=[],a=t;for(;void 0!==a&&!s.has(a);)s.add(a),i.push(e[a]),a=n.get(a);r.push(i)}for(let t=0;t<e.length;t++)s.has(t)||(s.add(t),r.push([e[t]]));let a=new Map;e.forEach((e,t)=>a.set(e,t));let l=e=>Math.min(...e.map(e=>a.get(e)));return r.sort((e,t)=>l(e)-l(t))}(t,e),n=new Set,o=i.map(e=>{let t=e[0].id;for(let i=2;n.has(t);i++)t=`${e[0].id}#${i}`;return n.add(t),t}),r=new Map;return i.forEach((e,t)=>{for(let i of e)for(let e of i.backbone)r.set(e.id,o[t]),void 0!==e.branchAtom&&r.set(e.branchAtom.id,o[t])}),i.map((t,i)=>function(e,t,i,n){let o=[],r=[],s=[],a=[];for(let t of e)o.push(...t.backbone),r.push(...t.bases),s.push(...t.backboneBonds),a.push(...t.baseBonds);let l=e.find(e=>void 0!==e.strandType)?.strandType;return{id:t,polymerType:Se(e),segments:e.map(e=>e.id),backbone:o,bases:r,backboneBonds:s,baseBonds:a,isCyclic:Le(i,t,o,n),...void 0!==l?{strandType:l}:{}}}(t,o[i],e,r))}(e),l=new Map;for(let t of a){let a=Bt(t,e,i,n,o,r,s);for(let[e,t]of a)l.set(e,t);Qe(t,l,{bondLength:i})}let h=function(e,t,i,n){let o=1.6*(n?.bondLength??28),r=new Map,s=new Map;for(let t of e){let e=new Set;for(let i of t.backbone)e.add(i.id);for(let i of t.bases)null!==i&&e.add(i.id);s.set(t.id,{chain:t,atomIds:e});for(let i of e)r.set(i,t)}let a=new Map;for(let e of i.bonds)for(let t of[e.a1,e.a2]){let i=a.get(t.id);void 0===i?a.set(t.id,[e]):i.push(e)}let l=new Set;if(e.length>0){let t=e.find(e=>"ss"===e.strandType);l.add((t??e[0]).id)}let h=new Map;for(let t of e)h.set(t.id,t.id);let d=e=>{let t=e;for(;h.get(t)!==t;)t=h.get(t);let i=e;for(;h.get(i)!==t;){let e=h.get(i);h.set(i,t),i=e}return t},c=(e,t)=>{h.set(d(e),d(t))},u=e=>{let t=d(e),i=0;for(let e of h.keys())d(e)===t&&(i+=1);return i},p=e=>{let t=r.get(e),i=void 0===t?void 0:d(t.id);return e=>{let t=r.get(e);return void 0!==t&&void 0!==i&&d(t.id)===i}},m=e=>{let t=d(e),i=new Set;for(let[e,n]of s)if(d(e)===t)for(let e of n.atomIds)i.add(e);return i};for(let e of i.bonds){if("backbone"===e.kind||"branch"===e.kind)continue;let n=r.get(e.a1.id),h=r.get(e.a2.id);if(void 0===n||void 0===h||n.id===h.id)continue;if("hbond"===e.kind&&("as"===n.strandType&&"ss"===h.strandType?l.add(h.id):"as"===h.strandType&&"ss"===n.strandType?l.add(n.id):"as"!==n.strandType||l.has(h.id)?"as"===h.strandType&&!l.has(n.id)&&l.add(n.id):l.add(h.id)),"cross-polymer"===e.kind){let e=l.has(n.id)!==l.has(h.id)?l.has(n.id)?n:h:void 0,t=void 0===e?void 0:e===n?h:n;void 0!==e&&void 0!==t&&1===u(e.id)&&t.backbone.length>e.backbone.length&&(l.delete(e.id),l.add(t.id))}let f=h,b=e.a1,g=e.a2;if(l.has(h.id)&&!l.has(n.id))f=n,b=e.a2,g=e.a1;else if(l.has(n.id)||l.has(h.id)){if(l.has(n.id)&&l.has(h.id)){if(d(n.id)===d(h.id)||"cross-polymer"!==e.kind)continue;let r=m(n.id),u=m(h.id),f=r.size<=u.size,b=f?r:u,g=f?u:r,A=f?e.a1:e.a2,_=f?e.a2:e.a1,y=t.get(A.id),v=t.get(_.id);if(void 0!==y&&void 0!==v){let e={fixedAtomId:_.id,fixedPos:v,movingAtomId:A.id},n=et(l,s);ut(b,y,_,e,mt(b,e,i,n,t,p(_.id)),a,n,o,t)||at(b,y,g,v,o,t)}c(n.id,h.id);continue}}else{if(l.size>0){let e=it(et(l,s),t),i=s.get(n.id),r=tt(i.atomIds,t);if(null!==e&&null!==r){let n=e+o*Pe-r;n>0&&nt(i.atomIds,t,0,n)}}l.add(n.id),f=h,b=e.a1,g=e.a2}let A=t.get(b.id),_=t.get(g.id);if(void 0!==A&&void 0!==_){if("hbond"===e.kind){let e=s.get(f.id);ot(e.atomIds,t),rt(e.atomIds,t);let i=t.get(g.id),n=A.x-i.x,r=A.y+o*Re-i.y;r=Je(r,e,l,s,t,o*Re),nt(e.atomIds,t,n,r)}else{let e=s.get(f.id),r=et(l,s),d={fixedAtomId:b.id,fixedPos:A,movingAtomId:g.id},u=mt(e.atomIds,d,i,r,t,p(b.id));if(f.isCyclic&&f.backbone.length>=3&&1===u.length){let i=f.id===n.id?h:n,r=s.get(i.id);gt(e.atomIds,_,r.atomIds,A,o,t),l.add(f.id),c(n.id,h.id);continue}if(!ut(e.atomIds,_,b,d,u,a,r,o,t)){let i=A.x-_.x,n=A.y+o*He-_.y;n=Je(n,e,l,s,t,o*He),nt(e.atomIds,t,i,n)}}l.add(f.id),c(n.id,h.id)}}return l}(a,l,e,{bondLength:i});!function(e,t,i,n){let o=n?.bondLength??28,r=(n?.gap??Pe)*(1.6*o),s=0,a=!1;for(let n of e)if(i.has(n.id)){for(let e of n.backbone){let i=t.get(e.id);void 0!==i&&(a?i.y>s&&(s=i.y):(s=i.y,a=!0))}for(let e of n.bases){if(null===e)continue;let i=t.get(e.id);void 0!==i&&i.y>s&&(s=i.y)}}a||(s=0);let l=s+r;for(let n of e){if(i.has(n.id))continue;let e=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(let i of n.backbone){let n=t.get(i.id);void 0!==n&&(n.y<e&&(e=n.y),n.y>o&&(o=n.y))}for(let i of n.bases){if(null===i)continue;let n=t.get(i.id);void 0!==n&&(n.y<e&&(e=n.y),n.y>o&&(o=n.y))}if(e===Number.POSITIVE_INFINITY){i.add(n.id);continue}let s=l-e;for(let e of n.backbone){let i=t.get(e.id);void 0!==i&&t.set(e.id,{x:i.x,y:i.y+s})}for(let e of n.bases){if(null===e)continue;let i=t.get(e.id);void 0!==i&&t.set(e.id,{x:i.x,y:i.y+s})}l=o+s+r,i.add(n.id)}}(a,l,h,{bondLength:i});for(let t of e.atoms)l.has(t.id)||l.set(t.id,{x:0,y:0});return function(e,t){let i=new Map,n=[];for(let o of e.atoms){let e=t.get(o.id)??o.p,r={...o,p:{x:e.x,y:e.y}};i.set(o.id,r),n.push(r)}for(let t=0;t<n.length;t++){let o=e.atoms[t];if(void 0!==o.branchAtom){let e=i.get(o.branchAtom.id);void 0!==e&&(n[t]={...n[t],branchAtom:e}),i.set(n[t].id,n[t])}}let o=[];for(let t of e.bonds){let e=i.get(t.a1.id),n=i.get(t.a2.id);void 0===e||void 0===n||o.push({...t,a1:e,a2:n})}let r=[];for(let t of e.chains){let e=t.backboneAtoms.map(e=>i.get(e.id)??e),n=t.bonds.map(e=>{let t=i.get(e.a1.id)??e.a1,n=i.get(e.a2.id)??e.a2;return{...e,a1:t,a2:n}});r.push({id:t.id,polymerType:t.polymerType,backboneAtoms:e,bonds:n,...void 0!==t.annotation?{annotation:t.annotation}:{},...void 0!==t.strandType?{strandType:t.strandType}:{}})}return{atoms:n,bonds:o,chains:r,groups:e.groups,annotations:e.annotations}}(e,l)}function Bt(e,t,i,n,o,r,s){let a=e.backbone.length;if(0===a)return new Map;let l="RNA"===e.polymerType||e.bases.some(e=>null!==e),h=n??function(e,t,i){let n=yt().settings,o=void 0!==i?vt(i):n.monomersPerRow,r=e?2*o:o;return n.adaptive?function(e,t){let i=1,n=250;for(;t>n;)i*=2,n*=4;return e*i}(r,t):r}(l,a,o),d=r??h;if("RNA"===e.polymerType&&function(e,t){if("RNA"!==e.polymerType||0===e.backbone.length)return!1;let{sugarToIdx:i,baseToIdx:n}=qe(e);for(let e of t.bonds)if(null!==Ye(e,i,n))return!0;return!1}(e,t))return function(e,t,i){let n=i?.bondLength??28,o=1.6*n,r=o/2,s=n/28*42+2*r,a=i?.origin??{x:0,y:0},l=Ve(i?.rootDirection??{x:1,y:0}),h=function(e){return{x:-e.y,y:e.x}}(l),d=new Map;if(0===e.backbone.length)return d;let c=function(e,t){let i=e.backbone.length,n=new Int32Array(i).fill(-1);if(0===i)return n;let{sugarToIdx:o,baseToIdx:r}=qe(e),s=[];for(let e of t.bonds){let t=Ye(e,o,r);null!==t&&s.push([t.lo,t.hi])}s.sort((e,t)=>e[0]-t[0]||t[1]-e[1]);let a=[];for(let e of s){let[t,i]=e,o=!1;for(let[e,n]of a)if(!(i<e||t>n||t>e&&i<n||t<e&&i>n)){o=!0;break}o||-1!==n[t]||-1!==n[i]||(n[t]=i,n[i]=t,a.push(e))}return n}(e,t),u=function(e){return function t(i,n,o){let r=[],s=-1,a=i;for(;a<=n;){let i=e[a];if(i>a&&i<=n){-1!==s&&(r.push({kind:"unpaired",from:s,to:a-1}),s=-1);let n=1;for(;a+2*n<i-2*n&&e[a+2*n]===i-2*n&&-1===e[a+2*n-1]&&-1===e[i-2*n+1];)n+=1;let o=a+2*(n-1),l=i-2*(n-1),h=t(o+1,l-1,[o,l]);r.push({kind:"stem",fromIdx:a,toIdx:i,numPairs:n,child:h}),a=i+1}else-1===s&&(s=a),a+=1}return-1!==s&&r.push({kind:"unpaired",from:s,to:n}),{kind:"loop",nodes:r,closingPair:o}}(0,e.length-1,null)}(c);!function(e,t,i){let{step:n,rail:o,out:r}=i,s={x:t.origin.x,y:t.origin.y},a={x:t.tangent.x,y:t.tangent.y},l={x:-t.normal.x,y:-t.normal.y};for(let h of e.nodes)if("unpaired"===h.kind)for(let e=h.from;e<=h.to;e++){let o={x:s.x,y:s.y};r.set(i.chain.backbone[e].id,o),Ue(e,o,{x:t.normal.x,y:t.normal.y},i.step,i),s={x:s.x+n*a.x,y:s.y+n*a.y}}else{let e=Ke(h,{origin:{x:s.x,y:s.y},tangent:l,normal:a},i);Xe(h.child,e,i),s={x:s.x+(o+n)*a.x,y:s.y+(o+n)*a.y}}}(u,{origin:a,tangent:l,normal:h},{chain:e,step:o,rail:s,baseInwardHang:r,out:d});for(let t of e.backbone)d.has(t.id)||d.set(t.id,{x:a.x,y:a.y});return d}(e,t,{bondLength:i});if(e.isCyclic&&a<=s)return Fe(e,{bondLength:i});if(!e.isCyclic&&function(e,t){return null!==t&&Oe(e,t).length>0}(e,t))return Ge(e,t,{bondLength:i});if(a>d){let t=l?2:void 0;return function(e,t){let i=t?.bondLength??28,n=t?.origin??{x:0,y:0},o=Math.max(1,t?.perRow??10),r=1.6*i,s=(t?.rowSpacing??.9375)*r,a=new Map;for(let t=0;t<e.backbone.length;t++){let i=e.backbone[t],l=Math.floor(t/o),h=t%o,d=l%2==0?n.x+h*r:n.x+(o-1-h)*r,c=n.y+l*s;a.set(i.id,{x:d,y:c})}return a}(e,void 0!==t?{bondLength:i,perRow:h,rowSpacing:t}:{bondLength:i,perRow:h})}return e.isCyclic?Ne(e,{bondLength:i}):Ge(e,t,{bondLength:i})}function St(e,t){let i=Math.min(e.x,t.x),n=Math.min(e.y,t.y);return{x:i,y:n,width:Math.max(e.x+e.width,t.x+t.width)-i,height:Math.max(e.y+e.height,t.y+t.height)-n}}function Mt(e){if(Number.isInteger(e))return 0===e?"0":e.toString();if(!Number.isFinite(e)||Object.is(e,-0))return"0";let t=Math.round(1e3*e)/1e3;return 0===t?"0":t.toString()}function Tt(e){if(0===e.length)return"";let t=e[0],i=`M ${Mt(t.x)} ${Mt(t.y)}`;for(let t=1;t<e.length;t++){let n=e[t];i+=` L ${Mt(n.x)} ${Mt(n.y)}`}return i+=` L ${Mt(t.x)} ${Mt(t.y)} Z`,i}function It(e,t,i,n){let o=[],r=360/t;for(let s=0;s<t;s++){let t=(n+s*r)*Math.PI/180;o.push({x:e.x+i*Math.cos(t),y:e.y+i*Math.sin(t)})}return o}function Lt(e,t,i,n){let o=Math.abs(t)/2,r=Math.abs(i)/2,s=Math.max(0,Math.min(n,o,r)),a=e.x-o,l=e.y-r,h=a+2*o,d=l+2*r,c=`M ${Mt(a+s)} ${Mt(l)}`;return c+=` L ${Mt(h-s)} ${Mt(l)}`,c+=` A ${Mt(s)} ${Mt(s)} 0 0 1 ${Mt(h)} ${Mt(l+s)}`,c+=` L ${Mt(h)} ${Mt(d-s)}`,c+=` A ${Mt(s)} ${Mt(s)} 0 0 1 ${Mt(h-s)} ${Mt(d)}`,c+=` L ${Mt(a+s)} ${Mt(d)}`,c+=` A ${Mt(s)} ${Mt(s)} 0 0 1 ${Mt(a)} ${Mt(d-s)}`,c+=` L ${Mt(a)} ${Mt(l+s)}`,c+=` A ${Mt(s)} ${Mt(s)} 0 0 1 ${Mt(a+s)} ${Mt(l)}`,c+=" Z",c}function $t(e,t){return`M ${Mt(e.x)} ${Mt(e.y)} L ${Mt(t.x)} ${Mt(t.y)}`}function Pt(e,t,i=6){let n=t.x-e.x,o=t.y-e.y,r=Math.sqrt(n*n+o*o);if(0===r)return`M ${Mt(e.x)} ${Mt(e.y)} L ${Mt(e.x)} ${Mt(e.y)}`;let s=n/r,a=o/r,l=-a,h=s,d=(e.x+t.x)/2,c=(e.y+t.y)/2,u=i/2,p=Math.min(.6*i,.25*r),m=d-s*p,f=c-a*p,b=d+s*p,g=c+a*p;return`M ${Mt(m-l*u)} ${Mt(f-h*u)} L ${Mt(m+l*u)} ${Mt(f+h*u)} M ${Mt(b-l*u)} ${Mt(g-h*u)} L ${Mt(b+l*u)} ${Mt(g+h*u)}`}function Rt(e,t,i,n){switch(e){case"hexagon":{let e=i*Math.sqrt(3)/2,n=i;return{x:t.x-e,y:t.y-n,width:2*e,height:2*n}}case"diamond":return{x:t.x-i,y:t.y-i,width:2*i,height:2*i};case"pentagon":{let e=Math.cos(18*Math.PI/180)*i,n=-i,o=Math.sin(54*Math.PI/180)*i;return{x:t.x-e,y:t.y+n,width:2*e,height:o-n}}case"rounded-rect":case"blob":{let e=n??i,o=Math.abs(i)/2,r=Math.abs(e)/2;return{x:t.x-o,y:t.y-r,width:2*o,height:2*r}}case"ellipse":{let e=Math.abs(i),o=Math.abs(n??i);return{x:t.x-e,y:t.y-o,width:2*e,height:2*o}}case"circle":{let e=Math.abs(i);return{x:t.x-e,y:t.y-e,width:2*e,height:2*e}}}}At.monomersPerRow,At.monomersPerRow;var Ht='"Helvetica Neue", Helvetica, Arial, sans-serif';function Nt(e){return{aa:{size:.72*e,strokeWidth:5},sugar:{size:1.39*e,strokeWidth:5,cornerRadius:.3*e},base:{size:.88*e,strokeWidth:5},linker:{size:.63*e,strokeWidth:5},chem:{size:1.49*e,strokeWidth:5,cornerRadius:.5*e},blob:{size:1.64*e,strokeWidth:5,cornerRadius:.8*e},nucleotide:{size:.98*e,strokeWidth:5}}}var Dt={name:"light",background:"#ffffff",defaultStroke:"#202020",defaultFill:"#ffffff",selectionColor:"#FFC107",highlightColor:"#A4E2DC",errorColor:"#cc0000",fontSize:14,fontFamily:Ht,bondLength:28,textColor:"#000000",idColor:"#00aa00",annotationColor:"#FFA500",tagDotColor:"#dd2222",hbondColor:"#888888",nonCanonicalHbondColor:"#cc8800",crossPolymerBondColor:"#1f5fcd",colorTheme:Z,palette:{softenCanvas:!1},shapes:Nt(14)},Ft={name:"dark",background:"#1a1d23",defaultStroke:"#e0e0e0",defaultFill:"#2b2f37",selectionColor:"#FFD54F",highlightColor:"#7DD8CC",errorColor:"#ff5050",fontSize:14,fontFamily:Ht,bondLength:28,textColor:"#ffffff",idColor:"#33ff33",annotationColor:"#FFB84D",tagDotColor:"#ff6464",hbondColor:"#aaaaaa",nonCanonicalHbondColor:"#ffaa44",crossPolymerBondColor:"#6699ff",colorTheme:ee,palette:{softenCanvas:!1},shapes:Nt(14)};function Ot(e,t){switch(t){case y:return e.shapes.aa;case v:return e.shapes.sugar;case w:return e.shapes.base;case x:return e.shapes.linker;case C:return e.shapes.chem;case k:return e.shapes.blob;case E:return e.shapes.nucleotide}}function zt(e){switch(e){case y:return"hexagon";case v:return"rounded-rect";case w:return"diamond";case x:return"circle";case C:return"rounded-rect";case k:return"blob";case E:return"pentagon"}}function Gt(e,t,i=0){let n=Ot(t,e.biotype);switch(zt(e.biotype)){case"hexagon":{let t=0===i?0:i/Math.cos(Math.PI/6);return function(e,t,i=-30){return Tt(It(e,6,t,i))}(e.p,n.size+t)}case"diamond":{let t=0===i?0:i/Math.cos(Math.PI/4);return function(e,t){return Tt([{x:e.x,y:e.y-t},{x:e.x+t,y:e.y},{x:e.x,y:e.y+t},{x:e.x-t,y:e.y}])}(e.p,n.size+t)}case"pentagon":{let t=0===i?0:i/Math.cos(Math.PI/5);return function(e,t,i=-90){return Tt(It(e,5,t,i))}(e.p,n.size+t)}case"rounded-rect":return Lt(e.p,n.size+2*i,n.size+2*i,(n.cornerRadius??0)+i);case"blob":return function(e,t,i,n){return Lt(e,t,i,n)}(e.p,n.size+2*i,n.size+2*i,(n.cornerRadius??0)+i);case"circle":return function(e,t,i){let n=Math.abs(t),o=Math.abs(i);return`M ${Mt(e.x-n)} ${Mt(e.y)} A ${Mt(n)} ${Mt(o)} 0 1 0 ${Mt(e.x+n)} ${Mt(e.y)} A ${Mt(n)} ${Mt(o)} 0 1 0 ${Mt(e.x-n)} ${Mt(e.y)} Z`}(e.p,n.size+i,n.size+i)}}function qt(e,t){let i,n=Ot(t,e.biotype),o=zt(e.biotype);switch(o){case"hexagon":case"diamond":case"pentagon":case"circle":i=Rt(o,e.p,n.size);break;case"rounded-rect":case"blob":i=Rt(o,e.p,n.size,n.size)}let r=n.strokeWidth/2;return{x:i.x-r,y:i.y-r,width:i.width+2*r,height:i.height+2*r}}function jt(e,t){return Ot(t,e.biotype).size}function Yt(e,t){return Ot(t,e.biotype)}var Vt=/[&"'<>]/,Wt=/[&<>]/;function Ut(e){return Vt.test(e)?e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"):e}function Kt(e){return Wt.test(e)?e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):e}function Xt(e){if(Number.isInteger(e))return 0===e?"0":e.toString();if(!Number.isFinite(e)||Object.is(e,-0))return"0";let t=Math.round(1e3*e)/1e3;return 0===t?"0":t.toString()}function Qt(e,t,i){let n=`<${e}`;if(void 0!==t)for(let e in t){let i=t[e];if(void 0!==i&&!1!==i){if(!0===i){n+=` ${e}`;continue}n+="number"==typeof i?` ${e}="${Xt(i)}"`:` ${e}="${Ut(i)}"`}}return void 0===i?`${n}/>`:"string"==typeof i?`${n}>${i}</${e}>`:`${n}>${i.join("")}</${e}>`}var Zt=[["A","T"],["A","U"],["G","C"]];function Jt(e,t={}){let i=t.theme??Dt,n=t.width??400,o=t.height??100,r=t.padding??16,s=t.backColor??i.background,a=t.showIds??!1,l=t.showAnnotations??!0,h=t.fontSize??i.fontSize,d=t.selectedAtomIds??new Set,c=t.highlightedAtomIds??new Set;t.documentImpl??(typeof globalThis<"u"&&typeof globalThis.document<"u"&&globalThis.document);let u=t.fixedModelBbox??ei(e,i),p=function(e,t,i,n,o=1){let r=Math.max(0,t-2*n),s=Math.max(0,i-2*n),a=1;if(e.width>0||e.height>0){let t=e.width>0?r/e.width:Number.POSITIVE_INFINITY,i=e.height>0?s/e.height:Number.POSITIVE_INFINITY;a=Math.min(t,i,o),(!Number.isFinite(a)||a<=0)&&(a=1)}let l=e.width*a,h=e.height*a;return{x:(t-l)/2,y:(i-h)/2,width:l,height:h,scale:a}}(u,n,o,r,t.maxScale??1),m=p.x-u.x*p.scale,f=p.y-u.y*p.scale,b=ti(e,i,c),g=ii(e,i,d),A=function(e,t){let i=[];for(let n of e.bonds)i.push(ni(n,t));return Qt("g",{class:"hw-layer hw-bonds"},i.join(""))}(e,i),_=function(e,t,i,n,o=t.bondLength){let r=[];for(let s of e.atoms)s.hidden||r.push(ri(s,t,i,n,o));return Qt("g",{class:"hw-layer hw-atoms"},r.join(""))}(e,i,h,a,t.bondLength??i.bondLength),y=l?function(e,t,i){let n=[];for(let o of e.bonds){if(void 0===o.ratio)continue;let e=(o.a1.p.x+o.a2.p.x)/2,r=(o.a1.p.y+o.a2.p.y)/2,s=void 0!==o.ratio.denominator?`${o.ratio.numerator}/${o.ratio.denominator}`:`${o.ratio.numerator}`;n.push(Qt("text",{class:"hw-annotation hw-annotation--bond-ratio",x:e,y:r-.4*i,"text-anchor":"middle","font-size":.7*i,"font-family":t.fontFamily,fill:t.annotationColor},Kt(s)))}for(let o of e.atoms){let e=o.bio.annotation;if(void 0===e||""===e)continue;let r=Yt(o,t);n.push(Qt("text",{class:"hw-annotation hw-annotation--atom",x:o.p.x+r.size+2,y:o.p.y-r.size,"font-size":.7*i,"font-family":t.fontFamily,fill:t.annotationColor},Kt(e)))}for(let o of e.chains){if(void 0===o.annotation||""===o.annotation)continue;let e=o.backboneAtoms[0];void 0!==e&&n.push(Qt("text",{class:"hw-annotation hw-annotation--chain",x:e.p.x,y:e.p.y-1.4*t.fontSize,"font-size":.8*i,"font-family":t.fontFamily,fill:t.annotationColor},Kt(o.annotation)))}for(let o of e.chains){if("RNA"!==o.polymerType)continue;let e=o.backboneAtoms;if(e.length<2)continue;let r=e[0],s=e[e.length-1],a=e.length>=2?e[1]:null,l=e.length>=2?e[e.length-2]:null,h=1.4*t.fontSize,d=si(r.p,a?.p??null,h),c=si(s.p,l?.p??null,h),u=void 0!==o.strandType?`5'${o.strandType}`:"5'",p=void 0!==o.strandType?`3'${o.strandType}`:"3'";n.push(Qt("text",{class:"hw-annotation hw-annotation--prime hw-annotation--prime-5","data-testid":`prime-5-${o.id}`,x:d.x,y:d.y,"text-anchor":"middle","dominant-baseline":"central","font-size":.85*i,"font-family":t.fontFamily,"font-weight":"bold",fill:t.annotationColor},Kt(u))),n.push(Qt("text",{class:"hw-annotation hw-annotation--prime hw-annotation--prime-3","data-testid":`prime-3-${o.id}`,x:c.x,y:c.y,"text-anchor":"middle","dominant-baseline":"central","font-size":.85*i,"font-family":t.fontFamily,"font-weight":"bold",fill:t.annotationColor},Kt(p)))}return Qt("g",{class:"hw-layer hw-annotations"},n.join(""))}(e,i,h):"",v=Qt("g",{class:"hw-content",transform:`translate(${Xt(m)} ${Xt(f)}) scale(${Xt(p.scale)})`},[A,_,y,b,g].join("")),w=Qt("defs",void 0,"<style>.hw-atom{transition:stroke-width 120ms,filter 120ms;}.hw-atom:focus{outline:none;}.hw-atom__shape{shape-rendering:geometricPrecision;}.hw-bond__stroke{stroke-linecap:round;}</style>"),x=Qt("rect",{class:"hw-bg",x:0,y:0,width:n,height:o,fill:s});return{svg:Qt("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:`0 0 ${Xt(n)} ${Xt(o)}`,width:n,height:o,"data-hw-theme":i.name},[w,x,v].join("")),bbox:{x:u.x,y:u.y,width:u.width,height:u.height},drawBox:{x:p.x,y:p.y,width:p.width,height:p.height,scale:p.scale}}}function ei(e,t=Dt){if(0===e.atoms.length)return{x:0,y:0,width:0,height:0};let i=qt(e.atoms[0],t);for(let n=1;n<e.atoms.length;n++)i=St(i,qt(e.atoms[n],t));return i}function ti(e,t,i){if(0===i.size)return Qt("g",{class:"hw-layer hw-highlights"},"");let n=[];for(let o of e.atoms){if(!i.has(o.id))continue;let e=Gt(o,t,(Yt(o,t).strokeWidth+3)/2);n.push(Qt("path",{d:e,class:"hw-highlight",fill:"none",stroke:t.highlightColor,"stroke-width":3,"stroke-linejoin":"round","stroke-linecap":"round","data-symbol":o.symbol,"data-ring-atom-id":o.id,"data-testid":`highlight-ring-${o.id}`}))}return Qt("g",{class:"hw-layer hw-highlights"},n.join(""))}function ii(e,t,i){if(0===i.size)return Qt("g",{class:"hw-layer hw-selections"},"");let n=[];for(let o of e.atoms){if(!i.has(o.id))continue;let e=Gt(o,t,(Yt(o,t).strokeWidth+3)/2);n.push(Qt("path",{d:e,class:"hw-selection",fill:"none",stroke:t.selectionColor,"stroke-width":3,"stroke-linejoin":"round","stroke-linecap":"round","data-symbol":o.symbol,"data-ring-atom-id":o.id,"data-testid":`selection-ring-${o.id}`}))}return Qt("g",{class:"hw-layer hw-selections"},n.join(""))}function ni(e,t){let i=e.a1.p,n=e.a2.p,o=function(e,t){switch(e.kind){case"backbone":case"branch":case"group":return t.defaultStroke;case"cross-polymer":return t.crossPolymerBondColor;case"hbond":return function(e){if(e.a1.biotype!==w||e.a2.biotype!==w)return!1;let t=oi(e.a1),i=oi(e.a2);for(let[e,n]of Zt)if(t===e&&i===n||t===n&&i===e)return!0;return!1}(e)?t.hbondColor:t.nonCanonicalHbondColor}}(e,t),r=function(e){if("hbond"===e.kind)return"4 3"}(e),s={d:$t(i,n),class:"hw-bond__stroke",fill:"none",stroke:o,"stroke-width":1.125};void 0!==r&&(s["stroke-dasharray"]=r);let a=[Qt("path",s)];return"hbond"===e.kind&&a.push(Qt("path",{d:Pt(i,n,.6*t.fontSize),class:"hw-bond__hash",fill:"none",stroke:o,"stroke-width":1.125})),Qt("g",{class:`hw-bond hw-bond--${e.kind}`,"data-bond-id":e.id,"data-kind":e.kind,"data-testid":`canvas-bond-${e.id}`},a.join(""))}function oi(e){let t=e.monomer?.naturalAnalog,i=void 0!==t&&""!==t?t:e.symbol;return 0===i.length?"":i.charAt(0).toUpperCase()}function ri(e,t,i,n,o=t.bondLength){let r=Yt(e,t),s=Gt(e,t),a=te(e.monomer,e.biotype,t.colorTheme),l=a.background,h=a.text,d="*"===e.symbol?"3 3":void 0,c={d:s,class:"hw-atom__shape",fill:l,stroke:l,"stroke-width":r.strokeWidth,"stroke-linejoin":"round","stroke-linecap":"round"};void 0!==d&&(c["stroke-dasharray"]=d);let u=[Qt("path",c)],p=e.monomer?.symbol??e.symbol;if(""!==p){let n=i*(p.length<=1?1:Math.min(1,2/p.length));u.push(Qt("text",{class:"hw-atom__label",x:e.p.x,y:e.p.y+.35*n,"text-anchor":"middle","font-size":n,"font-family":t.fontFamily,fill:h},Kt(p)))}if(void 0!==e.bio.ambiguity&&""!==e.bio.ambiguity&&u.push(Qt("text",{class:"hw-atom__ambiguity",x:e.p.x,y:e.p.y+r.size+.7*i,"text-anchor":"middle","font-size":.7*i,"font-family":t.fontFamily,fill:h},Kt(e.bio.ambiguity))),n){let n=.525*o;u.push(Qt("text",{class:"hw-atom__id",x:e.p.x-n,y:e.p.y-n,"font-size":.8*i,"font-family":t.fontFamily,fill:t.idColor},Kt(String(e.bio.continuousId))))}void 0!==e.tag&&""!==e.tag&&u.push(Qt("circle",{class:"hw-atom__tag-dot",cx:e.p.x+.7*r.size,cy:e.p.y-.7*r.size,r:Math.max(2,.18*i),fill:t.tagDotColor}));let m=function(e){let t=""===e.symbol?"?":e.symbol,i=""===e.bio.chainId?"unknown chain":e.bio.chainId;return`${t} at position ${e.bio.positionInChain} of ${i}`}(e);return Qt("g",{class:"hw-atom","data-atom-id":e.id,"data-symbol":e.symbol,"data-chain-id":e.bio.chainId,"data-biotype":e.biotype,"data-testid":`canvas-atom-${e.id}`,tabindex:0,role:"button","aria-label":m},u.join(""))}function si(e,t,i){if(null===t)return{x:e.x-i,y:e.y};let n=e.x-t.x,o=e.y-t.y,r=Math.hypot(n,o);return 0===r?{x:e.x-i,y:e.y}:{x:e.x+i*(n/r),y:e.y+i*(o/r)}}function ai(e,t,i,n={}){let o=n.theme??Dt,r=n.padding??16,s=function(e,t){if(0===e.atoms.length)return{x:0,y:0,width:0,height:0};let i=qt(e.atoms[0],t);for(let n=1;n<e.atoms.length;n++)i=St(i,qt(e.atoms[n],t));return i}(t,o),a=function(e,t,i,n,o=1){let r=Math.max(0,t-2*n),s=Math.max(0,i-2*n),a=1;if(e.width>0||e.height>0){let t=e.width>0?r/e.width:Number.POSITIVE_INFINITY,i=e.height>0?s/e.height:Number.POSITIVE_INFINITY;a=Math.min(t,i,o),(!Number.isFinite(a)||a<=0)&&(a=1)}let l=e.width*a,h=e.height*a;return{x:(t-l)/2,y:(i-h)/2,width:l,height:h,scale:a}}(s,i.width,i.height,r,n.maxScale??1),l=i.x+a.x,h=i.y+a.y;return e.save(),e.beginPath(),e.rect(i.x,i.y,i.width,i.height),e.clip(),void 0!==n.backColor&&(e.fillStyle=n.backColor,e.fillRect(i.x,i.y,i.width,i.height)),e.translate(l,h),e.scale(a.scale,a.scale),e.translate(-s.x,-s.y),function(e,t,i){for(let n of t.bonds)e.save(),e.strokeStyle=ci(n,i),e.lineWidth=ui(),"hbond"===n.kind?e.setLineDash([4,3]):e.setLineDash([]),e.beginPath(),e.moveTo(n.a1.p.x,n.a1.p.y),e.lineTo(n.a2.p.x,n.a2.p.y),e.stroke(),e.restore()}(e,t,o),function(e,t,i,n,o=!1,r=i.bondLength){for(let s of t.atoms){if(s.hidden)continue;let t=Yt(s,i),a=te(s.monomer,s.biotype,i.colorTheme);e.save(),e.fillStyle=a.background,e.strokeStyle=a.background,e.lineWidth=t.strokeWidth,e.lineJoin="round",e.lineCap="round","*"===s.symbol?e.setLineDash([3,3]):e.setLineDash([]),hi(e,s,t.size,t.cornerRadius??0),e.fill(),e.stroke(),e.restore();let l=s.monomer?.symbol??s.symbol;if(""!==l){let t=n*(l.length<=1?1:Math.min(1,2/l.length));e.save(),e.fillStyle=a.text,e.font=`${t}px ${i.fontFamily}`,e.textAlign="center",e.textBaseline="middle",e.fillText(l,s.p.x,s.p.y),e.restore()}if(o){let t=.525*r;e.save(),e.fillStyle=i.idColor,e.font=`${.8*n}px ${i.fontFamily}`,e.textAlign="right",e.textBaseline="bottom",e.fillText(String(s.bio.continuousId),s.p.x-t,s.p.y-t),e.restore()}}}(e,t,o,n.fontSize??o.fontSize,n.showIds??!1,n.bondLength??o.bondLength),!1!==n.showAnnotations&&function(e,t,i,n){e.save(),e.fillStyle=i.annotationColor,e.font=`${.7*n}px ${i.fontFamily}`,e.textAlign="left",e.textBaseline="alphabetic";for(let n of t.atoms){let t=n.bio.annotation;if(void 0===t||""===t)continue;let o=Yt(n,i);e.fillText(t,n.p.x+o.size+2,n.p.y-o.size)}e.font=`${.8*n}px ${i.fontFamily}`;for(let n of t.chains){if(void 0===n.annotation||""===n.annotation)continue;let t=n.backboneAtoms[0];void 0!==t&&e.fillText(n.annotation,t.p.x,t.p.y-1.4*i.fontSize)}e.font=`bold ${.85*n}px ${i.fontFamily}`,e.textAlign="center",e.textBaseline="middle";let o=1.4*i.fontSize;for(let i of t.chains){if("RNA"!==i.polymerType)continue;let t=i.backboneAtoms;if(t.length<2)continue;let n=t[0],r=t[t.length-1],s=t.length>=2?t[1]:null,a=t.length>=2?t[t.length-2]:null,l=li(n.p,s?.p??null,o),h=li(r.p,a?.p??null,o),d=void 0!==i.strandType?`5'${i.strandType}`:"5'",c=void 0!==i.strandType?`3'${i.strandType}`:"3'";e.fillText(d,l.x,l.y),e.fillText(c,h.x,h.y)}e.restore()}(e,t,o,n.fontSize??o.fontSize),e.restore(),{bbox:{x:s.x,y:s.y,width:s.width,height:s.height},drawBox:{x:l,y:h,width:a.width,height:a.height}}}function li(e,t,i){if(null===t)return{x:e.x-i,y:e.y};let n=e.x-t.x,o=e.y-t.y,r=Math.hypot(n,o);return 0===r?{x:e.x-i,y:e.y}:{x:e.x+i*(n/r),y:e.y+i*(o/r)}}function hi(e,t,i,n){let o=t.p,r=zt(t.biotype);switch(e.beginPath(),r){case"hexagon":di(e,o,6,i,-30);break;case"diamond":e.moveTo(o.x,o.y-i),e.lineTo(o.x+i,o.y),e.lineTo(o.x,o.y+i),e.lineTo(o.x-i,o.y),e.closePath();break;case"pentagon":di(e,o,5,i,-90);break;case"rounded-rect":case"blob":{let t=i/2,r=Math.max(0,Math.min(n,t)),s=o.x-t,a=o.y-t,l=2*t,h=2*t;e.moveTo(s+r,a),e.lineTo(s+l-r,a),e.quadraticCurveTo(s+l,a,s+l,a+r),e.lineTo(s+l,a+h-r),e.quadraticCurveTo(s+l,a+h,s+l-r,a+h),e.lineTo(s+r,a+h),e.quadraticCurveTo(s,a+h,s,a+h-r),e.lineTo(s,a+r),e.quadraticCurveTo(s,a,s+r,a),e.closePath();break}case"circle":e.ellipse(o.x,o.y,i,i,0,0,2*Math.PI)}}function di(e,t,i,n,o){let r=360/i;for(let s=0;s<i;s++){let i=(o+s*r)*Math.PI/180,a=t.x+n*Math.cos(i),l=t.y+n*Math.sin(i);0===s?e.moveTo(a,l):e.lineTo(a,l)}e.closePath()}function ci(e,t){switch(e.kind){case"backbone":case"branch":case"group":return t.defaultStroke;case"cross-polymer":return t.crossPolymerBondColor;case"hbond":return function(e){if(e.a1.biotype!==w||e.a2.biotype!==w)return!1;let t=mi(e.a1),i=mi(e.a2);for(let[e,n]of pi)if(t===e&&i===n||t===n&&i===e)return!0;return!1}(e)?t.hbondColor:t.nonCanonicalHbondColor}}function ui(e){return 1.125}var pi=[["A","T"],["A","U"],["G","C"]];function mi(e){let t=e.monomer?.naturalAnalog,i=void 0!==t&&""!==t?t:e.symbol;return 0===i.length?"":i.charAt(0).toUpperCase()}function fi(e){let t=new Map,i=new Map;for(let t of e.bonds){let e=t.a1.id,n=t.a2.id,o=i.get(e);void 0===o&&(o=[],i.set(e,o)),o.push(t);let r=i.get(n);void 0===r&&(r=[],i.set(n,r)),r.push(t)}for(let n of e.atoms)Ai(t,n,i.get(n.id)??[]);for(let n of e.groups){if("bracket"!==n.kind)continue;let o=n.repeat?.min??1;if(1===o)continue;let r=new Set(n.members.map(e=>e.target)),s=new Map;for(let t of e.atoms){if(!r.has(t.bio.chainId))continue;let e=new Map;Ai(e,t,i.get(t.id)??[]);for(let[t,i]of e)s.set(t,(s.get(t)??0)+i*(o-1))}for(let[e,i]of s)t.set(e,(t.get(e)??0)+i)}for(let[e,i]of[...t])0===i&&t.delete(e);let n=function(e){let t=0;for(let[i,n]of e){let e=bi[i];void 0!==e&&(t+=e*n)}return Math.round(1e3*t)/1e3}(t);return{elements:t,mw:n}}var bi={H:1.008,C:12.011,N:14.007,O:15.999,F:18.998,Na:22.99,Mg:24.305,P:30.974,S:32.06,Cl:35.45,K:39.098,Ca:40.078,Br:79.904,I:126.904,Fe:55.845,Zn:65.38,Cu:63.546},gi={C:4,N:3,O:2,S:2,P:3,F:1,Cl:1,Br:1,I:1,H:1};function Ai(e,t,i){if(null===t.monomer)return;let n=function(e){let t=vi.get(e);if(void 0!==t)return t;let i=function(e){let t=new Map;if(void 0===e.molfile||""===e.molfile)return{elements:t};let i=function(e){let t=e.split(/\r\n|\n|\r/);if(t.length<5)return null;let i=t[3];if(void 0===i||i.length<6)return null;let n=parseInt(i.slice(0,3),10),o=parseInt(i.slice(3,6),10);if(!Number.isFinite(n)||!Number.isFinite(o)||t.length<4+n+o)return null;let r=[];for(let e=0;e<n;e++){let i=t[4+e];if(void 0===i)return null;let n=i.slice(31,34).trim();r.push(n)}let s=new Array(n).fill(0);for(let e=0;e<o;e++){let i=t[4+n+e];if(void 0===i)return null;let o=parseInt(i.slice(0,3),10),r=parseInt(i.slice(3,6),10),a=parseInt(i.slice(6,9),10);if(!Number.isFinite(o)||!Number.isFinite(r)||!Number.isFinite(a))continue;let l=4===a?1:a;o>=1&&o<=n&&(s[o-1]=(s[o-1]??0)+l),r>=1&&r<=n&&(s[r-1]=(s[r-1]??0)+l)}return{atoms:r,bondOrders:s}}(e.molfile);if(null===i)return{elements:t};let{atoms:n,bondOrders:o}=i;for(let e=0;e<n.length;e++){let i=n[e];if("R"===i||"R#"===i||"*"===i)continue;t.set(i,(t.get(i)??0)+1);let r=gi[i];if(void 0===r)continue;let s=r-(o[e]??0);s>0&&t.set("H",(t.get("H")??0)+s)}for(let i of e.rgroups){let e=i.capGroupName;if(void 0===e)continue;let n=yi(e);for(let[e,i]of n)t.set(e,(t.get(e)??0)+i)}return{elements:t}}(e);return vi.set(e,i),i}(t.monomer);for(let[t,i]of n.elements)e.set(t,(e.get(t)??0)+i);for(let n of i){if("hbond"===n.kind||"group"===n.kind)continue;let i=n.a1.id===t.id?n.r1:n.r2,o=_i(t.monomer,i);if(void 0===o)continue;let r=yi(o);for(let[t,i]of r)e.set(t,(e.get(t)??0)-i)}}function _i(e,t){if("numeric"!==t.kind&&"positional"!==t.kind)return;let i=(t.kind,t.r);for(let t of e.rgroups){let e=/^R([1-9][0-9]*)$/.exec(t.label);if(null!==e&&parseInt(e[1],10)===i)return t.capGroupName}}function yi(e){let t=new Map;switch(e){case"H":t.set("H",1);break;case"OH":t.set("H",1),t.set("O",1)}return t}var vi=new WeakMap;function wi(e){return fi(e).mw}var xi={AA:13.65,AC:10.67,AG:12.79,AU:12.14,CA:10.67,CC:7.52,CG:9.39,CU:8.37,GA:12.79,GC:9.39,GG:11.77,GU:10.21,UA:12.14,UC:8.37,UG:10.21,UU:8.99},Ci={A:15.4,C:7.4,G:11.7,U:10,T:8.8};function ki(e){let t=0;for(let i of e.chains)"PEPTIDE"===i.polymerType?t+=Ei(i.backboneAtoms):"RNA"===i.polymerType&&(t+=Bi(i.backboneAtoms));return Math.round(1e4*t)/1e4}function Ei(e){let t=0,i=0,n=0;for(let o of e){let e=Si(o);"W"===e?t++:"Y"===e?i++:"C"===e&&n++}return 5.5*t+1.49*i+.0625*n}function Bi(e){let t=[];for(let i of e)if(void 0!==i.branchAtom&&i.branchAtom.biotype===w){let e=Si(i.branchAtom);"T"===e&&(e="U"),""!==e&&t.push(e)}if(0===t.length)return 0;if(1===t.length){let e=t[0];return Ci[e]??0}let i=0;for(let e=0;e<t.length-1;e++){let n=t[e],o=t[e+1],r=xi[n+o];void 0!==r&&(i+=r)}let n=0;for(let e=1;e<t.length-1;e++){let i=t[e];n+=Ci[i]??0}return 2*i-n}function Si(e){let t=e.monomer;return null!==t&&void 0!==t.naturalAnalog&&""!==t.naturalAnalog?t.naturalAnalog.charAt(0).toUpperCase():""===e.symbol?"":e.symbol.charAt(0).toUpperCase()}function Mi(e){let t=[];t.push("HWE pseudo-molfile"),t.push(" HWE 2D"),t.push("");let i=e.atoms.length,n=e.bonds.length;t.push(function(e,t){return Li(e)+Li(t)+" 0 0 0 0 0 0 0 0999 V2000"}(i,n));for(let i of e.atoms)t.push(Ti(i));let o=new Map;for(let t=0;t<e.atoms.length;t++)o.set(e.atoms[t].id,t+1);for(let i of e.bonds){let e=o.get(i.a1.id),n=o.get(i.a2.id);void 0===e||void 0===n||t.push(Ii(e,n))}return t.push("M END"),t.join("\n")+"\n"}function Ti(e){let t=function(e){let t=e.monomer;return null!==t&&""!==t.symbol?t.symbol:""!==e.symbol?e.symbol:null!==t&&void 0!==t.naturalAnalog&&""!==t.naturalAnalog?t.naturalAnalog:"X"}(e);return $i(e.p.x)+$i(e.p.y)+$i(0)+" "+function(e){return e.length>=3?e:e+" ".repeat(3-e.length)}(t)+" 0 0 0 0 0 0 0 0 0 0 0 0"}function Ii(e,t){return Li(e)+Li(t)+Li(1)+Li(0)}function Li(e){let t=String(e);return t.length>=3?t:" ".repeat(3-t.length)+t}function $i(e){let t=e.toFixed(4);return t.length>=10?t.slice(0,10):" ".repeat(10-t.length)+t}var Pi=new Map,Ri=class{constructor(e){if(this._destroyed=!1,this._parseHits=0,this._parseMisses=0,this._layoutHits=0,this._layoutMisses=0,this._renderHits=0,this._renderMisses=0,void 0===e.monomerLib||null===e.monomerLib)throw new TypeError("HelmService: options.monomerLib is required");this.monomerLib=e.monomerLib,this.theme=e.theme??Dt,this.logger=e.logger??new h,this.options=Object.freeze({...e});let t=e.cacheSize??256;this._parseCache=new l({max:t}),this._layoutCache=new l({max:t}),this._renderCache=new l({max:t}),this._libUnsub=this.monomerLib.onChanged.subscribe(()=>{this.clearCaches()})}parse(e,t){this._ensureLive(),e=this._normalizeHelm(e);let i=t?.mode??"lenient",n=!1!==t?.resolveMonomers,o=`${(s={mode:i,resolveMonomers:n,helm:e}).mode}|${s.resolveMonomers?1:0}|${s.helm}`,r=this._parseCache.get(o);var s;if(void 0!==r)return this._parseHits+=1,r;this._parseMisses+=1;let a={mode:i,resolveMonomers:n},l=le(e,this.monomerLib,a),h={mol:l.mol,diagnostics:Object.freeze([...l.diagnostics])};return this._parseCache.set(o,h),h}serialize(e,t){return this._ensureLive(),pe(e,{...void 0!==t?.canonicalize?{canonicalize:t.canonicalize}:{},...void 0!==t?.includeHighlights?{includeHighlights:t.includeHighlights}:{},...void 0!==t?.version?{version:t.version}:{}})}validate(e,t){this._ensureLive(),e=this._normalizeHelm(e);let{mol:i,diagnostics:n}=this.parse(e,{mode:"lenient"}),o=void 0!==t?.mode?{mode:t.mode}:{},r=function(e,t,i){let n=i?.mode??"lenient",o=[];for(let i of ke)o.push(...i(e,t));let r="pedantic"===n?o.map(e=>"warning"===e.severity?{...e,severity:"error"}:e):o;if("strict"===n||"pedantic"===n){let e=r.filter(e=>"error"===e.severity);if(e.length>0)throw new s(e)}return r}(i,this.monomerLib,o);return[...n,...r]}canonicalize(e){this._ensureLive(),e=this._normalizeHelm(e);let{mol:t}=this.parse(e,{mode:"lenient"});return pe(new Ae(t).run(),{canonicalize:!0,version:"V2.0"})}removeGaps(e){return this._ensureLive(),function(e,t){let i=function(e){let t=new Map;for(let i of e.atoms)t.set(i.bio.continuousId,i.id);let i=new Set;for(let t of e.atoms)"*"===t.symbol&&i.add(t.id);if(0===i.size)return{mol:e,survivorByOldContinuousId:t};let n=new Map;for(let t of e.atoms)n.set(t.id,[]);for(let t of e.bonds)n.get(t.a1.id)?.push(t),t.a2.id!==t.a1.id&&n.get(t.a2.id)?.push(t);let o=function(e,t){let i=[],n=new Set;for(let o of e){if(n.has(o))continue;let r=new Set,s=[o];for(;s.length>0;){let i=s.pop();if(!r.has(i)){r.add(i),n.add(i);for(let n of t.get(i)??[]){let t=n.a1.id===i?n.a2.id:n.a1.id;e.has(t)&&!r.has(t)&&s.push(t)}}}let a=[],l=new Set;for(let e of r)for(let i of t.get(e)??[])l.has(i.id)||r.has(i.a1.id)!==r.has(i.a2.id)&&(l.add(i.id),a.push(i));i.push({atoms:r,boundary:a})}return i}(i,n);for(let e of o)we(e,n);let r=e.atoms.filter(e=>!i.has(e.id)),s=e.chains.map(e=>({chain:e,backbone:e.backboneAtoms.filter(e=>!i.has(e.id))})).filter(e=>e.backbone.length>0||0===e.chain.backboneAtoms.length),a=new Map,l=new Map;for(let e of s)e.backbone.forEach((t,i)=>{a.set(t.id,e.chain.id),l.set(t.id,i+1)});let h=1;for(let t of e.bonds)t.id>=h&&(h=t.id+1);let d=new Map;for(let e of o){if(2!==e.boundary.length)continue;let t=xe(e,e.boundary[0]),i=xe(e,e.boundary[1]);Ce(t.r,1)&&Ce(i.r,2)&&([t,i]=[i,t]);let n=a.get(t.atom.id)===a.get(i.atom.id),o=l.get(t.atom.id),r=l.get(i.atom.id),s=n&&void 0!==o&&void 0!==r&&o+1===r&&Ce(t.r,2)&&Ce(i.r,1)?"backbone":"cross-polymer",c=Math.min(...e.boundary.map(e=>e.id));d.set(c,{id:h++,a1:t.atom,a2:i.atom,kind:s,r1:t.r,r2:i.r})}let c=[];for(let t of e.bonds){let e=d.get(t.id);void 0!==e&&c.push(e),!i.has(t.a1.id)&&!i.has(t.a2.id)&&c.push(t)}let u=s.map(e=>({id:e.chain.id,polymerType:e.chain.polymerType,backboneAtoms:e.backbone,bonds:c.filter(t=>a.get(t.a1.id)===e.chain.id&&a.get(t.a2.id)===e.chain.id),...void 0!==e.chain.annotation?{annotation:e.chain.annotation}:{}})),p=new Map;for(let e of u){let t=0;for(let i of e.backboneAtoms)t+=1,p.set(i.id,{...i,bio:{...i.bio,positionInChain:t}})}for(let e of r)p.has(e.id)||p.set(e.id,e);for(let[e,t]of p)if(void 0!==t.branchAtom&&i.has(t.branchAtom.id)){let{branchAtom:i,...n}=t;p.set(e,n)}let m=u.map(e=>{let t=e.backboneAtoms.map(e=>p.get(e.id)),i=e.bonds.map(e=>({...e,a1:p.get(e.a1.id),a2:p.get(e.a2.id)}));return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:i,...void 0!==e.annotation?{annotation:e.annotation}:{}}}),f=c.map(e=>({...e,a1:p.get(e.a1.id),a2:p.get(e.a2.id)}));return{mol:{atoms:r.map(e=>p.get(e.id)),bonds:f,chains:m,groups:e.groups,annotations:e.annotations},survivorByOldContinuousId:t}}(le(e,t??null,{mode:"lenient",resolveMonomers:!1}).mol),n=function(e){let t=M(e),i=new Map;for(let n of e.atoms){let e=t.get(n.id);void 0!==e&&e!==n.bio.continuousId?i.set(n.id,{...n,bio:{...n.bio,continuousId:e}}):i.set(n.id,n)}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=i.get(t.id),n=i.get(t.branchAtom.id);void 0===e||void 0===n||(e.branchAtom=n)}let n=e.bonds.map(e=>{let t=i.get(e.a1.id),n=i.get(e.a2.id);return void 0===t||void 0===n||t===e.a1&&n===e.a2?e:{...e,a1:t,a2:n}}),o=new Map;for(let e of n)o.set(e.id,e);let r=e.chains.map(e=>{let t=[];for(let n of e.backboneAtoms){let e=i.get(n.id);t.push(e??n)}let n=[];for(let t of e.bonds){let e=o.get(t.id);n.push(e??t)}return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>i.get(e.id)??e),bonds:n,chains:r,groups:e.groups,annotations:e.annotations}}(i.mol),o=new Map;for(let e of n.atoms)o.set(e.id,e.bio.continuousId);let r=new Map;for(let[e,t]of i.survivorByOldContinuousId){let i=o.get(t);void 0!==i&&r.set(e,i)}return{srcHelm:e,resHelm:pe(n,{version:"V2.0"}),monomerMap:r}}(this._normalizeHelm(e),this.monomerLib)}renderToSvg(e,t){this._ensureLive(),e=this._normalizeHelm(e);let i=this._resolveRenderOptions(t),n=this._renderKey(e,i),o=this._renderCache.get(n);if(void 0!==o)return this._renderHits+=1,o;this._renderMisses+=1;let{mol:r}=this.parse(e,{mode:"lenient"}),s=this._layout(r,i.bondLength),{svg:a}=Jt(s,i);return this._renderCache.set(n,a),a}renderMol(e,t){this._ensureLive();let i=this._resolveRenderOptions(t),{svg:n}=Jt(e,i);return n}renderMolResult(e,t){return this._ensureLive(),Jt(e,this._resolveRenderOptions(t))}async renderToPng(e,t){if(this._ensureLive(),e=this._normalizeHelm(e),"function"!=typeof globalThis.OffscreenCanvas)throw new a("png-rendering-requires-browser","HelmService.renderToPng requires OffscreenCanvas (browser-only).");let i=this._resolveRenderOptions(t),{mol:n}=this.parse(e,{mode:"lenient"});return async function(e,t={}){let i=function(){let e=globalThis;return"function"==typeof e.OffscreenCanvas?e.OffscreenCanvas:null}();if(null===i&&void 0===t.canvas)throw new Error("renderToPng: OffscreenCanvas is not available in this environment");let n=t.theme??Dt,o=t.width??400,r=t.height??100,s=t.pixelRatio??1,a=t.canvas??new i(Math.max(1,Math.round(o*s)),Math.max(1,Math.round(r*s))),l=a.getContext("2d");if(null===l)throw new Error("renderToPng: failed to acquire 2D context");l.save(),l.scale(s,s),ai(l,e,{x:0,y:0,width:o,height:r},{...t,backColor:t.backColor??n.background}),l.restore();let h=a;if("function"!=typeof h.convertToBlob)throw new Error("renderToPng: canvas.convertToBlob is not available");let d=await(await h.convertToBlob({type:"image/png"})).arrayBuffer();return new Uint8Array(d)}(this._layout(n,i.bondLength),i)}renderToCanvas(e,t,i,n){this._ensureLive(),t=this._normalizeHelm(t);let o=this._resolveRenderOptions(n),{mol:r}=this.parse(t,{mode:"lenient"}),s=this._layout(r,o.bondLength),{bbox:a,drawBox:l}=ai(e,s,i,o);return{mol:s,bbox:a,drawBox:l}}renderMolToCanvas(e,t,i,n){this._ensureLive();let o=this._resolveRenderOptions(n),{bbox:r,drawBox:s}=ai(e,t,i,o);return{mol:t,bbox:r,drawBox:s}}*renderMany(e,t){for(let i of e??[]){let e=this.renderToSvg(i.helm,t);yield{id:i.id,svg:e}}}getFormula(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return fi(t)}getMolWeight(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return wi(t)}getExtinctionCoefficient(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return ki(t)}getMolfile(e){this._ensureLive();let{mol:t}=this.parse(this._normalizeHelm(e),{mode:"lenient"});return Mi(t)}hasAtomicMolfileProvider(){return"function"==typeof this.options.atomicMolfileProvider}async getAtomicMolfile(e){this._ensureLive(),e=this._normalizeHelm(e);let t=this.options.atomicMolfileProvider;if("function"!=typeof t)throw new a("atomic-molfile-not-configured","Set HelmServiceOptions.atomicMolfileProvider to enable atomic-level expansion.");return await t(e,this.monomerLib)}hasExtraPanes(){let e=this.options.extraPanes;return void 0!==e&&e.size>0}getExtraPanes(){return this.options.extraPanes??Pi}invalidate(e){if(void 0!==e)for(let t of[this._parseCache,this._layoutCache,this._renderCache]){let i=[];for(let n of t.keys())e(n)&&i.push(n);for(let e of i)t.delete(e)}else this.clearCaches()}clearCaches(){this._parseCache.clear(),this._layoutCache.clear(),this._renderCache.clear(),this._parseHits=0,this._parseMisses=0,this._layoutHits=0,this._layoutMisses=0,this._renderHits=0,this._renderMisses=0}destroy(){this._destroyed||(this._destroyed=!0,this._libUnsub(),this.clearCaches())}_ensureLive(){if(this._destroyed)throw new a("service-destroyed","HelmService instance has been destroyed.")}_normalizeHelm(e){return null==e?"":"string"==typeof e?e:String(e)}_resolveRenderOptions(e){let t={},i=e?.theme??this.theme;return t.theme=i,void 0!==e?.width&&(t.width=e.width),void 0!==e?.height&&(t.height=e.height),void 0!==e?.backColor&&(t.backColor=e.backColor),void 0!==e?.padding&&(t.padding=e.padding),void 0!==e?.showIds&&(t.showIds=e.showIds),void 0!==e?.showAnnotations&&(t.showAnnotations=e.showAnnotations),void 0!==e?.bondLength&&(t.bondLength=e.bondLength),void 0!==e?.fontSize&&(t.fontSize=e.fontSize),void 0!==e?.maxScale&&(t.maxScale=e.maxScale),void 0!==e?.showRGroupLabels&&(t.showRGroupLabels=e.showRGroupLabels),void 0!==e?.selectedAtomIds&&(t.selectedAtomIds=e.selectedAtomIds),void 0!==e?.highlightedAtomIds&&(t.highlightedAtomIds=e.highlightedAtomIds),void 0!==e?.fixedModelBbox&&(t.fixedModelBbox=e.fixedModelBbox),t}_renderKey(e,t){let i=(t.theme??this.theme).name;return`${this._libCacheTag()}|${i}|${t.width??0}x${t.height??0}|p${t.padding??-1}|b${t.bondLength??-1}|bg${t.backColor??""}|i${!0===t.showIds?1:0}a${!1===t.showAnnotations?0:1}|s${t.maxScale??1}|w${xt()}|${e}`}_layout(e,t){let i=`${(r=e).chains.map(e=>`${e.id}:${e.polymerType}:${e.backboneAtoms.length}`).join(",")}#${r.atoms.map(e=>`${e.id}@${e.symbol}@${e.bio.chainId}`).join(";")}#${r.bonds.map(e=>`${e.id}:${e.a1.id}-${e.a2.id}:${e.kind}`).join(";")}`,n=`${this._libCacheTag()}|${t??"d"}|w${xt()}|${i}`,o=this._layoutCache.get(n);var r;if(void 0!==o)return this._layoutHits+=1,o;this._layoutMisses+=1;let s=void 0!==t?Et(e,{bondLength:t}):Et(e);return this._layoutCache.set(n,s),s}get stats(){return{parseHits:this._parseHits,parseMisses:this._parseMisses,layoutHits:this._layoutHits,layoutMisses:this._layoutMisses,renderHits:this._renderHits,renderMisses:this._renderMisses}}_libCacheTag(){let e=this.monomerLib,t="number"==typeof e.version?e.version:0;return`${this.monomerLib.source}@${t}`}},Hi=class{constructor(e,t){this.atoms=e,this.bonds=t,this.isEmpty=0===e.size&&0===t.size,Object.freeze(this)}},Ni=new Hi(new Set,new Set),Di={empty:()=>Ni,fromAtoms:e=>new Hi(new Set(e),new Set),fromBonds:e=>new Hi(new Set,new Set(e)),fromAtomsAndBonds:(e,t)=>new Hi(new Set(e),new Set(t)),union(...e){if(0===e.length)return Ni;let t=new Set,i=new Set;for(let n of e){for(let e of n.atoms)t.add(e);for(let e of n.bonds)i.add(e)}return new Hi(t,i)},difference(e,t){let i=new Set,n=new Set;for(let n of e.atoms)t.atoms.has(n)||i.add(n);for(let i of e.bonds)t.bonds.has(i)||n.add(i);return new Hi(i,n)},intersect(e,t){let i=new Set,n=new Set;for(let n of e.atoms)t.atoms.has(n)&&i.add(n);for(let i of e.bonds)t.bonds.has(i)&&n.add(i);return new Hi(i,n)},toggle(e,t){if("atom"===t.kind){let i=new Set(e.atoms);return i.has(t.id)?i.delete(t.id):i.add(t.id),new Hi(i,new Set(e.bonds))}let i=new Set(e.bonds);return i.has(t.id)?i.delete(t.id):i.add(t.id),new Hi(new Set(e.atoms),i)},hasAtom:(e,t)=>e.atoms.has(t),hasBond:(e,t)=>e.bonds.has(t),equals(e,t){if(e===t)return!0;if(e.atoms.size!==t.atoms.size||e.bonds.size!==t.bonds.size)return!1;for(let i of e.atoms)if(!t.atoms.has(i))return!1;for(let i of e.bonds)if(!t.bonds.has(i))return!1;return!0}};function Fi(e){let t=e.monomer;return null===t?0:t.rgroups.length}function Oi(e,t){let i=Fi(e);if(0===i)return[];let n=new Set(function(e,t){let i=new Set;for(let n of t)n.a1.id===e.id&&"numeric"===n.r1.kind&&i.add(n.r1.r),n.a2.id===e.id&&"numeric"===n.r2.kind&&i.add(n.r2.r);let n=[],o=Array.from(i).sort((e,t)=>e-t);for(let e of o)n.push(e);return n}(e,t)),o=[];for(let e=1;e<=i;e++)n.has(e)||o.push(e);return o}function zi(e,t){let i=[];for(let n of t)if(n.a1.id===e.id){let e="numeric"===n.r1.kind?n.r1.r:0;i.push({bond:n,side:"r1",rNumber:e})}else if(n.a2.id===e.id){let e="numeric"===n.r2.kind?n.r2.r:0;i.push({bond:n,side:"r2",rNumber:e})}return i}function Gi(e,t){return e.kind===t.kind&&("numeric"===e.kind&&"numeric"===t.kind?e.r===t.r:"positional"!==e.kind||"positional"!==t.kind||e.position===t.position&&e.r===t.r)}var qi=class{constructor(e){this._atoms=new Map,this._atomOrder=[],this._bonds=new Map,this._bondOrder=[],this._chains=new Map,this._chainOrder=[],this._addedAtoms=new Set,this._removedAtoms=new Set,this._modifiedAtoms=new Set,this._addedBonds=new Set,this._removedBonds=new Set,this._modifiedBonds=new Set,this._topologyDirty=!1,this._idgen=new S;let t=function(e){let t=0;for(let i of e.atoms)i.id>t&&(t=i.id);for(let i of e.bonds)i.id>t&&(t=i.id);return t}(e);for(let e=0;e<t;e++)this._idgen.next();for(let t of e.chains)this._chains.set(t.id,{id:t.id,polymerType:t.polymerType,backboneAtomIds:t.backboneAtoms.map(e=>e.id),bondIds:t.bonds.map(e=>e.id),annotation:t.annotation}),this._chainOrder.push(t.id);for(let t of e.atoms)this._atoms.set(t.id,{id:t.id,p:{x:t.p.x,y:t.p.y},biotype:t.biotype,symbol:t.symbol,monomer:t.monomer,bio:{...t.bio},hidden:t.hidden,selected:t.selected,highlighted:t.highlighted,tag:t.tag,branchAtomId:t.branchAtom?.id,inlineSource:t.inlineSource}),this._atomOrder.push(t.id);for(let t of e.bonds)this._bonds.set(t.id,{id:t.id,a1Id:t.a1.id,a2Id:t.a2.id,kind:t.kind,r1:t.r1,r2:t.r2,ratio:t.ratio,tag:t.tag}),this._bondOrder.push(t.id);this._groups=[...e.groups],this._annotations=e.annotations}addAtom(e){let t=this._idgen.next(),i=function(e){switch(e){case y:return B.PEPTIDE;case v:case w:case x:case E:return B.RNA;case C:return B.CHEM;case k:return B.BLOB}}(e.biotype),n=e.chainId??this._pickChainId(i),o=this._chains.get(n);void 0===o&&(o={id:n,polymerType:i,backboneAtomIds:[],bondIds:[],annotation:void 0},this._chains.set(n,o),this._chainOrder.push(n));let r=e.positionInChain??o.backboneAtomIds.length+1,s={id:t,p:{x:e.p.x,y:e.p.y},biotype:e.biotype,symbol:e.symbol,monomer:null,bio:{chainId:n,positionInChain:r,continuousId:0},hidden:!1,selected:!1,highlighted:!1,tag:void 0,branchAtomId:void 0,inlineSource:void 0};this._atoms.set(t,s),this._atomOrder.push(t);let a=Math.max(0,Math.min(r-1,o.backboneAtomIds.length));return o.backboneAtomIds.splice(a,0,t),this._addedAtoms.add(t),this._topologyDirty=!0,t}removeAtom(e){let t=this._atoms.get(e);if(void 0===t)return;let i=[];for(let t of this._bonds.values())(t.a1Id===e||t.a2Id===e)&&i.push(t.id);for(let e of i)this._removeBondInternal(e);for(let t of this._atoms.values())t.branchAtomId===e&&(t.branchAtomId=void 0);let n=this._chains.get(t.bio.chainId);if(void 0!==n){let t=n.backboneAtomIds.indexOf(e);t>=0&&n.backboneAtomIds.splice(t,1)}this._atoms.delete(e);let o=this._atomOrder.indexOf(e);o>=0&&this._atomOrder.splice(o,1),this._addedAtoms.has(e)?this._addedAtoms.delete(e):this._removedAtoms.add(e),this._modifiedAtoms.delete(e),this._topologyDirty=!0}updateAtom(e,t){let i=this._atoms.get(e);void 0!==i&&(void 0!==t.p&&(i.p={x:t.p.x,y:t.p.y}),void 0!==t.symbol&&(i.symbol=t.symbol),void 0!==t.selected&&(i.selected=t.selected),void 0!==t.highlighted&&(i.highlighted=t.highlighted),"tag"in t&&(i.tag=t.tag),void 0!==t.hidden&&(i.hidden=t.hidden),this._addedAtoms.has(e)||this._modifiedAtoms.add(e))}addBond(e){if(!this._atoms.has(e.a1))throw new Error(`Transaction.addBond: atom ${e.a1} does not exist`);if(!this._atoms.has(e.a2))throw new Error(`Transaction.addBond: atom ${e.a2} does not exist`);for(let t of this._bonds.values()){let i=t.a1Id===e.a1&&t.a2Id===e.a2&&Gi(t.r1,e.r1)&&Gi(t.r2,e.r2),n=t.a1Id===e.a2&&t.a2Id===e.a1&&Gi(t.r1,e.r2)&&Gi(t.r2,e.r1);if(i||n)throw new Error(`Transaction.addBond: duplicate bond ${e.a1}:${ji(e.r1)}-${e.a2}:${ji(e.r2)}`)}let t=this._idgen.next();this._bonds.set(t,{id:t,a1Id:e.a1,a2Id:e.a2,kind:e.kind,r1:e.r1,r2:e.r2,ratio:void 0,tag:void 0}),this._bondOrder.push(t);let i=this._atoms.get(e.a1),n=this._atoms.get(e.a2);if(void 0!==i&&void 0!==n&&i.bio.chainId===n.bio.chainId){let e=this._chains.get(i.bio.chainId);void 0!==e&&e.bondIds.push(t)}return this._addedBonds.add(t),this._topologyDirty=!0,t}removeBond(e){this._bonds.has(e)&&(this._removeBondInternal(e),this._topologyDirty=!0)}updateBond(e,t){let i=this._bonds.get(e);void 0!==i&&("tag"in t&&(i.tag=t.tag),"ratio"in t&&(i.ratio=t.ratio),this._addedBonds.has(e)||this._modifiedBonds.add(e))}commit(){let e=new Map;for(let t of this._atomOrder){let i=this._atoms.get(t);if(void 0===i)continue;let n={id:i.id,p:{x:i.p.x,y:i.p.y},biotype:i.biotype,symbol:i.symbol,monomer:i.monomer,bio:{...i.bio},hidden:i.hidden,selected:i.selected,highlighted:i.highlighted,...void 0!==i.tag?{tag:i.tag}:{},...void 0!==i.inlineSource?{inlineSource:i.inlineSource}:{}};e.set(t,n)}for(let t of this._atomOrder){let i=this._atoms.get(t);if(void 0===i||void 0===i.branchAtomId)continue;let n=e.get(t),o=e.get(i.branchAtomId);void 0===n||void 0===o||(n.branchAtom=o)}let t=new Map;for(let i of this._bondOrder){let n=this._bonds.get(i);if(void 0===n)continue;let o=e.get(n.a1Id),r=e.get(n.a2Id);if(void 0===o||void 0===r)continue;let s={id:n.id,a1:o,a2:r,kind:n.kind,r1:n.r1,r2:n.r2,...void 0!==n.ratio?{ratio:{...n.ratio}}:{},...void 0!==n.tag?{tag:n.tag}:{}};t.set(i,s)}let i=[];for(let n of this._chainOrder){let o=this._chains.get(n);if(void 0===o||0===o.backboneAtomIds.length&&0===o.bondIds.length)continue;let r=[];for(let t of o.backboneAtomIds){let i=e.get(t);void 0!==i&&r.push(i)}let s=[];for(let e of o.bondIds){let i=t.get(e);void 0!==i&&s.push(i)}i.push({id:o.id,polymerType:o.polymerType,backboneAtoms:r,bonds:s,...void 0!==o.annotation?{annotation:o.annotation}:{}})}let n={atoms:this._atomOrder.map(t=>e.get(t)).filter(e=>void 0!==e),bonds:this._bondOrder.map(e=>t.get(e)).filter(e=>void 0!==e),chains:i,groups:[...this._groups],annotations:this._annotations};this._topologyDirty&&(n=function(e){let t=M(e),i=new Map;for(let n of e.atoms){let e=t.get(n.id);void 0!==e&&e!==n.bio.continuousId?i.set(n.id,{...n,bio:{...n.bio,continuousId:e}}):i.set(n.id,n)}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=i.get(t.id),n=i.get(t.branchAtom.id);void 0===e||void 0===n||(e.branchAtom=n)}let n=e.bonds.map(e=>{let t=i.get(e.a1.id),n=i.get(e.a2.id);return void 0===t||void 0===n||t===e.a1&&n===e.a2?e:{...e,a1:t,a2:n}}),o=new Map;for(let e of n)o.set(e.id,e);let r=e.chains.map(e=>{let t=[];for(let n of e.backboneAtoms)t.push(i.get(n.id)??n);let n=[];for(let t of e.bonds)n.push(o.get(t.id)??t);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>i.get(e.id)??e),bonds:n,chains:r,groups:e.groups,annotations:e.annotations}}(n));let o=Object.freeze({addedAtomIds:new Set(this._addedAtoms),removedAtomIds:new Set(this._removedAtoms),addedBondIds:new Set(this._addedBonds),removedBondIds:new Set(this._removedBonds),modifiedAtomIds:new Set(this._modifiedAtoms),modifiedBondIds:new Set(this._modifiedBonds)});return this._addedAtoms.clear(),this._removedAtoms.clear(),this._modifiedAtoms.clear(),this._addedBonds.clear(),this._removedBonds.clear(),this._modifiedBonds.clear(),this._topologyDirty=!1,{mol:n,changes:o}}_removeBondInternal(e){if(void 0===this._bonds.get(e))return;this._bonds.delete(e);let t=this._bondOrder.indexOf(e);t>=0&&this._bondOrder.splice(t,1);for(let t of this._chains.values()){let i=t.bondIds.indexOf(e);i>=0&&t.bondIds.splice(i,1)}this._addedBonds.has(e)?this._addedBonds.delete(e):this._removedBonds.add(e),this._modifiedBonds.delete(e)}_pickChainId(e){let t=function(e){switch(e){case B.PEPTIDE:return"PEPTIDE";case B.RNA:return"RNA";case B.CHEM:return"CHEM";case B.BLOB:return"BLOB";case B.G:return"G"}}(e),i=1;for(;this._chains.has(`${t}${i}`);)i+=1;return`${t}${i}`}};function ji(e){switch(e.kind){case"numeric":return`R${e.r}`;case"unspecified":return"?";case"wildcard":return"*";case"pair":return"pair";case"positional":return`${e.position}pos:R${e.r}`}}var Yi=class{constructor(e,t,i){this.atoms=[],this.bonds=[],this.bondHitWidth=i?.bondHitWidth??4,this.rebuild(e,t)}rebuild(e,t){let i=[];for(let n of e.atoms)n.hidden||i.push({atom:n,bbox:qt(n,t),hitRadius:jt(n,t)});let n=[];for(let t of e.bonds)n.push({bond:t,a:t.a1.p,b:t.a2.p});this.atoms=i,this.bonds=n}test(e){let t=null,i=null;for(let n of this.atoms){if(!Vi(e,n.bbox))continue;let o=e.x-n.atom.p.x,r=e.y-n.atom.p.y,s=Math.sqrt(o*o+r*r);s>n.hitRadius||(null===t||s<t.d?(i=t,t={entry:n,d:s}):(null===i||s<i.d)&&(i={entry:n,d:s}))}if(null!==t)return{atom:t.entry.atom};let n=null;for(let t of this.bonds){let i=Wi(e,t.a,t.b);i>this.bondHitWidth||(null===n||i<n.d)&&(n={entry:t,d:i})}return null!==n?{bond:n.entry.bond}:null}testRect(e){let t=[];for(let i of this.atoms)Vi(i.atom.p,e)&&t.push(i.atom);let i=[];for(let t of this.bonds)Vi(t.a,e)&&Vi(t.b,e)&&i.push(t.bond);return{atoms:t,bonds:i}}atomCount(){return this.atoms.length}bondCount(){return this.bonds.length}};function Vi(e,t){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}function Wi(e,t,i){let n=i.x-t.x,o=i.y-t.y,r=n*n+o*o;if(0===r){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}let s=((e.x-t.x)*n+(e.y-t.y)*o)/r;s<0?s=0:s>1&&(s=1);let a=t.x+s*n,l=t.y+s*o,h=e.x-a,d=e.y-l;return Math.sqrt(h*h+d*d)}var Ui=class{constructor(){this._handlers=new Map}on(e,t){let i=this._handlers.get(e);void 0===i&&(i=new Set,this._handlers.set(e,i));let n=t;return i.add(n),()=>{let t=this._handlers.get(e);void 0!==t&&t.delete(n)}}off(e,t){let i=this._handlers.get(e);void 0!==i&&i.delete(t)}fire(e,t){let i=this._handlers.get(e);if(void 0===i||0===i.size)return;let n=[...i];for(let e of n)e(t)}clear(){this._handlers.clear()}observerCount(e){if(void 0===e){let e=0;for(let t of this._handlers.values())e+=t.size;return e}return this._handlers.get(e)?.size??0}},Ki=class{constructor(e){this._entries=[],this._idx=-1;let t=e?.maxEntries??100;if(t<=0)throw new RangeError("HistoryStack: maxEntries must be > 0");this._max=t}push(e){for(this._idx<this._entries.length-1&&(this._entries=this._entries.slice(0,this._idx+1)),this._entries.push(e),this._idx=this._entries.length-1;this._entries.length>this._max;)this._entries.shift(),this._idx-=1}canUndo(){return this._idx>0}canRedo(){return this._idx>=0&&this._idx<this._entries.length-1}undo(){return this.canUndo()?(this._idx-=1,this._entries[this._idx]??null):null}redo(){return this.canRedo()?(this._idx+=1,this._entries[this._idx]??null):null}clear(){this._entries=[],this._idx=-1}get size(){return this._entries.length}current(){return this._idx<0?null:this._entries[this._idx]??null}};function Xi(e){let t=e.ownerDocument;if(null!=t)return t;let i=globalThis;if(void 0!==i.document)return i.document;throw new Error("EditorView: no Document available (host.ownerDocument is null).")}function Qi(e,t,i,n){let o=e.createElement(t);if(void 0!==i)for(let e of Object.keys(i)){let t=i[e];!1===t||void 0===t||o.setAttribute(e,!0===t?"":String(t))}if(void 0!==n)for(let t of n)"string"==typeof t?o.appendChild(e.createTextNode(t)):o.appendChild(t);return o}function Zi(e,t,i=220,n=140){if(null==e||""===t)return null;try{let o=e.get_mol(t);if(null===o)return null;let r=o.get_svg(i,n);return o.delete(),r}catch{return null}}function Ji(e,t,i){let n="data-testid";for(let i=0;i<e.body.children.length;i++){let o=e.body.children[i];if(void 0!==o&&o.getAttribute(n)===t)return o}let o=Qi(e,"div",{class:i,[n]:t});return o.style.display="none",e.body.appendChild(o),o}function en(e,t,i){for(;null!==t.firstChild;)t.removeChild(t.firstChild);if(t.appendChild(Qi(e,"div",{class:"hw-tooltip__symbol"},[i.symbol])),void 0!==i.name&&""!==i.name&&i.name!==i.symbol&&t.appendChild(Qi(e,"div",{class:"hw-tooltip__name"},[i.name])),void 0!==i.rdkitSvg&&null!==i.rdkitSvg&&""!==i.rdkitSvg){let n={class:"hw-tooltip__rdkit"};void 0!==i.rdkitTestid&&(n["data-testid"]=i.rdkitTestid);let o=Qi(e,"div",n);o.innerHTML=i.rdkitSvg,t.appendChild(o)}void 0!==i.hint&&""!==i.hint&&t.appendChild(Qi(e,"div",{class:"hw-tooltip__hint"},[i.hint]))}function tn(e,t,i){let n=e.style;n.display="block",n.left=`${t+12}px`,n.top=`${i+12}px`}function nn(e){null!==e&&(e.style.display="none")}function on(e){let t=e.body;if(null!=t)for(let e=0;e<t.children.length;e++){let i=t.children[e];if(void 0===i)continue;let n=void 0===i.getAttribute?null:i.getAttribute("data-testid");null!=n&&n.endsWith("-tooltip")&&nn(i)}}var rn=class e{constructor(e,t,i){this._baseTransform="",this._viewport={scale:1,offset:{x:0,y:0}},this._pinnedBbox=null,this._tooltip=null,this._bondTooltip=null,this._rdkitSvgCache=new Map,this._unsubs=[],this._destroyed=!1,this.host=e,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._width=i?.width??400,this._height=i?.height??200,function(e){let t=Xi(e);if(null!==t.querySelector("style[data-hw-editor-view-styles]"))return;let i=t.createElement("style");i.setAttribute("data-hw-editor-view-styles",""),i.textContent=".hw-editor-view{position:relative;display:block;overflow:hidden;outline:none;}.hw-editor-view svg{display:block;user-select:none;}.hw-editor-view.hw-view-only{cursor:default;}";let n=t.head??t.documentElement;null!==n&&n.appendChild(i)}(e);let n=this._doc.createElement("div");n.setAttribute("class","hw-editor-view"),e.appendChild(n),this._tooltip=Ji(this._doc,"atom-tooltip","hw-atom-tooltip"),this._bondTooltip=Ji(this._doc,"bond-tooltip","hw-bond-tooltip"),this._svgRoot=this._renderFresh(),this._unsubs.push(t.on("mol:changed",e=>{this._hideTooltip(),this._hideBondTooltip(),("setHelm"===e.reason||"cleanLayout"===e.reason||"initial"===e.reason)&&(this._pinnedBbox=null),this._renderFresh()})),this._unsubs.push(t.on("selection:change",e=>{this._refreshOverlays(e)})),this._unsubs.push(t.on("highlight:change",e=>{this._refreshOverlays(e)})),this._unsubs.push(t.on("theme:change",()=>{this._renderFresh()})),this._unsubs.push(t.on("view:resize",e=>{this._applyResize(e.width,e.height)})),this._unsubs.push(t.on("view:viewport-change",e=>{this._viewport=e.viewport,this._applyViewport(e.viewport)})),this._unsubs.push(t.on("view:fit-to-content",()=>{this._pinnedBbox=null,this._renderFresh()})),this._unsubs.push(t.on("monomer:hover",e=>{this._showTooltip(e.atom,e.clientX,e.clientY)})),this._unsubs.push(t.on("monomer:hover-end",()=>{this._hideTooltip()})),this._unsubs.push(t.on("bond:hover",e=>{this._showBondTooltip(e.bond,e.clientX,e.clientY)})),this._unsubs.push(t.on("bond:hover-end",()=>{this._hideBondTooltip()})),this._unsubs.push(t.on("bond:preview",e=>{this._paintBondPreview(e.start.p,e.cursor,null!==e.candidate)})),this._unsubs.push(t.on("bond:preview-end",()=>{this._clearBondPreview()})),this._unsubs.push(t.on("bond:cancel",()=>{this._clearBondPreview()})),this._unsubs.push(t.on("selection:rectangle-start",e=>{this._paintSelectionRect(e.origin,e.origin)})),this._unsubs.push(t.on("selection:rectangle-update",e=>{this._paintSelectionRectFromRect(e.rect)})),this._unsubs.push(t.on("selection:rectangle-end",()=>{this._clearSelectionRect()}))}get svgRoot(){return this._svgRoot}get width(){return this._width}get height(){return this._height}resize(e,t){this._destroyed||(this._width=e,this._height=t,this._renderFresh())}redraw(){this._destroyed||this._renderFresh()}destroy(){if(this._destroyed)return;this._destroyed=!0;for(let e of this._unsubs)e();this._unsubs.length=0;let e=this.host.querySelector(".hw-editor-view");null!==e&&null!==e.parentNode&&e.parentNode.removeChild(e),nn(this._tooltip),nn(this._bondTooltip),this._tooltip=null,this._bondTooltip=null}_renderFresh(){let e=this._editor.getService(),t=this._currentTheme(),i=this._editor.getMol();null===this._pinnedBbox&&(this._pinnedBbox=ei(i,t));let n=e.renderMol(i,{width:this._width,height:this._height,theme:t,fixedModelBbox:this._pinnedBbox});this._svgRoot=function(e,t){let i=Xi(e),n=e.querySelector(".hw-editor-view");if(null===n)throw new Error("EditorView.replaceSvg: missing .hw-editor-view wrapper.");let o=i.createElement("div");o.innerHTML=t;let r=o.querySelector("svg");if(null===r)throw new Error("EditorView.replaceSvg: rendered output contained no <svg>.");for(;null!==n.firstChild;)n.removeChild(n.firstChild);return n.appendChild(r),r}(this.host,n);let o=this._svgRoot.querySelector(".hw-content");return this._baseTransform=null!==o?o.getAttribute("transform")??"":"",this._svgRoot.setAttribute("data-testid","editor-svg"),this._applyOverlaysToCurrent(),(1!==this._viewport.scale||0!==this._viewport.offset.x||0!==this._viewport.offset.y)&&this._applyViewport(this._viewport),this._svgRoot}_refreshOverlays(e){this._applyOverlaysToCurrent()}_applyOverlaysToCurrent(){let e=this._editor.getMol(),t=this._editor.getSelection(),i=function(e,t={}){let i=t.theme??Dt,n=t.selectedAtomIds??new Set;return{highlightLayer:ti(e,i,t.highlightedAtomIds??new Set),selectionLayer:ii(e,i,n)}}(e,{theme:this._currentTheme(),selectedAtomIds:t.atoms,highlightedAtomIds:this._editorHighlights()});this._spliceLayer("hw-highlights",i.highlightLayer),this._spliceLayer("hw-selections",i.selectionLayer)}_spliceLayer(e,t){let i=this._svgRoot.querySelector(`.${e}`);if(null===i||null===i.parentNode)return;let n=this._doc.createElementNS("http://www.w3.org/2000/svg","svg");n.innerHTML=t;let o=n.querySelector(`.${e}`);null!==o&&i.parentNode.replaceChild(o,i)}_editorHighlights(){let e=this._editor;return"function"==typeof e._currentHighlights?e._currentHighlights():new Set}_currentTheme(){let e=this._editor;return"function"==typeof e._currentTheme?e._currentTheme():this._editor.getService().theme}_applyResize(e,t){this._width=e,this._height=t,this._pinnedBbox=null,this._renderFresh()}_applyViewport(e){let t=this._svgRoot.querySelector(".hw-content");if(null===t)return;let i=`translate(${e.offset.x} ${e.offset.y}) scale(${e.scale})`,n=""===this._baseTransform?i:`${i} ${this._baseTransform}`;t.setAttribute("transform",n)}_showTooltip(e,t,i){let n=this._tooltip;if(null===n)return;let o=""===e.symbol?"?":e.symbol,r=e.monomer?.name??"",s=e.bio.positionInChain,a=""===e.bio.chainId?"?":e.bio.chainId,l=""!==r&&r!==o?`${r} @ ${a}:${s}`:`${o} @ ${a}:${s}`,h=this._renderRdkitTooltipSvg(e);en(this._doc,n,{symbol:o,name:l,rdkitSvg:h,rdkitTestid:"atom-tooltip-rdkit-svg"});let d=""!==r&&r!==o?`${o} — ${r} @ ${a}:${s}`:`${o} @ ${a}:${s}`,c=this._doc.createElement("div");c.setAttribute("class","hw-atom-tooltip__text"),c.style.display="none",c.appendChild(this._doc.createTextNode(d)),n.appendChild(c),tn(n,t,i)}_renderRdkitTooltipSvg(t){let i=this._editor.getService().options.rdkitModule;if(null==i)return null;let n=t.monomer;if(null===n)return null;let o=n.smiles;if(void 0===o||""===o)return null;let r=`${n.polymerType}:${n.symbol}`;if(this._rdkitSvgCache.has(r))return this._rdkitSvgCache.get(r)??null;let s=Zi(i,o,220,140);if(this._rdkitSvgCache.size>=e._RDKIT_CACHE_LIMIT){let e=this._rdkitSvgCache.keys().next().value;void 0!==e&&this._rdkitSvgCache.delete(e)}return this._rdkitSvgCache.set(r,s),s}_hideTooltip(){nn(this._tooltip)}_showBondTooltip(e,t,i){let n=this._bondTooltip;if(null===n)return;let o=an(e.r1),r=an(e.r2),s=`${e.a1.symbol}@${e.a1.bio.chainId}:${e.a1.bio.positionInChain}`,a=`${e.a2.symbol}@${e.a2.bio.chainId}:${e.a2.bio.positionInChain}`;en(this._doc,n,{symbol:`${o}-${r} (${e.kind})`,name:`${s} ↔ ${a}`}),tn(n,t,i)}_hideBondTooltip(){nn(this._bondTooltip)}_paintBondPreview(e,t,i){let n=this._svgRoot.querySelector(".hw-content");if(null===n)return;let o=n.querySelector(".hw-bond-preview");null===o&&(o=this._doc.createElementNS("http://www.w3.org/2000/svg","line"),o.setAttribute("class","hw-bond-preview"),o.setAttribute("data-testid","bond-preview"),o.setAttribute("stroke-dasharray","6 4"),o.setAttribute("stroke-width","2"),o.setAttribute("fill","none"),o.setAttribute("pointer-events","none"),n.appendChild(o)),o.setAttribute("x1",String(e.x)),o.setAttribute("y1",String(e.y)),o.setAttribute("x2",String(t.x)),o.setAttribute("y2",String(t.y)),o.setAttribute("stroke",i?"#1f5fcd":"#999999")}_clearBondPreview(){let e=this._svgRoot.querySelector(".hw-bond-preview");null!==e&&null!==e.parentNode&&e.parentNode.removeChild(e)}_paintSelectionRect(e,t){let i=Math.min(e.x,t.x),n=Math.min(e.y,t.y),o=Math.abs(e.x-t.x),r=Math.abs(e.y-t.y);this._paintSelectionRectAt(i,n,o,r)}_paintSelectionRectFromRect(e){this._paintSelectionRectAt(e.x,e.y,e.width,e.height)}_paintSelectionRectAt(e,t,i,n){let o=this._svgRoot.querySelector(".hw-content");if(null===o)return;let r=o.querySelector(".hw-selection-rect");null===r&&(r=this._doc.createElementNS("http://www.w3.org/2000/svg","rect"),r.setAttribute("class","hw-selection-rect"),r.setAttribute("data-testid","selection-rect"),r.setAttribute("fill","rgba(31, 95, 205, 0.08)"),r.setAttribute("stroke","#1f5fcd"),r.setAttribute("stroke-width","1"),r.setAttribute("stroke-dasharray","4 3"),r.setAttribute("pointer-events","none"),o.appendChild(r)),r.setAttribute("x",String(e)),r.setAttribute("y",String(t)),r.setAttribute("width",String(i)),r.setAttribute("height",String(n))}_clearSelectionRect(){let e=this._svgRoot.querySelector(".hw-selection-rect");null!==e&&null!==e.parentNode&&e.parentNode.removeChild(e)}};rn._RDKIT_CACHE_LIMIT=256;var sn=rn;function an(e){switch(e.kind){case"numeric":return`R${e.r}`;case"unspecified":return"?";case"wildcard":return"*";case"pair":return"pair";case"positional":return`${e.position}pos:R${e.r}`}}var ln=class e{constructor(e,t){this._onClose=null,this._primaryAction=null,this._host=e,this._doc=t.documentImpl??Xi(e);let i=this._doc,n={class:"hw-modal-backdrop",role:"presentation"};void 0!==t.testId&&(n["data-testid"]=`dialog-${t.testId}`);let o=Qi(i,"div",n),r={class:"hw-modal",role:"dialog","aria-modal":"true","aria-label":t.title};void 0!==t.testId&&(r["data-testid"]=`dialog-${t.testId}-frame`);let s=Qi(i,"div",r),a=Qi(i,"div",{class:"hw-modal__header"},[t.title]),l=Qi(i,"div",{class:"hw-modal__body"});s.appendChild(a),s.appendChild(l),o.appendChild(s);let h=e=>{e.stopPropagation()};for(let e of["mousedown","mousemove","mouseup","mouseover","mouseenter","mouseleave","wheel","contextmenu","dblclick","keydown","keyup","keypress"])o.addEventListener(e,h);s.addEventListener("keydown",e=>{let t=e;if("Enter"!==t.key||"TEXTAREA"===t.target?.tagName)return;let i=this._primaryAction;null!==i&&(t.preventDefault?.(),t.stopImmediatePropagation?.(),i())}),o.addEventListener("click",e=>{e.target!==o?e.stopPropagation():this.close()}),this.root=o,this.body=l}static anyOpen(){return e._openStack.length>0}static closeTopmost(){let t=e._openStack[e._openStack.length-1];return void 0!==t&&(t.close(),!0)}open(t){this._onClose=t??null,null===this.root.parentNode&&this._host.appendChild(this.root),e._openStack.includes(this)||e._openStack.push(this),on(this._doc)}close(){let t=e._openStack.indexOf(this);t>=0&&e._openStack.splice(t,1),null!==this.root.parentNode&&this.root.parentNode.removeChild(this.root);let i=this._onClose;this._onClose=null,null!==i&&i()}setPrimaryAction(e){this._primaryAction=e}get isOpen(){return null!==this.root.parentNode}};ln._openStack=[];var hn=ln;function dn(e,t,i,n){let o=`hw-input-${Math.random().toString(36).slice(2,9)}`,r=Qi(e,"label",{for:o,class:"hw-modal__label"},[t]),s=e.createElement("input");return s.setAttribute("id",o),s.setAttribute("type","text"),s.setAttribute("class","hw-modal__input"),void 0!==n&&s.setAttribute("data-testid",n),s.value=i,{row:Qi(e,"div",{class:"hw-modal__row"},[r,s]),input:s}}function cn(e,t,i,n,o){let r=`hw-sel-${Math.random().toString(36).slice(2,9)}`,s=Qi(e,"label",{for:r,class:"hw-modal__label"},[t]),a=e.createElement("select");a.setAttribute("id",r),a.setAttribute("class","hw-modal__select"),void 0!==o&&a.setAttribute("data-testid",o);for(let t of i){let i=e.createElement("option");i.setAttribute("value",t.value),t.value===n&&i.setAttribute("selected",""),i.appendChild(e.createTextNode(t.label)),a.appendChild(i)}return{row:Qi(e,"div",{class:"hw-modal__row"},[s,a]),select:a}}function un(e,t){let i=e.createElement("button");i.setAttribute("class","hw-modal__ok"),i.setAttribute("type","button"),void 0!==t&&i.setAttribute("data-testid",`${t}-ok`),i.appendChild(e.createTextNode("OK"));let n=e.createElement("button");return n.setAttribute("class","hw-modal__cancel"),n.setAttribute("type","button"),void 0!==t&&n.setAttribute("data-testid",`${t}-cancel`),n.appendChild(e.createTextNode("Cancel")),{row:Qi(e,"div",{class:"hw-modal__actions"},[i,n]),ok:i,cancel:n}}var pn=class{constructor(e,t){this._modal=null,this._editor=e;let i=e._getHost();if(null===i)throw new Error("ChooseRDialog: editor has no host element.");this._doc=t?.documentImpl??Xi(i)}open(e,t,i){this.close();let n=this._editor._getHost();if(null===n)return Promise.resolve(null);let o=new hn(n,{documentImpl:this._doc,title:"Choose R-Groups",testId:"choose-r"});this._modal=o;let r=fn(e,i?.freeR1,i?.currentR1,this._editor),s=fn(t,i?.freeR2,i?.currentR2,this._editor),a=Qi(this._doc,"div",{class:"hw-modal__info"},[`${e.symbol} (${e.bio.chainId})`]),l=void 0!==i?.currentR1?String(i.currentR1):r[0]?.value??"1",h=void 0!==i?.currentR2?String(i.currentR2):s[0]?.value??"1",d=cn(this._doc,"R-group on side A",r,l,"choose-r-r1"),c=Qi(this._doc,"div",{class:"hw-modal__info"},[`${t.symbol} (${t.bio.chainId})`]),u=cn(this._doc,"R-group on side B",s,h,"choose-r-r2"),p=un(this._doc,"choose-r"),m=[];return 0===r.length&&m.push(Qi(this._doc,"div",{class:"hw-modal__info hw-modal__note-fully-booked"},[`All R-groups on ${e.symbol} are in use.`])),0===s.length&&m.push(Qi(this._doc,"div",{class:"hw-modal__info hw-modal__note-fully-booked"},[`All R-groups on ${t.symbol} are in use.`])),new Promise(e=>{let t=!1,i=i=>{t||(t=!0,e(i))},n=e=>{i(e),this.close()},r=()=>n({r1:mn(d.select),r2:mn(u.select)});p.ok.addEventListener("click",r),p.cancel.addEventListener("click",()=>n(null)),o.setPrimaryAction(r),o.body.appendChild(a),o.body.appendChild(d.row),o.body.appendChild(c),o.body.appendChild(u.row);for(let e of m)o.body.appendChild(e);o.body.appendChild(p.row),o.open(()=>i(null))})}get isOpen(){return null!==this._modal&&this._modal.isOpen}close(){null!==this._modal&&(this._modal.close(),this._modal=null)}};function mn(e){let t=e.value;if("string"==typeof t&&t.length>0){let e=Number(t);if(Number.isFinite(e)&&e>=1)return e}let i=e.querySelectorAll("option");for(let e of Array.from(i))if(null!==e.getAttribute("selected")){let t=e.getAttribute("value")??"",i=Number(t);if(Number.isFinite(i)&&i>=1)return i}let n=i[0];if(void 0!==n){let e=n.getAttribute("value")??"",t=Number(e);if(Number.isFinite(t)&&t>=1)return t}return 1}function fn(e,t,i,n){let o,r=e.monomer?.rgroups;if(void 0===r||0===r.length)return[{value:"1",label:"R1"},{value:"2",label:"R2"},{value:"3",label:"R3"}];if(void 0!==t)o=new Set(t);else if(o=new Set(Oi(e,n.getMol().bonds)),0===o.size)for(let e=1;e<=r.length;e++)o.add(e);void 0!==i&&i>=1&&i<=r.length&&o.add(i);let s=[],a=Array.from(o).sort((e,t)=>e-t);for(let e of a){let t=r[e-1];if(void 0===t)continue;let i=void 0!==t.capGroupName&&""!==t.capGroupName?` (${t.capGroupName})`:"";s.push({value:String(e),label:`${t.label}${i}`})}return s}var bn="next-add-cursor";function gn(e){null!==e&&(e.style.display="none")}var An=class{constructor(e,t,i){this._hoverAtom=null,this._hoverBond=null,this._dragOrigin=null,this._bondStart=null,this._bondDragMoved=!1,this._rectDragHappened=!1,this._chooseRDialog=null,this._panStart=null,this._atomDragState=null,this._panMoved=!1,this._atomDragMoved=!1,this._nextAddCursorEl=null,this._destroyed=!1,this._unsubs=[],this._host=e,this._editor=t,this._enableContextMenu=i?.enableContextMenu??!0,this._tester=new Yi(t.getMol(),t._currentTheme()),this._unsubs.push(t.on("mol:changed",()=>{this._tester=new Yi(this._editor.getMol(),this._editor._currentTheme()),this._hoverAtom=null,this._hoverBond=null})),this._unsubs.push(t.on("option:change",e=>{("mode"===e.key||"nextAdd"===e.key)&&gn(this._nextAddCursorEl)})),this._onMove=e=>this._handleMove(e),this._onClick=e=>this._handleClick(e),this._onDblClick=e=>this._handleDblClick(e),this._onContextMenu=e=>this._handleContextMenu(e),this._onMouseDown=e=>this._handleMouseDown(e),this._onMouseUp=e=>this._handleMouseUp(e),this._onMouseLeave=e=>this._handleMouseLeave(e),this._onWheel=e=>this._handleWheel(e),e.addEventListener("mousemove",this._onMove),e.addEventListener("click",this._onClick),e.addEventListener("dblclick",this._onDblClick),e.addEventListener("contextmenu",this._onContextMenu),e.addEventListener("mousedown",this._onMouseDown),e.addEventListener("mouseup",this._onMouseUp),e.addEventListener("mouseleave",this._onMouseLeave),e.addEventListener("wheel",this._onWheel,{passive:!1})}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();this._host.removeEventListener("mousemove",this._onMove),this._host.removeEventListener("click",this._onClick),this._host.removeEventListener("dblclick",this._onDblClick),this._host.removeEventListener("contextmenu",this._onContextMenu),this._host.removeEventListener("mousedown",this._onMouseDown),this._host.removeEventListener("mouseup",this._onMouseUp),this._host.removeEventListener("mouseleave",this._onMouseLeave),this._host.removeEventListener("wheel",this._onWheel),null!==this._chooseRDialog&&(this._chooseRDialog.close(),this._chooseRDialog=null),gn(this._nextAddCursorEl),this._nextAddCursorEl=null}}_handleMove(e){if(null!==this._panStart){let t=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),i=t.x-this._panStart.origin.x,n=t.y-this._panStart.origin.y;return this._editor.panTo({x:this._panStart.initialOffset.x+i,y:this._panStart.initialOffset.y+n}),void(this._panMoved=!0)}if(null!==this._atomDragState){let t=this._toModel(e),i=t.x-this._atomDragState.pointerDownModel.x,n=t.y-this._atomDragState.pointerDownModel.y,o=[];for(let e of this._atomDragState.atomIds){let t=this._atomDragState.initialPositions.get(e);void 0!==t&&o.push({atomId:e,p:{x:t.x+i,y:t.y+n}})}return this._editor.moveAtoms(o),void(this._atomDragMoved=!0)}let t=this._toModel(e),i=this._tester.test(t),n=i?.atom??null,o=i?.bond??null;if(null!==this._bondStart){this._bondDragMoved=!0;let e=null!==n&&n.id!==this._bondStart.id?n:null;this._editor.fire("bond:preview",{start:this._bondStart,cursor:t,candidate:e,kind:"hbond"===this._editor.getMode()?"hbond":"backbone"})}if(null!==this._hoverAtom&&(null===n||n.id!==this._hoverAtom.id)&&(this._editor.fire("monomer:hover-end",{atom:this._hoverAtom}),this._hoverAtom=null),null!==n&&(null===this._hoverAtom||this._hoverAtom.id!==n.id)&&(this._hoverAtom=n,this._editor.fire("monomer:hover",{atom:n,clientX:e.clientX,clientY:e.clientY,modelX:t.x,modelY:t.y})),null!==this._hoverBond&&(null===o||o.id!==this._hoverBond.id)&&(this._editor.fire("bond:hover-end",{bond:this._hoverBond}),this._hoverBond=null),null!==o&&(null===this._hoverBond||this._hoverBond.id!==o.id)&&(this._hoverBond=o,this._editor.fire("bond:hover",{bond:o,clientX:e.clientX,clientY:e.clientY})),null!==this._dragOrigin){let e=xn(this._dragOrigin,t);this._editor.fire("selection:rectangle-update",{rect:e})}this._updateNextAddCursor(e)}_handleClick(e){if(this._bondDragMoved)return void(this._bondDragMoved=!1);if(this._rectDragHappened)return void(this._rectDragHappened=!1);if(this._panMoved)return void(this._panMoved=!1);if(this._atomDragMoved)return void(this._atomDragMoved=!1);let t=this._toModel(e),i=this._tester.test(t),n=wn(e),o=this._editor.getMode();if("eraser"===o)return void 0!==i?.atom?void this._editor.removeAtom(i.atom):void 0!==i?.bond?void this._editor.removeBond(i.bond):void 0;if(void 0===i?.atom)if(void 0===i?.bond){if(this._addsEnabled()){let e=this._editor.getNextAddSymbol();if(null!==e)return void this._editor.addAtom(t,e.biotype,e.symbol)}!n.shift&&!n.ctrl&&!n.meta&&this._editor.clearSelection()}else this._editor.fire("bond:click",{bond:i.bond,modifiers:n});else{if("select"===o&&!n.ctrl&&!n.shift&&!n.meta){let e=this._editor.getNextAddSymbol();if(null!==e)return i.atom.biotype===e.biotype?void this._editor.replaceMonomer(i.atom,e.symbol):void this._editor.fire("editor:status",{message:`Cannot replace: ${i.atom.biotype} is incompatible with ${e.biotype}`,severity:"warn",durationMs:3e3})}this._editor.fire("monomer:click",{atom:i.atom,modifiers:n,clientX:e.clientX,clientY:e.clientY})}}_handleDblClick(e){let t=this._toModel(e),i=this._tester.test(t),n=wn(e);void 0===i?.atom?null===i&&this._editor.fitToContent():this._editor.fire("monomer:dblclick",{atom:i.atom,modifiers:n})}_handleContextMenu(e){this._enableContextMenu||e.preventDefault();let t=this._toModel(e),i=this._tester.test(t),n=()=>{e.preventDefault()};void 0!==i?.atom?this._editor.fire("monomer:contextmenu",{atom:i.atom,clientX:e.clientX,clientY:e.clientY,preventDefault:n}):void 0!==i?.bond&&this._editor.fire("bond:contextmenu",{bond:i.bond,clientX:e.clientX,clientY:e.clientY,preventDefault:n})}_handleMouseDown(e){if(0!==e.button)return;let t=this._toModel(e),i=this._tester.test(t),n=this._editor.getMode(),o=!0===e.ctrlKey||!0===e.metaKey,r=!0===e.shiftKey;if(void 0!==i?.atom){if("move"===n||"select"===n&&o){let e=this._editor.getSelection(),n=e.atoms.has(i.atom.id)?Array.from(e.atoms):[i.atom.id],o=this._editor.getMol(),r=new Map;for(let e of n){let t=o.atoms.find(t=>t.id===e);void 0!==t&&r.set(e,{x:t.p.x,y:t.p.y})}return this._atomDragState={atomIds:n,pointerDownModel:{x:t.x,y:t.y},initialPositions:r},void(this._atomDragMoved=!1)}return this._bondStart=i.atom,void(this._bondDragMoved=!1)}if(null===i){if("move"===n||"select"===n&&!r){let t=this._editor.getViewport();return this._panStart={origin:this._toViewBox({clientX:e.clientX,clientY:e.clientY}),initialOffset:{x:t.offset.x,y:t.offset.y}},void(this._panMoved=!1)}"select"===n&&r&&(this._dragOrigin=t,this._editor.fire("selection:rectangle-start",{origin:t}))}}_handleMouseUp(e){if(null!==this._panStart)return void(this._panStart=null);if(null!==this._atomDragState)return void(this._atomDragState=null);if(null!==this._bondStart){let t=this._bondStart,i=this._bondDragMoved;this._bondStart=null;let n=this._toModel(e),o=this._tester.test(n)?.atom;if(i&&void 0!==o&&o.id!==t.id){if(this._editor.fire("bond:preview-end",{start:t}),"hbond"===this._editor.getMode()){try{this._editor.addHydrogenBond(t,o)}catch{this._editor.fire("bond:cancel",{start:t})}return}let e=t.bio.chainId===o.bio.chainId&&vn(t,o,this._editor.getMol())?"backbone":"cross-polymer",i=_n(t,o,this._editor.getMol().bonds,e);if("fail"===i.mode)return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("editor:status",{message:i.reason,severity:"error",durationMs:3e3});if("auto"===i.mode){try{this._editor.addBond(t,o,i.r1,i.r2,i.kind)}catch{this._editor.fire("bond:cancel",{start:t})}return}return void this._openChooseR(t,o,e,i.freeR1,i.freeR2)}if(i){let e=this._addsEnabled()?this._editor.getNextAddSymbol():null;if(null!==e){let i;try{i=this._editor.addAtom(n,e.biotype,e.symbol)}catch{return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("bond:preview-end",{start:t})}let o=this._editor.getMol().atoms.find(e=>e.id===t.id);if(void 0===o)return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("bond:preview-end",{start:t});let r=o.bio.chainId===i.bio.chainId&&vn(o,i,this._editor.getMol())?"backbone":"cross-polymer",s=Oi(o,this._editor.getMol().bonds),a=Oi(i,this._editor.getMol().bonds);if(s.includes(2)&&a.includes(1)){try{this._editor.addBond(o,i,2,1,r)}catch{this._editor.fire("bond:cancel",{start:t})}return void this._editor.fire("bond:preview-end",{start:t})}let l=_n(o,i,this._editor.getMol().bonds,r);if("fail"===l.mode)return this._editor.fire("bond:cancel",{start:t}),this._editor.fire("editor:status",{message:l.reason,severity:"error",durationMs:3e3}),void this._editor.fire("bond:preview-end",{start:t});if("auto"===l.mode){try{this._editor.addBond(o,i,l.r1,l.r2,l.kind)}catch{this._editor.fire("bond:cancel",{start:t})}return void this._editor.fire("bond:preview-end",{start:t})}return this._editor.fire("bond:preview-end",{start:t}),void this._openChooseR(o,i,r,l.freeR1,l.freeR2)}return this._editor.fire("bond:cancel",{start:t}),void this._editor.fire("bond:preview-end",{start:t})}return}if(null===this._dragOrigin)return;let t=this._toModel(e),i=xn(this._dragOrigin,t);this._dragOrigin=null;let n=this._tester.testRect(i),o=Di.fromAtomsAndBonds(n.atoms.map(e=>e.id),n.bonds.map(e=>e.id)),r=Di.union(this._editor.getSelection(),o);this._editor.setSelection(r),this._editor.fire("selection:rectangle-end",{rect:i,selection:r}),this._rectDragHappened=!0,r.atoms.size>0&&"select"===this._editor.getMode()&&this._editor.setMode("move")}_handleMouseLeave(e){null!==this._hoverAtom&&(this._editor.fire("monomer:hover-end",{atom:this._hoverAtom}),this._hoverAtom=null),null!==this._hoverBond&&(this._editor.fire("bond:hover-end",{bond:this._hoverBond}),this._hoverBond=null),null!==this._bondStart&&(this._editor.fire("bond:cancel",{start:this._bondStart}),this._editor.fire("bond:preview-end",{start:this._bondStart}),this._bondStart=null,this._bondDragMoved=!1),this._dragOrigin=null,this._panStart=null,this._atomDragState=null,this._panMoved=!1,this._atomDragMoved=!1,gn(this._nextAddCursorEl)}_openChooseR(e,t,i,n,o){null===this._chooseRDialog&&(this._chooseRDialog=new pn(this._editor)),this._chooseRDialog.open(e,t,{freeR1:n,freeR2:o}).then(n=>{if(!this._destroyed){if(null===n)return void this._editor.fire("bond:cancel",{start:e});try{this._editor.addBond(e,t,n.r1,n.r2,i)}catch{this._editor.fire("bond:cancel",{start:e})}}})}_updateNextAddCursor(e){let t=this._editor.getNextAddSymbol(),i=this._editor.getMode(),n=null!==this._hoverAtom,o=null!==this._bondStart||null!==this._dragOrigin||null!==this._panStart||null!==this._atomDragState;if("select"!==i||null===t||n||o)return void(null!==this._nextAddCursorEl&&gn(this._nextAddCursorEl));let r=this._host.ownerDocument;if(null===r)return;null===this._nextAddCursorEl&&(this._nextAddCursorEl=function(e){let t="data-testid";for(let i=0;i<e.body.children.length;i++){let n=e.body.children[i];if(void 0!==n&&n.getAttribute(t)===bn)return n}let i=e.createElement("div");return i.className="hw-next-add-cursor",i.setAttribute(t,bn),i.style.display="none",e.body.appendChild(i),i}(r));let s=this._editor.getService().monomerLib,a=null;for(let e of s.getPolymerTypes()){let i=s.getMonomer(e,t.symbol);if(null!==i){a=i;break}}!function(e,t,i,n,o,r,s){let a=Gt({p:{x:0,y:0},biotype:i},o),l=te(n,i,o.colorTheme).background,h=q(l),d=t.length,c=d<=1?1:Math.min(1,2/d),u=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="-28 -28 56 56" width="56" height="56" class="hw-next-add-cursor__svg" aria-hidden="true"><path d="${a}" fill="${l}" stroke="${l}" stroke-width="5" stroke-linejoin="round" stroke-linecap="round"/><text x="0" y="0" text-anchor="middle" dominant-baseline="central" font-family="Helvetica Neue, Helvetica, Arial, sans-serif" font-size="${o.fontSize*c}" fill="${h}">${function(e){let t="";for(let i=0;i<e.length;i++){let n=e.charAt(i);t+="<"===n?"<":">"===n?">":"&"===n?"&":n}return t}(t)}</text></svg>`;e.innerHTML=u;let p=e.style;p.left=r-28+"px",p.top=s-28+"px",p.display="block"}(this._nextAddCursorEl,t.symbol,t.biotype,a,this._editor._currentTheme(),e.clientX,e.clientY)}_addsEnabled(){return"select"===this._editor.getMode()}_handleWheel(e){let t=!0===e.ctrlKey||!0===e.metaKey;if(e.preventDefault(),t)return void this._wheelPan(e);let i=e.deltaY<0?1.1:1/1.1,n=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),o=this._editor.getViewport(),r=0===o.scale?n:{x:(n.x-o.offset.x)/o.scale,y:(n.y-o.offset.y)/o.scale};this._editor.zoom(i,r)}_wheelPan(e){let t=e.deltaX??0,i=e.deltaY??0;if(0===t&&0===i)return;let n=this._toViewBox({clientX:e.clientX,clientY:e.clientY}),o=this._toViewBox({clientX:e.clientX+t,clientY:e.clientY+i}),r=o.x-n.x,s=o.y-n.y,a=this._editor.getViewport();this._editor.panTo({x:a.offset.x-r,y:a.offset.y-s})}_toModel(e){let t=this._host.querySelector("svg"),i=null!==t?t.querySelector(".hw-content"):null;if(null!==t&&null!==i){let t=yn(i,e.clientX,e.clientY);if(null!==t)return t;let n=this._host.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,s=function(e){if(""===e)return null;let t,i=0,n=0,o=1,r=/(translate|scale)\(([^)]+)\)/g,s=!1;for(;null!==(t=r.exec(e));){s=!0;let e=t[1],r=(t[2]??"").split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e));"translate"===e?(i+=o*(r[0]??0),n+=o*(r[1]??0)):"scale"===e&&(o*=r[0]??1)}return s?{tx:i,ty:n,scale:o}:null}(i.getAttribute("transform")??"");return null!==s?{x:(o-s.tx)/(0===s.scale?1:s.scale),y:(r-s.ty)/(0===s.scale?1:s.scale)}:{x:o,y:r}}let n=this._host.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}_toViewBox(e){let t=this._host.querySelector("svg");if(null!==t){let i=yn(t,e.clientX,e.clientY);if(null!==i)return i;let n=this._host.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,s=function(e){if(null===e||""===e)return null;let t=e.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e));if(t.length<4)return null;let i=t[2],n=t[3];return i<=0||n<=0?null:{w:i,h:n}}(t.getAttribute("viewBox"));return null!==s&&n.width>0&&n.height>0?{x:o*(s.w/n.width),y:r*(s.h/n.height)}:{x:o,y:r}}let i=this._host.getBoundingClientRect();return{x:e.clientX-i.left,y:e.clientY-i.top}}};function _n(e,t,i,n){let o=Fi(e),r=Fi(t);if(0===o||0===r)return{mode:"auto",r1:2,r2:1,kind:n};let s=Oi(e,i),a=Oi(t,i);return 0===s.length?{mode:"fail",reason:`${e.symbol} has no free R-groups (max ${o}).`}:0===a.length?{mode:"fail",reason:`${t.symbol} has no free R-groups (max ${r}).`}:s.includes(2)&&a.includes(1)&&(1===s.length||1===a.length)?{mode:"auto",r1:2,r2:1,kind:n}:1===s.length&&1===a.length?{mode:"auto",r1:s[0],r2:a[0],kind:n}:{mode:"choose",freeR1:s,freeR2:a}}function yn(e,t,i){let n=e;if("function"!=typeof n.getScreenCTM)return null;let o=n.getScreenCTM();if(null===o)return null;let r=null;try{let e=o;"function"==typeof e.inverse&&(r=e.inverse())}catch{return null}if(null===r)return null;let s=n.ownerSVGElement;if(null!=s&&"function"==typeof s.createSVGPoint){let e=s.createSVGPoint();e.x=t,e.y=i;let n=e.matrixTransform(r);return{x:n.x,y:n.y}}let a=r;return{x:a.a*t+a.c*i+a.e,y:a.b*t+a.d*i+a.f}}function vn(e,t,i){if(e.bio.chainId!==t.bio.chainId)return!1;let n=i.chains.find(t=>t.id===e.bio.chainId);if(void 0===n)return!1;let o=-1,r=-1;for(let i=0;i<n.backboneAtoms.length;i++){let s=n.backboneAtoms[i];s.id===e.id&&(o=i),s.id===t.id&&(r=i)}return!(o<0||r<0)&&1===Math.abs(o-r)}function wn(e){return{shift:!0===e.shiftKey,alt:!0===e.altKey,ctrl:!0===e.ctrlKey,meta:!0===e.metaKey}}function xn(e,t){return{x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)}}var Cn=class{constructor(e,t,i){this._destroyed=!1,this._host=e,this._editor=t,this._enabled=!1!==i?.enableKeyboard,this._enabled&&null===e.getAttribute("tabindex")&&e.setAttribute("tabindex","0"),this._onKey=e=>this._handleKey(e),e.addEventListener("keydown",this._onKey)}destroy(){this._destroyed||(this._destroyed=!0,this._host.removeEventListener("keydown",this._onKey))}_handleKey(e){if(!this._enabled)return;let t=this._classify(e),i={shift:!0===(n=e).shiftKey,alt:!0===n.altKey,ctrl:!0===n.ctrlKey,meta:!0===n.metaKey};var n;if(null===t)return void this._editor.fire("key:unhandled",{key:e.key,modifiers:i,preventDefault:()=>e.preventDefault()});let o=!1;this._editor.fire("key:command",{command:t,preventDefault:()=>{o=!0,e.preventDefault()}}),!o&&(e.preventDefault(),"clearSelection"!==t&&(e.stopPropagation(),e.stopImmediatePropagation?.()),this._execute(t))}_classify(e){let t=e.key,i=e.ctrlKey||e.metaKey;return"Delete"===t||"Backspace"===t?"delete":!i||"z"!==t&&"Z"!==t||e.shiftKey?i&&(("z"===t||"Z"===t)&&e.shiftKey||"y"===t||"Y"===t)?"redo":!i||"a"!==t&&"A"!==t?!i||"c"!==t&&"C"!==t?!i||"v"!==t&&"V"!==t?!i||"x"!==t&&"X"!==t?"Escape"===t?"clearSelection":"+"===t||"="===t?"zoomIn":"-"===t||"_"===t?"zoomOut":"0"===t?"fitToContent":"ArrowUp"===t?"nudgeUp":"ArrowDown"===t?"nudgeDown":"ArrowLeft"===t?"nudgeLeft":"ArrowRight"===t?"nudgeRight":null:"cut":"paste":"copy":"selectAll":"undo"}_execute(e){switch(e){case"delete":return void this._editor.deleteSelection();case"undo":return void this._editor.undo();case"redo":return void this._editor.redo();case"selectAll":return void this._editor.selectAll();case"clearSelection":return void this._editor.clearSelection();case"zoomIn":return void this._editor.zoom(1.1);case"zoomOut":return void this._editor.zoom(1/1.1);case"fitToContent":return void this._editor.fitToContent();case"nudgeUp":return void this._editor.nudgeSelection(0,-5);case"nudgeDown":return void this._editor.nudgeSelection(0,5);case"nudgeLeft":return void this._editor.nudgeSelection(-5,0);case"nudgeRight":return void this._editor.nudgeSelection(5,0);case"copy":{let e=this._editor.getHelm();return void this._editor.fire("clipboard:copy",{format:"helm",payload:e})}case"cut":{let e=this._editor.getHelm();return this._editor.fire("clipboard:copy",{format:"helm",payload:e}),void this._editor.deleteSelection()}case"paste":return void this._editor.fire("clipboard:paste",{format:"helm"});default:return}}},kn=class{constructor(e,t){this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._destroyed=!1,this._unsubs=[],this._host=e,this._editor=t,this._tester=new Yi(t.getMol(),t._currentTheme()),this._unsubs.push(t.on("mol:changed",()=>{this._tester=new Yi(this._editor.getMol(),this._editor._currentTheme())})),this._onDragOver=e=>this._handleDragOver(e),this._onDrop=e=>this._handleDrop(e),this._onDragStart=e=>this._handleDragStart(e),this._onDragEnd=e=>this._handleDragEnd(e),this._onDragEnter=e=>this._handleDragEnter(e),this._onDragLeave=e=>this._handleDragLeave(e),e.addEventListener("dragover",this._onDragOver),e.addEventListener("drop",this._onDrop),e.addEventListener("dragstart",this._onDragStart),e.addEventListener("dragend",this._onDragEnd),e.addEventListener("dragenter",this._onDragEnter),e.addEventListener("dragleave",this._onDragLeave)}startPaletteDrag(e,t){this._currentPaletteSymbol=e,this._currentPaletteBiotype=t,this._editor.fire("dnd:start",{source:"palette",symbol:e})}cancelPaletteDrag(){null!==this._currentPaletteSymbol&&(this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._editor.fire("dnd:cancel",{source:"palette"}))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();this._host.removeEventListener("dragover",this._onDragOver),this._host.removeEventListener("drop",this._onDrop),this._host.removeEventListener("dragstart",this._onDragStart),this._host.removeEventListener("dragend",this._onDragEnd),this._host.removeEventListener("dragenter",this._onDragEnter),this._host.removeEventListener("dragleave",this._onDragLeave)}}_activePaletteSymbol(e){if(null!==this._currentPaletteSymbol&&null!==this._currentPaletteBiotype)return{symbol:this._currentPaletteSymbol,biotype:this._currentPaletteBiotype};let t=e.dataTransfer;if(null==t)return null;try{let e="function"==typeof t.getData?t.getData("application/x-hwe-monomer"):"";if(""===e)return null;let i=JSON.parse(e);return"string"!=typeof i.symbol||"string"!=typeof i.biotype?null:{symbol:i.symbol,biotype:i.biotype}}catch{return null}}_handleDragEnter(e){if(null!==this._activePaletteSymbol(e)&&(e.preventDefault(),null!==e.dataTransfer&&void 0!==e.dataTransfer))try{e.dataTransfer.dropEffect="copy"}catch{}}_handleDragLeave(e){}_handleDragOver(e){if(null===this._activePaletteSymbol(e))return;if(e.preventDefault(),null!==e.dataTransfer&&void 0!==e.dataTransfer)try{e.dataTransfer.dropEffect="copy"}catch{}let t=this._toModel(e),i=this._tester.test(t),n=void 0!==i?.atom?i.atom:void 0!==i?.bond?i.bond:void 0,o={clientX:e.clientX,clientY:e.clientY};void 0!==n&&(o.target=n),this._editor.fire("dnd:over",o)}_handleDrop(e){let t=this._activePaletteSymbol(e);if(null===t)return;e.preventDefault();let{symbol:i,biotype:n}=t,o=this._toModel(e),r=this._tester.test(o),s=void 0!==r?.atom?r.atom:void 0!==r?.bond?r.bond:void 0,a={symbol:i,biotype:n,clientX:e.clientX,clientY:e.clientY};void 0!==s&&(a.target=s),this._editor.fire("dnd:drop",a),void 0!==r?.atom?this._editor.replaceMonomer(r.atom,i):this._editor.addAtom(o,n,i),this._currentPaletteSymbol=null,this._currentPaletteBiotype=null}_handleDragStart(e){this._editor.fire("dnd:start",{source:"canvas"})}_handleDragEnd(e){null!==this._currentPaletteSymbol&&(this._currentPaletteSymbol=null,this._currentPaletteBiotype=null,this._editor.fire("dnd:cancel",{source:"palette"}))}_toModel(e){let t=this._host.querySelector("svg"),i=null!==t?t.querySelector(".hw-content"):null;if(null!==t&&null!==i){let t=function(e,t,i){let n=e;if("function"!=typeof n.getScreenCTM)return null;let o=n.getScreenCTM();if(null===o)return null;let r=null;try{let e=o;"function"==typeof e.inverse&&(r=e.inverse())}catch{return null}if(null===r)return null;let s=n.ownerSVGElement;if(null!=s&&"function"==typeof s.createSVGPoint){let e=s.createSVGPoint();e.x=t,e.y=i;let n=e.matrixTransform(r);return{x:n.x,y:n.y}}let a=r;return{x:a.a*t+a.c*i+a.e,y:a.b*t+a.d*i+a.f}}(i,e.clientX,e.clientY);if(null!==t)return t;let n=this._host.getBoundingClientRect(),o=e.clientX-n.left,r=e.clientY-n.top,s=function(e){if(""===e)return null;let t,i=0,n=0,o=1,r=/(translate|scale)\(([^)]+)\)/g,s=!1;for(;null!==(t=r.exec(e));){s=!0;let e=t[1],r=(t[2]??"").split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e));"translate"===e?(i+=o*(r[0]??0),n+=o*(r[1]??0)):"scale"===e&&(o*=r[0]??1)}return s?{tx:i,ty:n,scale:o}:null}(i.getAttribute("transform")??"");return null!==s?{x:(o-s.tx)/(0===s.scale?1:s.scale),y:(r-s.ty)/(0===s.scale?1:s.scale)}:{x:o,y:r}}let n=this._host.getBoundingClientRect();return{x:e.clientX-n.left,y:e.clientY-n.top}}},En=class{constructor(e,t){this._modal=null,this._atom=null,this._editor=e;let i=e._getHost();if(null===i)throw new Error("AtomPropsDialog: editor has no host element.");this._doc=t?.documentImpl??Xi(i)}get isOpen(){return null!==this._modal&&this._modal.isOpen}open(e){this.close(),this._atom=e;let t=this._editor._getHost();if(null===t)return;let i=new hn(t,{documentImpl:this._doc,title:"Monomer Properties",testId:"atom-props"});this._modal=i;let n=Qi(this._doc,"div",{class:"hw-modal__info"},[`Position ${e.bio.continuousId} in ${e.bio.chainId}`]),o=dn(this._doc,"Symbol",e.symbol,"atom-props-symbol"),r=dn(this._doc,"Annotation",e.bio.annotation??"","atom-props-annotation"),s=un(this._doc,"atom-props"),a=()=>this._commit(o.input.value,r.input.value);s.ok.addEventListener("click",a),s.cancel.addEventListener("click",()=>this.close()),i.setPrimaryAction(a),i.body.appendChild(n),i.body.appendChild(o.row),i.body.appendChild(r.row),i.body.appendChild(s.row),i.open()}close(){null!==this._modal&&(this._modal.close(),this._modal=null),this._atom=null}_commit(e,t){let i=this._atom;if(null===i)return void this.close();let n=e.trim(),o=(i.bio.annotation??"")!==t;if(n.length>0&&n!==i.symbol&&this._editor.replaceMonomer(i,n),o){let e=new qi(this._editor.getMol()),n={};n.tag=""===t?void 0:t,e.updateAtom(i.id,n);let{mol:o}=e.commit();this._editor.setMol(o);let r=o.atoms.find(e=>e.id===i.id);if(void 0!==r){let e={atom:r};void 0!==i.bio.annotation&&(e.oldAnnotation=i.bio.annotation),""!==t&&(e.newAnnotation=t),this._editor.fire("monomer:annotate",e)}}this.close()}},Bn=class{constructor(e,t){this._modal=null,this._bond=null,this._editor=e;let i=e._getHost();if(null===i)throw new Error("BondPropsDialog: editor has no host element.");this._doc=t?.documentImpl??Xi(i)}get isOpen(){return null!==this._modal&&this._modal.isOpen}open(e){this.close(),this._bond=e;let t=this._editor._getHost();if(null===t)return;let i=new hn(t,{documentImpl:this._doc,title:"Bond Properties",testId:"bond-props"});this._modal=i;let n=Qi(this._doc,"div",{class:"hw-modal__info"},[`Kind: ${e.kind}`]),o=this._buildAtomsPreviewRow(e),r="numeric"===e.r1.kind,s="numeric"===e.r2.kind,a=r&&s,l=this._editor.getMol().bonds,h=a?Sn(e.r1,e.a1,l):[],d=a?Sn(e.r2,e.a2,l):[],c=null,u=null;if(a){let t=String(e.r1.r),i=String(e.r2.r);c=cn(this._doc,`R-group on ${e.a1.symbol} (${e.a1.bio.chainId}:${e.a1.bio.positionInChain})`,h,t,"bond-props-r1"),u=cn(this._doc,`R-group on ${e.a2.symbol} (${e.a2.bio.chainId}:${e.a2.bio.positionInChain})`,d,i,"bond-props-r2")}let p=un(this._doc,"bond-props"),m=()=>{let t=null!==c?Number(Mn(c.select,e.r1.r)):null,i=null!==u?Number(Mn(u.select,e.r2.r)):null;this._commit(t,i)};p.ok.addEventListener("click",m),p.cancel.addEventListener("click",()=>this.close()),i.setPrimaryAction(m),i.body.appendChild(n),null!==o&&i.body.appendChild(o),null!==c&&i.body.appendChild(c.row),null!==u&&i.body.appendChild(u.row),i.body.appendChild(p.row),i.open()}_buildAtomsPreviewRow(e){let t=this._rdkit(),i=this._buildAtomCell(e.a1,t,"bond-props-atom-a1"),n=this._buildAtomCell(e.a2,t,"bond-props-atom-a2"),o=Qi(this._doc,"div",{class:"hw-bond-props__bond-arrow"},["↔"]);return Qi(this._doc,"div",{class:"hw-bond-props__atoms","data-testid":"bond-props-atoms"},[i,o,n])}_buildAtomCell(e,t,i){let n=e.monomer?.name??e.symbol,o=e.symbol===n?e.symbol:`${e.symbol} — ${n}`,r=Qi(this._doc,"div",{class:"hw-bond-props__atom-label"},[o]),s={class:"hw-bond-props__atom-rdkit","data-testid":`${i}-rdkit`},a=Qi(this._doc,"div",s),l=e.monomer?.smiles;if(null!==t&&void 0!==l&&""!==l){let e=Zi(t,l,220,140);null!==e&&""!==e&&(a.innerHTML=e)}return Qi(this._doc,"div",{class:"hw-bond-props__atom","data-testid":i},[r,a])}_rdkit(){let e=this._editor.getService().options?.rdkitModule;return e??null}close(){null!==this._modal&&(this._modal.close(),this._modal=null),this._bond=null}_commit(e,t){let i=this._bond;if(null===i)return void this.close();let n="numeric"===i.r1.kind?i.r1.r:null,o="numeric"===i.r2.kind?i.r2.r:null;if(null===e||null===t||e===n&&t===o)this.close();else{if(null!==e&&null!==t){let r=i.kind,s=i.a1,a=i.a2;this._editor.removeBond(i);try{this._editor.addBond(s,a,e,t,r)}catch(e){if(null!==n&&null!==o)try{this._editor.addBond(s,a,n,o,i.kind)}catch{}}}this.close()}}};function Sn(e,t,i){let n=t.monomer?.rgroups;if(void 0===n||0===n.length)return[{value:"1",label:"R1"},{value:"2",label:"R2"},{value:"3",label:"R3"}];let o=new Set(Oi(t,i));o.add(e.r);let r=Array.from(o).sort((e,t)=>e-t),s=[];for(let e of r){let t=n[e-1];if(void 0===t)continue;let i=void 0!==t.capGroupName&&""!==t.capGroupName?` (${t.capGroupName})`:"";s.push({value:String(e),label:`${t.label}${i}`})}return s}function Mn(e,t){let i=e.value;if("string"==typeof i&&i.length>0){let e=Number(i);if(Number.isFinite(e)&&e>=1)return e}let n=e.querySelectorAll("option");for(let e of Array.from(n))if(null!==e.getAttribute("selected")){let t=e.getAttribute("value")??"",i=Number(t);if(Number.isFinite(i)&&i>=1)return i}return t}var Tn=class{constructor(e,t){this._modal=null,this._result=null,this._findInput=null,this._replaceInput=null,this._matches=[],this._cursor=-1,this._editor=e;let i=e._getHost();if(null===i)throw new Error("FindReplaceDialog: editor has no host element.");this._doc=t?.documentImpl??Xi(i)}get isOpen(){return null!==this._modal&&this._modal.isOpen}open(){this.close();let e=this._editor._getHost();if(null===e)return;let t=new hn(e,{documentImpl:this._doc,title:"Find / Replace",testId:"find-replace"});this._modal=t;let i=dn(this._doc,"Find","","find-replace-find"),n=dn(this._doc,"Replace with","","find-replace-replace");this._findInput=i.input,this._replaceInput=n.input;let o=this._doc.createElement("button");o.setAttribute("class","hw-modal__find-next"),o.setAttribute("type","button"),o.setAttribute("data-testid","find-replace-next"),o.appendChild(this._doc.createTextNode("Find Next")),o.addEventListener("click",()=>this._findNext());let r=this._doc.createElement("button");r.setAttribute("class","hw-modal__replace"),r.setAttribute("type","button"),r.setAttribute("data-testid","find-replace-replace-one"),r.appendChild(this._doc.createTextNode("Replace")),r.addEventListener("click",()=>this._replaceOne());let s=this._doc.createElement("button");s.setAttribute("class","hw-modal__replace-all"),s.setAttribute("type","button"),s.setAttribute("data-testid","find-replace-replace-all"),s.appendChild(this._doc.createTextNode("Replace All")),s.addEventListener("click",()=>this._replaceAll());let a=this._doc.createElement("button");a.setAttribute("class","hw-modal__cancel"),a.setAttribute("type","button"),a.setAttribute("data-testid","find-replace-close"),a.appendChild(this._doc.createTextNode("Close")),a.addEventListener("click",()=>this.close());let l=Qi(this._doc,"div",{class:"hw-modal__actions"},[o,r,s,a]),h=Qi(this._doc,"div",{class:"hw-modal__result","data-testid":"find-replace-result"},["0 matches"]);this._result=h,t.setPrimaryAction(()=>this._findNext()),t.body.appendChild(i.row),t.body.appendChild(n.row),t.body.appendChild(l),t.body.appendChild(h),t.open()}close(){null!==this._modal&&(this._modal.close(),this._modal=null),this._result=null,this._findInput=null,this._replaceInput=null,this._matches=[],this._cursor=-1}_findNext(){let e=this._findInput?.value.trim()??"";if(""===e)return void this._setResultText("Enter a symbol to find");let t=this._editor.findMonomers(e);if(this._matches=t.map(e=>e.id),0===this._matches.length)return this._cursor=-1,this._editor.setHighlights([]),void this._setResultText("No matches");this._cursor=(this._cursor+1)%this._matches.length;let i=this._matches[this._cursor];void 0!==i&&this._editor.setHighlights([i]),this._setResultText(`${this._cursor+1} / ${this._matches.length} matches`)}_replaceOne(){let e=this._findInput?.value.trim()??"",t=this._replaceInput?.value.trim()??"";if(""===e||""===t)return void this._setResultText("Both Find and Replace fields are required");if(0===this._matches.length||this._cursor<0)return void this._findNext();let i=this._matches[this._cursor];if(void 0===i)return;let n=this._editor.getMol().atoms.find(e=>e.id===i);if(void 0!==n)if(this._editor.replaceMonomer(n,t),this._matches.splice(this._cursor,1),0===this._matches.length)this._cursor=-1,this._editor.setHighlights([]),this._setResultText("Replaced; no further matches");else{this._cursor=this._cursor%this._matches.length;let e=this._matches[this._cursor];void 0!==e&&this._editor.setHighlights([e]),this._setResultText(`${this._matches.length} matches remaining`)}}_replaceAll(){let e=this._findInput?.value.trim()??"",t=this._replaceInput?.value.trim()??"";if(""===e||""===t)return void this._setResultText("Both Find and Replace fields are required");let i=this._editor.replaceMonomers(e,t);this._matches=[],this._cursor=-1,this._editor.setHighlights([]),this._setResultText(`${i} replacement${1===i?"":"s"} made`)}_setResultText(e){if(null!==this._result){for(;null!==this._result.firstChild;)this._result.removeChild(this._result.firstChild);this._result.appendChild(this._doc.createTextNode(e))}}},In=Object.freeze(new Set),Ln=class{constructor(e,t){if(this._events=new Ui,this._destroyed=!1,this._view=null,this._pointer=null,this._keyboard=null,this._dnd=null,this._atomDialog=null,this._bondDialog=null,this._findReplaceDialog=null,this._viewBootstrapped=!1,this._mode="select",this._nextAdd=null,this._lastAction=null,this._lastTripletSugarPos=null,void 0===t.service||null===t.service)throw new TypeError("HelmEditor: options.service is required");this._host=e,this._service=t.service,this._options=Object.freeze({...t}),this._mol=b(),this._selection=Di.empty(),this._highlights=In,this._theme=t.service.theme??Dt,this._viewport={scale:1,offset:{x:0,y:0}},this._viewOnly=t.viewOnly??!1,this._history=new Ki({maxEntries:100}),this._history.push({mol:this._mol,label:"initial"}),this._libUnsub=this._service.monomerLib.onChanged.subscribe(e=>{let t=this._service.monomerLib,i="number"==typeof t.version?t.version:0,n="reload"===e.type?"replace":"update";this._events.fire("monomer-lib:change",{source:this._service.monomerLib.source,version:i,reason:n})}),void 0!==t.initialHelm&&this.setHelm(t.initialHelm),this._bootstrapWaveB()}_bootstrapWaveB(){if(this._viewBootstrapped||null===this._host)return;let e=this._resolveDocument(this._host);if(null===e)return;this._viewBootstrapped=!0;let t={documentImpl:e};void 0!==this._options.width&&(t.width=this._options.width),void 0!==this._options.height&&(t.height=this._options.height),this._view=new sn(this._host,this,t),!0!==this._viewOnly&&(this._pointer=new An(this._host,this,{enableContextMenu:this._options.enableContextMenu??!0})),!1!==this._options.enableKeyboard&&(this._keyboard=new Cn(this._host,this,{enableKeyboard:!0})),!1!==this._options.enableDragDrop&&(this._dnd=new kn(this._host,this)),this._events.on("monomer:hover",e=>{this.setHighlights([e.atom.id])}),this._events.on("monomer:hover-end",()=>{this.clearHighlights()}),this._events.on("monomer:click",e=>{let t=e.modifiers;!0!==t.ctrl&&!0!==t.meta?!0!==t.shift?this.setSelection(Di.fromAtoms([e.atom.id])):this.setSelection(Di.union(this._selection,Di.fromAtoms([e.atom.id]))):this.setSelection(Di.toggle(this._selection,{kind:"atom",id:e.atom.id}))})}_resolveDocument(e){let t=e.ownerDocument;if(null!=t)return t;let i=globalThis;return void 0!==i.document?i.document:null}destroy(){this._destroyed||(this._destroyed=!0,null!==this._atomDialog&&(this._atomDialog.close(),this._atomDialog=null),null!==this._bondDialog&&(this._bondDialog.close(),this._bondDialog=null),null!==this._findReplaceDialog&&(this._findReplaceDialog.close(),this._findReplaceDialog=null),null!==this._dnd&&(this._dnd.destroy(),this._dnd=null),null!==this._keyboard&&(this._keyboard.destroy(),this._keyboard=null),null!==this._pointer&&(this._pointer.destroy(),this._pointer=null),null!==this._view&&(this._view.destroy(),this._view=null),this._libUnsub(),this._events.clear(),this._history.clear())}resize(e,t){this._ensureLive(),null!==this._view&&this._view.resize(e,t),this._events.fire("view:resize",{width:e,height:t})}redraw(){this._ensureLive(),null===this._view?this._events.fire("render:skip",{reason:"no-view-mounted"}):this._view.redraw()}setHelm(e,t){this._ensureLive();let i=t?.canonicalize??this._options.canonicalize??!1,n=this._service.parse(e,{mode:"lenient"}),o=n.diagnostics;o.filter(e=>"error"===e.severity).length>0&&this._events.fire("helm:parse-error",{helm:e,diagnostics:o});for(let e of o)"error"===e.severity?this._events.fire("validation:error",{diagnostic:e}):"warning"===e.severity&&this._events.fire("validation:warning",{diagnostic:e});let r=n.mol;if(i){let t=this._service.canonicalize(e);r=this._service.parse(t,{mode:"lenient"}).mol}let s=Et(r,this._layoutOptions());return this._replaceMol(s,"setHelm","api"),{mol:s,diagnostics:o}}getHelm(e){this._ensureLive();let t={};return void 0!==e?.canonicalize&&(t.canonicalize=e.canonicalize),void 0!==e?.includeHighlights&&(t.includeHighlights=e.includeHighlights),this._service.serialize(this._mol,t)}setMol(e){this._ensureLive(),this._replaceMol(e,"setMol","api")}getMol(){return this._mol}getService(){return this._service}getSelection(){return this._selection}setSelection(e){if(this._ensureLive(),Di.equals(this._selection,e))return;let t=Di.difference(e,this._selection),i=Di.difference(this._selection,e);this._selection=e,this._events.fire("selection:change",{selection:e,addedAtomIds:t.atoms,removedAtomIds:i.atoms,addedBondIds:t.bonds,removedBondIds:i.bonds})}selectAll(){this._ensureLive();let e=this._mol.atoms.map(e=>e.id),t=this._mol.bonds.map(e=>e.id);this.setSelection(Di.fromAtomsAndBonds(e,t))}clearSelection(){this._ensureLive(),!this._selection.isEmpty&&this.setSelection(Di.empty())}setHighlights(e){this._ensureLive();let t=new Set(e);this._highlights=t,this._events.fire("highlight:change",{atomIds:t,bondIds:In})}clearHighlights(){this._ensureLive(),0!==this._highlights.size&&(this._highlights=In,this._events.fire("highlight:change",{atomIds:In,bondIds:In}))}addAtom(e,t,i){this._ensureLive();let n=new qi(this._mol),o=n.addAtom({p:e,biotype:t,symbol:i}),{mol:r}=n.commit(),s=oe(r,this._service.monomerLib,{mode:"lenient"}).mol;this._replaceMol(s,`addAtom:${i}`,"api");let a=g(s,o);if(void 0===a)throw new Error("HelmEditor.addAtom: lost atom after commit");return this._events.fire("monomer:add",{atom:a,source:"api"}),a}removeAtom(e){this._ensureLive();let t="number"==typeof e?e:e.id,i=g(this._mol,t);if(void 0===i)return;let n=new qi(this._mol);n.removeAtom(t);let{mol:o}=n.commit();this._replaceMol(o,`removeAtom:${i.symbol}`,"api"),this._events.fire("monomer:remove",{atom:i,source:"api"})}addBond(e,t,i,n,r){let s,a;this._ensureLive();try{this._validateAddBondConstraints(e,t,i,n);let o=r??"backbone",l=this._maybeMergeForLinearExtend(e,t,i,n,o);if(null!==l)({id:s,mol:a}=l);else{let o=new qi(this._mol);s=o.addBond({a1:e.id,a2:t.id,kind:r??"backbone",r1:{kind:"numeric",r:i},r2:{kind:"numeric",r:n}}),({mol:a}=o.commit())}}catch(r){let s=r instanceof o?r.message:this._friendlyBondError(r instanceof Error?r.message:String(r),e,t,i,n);throw this._events.fire("editor:status",{message:`Could not add bond: ${s}`,severity:"error",durationMs:3e3}),r}this._replaceMol(a,"addBond","api");let l=A(a,s);if(void 0===l)throw new Error("HelmEditor.addBond: lost bond after commit");return this._events.fire("bond:add",{bond:l,source:"api"}),l}_maybeMergeForLinearExtend(e,t,i,n,o){if(e.bio.chainId===t.bio.chainId||"backbone"!==o&&"cross-polymer"!==o)return null;let r=this._mol.chains.find(t=>t.id===e.bio.chainId),s=this._mol.chains.find(e=>e.id===t.bio.chainId);if(void 0===r||void 0===s||r.polymerType!==s.polymerType||r.polymerType===B.CHEM||r.polymerType===B.BLOB)return null;if(2===i&&1===n){let i=r.backboneAtoms[r.backboneAtoms.length-1],n=s.backboneAtoms[0];if(void 0!==i&&void 0!==n&&i.id===e.id&&n.id===t.id)return this._mergeChains(r,s,o)}if(1===i&&2===n){let i=r.backboneAtoms[0],n=s.backboneAtoms[s.backboneAtoms.length-1];if(void 0!==i&&void 0!==n&&i.id===e.id&&n.id===t.id)return this._mergeChains(s,r,o)}return null}_mergeChains(e,t,i){let n=e.backboneAtoms.length,o=new Set;for(let e of t.backboneAtoms)o.add(e.id),void 0!==e.branchAtom&&o.add(e.branchAtom.id);let r=new Map,s=n;for(let i of t.backboneAtoms){s+=1;let t={...i,bio:{...i.bio,chainId:e.id,positionInChain:s}};if(r.set(i.id,t),void 0!==i.branchAtom){let t=i.branchAtom,n={...t,bio:{...t.bio,chainId:e.id,positionInChain:s}};r.set(t.id,n)}}for(let e of t.backboneAtoms){let t=r.get(e.id);if(void 0===t||void 0===e.branchAtom)continue;let i=r.get(e.branchAtom.id);void 0!==i&&(t.branchAtom=i)}for(let e of this._mol.atoms)r.has(e.id)||r.set(e.id,e);let a=0;for(let e of this._mol.atoms)e.id>a&&(a=e.id);for(let e of this._mol.bonds)e.id>a&&(a=e.id);let l=a+1,h={id:l,a1:r.get(e.backboneAtoms[e.backboneAtoms.length-1].id),a2:r.get(t.backboneAtoms[0].id),kind:"backbone",r1:{kind:"numeric",r:2},r2:{kind:"numeric",r:1}},d=[];for(let e of this._mol.bonds){let t=r.get(e.a1.id)??e.a1,i=r.get(e.a2.id)??e.a2;t===e.a1&&i===e.a2?d.push(e):d.push({...e,a1:t,a2:i})}d.push(h);let c=[],u=[...e.backboneAtoms];for(let e of t.backboneAtoms)u.push(r.get(e.id));for(let i of this._mol.chains)if(i.id!==t.id)if(i.id===e.id){let e=i.bonds.map(e=>{let t=r.get(e.a1.id)??e.a1,i=r.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}});for(let i of t.bonds){let t=r.get(i.a1.id)??i.a1,n=r.get(i.a2.id)??i.a2;e.push(t===i.a1&&n===i.a2?i:{...i,a1:t,a2:n})}e.push(h),c.push({id:i.id,polymerType:i.polymerType,backboneAtoms:u,bonds:e,...void 0!==i.annotation?{annotation:i.annotation}:{}})}else{let e=i.backboneAtoms.map(e=>r.get(e.id)??e),t=i.bonds.map(e=>{let t=r.get(e.a1.id)??e.a1,i=r.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}});c.push({id:i.id,polymerType:i.polymerType,backboneAtoms:e,bonds:t,...void 0!==i.annotation?{annotation:i.annotation}:{}})}let p={atoms:this._mol.atoms.map(e=>r.get(e.id)??e),bonds:d,chains:c,groups:this._mol.groups,annotations:this._mol.annotations};return p=this._refreshContinuousIdsLocal(p),{id:l,mol:p}}_refreshContinuousIdsLocal(e){let t=M(e),i=new Map;for(let n of e.atoms){let e=t.get(n.id);void 0!==e&&e!==n.bio.continuousId?i.set(n.id,{...n,bio:{...n.bio,continuousId:e}}):i.set(n.id,n)}for(let t of e.atoms){if(void 0===t.branchAtom)continue;let e=i.get(t.id),n=i.get(t.branchAtom.id);void 0===e||void 0===n||(e.branchAtom=n)}let n=e.bonds.map(e=>{let t=i.get(e.a1.id)??e.a1,n=i.get(e.a2.id)??e.a2;return t===e.a1&&n===e.a2?e:{...e,a1:t,a2:n}}),o=new Map;for(let e of n)o.set(e.id,e);let r=e.chains.map(e=>{let t=e.backboneAtoms.map(e=>i.get(e.id)??e),n=e.bonds.map(e=>o.get(e.id)??e);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:n,...void 0!==e.annotation?{annotation:e.annotation}:{}}});return{atoms:e.atoms.map(e=>i.get(e.id)??e),bonds:n,chains:r,groups:e.groups,annotations:e.annotations}}_friendlyBondError(e,t,i,n,o){return e.includes("duplicate bond")?`bond ${t.symbol}:R${n} ↔ ${i.symbol}:R${o} already exists`:e.includes("does not exist")?"one of the endpoint atoms is missing":e}_validateAddBondConstraints(e,t,i,n){let r=this._mol.bonds,s=Fi(e);if(s>0&&(i<1||i>s))throw new o("rgroup-not-on-monomer",`R-group R${i} is not defined on monomer '${e.symbol}' (has R1..R${s})`,{atomId:e.id,requested:i,total:s});let a=Fi(t);if(a>0&&(n<1||n>a))throw new o("rgroup-not-on-monomer",`R-group R${n} is not defined on monomer '${t.symbol}' (has R1..R${a})`,{atomId:t.id,requested:n,total:a});if(s>0){let t=zi(e,r).find(e=>e.rNumber===i);if(void 0!==t){let n="r1"===t.side?t.bond.a2:t.bond.a1;throw new o("rgroup-already-bonded",`R-group R${i} on '${e.symbol}' is already bonded to '${n.symbol}' (${n.bio.chainId}:${n.bio.positionInChain})`,{atomId:e.id,requested:i,conflictingBondId:t.bond.id})}}if(a>0){let e=zi(t,r).find(e=>e.rNumber===n);if(void 0!==e){let i="r1"===e.side?e.bond.a2:e.bond.a1;throw new o("rgroup-already-bonded",`R-group R${n} on '${t.symbol}' is already bonded to '${i.symbol}' (${i.bio.chainId}:${i.bio.positionInChain})`,{atomId:t.id,requested:n,conflictingBondId:e.bond.id})}}for(let s of r){if("numeric"!==s.r1.kind||"numeric"!==s.r2.kind)continue;let r=s.a1.id===e.id&&s.a2.id===t.id&&s.r1.r===i&&s.r2.r===n,a=s.a1.id===t.id&&s.a2.id===e.id&&s.r1.r===n&&s.r2.r===i;if(r||a)throw new o("duplicate-bond",`bond ${e.symbol}:R${i} ↔ ${t.symbol}:R${n} already exists`,{atomId:e.id,bondId:s.id})}}_freeRgroupsOn(e){return Oi(e,this._mol.bonds)}addHydrogenBond(e,t){this._ensureLive();let i=new qi(this._mol),n={kind:"pair"},o=i.addBond({a1:e.id,a2:t.id,kind:"hbond",r1:n,r2:n}),{mol:r}=i.commit();this._replaceMol(r,"addHydrogenBond","api");let s=A(r,o);if(void 0===s)throw new Error("HelmEditor.addHydrogenBond: lost bond after commit");return this._events.fire("bond:add",{bond:s,source:"api"}),s}removeBond(e){this._ensureLive();let t="number"==typeof e?e:e.id,i=A(this._mol,t);if(void 0===i)return;let n=new qi(this._mol);n.removeBond(t);let{mol:o}=n.commit();this._replaceMol(o,"removeBond","api"),this._events.fire("bond:remove",{bond:i,source:"api"})}replaceMonomer(e,t){this._ensureLive();let i=g(this._mol,e.id);if(void 0===i)return;let n=i.symbol;if(n===t)return;let o=new qi(this._mol);o.updateAtom(e.id,{symbol:t});let{mol:r}=o.commit(),s=oe(r,this._service.monomerLib,{mode:"lenient"}).mol;this._replaceMol(s,`replaceMonomer:${n}->${t}`,"api");let a=g(s,e.id);void 0!==a&&this._events.fire("monomer:replace",{atom:a,oldSymbol:n,newSymbol:t})}hitTest(e,t){this._ensureLive();let i=new Yi(this._mol,this._theme).test({x:e,y:t});return null===i?null:void 0!==i.atom?{atom:i.atom}:void 0!==i.bond?{bond:i.bond}:null}moveAtom(e,t){this._ensureLive();let i=g(this._mol,e);if(void 0===i||i.p.x===t.x&&i.p.y===t.y)return;let n=new qi(this._mol);n.updateAtom(e,{p:{x:t.x,y:t.y}});let{mol:o}=n.commit();this._replaceMol(o,"moveAtom","user")}moveAtoms(e){if(this._ensureLive(),0===e.length)return;let t=new qi(this._mol),i=0;for(let n of e){let e=g(this._mol,n.atomId);void 0!==e&&(e.p.x===n.p.x&&e.p.y===n.p.y||(t.updateAtom(n.atomId,{p:{x:n.p.x,y:n.p.y}}),i+=1))}if(0===i)return;let{mol:n}=t.commit();this._replaceMol(n,"moveAtom","user")}_layoutOptions(){let e={};return void 0!==this._options.bondLength&&(e.bondLength=this._options.bondLength),void 0!==this._options.monomersPerRow&&(e.monomersPerRow=this._options.monomersPerRow),Object.keys(e).length>0?e:void 0}cleanLayout(e){this._ensureLive(),this._resetLastAction();let t=Et(this._mol,this._layoutOptions());this._mol=t,this._history.push({mol:t,label:"cleanLayout"}),this._events.fire("layout:change",{mol:t,strategy:"auto"}),this._events.fire("mol:changed",{mol:t,changedAtomIds:new Set(t.atoms.map(e=>e.id)),changedBondIds:In,reason:"cleanLayout"})}canUndo(){return this._history.canUndo()}canRedo(){return this._history.canRedo()}undo(){this._ensureLive();let e=this._history.undo();null!==e&&this._restoreFromHistory(e.mol,"undo")}redo(){this._ensureLive();let e=this._history.redo();null!==e&&this._restoreFromHistory(e.mol,"redo")}on(e,t){return this._events.on(e,t)}off(e,t){this._events.off(e,t)}fire(e,t){this._events.fire(e,t)}zoom(e,t){if(this._ensureLive(),!Number.isFinite(e)||e<=0)return;let i=this._viewport.scale,n=Math.min(8,Math.max(.2,i*e));if(n===i)return;let o={...this._viewport.offset},r=o;void 0!==t&&(r={x:o.x+(i-n)*t.x,y:o.y+(i-n)*t.y});let s={scale:n,offset:r};this._viewport=s;let a=t??{x:0,y:0};this._events.fire("view:zoom",{scale:n,center:a,previousScale:i}),this._events.fire("view:viewport-change",{viewport:s})}panTo(e){this._ensureLive();let t={...this._viewport.offset},i={scale:this._viewport.scale,offset:{...e}};this._viewport=i,this._events.fire("view:pan",{offset:i.offset,previousOffset:t}),this._events.fire("view:viewport-change",{viewport:i})}getViewport(){return{scale:this._viewport.scale,offset:{...this._viewport.offset}}}fitToContent(e){this._ensureLive();let t=0,i=0,n=0,o=0,r=!1;for(let e of this._mol.atoms)r?(e.p.x<t&&(t=e.p.x),e.p.x>n&&(n=e.p.x),e.p.y<i&&(i=e.p.y),e.p.y>o&&(o=e.p.y)):(t=n=e.p.x,i=o=e.p.y,r=!0);let s=r?{x:t,y:i,width:n-t,height:o-i}:{x:0,y:0,width:0,height:0},a={...this._viewport.offset},l=this._viewport.scale,h={scale:1,offset:{x:0,y:0}};this._viewport=h,1!==l&&this._events.fire("view:zoom",{scale:1,center:{x:0,y:0},previousScale:l}),(0!==a.x||0!==a.y)&&this._events.fire("view:pan",{offset:h.offset,previousOffset:a}),this._events.fire("view:viewport-change",{viewport:h}),this._events.fire("view:fit-to-content",{bbox:s})}setViewOnly(e){this._ensureLive();let t=this._viewOnly;t!==e&&(this._viewOnly=e,this._events.fire("option:change",{key:"viewOnly",oldValue:t,newValue:e}))}setTheme(e){this._ensureLive();let t=this._theme;t!==e&&(this._theme=e,this._events.fire("theme:change",{theme:e,previousTheme:t}))}toSvg(e){this._ensureLive();let t=this.getHelm(),i={};return void 0!==e?.width&&(i.width=e.width),void 0!==e?.height&&(i.height=e.height),this._service.renderToSvg(t,i)}async toPng(e){this._ensureLive();let t=this.getHelm(),i={};return void 0!==e?.width&&(i.width=e.width),void 0!==e?.height&&(i.height=e.height),this._service.renderToPng(t,i)}_getHost(){return this._host}_observerCount(){return this._events.observerCount()}_currentHighlights(){return this._highlights}_currentTheme(){return this._theme}_getView(){return this._view}_getViewport(){return this._viewport}openAtomProps(e){this._ensureLive(),null!==this._host&&(null===this._atomDialog&&(this._atomDialog=new En(this)),this._atomDialog.open(e))}openBondProps(e){this._ensureLive(),null!==this._host&&(null===this._bondDialog&&(this._bondDialog=new Bn(this)),this._bondDialog.open(e))}openFindReplace(){this._ensureLive(),null!==this._host&&(null===this._findReplaceDialog&&(this._findReplaceDialog=new Tn(this)),this._findReplaceDialog.open())}getMode(){return this._mode}setMode(e){this._ensureLive();let t=this._mode;t!==e&&(this._mode=e,this._events.fire("option:change",{key:"mode",oldValue:t,newValue:e}))}getNextAddSymbol(){return this._nextAdd}setNextAddSymbol(e,t){this._ensureLive();let i=this._nextAdd;if(null===e)this._nextAdd=null;else{if(void 0===t)return;this._nextAdd={symbol:e,biotype:t}}this._events.fire("option:change",{key:"nextAdd",oldValue:i,newValue:this._nextAdd})}startPaletteDrag(e,t){this._ensureLive(),null!==this._dnd?this._dnd.startPaletteDrag(e,t):this._events.fire("dnd:start",{source:"palette",symbol:e})}findMonomers(e){this._ensureLive();let t=[];for(let i of this._mol.atoms)i.symbol===e&&t.push(i);return t}replaceMonomers(e,t){let i,n;if(this._ensureLive(),"string"==typeof e){let o=e,r=t;if(i=this.findMonomers(o),0===i.length)return 0;if(o===r)return i.length;n=`${o}->${r}`}else{let o=t,r=new Set,s=[];for(let t of e){if(r.has(t.id))continue;r.add(t.id);let e=g(this._mol,t.id);void 0!==e&&e.symbol!==o&&s.push(e)}if(0===s.length)return 0;i=s,n=`atoms[${s.length}]->${o}`}let o=t,r=new qi(this._mol);for(let e of i)r.updateAtom(e.id,{symbol:o});let{mol:s}=r.commit(),a=oe(s,this._service.monomerLib,{mode:"lenient"}).mol;return this._replaceMol(a,`replaceMonomers:${n}`,"api"),i.length}nudgeSelection(e,t){this._ensureLive();let i=this._selection;if(0===i.atoms.size)return;let n=new qi(this._mol);for(let o of i.atoms){let i=g(this._mol,o);void 0!==i&&n.updateAtom(o,{p:{x:i.p.x+e,y:i.p.y+t}})}let{mol:o}=n.commit();this._replaceMol(o,"nudge","user")}deleteSelection(){this._ensureLive();let e=this._selection;if(0===e.atoms.size&&0===e.bonds.size)return;let t=new qi(this._mol);for(let i of e.atoms)t.removeAtom(i);for(let i of e.bonds)t.removeBond(i);let{mol:i}=t.commit();this._selection=Di.empty(),this._replaceMol(i,"delete-selection","user"),this._events.fire("selection:change",{selection:this._selection,addedAtomIds:In,removedAtomIds:e.atoms,addedBondIds:In,removedBondIds:e.bonds})}appendRnaTriplet(e,t,i){this._ensureLive();let n=Pn(e,t,i),o=function(e,t){if(""===e)return`RNA1{${t}}$$$$V2.0`;let i,n=/(^|\|)(RNA\d+)\{([^}]*)\}/g,o=null;for(;null!==(i=n.exec(e));)o={name:i[2],body:i[3],matchText:i[0]};if(null!==o){let i=""===o.body?"":".",n=`${o.matchText.startsWith("|")?"|":""}${o.name}{${o.body}${i}${t}}`,r=e.lastIndexOf(o.matchText);return e.slice(0,r)+n+e.slice(r+o.matchText.length)}let r,s=new Set,a=/RNA(\d+)\{/g;for(;null!==(r=a.exec(e));)s.add(Number(r[1]));let l=1;for(;s.has(l);)l+=1;let h=`RNA${l}{${t}}`,d=e.indexOf("$");if(d<0)return`${e}|${h}$$$$V2.0`;let c=e.slice(0,d);return`${c}${""===c?"":"|"}${h}${e.slice(d)}`}(this.getHelm(),n);this.setHelm(o)}placeRnaTriplet(e,t,i){this._ensureLive();let n,o=1.6*(this._options.bondLength??28),r=this._mol.atoms;if("add-triplet"===this._lastAction&&null!==this._lastTripletSugarPos)n={x:this._lastTripletSugarPos.x+2*o,y:this._lastTripletSugarPos.y};else if(0===r.length)n={x:0,y:0};else{let e=r[0].p.x,t=r[0].p.y;for(let i of r)i.p.x<e&&(e=i.p.x),i.p.y>t&&(t=i.p.y);n={x:e,y:t+o}}let s={x:n.x+o,y:n.y},a={x:n.x,y:n.y+o},l=new Set;for(let e of this._mol.chains)l.add(e.id);let h=1;for(;l.has(`RNA${h}`);)h+=1;let d=`RNA${h}`,c=new qi(this._mol),u=c.addAtom({p:n,biotype:v,symbol:e,chainId:d,positionInChain:1}),p=c.addAtom({p:s,biotype:x,symbol:i,chainId:d,positionInChain:2}),m=c.addAtom({p:a,biotype:w,symbol:t,chainId:d,positionInChain:0});c.addBond({a1:u,a2:m,kind:"branch",r1:{kind:"numeric",r:3},r2:{kind:"numeric",r:1}}),c.addBond({a1:u,a2:p,kind:"backbone",r1:{kind:"numeric",r:2},r2:{kind:"numeric",r:1}});let{mol:f}=c.commit(),b=oe(this._postProcessTripletMol(f,u,m,d),this._service.monomerLib,{mode:"lenient"}).mol;this._replaceMol(b,"placeRnaTriplet","user"),this._lastAction="add-triplet",this._lastTripletSugarPos=n}_postProcessTripletMol(e,t,i,n){let o=new Map,r=g(e,i),s=g(e,t);if(void 0===r||void 0===s)return e;let a={...s,branchAtom:r};o.set(t,a);let l=e.bonds.map(e=>{let t=o.get(e.a1.id)??e.a1,i=o.get(e.a2.id)??e.a2;return t===e.a1&&i===e.a2?e:{...e,a1:t,a2:i}}),h=new Map;for(let e of l)h.set(e.id,e);let d=e.chains.map(e=>{let t=[];for(let r of e.backboneAtoms)e.id===n&&r.id===i||t.push(o.get(r.id)??r);let r=e.bonds.map(e=>h.get(e.id)??e);return{id:e.id,polymerType:e.polymerType,backboneAtoms:t,bonds:r,...void 0!==e.annotation?{annotation:e.annotation}:{}}}),c={atoms:e.atoms.map(e=>o.get(e.id)??e),bonds:l,chains:d,groups:e.groups,annotations:e.annotations};return c=this._refreshContinuousIdsLocal(c),c}_resetLastAction(){this._lastAction="other",this._lastTripletSugarPos=null}_ensureLive(){if(this._destroyed)throw new Error("HelmEditor: this instance has been destroyed.")}_replaceMol(e,t,i){let n=this._service.serialize(this._mol),o=this._service.serialize(e);this._mol=e,this._history.push({mol:e,label:t}),this._resetLastAction(),this._events.fire("mol:changed",{mol:e,changedAtomIds:new Set(e.atoms.map(e=>e.id)),changedBondIds:new Set(e.bonds.map(e=>e.id)),reason:t}),n!==o&&this._events.fire("helm:changed",{helm:o,mol:e,source:i})}_restoreFromHistory(e,t){let i=this._service.serialize(this._mol),n=this._service.serialize(e);this._mol=e,this._resetLastAction(),this._events.fire("mol:changed",{mol:e,changedAtomIds:new Set(e.atoms.map(e=>e.id)),changedBondIds:new Set(e.bonds.map(e=>e.id)),reason:t}),i!==n&&this._events.fire("helm:changed",{helm:n,mol:e,source:t})}};function $n(e){return e.startsWith("[")&&e.endsWith("]")||1===e.length&&/^[A-Za-z]$/.test(e)?e:`[${e}]`}function Pn(e,t,i){return`${$n(e)}(${$n(t)})${$n(i)}`}var Rn="http://www.w3.org/2000/svg",Hn={sugar:v,base:w,linker:x},Nn={sugar:["r","R"],base:["A"],linker:["p","P"]},Dn={x:70,y:60},Fn={x:140,y:60},On={x:70,y:130},zn=class e{constructor(e,t,i){this.onValueSet=new I,this.onPickModeChange=new I,this._slots=new Map,this._favStar=null,this._pickMode=null,this._destroyed=!1,this._builderRdkitCache=new Map,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._hooks=i?.paletteHooks??null,this._favHooks=i?.favoriteHooks??null,this.element=Qi(this._doc,"div",{class:"hw-rna-builder","data-testid":"rna-builder"});let n=Qi(this._doc,"div",{class:"hw-rna-builder__header"});if(n.appendChild(Qi(this._doc,"div",{class:"hw-rna-builder__title"},["RNA builder"])),null!==this._favHooks){let e=Qi(this._doc,"span",{class:"hw-rna-builder__fav hw-rna-builder__fav--disabled",role:"button",tabindex:"0","data-testid":"rna-builder-fav-star",title:"Favorite this triplet","aria-pressed":"false","aria-disabled":"true"},["☆"]),t=e=>{e.stopPropagation();let t=this.getSelection();""===t.preview||null===this._favHooks||this._favHooks.toggleFavoriteTriplet(t.sugar,t.base,t.linker)};e.addEventListener("click",t),e.addEventListener("keydown",e=>{let i=e;("Enter"===i.key||" "===i.key)&&t(e)}),this._favStar=e,n.appendChild(e)}this.element.appendChild(n),this._hintEl=Qi(this._doc,"div",{class:"hw-rna-builder__hint","data-testid":"rna-builder-hint",hidden:!0}),this.element.appendChild(this._hintEl);let o=this._buildSvg();this.element.appendChild(o),this._preview=Qi(this._doc,"div",{class:"hw-rna-builder__preview","data-testid":"rna-builder-preview"}),this.element.appendChild(this._preview),this._addBtn=Qi(this._doc,"button",{class:"hw-rna-builder__add",type:"button","data-testid":"rna-builder-add-btn"},["Add triplet"]),this._addBtn.addEventListener("click",()=>this._onAddClicked()),this.element.appendChild(this._addBtn),e.appendChild(this.element);let r=t.getService().monomerLib.onChanged.subscribe(()=>{this._destroyed||this.refresh()}),s=t.on("theme:change",()=>{this._destroyed||this._repaintSlotColors()});this._libUnsub=()=>{try{r()}catch{}try{s()}catch{}},this._populateDefaults(),this._updatePreview(),this._repaintSlotColors()}refresh(){this._populateDefaults(),this._updatePreview(),this._repaintSlotColors()}getSelection(){let e=this._slots.get("sugar")?.value??"",t=this._slots.get("base")?.value??"",i=this._slots.get("linker")?.value??"";return{sugar:e,base:t,linker:i,preview:""!==e&&""!==t&&""!==i?Pn(e,t,i):""}}setField(e,t){let i=this._slots.get(e);void 0!==i&&(i.value=t,this._setLabelText(i.labelEl,t),this._repaintSlot(i),this._updatePreview(),this.onValueSet.next({field:e,symbol:t}))}startPickMode(e){this._pickMode!==e?(null!==this._pickMode&&this._setSlotPressed(this._pickMode,!1),this._pickMode=e,this._setSlotPressed(e,!0),this._setHintActive(e),this.onPickModeChange.next({field:e}),null!==this._hooks&&this._hooks.beginBiotypeFilter(Hn[e],t=>{this.setField(e,t),this._exitPickMode()},()=>{this._exitPickMode()})):this.cancelPickMode()}cancelPickMode(){null!==this._pickMode&&(null!==this._hooks&&this._hooks.endBiotypeFilter(),this._exitPickMode())}getPickMode(){return this._pickMode}triggerAdd(){this._onAddClicked()}destroy(){this._destroyed||(this._destroyed=!0,null!==this._pickMode&&null!==this._hooks&&this._hooks.endBiotypeFilter(),this._libUnsub(),this.onValueSet.complete(),this.onPickModeChange.complete(),null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element))}_buildSvg(){let e=this._doc.createElementNS(Rn,"svg");e.setAttribute("class","hw-rna-builder__triplet"),e.setAttribute("viewBox","0 0 200 180"),e.setAttribute("data-testid","rna-builder-triplet-svg"),e.setAttribute("role","group"),e.setAttribute("aria-label","Triplet preview");let t=this._doc.createElementNS(Rn,"line");t.setAttribute("class","hw-rna-builder__bond"),t.setAttribute("x1",String(Dn.x+18)),t.setAttribute("y1",String(Dn.y)),t.setAttribute("x2",String(Fn.x-18)),t.setAttribute("y2",String(Fn.y)),e.appendChild(t);let i=this._doc.createElementNS(Rn,"line");i.setAttribute("class","hw-rna-builder__bond"),i.setAttribute("x1",String(Dn.x)),i.setAttribute("y1",String(Dn.y+18)),i.setAttribute("x2",String(On.x)),i.setAttribute("y2",String(On.y-22)),e.appendChild(i);let n=this._doc.createElementNS(Rn,"rect");n.setAttribute("class","hw-rna-builder__slot-shape"),n.setAttribute("x",String(-18)),n.setAttribute("y",String(-18)),n.setAttribute("width",String(36)),n.setAttribute("height",String(36)),n.setAttribute("rx","8"),n.setAttribute("ry","8");let o=this._buildSlot("sugar","Pick sugar (backbone)",Dn,n),r=this._doc.createElementNS(Rn,"circle");r.setAttribute("class","hw-rna-builder__slot-shape"),r.setAttribute("cx","0"),r.setAttribute("cy","0"),r.setAttribute("r",String(18));let s=this._buildSlot("linker","Pick linker",Fn,r),a=this._doc.createElementNS(Rn,"path");a.setAttribute("class","hw-rna-builder__slot-shape"),a.setAttribute("d","M -22 0 L 0 -22 L 22 0 L 0 22 Z");let l=this._buildSlot("base","Pick base",On,a);return e.appendChild(s.groupEl),e.appendChild(o.groupEl),e.appendChild(l.groupEl),this._slots.set("sugar",o),this._slots.set("linker",s),this._slots.set("base",l),e}_buildSlot(e,t,i,n){let o=this._doc.createElementNS(Rn,"g");o.setAttribute("class","hw-rna-builder__slot"),o.setAttribute("data-slot",e),o.setAttribute("data-testid",`rna-builder-slot-${e}`),o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.setAttribute("aria-label",t),o.setAttribute("aria-pressed","false"),o.setAttribute("transform",`translate(${i.x} ${i.y})`),o.appendChild(n);let r=this._doc.createElementNS(Rn,"text");r.setAttribute("class","hw-rna-builder__slot-label"),r.setAttribute("data-testid",`rna-builder-${e}-value`),r.setAttribute("x","0"),r.setAttribute("y","0"),r.setAttribute("text-anchor","middle"),r.setAttribute("dominant-baseline","central"),o.appendChild(r);let s=t=>{t.stopPropagation(),this.startPickMode(e)};return o.addEventListener("click",s),o.addEventListener("keydown",e=>{let t=e;("Enter"===t.key||" "===t.key)&&s(e)}),o.addEventListener("mouseenter",t=>this._showSlotTooltip(e,t)),o.addEventListener("mouseleave",()=>this._hideSlotTooltip()),o.addEventListener("focus",()=>this._showSlotTooltip(e,null)),o.addEventListener("blur",()=>this._hideSlotTooltip()),{id:e,biotype:Hn[e],groupEl:o,shapeEl:n,labelEl:r,value:""}}_setLabelText(e,t){let i=[];for(let t=e.firstChild;null!==t;t=t.nextSibling)"title"===t.nodeName||"TITLE"===t.nodeName||i.push(t);for(let t of i)e.removeChild(t);let n=function(e){let t=e.length;return t<=2?16:t<=4?11:t<=7?8:t<=10?6:5}(t);e.setAttribute("font-size",String(n)),e.setAttribute("text-anchor","middle"),e.setAttribute("dominant-baseline","central");let o=t.length>10?`${t.slice(0,9)}…`:t;e.appendChild(this._doc.createTextNode(o));let r=e.parentNode;if(null!==r){let e=null;for(let t=r.firstChild;null!==t;t=t.nextSibling)if("title"===t.nodeName||"TITLE"===t.nodeName){e=t;break}for(null===e&&(e=this._doc.createElementNS(Rn,"title"),r.insertBefore(e,r.firstChild));null!==e.firstChild;)e.removeChild(e.firstChild);e.appendChild(this._doc.createTextNode(t))}}_repaintSlotColors(){for(let e of this._slots.values())this._repaintSlot(e)}_repaintSlot(e){let t=this._editor.getService().monomerLib,i=this._theme(),n=""===e.value?null:function(e,t,i){return e.getMonomerSet(t).get(i)??null}(t,e.biotype,e.value),o=te(n,e.biotype,i.colorTheme);e.shapeEl.style.fill=o.background,e.shapeEl.style.stroke=o.line,e.labelEl.style.fill=o.text}_populateDefaults(){let e=this._editor.getService().monomerLib;for(let[t,i]of this._slots.entries()){let n=qn(e,i.biotype),o=jn(n,Nn[t]),r=""!==i.value&&n.some(e=>e.symbol===i.value)?i.value:o??n[0]?.symbol??"";i.value=r,this._setLabelText(i.labelEl,r)}}_updatePreview(){let e=this.getSelection();for(;null!==this._preview.firstChild;)this._preview.removeChild(this._preview.firstChild);this._preview.appendChild(this._doc.createTextNode(""===e.preview?"-":e.preview)),this._updateFavStar(e)}_updateFavStar(e){if(null===this._favStar||null===this._favHooks)return;let t=""!==e.preview,i=t&&this._favHooks.isFavoriteTriplet(e.sugar,e.base,e.linker);for(;null!==this._favStar.firstChild;)this._favStar.removeChild(this._favStar.firstChild);this._favStar.appendChild(this._doc.createTextNode(i?"★":"☆")),this._favStar.setAttribute("aria-pressed",i?"true":"false"),t?this._favStar.removeAttribute("aria-disabled"):this._favStar.setAttribute("aria-disabled","true");let n="hw-rna-builder__fav"+(i?" hw-rna-builder__fav--active":"")+(t?"":" hw-rna-builder__fav--disabled");this._favStar.setAttribute("class",n)}_onAddClicked(){let e=this.getSelection();""!==e.preview&&this._editor.placeRnaTriplet(e.sugar,e.base,e.linker)}_exitPickMode(){if(null===this._pickMode)return;let e=this._pickMode;this._setSlotPressed(e,!1),this._pickMode=null,this._setHintActive(null),this.onPickModeChange.next({field:null})}_setHintActive(e){let t=this._hintEl;for(;null!==t.firstChild;)t.removeChild(t.firstChild);if(null===e)return void t.setAttribute("hidden","");t.removeAttribute("hidden");let i="sugar"===e?"sugar":"base"===e?"base":"linker";t.appendChild(this._doc.createTextNode(`Pick ${i} from palette`))}_setSlotPressed(e,t){let i=this._slots.get(e);if(void 0===i)return;i.groupEl.setAttribute("aria-pressed",t?"true":"false");let n=(i.groupEl.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-rna-builder__slot--active"!==e).join(" ");i.groupEl.setAttribute("class",t?`${n} hw-rna-builder__slot--active`:n)}_theme(){let e=this._editor;return"function"==typeof e._currentTheme?e._currentTheme():this._editor.getService().theme}_rdkit(){let e=this._editor.getService().options?.rdkitModule;return e??null}_builderRdkitSvgFor(t){if(null===t)return null;let i=t.smiles;if(void 0===i||""===i)return null;let n=this._rdkit();if(null===n)return null;let o=`${t.polymerType}:${t.symbol}`;if(this._builderRdkitCache.has(o))return this._builderRdkitCache.get(o)??null;let r=Zi(n,i,220,140);if(this._builderRdkitCache.size>=e._BUILDER_RDKIT_CACHE_LIMIT){let e=this._builderRdkitCache.keys().next().value;void 0!==e&&this._builderRdkitCache.delete(e)}return this._builderRdkitCache.set(o,r),r}_slotHint(e){switch(e){case"sugar":return"Click to choose a different sugar";case"base":return"Click to choose a different base";case"linker":return"Click to choose a different linker"}}_slotTitle(e,t){let i=""===t?"?":t;switch(e){case"sugar":return`Sugar: ${i}`;case"base":return`Base: ${i}`;case"linker":return`Linker: ${i}`}}_showSlotTooltip(e,t){let i=this._slots.get(e);if(void 0===i)return;let n=this._editor.getService().monomerLib.getMonomerSet(i.biotype),o=""===i.value?null:n.get(i.value)??null,r=Ji(this._doc,"builder-tooltip","hw-builder-tooltip");en(this._doc,r,{symbol:this._slotTitle(e,i.value),name:o?.name??"",rdkitSvg:this._builderRdkitSvgFor(o),rdkitTestid:"builder-tooltip-rdkit-svg",hint:this._slotHint(e)});let s=t;if(null!==s&&"number"==typeof s.clientX&&"number"==typeof s.clientY)tn(r,s.clientX,s.clientY);else{let e=i.groupEl,t="function"==typeof e.getBoundingClientRect?e.getBoundingClientRect():null;null!==t?tn(r,t.left+t.width/2,t.top+t.height/2):tn(r,0,0)}}_hideSlotTooltip(){nn(this._doc.body.querySelector('[data-testid="builder-tooltip"]'))}};zn._BUILDER_RDKIT_CACHE_LIMIT=256;var Gn=zn;function qn(e,t){let i=e.getMonomerSet(t),n=[];for(let e of i.values())n.push(e);return n.sort((e,t)=>e.symbol.localeCompare(t.symbol)),n}function jn(e,t){let i=new Set;for(let t of e)i.add(t.symbol);for(let e of t)if(i.has(e))return e;return null}var Yn="Favorites",Vn={[Yn]:"★ Favorites",[B.PEPTIDE]:"Peptides",[B.RNA]:"RNA",[B.CHEM]:"CHEM",[B.BLOB]:"BLOB",G:"G"},Wn=[Yn,B.PEPTIDE,B.RNA,B.CHEM,B.BLOB,"G"],Un="hwe:palette:favorites",Kn="hwe:palette:active-tab";function Xn(e){return`${e.sugar}|${e.base}|${e.linker}`}var Qn=class e{constructor(e,t,i){this.favoritesChanged=new I,this._nextAddUnsub=()=>{},this._favorites=new Set,this._favoriteTriplets=[],this._pendingRnaSelection=null,this._visibleTabs=[Yn],this._activeTab=Yn,this._searchInput=null,this._filter="",this._destroyed=!1,this._rnaBuilder=null,this._activeBiotypeFilter=null,this._pickResolver=null,this._pickCanceller=null,this._pickEscapeListener=null,this._pickOutsideClickListener=null,this._paletteRdkitCache=new Map,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._opts={documentImpl:this._doc,groupByNaturalAnalog:i?.groupByNaturalAnalog??!0,allowFavorites:i?.allowFavorites??!0},this._loadFavorites(),this._activeTab=this._resolveInitialTab(i?.initialTab),this.element=Qi(this._doc,"div",{class:"hw-palette","data-testid":"palette"}),e.appendChild(this.element),this._render(),this._libUnsub=t.getService().monomerLib.onChanged.subscribe(()=>{this._destroyed||this.refresh()}),this._themeUnsub=t.on("theme:change",()=>{this._destroyed||this.refresh()}),this._nextAddUnsub=t.on("option:change",e=>{this._destroyed||"nextAdd"===e.key&&this._updatePrimedClasses()})}refresh(){this._render()}setFilter(e){this._filter=e.trim().toLowerCase(),null!==this._searchInput&&this._searchInput.value!==e&&(this._searchInput.value=e),this._applyFilter()}setActiveTab(e){this._visibleTabs.includes(e)&&(this._activeTab=e,this._persistActiveTab(),this._applyActiveTabClasses(),this._applyFilter())}getActiveTab(){return this._activeTab}getFavorites(){let e=this._editor.getService().monomerLib,t=[];for(let i of this._favorites)null!==this._findMonomer(e,i)&&t.push(i);return t}setFavorite(e,t){t!==this._favorites.has(e)&&(t?this._favorites.add(e):this._favorites.delete(e),this._saveFavorites(),this._hidePaletteTooltips(),this._render(),this._emitFavoritesChanged())}clearFavorites(){0===this._favorites.size&&0===this._favoriteTriplets.length||(this._favorites.clear(),this._favoriteTriplets.length=0,this._saveFavorites(),this._render(),this._emitFavoritesChanged())}getFavoriteTriplets(){return this._favoriteTriplets.map(e=>({...e}))}isFavoriteTriplet(e,t,i){let n=Xn({sugar:e,base:t,linker:i});return this._favoriteTriplets.some(e=>Xn(e)===n)}setFavoriteTriplet(e,t,i,n){let o=Xn({sugar:e,base:t,linker:i}),r=this._favoriteTriplets.findIndex(e=>Xn(e)===o);n!==r>=0&&(n?this._favoriteTriplets.push({sugar:e,base:t,linker:i}):this._favoriteTriplets.splice(r,1),this._saveFavorites(),this._hidePaletteTooltips(),this._render(),this._emitFavoritesChanged())}_hidePaletteTooltips(){let e=this._doc.body;nn(e.querySelector('[data-testid="palette-tooltip"]')),nn(e.querySelector('[data-testid="palette-triplet-tooltip"]'))}_emitFavoritesChanged(){this.favoritesChanged.next({favorites:this.getFavorites(),triplets:this.getFavoriteTriplets()})}destroy(){this._destroyed||(this._destroyed=!0,null!==this._rnaBuilder&&(this._rnaBuilder.destroy(),this._rnaBuilder=null),this._libUnsub(),this._themeUnsub(),this._nextAddUnsub(),null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element))}getRnaBuilder(){return this._rnaBuilder}hasActiveBiotypeFilter(){return null!==this._activeBiotypeFilter}getActiveBiotypeFilter(){return this._activeBiotypeFilter}cancelBiotypeFilter(){if(null===this._activeBiotypeFilter)return;let e=this._pickCanceller;this._teardownPickMode(),e?.()}_buildPaletteFilterHooks(){return{beginBiotypeFilter:(e,t,i)=>{null!==this._activeBiotypeFilter&&this._teardownPickMode(),this._activeBiotypeFilter=e,this._pickResolver=t,this._pickCanceller=i,this._applyFilter();let n=e=>{"Escape"===e.key&&this.cancelBiotypeFilter()};this._pickEscapeListener=n,this._doc.defaultView?.addEventListener("keydown",n);let o=e=>{if(null===this._activeBiotypeFilter)return;let t=e.target;if(null==t)return;let i=this._activeBiotypeFilter,n=t;for(;null!==n;){let e=void 0===n.getAttribute?null:n.getAttribute("class");if(null!==e){let t=e.split(/\s+/);if(t.includes("hw-palette__tile")){if((n.getAttribute("data-biotype")??"")===i)return;break}if(t.includes("hw-rna-builder__slot")){if(this._isInsideOwnPalette(n))return;break}}n=n.parentElement}this.cancelBiotypeFilter()};this._pickOutsideClickListener=o,this._doc.addEventListener("mousedown",o,!0)},endBiotypeFilter:()=>this._teardownPickMode()}}_scrollActivePaneToTop(){let e=this.element.querySelector(`.hw-palette__pane[data-tab="${this._activeTab}"]`);if(null===e)return;let t=e;try{if("function"==typeof t.scrollTo)return void t.scrollTo({top:0,behavior:"smooth"})}catch{}"number"==typeof t.scrollTop&&(t.scrollTop=0)}_isInsideOwnPalette(e){let t=e;for(;null!==t;){if(t===this.element)return!0;t=t.parentElement}return!1}_teardownPickMode(){null!==this._activeBiotypeFilter&&(this._activeBiotypeFilter=null,this._pickResolver=null,this._pickCanceller=null,null!==this._pickEscapeListener&&(this._doc.defaultView?.removeEventListener("keydown",this._pickEscapeListener),this._pickEscapeListener=null),null!==this._pickOutsideClickListener&&(this._doc.removeEventListener("mousedown",this._pickOutsideClickListener,!0),this._pickOutsideClickListener=null),this._applyFilter())}_render(){for(null!==this._rnaBuilder&&(this._pendingRnaSelection=this._rnaBuilder.getSelection(),this._rnaBuilder.destroy(),this._rnaBuilder=null);null!==this.element.firstChild;)this.element.removeChild(this.element.firstChild);let e=this._doc.createElement("input");e.setAttribute("type","search"),e.setAttribute("class","hw-palette__search"),e.setAttribute("placeholder","Search monomers..."),e.setAttribute("data-testid","palette-search"),""!==this._filter&&(e.value=this._filter),e.addEventListener("input",()=>this.setFilter(e.value)),this._searchInput=e,this.element.appendChild(e),this._visibleTabs=this._computeVisibleTabs(),this._visibleTabs.includes(this._activeTab)||(this._activeTab=Yn);let t=Qi(this._doc,"div",{class:"hw-palette__tabs",role:"tablist","data-testid":"palette-tabs"});for(let e of this._visibleTabs){let i=e===this._activeTab,n=Qi(this._doc,"button",{class:"hw-palette__tab",type:"button",role:"tab","aria-controls":`hw-palette-pane-${e}`,"aria-selected":i?"true":"false","data-testid":`palette-tab-${e}`,"data-tab":e,title:Vn[e]},[Vn[e]]);n.addEventListener("click",()=>this.setActiveTab(e)),t.appendChild(n)}this.element.appendChild(t);let i=Qi(this._doc,"div",{class:"hw-palette__panes"}),n=this._theme(),o=this._editor.getService().monomerLib;for(let e of this._visibleTabs){let t=e===this._activeTab,r=Qi(this._doc,"div",{class:"hw-palette__pane",id:`hw-palette-pane-${e}`,role:"tabpanel","data-testid":`palette-pane-${e}`,"data-tab":e,hidden:!t});e===Yn?this._buildFavoritesPane(r,o,n):this._buildPolymerPane(r,e,o,n),i.appendChild(r)}this.element.appendChild(i),this._applyFilter()}_computeVisibleTabs(){let e=this._editor.getService().monomerLib,t=new Set;for(let i of e.getPolymerTypes())t.add(i);let i=[];i.push(Yn);for(let e of Wn)e!==Yn&&t.has(e)&&i.push(e);return i}_buildFavoritesPane(e,t,i){let n=this._resolveFavoriteMonomers(t),o=this._favoriteTriplets;if(0===n.length&&0===o.length){let t=Qi(this._doc,"div",{class:"hw-palette__placeholder","data-testid":"palette-favorites-empty"},["No favorites yet — click the ☆ on any tile to add one."]);return void e.appendChild(t)}for(let[t,i]of this._groupByPolymerAndType(n))e.appendChild(this._renderGroup(t,i));o.length>0&&e.appendChild(this._renderTripletGroup("RNA · Triplets",o,t))}_groupByPolymerAndType(e){let t=new Map;for(let i of e){let e=i.polymerType,n=i.monomerType??"Undefined",o=`${e}|${n}`,r=t.get(o);void 0===r&&(r={pt:e,mt:n,list:[]},t.set(o,r)),r.list.push(i)}let i=e=>{let t=Wn.indexOf(e);return t<0?99:t},n={Backbone:0,Branch:1,Terminal:2,Undefined:3};return Array.from(t.values()).sort((e,t)=>i(e.pt)-i(t.pt)||(n[e.mt]??9)-(n[t.mt]??9)||e.mt.localeCompare(t.mt)).map(e=>[`${this._polymerLabel(e.pt)} · ${e.mt}`,e.list])}_polymerLabel(e){return Vn[e]??e}_renderTripletGroup(e,t,i){let n=Qi(this._doc,"div",{class:"hw-palette__group","data-natural-analog":e}),o=Qi(this._doc,"div",{class:"hw-palette__group-header","data-testid":`palette-group-${e}`},[e]),r=Qi(this._doc,"div",{class:"hw-triplet-chips","data-testid":"palette-triplet-favorites"});for(let e of t)r.appendChild(this._renderTripletChip(e,i));return n.appendChild(o),n.appendChild(r),n}_renderTripletChip(e,t){let i=Pn(e.sugar,e.base,e.linker),n=t.getMonomerSet(w).get(e.base)??null,o=te(n,w,this._theme().colorTheme),r=this.isFavoriteTriplet(e.sugar,e.base,e.linker),s=void 0!==n?.name&&""!==n.name?`${i} — ${n.name}`:i,{root:a}=function(e,t){let i=!1!==t.showStar,n=Qi(e,"span",{class:"hw-triplet-chip__star"},[t.favorite?"★":"☆"]),o=Qi(e,"span",{class:"hw-triplet-chip__label"},[t.label]),r=["hw-triplet-chip"];t.favorite&&r.push("hw-triplet-chip--favorite");let s=i?[n,o]:[o];return{root:Qi(e,"div",{class:r.join(" "),role:"button",tabindex:"0","aria-label":t.title,"data-sugar":t.sugar,"data-base":t.base,"data-linker":t.linker,"data-triplet":t.label,"data-testid":`palette-triplet-${t.label}`,title:t.title,style:`background:${t.background};color:${t.textColor};`},s),star:n}}(this._doc,{sugar:e.sugar,base:e.base,linker:e.linker,label:i,title:s,background:O(o.background),textColor:o.text,favorite:r,showStar:this._opts.allowFavorites});return this._wireTripletChip(a,e),a}_wireTripletChip(e,t){e.addEventListener("mouseenter",e=>{let i=e,n=Ji(this._doc,"palette-triplet-tooltip","hw-palette-tooltip hw-triplet-tooltip");(function(e,t,i){for(;null!==t.firstChild;)t.removeChild(t.firstChild);t.appendChild(Qi(e,"div",{class:"hw-tooltip__symbol"},[i.title]));let n=Qi(e,"div",{class:"hw-tooltip__triplet"});for(let t of i.parts){let o=Qi(e,"div",{class:"hw-tooltip__triplet-part"});if(o.appendChild(Qi(e,"div",{class:"hw-tooltip__triplet-role"},[`${t.role}: ${t.symbol}`])),void 0!==t.name&&""!==t.name&&t.name!==t.symbol&&o.appendChild(Qi(e,"div",{class:"hw-tooltip__name"},[t.name])),void 0!==t.rdkitSvg&&null!==t.rdkitSvg&&""!==t.rdkitSvg){let n={class:"hw-tooltip__rdkit"};void 0!==i.rdkitTestid&&(n["data-testid"]=i.rdkitTestid);let r=Qi(e,"div",n);r.innerHTML=t.rdkitSvg,o.appendChild(r)}n.appendChild(o)}t.appendChild(n),void 0!==i.hint&&""!==i.hint&&t.appendChild(Qi(e,"div",{class:"hw-tooltip__hint"},[i.hint]))})(this._doc,n,{title:Pn(t.sugar,t.base,t.linker),parts:this._tripletTooltipParts(t),hint:"Click to add this triplet",rdkitTestid:"palette-triplet-tooltip-rdkit-svg"}),tn(n,"number"==typeof i.clientX?i.clientX:0,"number"==typeof i.clientY?i.clientY:0)}),e.addEventListener("mouseleave",()=>{nn(this._doc.body.querySelector('[data-testid="palette-triplet-tooltip"]'))}),e.addEventListener("click",e=>{let i=e.target;if(this._opts.allowFavorites&&!0===i?.classList?.contains("hw-triplet-chip__star"))return this.setFavoriteTriplet(t.sugar,t.base,t.linker,!this.isFavoriteTriplet(t.sugar,t.base,t.linker)),void e.stopPropagation();this._editor.placeRnaTriplet(t.sugar,t.base,t.linker)}),e.addEventListener("keydown",e=>{let i=e;("Enter"===i.key||" "===i.key)&&this._editor.placeRnaTriplet(t.sugar,t.base,t.linker)})}_buildRnaDefaultChips(t){let i=this._pickSymbol(t.getMonomerSet(v),["r","R"]),n=this._pickSymbol(t.getMonomerSet(x),["p","P"]),o=t.getMonomerSet(w);if(null===i||null===n)return null;let r=e._DEFAULT_TRIPLET_BASES.filter(e=>o.has(e));if(0===r.length)return null;let s=Qi(this._doc,"div",{class:"hw-triplet-chips hw-triplet-chips--defaults","data-testid":"rna-default-triplets"});for(let e of r)s.appendChild(this._renderTripletChip({sugar:i,base:e,linker:n},t));return s}_tripletTooltipParts(e){let t=this._editor.getService().monomerLib,i=(e,i,n)=>{let o=t.getMonomerSet(i).get(n)??null;return{role:e,symbol:n,...void 0!==o?.name?{name:o.name}:{},rdkitSvg:null===o?null:this._paletteRdkitSvg(o)}};return[i("Sugar",v,e.sugar),i("Base",w,e.base),i("Linker",x,e.linker)]}_pickSymbol(e,t){for(let i of t)if(e.has(i))return i;let i=e.keys().next();return!0===i.done?null:i.value}_restoreRnaSelection(){let e=this._pendingRnaSelection;if(this._pendingRnaSelection=null,null===e||null===this._rnaBuilder)return;let t=this._editor.getService().monomerLib;""!==e.sugar&&t.getMonomerSet(v).has(e.sugar)&&this._rnaBuilder.setField("sugar",e.sugar),""!==e.base&&t.getMonomerSet(w).has(e.base)&&this._rnaBuilder.setField("base",e.base),""!==e.linker&&t.getMonomerSet(x).has(e.linker)&&this._rnaBuilder.setField("linker",e.linker)}_resolveFavoriteMonomers(e){let t=[];for(let i of this._favorites){let n=this._findMonomer(e,i);null!==n&&t.push(n)}return t}_findMonomer(e,t){for(let i of e.getPolymerTypes()){let n=e.getMonomer(i,t);if(null!==n)return n}return null}_buildPolymerPane(e,t,i,n){let o=t,r=this._monomersForPolymer(o,i);if(0===r.length)return;if(o===B.RNA){this._rnaBuilder=new Gn(e,this._editor,{documentImpl:this._doc,paletteHooks:this._buildPaletteFilterHooks(),favoriteHooks:this._opts.allowFavorites?{isFavoriteTriplet:(e,t,i)=>this.isFavoriteTriplet(e,t,i),toggleFavoriteTriplet:(e,t,i)=>this.setFavoriteTriplet(e,t,i,!this.isFavoriteTriplet(e,t,i))}:null}),this._restoreRnaSelection();let t=this._buildRnaDefaultChips(i);null!==t&&e.appendChild(t);let n=this._groupRna(r);for(let[t,i]of n)0!==i.length&&e.appendChild(this._renderGroup(t,i));return}if(o===B.PEPTIDE&&this._opts.groupByNaturalAnalog){let t=this._groupByAnalog(r);for(let[i,n]of t){let t=""===i?"Other":i;e.appendChild(this._renderGroup(t,n))}return}let s=Qi(this._doc,"div",{class:"hw-palette__group-tiles"}),a=this._editor.getNextAddSymbol(),l=this._sortByColor(r);for(let e of l){let t=this._biotype(e,o);s.appendChild(this._renderTile(e,t,a))}e.appendChild(s)}_renderGroup(e,t){let i=Qi(this._doc,"div",{class:"hw-palette__group","data-natural-analog":e}),n=Qi(this._doc,"div",{class:"hw-palette__group-header","data-testid":`palette-group-${e}`},[e]),o=Qi(this._doc,"div",{class:"hw-palette__group-tiles"}),r=this._editor.getNextAddSymbol(),s=this._sortByColor(t);for(let e of s){let t=this._biotype(e,e.polymerType);o.appendChild(this._renderTile(e,t,r))}return i.appendChild(n),i.appendChild(o),i}_sortByColor(e){let t=this._theme(),i=e.map((e,i)=>{let n=function(e){let t=P(e);if(null===t)return{h:0,s:0,l:0};let[i,n,o]=N(t[0],t[1],t[2]);return{h:i,s:n,l:o}}(te(e,this._biotype(e,e.polymerType),t.colorTheme).background),o=0===n.s?1:0;return{m:e,idx:i,h:n.h,s:n.s,l:n.l,isGrey:o}});return i.sort((e,t)=>e.isGrey!==t.isGrey?e.isGrey-t.isGrey:e.h!==t.h?e.h-t.h:e.s!==t.s?e.s-t.s:e.l!==t.l?e.l-t.l:e.idx-t.idx),i.map(e=>e.m)}_monomersForPolymer(e,t){let i=t.getMonomerSymbolsByType(e),n=[];for(let o of i){let i=t.getMonomer(e,o);null!==i&&n.push(i)}return n.sort((e,t)=>e.symbol.localeCompare(t.symbol)),n}_groupByAnalog(e){let t=new Map;for(let i of e){let e=i.naturalAnalog??"",n=t.get(e);void 0===n&&(n=[],t.set(e,n)),n.push(i)}let i=[],n=Array.from(t.keys()).sort((e,t)=>""===e&&""!==t?1:""===t&&""!==e?-1:e.localeCompare(t));for(let e of n)i.push([e,t.get(e)]);return new Map(i)}_groupRna(e){let t=[],i=[],n=[],o=[];for(let r of e){let e=ne(r);e===v?t.push(r):e===w?i.push(r):e===x?n.push(r):o.push(r)}let r=new Map;return r.set("Backbones",t),r.set("Bases",i),r.set("Linkers",n),o.length>0&&r.set("Other",o),r}_renderTile(e,t,i){let n=this._favorites.has(e.symbol),o=null!==i&&i.symbol===e.symbol&&i.biotype===t,{root:r,star:s}=function(e,t){let i=te(t.monomer,t.biotype,t.theme.colorTheme),n=O(i.background),o=i.text,r=function(e,t){let i=z(e),n=z(t);return(Math.max(i,n)+.05)/(Math.min(i,n)+.05)}(o,n)<5,s=t.monomer.symbol,a=function(e){return e<=3?14:e<=6?11:e<=9?9:8}(s.length),l=`font-size:${a}px;${s.length>=10?"line-height:1.1;letter-spacing:-0.02em;":""}white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:80px;display:inline-block;`,h=Qi(e,"span",{class:"hw-palette__star"},[t.favorite?"★":"☆"]),d=Qi(e,"span",{class:"hw-palette__label",style:l},[s]),c=["hw-palette__tile"];t.primed&&c.push("hw-palette__tile--primed"),t.favorite&&c.push("hw-palette__tile--favorite"),r&&c.push("hw-palette__tile--low-contrast");let u=void 0!==t.monomer.name?`${s} — ${t.monomer.name}`:s,p=`background:${n};color:${o};width:100%;min-width:48px;padding:4px 6px;height:40px;box-sizing:border-box;overflow:hidden;text-overflow:ellipsis;`;return{root:Qi(e,"div",{class:c.join(" "),draggable:"true",role:"button","aria-pressed":t.primed?"true":"false","aria-label":u,"data-symbol":s,"data-biotype":t.biotype,"data-bg":n,"data-raw-bg":i.background,"data-testid":`palette-tile-${s}`,title:u,style:p},[h,d]),star:h}}(this._doc,{monomer:e,biotype:t,theme:this._theme(),favorite:n,primed:o});return this._wireTile(r,s,e,t),r}_rdkit(){let e=this._editor.getService().options?.rdkitModule;return e??null}_paletteRdkitSvg(t){let i=t.smiles;if(void 0===i||""===i)return null;let n=this._rdkit();if(null===n)return null;let o=`${t.polymerType}:${t.symbol}`;if(this._paletteRdkitCache.has(o))return this._paletteRdkitCache.get(o)??null;let r=Zi(n,i,220,140);if(this._paletteRdkitCache.size>=e._PALETTE_RDKIT_CACHE_LIMIT){let e=this._paletteRdkitCache.keys().next().value;void 0!==e&&this._paletteRdkitCache.delete(e)}return this._paletteRdkitCache.set(o,r),r}_wireTile(e,t,i,n){e.addEventListener("mouseenter",e=>{let t=e,n=Ji(this._doc,"palette-tooltip","hw-palette-tooltip");en(this._doc,n,{symbol:i.symbol,name:i.name??"",rdkitSvg:this._paletteRdkitSvg(i),rdkitTestid:"palette-tooltip-rdkit-svg"}),tn(n,"number"==typeof t.clientX?t.clientX:0,"number"==typeof t.clientY?t.clientY:0)}),e.addEventListener("mouseleave",()=>{nn(this._doc.body.querySelector('[data-testid="palette-tooltip"]'))}),e.addEventListener("click",e=>{let t=e.target;if(this._opts.allowFavorites&&void 0!==t&&!0===t?.classList?.contains("hw-palette__star"))return this.setFavorite(i.symbol,!this._favorites.has(i.symbol)),void e.stopPropagation();if(null!==this._activeBiotypeFilter&&this._activeBiotypeFilter===n){let t=this._pickResolver;return this._teardownPickMode(),t?.(i.symbol),this._scrollActivePaneToTop(),void e.stopPropagation()}let o=this._editor.getSelection();if(o.atoms.size>0){let t=this._editor.getMol(),r=[];for(let e of o.atoms){let i=t.atoms.find(t=>t.id===e);void 0!==i&&r.push(i)}return r.length>0&&r.every(e=>e.biotype===n)?(this._editor.replaceMonomers(r,i.symbol),void e.stopPropagation()):(this._editor.fire("editor:status",{message:`Cannot bulk-replace ${r.length} selected atom(s) with ${i.symbol}: selection contains incompatible biotypes for ${n}.`,severity:"warn",durationMs:3e3}),void e.stopPropagation())}let r=this._editor.getNextAddSymbol();if(null!==r&&r.symbol===i.symbol&&r.biotype===n)return this._editor.setNextAddSymbol(null),void this._updatePrimedClasses();this._editor.setNextAddSymbol(i.symbol,n),this._updatePrimedClasses()}),e.addEventListener("dragstart",e=>{let t=e.dataTransfer;if(null!=t)try{t.setData("application/x-hwe-monomer",JSON.stringify({symbol:i.symbol,biotype:n})),t.effectAllowed="copy"}catch{}nn(this._doc.body.querySelector('[data-testid="palette-tooltip"]')),this._editor.startPaletteDrag(i.symbol,n)})}_biotype(e,t){let i=ne(e);if(null!==i)return i;switch(t){case B.PEPTIDE:return y;case B.RNA:return v;case B.CHEM:return C;case B.BLOB:return k;default:return C}}_theme(){let e=this._editor;return"function"==typeof e._currentTheme?e._currentTheme():this._editor.getService().theme}_applyFilter(){let e=this._filter,t=this._activeBiotypeFilter,i=this.element.querySelector(`.hw-palette__pane[data-tab="${this._activeTab}"]`),n=(i??this.element).querySelectorAll(".hw-palette__tile");for(let i=0;i<n.length;i++){let o=n[i],r=(o.getAttribute("data-symbol")??"").toLowerCase(),s=(o.getAttribute("title")??"").toLowerCase(),a=o.getAttribute("data-biotype")??"",l=(""===e||r.indexOf(e)>=0||s.indexOf(e)>=0)&&(null===t||a===t);o.style.display=l?"":"none"}let o=(i??this.element).querySelectorAll(".hw-triplet-chip");for(let i=0;i<o.length;i++){let n=o[i],r=[n.getAttribute("data-triplet")??"",n.getAttribute("data-sugar")??"",n.getAttribute("data-base")??"",n.getAttribute("data-linker")??""].join(" ").toLowerCase(),s=(""===e||r.indexOf(e)>=0)&&null===t;n.style.display=s?"":"none"}let r=(i??this.element).querySelectorAll(".hw-palette__group");for(let e=0;e<r.length;e++){let t=r[e],i=t.querySelectorAll(".hw-palette__tile, .hw-triplet-chip"),n=!1;for(let e=0;e<i.length;e++)if("none"!==i[e].style.display){n=!0;break}n?(t.removeAttribute("hidden"),t.removeAttribute("data-section-empty")):(t.setAttribute("hidden",""),t.setAttribute("data-section-empty","true"))}}_updatePrimedClasses(){let e=this._editor.getNextAddSymbol(),t=this.element.querySelectorAll(".hw-palette__tile");for(let i=0;i<t.length;i++){let n=t[i],o=n.getAttribute("data-symbol")??"",r=n.getAttribute("data-biotype")??"",s=null!==e&&e.symbol===o&&e.biotype===r,a=(n.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-palette__tile--primed"!==e).join(" ");n.setAttribute("class",s?`${a} hw-palette__tile--primed`:a),n.setAttribute("aria-pressed",s?"true":"false")}}_applyActiveTabClasses(){let e=this.element.querySelectorAll(".hw-palette__tab");for(let t=0;t<e.length;t++){let i=e[t],n=i.getAttribute("data-tab")??"";i.setAttribute("aria-selected",n===this._activeTab?"true":"false")}let t=this.element.querySelectorAll(".hw-palette__pane");for(let e=0;e<t.length;e++){let i=t[e];(i.getAttribute("data-tab")??"")===this._activeTab?i.removeAttribute("hidden"):i.setAttribute("hidden","")}}_localStorage(){if(!this._opts.allowFavorites)return null;let e=this._doc.defaultView;if(null==e)return null;try{return e.localStorage??null}catch{return null}}_resolveInitialTab(e){if(void 0!==e&&Wn.includes(e))return e;let t=this._localStorage();if(null!==t)try{let e=t.getItem(Kn);if(null!==e&&Wn.includes(e))return e}catch{}return Yn}_persistActiveTab(){let e=this._localStorage();if(null!==e)try{e.setItem(Kn,this._activeTab)}catch{}}_loadFavorites(){let e=this._localStorage();if(null!==e){try{let t=e.getItem(Un);if(null!==t&&""!==t){let e=JSON.parse(t),i=this._extractSymbols(e);for(let e of i)this._favorites.add(e);for(let t of this._extractTriplets(e))this._favoriteTriplets.push(t);return}}catch{}try{let t=e.getItem("hwe.palette.favorites");if(null===t||""===t)return;let i=JSON.parse(t);if(Array.isArray(i)){for(let e of i){if("string"!=typeof e)continue;let t=e.indexOf("|"),i=t>=0?e.slice(t+1):e;""!==i&&this._favorites.add(i)}this._saveFavorites()}}catch{}}}_extractSymbols(e){if(Array.isArray(e)){let t=[];for(let i of e)"string"==typeof i&&t.push(i);return t}if(null!==e&&"object"==typeof e){let t=e;if(Array.isArray(t.symbols)){let e=[];for(let i of t.symbols)"string"==typeof i&&e.push(i);return e}}return[]}_extractTriplets(e){if(null===e||"object"!=typeof e)return[];let t=e;if(!Array.isArray(t.triplets))return[];let i=[];for(let e of t.triplets){if(null===e||"object"!=typeof e)continue;let t=e;"string"==typeof t.sugar&&"string"==typeof t.base&&"string"==typeof t.linker&&i.push({sugar:t.sugar,base:t.base,linker:t.linker})}return i}_saveFavorites(){let e=this._localStorage();if(null!==e)try{let t={symbols:Array.from(this._favorites)};this._favoriteTriplets.length>0&&(t.triplets=this._favoriteTriplets.map(e=>({...e}))),e.setItem(Un,JSON.stringify(t))}catch{}}};Qn._DEFAULT_TRIPLET_BASES=["A","C","G","U","T"],Qn._PALETTE_RDKIT_CACHE_LIMIT=256;var Zn=Qn,Jn='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">',eo={new:`${Jn}<path d="M13 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V9z"/><path d="M13 3v6h6"/><line x1="12" y1="12.5" x2="12" y2="17.5"/><line x1="9.5" y1="15" x2="14.5" y2="15"/></svg>`,open:`${Jn}<path d="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"/></svg>`,save:`${Jn}<rect x="8" y="2" width="8" height="4" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="m9 14 2 2 4-4"/></svg>`,undo:`${Jn}<path d="M3 12a9 9 0 1 0 9-9 9.7 9.7 0 0 0-6.7 2.8L3 8"/><path d="M3 3v5h5"/></svg>`,redo:`${Jn}<path d="M21 12a9 9 0 1 1-9-9 9.7 9.7 0 0 1 6.7 2.8L21 8"/><path d="M21 3v5h-5"/></svg>`,eraser:`${Jn}<path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"/><path d="M22 21H7"/><path d="m5 11 9 9"/></svg>`,select:`${Jn}<path d="m4 4 7.07 17 2.51-7.39L21 11.07z"/></svg>`,hbond:`${Jn}<path d="M9 17H7A5 5 0 0 1 7 7h2"/><path d="M15 7h2a5 5 0 1 1 0 10h-2"/><line x1="8" y1="12" x2="16" y2="12"/></svg>`,"zoom-in":`${Jn}<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>`,"zoom-out":`${Jn}<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/><line x1="8" y1="11" x2="14" y2="11"/></svg>`,fit:`${Jn}<polyline points="15 3 21 3 21 9"/><polyline points="9 21 3 21 3 15"/><line x1="21" y1="3" x2="14" y2="10"/><line x1="3" y1="21" x2="10" y2="14"/></svg>`,move:`${Jn}<polyline points="5 9 2 12 5 15"/><polyline points="9 5 12 2 15 5"/><polyline points="15 19 12 22 9 19"/><polyline points="19 9 22 12 19 15"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="12" y1="2" x2="12" y2="22"/></svg>`,clean:`${Jn}<path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z"/><path d="m14 7 3 3"/><path d="M5 6v4"/><path d="M19 14v4"/><path d="M10 2v2"/><path d="M7 8H3"/><path d="M21 16h-4"/><path d="M11 3H9"/></svg>`,find:`${Jn}<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>`,theme:`${Jn}<circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor" stroke="none"/></svg>`},to={new:"New — clear the canvas",open:"Open — paste a HELM string",save:"Save — copy HELM string to clipboard",undo:"Undo last action",redo:"Redo last undone action",eraser:"Eraser — click an atom or bond to delete it",select:"Select mode (default)",hbond:"H-Bond mode — drag between two RNA bases to add a Watson-Crick pair","zoom-in":"Zoom in","zoom-out":"Zoom out",fit:"Fit to content — reset zoom and pan",move:"Move/Pan mode — drag the canvas to scroll",clean:"Clean layout — re-run automatic layout",find:"Find / Replace monomer",theme:"Toggle dark / light theme"},io=[{id:"new",label:"New",icon:"New"},{id:"open",label:"Open",icon:"Open"},{id:"save",label:"Save",icon:"Save"},{id:"undo",label:"Undo",icon:"↺",shortcut:"Ctrl+Z",separator:!0},{id:"redo",label:"Redo",icon:"↻",shortcut:"Ctrl+Y"},{id:"eraser",label:"Eraser",icon:"Eraser",separator:!0},{id:"select",label:"Select",icon:"Select"},{id:"hbond",label:"H-Bond",icon:"H-Bond"},{id:"zoom-in",label:"Zoom In",icon:"+",shortcut:"Ctrl++",separator:!0},{id:"zoom-out",label:"Zoom Out",icon:"−",shortcut:"Ctrl+−"},{id:"fit",label:"Fit",icon:"Fit",shortcut:"0"},{id:"move",label:"Move",icon:"Move"},{id:"clean",label:"Clean",icon:"Clean",separator:!0},{id:"find",label:"Find",icon:"Find",shortcut:"Ctrl+F"},{id:"theme",label:"Theme",icon:"Theme",separator:!0}],no=class{constructor(e,t,i){this._buttons=new Map,this._unsubs=[],this._destroyed=!1,this._editor=t,this._doc=i?.documentImpl??Xi(e);let n=i?.buttons??io;this.element=Qi(this._doc,"div",{class:"hw-toolbar","data-testid":"toolbar"}),e.appendChild(this.element);for(let e of n){if(!0===e.separator){let e=Qi(this._doc,"span",{class:"hw-toolbar__separator"});this.element.appendChild(e)}let t=this._buildButton(e);this.element.appendChild(t),this._buttons.set(e.id,t)}let o=()=>this._refreshHistoryState();this._unsubs.push(t.on("mol:changed",o)),this._unsubs.push(t.on("helm:changed",o)),o(),this._reflectMode(),this._unsubs.push(t.on("option:change",e=>{"mode"===e.key&&this._reflectMode()}))}setButtonEnabled(e,t){let i=this._buttons.get(e);void 0!==i&&(t?i.removeAttribute("disabled"):i.setAttribute("disabled",""))}destroy(){if(!this._destroyed){this._destroyed=!0,this._hideTip();for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_buildButton(e){let t=this._doc.createElement("button");t.setAttribute("class","hw-toolbar__btn"),t.setAttribute("type","button"),t.setAttribute("data-action",e.id),t.setAttribute("data-testid",`toolbar-${e.id}`);let i=to[e.id]??e.label,n=void 0!==e.shortcut?`${i} (${e.shortcut})`:i;t.setAttribute("data-tooltip",n),t.setAttribute("aria-label",i),t.addEventListener("mouseenter",e=>{let t=e;this._showTip(n,"number"==typeof t.clientX?t.clientX:0,"number"==typeof t.clientY?t.clientY:0)}),t.addEventListener("mouseleave",()=>this._hideTip()),t.addEventListener("click",()=>this._hideTip());let o=eo[e.id];if(void 0!==o){let e=this._doc.createElement("span");e.setAttribute("class","hw-toolbar__btn-icon"),e.setAttribute("aria-hidden","true"),e.innerHTML=o,t.appendChild(e)}else{let i=e.icon??e.label;t.appendChild(this._doc.createTextNode(i))}return t.addEventListener("click",()=>this._invoke(e.id)),t}_showTip(e,t,i){let n=Ji(this._doc,"toolbar-tooltip","hw-toolbar-tooltip");for(;null!==n.firstChild;)n.removeChild(n.firstChild);n.appendChild(this._doc.createTextNode(e)),tn(n,t,i)}_hideTip(){nn(this._doc.body.querySelector('[data-testid="toolbar-tooltip"]'))}_invoke(e){let t=!1;this._editor.fire("key:command",{command:e,preventDefault:()=>{t=!0}}),!t&&this._execute(e)}_execute(e){switch(e){case"new":return void this._editor.setHelm("");case"open":{let e=this._doc.defaultView;if(null!=e&&"function"==typeof e.prompt){let t=e.prompt("Enter HELM string");null!==t&&this._editor.setHelm(t)}return}case"save":{let e=this._editor.getHelm();return void this._editor.fire("clipboard:copy",{format:"helm",payload:e})}case"undo":return void this._editor.undo();case"redo":return void this._editor.redo();case"eraser":return this._editor.getSelection().isEmpty?void this._editor.setMode("eraser"):void this._editor.deleteSelection();case"select":case"hbond":case"move":return void this._editor.setMode(e);case"zoom-in":return void this._editor.zoom(1.1,this._molCenterOrUndefined());case"zoom-out":return void this._editor.zoom(1/1.1,this._molCenterOrUndefined());case"fit":return void this._editor.fitToContent();case"clean":return void this._editor.cleanLayout();case"find":return void this._editor.openFindReplace();case"theme":{let e=this._editor,t="function"==typeof e._currentTheme?e._currentTheme():null,i=null!==t&&"dark"===t.name;return void this._editor.setTheme(i?Dt:Ft)}default:return}}_refreshHistoryState(){this.setButtonEnabled("undo",this._editor.canUndo()),this.setButtonEnabled("redo",this._editor.canRedo())}_molCenterOrUndefined(){let e=this._editor.getMol();if(0===e.atoms.length)return;let t=e.atoms[0].p.x,i=t,n=e.atoms[0].p.y,o=n;for(let r=1;r<e.atoms.length;r++){let s=e.atoms[r].p;s.x<t&&(t=s.x),s.x>i&&(i=s.x),s.y<n&&(n=s.y),s.y>o&&(o=s.y)}return{x:(t+i)/2,y:(n+o)/2}}_reflectMode(){let e=this._editor.getMode();for(let t of["select","eraser","hbond","move"]){let i=this._buttons.get(t);if(void 0===i)continue;let n=(i.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-toolbar__btn--active"!==e).join(" ");i.setAttribute("class",t===e?`${n} hw-toolbar__btn--active`:n)}}},oo=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._content=Qi(this._doc,"pre",{class:"hw-pane__content hw-pane__sequence","data-testid":"sequence-pane-content"}),this.element=Qi(this._doc,"div",{class:"hw-pane hw-pane--sequence","data-testid":"pane-sequence"},[this._content]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on("helm:changed",()=>this.refresh())),this._unsubs.push(t.on("mol:changed",()=>this.refresh()))}refresh(){if(this._destroyed)return;let e=this._compute();for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_compute(){let e,t=this._editor.getMol(),i=[];for(let n of t.atoms){let t=n.bio.chainId;void 0!==e&&t!==e&&i.push("|"),e=t;let o=n.monomer?.naturalAnalog;i.push(void 0!==o&&""!==o?o:n.symbol)}return i.join("")}},ro=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._suppressNext=!1,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._input=Qi(this._doc,"div",{class:"hw-pane__content hw-pane__notation",contenteditable:"true",spellcheck:"false","data-testid":"notation-pane-content"}),this._error=Qi(this._doc,"div",{class:"hw-pane__error","data-testid":"notation-pane-error"}),this.element=Qi(this._doc,"div",{class:"hw-pane hw-pane--notation","data-testid":"pane-helm"},[this._input,this._error]),e.appendChild(this.element),this.refresh(),this._input.addEventListener("blur",()=>this._commit()),this._input.addEventListener("keydown",e=>{"Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this._commit())}),this._unsubs.push(t.on("helm:changed",()=>{this._suppressNext?this._suppressNext=!1:this.refresh()})),this._unsubs.push(t.on("mol:changed",()=>this.refresh()))}refresh(){if(this._destroyed)return;let e=this._editor.getHelm();for(;null!==this._input.firstChild;)this._input.removeChild(this._input.firstChild);this._input.appendChild(this._doc.createTextNode(e)),this._clearError()}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_commit(){if(this._destroyed)return;let e=(this._input.textContent??"").trim();if(e===this._editor.getHelm())return void this._clearError();let t=this._editor.getService().validate(e).filter(e=>"error"===e.severity);t.length>0?this._showError(t.map(e=>e.message).join("; ")):(this._clearError(),this._suppressNext=!0,this._editor.setHelm(e))}_showError(e){for(;null!==this._error.firstChild;)this._error.removeChild(this._error.firstChild);this._error.appendChild(this._doc.createTextNode(e)),this._error.setAttribute("class","hw-pane__error hw-pane__error--visible")}_clearError(){for(;null!==this._error.firstChild;)this._error.removeChild(this._error.firstChild);this._error.setAttribute("class","hw-pane__error")}},so=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._body=Qi(this._doc,"div",{class:"hw-pane__content hw-pane__properties","data-testid":"properties-pane-content"}),this.element=Qi(this._doc,"div",{class:"hw-pane hw-pane--properties","data-testid":"pane-properties"},[this._body]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on("helm:changed",()=>this.refresh())),this._unsubs.push(t.on("mol:changed",()=>this.refresh()))}refresh(){if(this._destroyed)return;for(;null!==this._body.firstChild;)this._body.removeChild(this._body.firstChild);let e=this._editor.getHelm();if(e.length>1e3)return void this._body.appendChild(Qi(this._doc,"div",{class:"hw-pane__placeholder"},["(too long)"]));let t=this._editor.getService(),i="",n=0,o=0;try{let o=t.getFormula(e);i=function(e){let t=Array.from(e.keys()).sort((e,t)=>e===t?0:"C"===e?-1:"C"===t?1:"H"===e?-1:"H"===t?1:e.localeCompare(t)),i="";for(let n of t){let t=e.get(n);void 0===t||0===t||(i+=1===t?n:`${n}${t}`)}return""===i?"—":i}(o.elements),n=o.mw}catch{i="—"}try{n=t.getMolWeight(e)}catch{}try{o=t.getExtinctionCoefficient(e)}catch{}this._body.appendChild(this._makeRow("Formula",i,"formula")),this._body.appendChild(this._makeRow("Molecular Weight",0===n?"—":n.toFixed(2),"mw")),this._body.appendChild(this._makeRow("Extinction Coefficient",0===o?"—":o.toFixed(0),"extinction"))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_makeRow(e,t,i){let n=Qi(this._doc,"span",{class:"hw-pane__prop-label"},[e]),o=Qi(this._doc,"span",{class:"hw-pane__prop-value","data-testid":`properties-${i}`},[t]);return Qi(this._doc,"div",{class:"hw-pane__prop-row"},[n,o])}},ao=class{constructor(e,t,i){this._unsubs=[],this._destroyed=!1,this._refreshToken=0,this._editor=t,this._doc=i?.documentImpl??Xi(e),this._content=Qi(this._doc,"pre",{class:"hw-pane__content hw-pane__atomic","data-testid":"atomic-pane-content"}),this.element=Qi(this._doc,"div",{class:"hw-pane hw-pane--atomic","data-testid":"pane-atomic"},[this._content]),e.appendChild(this.element),this.refresh(),this._unsubs.push(t.on("helm:changed",()=>{this.refresh()}))}async refresh(){if(this._destroyed)return;let e=++this._refreshToken,t=this._editor.getHelm(),i=this._editor.getService();if(i.hasAtomicMolfileProvider())try{let n=await i.getAtomicMolfile(t);if(this._destroyed||e!==this._refreshToken)return;this._render(n)}catch(t){if(this._destroyed||e!==this._refreshToken)return;let i=t instanceof Error?t.message:String(t);this._render(`Atomic structure unavailable: ${i}`)}else this._render("Atomic structure unavailable")}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_render(e){for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e))}};function lo(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}var ho=class{constructor(e,t,i,n,o){this._unsubs=[],this._destroyed=!1,this._active=!1,this._dirty=!0,this._refreshToken=0,this._editor=t,this._provider=n,this.name=i,this._doc=o?.documentImpl??Xi(e);let r=lo(i);this._content=Qi(this._doc,"div",{class:"hw-pane__content hw-pane__extra","data-testid":`extra-pane-content-${r}`}),this.element=Qi(this._doc,"div",{class:"hw-pane hw-pane--extra","data-testid":`pane-extra-${r}`},[this._content]),e.appendChild(this.element),this._unsubs.push(t.on("helm:changed",()=>{this._dirty=!0,this._active&&this.refresh()}))}setActive(e){this._active=e,e&&this._dirty&&this.refresh()}async refresh(){if(this._destroyed)return;let e=++this._refreshToken;this._dirty=!1;let t=this._editor.getHelm();try{let i=await this._provider(t);if(this._destroyed||e!==this._refreshToken)return;this._mount(i)}catch(t){if(this._destroyed||e!==this._refreshToken)return;let i=t instanceof Error?t.message:String(t);this._renderText(`Pane "${this.name}" failed: ${i}`)}}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}_mount(e){for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(e)}_renderText(e){for(;null!==this._content.firstChild;)this._content.removeChild(this._content.firstChild);this._content.appendChild(this._doc.createTextNode(e))}};function co(e){return"extra:"+e}var uo=[{id:"sequence",label:"Sequence"},{id:"helm",label:"HELM"},{id:"properties",label:"Properties"},{id:"atomic",label:"Atomic Structure"}],po=class{constructor(e,t){this._paneByName=new Map,this._tabsByName=new Map,this._unsubs=[],this._activePane="helm",this._destroyed=!1,this._statusModeNode=null,this._statusMessageNode=null,this._statusMessageTimeout=null,this._host=e,this._doc=t.documentImpl??Xi(e);let i="dark"===(t.theme??Dt).name?"hw-app hw-app--dark":"hw-app";this.element=Qi(this._doc,"div",{class:i,"data-testid":"app-root"}),this._toolbarHost=Qi(this._doc,"div",{class:"hw-app__toolbar"}),this._paletteHost=Qi(this._doc,"div",{class:"hw-app__palette"}),this._canvasHost=Qi(this._doc,"div",{class:"hw-app__canvas","data-testid":"canvas-host"});let n=Qi(this._doc,"div",{class:"hw-app__main"},[this._paletteHost,this._canvasHost]);this._tabsHost=Qi(this._doc,"div",{class:"hw-app__tabs",role:"tablist"}),this._paneBody=Qi(this._doc,"div",{class:"hw-app__pane-body"});let o=Qi(this._doc,"div",{class:"hw-app__panes"},[this._tabsHost,this._paneBody]);this.element.appendChild(this._toolbarHost),this.element.appendChild(n),this.element.appendChild(o),e.appendChild(this.element);let r={service:t.service};void 0!==t.initialHelm&&(r.initialHelm=t.initialHelm),void 0!==t.width&&(r.width=t.width),void 0!==t.height&&(r.height=t.height),this.canvas=new Ln(this._canvasHost,r),void 0!==t.theme&&this.canvas.setTheme(t.theme);let s={documentImpl:this._doc};void 0!==t.toolbarButtons&&(s.buttons=t.toolbarButtons),this.toolbar=new no(this._toolbarHost,this.canvas,s),this.palette=new Zn(this._paletteHost,this.canvas,{documentImpl:this._doc,...t.paletteOptions}),this.sequencePane=new oo(this._paneBody,this.canvas,{documentImpl:this._doc}),this.notationPane=new ro(this._paneBody,this.canvas,{documentImpl:this._doc}),this.propertiesPane=new so(this._paneBody,this.canvas,{documentImpl:this._doc}),t.service.hasAtomicMolfileProvider()?this.atomicStructurePane=new ao(this._paneBody,this.canvas,{documentImpl:this._doc}):this.atomicStructurePane=null,this._paneByName.set("sequence",this.sequencePane.element),this._paneByName.set("helm",this.notationPane.element),this._paneByName.set("properties",this.propertiesPane.element),null!==this.atomicStructurePane&&this._paneByName.set("atomic",this.atomicStructurePane.element);let a=[];for(let[e,i]of t.service.getExtraPanes()){let t=new ho(this._paneBody,this.canvas,e,i,{documentImpl:this._doc});a.push(t),this._paneByName.set(co(e),t.element)}this.extraPanes=a;let l=this._resolveVisiblePanes(t),h=[];for(let e of l){let t=uo.find(t=>t.id===e);void 0!==t&&h.push({id:t.id,label:t.label,testid:`tab-${t.id}`})}for(let e of a)h.push({id:co(e.name),label:e.name,testid:`tab-extra-${lo(e.name)}`});for(let{id:e,label:t,testid:i}of h){let n=this._doc.createElement("button");n.setAttribute("type","button"),n.setAttribute("class","hw-app__tab"),n.setAttribute("role","tab"),n.setAttribute("data-pane",e),n.setAttribute("data-testid",i),n.appendChild(this._doc.createTextNode(t)),n.addEventListener("click",()=>this.activatePane(e)),this._tabsHost.appendChild(n),this._tabsByName.set(e,n)}let d=l.includes("helm")?"helm":l[0]??"helm";this.activatePane(d),this._unsubs.push(this.canvas.on("theme:change",e=>this._applyTheme(e.theme))),this._buildStatusBar(),this._applyMode(this.canvas.getMode()),this._unsubs.push(this.canvas.on("option:change",e=>{"mode"===e.key&&this._applyMode(e.newValue),"nextAdd"===e.key&&this._refreshStatus()})),this._unsubs.push(this.canvas.on("mol:changed",()=>this._refreshStatus())),this._unsubs.push(this.canvas.on("helm:changed",()=>this._refreshStatus())),this._unsubs.push(this.canvas.on("editor:status",e=>{this._showStatusMessage(e.message,e.severity,e.durationMs)})),this._unsubs.push(this.canvas.on("monomer:contextmenu",e=>{e.preventDefault(),this.canvas.openAtomProps(e.atom)})),this._unsubs.push(this.canvas.on("bond:contextmenu",e=>{e.preventDefault(),this.canvas.openBondProps(e.bond)})),this._onDocKeydown=e=>this._handleEscape(e),this._doc.addEventListener("keydown",this._onDocKeydown,!0)}_handleEscape(e){let t=e;"Escape"===t.key&&(on(this._doc),hn.closeTopmost()&&(t.stopImmediatePropagation?.(),t.preventDefault?.()))}_buildStatusBar(){let e=Qi(this._doc,"div",{class:"hw-status-bar","data-testid":"status-bar"}),t=Qi(this._doc,"span",{class:"hw-status-bar__mode","data-testid":"status-mode"}),i=Qi(this._doc,"span",{class:"hw-status-bar__message","data-testid":"status-message",role:"status","aria-live":"polite"});e.appendChild(t),e.appendChild(i),this._canvasHost.appendChild(e),this._statusModeNode=t,this._statusMessageNode=i,this._refreshStatus()}_refreshStatus(){let e=this._statusModeNode;if(null===e)return;let t=this.canvas.getMode(),i=this.canvas.getNextAddSymbol();for(;null!==e.firstChild;)e.removeChild(e.firstChild);if(null===i)return void e.appendChild(this._doc.createTextNode(`Mode: ${t} | Next add: none`));e.appendChild(this._doc.createTextNode(`Mode: ${t} | Next add: `));let n=Qi(this._doc,"span",{class:"hw-status-bar__next-add-symbol","data-testid":"status-next-add-symbol"},[i.symbol]);e.appendChild(n);let o=Qi(this._doc,"button",{type:"button",class:"hw-status-bar__next-add-clear","data-testid":"status-next-add-clear","aria-label":"Clear next-add monomer",title:"Clear (Esc)"},["×"]);o.addEventListener("click",e=>{e.preventDefault(),e.stopPropagation(),this.canvas.setNextAddSymbol(null)}),e.appendChild(o)}_showStatusMessage(e,t,i){let n=this._statusMessageNode;if(null!==n){for(null!==this._statusMessageTimeout&&(clearTimeout(this._statusMessageTimeout),this._statusMessageTimeout=null);null!==n.firstChild;)n.removeChild(n.firstChild);n.appendChild(this._doc.createTextNode(e)),n.setAttribute("data-severity",t),i>0&&(this._statusMessageTimeout=setTimeout(()=>{let e=this._statusMessageNode;if(null!==e){for(;null!==e.firstChild;)e.removeChild(e.firstChild);e.removeAttribute("data-severity"),this._statusMessageTimeout=null}},i))}}_applyMode(e){let t=this._canvasHost.querySelector(".hw-editor-view");if(null===t)return;let i=(t.getAttribute("class")??"").split(/\s+/).filter(e=>!e.startsWith("hw-editor-view--")).join(" ");t.setAttribute("class",`${i} hw-editor-view--${e}`.trim()),this._refreshStatus()}setHelm(e){this.canvas.setHelm(e)}getHelm(){return this.canvas.getHelm()}on(e,t){return this.canvas.on(e,t)}activatePane(e){if(this._paneByName.has(e)||this._tabsByName.has(e)){this._activePane=e;for(let[t,i]of this._paneByName.entries())i.style.display=t===e?"":"none";for(let[t,i]of this._tabsByName.entries()){let n=(i.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-app__tab--active"!==e).join(" ");i.setAttribute("class",t===e?`${n} hw-app__tab--active`:n)}for(let e of this.extraPanes)e.setActive(this._activePane===co(e.name))}}getActivePane(){return this._activePane}destroy(){if(!this._destroyed){this._destroyed=!0,null!==this._statusMessageTimeout&&(clearTimeout(this._statusMessageTimeout),this._statusMessageTimeout=null),this._doc.removeEventListener("keydown",this._onDocKeydown,!0);for(let e of this._unsubs)e();for(let e of this.extraPanes)e.destroy();null!==this.atomicStructurePane&&this.atomicStructurePane.destroy(),this.propertiesPane.destroy(),this.notationPane.destroy(),this.sequencePane.destroy(),this.palette.destroy(),this.toolbar.destroy(),this.canvas.destroy(),null!==this.element.parentNode&&this.element.parentNode.removeChild(this.element),this._host}}_resolveVisiblePanes(e){let t=e.service.hasAtomicMolfileProvider(),i=e.visiblePanes??["sequence","helm","properties","atomic"];return t||(i=i.filter(e=>"atomic"!==e)),i}_applyTheme(e){let t="dark"===e.name,i=(this.element.getAttribute("class")??"").split(/\s+/).filter(e=>"hw-app--dark"!==e).join(" ");this.element.setAttribute("class",t?`${i} hw-app--dark`:i)}},mo=class{constructor(e){this.T="ATOM",this.selected=e.selected,this.highlighted=e.highlighted,this.p={x:e.p.x,y:e.p.y},this.elem=e.symbol,this.bio={type:e.biotype,continuousId:e.bio.continuousId,chainId:e.bio.chainId,positionInChain:e.bio.positionInChain,...void 0!==e.bio.annotation?{annotation:e.bio.annotation}:{},...void 0!==e.bio.blobtype?{blobtype:e.bio.blobtype}:{},...void 0!==e.bio.ambiguity?{ambiguity:e.bio.ambiguity}:{},id:e.id},void 0!==e.inlineSource&&(this.inlineSource=e.inlineSource)}biotype(){return this.bio.type}},fo=class{constructor(e,t,i){this.a1=t,this.a2=i,this.r1=bo(e.r1),this.r2=bo(e.r2),this.kind=e.kind}};function bo(e){switch(e.kind){case"numeric":case"positional":return e.r;default:return 0}}function go(e){let t=[],i=new Map;for(let n of e.atoms){let e=new mo(n);t.push(e),i.set(n.id,e)}let n=[];for(let t of e.bonds){let e=i.get(t.a1.id),o=i.get(t.a2.id);void 0===e||void 0===o||n.push(new fo(t,e,o))}return{atoms:t,bonds:n,clone:t=>go(e),_internalMol:e}}var Ao=class{constructor(e,t,i){this._laidMol=null,this._currentHelm="",this._drawOptions={fontsize:14},this._noDraw=!1,this._svgEl=null,this.host=e,this._service=t,this._doc=i?.documentImpl??Xi(e),this._width=i?.width??400,this._height=i?.height??100,this._mol=b(),this._molView=go(this._mol),this.editor=this._buildEditor()}resizeEditor(e,t){this._width=e,this._height=t,this._redraw()}_buildEditor(){let e=this,t={get noDraw(){return e._noDraw},set noDraw(t){e._noDraw=t},get jsd(){return e.editor}};return{get div(){return e.host},get m(){return e._molView},set m(t){e._molView=t},get helm(){return t},get options(){return{width:e._width,height:e._height}},setData(t,i){if("helm"!==i)throw new Error(`LegacyEditorWrapper: only 'helm' format supported (got '${i}').`);e._setHelm(t)},setHelm(t){e._setHelm(t)},setMol(t){e._mol=t._internalMol,e._molView=e._buildView(e._mol),e._currentHelm=e._service.serialize(e._mol),e._redraw()},getHelm:t=>e._currentHelm,getMolfile:()=>Mi(e._mol),resize(t,i){e._width=t,e._height=i,e._redraw()},setSize(t,i){e._width=t,e._height=i,e._redraw()},redraw(){e._redraw()},reset(){e._mol=b(),e._laidMol=null,e._molView=go(e._mol),e._currentHelm="",e._removeSvg()},getFormula:t=>function(e){let t=e=>{let t=_o.indexOf(e);return-1===t?_o.length:t},i=[...e.elements.keys()].sort((e,i)=>{let n=t(e),o=t(i);return n!==o?n-o:e<i?-1:e>i?1:0}),n=[];for(let t of i){let i=e.elements.get(t);n.push(1===i?t:`${t}${i}`)}return n.join("")}(fi(e._mol)),getMolWeight:()=>wi(e._mol),getExtinctionCoefficient:()=>ki(e._mol),getDrawOptions:()=>e._drawOptions}}_setHelm(e){this._currentHelm=e;let t=this._service.parse(e,{mode:"lenient",resolveMonomers:!0});this._mol=t.mol,this._molView=this._buildView(this._mol),this._redraw()}_buildView(e){return this._laidMol=this._noDraw?null:Et(e),go(this._laidMol??e)}_redraw(){if(this._noDraw)return void this._removeSvg();if(""===this._currentHelm||null===this._laidMol)return void this._removeSvg();let e=new Set,t=new Set;for(let i of this._molView.atoms){let n=i.bio.id;void 0!==n&&(i.selected&&e.add(n),i.highlighted&&t.add(n))}let i=this._service.renderMolResult(this._laidMol,{width:this._width,height:this._height,maxScale:1/0,showIds:!0,selectedAtomIds:e,highlightedAtomIds:t});this._bakeViewToSurface(i.bbox,i.drawBox),this._mountSvg(i.svg)}_bakeViewToSurface(e,t){if(null===this._laidMol)return;let i=t.scale,n=t.x-e.x*i,o=t.y-e.y*i,r=this._laidMol.atoms,s=this._molView.atoms,a=Math.min(r.length,s.length);for(let e=0;e<a;e++){let t=r[e].p,a=s[e].p;a.x=t.x*i+n,a.y=t.y*i+o}}_mountSvg(e){this._removeSvg();let t=function(e,t,i,n){let o=function(e,t){let i=globalThis.DOMParser;if(void 0===i)return null;try{let n=(new i).parseFromString(t,"image/svg+xml").documentElement;return null==n?null:e.importNode(n,!0)}catch{return null}}(e,t);if(null!==o)return o;let r=e.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(i)),r.setAttribute("height",String(n)),r}(this._doc,e,this._width,this._height);t.setAttribute("pointer-events","none"),null!==this.host.firstChild?this.host.insertBefore(t,this.host.firstChild):this.host.appendChild(t),this._svgEl=t}_removeSvg(){null!==this._svgEl&&null!==this._svgEl.parentNode&&this._svgEl.parentNode.removeChild(this._svgEl),this._svgEl=null}},_o=["C","H","N","O","S","P"],yo=class{constructor(e){this._width=0,this._height=0,this._doc=e}resize(e,t){this._width=e,this._height=t}select(){}dblclick(){}createMonomerDiv(e,t,i){let n=Qi(this._doc,"div",{"data-monomer":t,"data-biotype":i,"data-testid":`legacy-mex-monomer-${t}`});return e.appendChild(n),n}getSize(){return{width:this._width,height:this._height}}},vo=class{constructor(e,t,i){this.toolbarheight=32,this._drawOptions={fontsize:14},this._unsubs=[],this._destroyed=!1,this._host=e,this._service=t,this._doc=i?.documentImpl??Xi(e),this._width=i?.width??800,this._height=i?.height??400;let n={service:t};void 0!==i?.initialHelm&&(n.initialHelm=i.initialHelm),void 0!==i?.documentImpl&&(n.documentImpl=i.documentImpl),void 0!==i?.width&&(n.width=i.width),void 0!==i?.height&&(n.height=i.height),this._app=new po(e,n),this.sequence=this._app.sequencePane.element,this.notation=this._app.notationPane.element,this.properties={parent:this._app.propertiesPane.element},this._structureviewHost=Qi(this._doc,"div",{class:"hwe-legacy-app__structureview","data-testid":"legacy-app-structureview"}),this._structureviewWrapper=new Ao(this._structureviewHost,t,{documentImpl:this._doc}),this.structureview=this._structureviewWrapper,this.mex=new yo(this._doc),this._editorFacade=this._buildEditorFacade();let o=this._editorFacade;this.canvas={get host(){return o.div},get editor(){return o},get helm(){return o.helm},resizeEditor:(e,t)=>{this._resize(e,t)},getHelm:e=>o.getHelm(e),setHelm:e=>{o.setHelm(e)}};let r=()=>{this._structureviewWrapper.editor.setHelm(this._app.getHelm())};this._unsubs.push(this._app.canvas.on("helm:changed",r)),void 0!==i?.initialHelm&&i.initialHelm.length>0&&r()}get editorApp(){return this._app}_buildEditorFacade(){let e=this,t=this._app,i={noDraw:!1,get jsd(){return e._editorFacade}};return{get div(){return t.element},get m(){return e._currentMolView()},set m(e){null!=e&&void 0!==e._internalMol&&t.canvas.setMol(e._internalMol)},get helm(){return i},get options(){return{width:e._width,height:e._height}},setData(e,i){if("helm"!==i)throw new Error(`LegacyAppWrapper: only 'helm' format supported (got '${i}').`);t.setHelm(e)},setHelm(e){t.setHelm(e)},setMol(e){t.canvas.setMol(e._internalMol)},getHelm:e=>t.getHelm(),getMolfile:()=>e._service.getMolfile(t.getHelm()),resize(t,i){e._resize(t,i)},setSize(t,i){e._resize(t,i)},redraw(){t.canvas.redraw()},reset(){t.setHelm("")},getFormula:e=>function(e){let t=[];for(let[i,n]of e.elements.entries())t.push(1===n?i:`${i}${n}`);return t.join("")}(fi(t.canvas.getMol())),getMolWeight:()=>wi(t.canvas.getMol()),getExtinctionCoefficient:()=>ki(t.canvas.getMol()),getDrawOptions:()=>e._drawOptions}}_currentMolView(){let e=go(this._app.canvas.getMol()),t=this._app.canvas.getSelection();if(!t.isEmpty)for(let i of e.atoms){let e=i.bio.id;"number"==typeof e&&(i.selected=t.atoms.has(e))}return e}_resize(e,t){this._width=e,this._height=t,this._app.canvas.resize(e,t)}calculateSizes(){let e=wo(this._host.clientWidth,this._width),t=wo(this._host.clientHeight,this._height);this._resize(e,Math.max(50,t-this.toolbarheight))}destroy(){if(!this._destroyed){this._destroyed=!0;for(let e of this._unsubs)e();this._unsubs.length=0,this._app.destroy()}}};function wo(e,t){return"number"!=typeof e||isNaN(e)||e<=0?t:e}var xo=class{constructor(e,t,i){this._tooltip=null,this._destroyed=!1,this.name=e,this._service=t;let n=i?.documentImpl??globalThis.document??null;if(null===n)throw new Error("LegacyInputWrapper: no Document available.");this._doc=n,this._host=Qi(this._doc,"div",{class:"hwe-legacy-input","data-testid":"legacy-input-host"}),this.viewer=new Ao(this._host,t,{width:i?.editorOptions?.width??240,height:i?.editorOptions?.height??80,documentImpl:this._doc})}get value(){return this.viewer.editor.getHelm()}set value(e){this._ensureLive(),this.viewer.editor.setHelm(e)}get molValue(){return this.viewer.editor.m}set molValue(e){this._ensureLive(),this.viewer.editor.setMol(e)}redraw(){this._ensureLive(),this.viewer.editor.redraw()}showTooltip(e,t){this._ensureLive(),null!==this._tooltip&&null!==this._tooltip.parentNode&&this._tooltip.parentNode.removeChild(this._tooltip);let i=Qi(this._doc,"div",{class:"hwe-legacy-input__tooltip","data-testid":"legacy-input-tooltip",style:`position: absolute; left: ${t.p.x}px; top: ${t.p.y}px;`});"string"==typeof e?i.appendChild(this._doc.createTextNode(e)):i.appendChild(e),this._host.appendChild(i),this._tooltip=i}destroy(){this._destroyed||(this._destroyed=!0,null!==this._tooltip&&null!==this._tooltip.parentNode&&this._tooltip.parentNode.removeChild(this._tooltip),null!==this._host.parentNode&&this._host.parentNode.removeChild(this._host))}getHost(){return this._host}getTooltip(){return this._tooltip}_ensureLive(){if(this._destroyed)throw new Error("LegacyInputWrapper: this instance has been destroyed.");this._service}},Co=/^R([1-9][0-9]*)$/,ko=new Set([B.PEPTIDE,B.RNA,B.CHEM,B.BLOB]),Eo=new Set(["Backbone","Branch","Terminal","Undefined"]);function Bo(e){if("string"!=typeof e.symbol||0===e.symbol.length||"string"!=typeof e.molfile||!ko.has(e.polymerType)||!Eo.has(e.monomerType))return null;let t=[];for(let i of e.rgroups??[]){if("string"!=typeof i.label||!Co.test(i.label))continue;let e={label:i.label,capGroupName:"string"==typeof i.capGroupName?i.capGroupName:"",capGroupSMILES:ie(i)??""};"string"==typeof i.alternateId&&(e.alternateId=i.alternateId),t.push(e)}let i={symbol:e.symbol,molfile:e.molfile,polymerType:e.polymerType,monomerType:e.monomerType,rgroups:t};return"string"==typeof e.name&&(i.name=e.name),"string"==typeof e.smiles&&(i.smiles=e.smiles),"string"==typeof e.naturalAnalog&&(i.naturalAnalog=e.naturalAnalog),void 0!==e.meta&&null!==e.meta&&(i.meta={...e.meta}),"string"==typeof e.author&&(i.author=e.author),void 0!==e.createDate&&(i.createDate=e.createDate),"number"==typeof e.id&&(i.id=e.id),i}function So(e,t,i){if(e===B.PEPTIDE)return y;if(e===B.CHEM)return C;if(e===B.BLOB)return k;if(e===B.RNA){if("Branch"===t)return w;if("Backbone"===t)return"P"===i||"p"===i?x:v}return y}var Mo=class{constructor(e,t){this._cache=new Map,this._polymerTypesCache=null,this._version=0,this._base=e,this.source=t??("string"==typeof e.source?e.source:"datagrok-bridge"),this.onChanged=new I,this._unsub=function(e,t){let i=e.subscribe(t);return()=>{null!=i&&"function"==typeof i.unsubscribe&&i.unsubscribe()}}(e.onChanged,()=>{this._cache.clear(),this._polymerTypesCache=null,this._version+=1,this.onChanged.next({type:"reload"})})}get version(){return this._version}get isEmpty(){return"boolean"==typeof this._base.isEmpty?this._base.isEmpty:0===this.getPolymerTypes().length}getMonomer(e,t){let i=`${e}|${t}`;if(this._cache.has(i))return this._cache.get(i)??null;let n=this._base.getMonomer(e,t),o=null==n?null:this._enrichColors(Bo(n));return this._cache.set(i,o),o}_enrichColors(e){if(null===e)return null;let t=this._base;if("function"!=typeof t.getMonomerColors)return e;let i=So(e.polymerType,e.monomerType,e.naturalAnalog),n=null;try{n=t.getMonomerColors(i,e.symbol)}catch{n=null}if(null==n)return e;let o=n.backgroundcolor,r=n.textcolor,s=n.linecolor;if("string"!=typeof o||"string"!=typeof r||"string"!=typeof s)return e;let a={...e.meta??{},colors:{...e.meta?.colors??{},default:{line:s,text:r,background:o}}};return{...e,meta:a}}registerInlineSmilesMonomer(e,t){let i=this._base;var n;"function"==typeof i.getWebEditorMonomer&&i.getWebEditorMonomer((n=e)===B.PEPTIDE?y:n===B.RNA?v:n===B.CHEM?C:n===B.BLOB?k:y,t);let o=i.getMonomer(e,t),r=null==o?null:this._enrichColors(Bo(o));if(null===r)throw new Error(`BridgedMonomerLib: could not register inline SMILES monomer '${t}'`);return this._cache.set(`${e}|${t}`,r),this._cache.set(`${e}|${r.symbol}`,r),r}getMonomerSet(e){let t=new Map;for(let i of this.getPolymerTypes())for(let n of this.getMonomerSymbolsByType(i)){let o=this.getMonomer(i,n);null!==o&&So(o.polymerType,o.monomerType,o.naturalAnalog)===e&&t.set(n,o)}return t}getMonomerSymbolsByType(e){return this._base.getMonomerSymbolsByType(e)}getByNaturalAnalog(e,t){let i=[];for(let n of this.getMonomerSymbolsByType(e)){let o=this.getMonomer(e,n);null!==o&&o.naturalAnalog===t&&i.push(o)}return i}getPolymerTypes(){if(null!==this._polymerTypesCache)return this._polymerTypesCache;let e=[],t="function"==typeof this._base.getPolymerTypes?this._base.getPolymerTypes():Object.values(B);for(let i of t){if(!ko.has(i))continue;let t=this._base.getMonomerSymbolsByType(i);Array.isArray(t)&&t.length>0&&e.push(i)}return this._polymerTypesCache=e,e}getColors(e,t){let i="dark"===t?ee:Z;return te(e,null===e?y:So(e.polymerType,e.monomerType,e.naturalAnalog),i)}addMonomer(e){throw new Error("BridgedMonomerLib: mutation is not supported on a Datagrok-bridged library.")}removeMonomer(e,t){return!1}merge(e){throw new Error("BridgedMonomerLib: mutation is not supported on a Datagrok-bridged library.")}toJSON(){let e=[];for(let t of this.getPolymerTypes())for(let i of this.getMonomerSymbolsByType(t)){let n=this.getMonomer(t,i);null!==n&&e.push(n)}return e}destroy(){this._unsub(),this.onChanged.complete(),this._cache.clear()}};function To(e,t){return new Mo(e,t)}var Io=class e{constructor(e){if(this._overriddenFuncs=null,this._originalFuncs=null,this._molfilesEditor=null,this._molfilesEditorHost=null,this._molfilesGcTimer=null,void 0===e.service||null===e.service)throw new TypeError("HelmHelperAdapter: options.service is required");this._service=e.service,this.seqHelper=e.seqHelper??null,this._logger=e.logger??new h,this._bridge=e.monomerLibBridge??(e=>To(e)),this._doc=e.documentImpl??$o()}get service(){return this._service}createHelmInput(e,t){let i={...t};return void 0===i.documentImpl&&null!==this._doc&&(i.documentImpl=this._doc),new xo(e,this._service,i)}createHelmWebEditor(e,t){let i=e??this._createDetachedHost();return new Ao(i,this._service,{...void 0!==t?.width?{width:t.width}:{},...void 0!==t?.height?{height:t.height}:{},...null!==this._doc?{documentImpl:this._doc}:{}})}createWebEditorApp(e,t){return new vo(e,this._service,{...void 0!==t?{initialHelm:t}:{},...null!==this._doc?{documentImpl:this._doc}:{}})}get originalMonomersFuncs(){return this._originalFuncs}buildMonomersFuncsFromLib(e){let t=this._bridge(e),i=e;return{getMonomer:function(e,n){if("function"==typeof i.getWebEditorMonomer){let t=i.getWebEditorMonomer(e,n);if(null!=t)return t}let{biotype:o,symbol:r}=Po(e,n);if(null===r)return null;let s=(h=r).length>=2&&"["===h.charAt(0)&&"]"===h.charAt(h.length-1)?h.slice(1,h.length-1):h,a=Ro(o),l=t.getMonomer(a,s);var h;return null===l?null:Ho(l,s)},getMonomerSet:function(e){let{biotype:i}=Po(e,void 0),n=Ro(i),o={};for(let e of t.getMonomerSymbolsByType(n)){let i=t.getMonomer(n,e);null!==i&&(o[e]=Ho(i,e))}return o}}}overrideMonomersFuncs(e){let t=this._overriddenFuncs;return null===this._originalFuncs&&(this._originalFuncs=t??this._defaultFuncs()),this._overriddenFuncs=e,t??this._originalFuncs}revertOriginalMonomersFuncs(){let e=this._originalFuncs??this._defaultFuncs(),t=this._overriddenFuncs??e;return this._overriddenFuncs=e,this._originalFuncs=null,t}getHoveredAtom(e,t,i,n){let o=new Yi(i._internalMol,Dt).test({x:e,y:t});if(null===o||void 0===o.atom)return null;for(let e of i.atoms)if(e.bio.id===o.atom.id||void 0===e.bio.id&&e.bio.continuousId===o.atom.bio.continuousId)return e;return null}getMolfiles(e){let t=this._ensureMolfilesEditor();t.editor.helm.noDraw=!0;try{let i=[];for(let n of e)"string"==typeof n&&0!==n.length?(t.editor.setHelm(n),i.push(t.editor.getMolfile())):i.push("");return i}finally{t.editor.helm.noDraw=!1,this._scheduleMolfilesEditorGc()}}parse(e,t){return go(Et(this._service.parse(e,{mode:"lenient",resolveMonomers:!1}).mol))}removeGaps(e){let t;try{t=this._service.removeGaps(e)}catch(e){throw e instanceof a&&void 0===e.type&&(e.type="HelmNotSupportedError"),e}let i=function(e,t){try{let i=e.parse(t,{mode:"lenient",resolveMonomers:!1});for(let e of i.mol.atoms)if("*"===e.symbol)return!0;return!1}catch{return!1}}(this._service,e);return{srcHelm:t.srcHelm,resHelm:t.resHelm,monomerMap:i?new Map(t.monomerMap):null}}destroy(){null!==this._molfilesGcTimer&&(clearTimeout(this._molfilesGcTimer),this._molfilesGcTimer=null),this._removeMolfilesEditorNow()}_defaultFuncs(){return{getMonomer:(e,t)=>null,getMonomerSet:e=>({})}}_createDetachedHost(){let e=this._doc??$o();if(null===e)throw new Error("HelmHelperAdapter: no Document available");let t=e.createElement("div");return t.style.width="0px",t.style.height="0px",t.style.position="fixed",t}_ensureMolfilesEditor(){if(null!==this._molfilesEditor)return null!==this._molfilesGcTimer&&(clearTimeout(this._molfilesGcTimer),this._molfilesGcTimer=null),this._molfilesEditor;let e=this._createDetachedHost();return this._molfilesEditorHost=e,this._molfilesEditor=new Ao(e,this._service,{width:100,height:100,...null!==this._doc?{documentImpl:this._doc}:{}}),this._logger,this._molfilesEditor}_scheduleMolfilesEditorGc(){null!==this._molfilesGcTimer&&clearTimeout(this._molfilesGcTimer),"function"==typeof setTimeout&&(this._molfilesGcTimer=setTimeout(()=>{this._molfilesGcTimer=null,this._removeMolfilesEditorNow()},e._MOLFILES_GC_MS))}_removeMolfilesEditorNow(){this._molfilesEditor=null,null!==this._molfilesEditorHost&&null!==this._molfilesEditorHost.parentNode&&this._molfilesEditorHost.parentNode.removeChild(this._molfilesEditorHost),this._molfilesEditorHost=null}};Io._MOLFILES_GC_MS=1e3;var Lo=Io;function $o(){return globalThis.document??null}function Po(e,t){if("string"==typeof e)return{biotype:e,symbol:t??null};if(null!==e&&"object"==typeof e&&"ATOM"===e.T){let i=e;return{biotype:i.bio.type,symbol:t??i.elem}}return{biotype:y,symbol:t??null}}function Ro(e){switch(e){case y:return B.PEPTIDE;case v:case w:case x:case E:return B.RNA;case C:return B.CHEM;case k:return B.BLOB;default:return B.PEPTIDE}}function Ho(e,t){let i={};for(let t of e.rgroups)i[t.label]=t.capGroupName;let n={id:t??e.symbol,m:e.molfile,rs:e.rgroups.length,type:e.polymerType,mt:e.monomerType,at:i};return void 0!==e.name&&(n.n=e.name),void 0!==e.naturalAnalog&&(n.na=e.naturalAnalog),void 0!==e.smiles&&(n.smiles=e.smiles),n}},303(e,t,i){"use strict";i.d(t,{q:()=>p});const n="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,o=new Set,r="object"==typeof process&&process?process:{},s=(e,t,i,n)=>{"function"==typeof r.emitWarning?r.emitWarning(e,t,i,n):console.error(`[${i}] ${t}: ${e}`)};let a=globalThis.AbortController,l=globalThis.AbortSignal;if(void 0===a){l=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},a=class{constructor(){t()}signal=new l;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==r.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,s("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const h=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),d=e=>h(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?c:null:null;class c extends Array{constructor(e){super(e),this.fill(0)}}class u{heap;length;static#e=!1;static create(e){const t=d(e);if(!t)return[];u.#e=!0;const i=new u(e,t);return u.#e=!1,i}constructor(e,t){if(!u.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class p{#t;#i;#n;#o;#r;#s;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#l;#h;#d;#c;#u;#p;#m;#f;#b;#g;#A;#_;#y;#v;#w;#x;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#y,sizes:e.#A,keyMap:e.#h,keyList:e.#d,valList:e.#c,next:e.#u,prev:e.#p,get head(){return e.#m},get tail(){return e.#f},free:e.#b,isBackgroundFetch:t=>e.#C(t),backgroundFetch:(t,i,n,o)=>e.#k(t,i,n,o),moveToTail:t=>e.#E(t),indexes:t=>e.#B(t),rindexes:t=>e.#S(t),isStale:t=>e.#M(t)}}get max(){return this.#t}get maxSize(){return this.#i}get calculatedSize(){return this.#l}get size(){return this.#a}get fetchMethod(){return this.#r}get memoMethod(){return this.#s}get dispose(){return this.#n}get disposeAfter(){return this.#o}constructor(e){const{max:t=0,ttl:i,ttlResolution:n=1,ttlAutopurge:r,updateAgeOnGet:a,updateAgeOnHas:l,allowStale:c,dispose:m,disposeAfter:f,noDisposeOnSet:b,noUpdateTTL:g,maxSize:A=0,maxEntrySize:_=0,sizeCalculation:y,fetchMethod:v,memoMethod:w,noDeleteOnFetchRejection:x,noDeleteOnStaleGet:C,allowStaleOnFetchRejection:k,allowStaleOnFetchAbort:E,ignoreFetchAbort:B}=e;if(0!==t&&!h(t))throw new TypeError("max option must be a nonnegative integer");const S=t?d(t):Array;if(!S)throw new Error("invalid max value: "+t);if(this.#t=t,this.#i=A,this.maxEntrySize=_||this.#i,this.sizeCalculation=y,this.sizeCalculation){if(!this.#i&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==w&&"function"!=typeof w)throw new TypeError("memoMethod must be a function if defined");if(this.#s=w,void 0!==v&&"function"!=typeof v)throw new TypeError("fetchMethod must be a function if specified");if(this.#r=v,this.#w=!!v,this.#h=new Map,this.#d=new Array(t).fill(void 0),this.#c=new Array(t).fill(void 0),this.#u=new S(t),this.#p=new S(t),this.#m=0,this.#f=0,this.#b=u.create(t),this.#a=0,this.#l=0,"function"==typeof m&&(this.#n=m),"function"==typeof f?(this.#o=f,this.#g=[]):(this.#o=void 0,this.#g=void 0),this.#v=!!this.#n,this.#x=!!this.#o,this.noDisposeOnSet=!!b,this.noUpdateTTL=!!g,this.noDeleteOnFetchRejection=!!x,this.allowStaleOnFetchRejection=!!k,this.allowStaleOnFetchAbort=!!E,this.ignoreFetchAbort=!!B,0!==this.maxEntrySize){if(0!==this.#i&&!h(this.#i))throw new TypeError("maxSize must be a positive integer if specified");if(!h(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#T()}if(this.allowStale=!!c,this.noDeleteOnStaleGet=!!C,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!l,this.ttlResolution=h(n)||0===n?n:1,this.ttlAutopurge=!!r,this.ttl=i||0,this.ttl){if(!h(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#I()}if(0===this.#t&&0===this.ttl&&0===this.#i)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#i){const e="LRU_CACHE_UNBOUNDED";(e=>!o.has(e))(e)&&(o.add(e),s("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,p))}}getRemainingTTL(e){return this.#h.has(e)?1/0:0}#I(){const e=new c(this.#t),t=new c(this.#t);this.#y=e,this.#_=t,this.#L=(i,o,r=n.now())=>{if(t[i]=0!==o?r:0,e[i]=o,0!==o&&this.ttlAutopurge){const e=setTimeout(()=>{this.#M(i)&&this.#$(this.#d[i],"expire")},o+1);e.unref&&e.unref()}},this.#P=i=>{t[i]=0!==e[i]?n.now():0},this.#R=(n,r)=>{if(e[r]){const s=e[r],a=t[r];if(!s||!a)return;n.ttl=s,n.start=a,n.now=i||o();const l=n.now-a;n.remainingTTL=s-l}};let i=0;const o=()=>{const e=n.now();if(this.ttlResolution>0){i=e;const t=setTimeout(()=>i=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=n=>{const r=this.#h.get(n);if(void 0===r)return 0;const s=e[r],a=t[r];return s&&a?s-((i||o())-a):1/0},this.#M=n=>{const r=t[n],s=e[n];return!!s&&!!r&&(i||o())-r>s}}#P=()=>{};#R=()=>{};#L=()=>{};#M=()=>!1;#T(){const e=new c(this.#t);this.#l=0,this.#A=e,this.#H=t=>{this.#l-=e[t],e[t]=0},this.#N=(e,t,i,n)=>{if(this.#C(t))return 0;if(!h(i)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(i=n(t,e),!h(i))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return i},this.#D=(t,i,n)=>{if(e[t]=i,this.#i){const i=this.#i-e[t];for(;this.#l>i;)this.#F(!0)}this.#l+=e[t],n&&(n.entrySize=i,n.totalCalculatedSize=this.#l)}}#H=e=>{};#D=(e,t,i)=>{};#N=(e,t,i,n)=>{if(i||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#B({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#f;this.#O(t)&&(!e&&this.#M(t)||(yield t),t!==this.#m);)t=this.#p[t]}*#S({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#m;this.#O(t)&&(!e&&this.#M(t)||(yield t),t!==this.#f);)t=this.#u[t]}#O(e){return void 0!==e&&this.#h.get(this.#d[e])===e}*entries(){for(const e of this.#B())void 0===this.#c[e]||void 0===this.#d[e]||this.#C(this.#c[e])||(yield[this.#d[e],this.#c[e]])}*rentries(){for(const e of this.#S())void 0===this.#c[e]||void 0===this.#d[e]||this.#C(this.#c[e])||(yield[this.#d[e],this.#c[e]])}*keys(){for(const e of this.#B()){const t=this.#d[e];void 0===t||this.#C(this.#c[e])||(yield t)}}*rkeys(){for(const e of this.#S()){const t=this.#d[e];void 0===t||this.#C(this.#c[e])||(yield t)}}*values(){for(const e of this.#B())void 0===this.#c[e]||this.#C(this.#c[e])||(yield this.#c[e])}*rvalues(){for(const e of this.#S())void 0===this.#c[e]||this.#C(this.#c[e])||(yield this.#c[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const i of this.#B()){const n=this.#c[i],o=this.#C(n)?n.__staleWhileFetching:n;if(void 0!==o&&e(o,this.#d[i],this))return this.get(this.#d[i],t)}}forEach(e,t=this){for(const i of this.#B()){const n=this.#c[i],o=this.#C(n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,this.#d[i],this)}}rforEach(e,t=this){for(const i of this.#S()){const n=this.#c[i],o=this.#C(n)?n.__staleWhileFetching:n;void 0!==o&&e.call(t,o,this.#d[i],this)}}purgeStale(){let e=!1;for(const t of this.#S({allowStale:!0}))this.#M(t)&&(this.#$(this.#d[t],"expire"),e=!0);return e}info(e){const t=this.#h.get(e);if(void 0===t)return;const i=this.#c[t],o=this.#C(i)?i.__staleWhileFetching:i;if(void 0===o)return;const r={value:o};if(this.#y&&this.#_){const e=this.#y[t],i=this.#_[t];if(e&&i){const t=e-(n.now()-i);r.ttl=t,r.start=Date.now()}}return this.#A&&(r.size=this.#A[t]),r}dump(){const e=[];for(const t of this.#B({allowStale:!0})){const i=this.#d[t],o=this.#c[t],r=this.#C(o)?o.__staleWhileFetching:o;if(void 0===r||void 0===i)continue;const s={value:r};if(this.#y&&this.#_){s.ttl=this.#y[t];const e=n.now()-this.#_[t];s.start=Math.floor(Date.now()-e)}this.#A&&(s.size=this.#A[t]),e.unshift([i,s])}return e}load(e){this.clear();for(const[t,i]of e){if(i.start){const e=Date.now()-i.start;i.start=n.now()-e}this.set(t,i.value,i)}}set(e,t,i={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:o,noDisposeOnSet:r=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=i;let{noUpdateTTL:l=this.noUpdateTTL}=i;const h=this.#N(e,t,i.size||0,s);if(this.maxEntrySize&&h>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#$(e,"set"),this;let d=0===this.#a?void 0:this.#h.get(e);if(void 0===d)d=0===this.#a?this.#f:0!==this.#b.length?this.#b.pop():this.#a===this.#t?this.#F(!1):this.#a,this.#d[d]=e,this.#c[d]=t,this.#h.set(e,d),this.#u[this.#f]=d,this.#p[d]=this.#f,this.#f=d,this.#a++,this.#D(d,h,a),a&&(a.set="add"),l=!1;else{this.#E(d);const i=this.#c[d];if(t!==i){if(this.#w&&this.#C(i)){i.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=i;void 0===t||r||(this.#v&&this.#n?.(t,e,"set"),this.#x&&this.#g?.push([t,e,"set"]))}else r||(this.#v&&this.#n?.(i,e,"set"),this.#x&&this.#g?.push([i,e,"set"]));if(this.#H(d),this.#D(d,h,a),this.#c[d]=t,a){a.set="replace";const e=i&&this.#C(i)?i.__staleWhileFetching:i;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update")}if(0===n||this.#y||this.#I(),this.#y&&(l||this.#L(d,n,o),a&&this.#R(a,d)),!r&&this.#x&&this.#g){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}return this}pop(){try{for(;this.#a;){const e=this.#c[this.#m];if(this.#F(!0),this.#C(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#x&&this.#g){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}}}#F(e){const t=this.#m,i=this.#d[t],n=this.#c[t];return this.#w&&this.#C(n)?n.__abortController.abort(new Error("evicted")):(this.#v||this.#x)&&(this.#v&&this.#n?.(n,i,"evict"),this.#x&&this.#g?.push([n,i,"evict"])),this.#H(t),e&&(this.#d[t]=void 0,this.#c[t]=void 0,this.#b.push(t)),1===this.#a?(this.#m=this.#f=0,this.#b.length=0):this.#m=this.#u[t],this.#h.delete(i),this.#a--,t}has(e,t={}){const{updateAgeOnHas:i=this.updateAgeOnHas,status:n}=t,o=this.#h.get(e);if(void 0!==o){const e=this.#c[o];if(this.#C(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#M(o))return i&&this.#P(o),n&&(n.has="hit",this.#R(n,o)),!0;n&&(n.has="stale",this.#R(n,o))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:i=this.allowStale}=t,n=this.#h.get(e);if(void 0===n||!i&&this.#M(n))return;const o=this.#c[n];return this.#C(o)?o.__staleWhileFetching:o}#k(e,t,i,n){const o=void 0===t?void 0:this.#c[t];if(this.#C(o))return o;const r=new a,{signal:s}=i;s?.addEventListener("abort",()=>r.abort(s.reason),{signal:r.signal});const l={signal:r.signal,options:i,context:n},h=(n,o=!1)=>{const{aborted:s}=r.signal,a=i.ignoreFetchAbort&&void 0!==n;if(i.status&&(s&&!o?(i.status.fetchAborted=!0,i.status.fetchError=r.signal.reason,a&&(i.status.fetchAbortIgnored=!0)):i.status.fetchResolved=!0),s&&!a&&!o)return d(r.signal.reason);const h=c;return this.#c[t]===c&&(void 0===n?h.__staleWhileFetching?this.#c[t]=h.__staleWhileFetching:this.#$(e,"fetch"):(i.status&&(i.status.fetchUpdated=!0),this.set(e,n,l.options))),n},d=n=>{const{aborted:o}=r.signal,s=o&&i.allowStaleOnFetchAbort,a=s||i.allowStaleOnFetchRejection,l=a||i.noDeleteOnFetchRejection,h=c;if(this.#c[t]===c&&(l&&void 0!==h.__staleWhileFetching?s||(this.#c[t]=h.__staleWhileFetching):this.#$(e,"fetch")),a)return i.status&&void 0!==h.__staleWhileFetching&&(i.status.returnedStale=!0),h.__staleWhileFetching;if(h.__returned===h)throw n};i.status&&(i.status.fetchDispatched=!0);const c=new Promise((t,n)=>{const s=this.#r?.(e,o,l);s&&s instanceof Promise&&s.then(e=>t(void 0===e?void 0:e),n),r.signal.addEventListener("abort",()=>{i.ignoreFetchAbort&&!i.allowStaleOnFetchAbort||(t(void 0),i.allowStaleOnFetchAbort&&(t=e=>h(e,!0)))})}).then(h,e=>(i.status&&(i.status.fetchRejected=!0,i.status.fetchError=e),d(e))),u=Object.assign(c,{__abortController:r,__staleWhileFetching:o,__returned:void 0});return void 0===t?(this.set(e,u,{...l.options,status:void 0}),t=this.#h.get(e)):this.#c[t]=u,u}#C(e){if(!this.#w)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof a}async fetch(e,t={}){const{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,ttl:r=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:l=this.sizeCalculation,noUpdateTTL:h=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:c=this.allowStaleOnFetchRejection,ignoreFetchAbort:u=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:m,forceRefresh:f=!1,status:b,signal:g}=t;if(!this.#w)return b&&(b.fetch="get"),this.get(e,{allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:o,status:b});const A={allowStale:i,updateAgeOnGet:n,noDeleteOnStaleGet:o,ttl:r,noDisposeOnSet:s,size:a,sizeCalculation:l,noUpdateTTL:h,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:c,allowStaleOnFetchAbort:p,ignoreFetchAbort:u,status:b,signal:g};let _=this.#h.get(e);if(void 0===_){b&&(b.fetch="miss");const t=this.#k(e,_,A,m);return t.__returned=t}{const t=this.#c[_];if(this.#C(t)){const e=i&&void 0!==t.__staleWhileFetching;return b&&(b.fetch="inflight",e&&(b.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const o=this.#M(_);if(!f&&!o)return b&&(b.fetch="hit"),this.#E(_),n&&this.#P(_),b&&this.#R(b,_),t;const r=this.#k(e,_,A,m),s=void 0!==r.__staleWhileFetching&&i;return b&&(b.fetch=o?"stale":"refresh",s&&o&&(b.returnedStale=!0)),s?r.__staleWhileFetching:r.__returned=r}}async forceFetch(e,t={}){const i=await this.fetch(e,t);if(void 0===i)throw new Error("fetch() returned undefined");return i}memo(e,t={}){const i=this.#s;if(!i)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:o,...r}=t,s=this.get(e,r);if(!o&&void 0!==s)return s;const a=i(e,s,{options:r,context:n});return this.set(e,a,r),a}get(e,t={}){const{allowStale:i=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:o=this.noDeleteOnStaleGet,status:r}=t,s=this.#h.get(e);if(void 0!==s){const t=this.#c[s],a=this.#C(t);return r&&this.#R(r,s),this.#M(s)?(r&&(r.get="stale"),a?(r&&i&&void 0!==t.__staleWhileFetching&&(r.returnedStale=!0),i?t.__staleWhileFetching:void 0):(o||this.#$(e,"expire"),r&&i&&(r.returnedStale=!0),i?t:void 0)):(r&&(r.get="hit"),a?t.__staleWhileFetching:(this.#E(s),n&&this.#P(s),t))}r&&(r.get="miss")}#z(e,t){this.#p[t]=e,this.#u[e]=t}#E(e){e!==this.#f&&(e===this.#m?this.#m=this.#u[e]:this.#z(this.#p[e],this.#u[e]),this.#z(this.#f,e),this.#f=e)}delete(e){return this.#$(e,"delete")}#$(e,t){let i=!1;if(0!==this.#a){const n=this.#h.get(e);if(void 0!==n)if(i=!0,1===this.#a)this.#G(t);else{this.#H(n);const i=this.#c[n];if(this.#C(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#x)&&(this.#v&&this.#n?.(i,e,t),this.#x&&this.#g?.push([i,e,t])),this.#h.delete(e),this.#d[n]=void 0,this.#c[n]=void 0,n===this.#f)this.#f=this.#p[n];else if(n===this.#m)this.#m=this.#u[n];else{const e=this.#p[n];this.#u[e]=this.#u[n];const t=this.#u[n];this.#p[t]=this.#p[n]}this.#a--,this.#b.push(n)}}if(this.#x&&this.#g?.length){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}return i}clear(){return this.#G("delete")}#G(e){for(const t of this.#S({allowStale:!0})){const i=this.#c[t];if(this.#C(i))i.__abortController.abort(new Error("deleted"));else{const n=this.#d[t];this.#v&&this.#n?.(i,n,e),this.#x&&this.#g?.push([i,n,e])}}if(this.#h.clear(),this.#c.fill(void 0),this.#d.fill(void 0),this.#y&&this.#_&&(this.#y.fill(0),this.#_.fill(0)),this.#A&&this.#A.fill(0),this.#m=0,this.#f=0,this.#b.length=0,this.#l=0,this.#a=0,this.#x&&this.#g){const e=this.#g;let t;for(;t=e?.shift();)this.#o?.(...t)}}}}},t={};function i(n){var o=t[n];if(void 0!==o)return o.exports;var r=t[n]={id:n,exports:{}};return e[n].call(r.exports,r,r.exports,i),r.exports}i.m=e,i.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.u=e=>e+".js",i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;i.g.importScripts&&(e=i.g.location+"");var t=i.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var n=t.getElementsByTagName("script");if(n.length)for(var o=n.length-1;o>-1&&(!e||!/^http(s?):/.test(e));)e=n[o--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),i.p=e})(),i.b="undefined"!=typeof document&&document.baseURI||self.location.href,i.nc=void 0;var n=i(333);helm=n})();
|
|
2
2
|
//# sourceMappingURL=package.js.map
|