@czi-sds/data-viz 2.3.0 → 2.4.0

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.
Files changed (39) hide show
  1. package/dist/HeatmapChart.cjs.d.ts +2 -0
  2. package/dist/HeatmapChart.cjs.js +8 -0
  3. package/dist/HeatmapChart.esm.d.ts +2 -0
  4. package/dist/HeatmapChart.esm.js +3 -0
  5. package/dist/ProteinStructureViewer.cjs.d.ts +2 -0
  6. package/dist/ProteinStructureViewer.cjs.js +14 -0
  7. package/dist/ProteinStructureViewer.esm.d.ts +2 -0
  8. package/dist/ProteinStructureViewer.esm.js +3 -0
  9. package/dist/StackedBarChart.cjs.d.ts +2 -0
  10. package/dist/StackedBarChart.cjs.js +8 -0
  11. package/dist/StackedBarChart.esm.d.ts +2 -0
  12. package/dist/StackedBarChart.esm.js +3 -0
  13. package/dist/colorScales.cjs.d.ts +2 -0
  14. package/dist/colorScales.cjs.js +6 -0
  15. package/dist/colorScales.esm.d.ts +2 -0
  16. package/dist/colorScales.esm.js +3 -0
  17. package/dist/index.cjs.d.ts +4 -772
  18. package/dist/index.cjs.js +16 -5765
  19. package/dist/index.esm.d.ts +4 -774
  20. package/dist/index.esm.js +4 -5719
  21. package/dist/shared/HeatmapChart.cjs.js +349 -0
  22. package/dist/shared/HeatmapChart.esm.js +342 -0
  23. package/dist/shared/ProteinStructureViewer.cjs.js +4780 -0
  24. package/dist/shared/ProteinStructureViewer.esm.js +4728 -0
  25. package/dist/shared/StackedBarChart.cjs.js +489 -0
  26. package/dist/shared/StackedBarChart.esm.js +483 -0
  27. package/dist/shared/colorScales.cjs.d.ts +45 -0
  28. package/dist/shared/colorScales.cjs.js +126 -0
  29. package/dist/shared/colorScales.esm.d.ts +45 -0
  30. package/dist/shared/colorScales.esm.js +103 -0
  31. package/dist/shared/index.cjs.d.ts +183 -0
  32. package/dist/shared/index.esm.d.ts +183 -0
  33. package/dist/shared/index2.cjs.d.ts +389 -0
  34. package/dist/shared/index2.esm.d.ts +391 -0
  35. package/dist/shared/index3.cjs.d.ts +166 -0
  36. package/dist/shared/index3.esm.d.ts +166 -0
  37. package/dist/shared/objectSpread2.cjs.js +124 -0
  38. package/dist/shared/objectSpread2.esm.js +85 -0
  39. package/package.json +64 -2
@@ -0,0 +1,4728 @@
1
+ "use client";
2
+ import { n as _objectWithoutProperties, t as _objectSpread2 } from "./objectSpread2.esm.js";
3
+ import { i as toCssGradient, n as sampleColorScale, r as sampleSteppedScale, t as PLASMA_COLOR_SCALE } from "./colorScales.esm.js";
4
+ import { Fragment, createContext, forwardRef, memo, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
5
+ import styled from "@emotion/styled";
6
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
7
+ import { Button, Theme, Tooltip, defaultTheme, fontBodyXs, fontBodyXxxs, fontCodeXs, fontHeaderM, getMode, getSemanticColors, getSpaces } from "@czi-sds/components";
8
+ import { ThemeProvider, useTheme } from "@mui/material/styles";
9
+ import { ApertureIcon, ArrowCounterClockwiseIcon, CheckIcon, CopyIcon, EyeIcon, EyeSlashIcon, QuestionIcon } from "@phosphor-icons/react";
10
+ import { Structure, StructureElement, StructureProperties, Unit } from "molstar/lib/mol-model/structure";
11
+ import { clearStructureTransparency, setStructureTransparency } from "molstar/lib/mol-plugin-state/helpers/structure-transparency";
12
+ import { createPluginUI } from "molstar/lib/mol-plugin-ui";
13
+ import { renderReact18 } from "molstar/lib/mol-plugin-ui/react18";
14
+ import { DefaultPluginUISpec } from "molstar/lib/mol-plugin-ui/spec";
15
+ import { PluginBehaviors } from "molstar/lib/mol-plugin/behavior";
16
+ import { setSubtreeVisibility } from "molstar/lib/mol-plugin/behavior/static/state";
17
+ import { PluginConfig } from "molstar/lib/mol-plugin/config";
18
+ import { Representation } from "molstar/lib/mol-repr/representation";
19
+ import { BehaviorSubject, Subject } from "rxjs";
20
+ import { EveryLoci, Loci } from "molstar/lib/mol-model/loci";
21
+ import { PluginReactContext } from "molstar/lib/mol-plugin-ui/base";
22
+ import { ButtonsType, getButton, getButtons, getModifiers } from "molstar/lib/mol-util/input/input-observer";
23
+ import { throttleTime } from "rxjs/operators";
24
+ import { OrderedSet } from "molstar/lib/mol-data/int";
25
+ import { useTheme as useTheme$1 } from "@mui/material";
26
+ import { PluginStateObject } from "molstar/lib/mol-plugin-state/objects";
27
+ import { getChainOptions, getModelEntityOptions, getOperatorOptions, getSequenceWrapper, getStructureOptions } from "molstar/lib/mol-plugin-ui/sequence";
28
+ import { StateSelection } from "molstar/lib/mol-state/state/selection";
29
+ import { arrayEqual } from "molstar/lib/mol-util";
30
+ import { ParamDefinition } from "molstar/lib/mol-util/param-definition";
31
+ import { Toasts } from "molstar/lib/mol-plugin-ui/toast";
32
+ import { Viewport } from "molstar/lib/mol-plugin-ui/viewport";
33
+ import { Color } from "molstar/lib/mol-util/color";
34
+ import { PluginCommands } from "molstar/lib/mol-plugin/commands";
35
+ import { Vec3 } from "molstar/lib/mol-math/linear-algebra";
36
+ import { BondType } from "molstar/lib/mol-model/structure/model/types";
37
+ import { elementLabel } from "molstar/lib/mol-theme/label";
38
+ import { MolScriptBuilder } from "molstar/lib/mol-script/language/builder";
39
+ import { CustomElementProperty } from "molstar/lib/mol-model-props/common/custom-element-property";
40
+ import { StructureFocusRepresentation } from "molstar/lib/mol-plugin/behavior/dynamic/selection/structure-focus-representation";
41
+ //#region src/core/ProteinStructureViewer/components/ChainLegend/style.ts
42
+ /** Opacity applied to a hidden chain's row, so it reads as off but reachable. */
43
+ const HIDDEN_OPACITY = .4;
44
+ /** Side of the color swatch. */
45
+ const SWATCH_SIZE = 8;
46
+ /**
47
+ * The rows, stacked and right-aligned against the color key beside them.
48
+ *
49
+ * Pointer events are switched back on here: the legend overlay turns them off
50
+ * so drags meant for the structure are not intercepted, and this is one of the
51
+ * two places in it that has to be clickable.
52
+ */
53
+ const ChainRowList = styled("div")`
54
+ display: flex;
55
+ flex-direction: column;
56
+ align-items: flex-end;
57
+ pointer-events: auto;
58
+ max-height: 80px;
59
+ overflow-y: auto;
60
+ `;
61
+ const ChainRow = styled("div")`
62
+ display: flex;
63
+ align-items: center;
64
+
65
+ ${(props) => {
66
+ const spaces = getSpaces(props);
67
+ return `
68
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
69
+ `;
70
+ }}
71
+ `;
72
+ const ChainSwatch = styled("div")`
73
+ flex: none;
74
+ width: ${SWATCH_SIZE}px;
75
+ height: ${SWATCH_SIZE}px;
76
+ border-radius: 1px;
77
+
78
+ ${(props) => `
79
+ background-color: ${props.swatchColor};
80
+ opacity: ${props.isHidden ? HIDDEN_OPACITY : 1};
81
+ `}
82
+ `;
83
+ /**
84
+ * A swatch quartered into a grid, for a coloring no single color stands for.
85
+ *
86
+ * Occupies the same box as the solid swatch so the rows stay aligned whichever
87
+ * one a chain gets, with a hairline gap between the quadrants to read as four
88
+ * colors rather than one blurred square.
89
+ */
90
+ const ChainSwatchGrid = styled("div")`
91
+ flex: none;
92
+ display: grid;
93
+ grid-template-columns: repeat(2, 1fr);
94
+ grid-template-rows: repeat(2, 1fr);
95
+ gap: 0px;
96
+ width: ${SWATCH_SIZE}px;
97
+ height: ${SWATCH_SIZE}px;
98
+ border-radius: 1px;
99
+ overflow: hidden;
100
+
101
+ ${(props) => `
102
+ opacity: ${props.isHidden ? HIDDEN_OPACITY : 1};
103
+ `}
104
+ `;
105
+ const ChainSwatchQuadrant = styled("div")`
106
+ ${(props) => `
107
+ background-color: ${props.swatchColor};
108
+ `}
109
+ `;
110
+ /**
111
+ * Selects the whole chain, or clears it when it is already the selection. A
112
+ * button so it is reachable from the keyboard.
113
+ */
114
+ const ChainLabel$1 = styled("button")`
115
+ ${fontBodyXxxs}
116
+
117
+ padding: 0;
118
+ border: none;
119
+ background: none;
120
+
121
+ ${(props) => {
122
+ var _semanticColors$base, _semanticColors$base2, _semanticColors$base3;
123
+ const semanticColors = getSemanticColors(props);
124
+ return `
125
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.textSecondary};
126
+ cursor: ${props.isHidden ? "default" : "pointer"};
127
+ font-weight: ${props.isSelected ? 600 : "inherit"};
128
+ opacity: ${props.isHidden ? HIDDEN_OPACITY : 1};
129
+
130
+ &:hover {
131
+ color: ${props.isHidden ? semanticColors === null || semanticColors === void 0 || (_semanticColors$base2 = semanticColors.base) === null || _semanticColors$base2 === void 0 ? void 0 : _semanticColors$base2.textSecondary : semanticColors === null || semanticColors === void 0 || (_semanticColors$base3 = semanticColors.base) === null || _semanticColors$base3 === void 0 ? void 0 : _semanticColors$base3.textPrimary};
132
+ }
133
+ `;
134
+ }}
135
+ `;
136
+ const VisibilityToggle = styled("button")`
137
+ display: flex;
138
+ align-items: center;
139
+ padding: 0;
140
+ border: none;
141
+ background: none;
142
+ cursor: pointer;
143
+ margin-top: 1px;
144
+
145
+ ${(props) => {
146
+ var _semanticColors$base4, _semanticColors$base5;
147
+ const semanticColors = getSemanticColors(props);
148
+ return `
149
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base4 = semanticColors.base) === null || _semanticColors$base4 === void 0 ? void 0 : _semanticColors$base4.textTertiaryOnDark};
150
+
151
+ &:hover {
152
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base5 = semanticColors.base) === null || _semanticColors$base5 === void 0 ? void 0 : _semanticColors$base5.textPrimary};
153
+ }
154
+
155
+ svg {
156
+ display: block;
157
+ }
158
+ `;
159
+ }}
160
+ `;
161
+ //#endregion
162
+ //#region src/core/ProteinStructureViewer/components/ChainLegend/index.tsx
163
+ /**
164
+ * Lists the structure's chains, each with its color and a visibility toggle.
165
+ *
166
+ * Only drawn for a complex: one chain needs no key to tell it from anything,
167
+ * and hiding it would leave an empty canvas with no way back. Its home is the
168
+ * legend rather than the sequence panel so that it survives
169
+ * `showSequenceViewer={false}`, where the chains would otherwise have nowhere
170
+ * to be listed.
171
+ */
172
+ function ChainLegend({ bandColors, chainColors, chains, hiddenChains, onChainHover, onChainSelect, onChainToggle, selectedChains }) {
173
+ if (chains.length < 2) return null;
174
+ return /* @__PURE__ */ jsx(ChainRowList, { children: chains.map((chain) => {
175
+ var _selectedChains$has;
176
+ const hidden = hiddenChains.has(chain.chainId);
177
+ const selected = (_selectedChains$has = selectedChains === null || selectedChains === void 0 ? void 0 : selectedChains.has(chain.chainId)) !== null && _selectedChains$has !== void 0 ? _selectedChains$has : false;
178
+ const color = chainColors === null || chainColors === void 0 ? void 0 : chainColors.get(chain.chainId);
179
+ return /* @__PURE__ */ jsxs(ChainRow, {
180
+ onBlur: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(null),
181
+ onFocus: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(chain.chainId),
182
+ onMouseEnter: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(chain.chainId),
183
+ onMouseLeave: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(null),
184
+ children: [
185
+ /* @__PURE__ */ jsx(Tooltip, {
186
+ arrow: true,
187
+ placement: "top",
188
+ disableInteractive: true,
189
+ title: hidden ? `Chain ${chain.label} is hidden` : `Click to ${selected ? "deselect" : "select"} Chain ${chain.label}`,
190
+ children: /* @__PURE__ */ jsxs(ChainLabel$1, {
191
+ "aria-pressed": selected,
192
+ disabled: hidden,
193
+ isHidden: hidden,
194
+ isSelected: selected,
195
+ onClick: () => onChainSelect(chain.chainId),
196
+ type: "button",
197
+ children: ["Chain ", chain.label]
198
+ })
199
+ }),
200
+ color !== void 0 && /* @__PURE__ */ jsx(ChainSwatch, {
201
+ isHidden: hidden,
202
+ swatchColor: color
203
+ }),
204
+ color === void 0 && bandColors !== void 0 && /* @__PURE__ */ jsx(ChainSwatchGrid, {
205
+ isHidden: hidden,
206
+ children: bandColors.map((band) => /* @__PURE__ */ jsx(ChainSwatchQuadrant, { swatchColor: band }, band))
207
+ }),
208
+ /* @__PURE__ */ jsx(Tooltip, {
209
+ arrow: true,
210
+ placement: "top",
211
+ disableInteractive: true,
212
+ title: hidden ? `Show Chain ${chain.label}` : `Hide Chain ${chain.label}`,
213
+ children: /* @__PURE__ */ jsx(VisibilityToggle, {
214
+ "aria-label": `${hidden ? "Show" : "Hide"} chain ${chain.label}`,
215
+ "aria-pressed": hidden,
216
+ onClick: () => onChainToggle(chain.chainId),
217
+ type: "button",
218
+ children: hidden ? /* @__PURE__ */ jsx(EyeSlashIcon, { size: 12 }) : /* @__PURE__ */ jsx(EyeIcon, { size: 12 })
219
+ })
220
+ })
221
+ ]
222
+ }, chain.chainId);
223
+ }) });
224
+ }
225
+ /** Height of the color bar itself. */
226
+ const BAR_HEIGHT = 8;
227
+ /**
228
+ * Inset applied to the outer tick labels on a stepped scale. Labels sit on the
229
+ * boundaries *between* bands, so the row is padded by half a band to line each
230
+ * label up with its boundary rather than with a band's center.
231
+ */
232
+ const STEPPED_LABEL_INSET = 5;
233
+ const LegendWrapper = styled("div")`
234
+ width: ${142}px;
235
+ `;
236
+ const LegendLabels = styled("div")`
237
+ ${fontBodyXxxs}
238
+
239
+ display: flex;
240
+ justify-content: space-between;
241
+ width: 100%;
242
+
243
+ ${(props) => {
244
+ var _semanticColors$base;
245
+ const semanticColors = getSemanticColors(props);
246
+ return `
247
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.textTertiaryOnDark};
248
+ `;
249
+ }}
250
+ `;
251
+ const SteppedLabels = styled(LegendLabels)`
252
+ &::before,
253
+ &::after {
254
+ content: "";
255
+ width: ${STEPPED_LABEL_INSET}px;
256
+ }
257
+ `;
258
+ const LegendBar = styled("div")`
259
+ display: flex;
260
+ height: ${BAR_HEIGHT}px;
261
+ width: 100%;
262
+ `;
263
+ const LegendBand = styled("div")`
264
+ flex: 1;
265
+ background-color: ${(props) => props.color};
266
+ `;
267
+ const LegendGradient = styled("div")`
268
+ height: ${BAR_HEIGHT}px;
269
+ width: 100%;
270
+ background: ${(props) => props.gradient};
271
+ `;
272
+ //#endregion
273
+ //#region src/core/ProteinStructureViewer/components/ColorScaleLegend/index.tsx
274
+ /** Decimal places used for the ticks on a continuous scale. */
275
+ const TICK_PRECISION = 2;
276
+ /**
277
+ * The color key beneath the structure viewer. A stepped scale renders as
278
+ * discrete bands with a tick at each boundary; a continuous scale renders as a
279
+ * gradient running from `min` to `max`, the range its values are normalized
280
+ * into before they are sampled.
281
+ */
282
+ function ColorScaleLegend({ max = null, min = 0, scale }) {
283
+ if (scale.kind === "stepped") return /* @__PURE__ */ jsxs(LegendWrapper, { children: [/* @__PURE__ */ jsx(SteppedLabels, { children: scale.stops.slice(0, -1).map((stop) => /* @__PURE__ */ jsx("div", { children: stop.label }, stop.label)) }), /* @__PURE__ */ jsx(LegendBar, { children: scale.stops.map((stop) => /* @__PURE__ */ jsx(LegendBand, { color: stop.color }, stop.label)) })] });
284
+ return /* @__PURE__ */ jsxs(LegendWrapper, { children: [/* @__PURE__ */ jsxs(LegendLabels, { children: [/* @__PURE__ */ jsx("div", { children: min.toFixed(TICK_PRECISION) }), /* @__PURE__ */ jsx("div", { children: max !== null ? max.toFixed(TICK_PRECISION) : "" })] }), /* @__PURE__ */ jsx(LegendGradient, { gradient: toCssGradient(scale.stops) })] });
285
+ }
286
+ //#endregion
287
+ //#region src/core/ProteinStructureViewer/style.ts
288
+ /** Smallest box in which Mol* can still lay out a usable viewport. */
289
+ const MIN_HEIGHT = 190;
290
+ const MIN_WIDTH = 200;
291
+ /**
292
+ * Name of the size container the root declares below, which is what lets the
293
+ * sequence panel and the legend reflow to the viewer's own width rather than
294
+ * the page's.
295
+ */
296
+ const VIEWER_CONTAINER_NAME = "sds-structure-viewer";
297
+ /**
298
+ * Height reserved for the sequence panel along the bottom, and the viewer
299
+ * width above which it grows. Measured against the container above rather than
300
+ * the page, so a viewer embedded in a wider page sizes to the room it has.
301
+ *
302
+ * The legend sits directly on top of the panel and offsets itself by these
303
+ * same three values, so it reads them from here rather than restating them.
304
+ * Copies that drifted would leave the legend floating off the panel.
305
+ */
306
+ const SEQUENCE_HEIGHT = "max(104px, 30%)";
307
+ const SEQUENCE_HEIGHT_WIDE = "max(134px, 32%)";
308
+ /**
309
+ * The element Mol* mounts into.
310
+ *
311
+ * This has to be its own node rather than the root: Mol* takes ownership of its
312
+ * target and replaces whatever is in it, so anything the viewer renders
313
+ * alongside the plugin (the legend) has to be a sibling of this, not a child.
314
+ */
315
+ const PluginMount = styled("div")`
316
+ position: absolute;
317
+ inset: 0;
318
+ `;
319
+ /**
320
+ * Root container for the viewer.
321
+ *
322
+ * Mol* ships no stylesheet of its own here: the viewport and sequence panel are
323
+ * replaced with custom components and the remaining chrome is hidden, so all
324
+ * that is left to style is the layout scaffolding. Those overrides are nested
325
+ * below rather than declared globally, so consumers do not have to import
326
+ * anything extra and two viewers on a page cannot fight over the same
327
+ * selectors.
328
+ *
329
+ * The element also declares itself a size container, which is what lets the
330
+ * legend reflow to the viewer's own width instead of the page's.
331
+ */
332
+ const ViewerRoot = styled("div")`
333
+ position: relative;
334
+ overflow: hidden;
335
+ width: 100%;
336
+ height: 100%;
337
+ min-width: ${MIN_WIDTH}px;
338
+ min-height: ${MIN_HEIGHT}px;
339
+ container-type: inline-size;
340
+ container-name: ${VIEWER_CONTAINER_NAME};
341
+
342
+ .msp-plugin {
343
+ position: absolute !important;
344
+ inset: 0 !important;
345
+ width: 100% !important;
346
+ height: 100% !important;
347
+ }
348
+
349
+ /*
350
+ * The expanded layout is kept hidden because it is the one piece of Mol*
351
+ * chrome that would escape this container: it takes the plugin out of the
352
+ * box it was given and over the page.
353
+ *
354
+ * Its neighbours used to be here too - the viewport's icon column, and the
355
+ * left, right and bottom regions. They are not any more, because hiding them
356
+ * from here made them unreachable: Mol* already gates each of them behind a
357
+ * PluginConfig.Viewport flag and behind layout.initial.regionState, both of
358
+ * which a consumer can set through molstarSpec, and a display:none on top of
359
+ * that overrode the answer. None of them shows by default - the viewer's own
360
+ * flags and region state are what keep them away - so this only has to stay
361
+ * out of their way.
362
+ *
363
+ * No backticks in here: this is inside a template literal, and one would end
364
+ * it.
365
+ */
366
+ .msp-plugin .msp-layout-expanded {
367
+ display: none !important;
368
+ }
369
+
370
+ .msp-plugin canvas {
371
+ display: block !important;
372
+ }
373
+
374
+ .msp-plugin .msp-layout-static {
375
+ height: 100%;
376
+ }
377
+
378
+ .msp-plugin .msp-sequence-wrapper-non-empty {
379
+ overflow-y: auto;
380
+ }
381
+
382
+ /*
383
+ * Mol* puts the sequence panel in its "top" region; move it to the bottom and
384
+ * shrink the main viewport region to match, so the structure sits above the
385
+ * sequence rather than behind it. The panel grows on wider viewers, and the
386
+ * viewport region's offset follows it.
387
+ */
388
+ ${(props) => {
389
+ const { showSequenceViewer } = props;
390
+ return `
391
+ .msp-plugin .msp-layout-region.msp-layout-top {
392
+ display: ${showSequenceViewer ? "block" : "none"} !important;
393
+ position: absolute !important;
394
+ inset: auto 0 0 0 !important;
395
+ height: ${SEQUENCE_HEIGHT} !important;
396
+ }
397
+
398
+ .msp-plugin .msp-layout-region.msp-layout-main {
399
+ position: absolute !important;
400
+ top: 0 !important;
401
+ left: 0 !important;
402
+ right: 0 !important;
403
+ bottom: ${showSequenceViewer ? SEQUENCE_HEIGHT : "0"} !important;
404
+ }
405
+
406
+ @container ${VIEWER_CONTAINER_NAME} (min-width: 880px) {
407
+ .msp-plugin .msp-layout-region.msp-layout-top {
408
+ height: ${SEQUENCE_HEIGHT_WIDE} !important;
409
+ }
410
+
411
+ .msp-plugin .msp-layout-region.msp-layout-main {
412
+ bottom: ${showSequenceViewer ? SEQUENCE_HEIGHT_WIDE : "0"} !important;
413
+ }
414
+ }
415
+ `;
416
+ }}
417
+
418
+ /*
419
+ * Toast slot rendered by the custom viewport. No loci label providers are
420
+ * registered (residue info goes to the legend instead), so this only carries
421
+ * Mol*'s own transient messages.
422
+ */
423
+ .msp-plugin .msp-highlight-toast-wrapper {
424
+ position: absolute !important;
425
+ left: 10px !important;
426
+ max-width: 95% !important;
427
+ z-index: 10000 !important;
428
+ pointer-events: none;
429
+ }
430
+ `;
431
+ //#endregion
432
+ //#region src/core/ProteinStructureViewer/components/StructureLegend/style.ts
433
+ /** Width below which the legend switches to its stacked layout. */
434
+ const NARROW_BREAKPOINT = 480;
435
+ /** Fixed stat column width, so labels swapping on hover never shift the grid. */
436
+ const STAT_COLUMN_WIDTH = "4.5rem";
437
+ /**
438
+ * Overlaid along the bottom of the viewer, above the sequence panel. Its bottom
439
+ * offset is the panel's own height, taken from the root style so the two cannot
440
+ * disagree; with no panel it drops to the bottom edge, where its own padding
441
+ * provides the gap. Pointer events are off so the legend never intercepts drags
442
+ * meant for the structure; the help tooltip re-enables them on itself.
443
+ */
444
+ const LegendOverlay = styled("div")`
445
+ position: absolute;
446
+ z-index: 1;
447
+ display: flex;
448
+ align-items: flex-end;
449
+ width: 100%;
450
+ pointer-events: none;
451
+
452
+ ${(props) => {
453
+ const spaces = getSpaces(props);
454
+ const { showSequenceViewer } = props;
455
+ return `
456
+ right: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
457
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
458
+ padding-bottom: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
459
+ bottom: ${showSequenceViewer ? SEQUENCE_HEIGHT : "0"};
460
+
461
+ /*
462
+ * Track the sequence panel as it grows on wider viewers. The panel is
463
+ * sized against this same container, so answering to the page instead
464
+ * would part the legend from it on a viewer narrower than its page.
465
+ */
466
+ @container ${VIEWER_CONTAINER_NAME} (min-width: 880px) {
467
+ bottom: ${showSequenceViewer ? SEQUENCE_HEIGHT_WIDE : "0"};
468
+ }
469
+
470
+ /* Spacer balancing the axes widget pinned in the opposite corner. */
471
+ &::before {
472
+ content: "";
473
+ display: block;
474
+ width: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxl}px;
475
+ }
476
+
477
+ @container ${VIEWER_CONTAINER_NAME} (max-width: ${NARROW_BREAKPOINT}px) {
478
+ width: auto;
479
+ flex-direction: column;
480
+ align-items: flex-end;
481
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.l}px;
482
+
483
+ /* The horizontal spacer only makes sense in the bottom-bar layout. */
484
+ &::before {
485
+ display: none;
486
+ }
487
+ }
488
+ `;
489
+ }}
490
+ `;
491
+ /**
492
+ * Fills the space between the axes widget on the left and the color legend on
493
+ * the right. Three fixed-width columns distributed with space-evenly, so the
494
+ * side padding equals the inter-column gap and both flex with the viewer width.
495
+ */
496
+ const StatsGrid = styled("div")`
497
+ display: grid;
498
+ flex: 1;
499
+ grid-template-columns: repeat(3, ${STAT_COLUMN_WIDTH});
500
+ align-items: end;
501
+ justify-content: space-evenly;
502
+ white-space: nowrap;
503
+
504
+ ${(props) => {
505
+ const spaces = getSpaces(props);
506
+ return `
507
+ @container ${VIEWER_CONTAINER_NAME} (max-width: ${NARROW_BREAKPOINT}px) {
508
+ flex: none;
509
+ grid-template-columns: minmax(0, 1fr);
510
+ justify-items: end;
511
+ text-align: right;
512
+ row-gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xl}px;
513
+ }
514
+ `;
515
+ }}
516
+ `;
517
+ const ChainScaleColumn = styled("div")`
518
+ display: flex;
519
+ flex-direction: column;
520
+ align-items: flex-end;
521
+
522
+ ${(props) => {
523
+ const spaces = getSpaces(props);
524
+ return `
525
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.l}px;
526
+ `;
527
+ }}
528
+ `;
529
+ const StatColumnWrapper = styled("div")`
530
+ display: flex;
531
+ flex-direction: column;
532
+ `;
533
+ const StatValue = styled("span")`
534
+ ${fontBodyXxxs}
535
+
536
+ ${(props) => {
537
+ var _semanticColors$base;
538
+ const semanticColors = getSemanticColors(props);
539
+ return `
540
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.textPrimary};
541
+ `;
542
+ }}
543
+ `;
544
+ const StatLabel = styled("span")`
545
+ ${fontBodyXxxs}
546
+
547
+ ${(props) => {
548
+ var _semanticColors$base2;
549
+ const semanticColors = getSemanticColors(props);
550
+ return `
551
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base2 = semanticColors.base) === null || _semanticColors$base2 === void 0 ? void 0 : _semanticColors$base2.textTertiaryOnDark};
552
+ `;
553
+ }}
554
+ `;
555
+ const ScaleColumn = styled("div")`
556
+ display: flex;
557
+ flex-direction: column;
558
+
559
+ ${(props) => {
560
+ const spaces = getSpaces(props);
561
+ return `
562
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
563
+ `;
564
+ }}
565
+ `;
566
+ /**
567
+ * A wrapping text line, not a flex row: the help icon has to sit at the end of
568
+ * the last line of the caption rather than beside the whole wrapped block.
569
+ */
570
+ const ScaleCaption = styled("span")`
571
+ ${fontBodyXxxs}
572
+
573
+ display: block;
574
+ text-align: left;
575
+
576
+ ${(props) => {
577
+ var _semanticColors$base3;
578
+ const semanticColors = getSemanticColors(props);
579
+ return `
580
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base3 = semanticColors.base) === null || _semanticColors$base3 === void 0 ? void 0 : _semanticColors$base3.textTertiaryOnDark};
581
+ max-width: 142px;
582
+ `;
583
+ }}
584
+ `;
585
+ /** Re-enables pointer events for the one interactive element in the overlay. */
586
+ const TooltipAnchor = styled("span")`
587
+ pointer-events: auto;
588
+
589
+ ${(props) => {
590
+ var _semanticColors$base4;
591
+ const spaces = getSpaces(props);
592
+ const semanticColors = getSemanticColors(props);
593
+ return `
594
+ display: inline-block;
595
+ padding-left: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxxs}px;
596
+ margin-bottom: 1px;
597
+ vertical-align: text-bottom;
598
+
599
+ &:hover {
600
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base4 = semanticColors.base) === null || _semanticColors$base4 === void 0 ? void 0 : _semanticColors$base4.ornamentSecondary};
601
+ }
602
+
603
+ svg {
604
+ display: block;
605
+ }
606
+ `;
607
+ }}
608
+ `;
609
+ //#endregion
610
+ //#region src/core/ProteinStructureViewer/components/StructureLegend/index.tsx
611
+ /** Number of stat columns, fixed so the grid tracks never move. */
612
+ const SLOT_COUNT = 3;
613
+ /** Decimal places for stat and readout values. */
614
+ const VALUE_PRECISION = 3;
615
+ /** Shown in place of a number the residue has none of. */
616
+ const MISSING_VALUE = "–";
617
+ function StatColumn({ label, value }) {
618
+ return /* @__PURE__ */ jsxs(StatColumnWrapper, { children: [/* @__PURE__ */ jsx(StatValue, { children: value }), /* @__PURE__ */ jsx(StatLabel, { children: label })] });
619
+ }
620
+ /**
621
+ * Builds one readout slot.
622
+ *
623
+ * A readout covering several residues reports a mean, and the label says so:
624
+ * calling it "pLDDT" while it averages ninety of them would read as a single
625
+ * residue's score.
626
+ */
627
+ function readoutSlot(label, value, residueCount) {
628
+ return {
629
+ label: residueCount > 1 ? `Mean ${label}` : label,
630
+ value: value !== null ? value.toFixed(VALUE_PRECISION) : MISSING_VALUE
631
+ };
632
+ }
633
+ /**
634
+ * Stats and color key overlaid on the structure viewer.
635
+ *
636
+ * When a residue is selected or hovered, the whole-structure stats are replaced
637
+ * in place by that residue's readout: slot 0 becomes the residue label, slot 1
638
+ * the overlay value (only when an overlay is active, otherwise the stat stays),
639
+ * and slot 2 the residue pLDDT. A selection pins the readout; hovering another
640
+ * residue takes priority so the user can inspect others without losing their
641
+ * selection.
642
+ */
643
+ function StructureLegend({ chainBandColors, chainColors, chains = [], hiddenChains, hoveredResidue = null, onChainHover, onChainSelect, onChainToggle, scale, scaleLabel, scaleMax = null, scaleMin = 0, scaleTooltip, scaleTooltipProps, selectedChains, selectedResidue = null, showSequenceViewer, stats, valueLabel }) {
644
+ var _activeResidue$residu, _stats$, _stats$2, _stats$3;
645
+ const activeResidue = hoveredResidue !== null && hoveredResidue !== void 0 ? hoveredResidue : selectedResidue;
646
+ const showResidue = activeResidue !== null;
647
+ const showValue = showResidue && valueLabel !== void 0;
648
+ const residueCount = (_activeResidue$residu = activeResidue === null || activeResidue === void 0 ? void 0 : activeResidue.residueCount) !== null && _activeResidue$residu !== void 0 ? _activeResidue$residu : 1;
649
+ const slots = [
650
+ showResidue ? {
651
+ label: residueCount > 1 ? "Selection" : "Residue",
652
+ value: activeResidue.label
653
+ } : (_stats$ = stats[0]) !== null && _stats$ !== void 0 ? _stats$ : null,
654
+ showValue ? readoutSlot(valueLabel, activeResidue.value, residueCount) : (_stats$2 = stats[1]) !== null && _stats$2 !== void 0 ? _stats$2 : null,
655
+ showResidue ? readoutSlot("pLDDT", activeResidue.plddt, residueCount) : (_stats$3 = stats[2]) !== null && _stats$3 !== void 0 ? _stats$3 : null
656
+ ];
657
+ return /* @__PURE__ */ jsxs(LegendOverlay, {
658
+ showSequenceViewer,
659
+ children: [/* @__PURE__ */ jsx(StatsGrid, { children: Array.from({ length: SLOT_COUNT }, (_, i) => {
660
+ var _slots$i;
661
+ const slot = (_slots$i = slots[i]) !== null && _slots$i !== void 0 ? _slots$i : null;
662
+ return slot ? /* @__PURE__ */ jsx(StatColumn, {
663
+ label: slot.label,
664
+ value: slot.value
665
+ }, i) : /* @__PURE__ */ jsx("div", {}, i);
666
+ }) }), /* @__PURE__ */ jsxs(ChainScaleColumn, { children: [onChainToggle && onChainSelect && /* @__PURE__ */ jsx(ChainLegend, {
667
+ bandColors: chainBandColors,
668
+ chainColors,
669
+ chains,
670
+ hiddenChains: hiddenChains !== null && hiddenChains !== void 0 ? hiddenChains : /* @__PURE__ */ new Set(),
671
+ onChainHover,
672
+ onChainSelect,
673
+ onChainToggle,
674
+ selectedChains
675
+ }), scale && /* @__PURE__ */ jsxs(ScaleColumn, { children: [/* @__PURE__ */ jsx(ColorScaleLegend, {
676
+ max: scaleMax,
677
+ min: scaleMin,
678
+ scale
679
+ }), /* @__PURE__ */ jsxs(ScaleCaption, { children: [scaleLabel, (scaleTooltip !== void 0 || scaleTooltipProps !== void 0) && /* @__PURE__ */ jsx(Tooltip, _objectSpread2(_objectSpread2({
680
+ arrow: true,
681
+ placement: "bottom"
682
+ }, scaleTooltipProps), {}, {
683
+ title: scaleTooltip !== null && scaleTooltip !== void 0 ? scaleTooltip : scaleTooltipProps === null || scaleTooltipProps === void 0 ? void 0 : scaleTooltipProps.title,
684
+ children: /* @__PURE__ */ jsx(TooltipAnchor, { children: /* @__PURE__ */ jsx(QuestionIcon, {
685
+ size: 10,
686
+ weight: "bold"
687
+ }) })
688
+ }))] })] })] })]
689
+ });
690
+ }
691
+ //#endregion
692
+ //#region \0@oxc-project+runtime@0.134.0/helpers/esm/asyncToGenerator.js
693
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
694
+ try {
695
+ var i = n[a](c), u = i.value;
696
+ } catch (n) {
697
+ e(n);
698
+ return;
699
+ }
700
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
701
+ }
702
+ function _asyncToGenerator(n) {
703
+ return function() {
704
+ var t = this, e = arguments;
705
+ return new Promise(function(r, o) {
706
+ var a = n.apply(t, e);
707
+ function _next(n) {
708
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
709
+ }
710
+ function _throw(n) {
711
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
712
+ }
713
+ _next(void 0);
714
+ });
715
+ };
716
+ }
717
+ //#endregion
718
+ //#region src/core/ProteinStructureViewer/hooks/useChainHighlight.ts
719
+ /**
720
+ * How transparent the other chains go while one is pointed at.
721
+ *
722
+ * Enough that the chain under the pointer is the one being read, not enough
723
+ * that the rest of the complex stops being context for it. 0 is opaque, 1 is
724
+ * invisible.
725
+ */
726
+ const CHAIN_DIM_TRANSPARENCY = .65;
727
+ /**
728
+ * The chain id in a component key.
729
+ *
730
+ * Chain components are tagged `structure-component-<part>-<chainId>`, and a
731
+ * key is the component's tags sorted and joined with commas. Anchoring on the
732
+ * part name and stopping at the comma is what keeps `A` from also matching the
733
+ * chain named `AA`.
734
+ */
735
+ const COMPONENT_CHAIN_ID = /structure-component-(?:polymer|ligand)-([^,]+)/;
736
+ /** The chain a component was built for, or undefined if it is not a chain's. */
737
+ function componentChainId(component) {
738
+ var _component$key, _COMPONENT_CHAIN_ID$e;
739
+ const key = (_component$key = component.key) !== null && _component$key !== void 0 ? _component$key : component.cell.transform.ref;
740
+ return (_COMPONENT_CHAIN_ID$e = COMPONENT_CHAIN_ID.exec(key)) === null || _COMPONENT_CHAIN_ID$e === void 0 ? void 0 : _COMPONENT_CHAIN_ID$e[1];
741
+ }
742
+ /** Every chain component of every loaded structure, polymers and ligands. */
743
+ function structureComponents(plugin) {
744
+ return plugin.managers.structure.hierarchy.current.structures.flatMap((entry) => entry.components);
745
+ }
746
+ /** A set of chain ids as one comparable string. */
747
+ function chainsKey(chains) {
748
+ return [...chains].sort().join("\0");
749
+ }
750
+ /**
751
+ * Makes every chain outside `lit` transparent, or all of them opaque again when
752
+ * nothing is lit.
753
+ *
754
+ * Transparency layers accumulate, so what is already there is cleared before
755
+ * the next chain is dimmed rather than added to - otherwise moving along the
756
+ * list would leave every chain it passed dimmed behind it.
757
+ *
758
+ * False when there is no structure to write to yet, which is what a selection
759
+ * arriving before the first load looks like. It is applied again after the load
760
+ * rather than being taken as done.
761
+ */
762
+ function dimChainsOutside(_x2, _x3) {
763
+ return _dimChainsOutside.apply(this, arguments);
764
+ }
765
+ function _dimChainsOutside() {
766
+ _dimChainsOutside = _asyncToGenerator(function* (plugin, lit) {
767
+ const components = structureComponents(plugin);
768
+ if (components.length === 0) return false;
769
+ yield clearStructureTransparency(plugin, components);
770
+ if (lit.size === 0) return true;
771
+ const dimmed = components.filter((component) => {
772
+ const chainId = componentChainId(component);
773
+ return chainId !== void 0 && !lit.has(chainId);
774
+ });
775
+ if (dimmed.length === 0) return true;
776
+ yield setStructureTransparency(plugin, dimmed, CHAIN_DIM_TRANSPARENCY, function() {
777
+ var _ref = _asyncToGenerator(function* (structure) {
778
+ return Structure.toStructureElementLoci(structure);
779
+ });
780
+ return function(_x) {
781
+ return _ref.apply(this, arguments);
782
+ };
783
+ }());
784
+ return true;
785
+ });
786
+ return _dimChainsOutside.apply(this, arguments);
787
+ }
788
+ /**
789
+ * Leaves one chain lit and dims the rest: the chain whose name is pointed at,
790
+ * in the sequence panel's captions or the chain legend's rows, or the chain the
791
+ * selection covers once the pointer has gone.
792
+ *
793
+ * The chain left lit is exactly as it was - in the chain palette, in pLDDT
794
+ * bands, or in an overlay - and the others recede around it. Nothing is painted
795
+ * over the top, so what the reader is being pointed at is still the color the
796
+ * legend beside it is describing, and a selected chain reads the same as a
797
+ * hovered one rather than sprouting a highlight of its own.
798
+ *
799
+ * A hover outranks the selection while it lasts, since pointing at a chain is a
800
+ * question about that chain, and hands it back on the way out.
801
+ *
802
+ * Dimming is a state-tree commit rather than a renderer setting, so it is
803
+ * applied one at a time and coalesced: a pointer crossing the list faster than
804
+ * a commit finishes skips the chains it passed over and settles on the one it
805
+ * came to rest on, instead of working through a queue of hovers that have
806
+ * already been left.
807
+ */
808
+ function useChainHighlight({ disabled, hiddenChains, loadCount, pluginRef, selectedChains }) {
809
+ const hoveredRef = useRef(null);
810
+ /**
811
+ * The chains left lit on the canvas as it stands. A freshly loaded structure
812
+ * carries no dimming at all, which is what the empty key means.
813
+ */
814
+ const shownRef = useRef(chainsKey(/* @__PURE__ */ new Set()));
815
+ const committingRef = useRef(false);
816
+ /**
817
+ * Read when a commit comes round rather than closed over, so one already in
818
+ * flight settles on the current props instead of the ones it started under.
819
+ */
820
+ const propsRef = useRef({
821
+ disabled,
822
+ hiddenChains,
823
+ selectedChains
824
+ });
825
+ propsRef.current = {
826
+ disabled,
827
+ hiddenChains,
828
+ selectedChains
829
+ };
830
+ const litChains = useCallback(() => {
831
+ const { disabled: hoverOff, hiddenChains: hidden, selectedChains: selected } = propsRef.current;
832
+ const hovered = hoveredRef.current;
833
+ if (!hoverOff && hovered !== null && !hidden.has(hovered)) return new Set([hovered]);
834
+ return new Set([...selected].filter((chainId) => !hidden.has(chainId)));
835
+ }, []);
836
+ const settle = useCallback(_asyncToGenerator(function* () {
837
+ if (committingRef.current) return;
838
+ committingRef.current = true;
839
+ try {
840
+ while (pluginRef.current) {
841
+ const lit = litChains();
842
+ const key = chainsKey(lit);
843
+ if (key === shownRef.current) break;
844
+ if (!(yield dimChainsOutside(pluginRef.current, lit))) break;
845
+ shownRef.current = key;
846
+ }
847
+ } catch (error) {
848
+ console.error("Failed to dim chains:", error);
849
+ } finally {
850
+ committingRef.current = false;
851
+ }
852
+ }), [litChains, pluginRef]);
853
+ const highlightChain = useCallback((chainId) => {
854
+ hoveredRef.current = chainId;
855
+ settle();
856
+ }, [settle]);
857
+ useEffect(() => {
858
+ settle();
859
+ }, [
860
+ disabled,
861
+ hiddenChains,
862
+ selectedChains,
863
+ settle
864
+ ]);
865
+ useEffect(() => {
866
+ shownRef.current = chainsKey(/* @__PURE__ */ new Set());
867
+ settle();
868
+ }, [loadCount, settle]);
869
+ return highlightChain;
870
+ }
871
+ //#endregion
872
+ //#region src/common/chainColors.ts
873
+ /**
874
+ * Default colors for telling chains apart, in assignment order.
875
+ *
876
+ * The Okabe-Ito qualitative palette, which is built to stay distinguishable
877
+ * under every common form of color blindness - the reason to prefer it over a
878
+ * hand-picked set, since a complex is read by which chain is which and a
879
+ * viewer that collapses two of them into one color stops answering that.
880
+ *
881
+ * Its black is left out: the canvas inverts with the theme, so a chain painted
882
+ * black would vanish against the dark background. The rest carry enough
883
+ * lightness to hold up against both.
884
+ *
885
+ * Chains past the end of the palette wrap around to the start.
886
+ */
887
+ const CHAIN_COLOR_PALETTE = [
888
+ "#009E73",
889
+ "#0072B2",
890
+ "#E69F00",
891
+ "#CC79A7",
892
+ "#56B4E9",
893
+ "#D55E00",
894
+ "#F0E442"
895
+ ];
896
+ /**
897
+ * Assigns each chain a color, in the order given, with `overrides` taking
898
+ * precedence by `chainId`.
899
+ *
900
+ * Palette positions are spent on every chain whether or not it is overridden,
901
+ * so overriding one chain does not shift the colors of the others.
902
+ */
903
+ function chainColorMap(chainIds, overrides) {
904
+ const colors = /* @__PURE__ */ new Map();
905
+ chainIds.forEach((chainId, i) => {
906
+ var _overrides$chainId;
907
+ const fallback = CHAIN_COLOR_PALETTE[i % CHAIN_COLOR_PALETTE.length];
908
+ colors.set(chainId, (_overrides$chainId = overrides === null || overrides === void 0 ? void 0 : overrides[chainId]) !== null && _overrides$chainId !== void 0 ? _overrides$chainId : fallback);
909
+ });
910
+ return colors;
911
+ }
912
+ //#endregion
913
+ //#region src/core/ProteinStructureViewer/hooks/useChains.ts
914
+ /**
915
+ * Reconciles the chains found in the structure with the visibility and coloring
916
+ * the consumer asked for.
917
+ *
918
+ * Visibility is controlled when `hiddenChains` is passed and owned here when it
919
+ * is not, so the legend's toggles work out of the box without taking the
920
+ * decision away from a consumer that wants it. `onChainVisibilityChange` fires
921
+ * either way: a consumer that only wants to follow along should not have to
922
+ * take ownership to hear about it.
923
+ */
924
+ function useChains({ chainColors, chains, hiddenChains, onChainVisibilityChange }) {
925
+ const isControlled = hiddenChains !== void 0;
926
+ const [ownHidden, setOwnHidden] = useState([]);
927
+ const onChainVisibilityChangeRef = useRef(onChainVisibilityChange);
928
+ onChainVisibilityChangeRef.current = onChainVisibilityChange;
929
+ const chainIds = useMemo(() => chains.map((c) => c.chainId), [chains]);
930
+ /**
931
+ * Chains the structure no longer has cannot be unhidden through the legend,
932
+ * since it has no row for them, so a stale id would hide a chain that shares
933
+ * its name in the next structure. Only the uncontrolled side is pruned; a
934
+ * controlled consumer owns its own list.
935
+ */
936
+ useEffect(() => {
937
+ if (isControlled) return;
938
+ setOwnHidden((prev) => {
939
+ const kept = prev.filter((id) => chainIds.includes(id));
940
+ return kept.length === prev.length ? prev : kept;
941
+ });
942
+ }, [chainIds, isControlled]);
943
+ const hiddenKey = [...isControlled ? hiddenChains : ownHidden].sort().join("\0");
944
+ const hidden = useMemo(() => new Set(hiddenKey === "" ? [] : hiddenKey.split("\0")), [hiddenKey]);
945
+ return {
946
+ colors: useMemo(() => chainColorMap(chainIds, chainColors), [chainIds.map((id) => {
947
+ var _chainColors$id;
948
+ return `${id}:${(_chainColors$id = chainColors === null || chainColors === void 0 ? void 0 : chainColors[id]) !== null && _chainColors$id !== void 0 ? _chainColors$id : ""}`;
949
+ }).join("\0")]),
950
+ hidden,
951
+ toggleChain: useCallback((chainId) => {
952
+ var _onChainVisibilityCha;
953
+ const next = hidden.has(chainId) ? [...hidden].filter((id) => id !== chainId) : [...hidden, chainId];
954
+ const ordered = chainIds.filter((id) => next.includes(id));
955
+ if (!isControlled) setOwnHidden(ordered);
956
+ (_onChainVisibilityCha = onChainVisibilityChangeRef.current) === null || _onChainVisibilityCha === void 0 || _onChainVisibilityCha.call(onChainVisibilityChangeRef, ordered);
957
+ }, [
958
+ chainIds,
959
+ hidden,
960
+ isControlled
961
+ ])
962
+ };
963
+ }
964
+ //#endregion
965
+ //#region src/core/ProteinStructureViewer/utils/theme.ts
966
+ const themeCache = /* @__PURE__ */ new Map();
967
+ /**
968
+ * The MUI theme for a mode, built at most once. Mol*'s view components rebuild
969
+ * their `ThemeProvider` on every render, and `Theme()` is not cheap.
970
+ */
971
+ function themeForMode(mode) {
972
+ const cached = themeCache.get(mode);
973
+ if (cached) return cached;
974
+ const theme = Theme(mode);
975
+ themeCache.set(mode, theme);
976
+ return theme;
977
+ }
978
+ const residueColorCache = /* @__PURE__ */ new Map();
979
+ function residueColorsForMode(mode) {
980
+ var _getSemanticColors, _base$fillSecondaryIn, _base$textPrimary, _base$textSecondary, _base$textTertiary;
981
+ const cached = residueColorCache.get(mode);
982
+ if (cached) return cached;
983
+ const base = (_getSemanticColors = getSemanticColors({ theme: themeForMode(mode) })) === null || _getSemanticColors === void 0 ? void 0 : _getSemanticColors.base;
984
+ const colors = {
985
+ activeBackground: (_base$fillSecondaryIn = base === null || base === void 0 ? void 0 : base.fillSecondaryInteraction) !== null && _base$fillSecondaryIn !== void 0 ? _base$fillSecondaryIn : "transparent",
986
+ activeText: (_base$textPrimary = base === null || base === void 0 ? void 0 : base.textPrimary) !== null && _base$textPrimary !== void 0 ? _base$textPrimary : "inherit",
987
+ defaultText: (_base$textSecondary = base === null || base === void 0 ? void 0 : base.textSecondary) !== null && _base$textSecondary !== void 0 ? _base$textSecondary : "inherit",
988
+ inactiveText: (_base$textTertiary = base === null || base === void 0 ? void 0 : base.textTertiary) !== null && _base$textTertiary !== void 0 ? _base$textTertiary : "inherit"
989
+ };
990
+ residueColorCache.set(mode, colors);
991
+ return colors;
992
+ }
993
+ //#endregion
994
+ //#region src/core/ProteinStructureViewer/hooks/useSubscribe.ts
995
+ /**
996
+ * Subscribes to an observable for as long as the component is mounted, the
997
+ * hook equivalent of `PluginUIComponent`'s `subscribe`.
998
+ *
999
+ * The handler is read through a ref so that passing a fresh closure on every
1000
+ * render - which is the normal case, since these handlers read props and state
1001
+ * - does not tear down and rebuild the subscription.
1002
+ */
1003
+ function useSubscribe(observable, handler) {
1004
+ const handlerRef = useRef(handler);
1005
+ handlerRef.current = handler;
1006
+ useEffect(() => {
1007
+ if (!observable) return;
1008
+ const subscription = observable.subscribe((value) => handlerRef.current(value));
1009
+ return () => subscription.unsubscribe();
1010
+ }, [observable]);
1011
+ }
1012
+ //#endregion
1013
+ //#region src/core/ProteinStructureViewer/hooks/useViewSetting.ts
1014
+ /**
1015
+ * One field of the settings Mol*'s own React root cannot read from context.
1016
+ *
1017
+ * The subject emits a whole new settings object on every push, so each field is
1018
+ * selected out separately: React's equality bailout then absorbs the pushes
1019
+ * that left this particular value alone, and a component only re-renders for
1020
+ * the settings it actually reads.
1021
+ */
1022
+ function useViewSetting(settings, select) {
1023
+ const [value, setValue] = useState(() => select(settings.value));
1024
+ useSubscribe(settings, (next) => setValue(() => select(next)));
1025
+ return value;
1026
+ }
1027
+ //#endregion
1028
+ //#region src/core/ProteinStructureViewer/hooks/useMolstarTheme.ts
1029
+ /**
1030
+ * The active theme for a component Mol* renders in its own React root.
1031
+ *
1032
+ * Those components sit outside the consumer's provider tree, so they cannot
1033
+ * read the theme from context; the mode reaches them through the settings
1034
+ * subject instead. Callers re-supply the theme to their subtree via a local
1035
+ * `ThemeProvider` so Emotion styles resolve SDS tokens correctly.
1036
+ */
1037
+ function useMolstarTheme(settings) {
1038
+ const mode = useViewSetting(settings, (s) => s.mode);
1039
+ return {
1040
+ mode,
1041
+ theme: themeForMode(mode)
1042
+ };
1043
+ }
1044
+ //#endregion
1045
+ //#region src/core/ProteinStructureViewer/components/SequenceView/constants.ts
1046
+ /** Attribute carrying a residue's sequence index, used for hit testing. */
1047
+ const SEQ_ID_ATTR = "data-seqid";
1048
+ /** Hover updates are coalesced to roughly one every three frames. */
1049
+ const HOVER_THROTTLE_MS = 3 * 16.666;
1050
+ /** How long the copy button shows its confirmation state. */
1051
+ const COPIED_FEEDBACK_MS = 2e3;
1052
+ //#endregion
1053
+ //#region src/core/ProteinStructureViewer/components/SequenceView/style.ts
1054
+ /** Height of the fade that masks residues scrolling under the panel header. */
1055
+ const SCROLL_FADE_HEIGHT = 8;
1056
+ const SequencePanel = styled("div")`
1057
+ display: flex;
1058
+ flex-direction: column;
1059
+ height: 100%;
1060
+
1061
+ ${(props) => {
1062
+ var _semanticColors$base, _props$backgroundColo, _semanticColors$base2;
1063
+ const spaces = getSpaces(props);
1064
+ const semanticColors = getSemanticColors(props);
1065
+ return `
1066
+ padding: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px 0;
1067
+ border-top: 1px solid ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.divider};
1068
+ background-color: ${(_props$backgroundColo = props.backgroundColor) !== null && _props$backgroundColo !== void 0 ? _props$backgroundColo : semanticColors === null || semanticColors === void 0 || (_semanticColors$base2 = semanticColors.base) === null || _semanticColors$base2 === void 0 ? void 0 : _semanticColors$base2.surfacePrimary};
1069
+ `;
1070
+ }}
1071
+ `;
1072
+ const EmptyState = styled("div")`
1073
+ ${fontBodyXs}
1074
+
1075
+ display: flex;
1076
+ align-items: center;
1077
+ justify-content: center;
1078
+ height: 100%;
1079
+
1080
+ ${(props) => {
1081
+ var _props$backgroundColo2, _semanticColors$base3, _semanticColors$base4;
1082
+ const spaces = getSpaces(props);
1083
+ const semanticColors = getSemanticColors(props);
1084
+ return `
1085
+ padding: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
1086
+ background-color: ${(_props$backgroundColo2 = props.backgroundColor) !== null && _props$backgroundColo2 !== void 0 ? _props$backgroundColo2 : semanticColors === null || semanticColors === void 0 || (_semanticColors$base3 = semanticColors.base) === null || _semanticColors$base3 === void 0 ? void 0 : _semanticColors$base3.surfaceSecondary};
1087
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base4 = semanticColors.base) === null || _semanticColors$base4 === void 0 ? void 0 : _semanticColors$base4.textTertiaryOnDark};
1088
+ `;
1089
+ }}
1090
+ `;
1091
+ const PanelHeader = styled("div")`
1092
+ display: flex;
1093
+ align-items: center;
1094
+
1095
+ ${(props) => {
1096
+ const spaces = getSpaces(props);
1097
+ return `
1098
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
1099
+ `;
1100
+ }}
1101
+ `;
1102
+ const PanelTitle = styled("span")`
1103
+ ${fontHeaderM}
1104
+
1105
+ ${(props) => {
1106
+ var _semanticColors$base5;
1107
+ const semanticColors = getSemanticColors(props);
1108
+ return `
1109
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base5 = semanticColors.base) === null || _semanticColors$base5 === void 0 ? void 0 : _semanticColors$base5.textPrimary};
1110
+ `;
1111
+ }}
1112
+ `;
1113
+ const CopyButton = styled("button")`
1114
+ display: flex;
1115
+ align-items: center;
1116
+ padding: 0;
1117
+ border: none;
1118
+ background: none;
1119
+ cursor: default;
1120
+
1121
+ ${(props) => {
1122
+ var _semanticColors$base6, _semanticColors$base7;
1123
+ const semanticColors = getSemanticColors(props);
1124
+ return `
1125
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base6 = semanticColors.base) === null || _semanticColors$base6 === void 0 ? void 0 : _semanticColors$base6.ornamentSecondary};
1126
+
1127
+ &:hover {
1128
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base7 = semanticColors.base) === null || _semanticColors$base7 === void 0 ? void 0 : _semanticColors$base7.textPrimary};
1129
+ }
1130
+ `;
1131
+ }}
1132
+ `;
1133
+ const ResidueCount = styled("div")`
1134
+ display: flex;
1135
+ align-items: center;
1136
+ margin-left: auto;
1137
+
1138
+ ${(props) => {
1139
+ const spaces = getSpaces(props);
1140
+ return `
1141
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
1142
+ `;
1143
+ }}
1144
+ `;
1145
+ const ResidueCountLabel = styled("span")`
1146
+ ${fontBodyXs}
1147
+
1148
+ ${(props) => {
1149
+ var _semanticColors$base8;
1150
+ const semanticColors = getSemanticColors(props);
1151
+ return `
1152
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base8 = semanticColors.base) === null || _semanticColors$base8 === void 0 ? void 0 : _semanticColors$base8.textTertiary};
1153
+ `;
1154
+ }}
1155
+ `;
1156
+ const ResidueCountValue = styled("span")`
1157
+ ${fontBodyXs}
1158
+
1159
+ ${(props) => {
1160
+ var _semanticColors$base9;
1161
+ const semanticColors = getSemanticColors(props);
1162
+ return `
1163
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base9 = semanticColors.base) === null || _semanticColors$base9 === void 0 ? void 0 : _semanticColors$base9.textPrimary};
1164
+ `;
1165
+ }}
1166
+ `;
1167
+ /**
1168
+ * Scroll region for the residue grid. The `::before` fade masks residues as
1169
+ * they scroll up under the header, so it has to start from whatever the panel
1170
+ * is painted with or it leaves a mismatched strip.
1171
+ */
1172
+ const SequenceScroller = styled("div")`
1173
+ position: relative;
1174
+ flex: 1;
1175
+ min-height: 0;
1176
+
1177
+ ${(props) => {
1178
+ var _props$backgroundColo3, _semanticColors$base10;
1179
+ const semanticColors = getSemanticColors(props);
1180
+ return `
1181
+ &::before {
1182
+ content: "";
1183
+ position: absolute;
1184
+ inset-inline: 0;
1185
+ top: 0;
1186
+ z-index: 10;
1187
+ height: ${SCROLL_FADE_HEIGHT}px;
1188
+ pointer-events: none;
1189
+ background: linear-gradient(to bottom, ${(_props$backgroundColo3 = props.backgroundColor) !== null && _props$backgroundColo3 !== void 0 ? _props$backgroundColo3 : semanticColors === null || semanticColors === void 0 || (_semanticColors$base10 = semanticColors.base) === null || _semanticColors$base10 === void 0 ? void 0 : _semanticColors$base10.surfacePrimary}, transparent);
1190
+ }
1191
+ `;
1192
+ }}
1193
+ `;
1194
+ /**
1195
+ * Residue spans are written to directly by `useResidueMarkers` rather than
1196
+ * re-rendered, so their hover and selection colors are set inline. Everything
1197
+ * here is the static styling underneath that: the monospace type, the pointer
1198
+ * affordance, and the superscript sequence numbers (which need their own color
1199
+ * rule, since they are nested inside residue spans and would otherwise inherit
1200
+ * the inline color).
1201
+ */
1202
+ const SequenceScrollArea = styled("div")`
1203
+ height: 100%;
1204
+ overflow-y: auto;
1205
+
1206
+ .msp-sequence-wrapper {
1207
+ ${fontCodeXs};
1208
+ font-size: 11px;
1209
+ line-height: 1.2;
1210
+ }
1211
+
1212
+ .msp-sequence-present {
1213
+ cursor: pointer;
1214
+ }
1215
+
1216
+ ${(props) => {
1217
+ var _semanticColors$base11;
1218
+ const semanticColors = getSemanticColors(props);
1219
+ return `
1220
+ .msp-sequence-number {
1221
+ font-size: 8px;
1222
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base11 = semanticColors.base) === null || _semanticColors$base11 === void 0 ? void 0 : _semanticColors$base11.textTertiaryOnDark};
1223
+ }
1224
+ `;
1225
+ }}
1226
+ `;
1227
+ /**
1228
+ * Layout for one chain's residues.
1229
+ *
1230
+ * Residues are grouped into fixed-size sections, each one grid cell. The
1231
+ * equal-width auto-fill tracks and uniform gap keep the spacing between
1232
+ * sections identical on every row - including a partial last row, which keeps
1233
+ * the same column width (rather than stretching) and stacks from the leading
1234
+ * edge.
1235
+ */
1236
+ const ResidueGrid = styled("div")`
1237
+ user-select: none;
1238
+ display: grid;
1239
+ grid-template-columns: repeat(
1240
+ auto-fill,
1241
+ minmax(${10}ch, 1fr)
1242
+ );
1243
+ gap: 8px;
1244
+ justify-items: start;
1245
+ padding-top: 6px;
1246
+
1247
+ /* Section wrappers, so a section's letters never split across lines. */
1248
+ & > span {
1249
+ white-space: nowrap;
1250
+ }
1251
+
1252
+ .msp-sequence-present {
1253
+ position: relative;
1254
+ display: inline-block;
1255
+ width: 1ch;
1256
+ /*
1257
+ * Reserves room above the letter for its superscript sequence number.
1258
+ * content-box clipping keeps the active fill off that gutter, so a
1259
+ * highlighted residue does not tint the number.
1260
+ */
1261
+ padding-top: 8px;
1262
+ background-clip: content-box;
1263
+ text-align: center;
1264
+ }
1265
+
1266
+ .msp-sequence-number {
1267
+ position: absolute;
1268
+ top: 0;
1269
+ line-height: 1.2;
1270
+ white-space: nowrap;
1271
+ pointer-events: none;
1272
+ }
1273
+ `;
1274
+ /**
1275
+ * The row above each chain's grid: a visibility toggle and the chain's name.
1276
+ *
1277
+ * A structure with more than one chain renders one grid per chain, and without
1278
+ * a caption between them the grids read as a single continuous protein. The
1279
+ * controls sit here rather than only in the legend because this is where a
1280
+ * reader is already looking at one chain at a time.
1281
+ */
1282
+ const ChainHeaderRow = styled("div")`
1283
+ display: flex;
1284
+ align-items: center;
1285
+
1286
+ ${(props) => {
1287
+ const spaces = getSpaces(props);
1288
+ return `
1289
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
1290
+ margin-top: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
1291
+ margin-bottom: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxxs}px;
1292
+ `;
1293
+ }}
1294
+ `;
1295
+ /**
1296
+ * Shows or hides the chain's cartoon in the 3D view. Full strength even while
1297
+ * the chain is hidden, since it is the way back.
1298
+ */
1299
+ const ChainVisibilityToggle = styled("button")`
1300
+ display: flex;
1301
+ align-items: center;
1302
+ padding: 0;
1303
+ border: none;
1304
+ background: none;
1305
+ cursor: pointer;
1306
+
1307
+ ${(props) => {
1308
+ var _semanticColors$base12, _semanticColors$base13;
1309
+ const semanticColors = getSemanticColors(props);
1310
+ return `
1311
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base12 = semanticColors.base) === null || _semanticColors$base12 === void 0 ? void 0 : _semanticColors$base12.textTertiaryOnDark};
1312
+
1313
+ &:hover {
1314
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base13 = semanticColors.base) === null || _semanticColors$base13 === void 0 ? void 0 : _semanticColors$base13.textPrimary};
1315
+ }
1316
+
1317
+ svg {
1318
+ display: block;
1319
+ }
1320
+ `;
1321
+ }}
1322
+ `;
1323
+ /**
1324
+ * The chain's name, and a button because it also selects the chain: the caption
1325
+ * is already the one thing on screen that stands for a whole chain, so clicking
1326
+ * it is where a reader looks to select one. Clicking it again clears it.
1327
+ */
1328
+ const ChainLabel = styled("button")`
1329
+ ${fontBodyXs}
1330
+
1331
+ padding: 0;
1332
+ border: none;
1333
+ background: none;
1334
+ text-align: left;
1335
+
1336
+ ${(props) => {
1337
+ var _semanticColors$base14, _semanticColors$base15, _semanticColors$base16;
1338
+ const semanticColors = getSemanticColors(props);
1339
+ const resting = props.isSelected ? semanticColors === null || semanticColors === void 0 || (_semanticColors$base14 = semanticColors.base) === null || _semanticColors$base14 === void 0 ? void 0 : _semanticColors$base14.textPrimary : semanticColors === null || semanticColors === void 0 || (_semanticColors$base15 = semanticColors.base) === null || _semanticColors$base15 === void 0 ? void 0 : _semanticColors$base15.textSecondary;
1340
+ return `
1341
+ color: ${resting};
1342
+ cursor: ${props.isHidden ? "default" : "pointer"};
1343
+ font-weight: ${props.isSelected ? 600 : 500};
1344
+ opacity: ${props.isHidden ? .4 : 1};
1345
+
1346
+ &:hover {
1347
+ color: ${props.isHidden ? resting : semanticColors === null || semanticColors === void 0 || (_semanticColors$base16 = semanticColors.base) === null || _semanticColors$base16 === void 0 ? void 0 : _semanticColors$base16.textPrimary};
1348
+ }
1349
+ `;
1350
+ }}
1351
+ `;
1352
+ /**
1353
+ * Wraps a chain whose 3D cartoon is hidden. The grid stays in place and stays
1354
+ * interactive - the sequence is still the sequence - but is dimmed to match the
1355
+ * chain being absent from the structure beside it. Dimmed rather than removed
1356
+ * so the panel does not reflow every time a chain is toggled.
1357
+ */
1358
+ const HiddenChainGroup = styled("div")`
1359
+ opacity: 0.4;
1360
+ `;
1361
+ //#endregion
1362
+ //#region src/core/ProteinStructureViewer/components/SequenceView/components/ChainHeader/index.tsx
1363
+ /**
1364
+ * The row above one chain's residue grid: a visibility toggle and the chain's
1365
+ * name, which selects it.
1366
+ *
1367
+ * The name is a toggle rather than a one-way switch, so the tooltip says which
1368
+ * way the next click goes - offering to select a chain that is already selected
1369
+ * would be telling the reader the wrong thing. A hidden chain cannot be
1370
+ * selected at all, so the name stops being a button then: there is no geometry
1371
+ * to focus, and the toggle beside it is what the reader wants instead.
1372
+ */
1373
+ function ChainHeader({ chainId, isHidden, isSelected, label, onHover, onSelect, onToggle }) {
1374
+ return /* @__PURE__ */ jsxs(ChainHeaderRow, {
1375
+ onBlur: () => onHover === null || onHover === void 0 ? void 0 : onHover(null),
1376
+ onFocus: () => onHover === null || onHover === void 0 ? void 0 : onHover(chainId),
1377
+ onMouseEnter: () => onHover === null || onHover === void 0 ? void 0 : onHover(chainId),
1378
+ onMouseLeave: () => onHover === null || onHover === void 0 ? void 0 : onHover(null),
1379
+ children: [/* @__PURE__ */ jsx(Tooltip, {
1380
+ arrow: true,
1381
+ placement: "top",
1382
+ title: isHidden ? `Chain ${label} is hidden` : `Click to ${isSelected ? "deselect" : "select"} Chain ${label}`,
1383
+ textAlign: "left",
1384
+ children: /* @__PURE__ */ jsxs(ChainLabel, {
1385
+ "aria-pressed": isSelected,
1386
+ disabled: isHidden,
1387
+ isHidden,
1388
+ isSelected,
1389
+ onClick: () => onSelect === null || onSelect === void 0 ? void 0 : onSelect(chainId),
1390
+ type: "button",
1391
+ children: ["Chain ", label]
1392
+ })
1393
+ }), onToggle && /* @__PURE__ */ jsx(Tooltip, {
1394
+ arrow: true,
1395
+ placement: "top",
1396
+ title: `${isHidden ? "Show" : "Hide"} Chain ${label}`,
1397
+ children: /* @__PURE__ */ jsx(ChainVisibilityToggle, {
1398
+ "aria-label": `${isHidden ? "Show" : "Hide"} chain ${label}`,
1399
+ "aria-pressed": isHidden,
1400
+ onClick: () => onToggle(chainId),
1401
+ type: "button",
1402
+ children: isHidden ? /* @__PURE__ */ jsx(EyeSlashIcon, { size: 12 }) : /* @__PURE__ */ jsx(EyeIcon, { size: 12 })
1403
+ })
1404
+ })]
1405
+ });
1406
+ }
1407
+ //#endregion
1408
+ //#region src/core/ProteinStructureViewer/hooks/usePlugin.ts
1409
+ /**
1410
+ * The plugin owning the React root this component renders in.
1411
+ *
1412
+ * Mol* renders its view components inside its own root and provides the plugin
1413
+ * through this context, which is what `PluginUIComponent` reads to populate
1414
+ * `this.plugin`.
1415
+ */
1416
+ function usePlugin() {
1417
+ return useContext(PluginReactContext);
1418
+ }
1419
+ //#endregion
1420
+ //#region src/core/ProteinStructureViewer/components/SequenceView/utils/residue.ts
1421
+ /** Reads the sequence index off a residue span, or undefined if it is not one. */
1422
+ function readSeqIdx(el) {
1423
+ if (!el || !el.getAttribute) return void 0;
1424
+ return el.hasAttribute("data-seqid") ? +el.getAttribute(SEQ_ID_ATTR) : void 0;
1425
+ }
1426
+ /**
1427
+ * Nearest ancestor that scrolls vertically, or null if none. Used to scope the
1428
+ * residue tooltip's hide-on-scroll listener to the sequence's own overflow
1429
+ * container instead of a global window listener.
1430
+ */
1431
+ function getScrollParent(node) {
1432
+ var _node$parentElement;
1433
+ let el = (_node$parentElement = node === null || node === void 0 ? void 0 : node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : null;
1434
+ while (el) {
1435
+ const overflowY = getComputedStyle(el).overflowY;
1436
+ if (overflowY === "auto" || overflowY === "scroll") return el;
1437
+ el = el.parentElement;
1438
+ }
1439
+ return null;
1440
+ }
1441
+ function getResidueClass(sequenceWrapper, seqIdx) {
1442
+ return sequenceWrapper.isHighlighted(seqIdx) || sequenceWrapper.isSelected(seqIdx) || sequenceWrapper.isFocused(seqIdx) ? "msp-sequence-present msp-sequence-residue-active" : "msp-sequence-present msp-sequence-residue";
1443
+ }
1444
+ /**
1445
+ * The label shown above a residue: its author sequence id for atomic units,
1446
+ * or a 1-based position for coarse ones.
1447
+ *
1448
+ * `location` is a scratch object the caller reuses across residues, since this
1449
+ * runs once per numbered residue on every render.
1450
+ */
1451
+ function getSequenceNumber(sequenceWrapper, seqIdx, location) {
1452
+ let seqNum = "";
1453
+ const loci = sequenceWrapper.getLoci(seqIdx);
1454
+ const l = StructureElement.Loci.getFirstLocation(loci, location);
1455
+ if (l) {
1456
+ if (Unit.isAtomic(l.unit)) {
1457
+ const seqId = StructureProperties.residue.auth_seq_id(l);
1458
+ const insCode = StructureProperties.residue.pdbx_PDB_ins_code(l);
1459
+ seqNum = `${seqId}${insCode ? insCode : ""}`;
1460
+ } else if (Unit.isCoarse(l.unit)) seqNum = `${seqIdx + 1}`;
1461
+ }
1462
+ return seqNum;
1463
+ }
1464
+ /**
1465
+ * How often a sequence number is drawn above the residues.
1466
+ *
1467
+ * Long sequences get one every ten residues. Short ones number every residue,
1468
+ * unless their numbers run to more than one digit, which would crowd them.
1469
+ */
1470
+ function resolveSequenceNumberPeriod(sequenceWrapper, location, sequenceNumberPeriod) {
1471
+ if (sequenceNumberPeriod !== void 0) return sequenceNumberPeriod;
1472
+ if (sequenceWrapper.length > 10) return 10;
1473
+ if (getSequenceNumber(sequenceWrapper, sequenceWrapper.length - 1, location).length > 1) return 5;
1474
+ return 1;
1475
+ }
1476
+ /**
1477
+ * The grid's accessible name.
1478
+ *
1479
+ * The grid is a rendering of the structure rather than a control of its own,
1480
+ * so it is exposed as an image; that makes this label the only thing an
1481
+ * assistive technology gets, which is why it carries the residues themselves
1482
+ * rather than just how many there are. They are spaced apart so they are read
1483
+ * as individual letters instead of running together into a word.
1484
+ *
1485
+ * A complex draws one grid per chain, and the caption naming each is a visual
1486
+ * sibling rather than a label, so the chain is named here too. Without it every
1487
+ * grid announces the same name and which chain a reader is on is apparent only
1488
+ * by sight.
1489
+ */
1490
+ function buildSequenceLabel(sequenceWrapper, chainLabel) {
1491
+ const letters = [];
1492
+ for (let i = 0; i < sequenceWrapper.length; i++) letters.push(sequenceWrapper.residueLabel(i));
1493
+ const name = chainLabel ? `Chain ${chainLabel}, residue sequence, ${sequenceWrapper.length} residues` : `Residue sequence, ${sequenceWrapper.length} residues`;
1494
+ return letters.length > 0 ? `${name}: ${letters.join(" ")}` : name;
1495
+ }
1496
+ //#endregion
1497
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResidueMarkers.ts
1498
+ /**
1499
+ * Keeps the residue grid's hover and selection colors in sync with the 3D
1500
+ * view.
1501
+ *
1502
+ * The colors are written straight to the residue spans rather than rendered,
1503
+ * because a marker change would otherwise re-render a grid that can hold
1504
+ * thousands of nodes.
1505
+ */
1506
+ function useResidueMarkers({ containerRef, residueColors, sequenceWrapper }) {
1507
+ const plugin = usePlugin();
1508
+ /**
1509
+ * Residues sit at the default color until something is active. A hovered,
1510
+ * selected, or focused residue brightens and takes a translucent fill; while
1511
+ * any residue is selected, the rest dim to draw attention to the selection.
1512
+ */
1513
+ const paintMarkers = useCallback(() => {
1514
+ const container = containerRef.current;
1515
+ if (!container) return;
1516
+ const { activeBackground, activeText, defaultText, inactiveText } = residueColors;
1517
+ const spans = container.querySelectorAll(`[${SEQ_ID_ATTR}]`);
1518
+ let anySelected = false;
1519
+ for (let i = 0; i < sequenceWrapper.length; i++) if (sequenceWrapper.isSelected(i)) {
1520
+ anySelected = true;
1521
+ break;
1522
+ }
1523
+ const inactiveColor = anySelected ? inactiveText : defaultText;
1524
+ for (let i = 0; i < sequenceWrapper.length; i++) {
1525
+ const span = spans[i];
1526
+ if (!span) return;
1527
+ const className = getResidueClass(sequenceWrapper, i);
1528
+ if (span.className !== className) span.className = className;
1529
+ const active = sequenceWrapper.isSelected(i) || sequenceWrapper.isFocused(i) || sequenceWrapper.isHighlighted(i);
1530
+ span.style.color = active ? activeText : inactiveColor;
1531
+ span.style.backgroundColor = active ? activeBackground : "";
1532
+ }
1533
+ }, [
1534
+ containerRef,
1535
+ residueColors,
1536
+ sequenceWrapper
1537
+ ]);
1538
+ const markFocus = useCallback((loci) => {
1539
+ sequenceWrapper.markResidue(EveryLoci, "unfocus");
1540
+ if (loci) sequenceWrapper.markResidue(loci, "focus");
1541
+ }, [sequenceWrapper]);
1542
+ const paintMarkersRef = useRef(paintMarkers);
1543
+ paintMarkersRef.current = paintMarkers;
1544
+ const sequenceWrapperRef = useRef(sequenceWrapper);
1545
+ sequenceWrapperRef.current = sequenceWrapper;
1546
+ useEffect(() => {
1547
+ const markProvider = (loci, action) => {
1548
+ if (sequenceWrapperRef.current.markResidue(loci.loci, action)) paintMarkersRef.current();
1549
+ };
1550
+ const { lociHighlights, lociSelects } = plugin.managers.interactivity;
1551
+ lociHighlights.addProvider(markProvider);
1552
+ lociSelects.addProvider(markProvider);
1553
+ return () => {
1554
+ lociHighlights.removeProvider(markProvider);
1555
+ lociSelects.removeProvider(markProvider);
1556
+ };
1557
+ }, [plugin]);
1558
+ useSubscribe(plugin.managers.structure.focus.behaviors.current, (focus) => {
1559
+ markFocus(focus === null || focus === void 0 ? void 0 : focus.loci);
1560
+ paintMarkers();
1561
+ });
1562
+ useLayoutEffect(() => {
1563
+ var _plugin$managers$stru;
1564
+ markFocus((_plugin$managers$stru = plugin.managers.structure.focus.behaviors.current.value) === null || _plugin$managers$stru === void 0 ? void 0 : _plugin$managers$stru.loci);
1565
+ paintMarkers();
1566
+ });
1567
+ }
1568
+ //#endregion
1569
+ //#region src/core/ProteinStructureViewer/utils/selection.ts
1570
+ /**
1571
+ * A stable string for a selection, for comparing one against another.
1572
+ *
1573
+ * A consumer holding the selection in state hands back a new object on every
1574
+ * render, so identity says nothing about whether the selection changed. Order
1575
+ * is normalized too: `{ residues: [2, 1] }` and `{ residues: [1, 2] }` select
1576
+ * the same residues and must not read as a change.
1577
+ */
1578
+ function selectionKey(selection) {
1579
+ var _selection$residues, _selection$chains;
1580
+ const residues = [...new Set((_selection$residues = selection.residues) !== null && _selection$residues !== void 0 ? _selection$residues : [])].sort((a, b) => a - b);
1581
+ return `${[...new Set((_selection$chains = selection.chains) !== null && _selection$chains !== void 0 ? _selection$chains : [])].sort().join(",")}|${residues.join(",")}`;
1582
+ }
1583
+ /** True when the selection names nothing at all. */
1584
+ function isEmptySelection(selection) {
1585
+ var _selection$residues2, _selection$chains2;
1586
+ if (!selection) return true;
1587
+ return !((_selection$residues2 = selection.residues) === null || _selection$residues2 === void 0 ? void 0 : _selection$residues2.length) && !((_selection$chains2 = selection.chains) === null || _selection$chains2 === void 0 ? void 0 : _selection$chains2.length);
1588
+ }
1589
+ /**
1590
+ * The residues a selection covers, ascending and without repeats.
1591
+ *
1592
+ * Chains are expanded through `residuesByChain`, which was read off the loaded
1593
+ * structure, so a chain contributes exactly the residues it holds rather than
1594
+ * the span between its ends. A residue named directly and also carried by a
1595
+ * selected chain is counted once.
1596
+ */
1597
+ function selectionResidues(selection, residuesByChain) {
1598
+ var _selection$residues3, _selection$chains3;
1599
+ const residues = new Set((_selection$residues3 = selection.residues) !== null && _selection$residues3 !== void 0 ? _selection$residues3 : []);
1600
+ for (const chainId of (_selection$chains3 = selection.chains) !== null && _selection$chains3 !== void 0 ? _selection$chains3 : []) {
1601
+ var _residuesByChain$get;
1602
+ for (const index of (_residuesByChain$get = residuesByChain.get(chainId)) !== null && _residuesByChain$get !== void 0 ? _residuesByChain$get : []) residues.add(index);
1603
+ }
1604
+ return [...residues].sort((a, b) => a - b);
1605
+ }
1606
+ /**
1607
+ * Names a selection for the legend's readout.
1608
+ *
1609
+ * A single chain is named as one, since "Chain A" says more than the number of
1610
+ * residues it happens to hold. Anything else is reported as a count, which is
1611
+ * the only thing true of every shape a selection can take. A lone residue is
1612
+ * named by the caller instead, which reads it back off the structure to get its
1613
+ * three-letter code and the number the file gives it.
1614
+ */
1615
+ function selectionLabel(selection, residueCount) {
1616
+ var _selection$chains4, _selection$residues4;
1617
+ const chains = (_selection$chains4 = selection.chains) !== null && _selection$chains4 !== void 0 ? _selection$chains4 : [];
1618
+ if (chains.length === 1 && !((_selection$residues4 = selection.residues) === null || _selection$residues4 === void 0 ? void 0 : _selection$residues4.length)) return `Chain ${chains[0]}`;
1619
+ return `${residueCount} residues`;
1620
+ }
1621
+ /** The mean of the values `read` returns, ignoring residues without one. */
1622
+ function meanOverResidues(residues, read) {
1623
+ let sum = 0;
1624
+ let count = 0;
1625
+ for (const index of residues) {
1626
+ const value = read(index);
1627
+ if (value === null || value === void 0) continue;
1628
+ sum += value;
1629
+ count++;
1630
+ }
1631
+ return count === 0 ? null : sum / count;
1632
+ }
1633
+ //#endregion
1634
+ //#region src/core/ProteinStructureViewer/utils/residueLoci.ts
1635
+ /**
1636
+ * Every atom the predicate accepts, as geometry Mol* can focus, frame and mark,
1637
+ * or undefined when it accepts none.
1638
+ *
1639
+ * One pass over the structure rather than a pass per residue: a whole-chain
1640
+ * selection names hundreds of residues, and resolving them one at a time would
1641
+ * walk the structure once for each.
1642
+ *
1643
+ * Atoms are bucketed by the unit they belong to because element indices are
1644
+ * unit-local. That bucketing is also what lets a result span a chain break: it
1645
+ * carries an entry per unit, which is what a range across two chains needs and
1646
+ * what a single unit-local entry cannot express.
1647
+ *
1648
+ * Whole residues are collected rather than one atom each, since the caller
1649
+ * frames the camera on the loci's bounding sphere and a lone atom would zoom
1650
+ * far closer than the residue warrants.
1651
+ */
1652
+ function lociMatching(structure, matches) {
1653
+ const location = StructureElement.Location.create(structure);
1654
+ const elements = [];
1655
+ for (const unit of structure.units) {
1656
+ location.unit = unit;
1657
+ const indices = [];
1658
+ for (let i = 0; i < unit.elements.length; i++) {
1659
+ location.element = unit.elements[i];
1660
+ if (matches(location)) indices.push(i);
1661
+ }
1662
+ if (indices.length > 0) elements.push({
1663
+ indices,
1664
+ unit
1665
+ });
1666
+ }
1667
+ if (elements.length === 0) return void 0;
1668
+ return StructureElement.Loci(structure, elements.map(({ indices, unit }) => ({
1669
+ indices: OrderedSet.ofSortedArray(indices),
1670
+ unit
1671
+ })));
1672
+ }
1673
+ /**
1674
+ * Every atom of the residues a selection covers, within one structure.
1675
+ *
1676
+ * `hiddenChains` is subtracted from the result. A hidden chain is not drawn, so
1677
+ * geometry built from it would have nothing to sit on: Mol*'s focus
1678
+ * representation draws its own ball-and-stick from whatever is focused, in a
1679
+ * part of the state tree the chain's own visibility does not reach, and a
1680
+ * hidden chain left in the loci would keep showing up there after its cartoon
1681
+ * had gone.
1682
+ */
1683
+ function lociForSelectionInStructure(structure, selection, hiddenChains) {
1684
+ var _selection$residues, _selection$chains;
1685
+ if (isEmptySelection(selection)) return void 0;
1686
+ const residues = new Set((_selection$residues = selection.residues) !== null && _selection$residues !== void 0 ? _selection$residues : []);
1687
+ const chains = new Set((_selection$chains = selection.chains) !== null && _selection$chains !== void 0 ? _selection$chains : []);
1688
+ return lociMatching(structure, (location) => {
1689
+ const chainId = StructureProperties.chain.auth_asym_id(location);
1690
+ if (hiddenChains === null || hiddenChains === void 0 ? void 0 : hiddenChains.has(chainId)) return false;
1691
+ return residues.has(StructureProperties.residue.key(location)) || chains.has(chainId);
1692
+ });
1693
+ }
1694
+ /**
1695
+ * Every atom of the residues between two 0-based indices, inclusive.
1696
+ *
1697
+ * A contiguous span is tested by comparison rather than by expanding it into a
1698
+ * set of indices: this runs on every residue a drag crosses, and a drag can
1699
+ * span the whole structure.
1700
+ */
1701
+ function lociForResidueRange(structure, min, max) {
1702
+ return lociMatching(structure, (location) => {
1703
+ const index = StructureProperties.residue.key(location);
1704
+ return index >= min && index <= max;
1705
+ });
1706
+ }
1707
+ /**
1708
+ * The same, across every structure loaded into a plugin. Results are merged
1709
+ * into the first structure that matched: a loci belongs to one structure, and
1710
+ * the residue index space already spans them as though they were one.
1711
+ */
1712
+ function lociForSelection(plugin, selection, hiddenChains) {
1713
+ for (const entry of plugin.managers.structure.hierarchy.current.structures) {
1714
+ var _entry$cell$obj;
1715
+ const structure = (_entry$cell$obj = entry.cell.obj) === null || _entry$cell$obj === void 0 ? void 0 : _entry$cell$obj.data;
1716
+ if (!structure) continue;
1717
+ const loci = lociForSelectionInStructure(structure, selection, hiddenChains);
1718
+ if (loci) return loci;
1719
+ }
1720
+ }
1721
+ //#endregion
1722
+ //#region src/core/ProteinStructureViewer/utils/residueRef.ts
1723
+ /**
1724
+ * Reads the residue a loci points at, or null when it points at nothing the
1725
+ * viewer can address.
1726
+ *
1727
+ * `index` comes from Mol*'s residue key, which counts residues in file order
1728
+ * from zero and is the same counter `injectPlddt` walks. Deriving it
1729
+ * from the residue's *number* instead would tie it to how the file happens to
1730
+ * be numbered: a crop beginning at residue 200 would index `plddt` at 199, and
1731
+ * a file numbering each chain from 1 would give two residues the same index.
1732
+ */
1733
+ function residueRefFromLoci(loci) {
1734
+ var _StructureProperties$;
1735
+ const location = StructureElement.Location.create(void 0);
1736
+ const firstLoc = StructureElement.Loci.getFirstLocation(loci, location);
1737
+ if (!firstLoc) return null;
1738
+ return {
1739
+ chainId: StructureProperties.chain.auth_asym_id(firstLoc),
1740
+ compId: StructureProperties.atom.label_comp_id(firstLoc),
1741
+ insCode: (_StructureProperties$ = StructureProperties.residue.pdbx_PDB_ins_code(firstLoc)) !== null && _StructureProperties$ !== void 0 ? _StructureProperties$ : "",
1742
+ index: StructureProperties.residue.key(firstLoc),
1743
+ seqId: StructureProperties.residue.auth_seq_id(firstLoc)
1744
+ };
1745
+ }
1746
+ /**
1747
+ * Every residue a loci covers, as a selection the consumer can echo back.
1748
+ *
1749
+ * The counterpart to `residueRefFromLoci`, which names only the first: a drag
1750
+ * across the sequence hands Mol* a range, and reporting its first residue
1751
+ * alone would turn a range the user drew into a single-residue selection.
1752
+ *
1753
+ * Reported as residues rather than as chains even when a whole chain is
1754
+ * covered. What the user drew is a span of residues, and calling it a chain
1755
+ * because it happens to end where one does would change the selection's meaning
1756
+ * on a structure where the two coincide.
1757
+ */
1758
+ function selectionFromLoci(loci) {
1759
+ const location = StructureElement.Location.create(loci.structure);
1760
+ const residues = /* @__PURE__ */ new Set();
1761
+ for (const element of loci.elements) {
1762
+ location.unit = element.unit;
1763
+ OrderedSet.forEach(element.indices, (i) => {
1764
+ location.element = element.unit.elements[i];
1765
+ residues.add(StructureProperties.residue.key(location));
1766
+ });
1767
+ }
1768
+ return { residues: [...residues].sort((a, b) => a - b) };
1769
+ }
1770
+ /**
1771
+ * How a residue is named in the readout, e.g. `"LYS 111"`. Takes the number and
1772
+ * the insertion code from the file so that the readout and the sequence panel
1773
+ * beneath it agree on what to call a residue.
1774
+ */
1775
+ function residueLabel(residue) {
1776
+ return `${residue.compId} ${residue.seqId}${residue.insCode}`;
1777
+ }
1778
+ //#endregion
1779
+ //#region src/core/ProteinStructureViewer/components/SequenceView/utils/loci.ts
1780
+ /** The loci for a residue, or undefined when there is no residue there. */
1781
+ function getLoci(sequenceWrapper, seqIdx) {
1782
+ if (seqIdx !== void 0) {
1783
+ const loci = sequenceWrapper.getLoci(seqIdx);
1784
+ if (!StructureElement.Loci.isEmpty(loci)) return loci;
1785
+ }
1786
+ }
1787
+ /**
1788
+ * Extends a loci to the range between the mouse-down anchor and the current
1789
+ * residue, so dragging across the sequence selects a contiguous span.
1790
+ *
1791
+ * The span is measured in the viewer's own residue index - position in file
1792
+ * order across the whole structure - rather than in element indices, which are
1793
+ * unit-local and so cannot describe a range reaching from one chain into the
1794
+ * next. Measuring it the way every other residue-keyed API measures it is what
1795
+ * lets a drag cross a chain break, and it means a range covers exactly the
1796
+ * residues whose indices lie between its ends.
1797
+ *
1798
+ * An endpoint that names no residue leaves the drag unextended rather than
1799
+ * guessing at where it was. An endpoint spanning several units - a chain with
1800
+ * more than one symmetry operator - is fine: each copy of a residue carries the
1801
+ * same index, so the span is the same either way and resolves back across all
1802
+ * of them.
1803
+ */
1804
+ function extendToRange(loci, anchor) {
1805
+ var _lociForResidueRange;
1806
+ const from = residueRefFromLoci(anchor);
1807
+ const to = residueRefFromLoci(loci);
1808
+ if (!from || !to) return loci;
1809
+ if (from.index === to.index) return loci;
1810
+ const min = Math.min(from.index, to.index);
1811
+ const max = Math.max(from.index, to.index);
1812
+ return (_lociForResidueRange = lociForResidueRange(loci.structure, min, max)) !== null && _lociForResidueRange !== void 0 ? _lociForResidueRange : loci;
1813
+ }
1814
+ //#endregion
1815
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useHoveredResidue.ts
1816
+ /**
1817
+ * Tracks which residue the pointer is over and keeps the tooltip pinned to it.
1818
+ *
1819
+ * The tracked index also deduplicates pointer moves: the grid sees a move for
1820
+ * every pixel, but only the ones that cross into a different residue matter.
1821
+ */
1822
+ function useHoveredResidue({ containerRef, sequenceWrapper }) {
1823
+ const tooltipRef = useRef(null);
1824
+ /** Index of the tracked residue, or -1 when the pointer is off the grid. */
1825
+ const seqIdxRef = useRef(-1);
1826
+ const hide = useCallback(() => {
1827
+ var _tooltipRef$current;
1828
+ return (_tooltipRef$current = tooltipRef.current) === null || _tooltipRef$current === void 0 ? void 0 : _tooltipRef$current.hide();
1829
+ }, []);
1830
+ const clear = useCallback(() => {
1831
+ var _tooltipRef$current2;
1832
+ if (seqIdxRef.current === -1) return false;
1833
+ seqIdxRef.current = -1;
1834
+ (_tooltipRef$current2 = tooltipRef.current) === null || _tooltipRef$current2 === void 0 || _tooltipRef$current2.hide();
1835
+ return true;
1836
+ }, []);
1837
+ const moveTo = useCallback((seqIdx, el) => {
1838
+ var _tooltipRef$current3, _tooltipRef$current4;
1839
+ if (seqIdxRef.current === seqIdx) return false;
1840
+ seqIdxRef.current = seqIdx;
1841
+ if (seqIdx < 0) (_tooltipRef$current3 = tooltipRef.current) === null || _tooltipRef$current3 === void 0 || _tooltipRef$current3.hide();
1842
+ else (_tooltipRef$current4 = tooltipRef.current) === null || _tooltipRef$current4 === void 0 || _tooltipRef$current4.show(el, sequenceWrapper.residueLabel(seqIdx));
1843
+ return true;
1844
+ }, [sequenceWrapper]);
1845
+ useEffect(() => {
1846
+ const scrollTarget = getScrollParent(containerRef.current);
1847
+ if (!scrollTarget) return;
1848
+ const handleScroll = () => clear();
1849
+ scrollTarget.addEventListener("scroll", handleScroll, { passive: true });
1850
+ return () => scrollTarget.removeEventListener("scroll", handleScroll);
1851
+ }, [clear, containerRef]);
1852
+ return useMemo(() => ({
1853
+ clear,
1854
+ hide,
1855
+ moveTo,
1856
+ tooltipRef
1857
+ }), [
1858
+ clear,
1859
+ hide,
1860
+ moveTo
1861
+ ]);
1862
+ }
1863
+ //#endregion
1864
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useLociDispatch.ts
1865
+ /**
1866
+ * Wraps a residue loci and the mouse state into a Mol* interaction event. An
1867
+ * `anchor` extends the loci to the range between it and `loci`, which is how a
1868
+ * drag across the sequence comes out as a contiguous span.
1869
+ */
1870
+ function buildEvent(loci, buttons, button, modifiers, anchor) {
1871
+ const ev = {
1872
+ button,
1873
+ buttons,
1874
+ current: Representation.Loci.Empty,
1875
+ modifiers
1876
+ };
1877
+ if (loci === void 0 || StructureElement.Loci.isEmpty(loci)) return ev;
1878
+ ev.current = { loci: anchor ? extendToRange(loci, anchor) : loci };
1879
+ return ev;
1880
+ }
1881
+ /**
1882
+ * Reports the grid's hover and click to Mol*, on the same behaviors the 3D
1883
+ * view publishes to, so an interaction in either surface reaches the other.
1884
+ */
1885
+ function useLociDispatch() {
1886
+ const plugin = usePlugin();
1887
+ const hover = useCallback((loci, buttons, button, modifiers, anchor) => {
1888
+ plugin.behaviors.interaction.hover.next(buildEvent(loci, buttons, button, modifiers, anchor));
1889
+ }, [plugin]);
1890
+ const click = useCallback((loci, buttons, button, modifiers, anchor) => {
1891
+ plugin.behaviors.interaction.click.next(buildEvent(loci, buttons, button, modifiers, anchor));
1892
+ }, [plugin]);
1893
+ return useMemo(() => ({
1894
+ click,
1895
+ hover
1896
+ }), [click, hover]);
1897
+ }
1898
+ //#endregion
1899
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useSequenceDrag.ts
1900
+ const SequenceDragContext = createContext({
1901
+ clearAnchor: () => void 0,
1902
+ getAnchor: () => void 0,
1903
+ setAnchor: () => void 0
1904
+ });
1905
+ const SequenceDragProvider = SequenceDragContext.Provider;
1906
+ /**
1907
+ * The anchor a drag across the sequence started from, shared by every chain's
1908
+ * grid.
1909
+ *
1910
+ * It has to live above the grids rather than inside one. A complex renders one
1911
+ * grid per chain, so a drag that begins on the target and ends on the binder
1912
+ * starts in one component and finishes in another; an anchor held by the grid
1913
+ * it started in is not there to be read by the grid it ends in, and the drag
1914
+ * would be reported as a plain click on whatever it landed on.
1915
+ *
1916
+ * Held in a ref rather than state: it changes on mouse-down and mouse-up, and
1917
+ * nothing renders from it, so re-rendering every residue in the panel twice per
1918
+ * drag would buy nothing.
1919
+ */
1920
+ function useCreateSequenceDrag() {
1921
+ const anchorRef = useRef(void 0);
1922
+ const getAnchor = useCallback(() => anchorRef.current, []);
1923
+ const setAnchor = useCallback((anchor) => {
1924
+ anchorRef.current = anchor;
1925
+ }, []);
1926
+ const clearAnchor = useCallback(() => {
1927
+ anchorRef.current = void 0;
1928
+ }, []);
1929
+ return useMemo(() => ({
1930
+ clearAnchor,
1931
+ getAnchor,
1932
+ setAnchor
1933
+ }), [
1934
+ clearAnchor,
1935
+ getAnchor,
1936
+ setAnchor
1937
+ ]);
1938
+ }
1939
+ function useSequenceDrag() {
1940
+ return useContext(SequenceDragContext);
1941
+ }
1942
+ //#endregion
1943
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResidueSelection.ts
1944
+ /**
1945
+ * Turns a press and release on the grid into a selection: one residue when
1946
+ * both land on the same one, otherwise the contiguous range dragged across -
1947
+ * which the panel-level anchor lets reach into another chain's grid.
1948
+ */
1949
+ function useResidueSelection({ sequenceWrapper }) {
1950
+ const { clearAnchor, getAnchor, setAnchor } = useSequenceDrag();
1951
+ const { click } = useLociDispatch();
1952
+ const onMouseDown = (e) => {
1953
+ e.stopPropagation();
1954
+ setAnchor(getLoci(sequenceWrapper, readSeqIdx(e.target)));
1955
+ };
1956
+ const onMouseUp = (e) => {
1957
+ e.stopPropagation();
1958
+ const anchor = getAnchor();
1959
+ if (anchor === void 0) return;
1960
+ const loci = getLoci(sequenceWrapper, readSeqIdx(e.target));
1961
+ if (loci) {
1962
+ const dragged = !StructureElement.Loci.areEqual(anchor, loci);
1963
+ click(loci, getButtons(e.nativeEvent), getButton(e.nativeEvent), getModifiers(e.nativeEvent), dragged ? anchor : void 0);
1964
+ }
1965
+ clearAnchor();
1966
+ };
1967
+ return {
1968
+ onMouseDown,
1969
+ onMouseUp
1970
+ };
1971
+ }
1972
+ //#endregion
1973
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResiduePointer.ts
1974
+ /**
1975
+ * Everything the grid does with a pointer: hover on move, and the drag-to-range
1976
+ * selection delegated to `useResidueSelection`.
1977
+ *
1978
+ * Hover reaches the 3D view through a throttled queue, so that sweeping the
1979
+ * pointer across the grid does not ask Mol* to re-mark on every residue
1980
+ * crossed. A drag is exempt: its hover carries the growing range, so it goes
1981
+ * out immediately to keep the preview under the pointer.
1982
+ */
1983
+ function useResiduePointer({ containerRef, sequenceWrapper }) {
1984
+ const { hover } = useLociDispatch();
1985
+ const { clear, hide, moveTo, tooltipRef } = useHoveredResidue({
1986
+ containerRef,
1987
+ sequenceWrapper
1988
+ });
1989
+ const { getAnchor } = useSequenceDrag();
1990
+ const { onMouseDown, onMouseUp } = useResidueSelection({ sequenceWrapper });
1991
+ const queueRef = useRef(null);
1992
+ if (queueRef.current === null) queueRef.current = new Subject();
1993
+ const queue = queueRef.current;
1994
+ useSubscribe(useMemo(() => queue.pipe(throttleTime(HOVER_THROTTLE_MS, void 0, {
1995
+ leading: true,
1996
+ trailing: true
1997
+ })), [queue]), (e) => {
1998
+ hover(getLoci(sequenceWrapper, e.seqIdx < 0 ? void 0 : e.seqIdx), e.buttons, e.button, e.modifiers, getAnchor());
1999
+ });
2000
+ const queueHover = (e, seqIdx) => queue.next({
2001
+ button: getButton(e.nativeEvent),
2002
+ buttons: getButtons(e.nativeEvent),
2003
+ modifiers: getModifiers(e.nativeEvent),
2004
+ seqIdx
2005
+ });
2006
+ /** Asks the 3D view to drop its hover, once, if the grid still holds one. */
2007
+ const releaseHover = (e) => {
2008
+ if (clear()) queueHover(e, -1);
2009
+ };
2010
+ const onContextMenu = (e) => {
2011
+ e.preventDefault();
2012
+ };
2013
+ const onMouseMove = (e) => {
2014
+ var _readSeqIdx;
2015
+ e.stopPropagation();
2016
+ const el = e.target;
2017
+ if (!el || !el.getAttribute) {
2018
+ releaseHover(e);
2019
+ return;
2020
+ }
2021
+ const seqIdx = (_readSeqIdx = readSeqIdx(el)) !== null && _readSeqIdx !== void 0 ? _readSeqIdx : -1;
2022
+ if (!moveTo(seqIdx, el)) return;
2023
+ const anchor = getAnchor();
2024
+ if (anchor === void 0) {
2025
+ queueHover(e, seqIdx);
2026
+ return;
2027
+ }
2028
+ hover(getLoci(sequenceWrapper, seqIdx), ButtonsType.Flag.None, ButtonsType.Flag.None, getModifiers(e.nativeEvent), anchor);
2029
+ };
2030
+ /**
2031
+ * Leaving one grid is not the end of a drag: on a complex the next chain's
2032
+ * grid is a separate element, so a drag from the target into the binder
2033
+ * leaves this one on its way. The anchor is therefore left alone here and
2034
+ * dropped by the release, or by the pointer leaving the panel altogether.
2035
+ */
2036
+ const onMouseLeave = (e) => {
2037
+ e.stopPropagation();
2038
+ hide();
2039
+ releaseHover(e);
2040
+ };
2041
+ return {
2042
+ handlers: {
2043
+ onContextMenu,
2044
+ onMouseDown,
2045
+ onMouseLeave,
2046
+ onMouseMove,
2047
+ onMouseUp
2048
+ },
2049
+ tooltipRef
2050
+ };
2051
+ }
2052
+ //#endregion
2053
+ //#region src/core/ProteinStructureViewer/components/SequenceView/components/ResidueTooltip/index.tsx
2054
+ var _getSpaces$m, _getSpaces;
2055
+ /**
2056
+ * Pull the tooltip toward the residue by the SDS `m` spacing token. Spacing
2057
+ * tokens are theme-invariant, so reading from the light theme is fine; popper's
2058
+ * offset modifier needs a number, hence deriving it from the token.
2059
+ */
2060
+ const MAIN_AXIS_OFFSET = -((_getSpaces$m = (_getSpaces = getSpaces({ theme: defaultTheme })) === null || _getSpaces === void 0 ? void 0 : _getSpaces.m) !== null && _getSpaces$m !== void 0 ? _getSpaces$m : 12);
2061
+ /**
2062
+ * A single controlled tooltip anchored to the residue span currently under the
2063
+ * cursor. Driven imperatively through its ref so that hover updates re-render
2064
+ * only the tooltip, not the residue grid.
2065
+ */
2066
+ const ResidueTooltip = forwardRef((_props, ref) => {
2067
+ var _getSemanticColors;
2068
+ const [{ anchorEl, label }, setState] = useState({
2069
+ anchorEl: null,
2070
+ label: ""
2071
+ });
2072
+ const residueTooltipBackgroundColor = (_getSemanticColors = getSemanticColors({ theme: useTheme$1() })) === null || _getSemanticColors === void 0 || (_getSemanticColors = _getSemanticColors.base) === null || _getSemanticColors === void 0 ? void 0 : _getSemanticColors.backgroundPrimary;
2073
+ useImperativeHandle(ref, () => ({
2074
+ hide: () => setState((prev) => prev.anchorEl === null ? prev : _objectSpread2(_objectSpread2({}, prev), {}, { anchorEl: null })),
2075
+ show: (nextAnchorEl, nextLabel) => setState({
2076
+ anchorEl: nextAnchorEl,
2077
+ label: nextLabel
2078
+ })
2079
+ }), []);
2080
+ return /* @__PURE__ */ jsx(Tooltip, {
2081
+ arrow: true,
2082
+ disableInteractive: true,
2083
+ open: anchorEl !== null,
2084
+ placement: "top",
2085
+ slotProps: {
2086
+ popper: {
2087
+ anchorEl,
2088
+ modifiers: [{
2089
+ name: "offset",
2090
+ options: { offset: [0, MAIN_AXIS_OFFSET] }
2091
+ }]
2092
+ },
2093
+ tooltip: { style: { backgroundColor: residueTooltipBackgroundColor } },
2094
+ arrow: { style: { color: residueTooltipBackgroundColor } }
2095
+ },
2096
+ title: label,
2097
+ children: /* @__PURE__ */ jsx("span", { style: {
2098
+ height: 0,
2099
+ position: "fixed",
2100
+ width: 0
2101
+ } })
2102
+ });
2103
+ });
2104
+ //#endregion
2105
+ //#region src/core/ProteinStructureViewer/components/SequenceView/components/Sequence/index.tsx
2106
+ /**
2107
+ * One residue. Not a component: the grid can hold thousands of these, and
2108
+ * giving each its own fiber costs more than it saves, since the markers that
2109
+ * actually change bypass React anyway.
2110
+ */
2111
+ function renderResidue(sequenceWrapper, seqIdx, seqNum) {
2112
+ return /* @__PURE__ */ jsxs("span", {
2113
+ className: getResidueClass(sequenceWrapper, seqIdx),
2114
+ "data-seqid": seqIdx,
2115
+ children: [seqNum && /* @__PURE__ */ jsx("span", {
2116
+ className: "msp-sequence-number",
2117
+ children: seqNum
2118
+ }), sequenceWrapper.residueLabel(seqIdx)]
2119
+ }, seqIdx);
2120
+ }
2121
+ /** Interactive residue grid, kept in sync with the 3D view's hover and selection. */
2122
+ const Sequence = ({ chainLabel, hideSequenceNumbers, residueColors, sequenceNumberPeriod, sequenceWrapper }) => {
2123
+ const containerRef = useRef(null);
2124
+ /** Scratch location reused by every sequence-number lookup below. */
2125
+ const locationRef = useRef(StructureElement.Location.create(void 0));
2126
+ useResidueMarkers({
2127
+ containerRef,
2128
+ residueColors,
2129
+ sequenceWrapper
2130
+ });
2131
+ const { handlers, tooltipRef } = useResiduePointer({
2132
+ containerRef,
2133
+ sequenceWrapper
2134
+ });
2135
+ const period = resolveSequenceNumberPeriod(sequenceWrapper, locationRef.current, sequenceNumberPeriod);
2136
+ const groups = [];
2137
+ for (let start = 0; start < sequenceWrapper.length; start += 10) {
2138
+ const end = Math.min(start + 10, sequenceWrapper.length);
2139
+ const residues = [];
2140
+ for (let i = start; i < end; i++) {
2141
+ const showNum = !hideSequenceNumbers && i % period === 0;
2142
+ residues.push(renderResidue(sequenceWrapper, i, showNum ? getSequenceNumber(sequenceWrapper, i, locationRef.current) : null));
2143
+ }
2144
+ groups.push(/* @__PURE__ */ jsx("span", { children: residues }, `group-${start}`));
2145
+ }
2146
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(ResidueGrid, _objectSpread2(_objectSpread2({
2147
+ "aria-label": buildSequenceLabel(sequenceWrapper, chainLabel),
2148
+ className: "msp-sequence-wrapper",
2149
+ ref: containerRef,
2150
+ role: "img"
2151
+ }, handlers), {}, { children: groups })), /* @__PURE__ */ jsx(ResidueTooltip, { ref: tooltipRef })] });
2152
+ };
2153
+ //#endregion
2154
+ //#region src/core/ProteinStructureViewer/components/SequenceView/utils/copyText.ts
2155
+ /**
2156
+ * Writes `text` to the clipboard.
2157
+ *
2158
+ * The async Clipboard API is preferred, but nested srcdoc sandboxes — MCP
2159
+ * inspectors, Claude Desktop, and similar hosts — often omit `clipboard-write`
2160
+ * from their Permissions Policy, so `navigator.clipboard.writeText` rejects
2161
+ * even on a user click. `document.execCommand("copy")` only needs that click, so
2162
+ * it covers those hosts without the consumer having to patch the bundle.
2163
+ */
2164
+ function copyText(text) {
2165
+ var _navigator$clipboard;
2166
+ if (!((_navigator$clipboard = navigator.clipboard) === null || _navigator$clipboard === void 0 ? void 0 : _navigator$clipboard.writeText)) return copyWithSelection(text);
2167
+ return navigator.clipboard.writeText(text).catch(() => copyWithSelection(text));
2168
+ }
2169
+ /**
2170
+ * Copies by selecting a transient textarea. Must run under user activation,
2171
+ * which a click still has after the Clipboard API has been refused.
2172
+ */
2173
+ function copyWithSelection(text) {
2174
+ return new Promise((resolve, reject) => {
2175
+ const area = document.createElement("textarea");
2176
+ area.value = text;
2177
+ area.setAttribute("readonly", "");
2178
+ area.setAttribute("aria-hidden", "true");
2179
+ area.style.position = "fixed";
2180
+ area.style.top = "-1000px";
2181
+ document.body.appendChild(area);
2182
+ area.select();
2183
+ area.setSelectionRange(0, text.length);
2184
+ let copied = false;
2185
+ try {
2186
+ copied = document.execCommand("copy");
2187
+ } catch (_unused) {
2188
+ copied = false;
2189
+ }
2190
+ area.remove();
2191
+ if (copied) resolve();
2192
+ else reject(/* @__PURE__ */ new Error("The host blocked clipboard access."));
2193
+ });
2194
+ }
2195
+ //#endregion
2196
+ //#region src/core/ProteinStructureViewer/components/SequenceView/utils/sequenceText.ts
2197
+ /**
2198
+ * The structure's residues as text, one section per chain separated by
2199
+ * `CHAIN_SEPARATOR`. Placeholder entries contribute nothing, since they have no
2200
+ * residues to write.
2201
+ */
2202
+ function sequenceTextFromEntries(entries) {
2203
+ return entries.filter((entry) => typeof entry.wrapper !== "string").map((entry) => {
2204
+ const wrapper = entry.wrapper;
2205
+ return Array.from({ length: wrapper.length }, (_, i) => wrapper.residueLabel(i)).join("");
2206
+ }).join("|");
2207
+ }
2208
+ //#endregion
2209
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useCopySequence.ts
2210
+ /**
2211
+ * Copies the structure's residues to the clipboard, chains separated so a
2212
+ * complex does not paste as one sequence, and holds a confirmation flag for a
2213
+ * moment afterwards.
2214
+ */
2215
+ function useCopySequence(entries) {
2216
+ const [copied, setCopied] = useState(false);
2217
+ const timeoutRef = useRef(null);
2218
+ useEffect(() => () => {
2219
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
2220
+ }, []);
2221
+ return {
2222
+ copied,
2223
+ copySequence: useCallback(() => {
2224
+ copyText(sequenceTextFromEntries(entries)).then(() => {
2225
+ setCopied(true);
2226
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
2227
+ timeoutRef.current = setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS);
2228
+ }).catch(() => {});
2229
+ }, [entries])
2230
+ };
2231
+ }
2232
+ //#endregion
2233
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useSequenceWrappers.ts
2234
+ const EMPTY_STATE = {
2235
+ chainGroupId: -1,
2236
+ modelEntityId: "",
2237
+ operatorKey: "",
2238
+ structure: Structure.Empty,
2239
+ structureOptions: {
2240
+ all: [],
2241
+ options: []
2242
+ },
2243
+ structureRef: ""
2244
+ };
2245
+ function readStructure(plugin, ref) {
2246
+ const cell = plugin.state.data.select(ref)[0];
2247
+ if (!ref || !cell || !cell.obj) return Structure.Empty;
2248
+ return cell.obj.data;
2249
+ }
2250
+ /** Picks the first structure, entity, chain, and operator Mol* offers. */
2251
+ function readInitialState(plugin) {
2252
+ const structureOptions = getStructureOptions(plugin.state.data);
2253
+ const structureRef = structureOptions.options[0][0];
2254
+ const structure = readStructure(plugin, structureRef);
2255
+ const modelEntityId = getModelEntityOptions(structure)[0][0];
2256
+ const chainGroupId = getChainOptions(structure, modelEntityId)[0][0];
2257
+ return {
2258
+ chainGroupId,
2259
+ modelEntityId,
2260
+ operatorKey: getOperatorOptions(structure, modelEntityId, chainGroupId)[0][0],
2261
+ structure,
2262
+ structureOptions,
2263
+ structureRef
2264
+ };
2265
+ }
2266
+ function buildParams(state) {
2267
+ const { modelEntityId, structure, structureOptions } = state;
2268
+ const chainOptions = getChainOptions(structure, modelEntityId);
2269
+ return {
2270
+ chain: ParamDefinition.Select(chainOptions[0][0], chainOptions, { shortLabel: true }),
2271
+ structure: ParamDefinition.Select(structureOptions.options[0][0], structureOptions.options, { shortLabel: true })
2272
+ };
2273
+ }
2274
+ /**
2275
+ * The file's own name for a chain group, or `""` when the structure holds no
2276
+ * unit for it. Mol* groups its sequence panel by `chainGroupId`, but every
2277
+ * chain-level prop on the viewer is keyed by `auth_asym_id`, so the two have
2278
+ * to be bridged through the structure itself.
2279
+ */
2280
+ function authAsymIdFor(structure, chainGroupId) {
2281
+ const location = StructureElement.Location.create(structure);
2282
+ for (const unit of structure.units) {
2283
+ if (unit.chainGroupId !== chainGroupId) continue;
2284
+ const element = unit.elements[0];
2285
+ if (element === void 0) continue;
2286
+ StructureElement.Location.set(location, structure, unit, element);
2287
+ return StructureProperties.chain.auth_asym_id(location);
2288
+ }
2289
+ return "";
2290
+ }
2291
+ /**
2292
+ * One entry per polymer chain, in Mol*'s entity / chain / operator order.
2293
+ *
2294
+ * Polymer entities only. The heteroatoms on a chain are separate entities, and
2295
+ * Mol* would hand back a caption and a grid for each - a myoglobin listing
2296
+ * "Chain A" and then two more headers, both reading "Chain A_1 [auth A]", one
2297
+ * holding the heme and one the hydroxide. They are drawn in the 3D view and
2298
+ * they are not sequence, and a caption per ligand offers a chain toggle for
2299
+ * something that is not a chain.
2300
+ */
2301
+ function buildEntries(structure, selection, _params) {
2302
+ const entries = [];
2303
+ for (const [modelEntityId] of getModelEntityOptions(structure, true)) for (const [chainGroupId, cLabel] of getChainOptions(structure, modelEntityId)) for (const [operatorKey] of getOperatorOptions(structure, modelEntityId, chainGroupId)) entries.push({
2304
+ chainId: authAsymIdFor(structure, chainGroupId),
2305
+ id: `${modelEntityId}:${chainGroupId}:${operatorKey}`,
2306
+ label: cLabel,
2307
+ wrapper: getSequenceWrapper({
2308
+ chainGroupId,
2309
+ modelEntityId,
2310
+ operatorKey,
2311
+ structure
2312
+ }, selection)
2313
+ });
2314
+ return entries;
2315
+ }
2316
+ function countResidues(entries) {
2317
+ return entries.reduce((sum, entry) => sum + (typeof entry.wrapper === "string" ? 0 : entry.wrapper.length), 0);
2318
+ }
2319
+ /**
2320
+ * The residue wrappers for every chain of the loaded structure, resynced
2321
+ * whenever Mol* creates, updates, or removes a structure object.
2322
+ *
2323
+ * The wrappers read the live selection, so they are rebuilt on each render
2324
+ * rather than memoized; that is what keeps the grid's dimming in step with a
2325
+ * selection made in the 3D view.
2326
+ */
2327
+ function useSequenceWrappers() {
2328
+ const plugin = usePlugin();
2329
+ const [state, setState] = useState(EMPTY_STATE);
2330
+ const sync = useCallback(() => {
2331
+ if (arrayEqual(getStructureOptions(plugin.state.data).all, state.structureOptions.all)) return;
2332
+ setState(readInitialState(plugin));
2333
+ }, [plugin, state.structureOptions.all]);
2334
+ useEffect(() => {
2335
+ if (plugin.state.data.select(StateSelection.Generators.rootsOfType(PluginStateObject.Molecule.Structure)).length > 0) setState(readInitialState(plugin));
2336
+ }, []);
2337
+ useSubscribe(plugin.state.events.object.updated, ({ ref, obj }) => {
2338
+ if (ref === state.structureRef && obj && obj.type === PluginStateObject.Molecule.Structure.type && obj.data !== state.structure) sync();
2339
+ });
2340
+ useSubscribe(plugin.state.events.object.created, ({ obj }) => {
2341
+ if (obj && obj.type === PluginStateObject.Molecule.Structure.type) sync();
2342
+ });
2343
+ useSubscribe(plugin.state.events.object.removed, ({ obj }) => {
2344
+ if (obj && obj.type === PluginStateObject.Molecule.Structure.type) sync();
2345
+ });
2346
+ const structure = readStructure(plugin, state.structureRef);
2347
+ if (structure === Structure.Empty) return {
2348
+ entries: [],
2349
+ isEmpty: true,
2350
+ residueCount: 0
2351
+ };
2352
+ const entries = buildEntries(structure, plugin.managers.structure.selection, buildParams(state));
2353
+ return {
2354
+ entries,
2355
+ isEmpty: false,
2356
+ residueCount: countResidues(entries)
2357
+ };
2358
+ }
2359
+ //#endregion
2360
+ //#region src/core/ProteinStructureViewer/components/SequenceView/index.tsx
2361
+ /**
2362
+ * Builds the Mol* sequence panel view.
2363
+ *
2364
+ * Like the viewport, Mol* renders this inside its own React root, so the theme
2365
+ * mode and the panel's background arrive through `viewSettings` and are watched
2366
+ * for changes rather than read once. The theme is re-supplied through a local
2367
+ * `ThemeProvider` for the Emotion styles and the SDS `Tooltip` below.
2368
+ */
2369
+ function createSequenceView(viewSettings) {
2370
+ return function SequenceView() {
2371
+ const { mode, theme } = useMolstarTheme(viewSettings);
2372
+ const backgroundColor = useViewSetting(viewSettings, (s) => s.sequenceViewerBackgroundColor);
2373
+ const hiddenChains = useViewSetting(viewSettings, (s) => s.hiddenChains);
2374
+ const onChainHover = useViewSetting(viewSettings, (s) => s.onChainHover);
2375
+ const onChainSelect = useViewSetting(viewSettings, (s) => s.onChainSelect);
2376
+ const onChainToggle = useViewSetting(viewSettings, (s) => s.onChainToggle);
2377
+ const selectedChains = useViewSetting(viewSettings, (s) => s.selectedChains);
2378
+ const { entries, isEmpty, residueCount } = useSequenceWrappers();
2379
+ const { copied, copySequence } = useCopySequence(entries);
2380
+ const drag = useCreateSequenceDrag();
2381
+ if (isEmpty) return /* @__PURE__ */ jsx(ThemeProvider, {
2382
+ theme,
2383
+ children: /* @__PURE__ */ jsx(EmptyState, {
2384
+ backgroundColor,
2385
+ className: "msp-sequence",
2386
+ children: "No structure available"
2387
+ })
2388
+ });
2389
+ const residueColors = residueColorsForMode(mode);
2390
+ const showChainLabels = entries.length > 1;
2391
+ return /* @__PURE__ */ jsx(ThemeProvider, {
2392
+ theme,
2393
+ children: /* @__PURE__ */ jsxs(SequencePanel, {
2394
+ backgroundColor,
2395
+ children: [/* @__PURE__ */ jsxs(PanelHeader, { children: [
2396
+ /* @__PURE__ */ jsx(PanelTitle, { children: "Sequence" }),
2397
+ /* @__PURE__ */ jsx(Tooltip, {
2398
+ arrow: true,
2399
+ placement: "top",
2400
+ title: copied ? "Copied!" : "Copy",
2401
+ children: /* @__PURE__ */ jsx(CopyButton, {
2402
+ "aria-label": "Copy sequence to clipboard",
2403
+ onClick: copySequence,
2404
+ type: "button",
2405
+ children: copied ? /* @__PURE__ */ jsx(CheckIcon, { size: 16 }) : /* @__PURE__ */ jsx(CopyIcon, { size: 16 })
2406
+ })
2407
+ }),
2408
+ /* @__PURE__ */ jsxs(ResidueCount, { children: [/* @__PURE__ */ jsx(ResidueCountLabel, { children: "Residues" }), /* @__PURE__ */ jsx(ResidueCountValue, { children: residueCount })] })
2409
+ ] }), /* @__PURE__ */ jsx(SequenceScroller, {
2410
+ backgroundColor,
2411
+ children: /* @__PURE__ */ jsx(SequenceDragProvider, {
2412
+ value: drag,
2413
+ children: /* @__PURE__ */ jsx(SequenceScrollArea, {
2414
+ className: "msp-sequence msp-sequence-wrapper-non-empty",
2415
+ onMouseLeave: drag.clearAnchor,
2416
+ children: entries.map((s) => {
2417
+ var _hiddenChains$has, _selectedChains$has;
2418
+ const hidden = (_hiddenChains$has = hiddenChains === null || hiddenChains === void 0 ? void 0 : hiddenChains.has(s.chainId)) !== null && _hiddenChains$has !== void 0 ? _hiddenChains$has : false;
2419
+ const grid = typeof s.wrapper === "string" ? /* @__PURE__ */ jsx("div", {
2420
+ className: "msp-sequence-wrapper",
2421
+ children: s.wrapper
2422
+ }) : /* @__PURE__ */ jsx(Sequence, {
2423
+ chainLabel: showChainLabels ? s.label : void 0,
2424
+ residueColors,
2425
+ sequenceWrapper: s.wrapper
2426
+ });
2427
+ return /* @__PURE__ */ jsxs(Fragment, { children: [showChainLabels && /* @__PURE__ */ jsx(ChainHeader, {
2428
+ chainId: s.chainId,
2429
+ isHidden: hidden,
2430
+ isSelected: (_selectedChains$has = selectedChains === null || selectedChains === void 0 ? void 0 : selectedChains.has(s.chainId)) !== null && _selectedChains$has !== void 0 ? _selectedChains$has : false,
2431
+ label: s.label,
2432
+ onHover: onChainHover,
2433
+ onSelect: onChainSelect,
2434
+ onToggle: onChainToggle
2435
+ }), hidden ? /* @__PURE__ */ jsx(HiddenChainGroup, { children: grid }) : grid] }, s.id);
2436
+ })
2437
+ })
2438
+ })
2439
+ })]
2440
+ })
2441
+ });
2442
+ };
2443
+ }
2444
+ //#endregion
2445
+ //#region src/core/ProteinStructureViewer/utils/axes.ts
2446
+ /**
2447
+ * The orientation axes widget, as Mol* parameterizes it.
2448
+ *
2449
+ * Shared rather than declared where it is used, because two different parts of
2450
+ * Mol* take the same shape: the live canvas takes it as
2451
+ * `camera.helper.axes`, and the screenshot helper takes it as its own `axes`,
2452
+ * so an image can carry the widget or leave it out independently of the view
2453
+ * it was captured from.
2454
+ */
2455
+ const AXES_ON = {
2456
+ name: "on",
2457
+ params: {
2458
+ alpha: .51,
2459
+ colorX: 16711680,
2460
+ colorY: 32768,
2461
+ colorZ: 255,
2462
+ labelColorX: 8421504,
2463
+ labelColorY: 8421504,
2464
+ labelColorZ: 8421504,
2465
+ labelOpacity: 1,
2466
+ labelScale: .25,
2467
+ labelX: "X",
2468
+ labelY: "Y",
2469
+ labelZ: "Z",
2470
+ location: "bottom-left",
2471
+ locationOffsetX: 0,
2472
+ locationOffsetY: 0,
2473
+ originColor: 8421504,
2474
+ planeColorXY: 8421504,
2475
+ planeColorXZ: 8421504,
2476
+ planeColorYZ: 8421504,
2477
+ radiusScale: .075,
2478
+ scale: .15,
2479
+ showLabels: false,
2480
+ showPlanes: true
2481
+ }
2482
+ };
2483
+ const AXES_OFF = {
2484
+ name: "off",
2485
+ params: {}
2486
+ };
2487
+ //#endregion
2488
+ //#region src/core/ProteinStructureViewer/utils/color.ts
2489
+ /** Parses `#RRGGBB` (or `RRGGBB`) into a Mol* `Color`. */
2490
+ function parseHexColor(hex) {
2491
+ const h = hex.replace("#", "");
2492
+ return Color.fromRgb(parseInt(h.substring(0, 2), 16), parseInt(h.substring(2, 4), 16), parseInt(h.substring(4, 6), 16));
2493
+ }
2494
+ /**
2495
+ * Parses a theme color into a Mol* `Color`, falling back when the token is
2496
+ * missing or is a format Mol* cannot consume (theme values are hex in practice,
2497
+ * but the palette types allow any CSS color string).
2498
+ */
2499
+ function themeColor(value, fallback) {
2500
+ const candidate = value === null || value === void 0 ? void 0 : value.trim();
2501
+ return parseHexColor(candidate !== void 0 && /^#?[0-9a-f]{6}$/i.test(candidate) ? candidate : fallback);
2502
+ }
2503
+ /**
2504
+ * Neutral fill for residues with no overlay value. Sits between the light and
2505
+ * dark backgrounds so unhighlighted geometry stays legible in both modes.
2506
+ */
2507
+ function neutralResidueColor(mode) {
2508
+ const g = mode === "dark" ? 100 : 180;
2509
+ return Color.fromRgb(g, g, g);
2510
+ }
2511
+ //#endregion
2512
+ //#region src/core/ProteinStructureViewer/utils/screenshot.ts
2513
+ /**
2514
+ * Each resolution as the Mol* preset that produces it: 1280x720, 1920x1080,
2515
+ * 3840x2160, 7680x4320. Named here rather than given as dimensions so the
2516
+ * aspect stays Mol*'s to choose.
2517
+ *
2518
+ * Mol*'s own `viewport` preset - the canvas at its current size - is left out
2519
+ * deliberately: it makes the image depend on how big the viewer happens to be
2520
+ * on screen, which is not something a caller asking for "high" is asking for.
2521
+ */
2522
+ const RESOLUTION_PRESETS = {
2523
+ high: "ultra-hd",
2524
+ low: "hd",
2525
+ maximum: "8k-ultra-hd",
2526
+ medium: "full-hd"
2527
+ };
2528
+ /** Painted behind the structure when a background is asked for but unreadable. */
2529
+ const FALLBACK_BACKGROUND = "#ffffff";
2530
+ /**
2531
+ * Downloads the structure as a PNG.
2532
+ *
2533
+ * Mol*'s screenshot helper renders its own pass rather than reading the canvas
2534
+ * back, so the image is drawn fresh at the requested size and carries its own
2535
+ * transparency and axes settings - none of which disturb the view on screen.
2536
+ *
2537
+ * A named background is the one exception. The helper only chooses between
2538
+ * transparent and whatever the renderer is already painting, so a color has to
2539
+ * be put on the canvas for the length of the capture and taken off afterwards.
2540
+ * `finally` is what guarantees the second half: leaving a figure's background
2541
+ * behind on the viewer would be a worse bug than a failed download.
2542
+ */
2543
+ function downloadStructureImage(_x) {
2544
+ return _downloadStructureImage.apply(this, arguments);
2545
+ }
2546
+ function _downloadStructureImage() {
2547
+ _downloadStructureImage = _asyncToGenerator(function* (plugin, options = {}) {
2548
+ const helper = plugin.helpers.viewportScreenshot;
2549
+ if (!helper) return;
2550
+ const { backgroundColor, filename, resolution = "medium", showAxes } = options;
2551
+ const transparent = backgroundColor === void 0;
2552
+ helper.behaviors.values.next(_objectSpread2(_objectSpread2({}, helper.behaviors.values.value), {}, {
2553
+ axes: showAxes ? AXES_ON : AXES_OFF,
2554
+ format: {
2555
+ name: "png",
2556
+ params: {}
2557
+ },
2558
+ resolution: {
2559
+ name: RESOLUTION_PRESETS[resolution],
2560
+ params: {}
2561
+ },
2562
+ transparent
2563
+ }));
2564
+ const canvas3d = plugin.canvas3d;
2565
+ const painted = canvas3d === null || canvas3d === void 0 ? void 0 : canvas3d.props.renderer.backgroundColor;
2566
+ const overrideBackground = !transparent && canvas3d !== void 0;
2567
+ if (overrideBackground) canvas3d === null || canvas3d === void 0 || canvas3d.setProps({ renderer: { backgroundColor: themeColor(backgroundColor, FALLBACK_BACKGROUND) } });
2568
+ try {
2569
+ yield helper.download(filename);
2570
+ } finally {
2571
+ if (overrideBackground && painted !== void 0) canvas3d === null || canvas3d === void 0 || canvas3d.setProps({ renderer: { backgroundColor: painted } });
2572
+ }
2573
+ });
2574
+ return _downloadStructureImage.apply(this, arguments);
2575
+ }
2576
+ //#endregion
2577
+ //#region src/core/ProteinStructureViewer/components/Viewport/constants.ts
2578
+ /**
2579
+ * Fraction of the bounding sphere radius within which the camera still counts
2580
+ * as sitting at the default view, absorbing easing and float error.
2581
+ */
2582
+ const DEFAULT_VIEW_TOLERANCE = .02;
2583
+ //#endregion
2584
+ //#region src/core/ProteinStructureViewer/components/Viewport/utils/camera.ts
2585
+ /** True when the camera's zoom/center differs from the default fit. */
2586
+ function isZoomedOffDefault(canvas3d) {
2587
+ const { center, radius } = canvas3d.boundingSphereVisible;
2588
+ if (radius <= 0) return false;
2589
+ const { state } = canvas3d.camera;
2590
+ const tolerance = radius * DEFAULT_VIEW_TOLERANCE;
2591
+ return Math.abs(state.radius - radius) > tolerance || Vec3.distance(state.target, center) > tolerance;
2592
+ }
2593
+ //#endregion
2594
+ //#region src/core/ProteinStructureViewer/components/Viewport/hooks/useCameraReset.ts
2595
+ /**
2596
+ * Tracks whether the camera has moved off the default view, and puts it back.
2597
+ *
2598
+ * The default view is the auto-fit to the structure's bounding sphere, so
2599
+ * "moved" means either the zoom/center has drifted off that fit or a manual
2600
+ * drag has rotated it - rotation has to be tracked separately, since it leaves
2601
+ * the zoom and center at the default and the bounding-sphere check cannot see
2602
+ * it.
2603
+ */
2604
+ function useCameraReset() {
2605
+ const plugin = usePlugin();
2606
+ const [cameraChanged, setCameraChanged] = useState(false);
2607
+ /**
2608
+ * Mirrors the state above so the per-frame handler below can skip redundant
2609
+ * updates without re-reading state through a stale closure.
2610
+ */
2611
+ const cameraChangedRef = useRef(false);
2612
+ const updateCameraChanged = useCallback((changed) => {
2613
+ if (changed === cameraChangedRef.current) return;
2614
+ cameraChangedRef.current = changed;
2615
+ setCameraChanged(changed);
2616
+ }, []);
2617
+ /**
2618
+ * A manual gesture (rotate via drag) moves the camera off the default view.
2619
+ * Tracked separately from zoom because rotation leaves the zoom/center at
2620
+ * the default fit, so the bounding-sphere check cannot detect it.
2621
+ */
2622
+ const gesturedRef = useRef(false);
2623
+ /**
2624
+ * A (re)loaded structure auto-fits to the default view. Ignore camera
2625
+ * changes until that fit transition settles so the button does not flash
2626
+ * during load.
2627
+ */
2628
+ const awaitingFitRef = useRef(true);
2629
+ const fitStartedRef = useRef(false);
2630
+ /**
2631
+ * Reconciles the button visibility with the current camera. The button
2632
+ * shows when the camera differs from the default view: either the
2633
+ * zoom/center has moved off the bounding-sphere fit, or a manual gesture
2634
+ * rotated the view.
2635
+ */
2636
+ const syncCameraChanged = useCallback(() => {
2637
+ const canvas3d = plugin.canvas3d;
2638
+ if (!canvas3d) return;
2639
+ const inTransition = canvas3d.camera.transition.inTransition;
2640
+ if (awaitingFitRef.current) {
2641
+ if (inTransition) {
2642
+ fitStartedRef.current = true;
2643
+ return;
2644
+ }
2645
+ if (!fitStartedRef.current && isZoomedOffDefault(canvas3d)) return;
2646
+ awaitingFitRef.current = false;
2647
+ }
2648
+ if (inTransition) return;
2649
+ updateCameraChanged(gesturedRef.current || isZoomedOffDefault(canvas3d));
2650
+ }, [plugin, updateCameraChanged]);
2651
+ useEffect(() => {
2652
+ const subscriptions = [];
2653
+ let cameraBound = false;
2654
+ const bindCamera = () => {
2655
+ const canvas3d = plugin.canvas3d;
2656
+ if (!canvas3d || cameraBound) return;
2657
+ cameraBound = true;
2658
+ const setGestured = () => {
2659
+ gesturedRef.current = true;
2660
+ syncCameraChanged();
2661
+ };
2662
+ subscriptions.push(canvas3d.input.drag.subscribe(setGestured), canvas3d.input.wheel.subscribe(setGestured), plugin.state.data.events.object.created.subscribe(() => {
2663
+ gesturedRef.current = false;
2664
+ awaitingFitRef.current = true;
2665
+ fitStartedRef.current = false;
2666
+ updateCameraChanged(false);
2667
+ }), canvas3d.didDraw.subscribe(syncCameraChanged));
2668
+ };
2669
+ subscriptions.push(plugin.behaviors.canvas3d.initialized.subscribe(bindCamera));
2670
+ bindCamera();
2671
+ return () => subscriptions.forEach((s) => s.unsubscribe());
2672
+ }, [
2673
+ plugin,
2674
+ syncCameraChanged,
2675
+ updateCameraChanged
2676
+ ]);
2677
+ return {
2678
+ cameraChanged,
2679
+ resetCamera: useCallback(_asyncToGenerator(function* () {
2680
+ yield PluginCommands.Camera.Reset(plugin, { durationMs: 250 });
2681
+ yield new Promise((resolve) => setTimeout(resolve, 250));
2682
+ yield PluginCommands.Camera.ResetAxes(plugin, { durationMs: 250 });
2683
+ yield new Promise((resolve) => setTimeout(resolve, 250));
2684
+ gesturedRef.current = false;
2685
+ updateCameraChanged(false);
2686
+ }), [plugin, updateCameraChanged])
2687
+ };
2688
+ }
2689
+ //#endregion
2690
+ //#region src/core/ProteinStructureViewer/components/Viewport/style.ts
2691
+ /**
2692
+ * Pinned to the lower-left of the viewport, clear of the sequence panel below
2693
+ * and the axes widget in the corner.
2694
+ *
2695
+ * Anchored by its bottom edge, so the buttons stack upwards: the last one
2696
+ * stays put where a reader last saw it, and an earlier one appearing or going
2697
+ * does not move the rest. Reset comes first in the markup and so sits above
2698
+ * capture.
2699
+ */
2700
+ const ViewportButtonStack = styled("div")`
2701
+ position: absolute;
2702
+ bottom: 48px;
2703
+ z-index: 10;
2704
+ display: flex;
2705
+ flex-direction: column;
2706
+
2707
+ ${(props) => {
2708
+ const spaces = getSpaces(props);
2709
+ return `
2710
+ left: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
2711
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
2712
+ `;
2713
+ }}
2714
+ `;
2715
+ //#endregion
2716
+ //#region src/core/ProteinStructureViewer/components/Viewport/index.tsx
2717
+ /**
2718
+ * Builds the Mol* viewport view.
2719
+ *
2720
+ * Mol* instantiates view components inside its own React root, so they render
2721
+ * outside the consumer's provider tree and cannot read the theme from context.
2722
+ * `viewSettings` carries the mode in instead, and is watched rather than read
2723
+ * once so that a theme change after the plugin was created still lands here;
2724
+ * the mode is re-supplied via a local `ThemeProvider` so the Emotion styles
2725
+ * below resolve SDS tokens correctly.
2726
+ */
2727
+ function createViewportView(viewSettings) {
2728
+ return function ViewportWithReset() {
2729
+ const plugin = usePlugin();
2730
+ const { theme } = useMolstarTheme(viewSettings);
2731
+ const { cameraChanged, resetCamera } = useCameraReset();
2732
+ const showAxes = useViewSetting(viewSettings, (s) => {
2733
+ var _s$showAxes;
2734
+ return (_s$showAxes = s.showAxes) !== null && _s$showAxes !== void 0 ? _s$showAxes : true;
2735
+ });
2736
+ const download = useViewSetting(viewSettings, (s) => s.download);
2737
+ /**
2738
+ * Disabled while a capture is in flight. A high resolution takes long
2739
+ * enough to click twice through, and each click renders its own pass.
2740
+ */
2741
+ const [downloading, setDownloading] = useState(false);
2742
+ const captureImage = useCallback(_asyncToGenerator(function* () {
2743
+ if (!download) return;
2744
+ setDownloading(true);
2745
+ try {
2746
+ yield downloadStructureImage(plugin, download);
2747
+ } catch (error) {
2748
+ console.error("Failed to download the structure image:", error);
2749
+ } finally {
2750
+ setDownloading(false);
2751
+ }
2752
+ }), [download, plugin]);
2753
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [
2754
+ /* @__PURE__ */ jsx(Viewport, {}),
2755
+ /* @__PURE__ */ jsx("div", {
2756
+ className: "msp-highlight-toast-wrapper",
2757
+ children: /* @__PURE__ */ jsx(Toasts, {})
2758
+ }),
2759
+ /* @__PURE__ */ jsx(ThemeProvider, {
2760
+ theme,
2761
+ children: /* @__PURE__ */ jsxs(ViewportButtonStack, { children: [/* @__PURE__ */ jsx("div", {
2762
+ hidden: !showAxes || !cameraChanged,
2763
+ children: /* @__PURE__ */ jsx(Tooltip, {
2764
+ arrow: true,
2765
+ placement: "right",
2766
+ title: "Reset camera",
2767
+ textAlign: "left",
2768
+ children: /* @__PURE__ */ jsx(Button, {
2769
+ "aria-label": "Reset camera",
2770
+ onClick: resetCamera,
2771
+ sdsStyle: "minimal",
2772
+ sdsType: "secondary",
2773
+ size: "medium",
2774
+ children: /* @__PURE__ */ jsx(ArrowCounterClockwiseIcon, {})
2775
+ })
2776
+ })
2777
+ }), download && /* @__PURE__ */ jsx(Tooltip, {
2778
+ arrow: true,
2779
+ placement: "right",
2780
+ title: "Download image",
2781
+ textAlign: "left",
2782
+ children: /* @__PURE__ */ jsx(Button, {
2783
+ "aria-label": "Download image of the structure",
2784
+ disabled: downloading,
2785
+ onClick: captureImage,
2786
+ sdsStyle: "minimal",
2787
+ sdsType: "secondary",
2788
+ size: "medium",
2789
+ children: /* @__PURE__ */ jsx(ApertureIcon, {})
2790
+ })
2791
+ })] })
2792
+ })
2793
+ ] });
2794
+ };
2795
+ }
2796
+ //#endregion
2797
+ //#region src/core/ProteinStructureViewer/utils/cameraFocus.ts
2798
+ /**
2799
+ * Margin (angstroms) added around a residue's bounding sphere when focusing,
2800
+ * matching Mol*'s default `FocusLoci` extra radius. Used both for the framing
2801
+ * radius that sets the zoom-in distance (floored at `FOCUS_MIN_RADIUS`) and for
2802
+ * the depth-clip anchor, so the focus crop matches Mol*'s default depth slab.
2803
+ */
2804
+ const FOCUS_MIN_RADIUS = 8;
2805
+ const FOCUS_EXTRA_RADIUS = 4;
2806
+ /**
2807
+ * Never let the clip window collapse below this, so the focused residue and its
2808
+ * immediate neighborhood stay visible even at extreme zoom-in.
2809
+ */
2810
+ const MIN_CLIP_RADIUS = 4;
2811
+ /** Camera transition length (ms) when zooming in on a residue. */
2812
+ const FOCUS_DURATION_MS = 250;
2813
+ /** Clip radius has to drift this far before it is worth redrawing. */
2814
+ const CLIP_EPSILON = .5;
2815
+ /**
2816
+ * Depth-clip radius at a given camera distance. The clip scales linearly with
2817
+ * distance, `ratio` being the clip radius per unit distance (fixed at focus so
2818
+ * the clip hugs the residue there), clamped to the scene. This keeps clipping
2819
+ * tied to the zoom:
2820
+ * - at the focus zoom the clip hugs the residue, peeling the structure so the
2821
+ * selected residue reads clearly;
2822
+ * - zooming in shrinks the clip further, peeling deeper toward the residue;
2823
+ * - zooming out grows the clip, revealing more of the structure, up to the
2824
+ * whole scene (`radiusMax`) - the point at which nothing is cropped.
2825
+ */
2826
+ function clipRadiusForDistance(distance, ratio, radiusMax) {
2827
+ return Math.max(MIN_CLIP_RADIUS, Math.min(ratio * distance, radiusMax));
2828
+ }
2829
+ /**
2830
+ * Zooms the camera in on a residue. Uses Mol*'s focus framing for the camera
2831
+ * *position* (so the zoom level matches the built-in focus) but anchors the
2832
+ * clip tightly on the residue itself, and returns the clip-radius-per-distance
2833
+ * ratio used to keep clipping in sync with the zoom afterwards.
2834
+ */
2835
+ function focusResidue(plugin, loci) {
2836
+ var _plugin$canvas3d;
2837
+ const camera = (_plugin$canvas3d = plugin.canvas3d) === null || _plugin$canvas3d === void 0 ? void 0 : _plugin$canvas3d.camera;
2838
+ if (!camera) return null;
2839
+ const sphere = Loci.getBoundingSphere(loci);
2840
+ if (!sphere) return null;
2841
+ const framingRadius = Math.max(sphere.radius + FOCUS_EXTRA_RADIUS, FOCUS_MIN_RADIUS);
2842
+ const snapshot = camera.getFocus(sphere.center, framingRadius);
2843
+ const focusDistance = camera.getTargetDistance(framingRadius);
2844
+ const clipRatio = (sphere.radius + FOCUS_EXTRA_RADIUS) / focusDistance;
2845
+ const radius = clipRadiusForDistance(focusDistance, clipRatio, camera.state.radiusMax);
2846
+ camera.setState(_objectSpread2(_objectSpread2({}, snapshot), {}, { radius }), FOCUS_DURATION_MS);
2847
+ return clipRatio;
2848
+ }
2849
+ /**
2850
+ * Frames the camera on a loci without cropping anything around it.
2851
+ *
2852
+ * The counterpart to `focusResidue` for something meant to be read in context
2853
+ * rather than peeled down to: the camera fits what was selected, and the depth
2854
+ * clip is left open to the whole scene, so the rest of the structure stays on
2855
+ * screen. A selected chain is shown by dimming the chains around it, and they
2856
+ * have to be there to be dimmed.
2857
+ */
2858
+ function frameLoci(plugin, loci) {
2859
+ var _plugin$canvas3d2;
2860
+ const camera = (_plugin$canvas3d2 = plugin.canvas3d) === null || _plugin$canvas3d2 === void 0 ? void 0 : _plugin$canvas3d2.camera;
2861
+ if (!camera) return;
2862
+ const sphere = Loci.getBoundingSphere(loci);
2863
+ if (!sphere) return;
2864
+ const framingRadius = Math.max(sphere.radius + FOCUS_EXTRA_RADIUS, FOCUS_MIN_RADIUS);
2865
+ const snapshot = camera.getFocus(sphere.center, framingRadius);
2866
+ camera.setState(_objectSpread2(_objectSpread2({}, snapshot), {}, { radius: camera.state.radiusMax }), FOCUS_DURATION_MS);
2867
+ }
2868
+ /**
2869
+ * Keeps the depth clip in sync with the zoom while a residue is focused.
2870
+ *
2871
+ * Mol*'s trackball zoom moves the camera without touching the clip radius, so
2872
+ * this recomputes it after each draw: zooming in tightens the clip (peeling
2873
+ * toward the residue), zooming out widens it toward the whole structure. It is
2874
+ * a no-op when `getClipRatio` returns null (nothing focused) and while the
2875
+ * camera is mid-transition, so it does not fight the focus animation.
2876
+ */
2877
+ function syncClipToZoom(plugin, getClipRatio) {
2878
+ var _plugin$canvas3d3;
2879
+ const camera = (_plugin$canvas3d3 = plugin.canvas3d) === null || _plugin$canvas3d3 === void 0 ? void 0 : _plugin$canvas3d3.camera;
2880
+ const clipRatio = getClipRatio();
2881
+ if (!camera || clipRatio === null || camera.transition.inTransition) return;
2882
+ const radius = clipRadiusForDistance(Vec3.distance(camera.state.position, camera.state.target), clipRatio, camera.state.radiusMax);
2883
+ if (Math.abs(camera.state.radius - radius) > CLIP_EPSILON) {
2884
+ var _plugin$canvas3d4;
2885
+ camera.setState({ radius });
2886
+ (_plugin$canvas3d4 = plugin.canvas3d) === null || _plugin$canvas3d4 === void 0 || _plugin$canvas3d4.requestDraw();
2887
+ }
2888
+ }
2889
+ //#endregion
2890
+ //#region src/core/ProteinStructureViewer/utils/chains.ts
2891
+ /**
2892
+ * The polymer of one chain, as named in the file. What each chain's cartoon is
2893
+ * built from, and so what makes a chain a thing Mol* can hide on its own.
2894
+ *
2895
+ * Paired with `chainLigandExpression`: between them they cover everything on a
2896
+ * chain the viewer draws, split by what it draws it as. The polymer
2897
+ * restriction is the one Mol*'s `polymer-cartoon` preset applied, and is what
2898
+ * keeps a heme from being handed to a representation that can only trace a
2899
+ * backbone.
2900
+ */
2901
+ function chainPolymerExpression(chainId) {
2902
+ return MolScriptBuilder.struct.generator.atomGroups({
2903
+ "chain-test": MolScriptBuilder.core.rel.eq([MolScriptBuilder.ammp("auth_asym_id"), chainId]),
2904
+ "entity-test": MolScriptBuilder.core.rel.eq([MolScriptBuilder.ammp("entityType"), "polymer"])
2905
+ });
2906
+ }
2907
+ /**
2908
+ * Bonds worth following out of a ligand: the ones holding it to the protein.
2909
+ *
2910
+ * Mol*'s own pair, and metallic coordination is the half that matters most -
2911
+ * a heme's iron is held to its histidine by a coordination bond and not a
2912
+ * covalent one, so covalent alone would leave every metalloprotein's cofactor
2913
+ * looking dropped in rather than bound.
2914
+ */
2915
+ const CONNECTING_BOND = MolScriptBuilder.core.flags.hasAny([MolScriptBuilder.struct.bondProperty.flags(), MolScriptBuilder.core.type.bitflags([BondType.fromNames(["covalent", "metal-coordination"])])]);
2916
+ /**
2917
+ * The heteroatoms of one chain - ligands, ions, glycans, lipids - along with
2918
+ * the residues holding them, which is what its ball-and-stick is built from.
2919
+ *
2920
+ * `non-polymer` is the one entity type a PDB's HETATM records land under,
2921
+ * ligands and ions alike, so there is nothing finer to test here: the
2922
+ * distinction Mol*'s presets draw between their `ligand`, `ion` and `lipid`
2923
+ * components is a residue-name lookup made to give each a slightly different
2924
+ * style, and all three are sticks. `branched` is the separate type glycans
2925
+ * arrive as.
2926
+ *
2927
+ * Water is the third type and is left out of the seed. Every solvent molecule
2928
+ * drawn as sticks buries the structure they surround, which is why Mol* draws
2929
+ * them at 60% alpha rather than plain, and none of them is what "show the
2930
+ * ligands" asks for.
2931
+ *
2932
+ * One layer of bonds out from there, taken as whole residues, is what brings
2933
+ * the binding residue along - myoglobin's His93, say. Without it the heme
2934
+ * floats unattached in the middle of a cartoon it is visibly bonded to, and
2935
+ * the bond drawn to its iron ends in mid-air. One layer and no more: the
2936
+ * residue that holds the ligand, not that residue's own neighbours.
2937
+ *
2938
+ * Intersected back with the chain, so everything a chain is drawn with belongs
2939
+ * to that chain. A ligand bonded across an interface would otherwise leave the
2940
+ * partner chain's residue in this chain's component, somewhere hiding the
2941
+ * partner chain could not reach.
2942
+ */
2943
+ function chainLigandExpression(chainId) {
2944
+ const onThisChain = MolScriptBuilder.core.rel.eq([MolScriptBuilder.ammp("auth_asym_id"), chainId]);
2945
+ return MolScriptBuilder.struct.modifier.union([MolScriptBuilder.struct.modifier.intersectBy({
2946
+ 0: MolScriptBuilder.struct.modifier.includeConnected({
2947
+ 0: MolScriptBuilder.struct.generator.atomGroups({
2948
+ "chain-test": onThisChain,
2949
+ "entity-test": MolScriptBuilder.core.set.has([MolScriptBuilder.set("non-polymer", "branched"), MolScriptBuilder.ammp("entityType")])
2950
+ }),
2951
+ "as-whole-residues": true,
2952
+ "bond-test": CONNECTING_BOND,
2953
+ "layer-count": 1
2954
+ }),
2955
+ by: MolScriptBuilder.struct.generator.atomGroups({ "chain-test": onThisChain })
2956
+ })]);
2957
+ }
2958
+ /**
2959
+ * Matches how the sequence panel captions its chains, which reaches the same
2960
+ * label through Mol*'s own `getChainOptions`. Deriving it the same way is what
2961
+ * keeps a chain from going by one name in the legend and another in the panel.
2962
+ */
2963
+ const CHAIN_LABEL_OPTIONS = {
2964
+ granularity: "chain",
2965
+ hidePrefix: true,
2966
+ htmlStyling: false
2967
+ };
2968
+ /**
2969
+ * Reads the chains of a structure and the polymer residues on each.
2970
+ *
2971
+ * Residue indices are Mol*'s residue keys, counting residues in file order
2972
+ * across the whole structure, so what is reported here addresses the same
2973
+ * residues as `plddt`, `residueOverlay` and `selection`.
2974
+ *
2975
+ * Heteroatoms are drawn (see `chainLigandExpression`) but are not counted
2976
+ * here. A heme is a residue to the file and not to a reader: it is no part of
2977
+ * the sequence the panel lists, and averaging a confidence score over it would
2978
+ * divide by a residue that has none.
2979
+ *
2980
+ * Residues are gathered into a set rather than inferred from the ends: a chain
2981
+ * carrying several symmetry operators repeats each of its residues once per
2982
+ * operator, and a structure whose chains interleave leaves a chain's indices
2983
+ * non-contiguous. Neither is what a predicted complex looks like, but a range
2984
+ * would misread both.
2985
+ */
2986
+ function scanChains(structure) {
2987
+ const accumulators = /* @__PURE__ */ new Map();
2988
+ const location = StructureElement.Location.create(structure);
2989
+ for (const unit of structure.units) {
2990
+ location.unit = unit;
2991
+ for (let i = 0; i < unit.elements.length; i++) {
2992
+ location.element = unit.elements[i];
2993
+ const chainId = StructureProperties.chain.auth_asym_id(location);
2994
+ let chain = accumulators.get(chainId);
2995
+ if (!chain) {
2996
+ chain = {
2997
+ chainId,
2998
+ label: elementLabel(location, CHAIN_LABEL_OPTIONS),
2999
+ residues: /* @__PURE__ */ new Set()
3000
+ };
3001
+ accumulators.set(chainId, chain);
3002
+ }
3003
+ if (StructureProperties.entity.type(location) !== "polymer") continue;
3004
+ chain.residues.add(StructureProperties.residue.key(location));
3005
+ }
3006
+ }
3007
+ const ordered = [...accumulators.values()].filter((chain) => chain.residues.size > 0).map((chain) => _objectSpread2(_objectSpread2({}, chain), {}, { residues: [...chain.residues].sort((a, b) => a - b) })).sort((a, b) => {
3008
+ var _a$residues$, _b$residues$;
3009
+ return ((_a$residues$ = a.residues[0]) !== null && _a$residues$ !== void 0 ? _a$residues$ : 0) - ((_b$residues$ = b.residues[0]) !== null && _b$residues$ !== void 0 ? _b$residues$ : 0);
3010
+ });
3011
+ return {
3012
+ chainLabels: new Map([...accumulators.values()].map(({ chainId, label }) => [chainId, label])),
3013
+ chains: ordered.map(({ chainId, label, residues }) => {
3014
+ var _residues, _residues$;
3015
+ return {
3016
+ chainId,
3017
+ endIndex: (_residues = residues[residues.length - 1]) !== null && _residues !== void 0 ? _residues : 0,
3018
+ label,
3019
+ residueCount: residues.length,
3020
+ startIndex: (_residues$ = residues[0]) !== null && _residues$ !== void 0 ? _residues$ : 0
3021
+ };
3022
+ }),
3023
+ residuesByChain: new Map(ordered.map(({ chainId, residues }) => [chainId, residues]))
3024
+ };
3025
+ }
3026
+ /** True when the two lists name the same chains, in the same order. */
3027
+ function chainsEqual(a, b) {
3028
+ return a.length === b.length && a.every((chain, i) => {
3029
+ const other = b[i];
3030
+ return other !== void 0 && chain.chainId === other.chainId && chain.startIndex === other.startIndex && chain.endIndex === other.endIndex && chain.residueCount === other.residueCount;
3031
+ });
3032
+ }
3033
+ //#endregion
3034
+ //#region src/core/ProteinStructureViewer/utils/molstarSpec.ts
3035
+ /**
3036
+ * The spec's list-valued keys. These are appended rather than merged: Mol*
3037
+ * reads them as collections, so a consumer's entries join the viewer's instead
3038
+ * of replacing them.
3039
+ *
3040
+ * `config` is the one where order carries meaning - Mol* folds the list into a
3041
+ * Map in order, so a later entry overwrites an earlier one, and appending is
3042
+ * what lets a consumer override a setting the viewer chose.
3043
+ */
3044
+ const LIST_KEYS = [
3045
+ "actions",
3046
+ "animations",
3047
+ "behaviors",
3048
+ "config",
3049
+ "customFormats",
3050
+ "customParamEditors"
3051
+ ];
3052
+ /**
3053
+ * Whether a value should be merged into rather than replaced.
3054
+ *
3055
+ * Only object literals qualify. Arrays are collections, and the spec is full
3056
+ * of React components and Mol* class instances, all of which are values in
3057
+ * their own right - merging into one would take it apart.
3058
+ */
3059
+ function isPlainObject(value) {
3060
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
3061
+ const proto = Object.getPrototypeOf(value);
3062
+ return proto === Object.prototype || proto === null;
3063
+ }
3064
+ function deepMerge(base, override) {
3065
+ if (!isPlainObject(base) || !isPlainObject(override)) return override;
3066
+ const merged = _objectSpread2({}, base);
3067
+ for (const [key, value] of Object.entries(override)) merged[key] = key in base ? deepMerge(base[key], value) : value;
3068
+ return merged;
3069
+ }
3070
+ function withoutLists(spec) {
3071
+ const rest = _objectSpread2({}, spec);
3072
+ for (const key of LIST_KEYS) delete rest[key];
3073
+ return rest;
3074
+ }
3075
+ /**
3076
+ * Lays a consumer's Mol* spec over the viewer's own.
3077
+ *
3078
+ * The viewer builds a spec of its own - the sequence panel and viewport it
3079
+ * renders, the controls it hides, the behaviors it drops - and this is how a
3080
+ * consumer reaches the rest of Mol* without the viewer having to grow a prop
3081
+ * per setting. Anything the consumer names wins, so `canvas3d.renderer` or a
3082
+ * `PluginConfig` item can be set to something other than the default the
3083
+ * viewer picked.
3084
+ *
3085
+ * The one thing it cannot do is take something away: `behaviors` is appended
3086
+ * to, so a behavior the viewer removed - Mol*'s click-to-zoom camera - stays
3087
+ * removed, and one the viewer kept cannot be dropped.
3088
+ */
3089
+ function mergeMolstarSpec(base, override) {
3090
+ if (!override) return base;
3091
+ const merged = deepMerge(withoutLists(base), withoutLists(override));
3092
+ for (const key of LIST_KEYS) {
3093
+ var _base, _override;
3094
+ const ours = (_base = base[key]) !== null && _base !== void 0 ? _base : [];
3095
+ const theirs = (_override = override[key]) !== null && _override !== void 0 ? _override : [];
3096
+ if (ours.length > 0 || theirs.length > 0) merged[key] = [...ours, ...theirs];
3097
+ }
3098
+ return merged;
3099
+ }
3100
+ //#endregion
3101
+ //#region src/core/ProteinStructureViewer/utils/structureFormat.ts
3102
+ /** How much of the file to inspect when guessing the format. */
3103
+ const DETECT_SAMPLE = 16384;
3104
+ /**
3105
+ * Infers whether `text` is PDB or mmCIF (PDBx).
3106
+ *
3107
+ * mmCIF documents start with a `data_` block and name their coordinates
3108
+ * `_atom_site.`. PDB never does either, so either marker is enough. A leading
3109
+ * comment (`# ...`) before `data_` is still mmCIF.
3110
+ */
3111
+ function detectStructureFormat(text) {
3112
+ const sample = text.slice(0, DETECT_SAMPLE);
3113
+ if (/(?:^|\n)\s*data_/.test(sample) || /_atom_site\./.test(sample)) return "mmcif";
3114
+ return "pdb";
3115
+ }
3116
+ //#endregion
3117
+ //#region src/core/ProteinStructureViewer/utils/chainColorTheme.ts
3118
+ /** Mol* color theme name under which per-chain coloring is registered. */
3119
+ const CHAIN_COLOR_THEME_NAME = "chain-color";
3120
+ /** Painted for a chain with no color assigned, or one assigned a bad value. */
3121
+ const DEFAULT_CHAIN_COLOR_HEX = "#808080";
3122
+ const DEFAULT_CHAIN_COLOR = Color.fromRgb(128, 128, 128);
3123
+ /**
3124
+ * Builds a Mol* color theme that paints each chain its own color.
3125
+ *
3126
+ * This stands in for Mol*'s built-in `chain-id` theme, which picks its own
3127
+ * colors from a palette we cannot read back. Owning the assignment is what
3128
+ * lets the chain legend show a swatch that matches the structure, rather than
3129
+ * a key for colors it has to guess at.
3130
+ *
3131
+ * Created per plugin instance, and its state read live inside `color()`, for
3132
+ * the same reasons as the residue value theme beside it: several viewers can
3133
+ * color chains differently on one page, and recoloring does not rebuild the
3134
+ * structure.
3135
+ */
3136
+ function createChainColorTheme() {
3137
+ const state = {
3138
+ colors: /* @__PURE__ */ new Map(),
3139
+ version: 0
3140
+ };
3141
+ const provider = {
3142
+ category: "chain property",
3143
+ defaultValues: {},
3144
+ factory() {
3145
+ const { colors } = state;
3146
+ const parsed = /* @__PURE__ */ new Map();
3147
+ for (const [chainId, hex] of colors) parsed.set(chainId, themeColor(hex, DEFAULT_CHAIN_COLOR_HEX));
3148
+ return {
3149
+ color(location) {
3150
+ var _parsed$get;
3151
+ if (!StructureElement.Location.is(location)) return DEFAULT_CHAIN_COLOR;
3152
+ const chainId = StructureProperties.chain.auth_asym_id(location);
3153
+ return (_parsed$get = parsed.get(chainId)) !== null && _parsed$get !== void 0 ? _parsed$get : DEFAULT_CHAIN_COLOR;
3154
+ },
3155
+ contextHash: state.version,
3156
+ description: "Color residues by the chain they sit on",
3157
+ factory: provider.factory,
3158
+ granularity: "group",
3159
+ props: {}
3160
+ };
3161
+ },
3162
+ getParams: () => ({}),
3163
+ isApplicable: () => true,
3164
+ label: "Chain Color",
3165
+ name: CHAIN_COLOR_THEME_NAME
3166
+ };
3167
+ return {
3168
+ provider,
3169
+ setState(colors) {
3170
+ state.colors = colors;
3171
+ state.version++;
3172
+ }
3173
+ };
3174
+ }
3175
+ //#endregion
3176
+ //#region src/core/ProteinStructureViewer/utils/plddt.ts
3177
+ /** Mol* color theme name under which pLDDT coloring is registered. */
3178
+ const PLDDT_THEME_NAME = "plddt-bfactor";
3179
+ /**
3180
+ * AlphaFold's pLDDT confidence bands. Thresholds are on the 0-1 scale that
3181
+ * `plddt` values use, ascending from lowest to highest confidence.
3182
+ */
3183
+ const PLDDT_COLOR_SCALE = {
3184
+ kind: "stepped",
3185
+ stops: [
3186
+ {
3187
+ color: "#FF7C45",
3188
+ label: "0.5",
3189
+ threshold: .5
3190
+ },
3191
+ {
3192
+ color: "#FFDB11",
3193
+ label: "0.7",
3194
+ threshold: .7
3195
+ },
3196
+ {
3197
+ color: "#64CBF3",
3198
+ label: "0.9",
3199
+ threshold: .9
3200
+ },
3201
+ {
3202
+ color: "#0053D5",
3203
+ label: "1.0",
3204
+ threshold: 1
3205
+ }
3206
+ ]
3207
+ };
3208
+ const PLDDT_BANDS = PLDDT_COLOR_SCALE.kind === "stepped" ? PLDDT_COLOR_SCALE.stops : [];
3209
+ /**
3210
+ * The band colors alone, ascending from least to most confident.
3211
+ *
3212
+ * What the chain legend shows in place of a single color while pLDDT is
3213
+ * painting the structure: no one color stands for a chain then, so the swatch
3214
+ * carries the whole key instead.
3215
+ */
3216
+ const PLDDT_BAND_COLORS = PLDDT_BANDS.map((stop) => stop.color);
3217
+ const DEFAULT_PLDDT_COLOR = Color.fromRgb(128, 128, 128);
3218
+ /**
3219
+ * Maps a pLDDT confidence score on the 0-100 B-factor scale to its band color.
3220
+ * `PLDDT_COLOR_SCALE` thresholds are on the 0-1 scale, so the score is
3221
+ * normalized before it is sampled.
3222
+ */
3223
+ function plddtToColor(value) {
3224
+ const [r, g, b] = sampleSteppedScale(PLDDT_BANDS, value / 100);
3225
+ return Color.fromRgb(r, g, b);
3226
+ }
3227
+ /**
3228
+ * Rewrites a PDB file's B-factor column with pLDDT scores so Mol* can read them
3229
+ * off the parsed model. B-factors occupy columns 60-66 of ATOM/HETATM lines;
3230
+ * scores arrive on a 0-1 scale and are stored on the conventional 0-100 one.
3231
+ * Residues past the end of `plddtValues` fall back to a mid-confidence 50.
3232
+ *
3233
+ * A residue is identified by chain, sequence number and insertion code. The
3234
+ * code has to be part of that: `10` and `10A` are two residues, Mol* counts
3235
+ * them as two, and treating them as one here would hand every residue after
3236
+ * them its neighbour's score.
3237
+ */
3238
+ function injectPlddtIntoPdb(pdbData, plddtValues) {
3239
+ const lines = pdbData.split("\n");
3240
+ let residueIndex = -1;
3241
+ let lastResidue = "";
3242
+ return lines.map((line) => {
3243
+ var _plddtValues$residueI;
3244
+ if (!line.startsWith("ATOM") && !line.startsWith("HETATM")) return line;
3245
+ const residue = line.substring(21, 27);
3246
+ if (residue !== lastResidue) {
3247
+ residueIndex++;
3248
+ lastResidue = residue;
3249
+ }
3250
+ const bfactorStr = (residueIndex < plddtValues.length ? ((_plddtValues$residueI = plddtValues[residueIndex]) !== null && _plddtValues$residueI !== void 0 ? _plddtValues$residueI : 0) * 100 : 50).toFixed(2).padStart(6, " ");
3251
+ const paddedLine = line.padEnd(66, " ");
3252
+ return paddedLine.substring(0, 60) + bfactorStr + paddedLine.substring(66);
3253
+ }).join("\n");
3254
+ }
3255
+ const ATOM_SITE_PREFIX = "_atom_site.";
3256
+ const B_FACTOR_COLUMN = "B_iso_or_equiv";
3257
+ function skipCifWhitespace(line, index) {
3258
+ let i = index;
3259
+ while (i < line.length && /\s/.test(line.charAt(i))) i += 1;
3260
+ return i;
3261
+ }
3262
+ function readCifToken(line, start) {
3263
+ const quote = line.charAt(start);
3264
+ if (quote === "'" || quote === "\"") {
3265
+ const end = line.indexOf(quote, start + 1);
3266
+ if (end < 0) return {
3267
+ next: line.length,
3268
+ token: line.slice(start + 1)
3269
+ };
3270
+ return {
3271
+ next: end + 1,
3272
+ token: line.slice(start + 1, end)
3273
+ };
3274
+ }
3275
+ let i = start;
3276
+ while (i < line.length && !/\s/.test(line.charAt(i))) i += 1;
3277
+ return {
3278
+ next: i,
3279
+ token: line.slice(start, i)
3280
+ };
3281
+ }
3282
+ /**
3283
+ * Splits one CIF line into tokens, honouring `'quoted'` and `"quoted"` values.
3284
+ * Atom-site rows are one line each in practice; multiline `;text;` fields are
3285
+ * not used there and are not handled.
3286
+ */
3287
+ function tokenizeCifLine(line) {
3288
+ const tokens = [];
3289
+ let i = skipCifWhitespace(line, 0);
3290
+ while (i < line.length) {
3291
+ const { next, token } = readCifToken(line, i);
3292
+ tokens.push(token);
3293
+ i = skipCifWhitespace(line, next);
3294
+ }
3295
+ return tokens;
3296
+ }
3297
+ function isCifNull(value) {
3298
+ return value === void 0 || value === "." || value === "?";
3299
+ }
3300
+ function columnIndex(columns, name) {
3301
+ return columns.indexOf(name);
3302
+ }
3303
+ /**
3304
+ * Residue identity matching `injectPlddtIntoPdb`: chain + sequence number +
3305
+ * insertion code. Prefers the `auth_*` columns Mol* reports on the parsed
3306
+ * model, falling back to `label_*` when a file omitted them. `.` / `?`
3307
+ * insertion codes count as empty, the way a blank PDB column 27 does.
3308
+ */
3309
+ function mmcifResidueKey(tokens, columns) {
3310
+ var _ref, _ref2, _ref3, _ref4;
3311
+ const authAsym = columnIndex(columns, "auth_asym_id");
3312
+ const labelAsym = columnIndex(columns, "label_asym_id");
3313
+ const authSeq = columnIndex(columns, "auth_seq_id");
3314
+ const labelSeq = columnIndex(columns, "label_seq_id");
3315
+ const ins = columnIndex(columns, "pdbx_PDB_ins_code");
3316
+ return `${(_ref = (_ref2 = authAsym >= 0 ? tokens[authAsym] : void 0) !== null && _ref2 !== void 0 ? _ref2 : labelAsym >= 0 ? tokens[labelAsym] : void 0) !== null && _ref !== void 0 ? _ref : ""}|${(_ref3 = (_ref4 = authSeq >= 0 ? tokens[authSeq] : void 0) !== null && _ref4 !== void 0 ? _ref4 : labelSeq >= 0 ? tokens[labelSeq] : void 0) !== null && _ref3 !== void 0 ? _ref3 : ""}|${isCifNull(ins >= 0 ? tokens[ins] : void 0) ? "" : tokens[ins]}`;
3317
+ }
3318
+ function isAtomSiteRow(tokens, columns) {
3319
+ const group = columnIndex(columns, "group_PDB");
3320
+ if (group < 0) return true;
3321
+ const value = tokens[group];
3322
+ return value === "ATOM" || value === "HETATM";
3323
+ }
3324
+ function plddtBFactor(residueIndex, plddtValues) {
3325
+ var _plddtValues$residueI2;
3326
+ return (residueIndex < plddtValues.length ? ((_plddtValues$residueI2 = plddtValues[residueIndex]) !== null && _plddtValues$residueI2 !== void 0 ? _plddtValues$residueI2 : 0) * 100 : 50).toFixed(2);
3327
+ }
3328
+ function isLoopStart(line) {
3329
+ return line.trim() === "loop_" || line.trim().startsWith("loop_");
3330
+ }
3331
+ function isAtomSiteColumn(line) {
3332
+ return line.trim().startsWith(ATOM_SITE_PREFIX);
3333
+ }
3334
+ function endsAtomSiteLoop(line) {
3335
+ const trimmed = line.trim();
3336
+ if (trimmed === "") return false;
3337
+ if (trimmed.startsWith("#")) return true;
3338
+ if (isLoopStart(trimmed)) return true;
3339
+ if (trimmed.startsWith("data_") || trimmed.startsWith("save_")) return true;
3340
+ return trimmed.startsWith("_") && !trimmed.startsWith(ATOM_SITE_PREFIX);
3341
+ }
3342
+ function isAtomSiteLoop(lines, loopIndex) {
3343
+ let peek = loopIndex + 1;
3344
+ while (peek < lines.length && lines[peek].trim() === "") peek += 1;
3345
+ return peek < lines.length && isAtomSiteColumn(lines[peek]);
3346
+ }
3347
+ function ensureBFactorColumn(columns, headerLines) {
3348
+ const existing = columnIndex(columns, B_FACTOR_COLUMN);
3349
+ if (existing >= 0) return existing;
3350
+ columns.push(B_FACTOR_COLUMN);
3351
+ headerLines.push(`${ATOM_SITE_PREFIX}${B_FACTOR_COLUMN}`);
3352
+ return columns.length - 1;
3353
+ }
3354
+ function rewriteAtomSiteRow(dataLine, columns, bIndex, plddtValues, walk) {
3355
+ if (dataLine.trim() === "") return dataLine;
3356
+ const tokens = tokenizeCifLine(dataLine);
3357
+ if (tokens.length === 0) return dataLine;
3358
+ while (tokens.length < columns.length) tokens.push(".");
3359
+ if (isAtomSiteRow(tokens, columns)) {
3360
+ const residue = mmcifResidueKey(tokens, columns);
3361
+ if (residue !== walk.lastResidue) {
3362
+ walk.residueIndex += 1;
3363
+ walk.lastResidue = residue;
3364
+ }
3365
+ tokens[bIndex] = plddtBFactor(walk.residueIndex, plddtValues);
3366
+ }
3367
+ return tokens.join(" ");
3368
+ }
3369
+ function rewriteAtomSiteLoop(lines, loopIndex, plddtValues, walk) {
3370
+ const rows = [lines[loopIndex]];
3371
+ let i = loopIndex + 1;
3372
+ const columns = [];
3373
+ while (i < lines.length && isAtomSiteColumn(lines[i])) {
3374
+ columns.push(lines[i].trim().slice(11));
3375
+ rows.push(lines[i]);
3376
+ i += 1;
3377
+ }
3378
+ const bIndex = ensureBFactorColumn(columns, rows);
3379
+ while (i < lines.length && !endsAtomSiteLoop(lines[i])) {
3380
+ rows.push(rewriteAtomSiteRow(lines[i], columns, bIndex, plddtValues, walk));
3381
+ i += 1;
3382
+ }
3383
+ return {
3384
+ next: i,
3385
+ rows
3386
+ };
3387
+ }
3388
+ /**
3389
+ * Rewrites an mmCIF (PDBx) file's `_atom_site.B_iso_or_equiv` column with
3390
+ * pLDDT scores so Mol* can read them off the parsed model, the same way
3391
+ * `injectPlddtIntoPdb` rewrites the PDB B-factor column. Scores arrive on a
3392
+ * 0-1 scale and are stored on the conventional 0-100 one. Residues past the
3393
+ * end of `plddtValues` fall back to a mid-confidence 50.
3394
+ *
3395
+ * If the file has no B-factor column, one is appended to the atom-site loop
3396
+ * rather than leaving the scores behind.
3397
+ */
3398
+ function injectPlddtIntoMmcif(mmcifData, plddtValues) {
3399
+ const lines = mmcifData.split("\n");
3400
+ const result = [];
3401
+ const walk = {
3402
+ lastResidue: "",
3403
+ residueIndex: -1
3404
+ };
3405
+ let i = 0;
3406
+ let rewrittenLoop = false;
3407
+ while (i < lines.length) {
3408
+ const line = lines[i];
3409
+ if (!rewrittenLoop && isLoopStart(line) && isAtomSiteLoop(lines, i)) {
3410
+ const rewritten = rewriteAtomSiteLoop(lines, i, plddtValues, walk);
3411
+ result.push(...rewritten.rows);
3412
+ i = rewritten.next;
3413
+ rewrittenLoop = true;
3414
+ continue;
3415
+ }
3416
+ result.push(line);
3417
+ i += 1;
3418
+ }
3419
+ return result.join("\n");
3420
+ }
3421
+ /**
3422
+ * Rewrites a structure file's B-factors with pLDDT scores. Dispatches to
3423
+ * `injectPlddtIntoPdb` or `injectPlddtIntoMmcif` from `format`, or from
3424
+ * detecting the format of `data` when `format` is omitted.
3425
+ */
3426
+ function injectPlddt(data, plddtValues, format = detectStructureFormat(data)) {
3427
+ return format === "mmcif" ? injectPlddtIntoMmcif(data, plddtValues) : injectPlddtIntoPdb(data, plddtValues);
3428
+ }
3429
+ /**
3430
+ * Mol* color theme that reads pLDDT scores out of the B-factor column, paired
3431
+ * with `injectPlddt`. Registered per plugin instance.
3432
+ */
3433
+ const PlddtColoring = CustomElementProperty.create({
3434
+ coloring: {
3435
+ defaultColor: DEFAULT_PLDDT_COLOR,
3436
+ getColor(e) {
3437
+ return plddtToColor(e);
3438
+ }
3439
+ },
3440
+ getData(model) {
3441
+ const map = /* @__PURE__ */ new Map();
3442
+ const atomCount = model.atomicHierarchy.atoms._rowCount;
3443
+ for (let i = 0; i < atomCount; i++) map.set(i, model.atomicConformation.B_iso_or_equiv.value(i));
3444
+ return { value: map };
3445
+ },
3446
+ label: "pLDDT",
3447
+ name: PLDDT_THEME_NAME
3448
+ });
3449
+ //#endregion
3450
+ //#region src/core/ProteinStructureViewer/utils/residueValueTheme.ts
3451
+ /** Mol* color theme name under which residue value overlays are registered. */
3452
+ const RESIDUE_VALUE_THEME_NAME = "residue-value";
3453
+ /**
3454
+ * Builds a Mol* color theme that paints residues by an arbitrary per-residue
3455
+ * value.
3456
+ *
3457
+ * The theme is created per plugin instance rather than shared at module scope,
3458
+ * so several viewers can render different overlays on the same page. Its state
3459
+ * lives in the closure below and is read live inside `color()`, which is what
3460
+ * lets an overlay update recolor the structure without rebuilding it.
3461
+ */
3462
+ function createResidueValueTheme(mode) {
3463
+ const state = {
3464
+ colorScale: PLASMA_COLOR_SCALE,
3465
+ max: 1,
3466
+ min: 0,
3467
+ mode,
3468
+ values: /* @__PURE__ */ new Map(),
3469
+ version: 0
3470
+ };
3471
+ const provider = {
3472
+ category: "residue property",
3473
+ defaultValues: {},
3474
+ factory() {
3475
+ const { colorScale, max, min, mode: currentMode, values } = state;
3476
+ const neutral = neutralResidueColor(currentMode);
3477
+ return {
3478
+ color(location) {
3479
+ if (!StructureElement.Location.is(location)) return neutral;
3480
+ const value = values.get(StructureProperties.residue.key(location));
3481
+ if (value === void 0) return neutral;
3482
+ const rgb = sampleColorScale(colorScale, value, max, min);
3483
+ return rgb ? Color.fromRgb(rgb[0], rgb[1], rgb[2]) : neutral;
3484
+ },
3485
+ contextHash: state.version,
3486
+ description: "Color residues by a per-residue value",
3487
+ factory: provider.factory,
3488
+ granularity: "group",
3489
+ props: {}
3490
+ };
3491
+ },
3492
+ getParams: () => ({}),
3493
+ isApplicable: () => true,
3494
+ label: "Residue Value",
3495
+ name: RESIDUE_VALUE_THEME_NAME
3496
+ };
3497
+ return {
3498
+ provider,
3499
+ setState(next) {
3500
+ Object.assign(state, next);
3501
+ state.version++;
3502
+ }
3503
+ };
3504
+ }
3505
+ //#endregion
3506
+ //#region src/core/ProteinStructureViewer/hooks/useMolstarPlugin.ts
3507
+ /**
3508
+ * Theme used when neither pLDDT scores nor an overlay are supplied. Our own
3509
+ * per-chain theme rather than Mol*'s built-in `chain-id`, so the chain legend
3510
+ * can show swatches that match the structure instead of guessing at the colors
3511
+ * Mol* picked.
3512
+ */
3513
+ const FALLBACK_THEME_NAME = CHAIN_COLOR_THEME_NAME;
3514
+ /** Delay before retrying initialization while the container has no size. */
3515
+ const LAYOUT_RETRY_MS = 100;
3516
+ /** How long to wait for a frame before starting without one. */
3517
+ const FRAME_WAIT_MS = 100;
3518
+ /**
3519
+ * Yield once so the container can be laid out before it is measured.
3520
+ *
3521
+ * `requestAnimationFrame` does not fire while the document is hidden -- a
3522
+ * background tab, a collapsed pane, or a headless capture that never paints --
3523
+ * and awaiting it alone leaves the viewer parked forever on a page that has in
3524
+ * fact been laid out. Racing it against a timeout keeps the fast path on a
3525
+ * visible page and still starts on a hidden one, where the size check below is
3526
+ * what actually guards against measuring too early.
3527
+ *
3528
+ * The loser of the race is cancelled rather than left to fire: on a visible
3529
+ * page this runs once per viewer, and a grid of them would otherwise each keep
3530
+ * a stray timer alive past the frame that already resolved.
3531
+ */
3532
+ function nextFrame() {
3533
+ return new Promise((resolve) => {
3534
+ const done = () => {
3535
+ cancelAnimationFrame(frame);
3536
+ clearTimeout(timer);
3537
+ resolve();
3538
+ };
3539
+ const frame = requestAnimationFrame(done);
3540
+ const timer = setTimeout(done, FRAME_WAIT_MS);
3541
+ });
3542
+ }
3543
+ /**
3544
+ * Hover fills the geometry with a tint; selection stays outline-only. Mol*'s
3545
+ * `colorMarker` is a global toggle for the per-fragment marker tint, so it is
3546
+ * scoped to hover via the per-state strengths below.
3547
+ */
3548
+ const HIGHLIGHT_STRENGTH = .2;
3549
+ const SELECT_STRENGTH = 0;
3550
+ /**
3551
+ * Turns the screenshot controls off, on the versions of Mol* that have them.
3552
+ *
3553
+ * `ShowScreenshotControls` arrived in Mol* 5 and this package's peer range
3554
+ * reaches back to 4, so the key is read through an index rather than named
3555
+ * directly: naming it would not compile against 4, and passing the resulting
3556
+ * `undefined` would ask Mol* to set a config item it has no name for. On 4
3557
+ * there are no screenshot controls to hide in the first place.
3558
+ */
3559
+ const SCREENSHOT_CONTROLS_CONFIG = (() => {
3560
+ const item = PluginConfig.Viewport.ShowScreenshotControls;
3561
+ return item ? [[item, false]] : [];
3562
+ })();
3563
+ function setAxes(plugin, enabled) {
3564
+ if (!plugin.canvas3d) return;
3565
+ try {
3566
+ plugin.canvas3d.setProps({ camera: { helper: { axes: enabled ? AXES_ON : AXES_OFF } } });
3567
+ } catch (e) {
3568
+ console.warn("Could not set axes:", e);
3569
+ }
3570
+ }
3571
+ function createViewer(_x) {
3572
+ return _createViewer.apply(this, arguments);
3573
+ }
3574
+ function _createViewer() {
3575
+ _createViewer = _asyncToGenerator(function* ({ backgroundColor, chainColorTheme, edgeColor, highlightColor, molstarSpec, residueValueTheme, root, showAxes, showSequenceViewer, viewSettings }) {
3576
+ var _spec$config;
3577
+ const spec = DefaultPluginUISpec();
3578
+ const behaviors = spec.behaviors.filter((b) => b.transformer !== PluginBehaviors.Camera.FocusLoci);
3579
+ const plugin = yield createPluginUI({
3580
+ render: renderReact18,
3581
+ spec: mergeMolstarSpec(_objectSpread2(_objectSpread2({}, spec), {}, {
3582
+ behaviors,
3583
+ canvas3d: {
3584
+ camera: { helper: { axes: showAxes ? AXES_ON : AXES_OFF } },
3585
+ marking: {
3586
+ highlightEdgeColor: edgeColor,
3587
+ selectEdgeColor: edgeColor
3588
+ },
3589
+ renderer: {
3590
+ backgroundColor,
3591
+ colorMarker: true,
3592
+ highlightColor,
3593
+ highlightStrength: HIGHLIGHT_STRENGTH,
3594
+ selectStrength: SELECT_STRENGTH
3595
+ }
3596
+ },
3597
+ components: {
3598
+ controls: {
3599
+ bottom: "none",
3600
+ left: "none",
3601
+ right: "none"
3602
+ },
3603
+ remoteState: "none",
3604
+ sequenceViewer: { view: createSequenceView(viewSettings) },
3605
+ viewport: { view: createViewportView(viewSettings) }
3606
+ },
3607
+ config: [
3608
+ ...(_spec$config = spec.config) !== null && _spec$config !== void 0 ? _spec$config : [],
3609
+ [PluginConfig.Viewport.ShowExpand, false],
3610
+ [PluginConfig.Viewport.ShowControls, false],
3611
+ [PluginConfig.Viewport.ShowSettings, false],
3612
+ [PluginConfig.Viewport.ShowSelectionMode, false],
3613
+ [PluginConfig.Viewport.ShowAnimation, false],
3614
+ [PluginConfig.Viewport.ShowTrajectoryControls, false],
3615
+ ...SCREENSHOT_CONTROLS_CONFIG
3616
+ ],
3617
+ layout: { initial: {
3618
+ controlsDisplay: "reactive",
3619
+ isExpanded: false,
3620
+ regionState: {
3621
+ bottom: "hidden",
3622
+ left: "hidden",
3623
+ right: "hidden",
3624
+ top: showSequenceViewer ? "full" : "hidden"
3625
+ }
3626
+ } }
3627
+ }), molstarSpec),
3628
+ target: root
3629
+ });
3630
+ const registry = plugin.representation.structure.themes.colorThemeRegistry;
3631
+ if (PlddtColoring.colorThemeProvider) registry.add(PlddtColoring.colorThemeProvider);
3632
+ registry.add(residueValueTheme.provider);
3633
+ registry.add(chainColorTheme.provider);
3634
+ for (const p of [...plugin.managers.lociLabels.providers]) plugin.managers.lociLabels.removeProvider(p);
3635
+ plugin.managers.structure.focus.behaviors.current.subscribe((entry) => {
3636
+ const select = plugin.managers.interactivity.lociSelects;
3637
+ if (entry === null || entry === void 0 ? void 0 : entry.loci) select.selectOnly({ loci: entry.loci });
3638
+ else select.deselectAll();
3639
+ });
3640
+ return plugin;
3641
+ });
3642
+ return _createViewer.apply(this, arguments);
3643
+ }
3644
+ /**
3645
+ * The representation parameters Mol*'s own presets compute, read from the same
3646
+ * manager state they read. Ported rather than hardcoded so a chain drawn here
3647
+ * looks exactly like the one the preset used to draw. Mol* hands the same set
3648
+ * to its cartoons and its ball-and-sticks, and so does this.
3649
+ */
3650
+ function representationTypeParams(plugin) {
3651
+ const { hydrogens, ignoreLight, visualQuality } = plugin.managers.structure.component.state.options;
3652
+ return {
3653
+ ignoreHydrogens: hydrogens !== "all",
3654
+ ignoreHydrogensVariant: hydrogens === "only-polar" ? "non-polar" : "all",
3655
+ ignoreLight,
3656
+ quality: visualQuality
3657
+ };
3658
+ }
3659
+ /**
3660
+ * The two halves of a chain the viewer draws. Each names the component its
3661
+ * half is built under and tags the representation drawn over it, and it is
3662
+ * that tag `applyColorTheme` reads back to tell the two apart.
3663
+ */
3664
+ const POLYMER_PART = "polymer";
3665
+ const LIGAND_PART = "ligand";
3666
+ /**
3667
+ * True for the representation drawing a chain's heteroatoms.
3668
+ *
3669
+ * Read off the tag put on the representation when it was built, rather than
3670
+ * off the component's key. Mol* does not store the key as it was given: it
3671
+ * files components under `structure-component-<key>`, so a test against the
3672
+ * key as written here silently matches nothing, and every ligand quietly takes
3673
+ * the structure-wide theme instead. The tag survives untouched.
3674
+ */
3675
+ function isLigandRepresentation(representation) {
3676
+ var _representation$cell$;
3677
+ return ((_representation$cell$ = representation.cell.transform.tags) === null || _representation$cell$ === void 0 ? void 0 : _representation$cell$.includes(LIGAND_PART)) === true;
3678
+ }
3679
+ /**
3680
+ * How heteroatoms are colored: the theme Mol* puts on a ball-and-stick when
3681
+ * left to itself, with the parameters it chooses too.
3682
+ *
3683
+ * Named rather than left blank only so that it survives `applyColorTheme`,
3684
+ * which would otherwise repaint the ligands along with everything else. The
3685
+ * structure-wide theme is the wrong answer for them twice over: a heme reads
3686
+ * as a heme because its iron is orange and its nitrogens are blue, which one
3687
+ * flat color throws away, and pLDDT and residue overlays have no value for a
3688
+ * HETATM to be colored by at all.
3689
+ */
3690
+ const ELEMENT_THEME = "element-symbol";
3691
+ /**
3692
+ * Draws one chain: its polymer as a cartoon, its ligands and ions as
3693
+ * ball-and-stick.
3694
+ *
3695
+ * Two components rather than one, because a component is what a representation
3696
+ * attaches to and neither representation suits both halves - a cartoon has no
3697
+ * backbone to trace through a heme, and a ball-and-stick over the whole chain
3698
+ * would draw every protein atom as a sphere.
3699
+ *
3700
+ * Hands back the refs of whichever components the chain turned out to have,
3701
+ * which is what `setSubtreeVisibility` is later pointed at. Grouping them
3702
+ * under the chain is what makes hiding a chain take its ligands with it.
3703
+ */
3704
+ function buildChainComponents(_x5, _x6, _x7, _x8) {
3705
+ return _buildChainComponents.apply(this, arguments);
3706
+ }
3707
+ function _buildChainComponents() {
3708
+ _buildChainComponents = _asyncToGenerator(function* (plugin, structure, chain, typeParams) {
3709
+ const builders = plugin.builders.structure;
3710
+ const refs = [];
3711
+ const addPart = function() {
3712
+ var _ref = _asyncToGenerator(function* (part, expression, props) {
3713
+ const component = yield builders.tryCreateComponentFromExpression(structure, expression, `${part}-${chain.chainId}`, { label: chain.label });
3714
+ if (!component) return;
3715
+ yield builders.representation.addRepresentation(component, props, { tag: part });
3716
+ refs.push(component.ref);
3717
+ });
3718
+ return function addPart(_x2, _x3, _x4) {
3719
+ return _ref.apply(this, arguments);
3720
+ };
3721
+ }();
3722
+ yield addPart(POLYMER_PART, chainPolymerExpression(chain.chainId), {
3723
+ type: "cartoon",
3724
+ typeParams
3725
+ });
3726
+ yield addPart(LIGAND_PART, chainLigandExpression(chain.chainId), {
3727
+ color: ELEMENT_THEME,
3728
+ type: "ball-and-stick",
3729
+ typeParams
3730
+ });
3731
+ return refs;
3732
+ });
3733
+ return _buildChainComponents.apply(this, arguments);
3734
+ }
3735
+ const NOTHING_LOADED = {
3736
+ chains: [],
3737
+ componentRefs: /* @__PURE__ */ new Map(),
3738
+ residuesByChain: /* @__PURE__ */ new Map()
3739
+ };
3740
+ /**
3741
+ * Parses the structure and draws each chain: a cartoon over its polymer, and
3742
+ * ball-and-stick over its ligands and ions.
3743
+ *
3744
+ * Mol*'s `default` hierarchy preset would be shorter, but it groups every
3745
+ * polymer chain into a single component, and a component is the unit Mol* can
3746
+ * hide. Building them per chain is what makes a chain individually hideable;
3747
+ * the refs handed back are what `setSubtreeVisibility` is later pointed at.
3748
+ *
3749
+ * The wrapper detects PDB vs mmCIF from the text; this just forwards that
3750
+ * guess to Mol*.
3751
+ */
3752
+ function loadStructure(_x9, _x10, _x11, _x12) {
3753
+ return _loadStructure.apply(this, arguments);
3754
+ }
3755
+ function _loadStructure() {
3756
+ _loadStructure = _asyncToGenerator(function* (plugin, structureText, usePlddtColoring, showAxes) {
3757
+ try {
3758
+ var _plugin$canvas3d;
3759
+ yield plugin.clear();
3760
+ const data = yield plugin.builders.data.rawData({
3761
+ data: structureText,
3762
+ label: "Structure"
3763
+ });
3764
+ const trajectory = yield plugin.builders.structure.parseTrajectory(data, detectStructureFormat(structureText));
3765
+ const model = yield plugin.builders.structure.createModel(trajectory);
3766
+ const structure = yield plugin.builders.structure.createStructure(model, {
3767
+ name: "model",
3768
+ params: {}
3769
+ });
3770
+ const data3d = structure.data;
3771
+ if (!data3d) return NOTHING_LOADED;
3772
+ const { chainLabels, chains, residuesByChain } = scanChains(data3d);
3773
+ const typeParams = representationTypeParams(plugin);
3774
+ const componentRefs = /* @__PURE__ */ new Map();
3775
+ for (const [chainId, label] of chainLabels) {
3776
+ const refs = yield buildChainComponents(plugin, structure, {
3777
+ chainId,
3778
+ label
3779
+ }, typeParams);
3780
+ if (refs.length > 0) componentRefs.set(chainId, refs);
3781
+ }
3782
+ if (usePlddtColoring) yield applyColorTheme(plugin, PLDDT_THEME_NAME);
3783
+ (_plugin$canvas3d = plugin.canvas3d) === null || _plugin$canvas3d === void 0 || _plugin$canvas3d.requestCameraReset();
3784
+ setAxes(plugin, showAxes);
3785
+ return {
3786
+ chains,
3787
+ componentRefs,
3788
+ residuesByChain
3789
+ };
3790
+ } catch (error) {
3791
+ console.error("Failed to load structure:", error);
3792
+ return NOTHING_LOADED;
3793
+ }
3794
+ });
3795
+ return _loadStructure.apply(this, arguments);
3796
+ }
3797
+ /**
3798
+ * Shows or hides everything each chain is drawn with, cartoon and sticks
3799
+ * alike. Every component under the chain, so hiding it takes its ligands with
3800
+ * it rather than leaving a heme floating where its protein used to be.
3801
+ *
3802
+ * The whole subtree of each, not just the component cell: visibility is
3803
+ * per-cell, and it is the representation underneath that actually draws.
3804
+ *
3805
+ * Set outright rather than through the component manager's `toggleVisibility`,
3806
+ * which flips whatever it finds: the hidden set is derived from props on every
3807
+ * pass, so it has to be applied as a statement of what should be true and not
3808
+ * as a change to what already is.
3809
+ */
3810
+ function applyChainVisibility(plugin, componentRefs, hidden) {
3811
+ for (const [chainId, refs] of componentRefs) for (const ref of refs) setSubtreeVisibility(plugin.state.data, ref, hidden.has(chainId));
3812
+ }
3813
+ /**
3814
+ * Recolors every loaded structure's representations with the named theme,
3815
+ * leaving the heteroatoms on `ELEMENT_THEME`.
3816
+ *
3817
+ * The per-representation form of `updateRepresentationsTheme`, so the two can
3818
+ * be told apart in one pass; handing it a filtered list instead would leave
3819
+ * the ligands on whichever theme happened to be current when they were built.
3820
+ */
3821
+ function applyColorTheme(_x13, _x14) {
3822
+ return _applyColorTheme.apply(this, arguments);
3823
+ }
3824
+ function _applyColorTheme() {
3825
+ _applyColorTheme = _asyncToGenerator(function* (plugin, colorTheme) {
3826
+ yield plugin.dataTransaction(_asyncToGenerator(function* () {
3827
+ for (const s of plugin.managers.structure.hierarchy.current.structures) yield plugin.managers.structure.component.updateRepresentationsTheme(s.components, (_component, representation) => ({ color: isLigandRepresentation(representation) ? ELEMENT_THEME : colorTheme }));
3828
+ }));
3829
+ });
3830
+ return _applyColorTheme.apply(this, arguments);
3831
+ }
3832
+ /**
3833
+ * Owns the Mol* plugin for one viewer: creates it, loads the structure, wires
3834
+ * interaction callbacks, and disposes of it on unmount.
3835
+ *
3836
+ * The plugin is built once and then mutated in place. Creating it is expensive
3837
+ * and destroys the camera, so prop changes that Mol* can absorb (background,
3838
+ * axes, coloring, new structure) are pushed in through the effects below and in
3839
+ * the sibling hooks rather than by rebuilding.
3840
+ */
3841
+ function useMolstarPlugin({ backgroundColor, chainColors, containerRef, download, edgeColor, hasPlddt, hiddenChains, highlightColor, mode, molstarSpec, onChainHover, onChainSelect, onChainToggle, onResidueClick, onResidueHover, onSelectionChange, onSelectionClear, selectedChains, sequenceViewerBackgroundColor, showAxes, showSequenceViewer, structure }) {
3842
+ const pluginRef = useRef(null);
3843
+ const residueValueThemeRef = useRef(null);
3844
+ const chainColorThemeRef = useRef(null);
3845
+ const currentStructureRef = useRef(null);
3846
+ const [isReady, setIsReady] = useState(false);
3847
+ const [chains, setChains] = useState([]);
3848
+ const [loadCount, setLoadCount] = useState(0);
3849
+ /**
3850
+ * Where each chain's components live in the state tree, which is what the
3851
+ * visibility effect points `setSubtreeVisibility` at. Rewritten by every
3852
+ * load, since the refs do not survive `plugin.clear()`.
3853
+ */
3854
+ const componentRefsRef = useRef(/* @__PURE__ */ new Map());
3855
+ /**
3856
+ * Which residues sit on each chain, for the readout to average a score over
3857
+ * a whole-chain selection. A ref rather than state: nothing renders from it
3858
+ * directly, and it is rewritten in step with `chains`, which does.
3859
+ */
3860
+ const residuesByChainRef = useRef(/* @__PURE__ */ new Map());
3861
+ /**
3862
+ * The visibility and coloring to apply as soon as a structure exists. Read
3863
+ * through refs because both arrive as fresh objects on every render, and a
3864
+ * load has to be able to consult them without the load effect depending on
3865
+ * them - a new Set each render would reload the structure on every pass.
3866
+ */
3867
+ const hiddenChainsRef = useRef(hiddenChains);
3868
+ hiddenChainsRef.current = hiddenChains;
3869
+ const chainColorsRef = useRef(chainColors);
3870
+ chainColorsRef.current = chainColors;
3871
+ /**
3872
+ * Carries the theme-dependent props into the views Mol* renders in its own
3873
+ * React root. They cannot read them from context, and rebuilding the plugin
3874
+ * would throw away the camera, so the values are pushed to them instead.
3875
+ */
3876
+ const viewSettingsRef = useRef(null);
3877
+ if (viewSettingsRef.current === null) viewSettingsRef.current = new BehaviorSubject({
3878
+ mode,
3879
+ sequenceViewerBackgroundColor,
3880
+ showAxes
3881
+ });
3882
+ const viewSettings = viewSettingsRef.current;
3883
+ /**
3884
+ * Clip-radius-per-camera-distance ratio recorded at the last residue focus,
3885
+ * or null when no residue is focused. Anchors the adaptive depth clipping.
3886
+ */
3887
+ const clipRatioRef = useRef(null);
3888
+ const setClipRatio = useCallback((ratio) => {
3889
+ clipRatioRef.current = ratio;
3890
+ }, []);
3891
+ /**
3892
+ * Takes up what a load produced: the component refs the chain-keyed props
3893
+ * address, the visibility they were already asking for, and the chain list
3894
+ * the consumer is told about.
3895
+ *
3896
+ * Chains are published only when they actually differ, so reloading the same
3897
+ * structure - a theme switch that happens to reload, a parent handing back an
3898
+ * equal PDB string - does not hand every consumer a new array to react to.
3899
+ */
3900
+ const adoptLoadedStructure = useCallback((plugin, loaded) => {
3901
+ componentRefsRef.current = loaded.componentRefs;
3902
+ residuesByChainRef.current = loaded.residuesByChain;
3903
+ applyChainVisibility(plugin, loaded.componentRefs, hiddenChainsRef.current);
3904
+ setChains((prev) => chainsEqual(prev, loaded.chains) ? prev : loaded.chains);
3905
+ setLoadCount((count) => count + 1);
3906
+ }, []);
3907
+ const onResidueClickRef = useRef(onResidueClick);
3908
+ onResidueClickRef.current = onResidueClick;
3909
+ const onSelectionClearRef = useRef(onSelectionClear);
3910
+ onSelectionClearRef.current = onSelectionClear;
3911
+ const onSelectionChangeRef = useRef(onSelectionChange);
3912
+ onSelectionChangeRef.current = onSelectionChange;
3913
+ const onResidueHoverRef = useRef(onResidueHover);
3914
+ onResidueHoverRef.current = onResidueHover;
3915
+ /** Last residue reported to `onResidueHover`, to suppress repeats. */
3916
+ const lastHoverRef = useRef(null);
3917
+ const initialPropsRef = useRef({
3918
+ backgroundColor,
3919
+ edgeColor,
3920
+ hasPlddt,
3921
+ highlightColor,
3922
+ mode,
3923
+ molstarSpec,
3924
+ showAxes,
3925
+ showSequenceViewer,
3926
+ structure
3927
+ });
3928
+ initialPropsRef.current = {
3929
+ backgroundColor,
3930
+ edgeColor,
3931
+ hasPlddt,
3932
+ highlightColor,
3933
+ mode,
3934
+ molstarSpec,
3935
+ showAxes,
3936
+ showSequenceViewer,
3937
+ structure
3938
+ };
3939
+ /**
3940
+ * The consumer's `canvas3d` overrides, keyed by content. Unlike the rest of
3941
+ * the spec these are re-applied when they change, and they commonly arrive
3942
+ * as an object written inline - so the effect below turns on what they say
3943
+ * rather than on the identity of the object saying it.
3944
+ */
3945
+ const canvas3dOverrideKey = (() => {
3946
+ try {
3947
+ var _molstarSpec$canvas3d;
3948
+ return JSON.stringify((_molstarSpec$canvas3d = molstarSpec === null || molstarSpec === void 0 ? void 0 : molstarSpec.canvas3d) !== null && _molstarSpec$canvas3d !== void 0 ? _molstarSpec$canvas3d : null);
3949
+ } catch (_unused) {
3950
+ return String(Date.now());
3951
+ }
3952
+ })();
3953
+ useEffect(() => {
3954
+ const container = containerRef.current;
3955
+ if (!container) return;
3956
+ let cancelled = false;
3957
+ let clipSubscription;
3958
+ const init = function() {
3959
+ var _ref2 = _asyncToGenerator(function* () {
3960
+ yield nextFrame();
3961
+ if (cancelled) return;
3962
+ const rect = container.getBoundingClientRect();
3963
+ if (rect.width === 0 || rect.height === 0) {
3964
+ setTimeout(init, LAYOUT_RETRY_MS);
3965
+ return;
3966
+ }
3967
+ const initial = initialPropsRef.current;
3968
+ try {
3969
+ var _plugin$canvas3d2;
3970
+ const residueValueTheme = createResidueValueTheme(initial.mode);
3971
+ const chainColorTheme = createChainColorTheme();
3972
+ const plugin = yield createViewer({
3973
+ backgroundColor: initial.backgroundColor,
3974
+ chainColorTheme,
3975
+ edgeColor: initial.edgeColor,
3976
+ highlightColor: initial.highlightColor,
3977
+ molstarSpec: initial.molstarSpec,
3978
+ residueValueTheme,
3979
+ root: container,
3980
+ showAxes: initial.showAxes,
3981
+ showSequenceViewer: initial.showSequenceViewer,
3982
+ viewSettings
3983
+ });
3984
+ if (cancelled) {
3985
+ plugin.dispose();
3986
+ return;
3987
+ }
3988
+ pluginRef.current = plugin;
3989
+ residueValueThemeRef.current = residueValueTheme;
3990
+ chainColorThemeRef.current = chainColorTheme;
3991
+ const latest = initialPropsRef.current;
3992
+ const loaded = yield loadStructure(plugin, latest.structure, latest.hasPlddt, latest.showAxes);
3993
+ currentStructureRef.current = latest.structure;
3994
+ adoptLoadedStructure(plugin, loaded);
3995
+ /**
3996
+ * Mol*'s click behavior is a BehaviorSubject, so subscribing replays
3997
+ * whatever it is currently holding - which, before anything has been
3998
+ * clicked, is an empty click. Acting on that would read as the user
3999
+ * clicking empty space and clear a selection the consumer had set
4000
+ * before the viewer was even interactive.
4001
+ *
4002
+ * Only the replay is skipped, not every empty click: clicking away
4003
+ * from the structure is how a selection is meant to be cleared.
4004
+ */
4005
+ let clickReplayConsumed = false;
4006
+ plugin.behaviors.interaction.click.subscribe((e) => {
4007
+ var _onResidueClickRef$cu, _onSelectionChangeRef;
4008
+ if (!clickReplayConsumed) {
4009
+ clickReplayConsumed = true;
4010
+ if (Representation.Loci.isEmpty(e.current)) return;
4011
+ }
4012
+ if (Representation.Loci.isEmpty(e.current)) {
4013
+ var _onSelectionClearRef$;
4014
+ (_onSelectionClearRef$ = onSelectionClearRef.current) === null || _onSelectionClearRef$ === void 0 || _onSelectionClearRef$.call(onSelectionClearRef);
4015
+ return;
4016
+ }
4017
+ const loci = e.current.loci;
4018
+ if (!StructureElement.Loci.is(loci)) return;
4019
+ const residue = residueRefFromLoci(loci);
4020
+ if (!residue) return;
4021
+ (_onResidueClickRef$cu = onResidueClickRef.current) === null || _onResidueClickRef$cu === void 0 || _onResidueClickRef$cu.call(onResidueClickRef, residue);
4022
+ (_onSelectionChangeRef = onSelectionChangeRef.current) === null || _onSelectionChangeRef === void 0 || _onSelectionChangeRef.call(onSelectionChangeRef, selectionFromLoci(loci));
4023
+ });
4024
+ plugin.behaviors.interaction.hover.subscribe((e) => {
4025
+ var _lastHoverRef$current, _onResidueHoverRef$cu;
4026
+ const loci = e.current.loci;
4027
+ const residue = StructureElement.Loci.is(loci) ? residueRefFromLoci(loci) : null;
4028
+ if ((residue === null || residue === void 0 ? void 0 : residue.index) === ((_lastHoverRef$current = lastHoverRef.current) === null || _lastHoverRef$current === void 0 ? void 0 : _lastHoverRef$current.index)) return;
4029
+ lastHoverRef.current = residue;
4030
+ (_onResidueHoverRef$cu = onResidueHoverRef.current) === null || _onResidueHoverRef$cu === void 0 || _onResidueHoverRef$cu.call(onResidueHoverRef, residue);
4031
+ });
4032
+ clipSubscription = (_plugin$canvas3d2 = plugin.canvas3d) === null || _plugin$canvas3d2 === void 0 ? void 0 : _plugin$canvas3d2.didDraw.subscribe(() => {
4033
+ syncClipToZoom(plugin, () => clipRatioRef.current);
4034
+ });
4035
+ if (!cancelled) setIsReady(true);
4036
+ } catch (error) {
4037
+ console.error("Failed to initialize Mol* viewer:", error);
4038
+ }
4039
+ });
4040
+ return function init() {
4041
+ return _ref2.apply(this, arguments);
4042
+ };
4043
+ }();
4044
+ init();
4045
+ return () => {
4046
+ var _pluginRef$current;
4047
+ cancelled = true;
4048
+ clipSubscription === null || clipSubscription === void 0 || clipSubscription.unsubscribe();
4049
+ (_pluginRef$current = pluginRef.current) === null || _pluginRef$current === void 0 || _pluginRef$current.dispose();
4050
+ pluginRef.current = null;
4051
+ residueValueThemeRef.current = null;
4052
+ chainColorThemeRef.current = null;
4053
+ componentRefsRef.current = /* @__PURE__ */ new Map();
4054
+ residuesByChainRef.current = /* @__PURE__ */ new Map();
4055
+ currentStructureRef.current = null;
4056
+ clipRatioRef.current = null;
4057
+ setIsReady(false);
4058
+ };
4059
+ }, []);
4060
+ useEffect(() => {
4061
+ var _pluginRef$current2, _initialPropsRef$curr;
4062
+ const canvas3d = (_pluginRef$current2 = pluginRef.current) === null || _pluginRef$current2 === void 0 ? void 0 : _pluginRef$current2.canvas3d;
4063
+ if (!canvas3d || !isReady) return;
4064
+ canvas3d.setProps({
4065
+ marking: {
4066
+ highlightEdgeColor: edgeColor,
4067
+ selectEdgeColor: edgeColor
4068
+ },
4069
+ renderer: {
4070
+ backgroundColor,
4071
+ highlightColor
4072
+ }
4073
+ });
4074
+ const override = (_initialPropsRef$curr = initialPropsRef.current.molstarSpec) === null || _initialPropsRef$curr === void 0 ? void 0 : _initialPropsRef$curr.canvas3d;
4075
+ if (override) canvas3d.setProps(override);
4076
+ }, [
4077
+ backgroundColor,
4078
+ canvas3dOverrideKey,
4079
+ edgeColor,
4080
+ highlightColor,
4081
+ isReady
4082
+ ]);
4083
+ useEffect(() => {
4084
+ viewSettings.next({
4085
+ download,
4086
+ hiddenChains,
4087
+ mode,
4088
+ onChainHover,
4089
+ onChainSelect,
4090
+ onChainToggle,
4091
+ selectedChains,
4092
+ sequenceViewerBackgroundColor,
4093
+ showAxes
4094
+ });
4095
+ }, [
4096
+ download,
4097
+ hiddenChains,
4098
+ mode,
4099
+ onChainHover,
4100
+ onChainSelect,
4101
+ onChainToggle,
4102
+ selectedChains,
4103
+ sequenceViewerBackgroundColor,
4104
+ showAxes,
4105
+ viewSettings
4106
+ ]);
4107
+ useEffect(() => {
4108
+ if (!isReady || !pluginRef.current) return;
4109
+ setAxes(pluginRef.current, showAxes);
4110
+ }, [showAxes, isReady]);
4111
+ useEffect(() => {
4112
+ const plugin = pluginRef.current;
4113
+ if (!plugin || !isReady) return;
4114
+ if (structure === currentStructureRef.current) return;
4115
+ currentStructureRef.current = structure;
4116
+ clipRatioRef.current = null;
4117
+ lastHoverRef.current = null;
4118
+ loadStructure(plugin, structure, hasPlddt, showAxes).then((loaded) => {
4119
+ if (pluginRef.current !== plugin) return;
4120
+ adoptLoadedStructure(plugin, loaded);
4121
+ });
4122
+ }, [
4123
+ structure,
4124
+ hasPlddt,
4125
+ isReady,
4126
+ adoptLoadedStructure
4127
+ ]);
4128
+ useEffect(() => {
4129
+ const plugin = pluginRef.current;
4130
+ if (!plugin || !isReady) return;
4131
+ applyChainVisibility(plugin, componentRefsRef.current, hiddenChains);
4132
+ }, [hiddenChains, isReady]);
4133
+ return {
4134
+ chainColorThemeRef,
4135
+ chains,
4136
+ isReady,
4137
+ loadCount,
4138
+ pluginRef,
4139
+ residuesByChainRef,
4140
+ residueValueThemeRef,
4141
+ setClipRatio
4142
+ };
4143
+ }
4144
+ //#endregion
4145
+ //#region src/core/ProteinStructureViewer/utils/focusRepresentation.ts
4146
+ /**
4147
+ * What Mol* draws around a focused selection, as ball-and-stick over the
4148
+ * cartoon: the selection itself, the residues near it, and the non-covalent
4149
+ * contacts between the two. All three stay on; what changes is how far "near"
4150
+ * reaches.
4151
+ */
4152
+ const FOCUS_COMPONENTS = [
4153
+ "target",
4154
+ "surroundings",
4155
+ "interactions"
4156
+ ];
4157
+ /** Mol*'s own default, in angstroms. */
4158
+ const NEIGHBOUR_RADIUS = 5;
4159
+ /**
4160
+ * Mol* builds the surroundings as `includeSurroundings(target, radius)` with
4161
+ * whole residues, so a radius of zero resolves to the residues of the target
4162
+ * and nothing else.
4163
+ */
4164
+ const OWN_RESIDUES_ONLY = 0;
4165
+ /**
4166
+ * Chooses how far the focus shell reaches around a selection.
4167
+ *
4168
+ * A residue, or a short range, is a site: the 5A shell around it is the point
4169
+ * of looking at it, and Mol*'s default earns its keep. A whole chain is a
4170
+ * structural unit instead, and its neighbours are the chain bound to it - so
4171
+ * on a complex the shell reaches straight across the interface and draws the
4172
+ * partner's contact face in atoms, which reads as the partner being selected
4173
+ * too.
4174
+ *
4175
+ * Taking the radius to zero confines the shell to the selection rather than
4176
+ * turning it off: the surroundings and the interactions are still drawn, over
4177
+ * the selected chain's own residues, so a chain shows its own atoms and
4178
+ * contacts and no others'.
4179
+ */
4180
+ function setFocusNeighbourhood(_x, _x2) {
4181
+ return _setFocusNeighbourhood.apply(this, arguments);
4182
+ }
4183
+ function _setFocusNeighbourhood() {
4184
+ _setFocusNeighbourhood = _asyncToGenerator(function* (plugin, includeNeighbours) {
4185
+ const expandRadius = includeNeighbours ? NEIGHBOUR_RADIUS : OWN_RESIDUES_ONLY;
4186
+ yield plugin.state.updateBehavior(StructureFocusRepresentation, (params) => {
4187
+ params.components = FOCUS_COMPONENTS;
4188
+ params.expandRadius = expandRadius;
4189
+ });
4190
+ });
4191
+ return _setFocusNeighbourhood.apply(this, arguments);
4192
+ }
4193
+ //#endregion
4194
+ //#region src/core/ProteinStructureViewer/hooks/useSelectionFocus.ts
4195
+ /**
4196
+ * Points the camera at a loci and marks it.
4197
+ *
4198
+ * A click has already focused what the consumer echoes back by the time it
4199
+ * arrives, so the focus is only set when it is not already what is marked;
4200
+ * setting it again would restate the selection and repaint the sequence panel
4201
+ * for nothing.
4202
+ */
4203
+ function focusLoci(plugin, loci, setClipRatio) {
4204
+ const focused = plugin.managers.structure.focus.behaviors.current.value;
4205
+ if (!focused || !StructureElement.Loci.areEqual(focused.loci, loci)) plugin.managers.structure.focus.setFromLoci(loci);
4206
+ setClipRatio(focusResidue(plugin, loci));
4207
+ }
4208
+ /**
4209
+ * Drops the focus, and the depth clipping anchored to it.
4210
+ *
4211
+ * `resetCamera` separates the two ways this happens. The consumer clearing the
4212
+ * selection means there is nothing to look at, so the view goes back to the
4213
+ * default. A selection that merely resolved to nothing visible - the chain it
4214
+ * covers having been hidden - still stands, so throwing the camera back would
4215
+ * be answering a question nobody asked.
4216
+ */
4217
+ function clearFocus(plugin, setClipRatio, resetCamera) {
4218
+ var _plugin$canvas3d;
4219
+ setClipRatio(null);
4220
+ plugin.managers.structure.focus.clear();
4221
+ if (resetCamera) (_plugin$canvas3d = plugin.canvas3d) === null || _plugin$canvas3d === void 0 || _plugin$canvas3d.requestCameraReset();
4222
+ }
4223
+ /**
4224
+ * Focuses a loci, resizing the focus shell first when this selection wants a
4225
+ * different reach than the last one did.
4226
+ *
4227
+ * The resize is asynchronous and the focus has to follow it - the shell is
4228
+ * sized before focusing so it is not drawn at the old reach and rebuilt - so
4229
+ * this hands back a teardown that abandons the focus if the effect is torn
4230
+ * down while the resize is still in flight.
4231
+ *
4232
+ * `currentShell` is the reach already configured, carried in a ref so that two
4233
+ * selections of the same kind do not each restate it.
4234
+ */
4235
+ function focusWithShell(plugin, loci, includeNeighbours, currentShell, pluginRef, setClipRatio) {
4236
+ if (currentShell.current === includeNeighbours) {
4237
+ focusLoci(plugin, loci, setClipRatio);
4238
+ return;
4239
+ }
4240
+ let cancelled = false;
4241
+ currentShell.current = includeNeighbours;
4242
+ setFocusNeighbourhood(plugin, includeNeighbours).then(() => {
4243
+ if (cancelled || pluginRef.current !== plugin) return;
4244
+ focusLoci(plugin, loci, setClipRatio);
4245
+ });
4246
+ return () => {
4247
+ cancelled = true;
4248
+ };
4249
+ }
4250
+ /**
4251
+ * Makes `selection` the one thing that decides where the camera sits.
4252
+ *
4253
+ * Setting the prop frames whatever it covers; clearing it drops the focus and
4254
+ * zooms back out. The camera frames the selection's bounding sphere, so a range
4255
+ * or a whole chain is fitted rather than approached as a point - one residue is
4256
+ * just the smallest case of that.
4257
+ *
4258
+ * Residues are also marked, which is what draws Mol*'s ball-and-stick and
4259
+ * outline over them. Whole chains are not: those are shown by dimming the
4260
+ * chains around them instead, in `useChainHighlight`.
4261
+ *
4262
+ * The click subscription only reports the selection it was given, so a click
4263
+ * moves the camera only once the consumer accepts it and echoes it back -
4264
+ * which is what the prop being controlled is supposed to mean. Clicking still
4265
+ * marks immediately, through Mol*'s own focus behavior, so the structure
4266
+ * responds to a click whether or not the consumer wires the prop up.
4267
+ */
4268
+ function useSelectionFocus({ hiddenChains, isReady, pluginRef, selection, setClipRatio }) {
4269
+ var _selection$chains, _selection$residues;
4270
+ /**
4271
+ * What this hook last pointed the camera at, as a key rather than the object
4272
+ * itself: a consumer echoing a selection back builds a new object each time,
4273
+ * and comparing identity would refocus on every render.
4274
+ *
4275
+ * Tracked here rather than compared against the previous prop so that a
4276
+ * selection made before the plugin was ready is still applied once it is,
4277
+ * and so that a plugin rebuilt underneath us - which comes up focused on
4278
+ * nothing - is not assumed to still be holding the old one.
4279
+ */
4280
+ const focusedRef = useRef(null);
4281
+ /**
4282
+ * Whether the focus shell currently reaches beyond the selection, so the
4283
+ * behavior is only updated when the answer actually changes rather than on
4284
+ * every selection.
4285
+ */
4286
+ const neighbourhoodRef = useRef(null);
4287
+ /**
4288
+ * What the camera should be pointed at, as a string. Hiding a chain changes
4289
+ * what there is to focus, so it belongs in here alongside the selection
4290
+ * itself - and comparing strings rather than objects is what keeps a consumer
4291
+ * echoing an equal selection back from refocusing on every render.
4292
+ */
4293
+ const focusKey = selection ? `${selectionKey(selection)}#${[...hiddenChains].sort().join(",")}` : null;
4294
+ /**
4295
+ * Whether the selection names chains and nothing else, which is the shape
4296
+ * shown by dimming the chains around it rather than by focusing it.
4297
+ */
4298
+ const chainsOnly = Boolean((selection === null || selection === void 0 || (_selection$chains = selection.chains) === null || _selection$chains === void 0 ? void 0 : _selection$chains.length) && !((_selection$residues = selection.residues) === null || _selection$residues === void 0 ? void 0 : _selection$residues.length));
4299
+ useEffect(() => {
4300
+ var _chosen$chains;
4301
+ const plugin = pluginRef.current;
4302
+ if (!plugin || !isReady) {
4303
+ focusedRef.current = null;
4304
+ neighbourhoodRef.current = null;
4305
+ return;
4306
+ }
4307
+ if (focusKey === focusedRef.current) return;
4308
+ focusedRef.current = focusKey;
4309
+ if (focusKey === null) {
4310
+ clearFocus(plugin, setClipRatio, true);
4311
+ return;
4312
+ }
4313
+ const chosen = selection;
4314
+ const loci = lociForSelection(plugin, chosen, hiddenChains);
4315
+ if (!loci) {
4316
+ clearFocus(plugin, setClipRatio, false);
4317
+ return;
4318
+ }
4319
+ if (chainsOnly) {
4320
+ plugin.managers.structure.focus.clear();
4321
+ frameLoci(plugin, loci);
4322
+ setClipRatio(null);
4323
+ return;
4324
+ }
4325
+ return focusWithShell(plugin, loci, !((_chosen$chains = chosen.chains) === null || _chosen$chains === void 0 ? void 0 : _chosen$chains.length), neighbourhoodRef, pluginRef, setClipRatio);
4326
+ }, [
4327
+ focusKey,
4328
+ isReady,
4329
+ setClipRatio
4330
+ ]);
4331
+ }
4332
+ //#endregion
4333
+ //#region src/core/ProteinStructureViewer/hooks/useSelectionReadout.ts
4334
+ /**
4335
+ * Tracks the residue under the pointer, deduplicated, and passes the event on
4336
+ * to the consumer.
4337
+ *
4338
+ * Mol* emits hover events continuously, so a residue the pointer is resting on
4339
+ * would otherwise cost a state update per event. The index alone does not
4340
+ * identify one: loading a new structure into the same plugin renumbers from
4341
+ * zero, so the residue now at an index is not the one that was there before.
4342
+ * Comparing the label as well is enough, because the readout this drives is
4343
+ * built from the label and the index and from nothing else.
4344
+ */
4345
+ function useResidueHoverState(onResidueHover) {
4346
+ const [hoveredResidue, setHoveredResidue] = useState(null);
4347
+ return {
4348
+ handleResidueHover: useCallback((residue) => {
4349
+ setHoveredResidue((prev) => {
4350
+ if (residue === null) return prev === null ? prev : null;
4351
+ const label = residueLabel(residue);
4352
+ return prev !== null && prev.index === residue.index && prev.label === label ? prev : {
4353
+ index: residue.index,
4354
+ label
4355
+ };
4356
+ });
4357
+ onResidueHover === null || onResidueHover === void 0 || onResidueHover(residue);
4358
+ }, [onResidueHover]),
4359
+ hoveredResidue
4360
+ };
4361
+ }
4362
+ /**
4363
+ * Derives the legend's readouts from what is hovered and what is selected.
4364
+ *
4365
+ * The viewer already knows everything they need - the label, the pLDDT, the
4366
+ * overlay value - so they are worked out here rather than asked of the
4367
+ * consumer. A readout covering several residues reports the mean of each,
4368
+ * which is the only reading that survives a range or a whole chain.
4369
+ */
4370
+ function useSelectionReadout({ hoveredResidue, isReady, plddt, pluginRef, residueOverlay, residuesByChainRef, selection }) {
4371
+ const [resolved, setResolved] = useState(null);
4372
+ /**
4373
+ * What the selection covers has to be read off the structure, since a
4374
+ * selection can be made without a click ever naming anything: a lone residue
4375
+ * is named the way the click path names it, so the two readouts cannot
4376
+ * disagree, and a chain is expanded to the residues it actually holds rather
4377
+ * than to the span between its ends.
4378
+ */
4379
+ useEffect(() => {
4380
+ var _residuesByChainRef$c;
4381
+ const plugin = pluginRef.current;
4382
+ if (!plugin || !isReady || isEmptySelection(selection)) {
4383
+ setResolved(null);
4384
+ return;
4385
+ }
4386
+ const chosen = selection;
4387
+ const residues = selectionResidues(chosen, (_residuesByChainRef$c = residuesByChainRef.current) !== null && _residuesByChainRef$c !== void 0 ? _residuesByChainRef$c : /* @__PURE__ */ new Map());
4388
+ if (residues.length === 0) {
4389
+ setResolved(null);
4390
+ return;
4391
+ }
4392
+ if (residues.length > 1) {
4393
+ setResolved({
4394
+ label: selectionLabel(chosen, residues.length),
4395
+ residues
4396
+ });
4397
+ return;
4398
+ }
4399
+ const loci = lociForSelection(plugin, chosen);
4400
+ const residue = loci && residueRefFromLoci(loci);
4401
+ setResolved(residue ? {
4402
+ label: residueLabel(residue),
4403
+ residues
4404
+ } : null);
4405
+ }, [isReady, selection && selectionKey(selection)]);
4406
+ const buildReadout = useCallback((label, residues) => ({
4407
+ label,
4408
+ plddt: meanOverResidues(residues, (i) => plddt === null || plddt === void 0 ? void 0 : plddt[i]),
4409
+ value: meanOverResidues(residues, (i) => residueOverlay === null || residueOverlay === void 0 ? void 0 : residueOverlay.values.get(i)),
4410
+ residueCount: residues.length
4411
+ }), [plddt, residueOverlay]);
4412
+ return {
4413
+ hoveredReadout: useMemo(() => hoveredResidue === null ? null : buildReadout(hoveredResidue.label, [hoveredResidue.index]), [hoveredResidue, buildReadout]),
4414
+ selectedReadout: useMemo(() => resolved === null ? null : buildReadout(resolved.label, resolved.residues), [resolved, buildReadout])
4415
+ };
4416
+ }
4417
+ //#endregion
4418
+ //#region src/core/ProteinStructureViewer/hooks/useStructureColoring.ts
4419
+ /**
4420
+ * Decides what is coloring the structure and keeps that theme's data current.
4421
+ *
4422
+ * Three themes compete for the same representations, in a fixed order: a
4423
+ * residue value overlay, then pLDDT scores, then per-chain colors. Only one
4424
+ * can be applied, so the precedence lives here rather than being spread across
4425
+ * the hooks that own each theme's data - and the legend resolves what to
4426
+ * describe the same way, so the two cannot disagree about what is on screen.
4427
+ *
4428
+ * Recoloring happens in place: the camera is left where it is, so selecting or
4429
+ * switching an overlay does not zoom back out to the default view.
4430
+ */
4431
+ function useStructureColoring({ chainColorThemeRef, chainColors, hasPlddt, isReady, mode, overlay, pluginRef, residueValueThemeRef }) {
4432
+ useEffect(() => {
4433
+ const plugin = pluginRef.current;
4434
+ const residueTheme = residueValueThemeRef.current;
4435
+ const chainTheme = chainColorThemeRef.current;
4436
+ if (!plugin || !residueTheme || !chainTheme || !isReady) return;
4437
+ chainTheme.setState(chainColors);
4438
+ if (overlay) {
4439
+ var _overlay$colorScale, _overlay$min;
4440
+ residueTheme.setState({
4441
+ colorScale: (_overlay$colorScale = overlay.colorScale) !== null && _overlay$colorScale !== void 0 ? _overlay$colorScale : PLASMA_COLOR_SCALE,
4442
+ max: overlay.max,
4443
+ min: (_overlay$min = overlay.min) !== null && _overlay$min !== void 0 ? _overlay$min : 0,
4444
+ mode,
4445
+ values: overlay.values
4446
+ });
4447
+ applyColorTheme(plugin, RESIDUE_VALUE_THEME_NAME);
4448
+ return;
4449
+ }
4450
+ residueTheme.setState({
4451
+ mode,
4452
+ values: /* @__PURE__ */ new Map()
4453
+ });
4454
+ applyColorTheme(plugin, hasPlddt ? PLDDT_THEME_NAME : FALLBACK_THEME_NAME);
4455
+ }, [
4456
+ overlay,
4457
+ hasPlddt,
4458
+ isReady,
4459
+ mode,
4460
+ chainColors
4461
+ ]);
4462
+ }
4463
+ //#endregion
4464
+ //#region src/core/ProteinStructureViewer/ProteinStructureViewer.types.ts
4465
+ /** Pixel dimensions each resolution produces, for documentation and labels. */
4466
+ const DOWNLOAD_RESOLUTIONS = {
4467
+ high: "3840x2160",
4468
+ low: "1280x720",
4469
+ maximum: "7680x4320",
4470
+ medium: "1920x1080"
4471
+ };
4472
+ //#endregion
4473
+ //#region src/core/ProteinStructureViewer/index.tsx
4474
+ const _excluded = [
4475
+ "backgroundColor",
4476
+ "chainColors",
4477
+ "disableChainHighlightOnHover",
4478
+ "download",
4479
+ "hiddenChains",
4480
+ "onChainVisibilityChange",
4481
+ "onChainsChange",
4482
+ "molstarSpec",
4483
+ "onResidueClick",
4484
+ "onResidueHover",
4485
+ "onSelectionChange",
4486
+ "structure",
4487
+ "plddt",
4488
+ "residueOverlay",
4489
+ "selection",
4490
+ "sequenceViewerBackgroundColor",
4491
+ "showAxes",
4492
+ "showChainLegend",
4493
+ "showLegend",
4494
+ "showSequenceViewer",
4495
+ "stats"
4496
+ ];
4497
+ /** Fallbacks for theme tokens Mol* needs as concrete hex colors. */
4498
+ const FALLBACK_EDGE_COLOR = "#6c6c6c";
4499
+ const FALLBACK_HIGHLIGHT_COLOR = "#1b1b1b";
4500
+ /**
4501
+ * Keyed by mode: unlike the two above, the canvas has to invert with it. Only
4502
+ * reached when the viewer renders outside an SDS theme; inside one the
4503
+ * `base.backgroundPrimary` token wins.
4504
+ */
4505
+ const FALLBACK_BACKGROUND_COLOR = {
4506
+ dark: "#000000",
4507
+ light: "#ffffff"
4508
+ };
4509
+ /** Caption shown beneath the color key when no overlay is active. */
4510
+ const PLDDT_SCALE_LABEL = "pLDDT";
4511
+ /** Caption used when an overlay does not name itself. */
4512
+ const DEFAULT_OVERLAY_LABEL = "Value";
4513
+ /** Readout slot label used when an overlay does not name one. */
4514
+ const DEFAULT_READOUT_LABEL = "Value";
4515
+ /**
4516
+ * Chooses what the legend describes, following whatever is actually coloring
4517
+ * the structure: the overlay when one is set, the pLDDT bands when scores were
4518
+ * supplied, and nothing at all otherwise - Mol* falls back to chain coloring
4519
+ * there, which no per-residue scale describes, so a key would be labelling
4520
+ * colors that are not on screen.
4521
+ */
4522
+ function resolveScaleProps(overlay, hasPlddt) {
4523
+ if (overlay) {
4524
+ var _overlay$colorScale, _overlay$label, _overlay$min, _overlay$readoutLabel;
4525
+ return {
4526
+ scale: (_overlay$colorScale = overlay.colorScale) !== null && _overlay$colorScale !== void 0 ? _overlay$colorScale : PLASMA_COLOR_SCALE,
4527
+ scaleLabel: (_overlay$label = overlay.label) !== null && _overlay$label !== void 0 ? _overlay$label : DEFAULT_OVERLAY_LABEL,
4528
+ scaleMax: overlay.max,
4529
+ scaleMin: (_overlay$min = overlay.min) !== null && _overlay$min !== void 0 ? _overlay$min : 0,
4530
+ scaleTooltip: overlay.tooltip,
4531
+ scaleTooltipProps: overlay.tooltipProps,
4532
+ valueLabel: (_overlay$readoutLabel = overlay.readoutLabel) !== null && _overlay$readoutLabel !== void 0 ? _overlay$readoutLabel : DEFAULT_READOUT_LABEL
4533
+ };
4534
+ }
4535
+ if (hasPlddt) return {
4536
+ scale: PLDDT_COLOR_SCALE,
4537
+ scaleLabel: PLDDT_SCALE_LABEL,
4538
+ scaleMax: null,
4539
+ scaleTooltip: void 0,
4540
+ scaleTooltipProps: void 0,
4541
+ valueLabel: void 0
4542
+ };
4543
+ return {
4544
+ scale: null,
4545
+ scaleLabel: void 0,
4546
+ scaleMax: null,
4547
+ scaleTooltip: void 0,
4548
+ scaleTooltipProps: void 0,
4549
+ valueLabel: void 0
4550
+ };
4551
+ }
4552
+ var ProteinStructureViewer_default = memo(forwardRef((props, ref) => {
4553
+ var _selection$chains;
4554
+ const { backgroundColor, chainColors: chainColorOverrides, disableChainHighlightOnHover = false, download, hiddenChains: hiddenChainsProp, onChainVisibilityChange, onChainsChange, molstarSpec, onResidueClick, onResidueHover, onSelectionChange, structure, plddt, residueOverlay, selection = null, sequenceViewerBackgroundColor, showAxes = true, showChainLegend = true, showLegend = true, showSequenceViewer = true, stats } = props, rest = _objectWithoutProperties(props, _excluded);
4555
+ const theme = useTheme();
4556
+ const mode = getMode({ theme });
4557
+ const semanticColors = getSemanticColors({ theme });
4558
+ const pluginMountRef = useRef(null);
4559
+ const hasPlddt = Boolean(plddt && plddt.length > 0);
4560
+ const processedStructure = useMemo(() => hasPlddt ? injectPlddt(structure, plddt) : structure, [
4561
+ structure,
4562
+ plddt,
4563
+ hasPlddt
4564
+ ]);
4565
+ const bgColor = useMemo(() => {
4566
+ var _semanticColors$base;
4567
+ return themeColor(backgroundColor !== null && backgroundColor !== void 0 ? backgroundColor : semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.backgroundPrimary, FALLBACK_BACKGROUND_COLOR[mode]);
4568
+ }, [
4569
+ backgroundColor,
4570
+ mode,
4571
+ semanticColors
4572
+ ]);
4573
+ const edgeColor = useMemo(() => {
4574
+ var _semanticColors$base2;
4575
+ return themeColor(semanticColors === null || semanticColors === void 0 || (_semanticColors$base2 = semanticColors.base) === null || _semanticColors$base2 === void 0 ? void 0 : _semanticColors$base2.borderPrimary, FALLBACK_EDGE_COLOR);
4576
+ }, [semanticColors]);
4577
+ const highlightColor = useMemo(() => {
4578
+ var _semanticColors$base3;
4579
+ return themeColor(semanticColors === null || semanticColors === void 0 || (_semanticColors$base3 = semanticColors.base) === null || _semanticColors$base3 === void 0 ? void 0 : _semanticColors$base3.fillSelected, FALLBACK_HIGHLIGHT_COLOR);
4580
+ }, [semanticColors]);
4581
+ const { handleResidueHover, hoveredResidue } = useResidueHoverState(onResidueHover);
4582
+ const handleSelectionClear = useCallback(() => {
4583
+ onSelectionChange === null || onSelectionChange === void 0 || onSelectionChange(null);
4584
+ }, [onSelectionChange]);
4585
+ /**
4586
+ * Chains the selection covers whole, which is what makes a chain caption a
4587
+ * toggle rather than a one-way switch. Keyed on its contents because the
4588
+ * set is pushed into the views Mol* renders, where a fresh object every
4589
+ * render would be a fresh push every render.
4590
+ */
4591
+ const selectedChainsKey = [...(_selection$chains = selection === null || selection === void 0 ? void 0 : selection.chains) !== null && _selection$chains !== void 0 ? _selection$chains : []].sort().join("\0");
4592
+ const selectedChains = useMemo(() => new Set(selectedChainsKey === "" ? [] : selectedChainsKey.split("\0")), [selectedChainsKey]);
4593
+ /**
4594
+ * Clicking a chain selects it; clicking the selected chain again clears it.
4595
+ *
4596
+ * A whole chain is reported as the chain it is, not as the hundreds of
4597
+ * residue indices it stands for, so echoing it back costs nothing. Only a
4598
+ * selection that is exactly this one chain toggles off - with a residue or
4599
+ * another chain also selected, the click is narrowing to this chain rather
4600
+ * than undoing itself.
4601
+ */
4602
+ const handleChainSelect = useCallback((chainId) => {
4603
+ var _selection$chains2, _selection$residues;
4604
+ const isOnlyThisChain = (selection === null || selection === void 0 || (_selection$chains2 = selection.chains) === null || _selection$chains2 === void 0 ? void 0 : _selection$chains2.length) === 1 && selection.chains[0] === chainId && !((_selection$residues = selection.residues) === null || _selection$residues === void 0 ? void 0 : _selection$residues.length);
4605
+ onSelectionChange === null || onSelectionChange === void 0 || onSelectionChange(isOnlyThisChain ? null : { chains: [chainId] });
4606
+ }, [onSelectionChange, selection]);
4607
+ /**
4608
+ * Dims every other chain while a chain's name is pointed at, in the legend
4609
+ * or in the sequence panel's captions, and leaves the selected chain lit
4610
+ * once the pointer has gone.
4611
+ *
4612
+ * Reached through a ref because the two ends need each other: dimming
4613
+ * other chains takes the plugin, which the hook below creates, and that
4614
+ * hook has to be handed the callback to give the captions it renders. This
4615
+ * one is stable and forwards to whatever the highlight hook installs once
4616
+ * there is a plugin for it to talk to.
4617
+ */
4618
+ const highlightChainRef = useRef(() => void 0);
4619
+ const highlightChain = useCallback((chainId) => {
4620
+ highlightChainRef.current(chainId);
4621
+ }, []);
4622
+ const [chains, setChains] = useState([]);
4623
+ const { colors: chainColors, hidden: hiddenChains, toggleChain } = useChains({
4624
+ chainColors: chainColorOverrides,
4625
+ chains,
4626
+ hiddenChains: hiddenChainsProp,
4627
+ onChainVisibilityChange
4628
+ });
4629
+ const { chainColorThemeRef, chains: loadedChains, isReady, loadCount, pluginRef, residuesByChainRef, residueValueThemeRef, setClipRatio } = useMolstarPlugin({
4630
+ backgroundColor: bgColor,
4631
+ chainColors,
4632
+ containerRef: pluginMountRef,
4633
+ download,
4634
+ edgeColor,
4635
+ hasPlddt,
4636
+ hiddenChains,
4637
+ highlightColor,
4638
+ mode,
4639
+ molstarSpec,
4640
+ onChainHover: highlightChain,
4641
+ onChainSelect: handleChainSelect,
4642
+ onChainToggle: toggleChain,
4643
+ onResidueClick,
4644
+ onResidueHover: handleResidueHover,
4645
+ onSelectionChange,
4646
+ onSelectionClear: handleSelectionClear,
4647
+ selectedChains,
4648
+ sequenceViewerBackgroundColor,
4649
+ showAxes,
4650
+ showSequenceViewer,
4651
+ structure: processedStructure
4652
+ });
4653
+ highlightChainRef.current = useChainHighlight({
4654
+ disabled: disableChainHighlightOnHover,
4655
+ hiddenChains,
4656
+ loadCount,
4657
+ pluginRef,
4658
+ selectedChains
4659
+ });
4660
+ useEffect(() => {
4661
+ setChains(loadedChains);
4662
+ }, [loadedChains]);
4663
+ const onChainsChangeRef = useRef(onChainsChange);
4664
+ onChainsChangeRef.current = onChainsChange;
4665
+ useEffect(() => {
4666
+ var _onChainsChangeRef$cu;
4667
+ (_onChainsChangeRef$cu = onChainsChangeRef.current) === null || _onChainsChangeRef$cu === void 0 || _onChainsChangeRef$cu.call(onChainsChangeRef, loadedChains);
4668
+ }, [loadedChains]);
4669
+ useStructureColoring({
4670
+ chainColorThemeRef,
4671
+ chainColors,
4672
+ hasPlddt,
4673
+ isReady,
4674
+ mode,
4675
+ overlay: residueOverlay,
4676
+ pluginRef,
4677
+ residueValueThemeRef
4678
+ });
4679
+ useSelectionFocus({
4680
+ hiddenChains,
4681
+ isReady,
4682
+ pluginRef,
4683
+ selection,
4684
+ setClipRatio
4685
+ });
4686
+ const { hoveredReadout, selectedReadout } = useSelectionReadout({
4687
+ hoveredResidue,
4688
+ isReady,
4689
+ plddt,
4690
+ pluginRef,
4691
+ residueOverlay,
4692
+ residuesByChainRef,
4693
+ selection
4694
+ });
4695
+ const scaleProps = useMemo(() => resolveScaleProps(residueOverlay, hasPlddt), [residueOverlay, hasPlddt]);
4696
+ /**
4697
+ * What a chain's swatch can show follows whatever is painting the
4698
+ * structure, in the same order the color key resolves in.
4699
+ *
4700
+ * Chain coloring gives each chain one color of its own. pLDDT gives every
4701
+ * chain the same four bands, which says they are colored by confidence
4702
+ * rather than telling them apart - so the swatch carries the whole key,
4703
+ * quartered. An overlay is continuous and has no discrete colors to put in
4704
+ * a swatch at all, so the rows keep their labels and toggles and the color
4705
+ * key beside them does the describing.
4706
+ */
4707
+ const chainColoringActive = !residueOverlay && !hasPlddt;
4708
+ const plddtColoringActive = !residueOverlay && hasPlddt;
4709
+ return /* @__PURE__ */ jsxs(ViewerRoot, _objectSpread2(_objectSpread2({
4710
+ ref,
4711
+ showSequenceViewer
4712
+ }, rest), {}, { children: [/* @__PURE__ */ jsx(PluginMount, { ref: pluginMountRef }), showLegend && /* @__PURE__ */ jsx(StructureLegend, _objectSpread2({
4713
+ chainBandColors: plddtColoringActive ? PLDDT_BAND_COLORS : void 0,
4714
+ chainColors: chainColoringActive ? chainColors : void 0,
4715
+ chains: showChainLegend ? chains : [],
4716
+ hiddenChains,
4717
+ hoveredResidue: hoveredReadout,
4718
+ onChainHover: highlightChain,
4719
+ onChainSelect: handleChainSelect,
4720
+ onChainToggle: toggleChain,
4721
+ selectedChains,
4722
+ selectedResidue: selectedReadout,
4723
+ showSequenceViewer,
4724
+ stats: stats !== null && stats !== void 0 ? stats : []
4725
+ }, scaleProps))] }));
4726
+ }));
4727
+ //#endregion
4728
+ export { injectPlddtIntoMmcif as a, injectPlddt as i, DOWNLOAD_RESOLUTIONS as n, injectPlddtIntoPdb as o, PLDDT_COLOR_SCALE as r, detectStructureFormat as s, ProteinStructureViewer_default as t };