@czi-sds/data-viz 2.1.1 → 2.3.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.
package/dist/index.esm.js CHANGED
@@ -1,17 +1,19 @@
1
1
  "use client";
2
2
  import { init } from "echarts";
3
- import { Fragment, cloneElement, forwardRef, memo, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { Fragment, cloneElement, createContext, forwardRef, memo, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
4
4
  import { throttle } from "lodash";
5
5
  import styled from "@emotion/styled";
6
6
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
7
7
  import { Button, Legend, Theme, Tooltip, TooltipTable, defaultTheme, fontBodyXs, fontBodyXxxs, fontCodeXs, fontHeaderM, fontHeaderS, fontTabularSemiboldXxxxs, generateDiscreteColors, getCorners, getMode, getSemanticColors, getSpaces } from "@czi-sds/components";
8
8
  import { ThemeProvider, useTheme } from "@mui/material/styles";
9
- import { ArrowCounterClockwiseIcon, CheckIcon, CopyIcon, QuestionIcon } from "@phosphor-icons/react";
9
+ import { ApertureIcon, ArrowCounterClockwiseIcon, CheckIcon, CopyIcon, EyeIcon, EyeSlashIcon, QuestionIcon } from "@phosphor-icons/react";
10
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";
11
12
  import { createPluginUI } from "molstar/lib/mol-plugin-ui";
12
13
  import { renderReact18 } from "molstar/lib/mol-plugin-ui/react18";
13
14
  import { DefaultPluginUISpec } from "molstar/lib/mol-plugin-ui/spec";
14
15
  import { PluginBehaviors } from "molstar/lib/mol-plugin/behavior";
16
+ import { setSubtreeVisibility } from "molstar/lib/mol-plugin/behavior/static/state";
15
17
  import { PluginConfig } from "molstar/lib/mol-plugin/config";
16
18
  import { Representation } from "molstar/lib/mol-repr/representation";
17
19
  import { BehaviorSubject, Subject } from "rxjs";
@@ -28,10 +30,14 @@ import { arrayEqual } from "molstar/lib/mol-util";
28
30
  import { ParamDefinition } from "molstar/lib/mol-util/param-definition";
29
31
  import { Toasts } from "molstar/lib/mol-plugin-ui/toast";
30
32
  import { Viewport } from "molstar/lib/mol-plugin-ui/viewport";
33
+ import { Color } from "molstar/lib/mol-util/color";
31
34
  import { PluginCommands } from "molstar/lib/mol-plugin/commands";
32
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";
33
39
  import { CustomElementProperty } from "molstar/lib/mol-model-props/common/custom-element-property";
34
- import { Color } from "molstar/lib/mol-util/color";
40
+ import { StructureFocusRepresentation } from "molstar/lib/mol-plugin/behavior/dynamic/selection/structure-focus-representation";
35
41
  //#region src/common/colorScales.ts
36
42
  /**
37
43
  * Perceptually uniform sequential scale (matplotlib's plasma), the default for
@@ -549,6 +555,191 @@ var HeatmapChart_default = memo(forwardRef((props, ref) => {
549
555
  else ref.current = element;
550
556
  }
551
557
  }));
558
+ //#endregion
559
+ //#region src/core/ProteinStructureViewer/components/ChainLegend/style.ts
560
+ /** Opacity applied to a hidden chain's row, so it reads as off but reachable. */
561
+ const HIDDEN_OPACITY = .4;
562
+ /** Side of the color swatch. */
563
+ const SWATCH_SIZE = 8;
564
+ /**
565
+ * The rows, stacked and right-aligned against the color key beside them.
566
+ *
567
+ * Pointer events are switched back on here: the legend overlay turns them off
568
+ * so drags meant for the structure are not intercepted, and this is one of the
569
+ * two places in it that has to be clickable.
570
+ */
571
+ const ChainRowList = styled("div")`
572
+ display: flex;
573
+ flex-direction: column;
574
+ align-items: flex-end;
575
+ pointer-events: auto;
576
+ max-height: 80px;
577
+ overflow-y: auto;
578
+ `;
579
+ const ChainRow = styled("div")`
580
+ display: flex;
581
+ align-items: center;
582
+
583
+ ${(props) => {
584
+ const spaces = getSpaces(props);
585
+ return `
586
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
587
+ `;
588
+ }}
589
+ `;
590
+ const ChainSwatch = styled("div")`
591
+ flex: none;
592
+ width: ${SWATCH_SIZE}px;
593
+ height: ${SWATCH_SIZE}px;
594
+ border-radius: 1px;
595
+
596
+ ${(props) => `
597
+ background-color: ${props.swatchColor};
598
+ opacity: ${props.isHidden ? HIDDEN_OPACITY : 1};
599
+ `}
600
+ `;
601
+ /**
602
+ * A swatch quartered into a grid, for a coloring no single color stands for.
603
+ *
604
+ * Occupies the same box as the solid swatch so the rows stay aligned whichever
605
+ * one a chain gets, with a hairline gap between the quadrants to read as four
606
+ * colors rather than one blurred square.
607
+ */
608
+ const ChainSwatchGrid = styled("div")`
609
+ flex: none;
610
+ display: grid;
611
+ grid-template-columns: repeat(2, 1fr);
612
+ grid-template-rows: repeat(2, 1fr);
613
+ gap: 0px;
614
+ width: ${SWATCH_SIZE}px;
615
+ height: ${SWATCH_SIZE}px;
616
+ border-radius: 1px;
617
+ overflow: hidden;
618
+
619
+ ${(props) => `
620
+ opacity: ${props.isHidden ? HIDDEN_OPACITY : 1};
621
+ `}
622
+ `;
623
+ const ChainSwatchQuadrant = styled("div")`
624
+ ${(props) => `
625
+ background-color: ${props.swatchColor};
626
+ `}
627
+ `;
628
+ /**
629
+ * Selects the whole chain, or clears it when it is already the selection. A
630
+ * button so it is reachable from the keyboard.
631
+ */
632
+ const ChainLabel$1 = styled("button")`
633
+ ${fontBodyXxxs}
634
+
635
+ padding: 0;
636
+ border: none;
637
+ background: none;
638
+
639
+ ${(props) => {
640
+ var _semanticColors$base, _semanticColors$base2, _semanticColors$base3;
641
+ const semanticColors = getSemanticColors(props);
642
+ return `
643
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.textSecondary};
644
+ cursor: ${props.isHidden ? "default" : "pointer"};
645
+ font-weight: ${props.isSelected ? 600 : "inherit"};
646
+ opacity: ${props.isHidden ? HIDDEN_OPACITY : 1};
647
+
648
+ &:hover {
649
+ 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};
650
+ }
651
+ `;
652
+ }}
653
+ `;
654
+ const VisibilityToggle = styled("button")`
655
+ display: flex;
656
+ align-items: center;
657
+ padding: 0;
658
+ border: none;
659
+ background: none;
660
+ cursor: pointer;
661
+ margin-top: 1px;
662
+
663
+ ${(props) => {
664
+ var _semanticColors$base4, _semanticColors$base5;
665
+ const semanticColors = getSemanticColors(props);
666
+ return `
667
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base4 = semanticColors.base) === null || _semanticColors$base4 === void 0 ? void 0 : _semanticColors$base4.textTertiaryOnDark};
668
+
669
+ &:hover {
670
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base5 = semanticColors.base) === null || _semanticColors$base5 === void 0 ? void 0 : _semanticColors$base5.textPrimary};
671
+ }
672
+
673
+ svg {
674
+ display: block;
675
+ }
676
+ `;
677
+ }}
678
+ `;
679
+ //#endregion
680
+ //#region src/core/ProteinStructureViewer/components/ChainLegend/index.tsx
681
+ /**
682
+ * Lists the structure's chains, each with its color and a visibility toggle.
683
+ *
684
+ * Only drawn for a complex: one chain needs no key to tell it from anything,
685
+ * and hiding it would leave an empty canvas with no way back. Its home is the
686
+ * legend rather than the sequence panel so that it survives
687
+ * `showSequenceViewer={false}`, where the chains would otherwise have nowhere
688
+ * to be listed.
689
+ */
690
+ function ChainLegend({ bandColors, chainColors, chains, hiddenChains, onChainHover, onChainSelect, onChainToggle, selectedChains }) {
691
+ if (chains.length < 2) return null;
692
+ return /* @__PURE__ */ jsx(ChainRowList, { children: chains.map((chain) => {
693
+ var _selectedChains$has;
694
+ const hidden = hiddenChains.has(chain.chainId);
695
+ const selected = (_selectedChains$has = selectedChains === null || selectedChains === void 0 ? void 0 : selectedChains.has(chain.chainId)) !== null && _selectedChains$has !== void 0 ? _selectedChains$has : false;
696
+ const color = chainColors === null || chainColors === void 0 ? void 0 : chainColors.get(chain.chainId);
697
+ return /* @__PURE__ */ jsxs(ChainRow, {
698
+ onBlur: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(null),
699
+ onFocus: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(chain.chainId),
700
+ onMouseEnter: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(chain.chainId),
701
+ onMouseLeave: () => onChainHover === null || onChainHover === void 0 ? void 0 : onChainHover(null),
702
+ children: [
703
+ /* @__PURE__ */ jsx(Tooltip, {
704
+ arrow: true,
705
+ placement: "top",
706
+ disableInteractive: true,
707
+ title: hidden ? `Chain ${chain.label} is hidden` : `Click to ${selected ? "deselect" : "select"} Chain ${chain.label}`,
708
+ children: /* @__PURE__ */ jsxs(ChainLabel$1, {
709
+ "aria-pressed": selected,
710
+ disabled: hidden,
711
+ isHidden: hidden,
712
+ isSelected: selected,
713
+ onClick: () => onChainSelect(chain.chainId),
714
+ type: "button",
715
+ children: ["Chain ", chain.label]
716
+ })
717
+ }),
718
+ color !== void 0 && /* @__PURE__ */ jsx(ChainSwatch, {
719
+ isHidden: hidden,
720
+ swatchColor: color
721
+ }),
722
+ color === void 0 && bandColors !== void 0 && /* @__PURE__ */ jsx(ChainSwatchGrid, {
723
+ isHidden: hidden,
724
+ children: bandColors.map((band) => /* @__PURE__ */ jsx(ChainSwatchQuadrant, { swatchColor: band }, band))
725
+ }),
726
+ /* @__PURE__ */ jsx(Tooltip, {
727
+ arrow: true,
728
+ placement: "top",
729
+ disableInteractive: true,
730
+ title: hidden ? `Show Chain ${chain.label}` : `Hide Chain ${chain.label}`,
731
+ children: /* @__PURE__ */ jsx(VisibilityToggle, {
732
+ "aria-label": `${hidden ? "Show" : "Hide"} chain ${chain.label}`,
733
+ "aria-pressed": hidden,
734
+ onClick: () => onChainToggle(chain.chainId),
735
+ type: "button",
736
+ children: hidden ? /* @__PURE__ */ jsx(EyeSlashIcon, { size: 12 }) : /* @__PURE__ */ jsx(EyeIcon, { size: 12 })
737
+ })
738
+ })
739
+ ]
740
+ }, chain.chainId);
741
+ }) });
742
+ }
552
743
  /** Height of the color bar itself. */
553
744
  const BAR_HEIGHT = 8;
554
745
  /**
@@ -673,14 +864,24 @@ const ViewerRoot = styled("div")`
673
864
  height: 100% !important;
674
865
  }
675
866
 
676
- /* Mol* chrome that the custom viewport and sequence panel replace. */
677
- .msp-plugin .msp-viewport-controls-buttons,
678
- .msp-plugin .msp-layout-expanded,
679
- .msp-plugin .msp-log,
680
- .msp-plugin .msp-left-panel-controls,
681
- .msp-plugin .msp-layout-region.msp-layout-left,
682
- .msp-plugin .msp-layout-region.msp-layout-right,
683
- .msp-plugin .msp-layout-region.msp-layout-bottom {
867
+ /*
868
+ * The expanded layout is kept hidden because it is the one piece of Mol*
869
+ * chrome that would escape this container: it takes the plugin out of the
870
+ * box it was given and over the page.
871
+ *
872
+ * Its neighbours used to be here too - the viewport's icon column, and the
873
+ * left, right and bottom regions. They are not any more, because hiding them
874
+ * from here made them unreachable: Mol* already gates each of them behind a
875
+ * PluginConfig.Viewport flag and behind layout.initial.regionState, both of
876
+ * which a consumer can set through molstarSpec, and a display:none on top of
877
+ * that overrode the answer. None of them shows by default - the viewer's own
878
+ * flags and region state are what keep them away - so this only has to stay
879
+ * out of their way.
880
+ *
881
+ * No backticks in here: this is inside a template literal, and one would end
882
+ * it.
883
+ */
884
+ .msp-plugin .msp-layout-expanded {
684
885
  display: none !important;
685
886
  }
686
887
 
@@ -831,6 +1032,18 @@ const StatsGrid = styled("div")`
831
1032
  `;
832
1033
  }}
833
1034
  `;
1035
+ const ChainScaleColumn = styled("div")`
1036
+ display: flex;
1037
+ flex-direction: column;
1038
+ align-items: flex-end;
1039
+
1040
+ ${(props) => {
1041
+ const spaces = getSpaces(props);
1042
+ return `
1043
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.l}px;
1044
+ `;
1045
+ }}
1046
+ `;
834
1047
  const StatColumnWrapper = styled("div")`
835
1048
  display: flex;
836
1049
  flex-direction: column;
@@ -923,6 +1136,19 @@ function StatColumn({ label, value }) {
923
1136
  return /* @__PURE__ */ jsxs(StatColumnWrapper, { children: [/* @__PURE__ */ jsx(StatValue, { children: value }), /* @__PURE__ */ jsx(StatLabel, { children: label })] });
924
1137
  }
925
1138
  /**
1139
+ * Builds one readout slot.
1140
+ *
1141
+ * A readout covering several residues reports a mean, and the label says so:
1142
+ * calling it "pLDDT" while it averages ninety of them would read as a single
1143
+ * residue's score.
1144
+ */
1145
+ function readoutSlot(label, value, residueCount) {
1146
+ return {
1147
+ label: residueCount > 1 ? `Mean ${label}` : label,
1148
+ value: value !== null ? value.toFixed(VALUE_PRECISION) : MISSING_VALUE
1149
+ };
1150
+ }
1151
+ /**
926
1152
  * Stats and color key overlaid on the structure viewer.
927
1153
  *
928
1154
  * When a residue is selected or hovered, the whole-structure stats are replaced
@@ -932,24 +1158,19 @@ function StatColumn({ label, value }) {
932
1158
  * residue takes priority so the user can inspect others without losing their
933
1159
  * selection.
934
1160
  */
935
- function StructureLegend({ hoveredResidue = null, scale, scaleLabel, scaleMax = null, scaleMin = 0, scaleTooltip, scaleTooltipProps, selectedResidue = null, showSequenceViewer, stats, valueLabel }) {
936
- var _stats$, _stats$2, _stats$3;
1161
+ 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 }) {
1162
+ var _activeResidue$residu, _stats$, _stats$2, _stats$3;
937
1163
  const activeResidue = hoveredResidue !== null && hoveredResidue !== void 0 ? hoveredResidue : selectedResidue;
938
1164
  const showResidue = activeResidue !== null;
939
1165
  const showValue = showResidue && valueLabel !== void 0;
1166
+ const residueCount = (_activeResidue$residu = activeResidue === null || activeResidue === void 0 ? void 0 : activeResidue.residueCount) !== null && _activeResidue$residu !== void 0 ? _activeResidue$residu : 1;
940
1167
  const slots = [
941
1168
  showResidue ? {
942
- label: "Residue",
1169
+ label: residueCount > 1 ? "Selection" : "Residue",
943
1170
  value: activeResidue.label
944
1171
  } : (_stats$ = stats[0]) !== null && _stats$ !== void 0 ? _stats$ : null,
945
- showValue ? {
946
- label: valueLabel,
947
- value: activeResidue.value !== null ? activeResidue.value.toFixed(VALUE_PRECISION) : MISSING_VALUE
948
- } : (_stats$2 = stats[1]) !== null && _stats$2 !== void 0 ? _stats$2 : null,
949
- showResidue ? {
950
- label: "pLDDT",
951
- value: activeResidue.plddt !== null ? activeResidue.plddt.toFixed(VALUE_PRECISION) : MISSING_VALUE
952
- } : (_stats$3 = stats[2]) !== null && _stats$3 !== void 0 ? _stats$3 : null
1172
+ showValue ? readoutSlot(valueLabel, activeResidue.value, residueCount) : (_stats$2 = stats[1]) !== null && _stats$2 !== void 0 ? _stats$2 : null,
1173
+ showResidue ? readoutSlot("pLDDT", activeResidue.plddt, residueCount) : (_stats$3 = stats[2]) !== null && _stats$3 !== void 0 ? _stats$3 : null
953
1174
  ];
954
1175
  return /* @__PURE__ */ jsxs(LegendOverlay, {
955
1176
  showSequenceViewer,
@@ -960,7 +1181,16 @@ function StructureLegend({ hoveredResidue = null, scale, scaleLabel, scaleMax =
960
1181
  label: slot.label,
961
1182
  value: slot.value
962
1183
  }, i) : /* @__PURE__ */ jsx("div", {}, i);
963
- }) }), scale && /* @__PURE__ */ jsxs(ScaleColumn, { children: [/* @__PURE__ */ jsx(ColorScaleLegend, {
1184
+ }) }), /* @__PURE__ */ jsxs(ChainScaleColumn, { children: [onChainToggle && onChainSelect && /* @__PURE__ */ jsx(ChainLegend, {
1185
+ bandColors: chainBandColors,
1186
+ chainColors,
1187
+ chains,
1188
+ hiddenChains: hiddenChains !== null && hiddenChains !== void 0 ? hiddenChains : /* @__PURE__ */ new Set(),
1189
+ onChainHover,
1190
+ onChainSelect,
1191
+ onChainToggle,
1192
+ selectedChains
1193
+ }), scale && /* @__PURE__ */ jsxs(ScaleColumn, { children: [/* @__PURE__ */ jsx(ColorScaleLegend, {
964
1194
  max: scaleMax,
965
1195
  min: scaleMin,
966
1196
  scale
@@ -973,8 +1203,281 @@ function StructureLegend({ hoveredResidue = null, scale, scaleLabel, scaleMax =
973
1203
  size: 10,
974
1204
  weight: "bold"
975
1205
  }) })
976
- }))] })] })]
1206
+ }))] })] })] })]
1207
+ });
1208
+ }
1209
+ //#endregion
1210
+ //#region \0@oxc-project+runtime@0.134.0/helpers/esm/asyncToGenerator.js
1211
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
1212
+ try {
1213
+ var i = n[a](c), u = i.value;
1214
+ } catch (n) {
1215
+ e(n);
1216
+ return;
1217
+ }
1218
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
1219
+ }
1220
+ function _asyncToGenerator(n) {
1221
+ return function() {
1222
+ var t = this, e = arguments;
1223
+ return new Promise(function(r, o) {
1224
+ var a = n.apply(t, e);
1225
+ function _next(n) {
1226
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
1227
+ }
1228
+ function _throw(n) {
1229
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
1230
+ }
1231
+ _next(void 0);
1232
+ });
1233
+ };
1234
+ }
1235
+ //#endregion
1236
+ //#region src/core/ProteinStructureViewer/hooks/useChainHighlight.ts
1237
+ /**
1238
+ * How transparent the other chains go while one is pointed at.
1239
+ *
1240
+ * Enough that the chain under the pointer is the one being read, not enough
1241
+ * that the rest of the complex stops being context for it. 0 is opaque, 1 is
1242
+ * invisible.
1243
+ */
1244
+ const CHAIN_DIM_TRANSPARENCY = .65;
1245
+ /**
1246
+ * The chain id in a component key.
1247
+ *
1248
+ * Chain components are tagged `structure-component-<part>-<chainId>`, and a
1249
+ * key is the component's tags sorted and joined with commas. Anchoring on the
1250
+ * part name and stopping at the comma is what keeps `A` from also matching the
1251
+ * chain named `AA`.
1252
+ */
1253
+ const COMPONENT_CHAIN_ID = /structure-component-(?:polymer|ligand)-([^,]+)/;
1254
+ /** The chain a component was built for, or undefined if it is not a chain's. */
1255
+ function componentChainId(component) {
1256
+ var _component$key, _COMPONENT_CHAIN_ID$e;
1257
+ const key = (_component$key = component.key) !== null && _component$key !== void 0 ? _component$key : component.cell.transform.ref;
1258
+ return (_COMPONENT_CHAIN_ID$e = COMPONENT_CHAIN_ID.exec(key)) === null || _COMPONENT_CHAIN_ID$e === void 0 ? void 0 : _COMPONENT_CHAIN_ID$e[1];
1259
+ }
1260
+ /** Every chain component of every loaded structure, polymers and ligands. */
1261
+ function structureComponents(plugin) {
1262
+ return plugin.managers.structure.hierarchy.current.structures.flatMap((entry) => entry.components);
1263
+ }
1264
+ /** A set of chain ids as one comparable string. */
1265
+ function chainsKey(chains) {
1266
+ return [...chains].sort().join("\0");
1267
+ }
1268
+ /**
1269
+ * Makes every chain outside `lit` transparent, or all of them opaque again when
1270
+ * nothing is lit.
1271
+ *
1272
+ * Transparency layers accumulate, so what is already there is cleared before
1273
+ * the next chain is dimmed rather than added to - otherwise moving along the
1274
+ * list would leave every chain it passed dimmed behind it.
1275
+ *
1276
+ * False when there is no structure to write to yet, which is what a selection
1277
+ * arriving before the first load looks like. It is applied again after the load
1278
+ * rather than being taken as done.
1279
+ */
1280
+ function dimChainsOutside(_x2, _x3) {
1281
+ return _dimChainsOutside.apply(this, arguments);
1282
+ }
1283
+ function _dimChainsOutside() {
1284
+ _dimChainsOutside = _asyncToGenerator(function* (plugin, lit) {
1285
+ const components = structureComponents(plugin);
1286
+ if (components.length === 0) return false;
1287
+ yield clearStructureTransparency(plugin, components);
1288
+ if (lit.size === 0) return true;
1289
+ const dimmed = components.filter((component) => {
1290
+ const chainId = componentChainId(component);
1291
+ return chainId !== void 0 && !lit.has(chainId);
1292
+ });
1293
+ if (dimmed.length === 0) return true;
1294
+ yield setStructureTransparency(plugin, dimmed, CHAIN_DIM_TRANSPARENCY, function() {
1295
+ var _ref = _asyncToGenerator(function* (structure) {
1296
+ return Structure.toStructureElementLoci(structure);
1297
+ });
1298
+ return function(_x) {
1299
+ return _ref.apply(this, arguments);
1300
+ };
1301
+ }());
1302
+ return true;
1303
+ });
1304
+ return _dimChainsOutside.apply(this, arguments);
1305
+ }
1306
+ /**
1307
+ * Leaves one chain lit and dims the rest: the chain whose name is pointed at,
1308
+ * in the sequence panel's captions or the chain legend's rows, or the chain the
1309
+ * selection covers once the pointer has gone.
1310
+ *
1311
+ * The chain left lit is exactly as it was - in the chain palette, in pLDDT
1312
+ * bands, or in an overlay - and the others recede around it. Nothing is painted
1313
+ * over the top, so what the reader is being pointed at is still the color the
1314
+ * legend beside it is describing, and a selected chain reads the same as a
1315
+ * hovered one rather than sprouting a highlight of its own.
1316
+ *
1317
+ * A hover outranks the selection while it lasts, since pointing at a chain is a
1318
+ * question about that chain, and hands it back on the way out.
1319
+ *
1320
+ * Dimming is a state-tree commit rather than a renderer setting, so it is
1321
+ * applied one at a time and coalesced: a pointer crossing the list faster than
1322
+ * a commit finishes skips the chains it passed over and settles on the one it
1323
+ * came to rest on, instead of working through a queue of hovers that have
1324
+ * already been left.
1325
+ */
1326
+ function useChainHighlight({ disabled, hiddenChains, loadCount, pluginRef, selectedChains }) {
1327
+ const hoveredRef = useRef(null);
1328
+ /**
1329
+ * The chains left lit on the canvas as it stands. A freshly loaded structure
1330
+ * carries no dimming at all, which is what the empty key means.
1331
+ */
1332
+ const shownRef = useRef(chainsKey(/* @__PURE__ */ new Set()));
1333
+ const committingRef = useRef(false);
1334
+ /**
1335
+ * Read when a commit comes round rather than closed over, so one already in
1336
+ * flight settles on the current props instead of the ones it started under.
1337
+ */
1338
+ const propsRef = useRef({
1339
+ disabled,
1340
+ hiddenChains,
1341
+ selectedChains
1342
+ });
1343
+ propsRef.current = {
1344
+ disabled,
1345
+ hiddenChains,
1346
+ selectedChains
1347
+ };
1348
+ const litChains = useCallback(() => {
1349
+ const { disabled: hoverOff, hiddenChains: hidden, selectedChains: selected } = propsRef.current;
1350
+ const hovered = hoveredRef.current;
1351
+ if (!hoverOff && hovered !== null && !hidden.has(hovered)) return new Set([hovered]);
1352
+ return new Set([...selected].filter((chainId) => !hidden.has(chainId)));
1353
+ }, []);
1354
+ const settle = useCallback(_asyncToGenerator(function* () {
1355
+ if (committingRef.current) return;
1356
+ committingRef.current = true;
1357
+ try {
1358
+ while (pluginRef.current) {
1359
+ const lit = litChains();
1360
+ const key = chainsKey(lit);
1361
+ if (key === shownRef.current) break;
1362
+ if (!(yield dimChainsOutside(pluginRef.current, lit))) break;
1363
+ shownRef.current = key;
1364
+ }
1365
+ } catch (error) {
1366
+ console.error("Failed to dim chains:", error);
1367
+ } finally {
1368
+ committingRef.current = false;
1369
+ }
1370
+ }), [litChains, pluginRef]);
1371
+ const highlightChain = useCallback((chainId) => {
1372
+ hoveredRef.current = chainId;
1373
+ settle();
1374
+ }, [settle]);
1375
+ useEffect(() => {
1376
+ settle();
1377
+ }, [
1378
+ disabled,
1379
+ hiddenChains,
1380
+ selectedChains,
1381
+ settle
1382
+ ]);
1383
+ useEffect(() => {
1384
+ shownRef.current = chainsKey(/* @__PURE__ */ new Set());
1385
+ settle();
1386
+ }, [loadCount, settle]);
1387
+ return highlightChain;
1388
+ }
1389
+ //#endregion
1390
+ //#region src/common/chainColors.ts
1391
+ /**
1392
+ * Default colors for telling chains apart, in assignment order.
1393
+ *
1394
+ * The Okabe-Ito qualitative palette, which is built to stay distinguishable
1395
+ * under every common form of color blindness - the reason to prefer it over a
1396
+ * hand-picked set, since a complex is read by which chain is which and a
1397
+ * viewer that collapses two of them into one color stops answering that.
1398
+ *
1399
+ * Its black is left out: the canvas inverts with the theme, so a chain painted
1400
+ * black would vanish against the dark background. The rest carry enough
1401
+ * lightness to hold up against both.
1402
+ *
1403
+ * Chains past the end of the palette wrap around to the start.
1404
+ */
1405
+ const CHAIN_COLOR_PALETTE = [
1406
+ "#009E73",
1407
+ "#0072B2",
1408
+ "#E69F00",
1409
+ "#CC79A7",
1410
+ "#56B4E9",
1411
+ "#D55E00",
1412
+ "#F0E442"
1413
+ ];
1414
+ /**
1415
+ * Assigns each chain a color, in the order given, with `overrides` taking
1416
+ * precedence by `chainId`.
1417
+ *
1418
+ * Palette positions are spent on every chain whether or not it is overridden,
1419
+ * so overriding one chain does not shift the colors of the others.
1420
+ */
1421
+ function chainColorMap(chainIds, overrides) {
1422
+ const colors = /* @__PURE__ */ new Map();
1423
+ chainIds.forEach((chainId, i) => {
1424
+ var _overrides$chainId;
1425
+ const fallback = CHAIN_COLOR_PALETTE[i % CHAIN_COLOR_PALETTE.length];
1426
+ colors.set(chainId, (_overrides$chainId = overrides === null || overrides === void 0 ? void 0 : overrides[chainId]) !== null && _overrides$chainId !== void 0 ? _overrides$chainId : fallback);
977
1427
  });
1428
+ return colors;
1429
+ }
1430
+ //#endregion
1431
+ //#region src/core/ProteinStructureViewer/hooks/useChains.ts
1432
+ /**
1433
+ * Reconciles the chains found in the structure with the visibility and coloring
1434
+ * the consumer asked for.
1435
+ *
1436
+ * Visibility is controlled when `hiddenChains` is passed and owned here when it
1437
+ * is not, so the legend's toggles work out of the box without taking the
1438
+ * decision away from a consumer that wants it. `onChainVisibilityChange` fires
1439
+ * either way: a consumer that only wants to follow along should not have to
1440
+ * take ownership to hear about it.
1441
+ */
1442
+ function useChains({ chainColors, chains, hiddenChains, onChainVisibilityChange }) {
1443
+ const isControlled = hiddenChains !== void 0;
1444
+ const [ownHidden, setOwnHidden] = useState([]);
1445
+ const onChainVisibilityChangeRef = useRef(onChainVisibilityChange);
1446
+ onChainVisibilityChangeRef.current = onChainVisibilityChange;
1447
+ const chainIds = useMemo(() => chains.map((c) => c.chainId), [chains]);
1448
+ /**
1449
+ * Chains the structure no longer has cannot be unhidden through the legend,
1450
+ * since it has no row for them, so a stale id would hide a chain that shares
1451
+ * its name in the next structure. Only the uncontrolled side is pruned; a
1452
+ * controlled consumer owns its own list.
1453
+ */
1454
+ useEffect(() => {
1455
+ if (isControlled) return;
1456
+ setOwnHidden((prev) => {
1457
+ const kept = prev.filter((id) => chainIds.includes(id));
1458
+ return kept.length === prev.length ? prev : kept;
1459
+ });
1460
+ }, [chainIds, isControlled]);
1461
+ const hiddenKey = [...isControlled ? hiddenChains : ownHidden].sort().join("\0");
1462
+ const hidden = useMemo(() => new Set(hiddenKey === "" ? [] : hiddenKey.split("\0")), [hiddenKey]);
1463
+ return {
1464
+ colors: useMemo(() => chainColorMap(chainIds, chainColors), [chainIds.map((id) => {
1465
+ var _chainColors$id;
1466
+ return `${id}:${(_chainColors$id = chainColors === null || chainColors === void 0 ? void 0 : chainColors[id]) !== null && _chainColors$id !== void 0 ? _chainColors$id : ""}`;
1467
+ }).join("\0")]),
1468
+ hidden,
1469
+ toggleChain: useCallback((chainId) => {
1470
+ var _onChainVisibilityCha;
1471
+ const next = hidden.has(chainId) ? [...hidden].filter((id) => id !== chainId) : [...hidden, chainId];
1472
+ const ordered = chainIds.filter((id) => next.includes(id));
1473
+ if (!isControlled) setOwnHidden(ordered);
1474
+ (_onChainVisibilityCha = onChainVisibilityChangeRef.current) === null || _onChainVisibilityCha === void 0 || _onChainVisibilityCha.call(onChainVisibilityChangeRef, ordered);
1475
+ }, [
1476
+ chainIds,
1477
+ hidden,
1478
+ isControlled
1479
+ ])
1480
+ };
978
1481
  }
979
1482
  //#endregion
980
1483
  //#region src/core/ProteinStructureViewer/utils/theme.ts
@@ -1036,7 +1539,7 @@ function useSubscribe(observable, handler) {
1036
1539
  */
1037
1540
  function useViewSetting(settings, select) {
1038
1541
  const [value, setValue] = useState(() => select(settings.value));
1039
- useSubscribe(settings, (next) => setValue(select(next)));
1542
+ useSubscribe(settings, (next) => setValue(() => select(next)));
1040
1543
  return value;
1041
1544
  }
1042
1545
  //#endregion
@@ -1065,72 +1568,427 @@ const HOVER_THROTTLE_MS = 3 * 16.666;
1065
1568
  /** How long the copy button shows its confirmation state. */
1066
1569
  const COPIED_FEEDBACK_MS = 2e3;
1067
1570
  //#endregion
1068
- //#region src/core/ProteinStructureViewer/hooks/usePlugin.ts
1069
- /**
1070
- * The plugin owning the React root this component renders in.
1071
- *
1072
- * Mol* renders its view components inside its own root and provides the plugin
1073
- * through this context, which is what `PluginUIComponent` reads to populate
1074
- * `this.plugin`.
1075
- */
1076
- function usePlugin() {
1077
- return useContext(PluginReactContext);
1078
- }
1079
- //#endregion
1080
- //#region src/core/ProteinStructureViewer/components/SequenceView/utils/residue.ts
1081
- /** Reads the sequence index off a residue span, or undefined if it is not one. */
1082
- function readSeqIdx(el) {
1083
- if (!el || !el.getAttribute) return void 0;
1084
- return el.hasAttribute("data-seqid") ? +el.getAttribute(SEQ_ID_ATTR) : void 0;
1085
- }
1086
- /**
1087
- * Nearest ancestor that scrolls vertically, or null if none. Used to scope the
1088
- * residue tooltip's hide-on-scroll listener to the sequence's own overflow
1089
- * container instead of a global window listener.
1090
- */
1091
- function getScrollParent(node) {
1092
- var _node$parentElement;
1093
- let el = (_node$parentElement = node === null || node === void 0 ? void 0 : node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : null;
1094
- while (el) {
1095
- const overflowY = getComputedStyle(el).overflowY;
1096
- if (overflowY === "auto" || overflowY === "scroll") return el;
1097
- el = el.parentElement;
1098
- }
1099
- return null;
1100
- }
1101
- function getResidueClass(sequenceWrapper, seqIdx) {
1102
- return sequenceWrapper.isHighlighted(seqIdx) || sequenceWrapper.isSelected(seqIdx) || sequenceWrapper.isFocused(seqIdx) ? "msp-sequence-present msp-sequence-residue-active" : "msp-sequence-present msp-sequence-residue";
1103
- }
1104
- /**
1105
- * The label shown above a residue: its author sequence id for atomic units,
1106
- * or a 1-based position for coarse ones.
1107
- *
1108
- * `location` is a scratch object the caller reuses across residues, since this
1109
- * runs once per numbered residue on every render.
1110
- */
1111
- function getSequenceNumber(sequenceWrapper, seqIdx, location) {
1112
- let seqNum = "";
1113
- const loci = sequenceWrapper.getLoci(seqIdx);
1114
- const l = StructureElement.Loci.getFirstLocation(loci, location);
1115
- if (l) {
1116
- if (Unit.isAtomic(l.unit)) {
1117
- const seqId = StructureProperties.residue.auth_seq_id(l);
1118
- const insCode = StructureProperties.residue.pdbx_PDB_ins_code(l);
1119
- seqNum = `${seqId}${insCode ? insCode : ""}`;
1120
- } else if (Unit.isCoarse(l.unit)) seqNum = `${seqIdx + 1}`;
1121
- }
1122
- return seqNum;
1123
- }
1124
- /**
1125
- * How often a sequence number is drawn above the residues.
1126
- *
1127
- * Long sequences get one every ten residues. Short ones number every residue,
1128
- * unless their numbers run to more than one digit, which would crowd them.
1129
- */
1130
- function resolveSequenceNumberPeriod(sequenceWrapper, location, sequenceNumberPeriod) {
1131
- if (sequenceNumberPeriod !== void 0) return sequenceNumberPeriod;
1132
- if (sequenceWrapper.length > 10) return 10;
1133
- if (getSequenceNumber(sequenceWrapper, sequenceWrapper.length - 1, location).length > 1) return 5;
1571
+ //#region src/core/ProteinStructureViewer/components/SequenceView/style.ts
1572
+ /** Height of the fade that masks residues scrolling under the panel header. */
1573
+ const SCROLL_FADE_HEIGHT = 8;
1574
+ const SequencePanel = styled("div")`
1575
+ display: flex;
1576
+ flex-direction: column;
1577
+ height: 100%;
1578
+
1579
+ ${(props) => {
1580
+ var _semanticColors$base, _props$backgroundColo, _semanticColors$base2;
1581
+ const spaces = getSpaces(props);
1582
+ const semanticColors = getSemanticColors(props);
1583
+ return `
1584
+ padding: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px 0;
1585
+ border-top: 1px solid ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.divider};
1586
+ 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};
1587
+ `;
1588
+ }}
1589
+ `;
1590
+ const EmptyState = styled("div")`
1591
+ ${fontBodyXs}
1592
+
1593
+ display: flex;
1594
+ align-items: center;
1595
+ justify-content: center;
1596
+ height: 100%;
1597
+
1598
+ ${(props) => {
1599
+ var _props$backgroundColo2, _semanticColors$base3, _semanticColors$base4;
1600
+ const spaces = getSpaces(props);
1601
+ const semanticColors = getSemanticColors(props);
1602
+ return `
1603
+ padding: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
1604
+ 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};
1605
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base4 = semanticColors.base) === null || _semanticColors$base4 === void 0 ? void 0 : _semanticColors$base4.textTertiaryOnDark};
1606
+ `;
1607
+ }}
1608
+ `;
1609
+ const PanelHeader = styled("div")`
1610
+ display: flex;
1611
+ align-items: center;
1612
+
1613
+ ${(props) => {
1614
+ const spaces = getSpaces(props);
1615
+ return `
1616
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
1617
+ `;
1618
+ }}
1619
+ `;
1620
+ const PanelTitle = styled("span")`
1621
+ ${fontHeaderM}
1622
+
1623
+ ${(props) => {
1624
+ var _semanticColors$base5;
1625
+ const semanticColors = getSemanticColors(props);
1626
+ return `
1627
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base5 = semanticColors.base) === null || _semanticColors$base5 === void 0 ? void 0 : _semanticColors$base5.textPrimary};
1628
+ `;
1629
+ }}
1630
+ `;
1631
+ const CopyButton = styled("button")`
1632
+ display: flex;
1633
+ align-items: center;
1634
+ padding: 0;
1635
+ border: none;
1636
+ background: none;
1637
+ cursor: default;
1638
+
1639
+ ${(props) => {
1640
+ var _semanticColors$base6, _semanticColors$base7;
1641
+ const semanticColors = getSemanticColors(props);
1642
+ return `
1643
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base6 = semanticColors.base) === null || _semanticColors$base6 === void 0 ? void 0 : _semanticColors$base6.ornamentSecondary};
1644
+
1645
+ &:hover {
1646
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base7 = semanticColors.base) === null || _semanticColors$base7 === void 0 ? void 0 : _semanticColors$base7.textPrimary};
1647
+ }
1648
+ `;
1649
+ }}
1650
+ `;
1651
+ const ResidueCount = styled("div")`
1652
+ display: flex;
1653
+ align-items: center;
1654
+ margin-left: auto;
1655
+
1656
+ ${(props) => {
1657
+ const spaces = getSpaces(props);
1658
+ return `
1659
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
1660
+ `;
1661
+ }}
1662
+ `;
1663
+ const ResidueCountLabel = styled("span")`
1664
+ ${fontBodyXs}
1665
+
1666
+ ${(props) => {
1667
+ var _semanticColors$base8;
1668
+ const semanticColors = getSemanticColors(props);
1669
+ return `
1670
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base8 = semanticColors.base) === null || _semanticColors$base8 === void 0 ? void 0 : _semanticColors$base8.textTertiary};
1671
+ `;
1672
+ }}
1673
+ `;
1674
+ const ResidueCountValue = styled("span")`
1675
+ ${fontBodyXs}
1676
+
1677
+ ${(props) => {
1678
+ var _semanticColors$base9;
1679
+ const semanticColors = getSemanticColors(props);
1680
+ return `
1681
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base9 = semanticColors.base) === null || _semanticColors$base9 === void 0 ? void 0 : _semanticColors$base9.textPrimary};
1682
+ `;
1683
+ }}
1684
+ `;
1685
+ /**
1686
+ * Scroll region for the residue grid. The `::before` fade masks residues as
1687
+ * they scroll up under the header, so it has to start from whatever the panel
1688
+ * is painted with or it leaves a mismatched strip.
1689
+ */
1690
+ const SequenceScroller = styled("div")`
1691
+ position: relative;
1692
+ flex: 1;
1693
+ min-height: 0;
1694
+
1695
+ ${(props) => {
1696
+ var _props$backgroundColo3, _semanticColors$base10;
1697
+ const semanticColors = getSemanticColors(props);
1698
+ return `
1699
+ &::before {
1700
+ content: "";
1701
+ position: absolute;
1702
+ inset-inline: 0;
1703
+ top: 0;
1704
+ z-index: 10;
1705
+ height: ${SCROLL_FADE_HEIGHT}px;
1706
+ pointer-events: none;
1707
+ 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);
1708
+ }
1709
+ `;
1710
+ }}
1711
+ `;
1712
+ /**
1713
+ * Residue spans are written to directly by `useResidueMarkers` rather than
1714
+ * re-rendered, so their hover and selection colors are set inline. Everything
1715
+ * here is the static styling underneath that: the monospace type, the pointer
1716
+ * affordance, and the superscript sequence numbers (which need their own color
1717
+ * rule, since they are nested inside residue spans and would otherwise inherit
1718
+ * the inline color).
1719
+ */
1720
+ const SequenceScrollArea = styled("div")`
1721
+ height: 100%;
1722
+ overflow-y: auto;
1723
+
1724
+ .msp-sequence-wrapper {
1725
+ ${fontCodeXs};
1726
+ font-size: 11px;
1727
+ line-height: 1.2;
1728
+ }
1729
+
1730
+ .msp-sequence-present {
1731
+ cursor: pointer;
1732
+ }
1733
+
1734
+ ${(props) => {
1735
+ var _semanticColors$base11;
1736
+ const semanticColors = getSemanticColors(props);
1737
+ return `
1738
+ .msp-sequence-number {
1739
+ font-size: 8px;
1740
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base11 = semanticColors.base) === null || _semanticColors$base11 === void 0 ? void 0 : _semanticColors$base11.textTertiaryOnDark};
1741
+ }
1742
+ `;
1743
+ }}
1744
+ `;
1745
+ /**
1746
+ * Layout for one chain's residues.
1747
+ *
1748
+ * Residues are grouped into fixed-size sections, each one grid cell. The
1749
+ * equal-width auto-fill tracks and uniform gap keep the spacing between
1750
+ * sections identical on every row - including a partial last row, which keeps
1751
+ * the same column width (rather than stretching) and stacks from the leading
1752
+ * edge.
1753
+ */
1754
+ const ResidueGrid = styled("div")`
1755
+ user-select: none;
1756
+ display: grid;
1757
+ grid-template-columns: repeat(
1758
+ auto-fill,
1759
+ minmax(${10}ch, 1fr)
1760
+ );
1761
+ gap: 8px;
1762
+ justify-items: start;
1763
+ padding-top: 6px;
1764
+
1765
+ /* Section wrappers, so a section's letters never split across lines. */
1766
+ & > span {
1767
+ white-space: nowrap;
1768
+ }
1769
+
1770
+ .msp-sequence-present {
1771
+ position: relative;
1772
+ display: inline-block;
1773
+ width: 1ch;
1774
+ /*
1775
+ * Reserves room above the letter for its superscript sequence number.
1776
+ * content-box clipping keeps the active fill off that gutter, so a
1777
+ * highlighted residue does not tint the number.
1778
+ */
1779
+ padding-top: 8px;
1780
+ background-clip: content-box;
1781
+ text-align: center;
1782
+ }
1783
+
1784
+ .msp-sequence-number {
1785
+ position: absolute;
1786
+ top: 0;
1787
+ line-height: 1.2;
1788
+ white-space: nowrap;
1789
+ pointer-events: none;
1790
+ }
1791
+ `;
1792
+ /**
1793
+ * The row above each chain's grid: a visibility toggle and the chain's name.
1794
+ *
1795
+ * A structure with more than one chain renders one grid per chain, and without
1796
+ * a caption between them the grids read as a single continuous protein. The
1797
+ * controls sit here rather than only in the legend because this is where a
1798
+ * reader is already looking at one chain at a time.
1799
+ */
1800
+ const ChainHeaderRow = styled("div")`
1801
+ display: flex;
1802
+ align-items: center;
1803
+
1804
+ ${(props) => {
1805
+ const spaces = getSpaces(props);
1806
+ return `
1807
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
1808
+ margin-top: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
1809
+ margin-bottom: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxxs}px;
1810
+ `;
1811
+ }}
1812
+ `;
1813
+ /**
1814
+ * Shows or hides the chain's cartoon in the 3D view. Full strength even while
1815
+ * the chain is hidden, since it is the way back.
1816
+ */
1817
+ const ChainVisibilityToggle = styled("button")`
1818
+ display: flex;
1819
+ align-items: center;
1820
+ padding: 0;
1821
+ border: none;
1822
+ background: none;
1823
+ cursor: pointer;
1824
+
1825
+ ${(props) => {
1826
+ var _semanticColors$base12, _semanticColors$base13;
1827
+ const semanticColors = getSemanticColors(props);
1828
+ return `
1829
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base12 = semanticColors.base) === null || _semanticColors$base12 === void 0 ? void 0 : _semanticColors$base12.textTertiaryOnDark};
1830
+
1831
+ &:hover {
1832
+ color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base13 = semanticColors.base) === null || _semanticColors$base13 === void 0 ? void 0 : _semanticColors$base13.textPrimary};
1833
+ }
1834
+
1835
+ svg {
1836
+ display: block;
1837
+ }
1838
+ `;
1839
+ }}
1840
+ `;
1841
+ /**
1842
+ * The chain's name, and a button because it also selects the chain: the caption
1843
+ * is already the one thing on screen that stands for a whole chain, so clicking
1844
+ * it is where a reader looks to select one. Clicking it again clears it.
1845
+ */
1846
+ const ChainLabel = styled("button")`
1847
+ ${fontBodyXs}
1848
+
1849
+ padding: 0;
1850
+ border: none;
1851
+ background: none;
1852
+ text-align: left;
1853
+
1854
+ ${(props) => {
1855
+ var _semanticColors$base14, _semanticColors$base15, _semanticColors$base16;
1856
+ const semanticColors = getSemanticColors(props);
1857
+ 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;
1858
+ return `
1859
+ color: ${resting};
1860
+ cursor: ${props.isHidden ? "default" : "pointer"};
1861
+ font-weight: ${props.isSelected ? 600 : 500};
1862
+ opacity: ${props.isHidden ? .4 : 1};
1863
+
1864
+ &:hover {
1865
+ color: ${props.isHidden ? resting : semanticColors === null || semanticColors === void 0 || (_semanticColors$base16 = semanticColors.base) === null || _semanticColors$base16 === void 0 ? void 0 : _semanticColors$base16.textPrimary};
1866
+ }
1867
+ `;
1868
+ }}
1869
+ `;
1870
+ /**
1871
+ * Wraps a chain whose 3D cartoon is hidden. The grid stays in place and stays
1872
+ * interactive - the sequence is still the sequence - but is dimmed to match the
1873
+ * chain being absent from the structure beside it. Dimmed rather than removed
1874
+ * so the panel does not reflow every time a chain is toggled.
1875
+ */
1876
+ const HiddenChainGroup = styled("div")`
1877
+ opacity: 0.4;
1878
+ `;
1879
+ //#endregion
1880
+ //#region src/core/ProteinStructureViewer/components/SequenceView/components/ChainHeader/index.tsx
1881
+ /**
1882
+ * The row above one chain's residue grid: a visibility toggle and the chain's
1883
+ * name, which selects it.
1884
+ *
1885
+ * The name is a toggle rather than a one-way switch, so the tooltip says which
1886
+ * way the next click goes - offering to select a chain that is already selected
1887
+ * would be telling the reader the wrong thing. A hidden chain cannot be
1888
+ * selected at all, so the name stops being a button then: there is no geometry
1889
+ * to focus, and the toggle beside it is what the reader wants instead.
1890
+ */
1891
+ function ChainHeader({ chainId, isHidden, isSelected, label, onHover, onSelect, onToggle }) {
1892
+ return /* @__PURE__ */ jsxs(ChainHeaderRow, {
1893
+ onBlur: () => onHover === null || onHover === void 0 ? void 0 : onHover(null),
1894
+ onFocus: () => onHover === null || onHover === void 0 ? void 0 : onHover(chainId),
1895
+ onMouseEnter: () => onHover === null || onHover === void 0 ? void 0 : onHover(chainId),
1896
+ onMouseLeave: () => onHover === null || onHover === void 0 ? void 0 : onHover(null),
1897
+ children: [/* @__PURE__ */ jsx(Tooltip, {
1898
+ arrow: true,
1899
+ placement: "top",
1900
+ title: isHidden ? `Chain ${label} is hidden` : `Click to ${isSelected ? "deselect" : "select"} Chain ${label}`,
1901
+ textAlign: "left",
1902
+ children: /* @__PURE__ */ jsxs(ChainLabel, {
1903
+ "aria-pressed": isSelected,
1904
+ disabled: isHidden,
1905
+ isHidden,
1906
+ isSelected,
1907
+ onClick: () => onSelect === null || onSelect === void 0 ? void 0 : onSelect(chainId),
1908
+ type: "button",
1909
+ children: ["Chain ", label]
1910
+ })
1911
+ }), onToggle && /* @__PURE__ */ jsx(Tooltip, {
1912
+ arrow: true,
1913
+ placement: "top",
1914
+ title: `${isHidden ? "Show" : "Hide"} Chain ${label}`,
1915
+ children: /* @__PURE__ */ jsx(ChainVisibilityToggle, {
1916
+ "aria-label": `${isHidden ? "Show" : "Hide"} chain ${label}`,
1917
+ "aria-pressed": isHidden,
1918
+ onClick: () => onToggle(chainId),
1919
+ type: "button",
1920
+ children: isHidden ? /* @__PURE__ */ jsx(EyeSlashIcon, { size: 12 }) : /* @__PURE__ */ jsx(EyeIcon, { size: 12 })
1921
+ })
1922
+ })]
1923
+ });
1924
+ }
1925
+ //#endregion
1926
+ //#region src/core/ProteinStructureViewer/hooks/usePlugin.ts
1927
+ /**
1928
+ * The plugin owning the React root this component renders in.
1929
+ *
1930
+ * Mol* renders its view components inside its own root and provides the plugin
1931
+ * through this context, which is what `PluginUIComponent` reads to populate
1932
+ * `this.plugin`.
1933
+ */
1934
+ function usePlugin() {
1935
+ return useContext(PluginReactContext);
1936
+ }
1937
+ //#endregion
1938
+ //#region src/core/ProteinStructureViewer/components/SequenceView/utils/residue.ts
1939
+ /** Reads the sequence index off a residue span, or undefined if it is not one. */
1940
+ function readSeqIdx(el) {
1941
+ if (!el || !el.getAttribute) return void 0;
1942
+ return el.hasAttribute("data-seqid") ? +el.getAttribute(SEQ_ID_ATTR) : void 0;
1943
+ }
1944
+ /**
1945
+ * Nearest ancestor that scrolls vertically, or null if none. Used to scope the
1946
+ * residue tooltip's hide-on-scroll listener to the sequence's own overflow
1947
+ * container instead of a global window listener.
1948
+ */
1949
+ function getScrollParent(node) {
1950
+ var _node$parentElement;
1951
+ let el = (_node$parentElement = node === null || node === void 0 ? void 0 : node.parentElement) !== null && _node$parentElement !== void 0 ? _node$parentElement : null;
1952
+ while (el) {
1953
+ const overflowY = getComputedStyle(el).overflowY;
1954
+ if (overflowY === "auto" || overflowY === "scroll") return el;
1955
+ el = el.parentElement;
1956
+ }
1957
+ return null;
1958
+ }
1959
+ function getResidueClass(sequenceWrapper, seqIdx) {
1960
+ return sequenceWrapper.isHighlighted(seqIdx) || sequenceWrapper.isSelected(seqIdx) || sequenceWrapper.isFocused(seqIdx) ? "msp-sequence-present msp-sequence-residue-active" : "msp-sequence-present msp-sequence-residue";
1961
+ }
1962
+ /**
1963
+ * The label shown above a residue: its author sequence id for atomic units,
1964
+ * or a 1-based position for coarse ones.
1965
+ *
1966
+ * `location` is a scratch object the caller reuses across residues, since this
1967
+ * runs once per numbered residue on every render.
1968
+ */
1969
+ function getSequenceNumber(sequenceWrapper, seqIdx, location) {
1970
+ let seqNum = "";
1971
+ const loci = sequenceWrapper.getLoci(seqIdx);
1972
+ const l = StructureElement.Loci.getFirstLocation(loci, location);
1973
+ if (l) {
1974
+ if (Unit.isAtomic(l.unit)) {
1975
+ const seqId = StructureProperties.residue.auth_seq_id(l);
1976
+ const insCode = StructureProperties.residue.pdbx_PDB_ins_code(l);
1977
+ seqNum = `${seqId}${insCode ? insCode : ""}`;
1978
+ } else if (Unit.isCoarse(l.unit)) seqNum = `${seqIdx + 1}`;
1979
+ }
1980
+ return seqNum;
1981
+ }
1982
+ /**
1983
+ * How often a sequence number is drawn above the residues.
1984
+ *
1985
+ * Long sequences get one every ten residues. Short ones number every residue,
1986
+ * unless their numbers run to more than one digit, which would crowd them.
1987
+ */
1988
+ function resolveSequenceNumberPeriod(sequenceWrapper, location, sequenceNumberPeriod) {
1989
+ if (sequenceNumberPeriod !== void 0) return sequenceNumberPeriod;
1990
+ if (sequenceWrapper.length > 10) return 10;
1991
+ if (getSequenceNumber(sequenceWrapper, sequenceWrapper.length - 1, location).length > 1) return 5;
1134
1992
  return 1;
1135
1993
  }
1136
1994
  /**
@@ -1226,470 +2084,489 @@ function useResidueMarkers({ containerRef, residueColors, sequenceWrapper }) {
1226
2084
  });
1227
2085
  }
1228
2086
  //#endregion
1229
- //#region src/core/ProteinStructureViewer/components/SequenceView/utils/loci.ts
1230
- /** The loci for a residue, or undefined when there is no residue there. */
1231
- function getLoci(sequenceWrapper, seqIdx) {
1232
- if (seqIdx !== void 0) {
1233
- const loci = sequenceWrapper.getLoci(seqIdx);
1234
- if (!StructureElement.Loci.isEmpty(loci)) return loci;
2087
+ //#region src/core/ProteinStructureViewer/utils/selection.ts
2088
+ /**
2089
+ * A stable string for a selection, for comparing one against another.
2090
+ *
2091
+ * A consumer holding the selection in state hands back a new object on every
2092
+ * render, so identity says nothing about whether the selection changed. Order
2093
+ * is normalized too: `{ residues: [2, 1] }` and `{ residues: [1, 2] }` select
2094
+ * the same residues and must not read as a change.
2095
+ */
2096
+ function selectionKey(selection) {
2097
+ var _selection$residues, _selection$chains;
2098
+ const residues = [...new Set((_selection$residues = selection.residues) !== null && _selection$residues !== void 0 ? _selection$residues : [])].sort((a, b) => a - b);
2099
+ return `${[...new Set((_selection$chains = selection.chains) !== null && _selection$chains !== void 0 ? _selection$chains : [])].sort().join(",")}|${residues.join(",")}`;
2100
+ }
2101
+ /** True when the selection names nothing at all. */
2102
+ function isEmptySelection(selection) {
2103
+ var _selection$residues2, _selection$chains2;
2104
+ if (!selection) return true;
2105
+ 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);
2106
+ }
2107
+ /**
2108
+ * The residues a selection covers, ascending and without repeats.
2109
+ *
2110
+ * Chains are expanded through `residuesByChain`, which was read off the loaded
2111
+ * structure, so a chain contributes exactly the residues it holds rather than
2112
+ * the span between its ends. A residue named directly and also carried by a
2113
+ * selected chain is counted once.
2114
+ */
2115
+ function selectionResidues(selection, residuesByChain) {
2116
+ var _selection$residues3, _selection$chains3;
2117
+ const residues = new Set((_selection$residues3 = selection.residues) !== null && _selection$residues3 !== void 0 ? _selection$residues3 : []);
2118
+ for (const chainId of (_selection$chains3 = selection.chains) !== null && _selection$chains3 !== void 0 ? _selection$chains3 : []) {
2119
+ var _residuesByChain$get;
2120
+ for (const index of (_residuesByChain$get = residuesByChain.get(chainId)) !== null && _residuesByChain$get !== void 0 ? _residuesByChain$get : []) residues.add(index);
1235
2121
  }
2122
+ return [...residues].sort((a, b) => a - b);
1236
2123
  }
1237
2124
  /**
1238
- * Extends a loci to the range between the mouse-down anchor and the current
1239
- * residue, so dragging across the sequence selects a contiguous span.
2125
+ * Names a selection for the legend's readout.
1240
2126
  *
1241
- * Element indices are only comparable within a single unit, and the range below
1242
- * is built on the anchor's unit alone. So a drag is only extended when both
1243
- * endpoints are a single element of the same unit; anything else -- different
1244
- * units, or an endpoint spanning several because the chain has more than one
1245
- * symmetry operator -- is left unextended rather than collapsed onto one unit
1246
- * and silently reinterpreted as a different range.
2127
+ * A single chain is named as one, since "Chain A" says more than the number of
2128
+ * residues it happens to hold. Anything else is reported as a count, which is
2129
+ * the only thing true of every shape a selection can take. A lone residue is
2130
+ * named by the caller instead, which reads it back off the structure to get its
2131
+ * three-letter code and the number the file gives it.
1247
2132
  */
1248
- function extendToRange(loci, anchor) {
1249
- if (anchor.elements.length !== 1 || loci.elements.length !== 1) return loci;
1250
- const ref = anchor.elements[0];
1251
- const ext = loci.elements[0];
1252
- if (!ref || !ext) return loci;
1253
- if (ref.unit !== ext.unit) return loci;
1254
- const min = Math.min(OrderedSet.min(ref.indices), OrderedSet.min(ext.indices));
1255
- const max = Math.max(OrderedSet.max(ref.indices), OrderedSet.max(ext.indices));
1256
- return StructureElement.Loci(loci.structure, [{
1257
- indices: OrderedSet.ofRange(min, max),
1258
- unit: ref.unit
1259
- }]);
2133
+ function selectionLabel(selection, residueCount) {
2134
+ var _selection$chains4, _selection$residues4;
2135
+ const chains = (_selection$chains4 = selection.chains) !== null && _selection$chains4 !== void 0 ? _selection$chains4 : [];
2136
+ if (chains.length === 1 && !((_selection$residues4 = selection.residues) === null || _selection$residues4 === void 0 ? void 0 : _selection$residues4.length)) return `Chain ${chains[0]}`;
2137
+ return `${residueCount} residues`;
2138
+ }
2139
+ /** The mean of the values `read` returns, ignoring residues without one. */
2140
+ function meanOverResidues(residues, read) {
2141
+ let sum = 0;
2142
+ let count = 0;
2143
+ for (const index of residues) {
2144
+ const value = read(index);
2145
+ if (value === null || value === void 0) continue;
2146
+ sum += value;
2147
+ count++;
2148
+ }
2149
+ return count === 0 ? null : sum / count;
1260
2150
  }
1261
2151
  //#endregion
1262
- //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useHoveredResidue.ts
2152
+ //#region src/core/ProteinStructureViewer/utils/residueLoci.ts
1263
2153
  /**
1264
- * Tracks which residue the pointer is over and keeps the tooltip pinned to it.
2154
+ * Every atom the predicate accepts, as geometry Mol* can focus, frame and mark,
2155
+ * or undefined when it accepts none.
1265
2156
  *
1266
- * The tracked index also deduplicates pointer moves: the grid sees a move for
1267
- * every pixel, but only the ones that cross into a different residue matter.
2157
+ * One pass over the structure rather than a pass per residue: a whole-chain
2158
+ * selection names hundreds of residues, and resolving them one at a time would
2159
+ * walk the structure once for each.
2160
+ *
2161
+ * Atoms are bucketed by the unit they belong to because element indices are
2162
+ * unit-local. That bucketing is also what lets a result span a chain break: it
2163
+ * carries an entry per unit, which is what a range across two chains needs and
2164
+ * what a single unit-local entry cannot express.
2165
+ *
2166
+ * Whole residues are collected rather than one atom each, since the caller
2167
+ * frames the camera on the loci's bounding sphere and a lone atom would zoom
2168
+ * far closer than the residue warrants.
1268
2169
  */
1269
- function useHoveredResidue({ containerRef, sequenceWrapper }) {
1270
- const tooltipRef = useRef(null);
1271
- /** Index of the tracked residue, or -1 when the pointer is off the grid. */
1272
- const seqIdxRef = useRef(-1);
1273
- const hide = useCallback(() => {
1274
- var _tooltipRef$current;
1275
- return (_tooltipRef$current = tooltipRef.current) === null || _tooltipRef$current === void 0 ? void 0 : _tooltipRef$current.hide();
1276
- }, []);
1277
- const clear = useCallback(() => {
1278
- var _tooltipRef$current2;
1279
- if (seqIdxRef.current === -1) return false;
1280
- seqIdxRef.current = -1;
1281
- (_tooltipRef$current2 = tooltipRef.current) === null || _tooltipRef$current2 === void 0 || _tooltipRef$current2.hide();
1282
- return true;
1283
- }, []);
1284
- const moveTo = useCallback((seqIdx, el) => {
1285
- var _tooltipRef$current3, _tooltipRef$current4;
1286
- if (seqIdxRef.current === seqIdx) return false;
1287
- seqIdxRef.current = seqIdx;
1288
- if (seqIdx < 0) (_tooltipRef$current3 = tooltipRef.current) === null || _tooltipRef$current3 === void 0 || _tooltipRef$current3.hide();
1289
- else (_tooltipRef$current4 = tooltipRef.current) === null || _tooltipRef$current4 === void 0 || _tooltipRef$current4.show(el, sequenceWrapper.residueLabel(seqIdx));
1290
- return true;
1291
- }, [sequenceWrapper]);
1292
- useEffect(() => {
1293
- const scrollTarget = getScrollParent(containerRef.current);
1294
- if (!scrollTarget) return;
1295
- const handleScroll = () => clear();
1296
- scrollTarget.addEventListener("scroll", handleScroll, { passive: true });
1297
- return () => scrollTarget.removeEventListener("scroll", handleScroll);
1298
- }, [clear, containerRef]);
1299
- return useMemo(() => ({
1300
- clear,
1301
- hide,
1302
- moveTo,
1303
- tooltipRef
1304
- }), [
1305
- clear,
1306
- hide,
1307
- moveTo
1308
- ]);
2170
+ function lociMatching(structure, matches) {
2171
+ const location = StructureElement.Location.create(structure);
2172
+ const elements = [];
2173
+ for (const unit of structure.units) {
2174
+ location.unit = unit;
2175
+ const indices = [];
2176
+ for (let i = 0; i < unit.elements.length; i++) {
2177
+ location.element = unit.elements[i];
2178
+ if (matches(location)) indices.push(i);
2179
+ }
2180
+ if (indices.length > 0) elements.push({
2181
+ indices,
2182
+ unit
2183
+ });
2184
+ }
2185
+ if (elements.length === 0) return void 0;
2186
+ return StructureElement.Loci(structure, elements.map(({ indices, unit }) => ({
2187
+ indices: OrderedSet.ofSortedArray(indices),
2188
+ unit
2189
+ })));
1309
2190
  }
1310
- //#endregion
1311
- //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useLociDispatch.ts
1312
2191
  /**
1313
- * Wraps a residue loci and the mouse state into a Mol* interaction event. An
1314
- * `anchor` extends the loci to the range between it and `loci`, which is how a
1315
- * drag across the sequence comes out as a contiguous span.
2192
+ * Every atom of the residues a selection covers, within one structure.
2193
+ *
2194
+ * `hiddenChains` is subtracted from the result. A hidden chain is not drawn, so
2195
+ * geometry built from it would have nothing to sit on: Mol*'s focus
2196
+ * representation draws its own ball-and-stick from whatever is focused, in a
2197
+ * part of the state tree the chain's own visibility does not reach, and a
2198
+ * hidden chain left in the loci would keep showing up there after its cartoon
2199
+ * had gone.
1316
2200
  */
1317
- function buildEvent(loci, buttons, button, modifiers, anchor) {
1318
- const ev = {
1319
- button,
1320
- buttons,
1321
- current: Representation.Loci.Empty,
1322
- modifiers
1323
- };
1324
- if (loci === void 0 || StructureElement.Loci.isEmpty(loci)) return ev;
1325
- ev.current = { loci: anchor ? extendToRange(loci, anchor) : loci };
1326
- return ev;
2201
+ function lociForSelectionInStructure(structure, selection, hiddenChains) {
2202
+ var _selection$residues, _selection$chains;
2203
+ if (isEmptySelection(selection)) return void 0;
2204
+ const residues = new Set((_selection$residues = selection.residues) !== null && _selection$residues !== void 0 ? _selection$residues : []);
2205
+ const chains = new Set((_selection$chains = selection.chains) !== null && _selection$chains !== void 0 ? _selection$chains : []);
2206
+ return lociMatching(structure, (location) => {
2207
+ const chainId = StructureProperties.chain.auth_asym_id(location);
2208
+ if (hiddenChains === null || hiddenChains === void 0 ? void 0 : hiddenChains.has(chainId)) return false;
2209
+ return residues.has(StructureProperties.residue.key(location)) || chains.has(chainId);
2210
+ });
1327
2211
  }
1328
2212
  /**
1329
- * Reports the grid's hover and click to Mol*, on the same behaviors the 3D
1330
- * view publishes to, so an interaction in either surface reaches the other.
2213
+ * Every atom of the residues between two 0-based indices, inclusive.
2214
+ *
2215
+ * A contiguous span is tested by comparison rather than by expanding it into a
2216
+ * set of indices: this runs on every residue a drag crosses, and a drag can
2217
+ * span the whole structure.
1331
2218
  */
1332
- function useLociDispatch() {
1333
- const plugin = usePlugin();
1334
- const hover = useCallback((loci, buttons, button, modifiers, anchor) => {
1335
- plugin.behaviors.interaction.hover.next(buildEvent(loci, buttons, button, modifiers, anchor));
1336
- }, [plugin]);
1337
- const click = useCallback((loci, buttons, button, modifiers, anchor) => {
1338
- plugin.behaviors.interaction.click.next(buildEvent(loci, buttons, button, modifiers, anchor));
1339
- }, [plugin]);
1340
- return useMemo(() => ({
1341
- click,
1342
- hover
1343
- }), [click, hover]);
2219
+ function lociForResidueRange(structure, min, max) {
2220
+ return lociMatching(structure, (location) => {
2221
+ const index = StructureProperties.residue.key(location);
2222
+ return index >= min && index <= max;
2223
+ });
1344
2224
  }
1345
- //#endregion
1346
- //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResidueSelection.ts
1347
2225
  /**
1348
- * Turns a press and release on the grid into a selection: one residue when
1349
- * both land on the same one, otherwise the contiguous range dragged across.
2226
+ * The same, across every structure loaded into a plugin. Results are merged
2227
+ * into the first structure that matched: a loci belongs to one structure, and
2228
+ * the residue index space already spans them as though they were one.
1350
2229
  */
1351
- function useResidueSelection({ sequenceWrapper }) {
1352
- const anchorRef = useRef(void 0);
1353
- const { click } = useLociDispatch();
1354
- const onMouseDown = (e) => {
1355
- e.stopPropagation();
1356
- anchorRef.current = getLoci(sequenceWrapper, readSeqIdx(e.target));
1357
- };
1358
- const onMouseUp = (e) => {
1359
- e.stopPropagation();
1360
- const anchor = anchorRef.current;
1361
- if (anchor === void 0) return;
1362
- const loci = getLoci(sequenceWrapper, readSeqIdx(e.target));
1363
- if (loci) {
1364
- const dragged = !StructureElement.Loci.areEqual(anchor, loci);
1365
- click(loci, getButtons(e.nativeEvent), getButton(e.nativeEvent), getModifiers(e.nativeEvent), dragged ? anchor : void 0);
1366
- }
1367
- anchorRef.current = void 0;
1368
- };
1369
- return {
1370
- clearAnchor: () => {
1371
- anchorRef.current = void 0;
1372
- },
1373
- getAnchor: () => anchorRef.current,
1374
- onMouseDown,
1375
- onMouseUp
1376
- };
2230
+ function lociForSelection(plugin, selection, hiddenChains) {
2231
+ for (const entry of plugin.managers.structure.hierarchy.current.structures) {
2232
+ var _entry$cell$obj;
2233
+ const structure = (_entry$cell$obj = entry.cell.obj) === null || _entry$cell$obj === void 0 ? void 0 : _entry$cell$obj.data;
2234
+ if (!structure) continue;
2235
+ const loci = lociForSelectionInStructure(structure, selection, hiddenChains);
2236
+ if (loci) return loci;
2237
+ }
1377
2238
  }
1378
2239
  //#endregion
1379
- //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResiduePointer.ts
2240
+ //#region src/core/ProteinStructureViewer/utils/residueRef.ts
1380
2241
  /**
1381
- * Everything the grid does with a pointer: hover on move, and the drag-to-range
1382
- * selection delegated to `useResidueSelection`.
2242
+ * Reads the residue a loci points at, or null when it points at nothing the
2243
+ * viewer can address.
1383
2244
  *
1384
- * Hover reaches the 3D view through a throttled queue, so that sweeping the
1385
- * pointer across the grid does not ask Mol* to re-mark on every residue
1386
- * crossed. A drag is exempt: its hover carries the growing range, so it goes
1387
- * out immediately to keep the preview under the pointer.
2245
+ * `index` comes from Mol*'s residue key, which counts residues in file order
2246
+ * from zero and is the same counter `injectPlddt` walks. Deriving it
2247
+ * from the residue's *number* instead would tie it to how the file happens to
2248
+ * be numbered: a crop beginning at residue 200 would index `plddt` at 199, and
2249
+ * a file numbering each chain from 1 would give two residues the same index.
1388
2250
  */
1389
- function useResiduePointer({ containerRef, sequenceWrapper }) {
1390
- const { hover } = useLociDispatch();
1391
- const { clear, hide, moveTo, tooltipRef } = useHoveredResidue({
1392
- containerRef,
1393
- sequenceWrapper
1394
- });
1395
- const { clearAnchor, getAnchor, onMouseDown, onMouseUp } = useResidueSelection({ sequenceWrapper });
1396
- const queueRef = useRef(null);
1397
- if (queueRef.current === null) queueRef.current = new Subject();
1398
- const queue = queueRef.current;
1399
- useSubscribe(useMemo(() => queue.pipe(throttleTime(HOVER_THROTTLE_MS, void 0, {
1400
- leading: true,
1401
- trailing: true
1402
- })), [queue]), (e) => {
1403
- hover(getLoci(sequenceWrapper, e.seqIdx < 0 ? void 0 : e.seqIdx), e.buttons, e.button, e.modifiers, getAnchor());
1404
- });
1405
- const queueHover = (e, seqIdx) => queue.next({
1406
- button: getButton(e.nativeEvent),
1407
- buttons: getButtons(e.nativeEvent),
1408
- modifiers: getModifiers(e.nativeEvent),
1409
- seqIdx
1410
- });
1411
- /** Asks the 3D view to drop its hover, once, if the grid still holds one. */
1412
- const releaseHover = (e) => {
1413
- if (clear()) queueHover(e, -1);
1414
- };
1415
- const onContextMenu = (e) => {
1416
- e.preventDefault();
1417
- };
1418
- const onMouseMove = (e) => {
1419
- var _readSeqIdx;
1420
- e.stopPropagation();
1421
- const el = e.target;
1422
- if (!el || !el.getAttribute) {
1423
- releaseHover(e);
1424
- return;
1425
- }
1426
- const seqIdx = (_readSeqIdx = readSeqIdx(el)) !== null && _readSeqIdx !== void 0 ? _readSeqIdx : -1;
1427
- if (!moveTo(seqIdx, el)) return;
1428
- const anchor = getAnchor();
1429
- if (anchor === void 0) {
1430
- queueHover(e, seqIdx);
1431
- return;
1432
- }
1433
- hover(getLoci(sequenceWrapper, seqIdx), ButtonsType.Flag.None, ButtonsType.Flag.None, getModifiers(e.nativeEvent), anchor);
1434
- };
1435
- const onMouseLeave = (e) => {
1436
- e.stopPropagation();
1437
- clearAnchor();
1438
- hide();
1439
- releaseHover(e);
1440
- };
2251
+ function residueRefFromLoci(loci) {
2252
+ var _StructureProperties$;
2253
+ const location = StructureElement.Location.create(void 0);
2254
+ const firstLoc = StructureElement.Loci.getFirstLocation(loci, location);
2255
+ if (!firstLoc) return null;
1441
2256
  return {
1442
- handlers: {
1443
- onContextMenu,
1444
- onMouseDown,
1445
- onMouseLeave,
1446
- onMouseMove,
1447
- onMouseUp
1448
- },
1449
- tooltipRef
2257
+ chainId: StructureProperties.chain.auth_asym_id(firstLoc),
2258
+ compId: StructureProperties.atom.label_comp_id(firstLoc),
2259
+ insCode: (_StructureProperties$ = StructureProperties.residue.pdbx_PDB_ins_code(firstLoc)) !== null && _StructureProperties$ !== void 0 ? _StructureProperties$ : "",
2260
+ index: StructureProperties.residue.key(firstLoc),
2261
+ seqId: StructureProperties.residue.auth_seq_id(firstLoc)
1450
2262
  };
1451
2263
  }
2264
+ /**
2265
+ * Every residue a loci covers, as a selection the consumer can echo back.
2266
+ *
2267
+ * The counterpart to `residueRefFromLoci`, which names only the first: a drag
2268
+ * across the sequence hands Mol* a range, and reporting its first residue
2269
+ * alone would turn a range the user drew into a single-residue selection.
2270
+ *
2271
+ * Reported as residues rather than as chains even when a whole chain is
2272
+ * covered. What the user drew is a span of residues, and calling it a chain
2273
+ * because it happens to end where one does would change the selection's meaning
2274
+ * on a structure where the two coincide.
2275
+ */
2276
+ function selectionFromLoci(loci) {
2277
+ const location = StructureElement.Location.create(loci.structure);
2278
+ const residues = /* @__PURE__ */ new Set();
2279
+ for (const element of loci.elements) {
2280
+ location.unit = element.unit;
2281
+ OrderedSet.forEach(element.indices, (i) => {
2282
+ location.element = element.unit.elements[i];
2283
+ residues.add(StructureProperties.residue.key(location));
2284
+ });
2285
+ }
2286
+ return { residues: [...residues].sort((a, b) => a - b) };
2287
+ }
2288
+ /**
2289
+ * How a residue is named in the readout, e.g. `"LYS 111"`. Takes the number and
2290
+ * the insertion code from the file so that the readout and the sequence panel
2291
+ * beneath it agree on what to call a residue.
2292
+ */
2293
+ function residueLabel(residue) {
2294
+ return `${residue.compId} ${residue.seqId}${residue.insCode}`;
2295
+ }
1452
2296
  //#endregion
1453
- //#region src/core/ProteinStructureViewer/components/SequenceView/style.ts
1454
- /** Height of the fade that masks residues scrolling under the panel header. */
1455
- const SCROLL_FADE_HEIGHT = 8;
1456
- const SequencePanel = styled("div")`
1457
- display: flex;
1458
- flex-direction: column;
1459
- height: 100%;
1460
-
1461
- ${(props) => {
1462
- var _semanticColors$base, _props$backgroundColo, _semanticColors$base2;
1463
- const spaces = getSpaces(props);
1464
- const semanticColors = getSemanticColors(props);
1465
- return `
1466
- padding: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px 0;
1467
- border-top: 1px solid ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base = semanticColors.base) === null || _semanticColors$base === void 0 ? void 0 : _semanticColors$base.divider};
1468
- 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};
1469
- `;
1470
- }}
1471
- `;
1472
- const EmptyState = styled("div")`
1473
- ${fontBodyXs}
1474
-
1475
- display: flex;
1476
- align-items: center;
1477
- justify-content: center;
1478
- height: 100%;
1479
-
1480
- ${(props) => {
1481
- var _props$backgroundColo2, _semanticColors$base3, _semanticColors$base4;
1482
- const spaces = getSpaces(props);
1483
- const semanticColors = getSemanticColors(props);
1484
- return `
1485
- padding: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
1486
- 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};
1487
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base4 = semanticColors.base) === null || _semanticColors$base4 === void 0 ? void 0 : _semanticColors$base4.textTertiaryOnDark};
1488
- `;
1489
- }}
1490
- `;
1491
- const PanelHeader = styled("div")`
1492
- display: flex;
1493
- align-items: center;
1494
-
1495
- ${(props) => {
1496
- const spaces = getSpaces(props);
1497
- return `
1498
- gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
1499
- `;
1500
- }}
1501
- `;
1502
- const PanelTitle = styled("span")`
1503
- ${fontHeaderM}
1504
-
1505
- ${(props) => {
1506
- var _semanticColors$base5;
1507
- const semanticColors = getSemanticColors(props);
1508
- return `
1509
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base5 = semanticColors.base) === null || _semanticColors$base5 === void 0 ? void 0 : _semanticColors$base5.textPrimary};
1510
- `;
1511
- }}
1512
- `;
1513
- const CopyButton = styled("button")`
1514
- display: flex;
1515
- align-items: center;
1516
- padding: 0;
1517
- border: none;
1518
- background: none;
1519
- cursor: default;
1520
-
1521
- ${(props) => {
1522
- var _semanticColors$base6, _semanticColors$base7;
1523
- const semanticColors = getSemanticColors(props);
1524
- return `
1525
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base6 = semanticColors.base) === null || _semanticColors$base6 === void 0 ? void 0 : _semanticColors$base6.ornamentSecondary};
1526
-
1527
- &:hover {
1528
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base7 = semanticColors.base) === null || _semanticColors$base7 === void 0 ? void 0 : _semanticColors$base7.textPrimary};
1529
- }
1530
- `;
1531
- }}
1532
- `;
1533
- const ResidueCount = styled("div")`
1534
- display: flex;
1535
- align-items: center;
1536
- margin-left: auto;
1537
-
1538
- ${(props) => {
1539
- const spaces = getSpaces(props);
1540
- return `
1541
- gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
1542
- `;
1543
- }}
1544
- `;
1545
- const ResidueCountLabel = styled("span")`
1546
- ${fontBodyXs}
1547
-
1548
- ${(props) => {
1549
- var _semanticColors$base8;
1550
- const semanticColors = getSemanticColors(props);
1551
- return `
1552
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base8 = semanticColors.base) === null || _semanticColors$base8 === void 0 ? void 0 : _semanticColors$base8.textTertiary};
1553
- `;
1554
- }}
1555
- `;
1556
- const ResidueCountValue = styled("span")`
1557
- ${fontBodyXs}
1558
-
1559
- ${(props) => {
1560
- var _semanticColors$base9;
1561
- const semanticColors = getSemanticColors(props);
1562
- return `
1563
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base9 = semanticColors.base) === null || _semanticColors$base9 === void 0 ? void 0 : _semanticColors$base9.textPrimary};
1564
- `;
1565
- }}
1566
- `;
2297
+ //#region src/core/ProteinStructureViewer/components/SequenceView/utils/loci.ts
2298
+ /** The loci for a residue, or undefined when there is no residue there. */
2299
+ function getLoci(sequenceWrapper, seqIdx) {
2300
+ if (seqIdx !== void 0) {
2301
+ const loci = sequenceWrapper.getLoci(seqIdx);
2302
+ if (!StructureElement.Loci.isEmpty(loci)) return loci;
2303
+ }
2304
+ }
1567
2305
  /**
1568
- * Scroll region for the residue grid. The `::before` fade masks residues as
1569
- * they scroll up under the header, so it has to start from whatever the panel
1570
- * is painted with or it leaves a mismatched strip.
2306
+ * Extends a loci to the range between the mouse-down anchor and the current
2307
+ * residue, so dragging across the sequence selects a contiguous span.
2308
+ *
2309
+ * The span is measured in the viewer's own residue index - position in file
2310
+ * order across the whole structure - rather than in element indices, which are
2311
+ * unit-local and so cannot describe a range reaching from one chain into the
2312
+ * next. Measuring it the way every other residue-keyed API measures it is what
2313
+ * lets a drag cross a chain break, and it means a range covers exactly the
2314
+ * residues whose indices lie between its ends.
2315
+ *
2316
+ * An endpoint that names no residue leaves the drag unextended rather than
2317
+ * guessing at where it was. An endpoint spanning several units - a chain with
2318
+ * more than one symmetry operator - is fine: each copy of a residue carries the
2319
+ * same index, so the span is the same either way and resolves back across all
2320
+ * of them.
1571
2321
  */
1572
- const SequenceScroller = styled("div")`
1573
- position: relative;
1574
- flex: 1;
1575
- min-height: 0;
1576
-
1577
- ${(props) => {
1578
- var _props$backgroundColo3, _semanticColors$base10;
1579
- const semanticColors = getSemanticColors(props);
1580
- return `
1581
- &::before {
1582
- content: "";
1583
- position: absolute;
1584
- inset-inline: 0;
1585
- top: 0;
1586
- z-index: 10;
1587
- height: ${SCROLL_FADE_HEIGHT}px;
1588
- pointer-events: none;
1589
- 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);
1590
- }
1591
- `;
1592
- }}
1593
- `;
2322
+ function extendToRange(loci, anchor) {
2323
+ var _lociForResidueRange;
2324
+ const from = residueRefFromLoci(anchor);
2325
+ const to = residueRefFromLoci(loci);
2326
+ if (!from || !to) return loci;
2327
+ if (from.index === to.index) return loci;
2328
+ const min = Math.min(from.index, to.index);
2329
+ const max = Math.max(from.index, to.index);
2330
+ return (_lociForResidueRange = lociForResidueRange(loci.structure, min, max)) !== null && _lociForResidueRange !== void 0 ? _lociForResidueRange : loci;
2331
+ }
2332
+ //#endregion
2333
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useHoveredResidue.ts
1594
2334
  /**
1595
- * Residue spans are written to directly by `useResidueMarkers` rather than
1596
- * re-rendered, so their hover and selection colors are set inline. Everything
1597
- * here is the static styling underneath that: the monospace type, the pointer
1598
- * affordance, and the superscript sequence numbers (which need their own color
1599
- * rule, since they are nested inside residue spans and would otherwise inherit
1600
- * the inline color).
2335
+ * Tracks which residue the pointer is over and keeps the tooltip pinned to it.
2336
+ *
2337
+ * The tracked index also deduplicates pointer moves: the grid sees a move for
2338
+ * every pixel, but only the ones that cross into a different residue matter.
2339
+ */
2340
+ function useHoveredResidue({ containerRef, sequenceWrapper }) {
2341
+ const tooltipRef = useRef(null);
2342
+ /** Index of the tracked residue, or -1 when the pointer is off the grid. */
2343
+ const seqIdxRef = useRef(-1);
2344
+ const hide = useCallback(() => {
2345
+ var _tooltipRef$current;
2346
+ return (_tooltipRef$current = tooltipRef.current) === null || _tooltipRef$current === void 0 ? void 0 : _tooltipRef$current.hide();
2347
+ }, []);
2348
+ const clear = useCallback(() => {
2349
+ var _tooltipRef$current2;
2350
+ if (seqIdxRef.current === -1) return false;
2351
+ seqIdxRef.current = -1;
2352
+ (_tooltipRef$current2 = tooltipRef.current) === null || _tooltipRef$current2 === void 0 || _tooltipRef$current2.hide();
2353
+ return true;
2354
+ }, []);
2355
+ const moveTo = useCallback((seqIdx, el) => {
2356
+ var _tooltipRef$current3, _tooltipRef$current4;
2357
+ if (seqIdxRef.current === seqIdx) return false;
2358
+ seqIdxRef.current = seqIdx;
2359
+ if (seqIdx < 0) (_tooltipRef$current3 = tooltipRef.current) === null || _tooltipRef$current3 === void 0 || _tooltipRef$current3.hide();
2360
+ else (_tooltipRef$current4 = tooltipRef.current) === null || _tooltipRef$current4 === void 0 || _tooltipRef$current4.show(el, sequenceWrapper.residueLabel(seqIdx));
2361
+ return true;
2362
+ }, [sequenceWrapper]);
2363
+ useEffect(() => {
2364
+ const scrollTarget = getScrollParent(containerRef.current);
2365
+ if (!scrollTarget) return;
2366
+ const handleScroll = () => clear();
2367
+ scrollTarget.addEventListener("scroll", handleScroll, { passive: true });
2368
+ return () => scrollTarget.removeEventListener("scroll", handleScroll);
2369
+ }, [clear, containerRef]);
2370
+ return useMemo(() => ({
2371
+ clear,
2372
+ hide,
2373
+ moveTo,
2374
+ tooltipRef
2375
+ }), [
2376
+ clear,
2377
+ hide,
2378
+ moveTo
2379
+ ]);
2380
+ }
2381
+ //#endregion
2382
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useLociDispatch.ts
2383
+ /**
2384
+ * Wraps a residue loci and the mouse state into a Mol* interaction event. An
2385
+ * `anchor` extends the loci to the range between it and `loci`, which is how a
2386
+ * drag across the sequence comes out as a contiguous span.
2387
+ */
2388
+ function buildEvent(loci, buttons, button, modifiers, anchor) {
2389
+ const ev = {
2390
+ button,
2391
+ buttons,
2392
+ current: Representation.Loci.Empty,
2393
+ modifiers
2394
+ };
2395
+ if (loci === void 0 || StructureElement.Loci.isEmpty(loci)) return ev;
2396
+ ev.current = { loci: anchor ? extendToRange(loci, anchor) : loci };
2397
+ return ev;
2398
+ }
2399
+ /**
2400
+ * Reports the grid's hover and click to Mol*, on the same behaviors the 3D
2401
+ * view publishes to, so an interaction in either surface reaches the other.
1601
2402
  */
1602
- const SequenceScrollArea = styled("div")`
1603
- height: 100%;
1604
- overflow-y: auto;
1605
-
1606
- .msp-sequence-wrapper {
1607
- ${fontCodeXs};
1608
- font-size: 11px;
1609
- line-height: 1.2;
1610
- }
1611
-
1612
- .msp-sequence-present {
1613
- cursor: pointer;
1614
- }
1615
-
1616
- ${(props) => {
1617
- var _semanticColors$base11;
1618
- const semanticColors = getSemanticColors(props);
1619
- return `
1620
- .msp-sequence-number {
1621
- font-size: 8px;
1622
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base11 = semanticColors.base) === null || _semanticColors$base11 === void 0 ? void 0 : _semanticColors$base11.textTertiaryOnDark};
1623
- }
1624
- `;
1625
- }}
1626
- `;
2403
+ function useLociDispatch() {
2404
+ const plugin = usePlugin();
2405
+ const hover = useCallback((loci, buttons, button, modifiers, anchor) => {
2406
+ plugin.behaviors.interaction.hover.next(buildEvent(loci, buttons, button, modifiers, anchor));
2407
+ }, [plugin]);
2408
+ const click = useCallback((loci, buttons, button, modifiers, anchor) => {
2409
+ plugin.behaviors.interaction.click.next(buildEvent(loci, buttons, button, modifiers, anchor));
2410
+ }, [plugin]);
2411
+ return useMemo(() => ({
2412
+ click,
2413
+ hover
2414
+ }), [click, hover]);
2415
+ }
2416
+ //#endregion
2417
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useSequenceDrag.ts
2418
+ const SequenceDragContext = createContext({
2419
+ clearAnchor: () => void 0,
2420
+ getAnchor: () => void 0,
2421
+ setAnchor: () => void 0
2422
+ });
2423
+ const SequenceDragProvider = SequenceDragContext.Provider;
1627
2424
  /**
1628
- * Layout for one chain's residues.
2425
+ * The anchor a drag across the sequence started from, shared by every chain's
2426
+ * grid.
1629
2427
  *
1630
- * Residues are grouped into fixed-size sections, each one grid cell. The
1631
- * equal-width auto-fill tracks and uniform gap keep the spacing between
1632
- * sections identical on every row - including a partial last row, which keeps
1633
- * the same column width (rather than stretching) and stacks from the leading
1634
- * edge.
2428
+ * It has to live above the grids rather than inside one. A complex renders one
2429
+ * grid per chain, so a drag that begins on the target and ends on the binder
2430
+ * starts in one component and finishes in another; an anchor held by the grid
2431
+ * it started in is not there to be read by the grid it ends in, and the drag
2432
+ * would be reported as a plain click on whatever it landed on.
2433
+ *
2434
+ * Held in a ref rather than state: it changes on mouse-down and mouse-up, and
2435
+ * nothing renders from it, so re-rendering every residue in the panel twice per
2436
+ * drag would buy nothing.
1635
2437
  */
1636
- const ResidueGrid = styled("div")`
1637
- user-select: none;
1638
- display: grid;
1639
- grid-template-columns: repeat(
1640
- auto-fill,
1641
- minmax(${10}ch, 1fr)
1642
- );
1643
- gap: 8px;
1644
- justify-items: start;
1645
- padding-top: 6px;
1646
-
1647
- /* Section wrappers, so a section's letters never split across lines. */
1648
- & > span {
1649
- white-space: nowrap;
1650
- }
1651
-
1652
- .msp-sequence-present {
1653
- position: relative;
1654
- display: inline-block;
1655
- width: 1ch;
1656
- /*
1657
- * Reserves room above the letter for its superscript sequence number.
1658
- * content-box clipping keeps the active fill off that gutter, so a
1659
- * highlighted residue does not tint the number.
1660
- */
1661
- padding-top: 8px;
1662
- background-clip: content-box;
1663
- text-align: center;
1664
- }
1665
-
1666
- .msp-sequence-number {
1667
- position: absolute;
1668
- top: 0;
1669
- line-height: 1.2;
1670
- white-space: nowrap;
1671
- pointer-events: none;
1672
- }
1673
- `;
2438
+ function useCreateSequenceDrag() {
2439
+ const anchorRef = useRef(void 0);
2440
+ const getAnchor = useCallback(() => anchorRef.current, []);
2441
+ const setAnchor = useCallback((anchor) => {
2442
+ anchorRef.current = anchor;
2443
+ }, []);
2444
+ const clearAnchor = useCallback(() => {
2445
+ anchorRef.current = void 0;
2446
+ }, []);
2447
+ return useMemo(() => ({
2448
+ clearAnchor,
2449
+ getAnchor,
2450
+ setAnchor
2451
+ }), [
2452
+ clearAnchor,
2453
+ getAnchor,
2454
+ setAnchor
2455
+ ]);
2456
+ }
2457
+ function useSequenceDrag() {
2458
+ return useContext(SequenceDragContext);
2459
+ }
2460
+ //#endregion
2461
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResidueSelection.ts
1674
2462
  /**
1675
- * Caption naming the chain a sequence grid belongs to. A structure with more
1676
- * than one chain renders one grid per chain, and without a caption between them
1677
- * the grids read as a single continuous protein.
2463
+ * Turns a press and release on the grid into a selection: one residue when
2464
+ * both land on the same one, otherwise the contiguous range dragged across -
2465
+ * which the panel-level anchor lets reach into another chain's grid.
1678
2466
  */
1679
- const ChainLabel = styled("div")`
1680
- ${fontBodyXs}
1681
-
1682
- ${(props) => {
1683
- var _semanticColors$base12;
1684
- const spaces = getSpaces(props);
1685
- const semanticColors = getSemanticColors(props);
1686
- return `
1687
- margin-top: ${spaces === null || spaces === void 0 ? void 0 : spaces.xs}px;
1688
- margin-bottom: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxxs}px;
1689
- color: ${semanticColors === null || semanticColors === void 0 || (_semanticColors$base12 = semanticColors.base) === null || _semanticColors$base12 === void 0 ? void 0 : _semanticColors$base12.textSecondary};
1690
- `;
1691
- }}
1692
- `;
2467
+ function useResidueSelection({ sequenceWrapper }) {
2468
+ const { clearAnchor, getAnchor, setAnchor } = useSequenceDrag();
2469
+ const { click } = useLociDispatch();
2470
+ const onMouseDown = (e) => {
2471
+ e.stopPropagation();
2472
+ setAnchor(getLoci(sequenceWrapper, readSeqIdx(e.target)));
2473
+ };
2474
+ const onMouseUp = (e) => {
2475
+ e.stopPropagation();
2476
+ const anchor = getAnchor();
2477
+ if (anchor === void 0) return;
2478
+ const loci = getLoci(sequenceWrapper, readSeqIdx(e.target));
2479
+ if (loci) {
2480
+ const dragged = !StructureElement.Loci.areEqual(anchor, loci);
2481
+ click(loci, getButtons(e.nativeEvent), getButton(e.nativeEvent), getModifiers(e.nativeEvent), dragged ? anchor : void 0);
2482
+ }
2483
+ clearAnchor();
2484
+ };
2485
+ return {
2486
+ onMouseDown,
2487
+ onMouseUp
2488
+ };
2489
+ }
2490
+ //#endregion
2491
+ //#region src/core/ProteinStructureViewer/components/SequenceView/hooks/useResiduePointer.ts
2492
+ /**
2493
+ * Everything the grid does with a pointer: hover on move, and the drag-to-range
2494
+ * selection delegated to `useResidueSelection`.
2495
+ *
2496
+ * Hover reaches the 3D view through a throttled queue, so that sweeping the
2497
+ * pointer across the grid does not ask Mol* to re-mark on every residue
2498
+ * crossed. A drag is exempt: its hover carries the growing range, so it goes
2499
+ * out immediately to keep the preview under the pointer.
2500
+ */
2501
+ function useResiduePointer({ containerRef, sequenceWrapper }) {
2502
+ const { hover } = useLociDispatch();
2503
+ const { clear, hide, moveTo, tooltipRef } = useHoveredResidue({
2504
+ containerRef,
2505
+ sequenceWrapper
2506
+ });
2507
+ const { getAnchor } = useSequenceDrag();
2508
+ const { onMouseDown, onMouseUp } = useResidueSelection({ sequenceWrapper });
2509
+ const queueRef = useRef(null);
2510
+ if (queueRef.current === null) queueRef.current = new Subject();
2511
+ const queue = queueRef.current;
2512
+ useSubscribe(useMemo(() => queue.pipe(throttleTime(HOVER_THROTTLE_MS, void 0, {
2513
+ leading: true,
2514
+ trailing: true
2515
+ })), [queue]), (e) => {
2516
+ hover(getLoci(sequenceWrapper, e.seqIdx < 0 ? void 0 : e.seqIdx), e.buttons, e.button, e.modifiers, getAnchor());
2517
+ });
2518
+ const queueHover = (e, seqIdx) => queue.next({
2519
+ button: getButton(e.nativeEvent),
2520
+ buttons: getButtons(e.nativeEvent),
2521
+ modifiers: getModifiers(e.nativeEvent),
2522
+ seqIdx
2523
+ });
2524
+ /** Asks the 3D view to drop its hover, once, if the grid still holds one. */
2525
+ const releaseHover = (e) => {
2526
+ if (clear()) queueHover(e, -1);
2527
+ };
2528
+ const onContextMenu = (e) => {
2529
+ e.preventDefault();
2530
+ };
2531
+ const onMouseMove = (e) => {
2532
+ var _readSeqIdx;
2533
+ e.stopPropagation();
2534
+ const el = e.target;
2535
+ if (!el || !el.getAttribute) {
2536
+ releaseHover(e);
2537
+ return;
2538
+ }
2539
+ const seqIdx = (_readSeqIdx = readSeqIdx(el)) !== null && _readSeqIdx !== void 0 ? _readSeqIdx : -1;
2540
+ if (!moveTo(seqIdx, el)) return;
2541
+ const anchor = getAnchor();
2542
+ if (anchor === void 0) {
2543
+ queueHover(e, seqIdx);
2544
+ return;
2545
+ }
2546
+ hover(getLoci(sequenceWrapper, seqIdx), ButtonsType.Flag.None, ButtonsType.Flag.None, getModifiers(e.nativeEvent), anchor);
2547
+ };
2548
+ /**
2549
+ * Leaving one grid is not the end of a drag: on a complex the next chain's
2550
+ * grid is a separate element, so a drag from the target into the binder
2551
+ * leaves this one on its way. The anchor is therefore left alone here and
2552
+ * dropped by the release, or by the pointer leaving the panel altogether.
2553
+ */
2554
+ const onMouseLeave = (e) => {
2555
+ e.stopPropagation();
2556
+ hide();
2557
+ releaseHover(e);
2558
+ };
2559
+ return {
2560
+ handlers: {
2561
+ onContextMenu,
2562
+ onMouseDown,
2563
+ onMouseLeave,
2564
+ onMouseMove,
2565
+ onMouseUp
2566
+ },
2567
+ tooltipRef
2568
+ };
2569
+ }
1693
2570
  //#endregion
1694
2571
  //#region src/core/ProteinStructureViewer/components/SequenceView/components/ResidueTooltip/index.tsx
1695
2572
  var _getSpaces$m, _getSpaces;
@@ -1912,10 +2789,37 @@ function buildParams(state) {
1912
2789
  structure: ParamDefinition.Select(structureOptions.options[0][0], structureOptions.options, { shortLabel: true })
1913
2790
  };
1914
2791
  }
1915
- /** One entry per chain, in Mol*'s entity / chain / operator order. */
2792
+ /**
2793
+ * The file's own name for a chain group, or `""` when the structure holds no
2794
+ * unit for it. Mol* groups its sequence panel by `chainGroupId`, but every
2795
+ * chain-level prop on the viewer is keyed by `auth_asym_id`, so the two have
2796
+ * to be bridged through the structure itself.
2797
+ */
2798
+ function authAsymIdFor(structure, chainGroupId) {
2799
+ const location = StructureElement.Location.create(structure);
2800
+ for (const unit of structure.units) {
2801
+ if (unit.chainGroupId !== chainGroupId) continue;
2802
+ const element = unit.elements[0];
2803
+ if (element === void 0) continue;
2804
+ StructureElement.Location.set(location, structure, unit, element);
2805
+ return StructureProperties.chain.auth_asym_id(location);
2806
+ }
2807
+ return "";
2808
+ }
2809
+ /**
2810
+ * One entry per polymer chain, in Mol*'s entity / chain / operator order.
2811
+ *
2812
+ * Polymer entities only. The heteroatoms on a chain are separate entities, and
2813
+ * Mol* would hand back a caption and a grid for each - a myoglobin listing
2814
+ * "Chain A" and then two more headers, both reading "Chain A_1 [auth A]", one
2815
+ * holding the heme and one the hydroxide. They are drawn in the 3D view and
2816
+ * they are not sequence, and a caption per ligand offers a chain toggle for
2817
+ * something that is not a chain.
2818
+ */
1916
2819
  function buildEntries(structure, selection, _params) {
1917
2820
  const entries = [];
1918
- for (const [modelEntityId] of getModelEntityOptions(structure)) for (const [chainGroupId, cLabel] of getChainOptions(structure, modelEntityId)) for (const [operatorKey] of getOperatorOptions(structure, modelEntityId, chainGroupId)) entries.push({
2821
+ 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({
2822
+ chainId: authAsymIdFor(structure, chainGroupId),
1919
2823
  id: `${modelEntityId}:${chainGroupId}:${operatorKey}`,
1920
2824
  label: cLabel,
1921
2825
  wrapper: getSequenceWrapper({
@@ -1984,8 +2888,14 @@ function createSequenceView(viewSettings) {
1984
2888
  return function SequenceView() {
1985
2889
  const { mode, theme } = useMolstarTheme(viewSettings);
1986
2890
  const backgroundColor = useViewSetting(viewSettings, (s) => s.sequenceViewerBackgroundColor);
2891
+ const hiddenChains = useViewSetting(viewSettings, (s) => s.hiddenChains);
2892
+ const onChainHover = useViewSetting(viewSettings, (s) => s.onChainHover);
2893
+ const onChainSelect = useViewSetting(viewSettings, (s) => s.onChainSelect);
2894
+ const onChainToggle = useViewSetting(viewSettings, (s) => s.onChainToggle);
2895
+ const selectedChains = useViewSetting(viewSettings, (s) => s.selectedChains);
1987
2896
  const { entries, isEmpty, residueCount } = useSequenceWrappers();
1988
2897
  const { copied, copySequence } = useCopySequence(entries);
2898
+ const drag = useCreateSequenceDrag();
1989
2899
  if (isEmpty) return /* @__PURE__ */ jsx(ThemeProvider, {
1990
2900
  theme,
1991
2901
  children: /* @__PURE__ */ jsx(EmptyState, {
@@ -2016,16 +2926,33 @@ function createSequenceView(viewSettings) {
2016
2926
  /* @__PURE__ */ jsxs(ResidueCount, { children: [/* @__PURE__ */ jsx(ResidueCountLabel, { children: "Residues" }), /* @__PURE__ */ jsx(ResidueCountValue, { children: residueCount })] })
2017
2927
  ] }), /* @__PURE__ */ jsx(SequenceScroller, {
2018
2928
  backgroundColor,
2019
- children: /* @__PURE__ */ jsx(SequenceScrollArea, {
2020
- className: "msp-sequence msp-sequence-wrapper-non-empty",
2021
- children: entries.map((s) => /* @__PURE__ */ jsxs(Fragment, { children: [showChainLabels && /* @__PURE__ */ jsx(ChainLabel, { children: s.label }), typeof s.wrapper === "string" ? /* @__PURE__ */ jsx("div", {
2022
- className: "msp-sequence-wrapper",
2023
- children: s.wrapper
2024
- }) : /* @__PURE__ */ jsx(Sequence, {
2025
- chainLabel: showChainLabels ? s.label : void 0,
2026
- residueColors,
2027
- sequenceWrapper: s.wrapper
2028
- })] }, s.id))
2929
+ children: /* @__PURE__ */ jsx(SequenceDragProvider, {
2930
+ value: drag,
2931
+ children: /* @__PURE__ */ jsx(SequenceScrollArea, {
2932
+ className: "msp-sequence msp-sequence-wrapper-non-empty",
2933
+ onMouseLeave: drag.clearAnchor,
2934
+ children: entries.map((s) => {
2935
+ var _hiddenChains$has, _selectedChains$has;
2936
+ const hidden = (_hiddenChains$has = hiddenChains === null || hiddenChains === void 0 ? void 0 : hiddenChains.has(s.chainId)) !== null && _hiddenChains$has !== void 0 ? _hiddenChains$has : false;
2937
+ const grid = typeof s.wrapper === "string" ? /* @__PURE__ */ jsx("div", {
2938
+ className: "msp-sequence-wrapper",
2939
+ children: s.wrapper
2940
+ }) : /* @__PURE__ */ jsx(Sequence, {
2941
+ chainLabel: showChainLabels ? s.label : void 0,
2942
+ residueColors,
2943
+ sequenceWrapper: s.wrapper
2944
+ });
2945
+ return /* @__PURE__ */ jsxs(Fragment, { children: [showChainLabels && /* @__PURE__ */ jsx(ChainHeader, {
2946
+ chainId: s.chainId,
2947
+ isHidden: hidden,
2948
+ isSelected: (_selectedChains$has = selectedChains === null || selectedChains === void 0 ? void 0 : selectedChains.has(s.chainId)) !== null && _selectedChains$has !== void 0 ? _selectedChains$has : false,
2949
+ label: s.label,
2950
+ onHover: onChainHover,
2951
+ onSelect: onChainSelect,
2952
+ onToggle: onChainToggle
2953
+ }), hidden ? /* @__PURE__ */ jsx(HiddenChainGroup, { children: grid }) : grid] }, s.id);
2954
+ })
2955
+ })
2029
2956
  })
2030
2957
  })]
2031
2958
  })
@@ -2033,6 +2960,138 @@ function createSequenceView(viewSettings) {
2033
2960
  };
2034
2961
  }
2035
2962
  //#endregion
2963
+ //#region src/core/ProteinStructureViewer/utils/axes.ts
2964
+ /**
2965
+ * The orientation axes widget, as Mol* parameterizes it.
2966
+ *
2967
+ * Shared rather than declared where it is used, because two different parts of
2968
+ * Mol* take the same shape: the live canvas takes it as
2969
+ * `camera.helper.axes`, and the screenshot helper takes it as its own `axes`,
2970
+ * so an image can carry the widget or leave it out independently of the view
2971
+ * it was captured from.
2972
+ */
2973
+ const AXES_ON = {
2974
+ name: "on",
2975
+ params: {
2976
+ alpha: .51,
2977
+ colorX: 16711680,
2978
+ colorY: 32768,
2979
+ colorZ: 255,
2980
+ labelColorX: 8421504,
2981
+ labelColorY: 8421504,
2982
+ labelColorZ: 8421504,
2983
+ labelOpacity: 1,
2984
+ labelScale: .25,
2985
+ labelX: "X",
2986
+ labelY: "Y",
2987
+ labelZ: "Z",
2988
+ location: "bottom-left",
2989
+ locationOffsetX: 0,
2990
+ locationOffsetY: 0,
2991
+ originColor: 8421504,
2992
+ planeColorXY: 8421504,
2993
+ planeColorXZ: 8421504,
2994
+ planeColorYZ: 8421504,
2995
+ radiusScale: .075,
2996
+ scale: .15,
2997
+ showLabels: false,
2998
+ showPlanes: true
2999
+ }
3000
+ };
3001
+ const AXES_OFF = {
3002
+ name: "off",
3003
+ params: {}
3004
+ };
3005
+ //#endregion
3006
+ //#region src/core/ProteinStructureViewer/utils/color.ts
3007
+ /** Parses `#RRGGBB` (or `RRGGBB`) into a Mol* `Color`. */
3008
+ function parseHexColor(hex) {
3009
+ const h = hex.replace("#", "");
3010
+ return Color.fromRgb(parseInt(h.substring(0, 2), 16), parseInt(h.substring(2, 4), 16), parseInt(h.substring(4, 6), 16));
3011
+ }
3012
+ /**
3013
+ * Parses a theme color into a Mol* `Color`, falling back when the token is
3014
+ * missing or is a format Mol* cannot consume (theme values are hex in practice,
3015
+ * but the palette types allow any CSS color string).
3016
+ */
3017
+ function themeColor(value, fallback) {
3018
+ const candidate = value === null || value === void 0 ? void 0 : value.trim();
3019
+ return parseHexColor(candidate !== void 0 && /^#?[0-9a-f]{6}$/i.test(candidate) ? candidate : fallback);
3020
+ }
3021
+ /**
3022
+ * Neutral fill for residues with no overlay value. Sits between the light and
3023
+ * dark backgrounds so unhighlighted geometry stays legible in both modes.
3024
+ */
3025
+ function neutralResidueColor(mode) {
3026
+ const g = mode === "dark" ? 100 : 180;
3027
+ return Color.fromRgb(g, g, g);
3028
+ }
3029
+ //#endregion
3030
+ //#region src/core/ProteinStructureViewer/utils/screenshot.ts
3031
+ /**
3032
+ * Each resolution as the Mol* preset that produces it: 1280x720, 1920x1080,
3033
+ * 3840x2160, 7680x4320. Named here rather than given as dimensions so the
3034
+ * aspect stays Mol*'s to choose.
3035
+ *
3036
+ * Mol*'s own `viewport` preset - the canvas at its current size - is left out
3037
+ * deliberately: it makes the image depend on how big the viewer happens to be
3038
+ * on screen, which is not something a caller asking for "high" is asking for.
3039
+ */
3040
+ const RESOLUTION_PRESETS = {
3041
+ high: "ultra-hd",
3042
+ low: "hd",
3043
+ maximum: "8k-ultra-hd",
3044
+ medium: "full-hd"
3045
+ };
3046
+ /** Painted behind the structure when a background is asked for but unreadable. */
3047
+ const FALLBACK_BACKGROUND = "#ffffff";
3048
+ /**
3049
+ * Downloads the structure as a PNG.
3050
+ *
3051
+ * Mol*'s screenshot helper renders its own pass rather than reading the canvas
3052
+ * back, so the image is drawn fresh at the requested size and carries its own
3053
+ * transparency and axes settings - none of which disturb the view on screen.
3054
+ *
3055
+ * A named background is the one exception. The helper only chooses between
3056
+ * transparent and whatever the renderer is already painting, so a color has to
3057
+ * be put on the canvas for the length of the capture and taken off afterwards.
3058
+ * `finally` is what guarantees the second half: leaving a figure's background
3059
+ * behind on the viewer would be a worse bug than a failed download.
3060
+ */
3061
+ function downloadStructureImage(_x) {
3062
+ return _downloadStructureImage.apply(this, arguments);
3063
+ }
3064
+ function _downloadStructureImage() {
3065
+ _downloadStructureImage = _asyncToGenerator(function* (plugin, options = {}) {
3066
+ const helper = plugin.helpers.viewportScreenshot;
3067
+ if (!helper) return;
3068
+ const { backgroundColor, filename, resolution = "medium", showAxes } = options;
3069
+ const transparent = backgroundColor === void 0;
3070
+ helper.behaviors.values.next(_objectSpread2(_objectSpread2({}, helper.behaviors.values.value), {}, {
3071
+ axes: showAxes ? AXES_ON : AXES_OFF,
3072
+ format: {
3073
+ name: "png",
3074
+ params: {}
3075
+ },
3076
+ resolution: {
3077
+ name: RESOLUTION_PRESETS[resolution],
3078
+ params: {}
3079
+ },
3080
+ transparent
3081
+ }));
3082
+ const canvas3d = plugin.canvas3d;
3083
+ const painted = canvas3d === null || canvas3d === void 0 ? void 0 : canvas3d.props.renderer.backgroundColor;
3084
+ const overrideBackground = !transparent && canvas3d !== void 0;
3085
+ if (overrideBackground) canvas3d === null || canvas3d === void 0 || canvas3d.setProps({ renderer: { backgroundColor: themeColor(backgroundColor, FALLBACK_BACKGROUND) } });
3086
+ try {
3087
+ yield helper.download(filename);
3088
+ } finally {
3089
+ if (overrideBackground && painted !== void 0) canvas3d === null || canvas3d === void 0 || canvas3d.setProps({ renderer: { backgroundColor: painted } });
3090
+ }
3091
+ });
3092
+ return _downloadStructureImage.apply(this, arguments);
3093
+ }
3094
+ //#endregion
2036
3095
  //#region src/core/ProteinStructureViewer/components/Viewport/constants.ts
2037
3096
  /**
2038
3097
  * Fraction of the bounding sphere radius within which the camera still counts
@@ -2050,32 +3109,6 @@ function isZoomedOffDefault(canvas3d) {
2050
3109
  return Math.abs(state.radius - radius) > tolerance || Vec3.distance(state.target, center) > tolerance;
2051
3110
  }
2052
3111
  //#endregion
2053
- //#region \0@oxc-project+runtime@0.134.0/helpers/esm/asyncToGenerator.js
2054
- function asyncGeneratorStep(n, t, e, r, o, a, c) {
2055
- try {
2056
- var i = n[a](c), u = i.value;
2057
- } catch (n) {
2058
- e(n);
2059
- return;
2060
- }
2061
- i.done ? t(u) : Promise.resolve(u).then(r, o);
2062
- }
2063
- function _asyncToGenerator(n) {
2064
- return function() {
2065
- var t = this, e = arguments;
2066
- return new Promise(function(r, o) {
2067
- var a = n.apply(t, e);
2068
- function _next(n) {
2069
- asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
2070
- }
2071
- function _throw(n) {
2072
- asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
2073
- }
2074
- _next(void 0);
2075
- });
2076
- };
2077
- }
2078
- //#endregion
2079
3112
  //#region src/core/ProteinStructureViewer/components/Viewport/hooks/useCameraReset.ts
2080
3113
  /**
2081
3114
  * Tracks whether the camera has moved off the default view, and puts it back.
@@ -2176,16 +3209,24 @@ function useCameraReset() {
2176
3209
  /**
2177
3210
  * Pinned to the lower-left of the viewport, clear of the sequence panel below
2178
3211
  * and the axes widget in the corner.
3212
+ *
3213
+ * Anchored by its bottom edge, so the buttons stack upwards: the last one
3214
+ * stays put where a reader last saw it, and an earlier one appearing or going
3215
+ * does not move the rest. Reset comes first in the markup and so sits above
3216
+ * capture.
2179
3217
  */
2180
- const ResetCameraSlot = styled("div")`
3218
+ const ViewportButtonStack = styled("div")`
2181
3219
  position: absolute;
2182
3220
  bottom: 48px;
2183
3221
  z-index: 10;
3222
+ display: flex;
3223
+ flex-direction: column;
2184
3224
 
2185
3225
  ${(props) => {
2186
3226
  const spaces = getSpaces(props);
2187
3227
  return `
2188
3228
  left: ${spaces === null || spaces === void 0 ? void 0 : spaces.m}px;
3229
+ gap: ${spaces === null || spaces === void 0 ? void 0 : spaces.xxs}px;
2189
3230
  `;
2190
3231
  }}
2191
3232
  `;
@@ -2203,8 +3244,30 @@ const ResetCameraSlot = styled("div")`
2203
3244
  */
2204
3245
  function createViewportView(viewSettings) {
2205
3246
  return function ViewportWithReset() {
3247
+ const plugin = usePlugin();
2206
3248
  const { theme } = useMolstarTheme(viewSettings);
2207
3249
  const { cameraChanged, resetCamera } = useCameraReset();
3250
+ const showAxes = useViewSetting(viewSettings, (s) => {
3251
+ var _s$showAxes;
3252
+ return (_s$showAxes = s.showAxes) !== null && _s$showAxes !== void 0 ? _s$showAxes : true;
3253
+ });
3254
+ const download = useViewSetting(viewSettings, (s) => s.download);
3255
+ /**
3256
+ * Disabled while a capture is in flight. A high resolution takes long
3257
+ * enough to click twice through, and each click renders its own pass.
3258
+ */
3259
+ const [downloading, setDownloading] = useState(false);
3260
+ const captureImage = useCallback(_asyncToGenerator(function* () {
3261
+ if (!download) return;
3262
+ setDownloading(true);
3263
+ try {
3264
+ yield downloadStructureImage(plugin, download);
3265
+ } catch (error) {
3266
+ console.error("Failed to download the structure image:", error);
3267
+ } finally {
3268
+ setDownloading(false);
3269
+ }
3270
+ }), [download, plugin]);
2208
3271
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [
2209
3272
  /* @__PURE__ */ jsx(Viewport, {}),
2210
3273
  /* @__PURE__ */ jsx("div", {
@@ -2213,18 +3276,37 @@ function createViewportView(viewSettings) {
2213
3276
  }),
2214
3277
  /* @__PURE__ */ jsx(ThemeProvider, {
2215
3278
  theme,
2216
- children: /* @__PURE__ */ jsx(ResetCameraSlot, {
2217
- hidden: !cameraChanged,
2218
- children: /* @__PURE__ */ jsx(Button, {
2219
- "aria-label": "Reset camera",
2220
- onClick: resetCamera,
3279
+ children: /* @__PURE__ */ jsxs(ViewportButtonStack, { children: [/* @__PURE__ */ jsx("div", {
3280
+ hidden: !showAxes || !cameraChanged,
3281
+ children: /* @__PURE__ */ jsx(Tooltip, {
3282
+ arrow: true,
3283
+ placement: "right",
2221
3284
  title: "Reset camera",
3285
+ textAlign: "left",
3286
+ children: /* @__PURE__ */ jsx(Button, {
3287
+ "aria-label": "Reset camera",
3288
+ onClick: resetCamera,
3289
+ sdsStyle: "minimal",
3290
+ sdsType: "secondary",
3291
+ size: "medium",
3292
+ children: /* @__PURE__ */ jsx(ArrowCounterClockwiseIcon, {})
3293
+ })
3294
+ })
3295
+ }), download && /* @__PURE__ */ jsx(Tooltip, {
3296
+ arrow: true,
3297
+ placement: "right",
3298
+ title: "Download image",
3299
+ textAlign: "left",
3300
+ children: /* @__PURE__ */ jsx(Button, {
3301
+ "aria-label": "Download image of the structure",
3302
+ disabled: downloading,
3303
+ onClick: captureImage,
2222
3304
  sdsStyle: "minimal",
2223
3305
  sdsType: "secondary",
2224
3306
  size: "medium",
2225
- children: /* @__PURE__ */ jsx(ArrowCounterClockwiseIcon, {})
3307
+ children: /* @__PURE__ */ jsx(ApertureIcon, {})
2226
3308
  })
2227
- })
3309
+ })] })
2228
3310
  })
2229
3311
  ] });
2230
3312
  };
@@ -2283,6 +3365,25 @@ function focusResidue(plugin, loci) {
2283
3365
  return clipRatio;
2284
3366
  }
2285
3367
  /**
3368
+ * Frames the camera on a loci without cropping anything around it.
3369
+ *
3370
+ * The counterpart to `focusResidue` for something meant to be read in context
3371
+ * rather than peeled down to: the camera fits what was selected, and the depth
3372
+ * clip is left open to the whole scene, so the rest of the structure stays on
3373
+ * screen. A selected chain is shown by dimming the chains around it, and they
3374
+ * have to be there to be dimmed.
3375
+ */
3376
+ function frameLoci(plugin, loci) {
3377
+ var _plugin$canvas3d2;
3378
+ const camera = (_plugin$canvas3d2 = plugin.canvas3d) === null || _plugin$canvas3d2 === void 0 ? void 0 : _plugin$canvas3d2.camera;
3379
+ if (!camera) return;
3380
+ const sphere = Loci.getBoundingSphere(loci);
3381
+ if (!sphere) return;
3382
+ const framingRadius = Math.max(sphere.radius + FOCUS_EXTRA_RADIUS, FOCUS_MIN_RADIUS);
3383
+ const snapshot = camera.getFocus(sphere.center, framingRadius);
3384
+ camera.setState(_objectSpread2(_objectSpread2({}, snapshot), {}, { radius: camera.state.radiusMax }), FOCUS_DURATION_MS);
3385
+ }
3386
+ /**
2286
3387
  * Keeps the depth clip in sync with the zoom while a residue is focused.
2287
3388
  *
2288
3389
  * Mol*'s trackball zoom moves the camera without touching the clip radius, so
@@ -2292,49 +3393,302 @@ function focusResidue(plugin, loci) {
2292
3393
  * camera is mid-transition, so it does not fight the focus animation.
2293
3394
  */
2294
3395
  function syncClipToZoom(plugin, getClipRatio) {
2295
- var _plugin$canvas3d2;
2296
- const camera = (_plugin$canvas3d2 = plugin.canvas3d) === null || _plugin$canvas3d2 === void 0 ? void 0 : _plugin$canvas3d2.camera;
3396
+ var _plugin$canvas3d3;
3397
+ const camera = (_plugin$canvas3d3 = plugin.canvas3d) === null || _plugin$canvas3d3 === void 0 ? void 0 : _plugin$canvas3d3.camera;
2297
3398
  const clipRatio = getClipRatio();
2298
3399
  if (!camera || clipRatio === null || camera.transition.inTransition) return;
2299
3400
  const radius = clipRadiusForDistance(Vec3.distance(camera.state.position, camera.state.target), clipRatio, camera.state.radiusMax);
2300
3401
  if (Math.abs(camera.state.radius - radius) > CLIP_EPSILON) {
2301
- var _plugin$canvas3d3;
3402
+ var _plugin$canvas3d4;
2302
3403
  camera.setState({ radius });
2303
- (_plugin$canvas3d3 = plugin.canvas3d) === null || _plugin$canvas3d3 === void 0 || _plugin$canvas3d3.requestDraw();
3404
+ (_plugin$canvas3d4 = plugin.canvas3d) === null || _plugin$canvas3d4 === void 0 || _plugin$canvas3d4.requestDraw();
2304
3405
  }
2305
3406
  }
2306
3407
  //#endregion
2307
- //#region src/core/ProteinStructureViewer/utils/residueRef.ts
3408
+ //#region src/core/ProteinStructureViewer/utils/chains.ts
2308
3409
  /**
2309
- * Reads the residue a loci points at, or null when it points at nothing the
2310
- * viewer can address.
3410
+ * The polymer of one chain, as named in the file. What each chain's cartoon is
3411
+ * built from, and so what makes a chain a thing Mol* can hide on its own.
2311
3412
  *
2312
- * `index` comes from Mol*'s residue key, which counts residues in file order
2313
- * from zero and is the same counter `injectPlddtIntoPdb` walks. Deriving it
2314
- * from the residue's *number* instead would tie it to how the file happens to
2315
- * be numbered: a crop beginning at residue 200 would index `plddt` at 199, and
2316
- * a file numbering each chain from 1 would give two residues the same index.
3413
+ * Paired with `chainLigandExpression`: between them they cover everything on a
3414
+ * chain the viewer draws, split by what it draws it as. The polymer
3415
+ * restriction is the one Mol*'s `polymer-cartoon` preset applied, and is what
3416
+ * keeps a heme from being handed to a representation that can only trace a
3417
+ * backbone.
2317
3418
  */
2318
- function residueRefFromLoci(loci) {
2319
- var _StructureProperties$;
2320
- const location = StructureElement.Location.create(void 0);
2321
- const firstLoc = StructureElement.Loci.getFirstLocation(loci, location);
2322
- if (!firstLoc) return null;
3419
+ function chainPolymerExpression(chainId) {
3420
+ return MolScriptBuilder.struct.generator.atomGroups({
3421
+ "chain-test": MolScriptBuilder.core.rel.eq([MolScriptBuilder.ammp("auth_asym_id"), chainId]),
3422
+ "entity-test": MolScriptBuilder.core.rel.eq([MolScriptBuilder.ammp("entityType"), "polymer"])
3423
+ });
3424
+ }
3425
+ /**
3426
+ * Bonds worth following out of a ligand: the ones holding it to the protein.
3427
+ *
3428
+ * Mol*'s own pair, and metallic coordination is the half that matters most -
3429
+ * a heme's iron is held to its histidine by a coordination bond and not a
3430
+ * covalent one, so covalent alone would leave every metalloprotein's cofactor
3431
+ * looking dropped in rather than bound.
3432
+ */
3433
+ const CONNECTING_BOND = MolScriptBuilder.core.flags.hasAny([MolScriptBuilder.struct.bondProperty.flags(), MolScriptBuilder.core.type.bitflags([BondType.fromNames(["covalent", "metal-coordination"])])]);
3434
+ /**
3435
+ * The heteroatoms of one chain - ligands, ions, glycans, lipids - along with
3436
+ * the residues holding them, which is what its ball-and-stick is built from.
3437
+ *
3438
+ * `non-polymer` is the one entity type a PDB's HETATM records land under,
3439
+ * ligands and ions alike, so there is nothing finer to test here: the
3440
+ * distinction Mol*'s presets draw between their `ligand`, `ion` and `lipid`
3441
+ * components is a residue-name lookup made to give each a slightly different
3442
+ * style, and all three are sticks. `branched` is the separate type glycans
3443
+ * arrive as.
3444
+ *
3445
+ * Water is the third type and is left out of the seed. Every solvent molecule
3446
+ * drawn as sticks buries the structure they surround, which is why Mol* draws
3447
+ * them at 60% alpha rather than plain, and none of them is what "show the
3448
+ * ligands" asks for.
3449
+ *
3450
+ * One layer of bonds out from there, taken as whole residues, is what brings
3451
+ * the binding residue along - myoglobin's His93, say. Without it the heme
3452
+ * floats unattached in the middle of a cartoon it is visibly bonded to, and
3453
+ * the bond drawn to its iron ends in mid-air. One layer and no more: the
3454
+ * residue that holds the ligand, not that residue's own neighbours.
3455
+ *
3456
+ * Intersected back with the chain, so everything a chain is drawn with belongs
3457
+ * to that chain. A ligand bonded across an interface would otherwise leave the
3458
+ * partner chain's residue in this chain's component, somewhere hiding the
3459
+ * partner chain could not reach.
3460
+ */
3461
+ function chainLigandExpression(chainId) {
3462
+ const onThisChain = MolScriptBuilder.core.rel.eq([MolScriptBuilder.ammp("auth_asym_id"), chainId]);
3463
+ return MolScriptBuilder.struct.modifier.union([MolScriptBuilder.struct.modifier.intersectBy({
3464
+ 0: MolScriptBuilder.struct.modifier.includeConnected({
3465
+ 0: MolScriptBuilder.struct.generator.atomGroups({
3466
+ "chain-test": onThisChain,
3467
+ "entity-test": MolScriptBuilder.core.set.has([MolScriptBuilder.set("non-polymer", "branched"), MolScriptBuilder.ammp("entityType")])
3468
+ }),
3469
+ "as-whole-residues": true,
3470
+ "bond-test": CONNECTING_BOND,
3471
+ "layer-count": 1
3472
+ }),
3473
+ by: MolScriptBuilder.struct.generator.atomGroups({ "chain-test": onThisChain })
3474
+ })]);
3475
+ }
3476
+ /**
3477
+ * Matches how the sequence panel captions its chains, which reaches the same
3478
+ * label through Mol*'s own `getChainOptions`. Deriving it the same way is what
3479
+ * keeps a chain from going by one name in the legend and another in the panel.
3480
+ */
3481
+ const CHAIN_LABEL_OPTIONS = {
3482
+ granularity: "chain",
3483
+ hidePrefix: true,
3484
+ htmlStyling: false
3485
+ };
3486
+ /**
3487
+ * Reads the chains of a structure and the polymer residues on each.
3488
+ *
3489
+ * Residue indices are Mol*'s residue keys, counting residues in file order
3490
+ * across the whole structure, so what is reported here addresses the same
3491
+ * residues as `plddt`, `residueOverlay` and `selection`.
3492
+ *
3493
+ * Heteroatoms are drawn (see `chainLigandExpression`) but are not counted
3494
+ * here. A heme is a residue to the file and not to a reader: it is no part of
3495
+ * the sequence the panel lists, and averaging a confidence score over it would
3496
+ * divide by a residue that has none.
3497
+ *
3498
+ * Residues are gathered into a set rather than inferred from the ends: a chain
3499
+ * carrying several symmetry operators repeats each of its residues once per
3500
+ * operator, and a structure whose chains interleave leaves a chain's indices
3501
+ * non-contiguous. Neither is what a predicted complex looks like, but a range
3502
+ * would misread both.
3503
+ */
3504
+ function scanChains(structure) {
3505
+ const accumulators = /* @__PURE__ */ new Map();
3506
+ const location = StructureElement.Location.create(structure);
3507
+ for (const unit of structure.units) {
3508
+ location.unit = unit;
3509
+ for (let i = 0; i < unit.elements.length; i++) {
3510
+ location.element = unit.elements[i];
3511
+ const chainId = StructureProperties.chain.auth_asym_id(location);
3512
+ let chain = accumulators.get(chainId);
3513
+ if (!chain) {
3514
+ chain = {
3515
+ chainId,
3516
+ label: elementLabel(location, CHAIN_LABEL_OPTIONS),
3517
+ residues: /* @__PURE__ */ new Set()
3518
+ };
3519
+ accumulators.set(chainId, chain);
3520
+ }
3521
+ if (StructureProperties.entity.type(location) !== "polymer") continue;
3522
+ chain.residues.add(StructureProperties.residue.key(location));
3523
+ }
3524
+ }
3525
+ 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) => {
3526
+ var _a$residues$, _b$residues$;
3527
+ 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);
3528
+ });
2323
3529
  return {
2324
- chainId: StructureProperties.chain.auth_asym_id(firstLoc),
2325
- compId: StructureProperties.atom.label_comp_id(firstLoc),
2326
- insCode: (_StructureProperties$ = StructureProperties.residue.pdbx_PDB_ins_code(firstLoc)) !== null && _StructureProperties$ !== void 0 ? _StructureProperties$ : "",
2327
- index: StructureProperties.residue.key(firstLoc),
2328
- seqId: StructureProperties.residue.auth_seq_id(firstLoc)
3530
+ chainLabels: new Map([...accumulators.values()].map(({ chainId, label }) => [chainId, label])),
3531
+ chains: ordered.map(({ chainId, label, residues }) => {
3532
+ var _residues, _residues$;
3533
+ return {
3534
+ chainId,
3535
+ endIndex: (_residues = residues[residues.length - 1]) !== null && _residues !== void 0 ? _residues : 0,
3536
+ label,
3537
+ residueCount: residues.length,
3538
+ startIndex: (_residues$ = residues[0]) !== null && _residues$ !== void 0 ? _residues$ : 0
3539
+ };
3540
+ }),
3541
+ residuesByChain: new Map(ordered.map(({ chainId, residues }) => [chainId, residues]))
2329
3542
  };
2330
3543
  }
3544
+ /** True when the two lists name the same chains, in the same order. */
3545
+ function chainsEqual(a, b) {
3546
+ return a.length === b.length && a.every((chain, i) => {
3547
+ const other = b[i];
3548
+ return other !== void 0 && chain.chainId === other.chainId && chain.startIndex === other.startIndex && chain.endIndex === other.endIndex && chain.residueCount === other.residueCount;
3549
+ });
3550
+ }
3551
+ //#endregion
3552
+ //#region src/core/ProteinStructureViewer/utils/molstarSpec.ts
2331
3553
  /**
2332
- * How a residue is named in the readout, e.g. `"LYS 111"`. Takes the number and
2333
- * the insertion code from the file so that the readout and the sequence panel
2334
- * beneath it agree on what to call a residue.
3554
+ * The spec's list-valued keys. These are appended rather than merged: Mol*
3555
+ * reads them as collections, so a consumer's entries join the viewer's instead
3556
+ * of replacing them.
3557
+ *
3558
+ * `config` is the one where order carries meaning - Mol* folds the list into a
3559
+ * Map in order, so a later entry overwrites an earlier one, and appending is
3560
+ * what lets a consumer override a setting the viewer chose.
2335
3561
  */
2336
- function residueLabel(residue) {
2337
- return `${residue.compId} ${residue.seqId}${residue.insCode}`;
3562
+ const LIST_KEYS = [
3563
+ "actions",
3564
+ "animations",
3565
+ "behaviors",
3566
+ "config",
3567
+ "customFormats",
3568
+ "customParamEditors"
3569
+ ];
3570
+ /**
3571
+ * Whether a value should be merged into rather than replaced.
3572
+ *
3573
+ * Only object literals qualify. Arrays are collections, and the spec is full
3574
+ * of React components and Mol* class instances, all of which are values in
3575
+ * their own right - merging into one would take it apart.
3576
+ */
3577
+ function isPlainObject(value) {
3578
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
3579
+ const proto = Object.getPrototypeOf(value);
3580
+ return proto === Object.prototype || proto === null;
3581
+ }
3582
+ function deepMerge(base, override) {
3583
+ if (!isPlainObject(base) || !isPlainObject(override)) return override;
3584
+ const merged = _objectSpread2({}, base);
3585
+ for (const [key, value] of Object.entries(override)) merged[key] = key in base ? deepMerge(base[key], value) : value;
3586
+ return merged;
3587
+ }
3588
+ function withoutLists(spec) {
3589
+ const rest = _objectSpread2({}, spec);
3590
+ for (const key of LIST_KEYS) delete rest[key];
3591
+ return rest;
3592
+ }
3593
+ /**
3594
+ * Lays a consumer's Mol* spec over the viewer's own.
3595
+ *
3596
+ * The viewer builds a spec of its own - the sequence panel and viewport it
3597
+ * renders, the controls it hides, the behaviors it drops - and this is how a
3598
+ * consumer reaches the rest of Mol* without the viewer having to grow a prop
3599
+ * per setting. Anything the consumer names wins, so `canvas3d.renderer` or a
3600
+ * `PluginConfig` item can be set to something other than the default the
3601
+ * viewer picked.
3602
+ *
3603
+ * The one thing it cannot do is take something away: `behaviors` is appended
3604
+ * to, so a behavior the viewer removed - Mol*'s click-to-zoom camera - stays
3605
+ * removed, and one the viewer kept cannot be dropped.
3606
+ */
3607
+ function mergeMolstarSpec(base, override) {
3608
+ if (!override) return base;
3609
+ const merged = deepMerge(withoutLists(base), withoutLists(override));
3610
+ for (const key of LIST_KEYS) {
3611
+ var _base, _override;
3612
+ const ours = (_base = base[key]) !== null && _base !== void 0 ? _base : [];
3613
+ const theirs = (_override = override[key]) !== null && _override !== void 0 ? _override : [];
3614
+ if (ours.length > 0 || theirs.length > 0) merged[key] = [...ours, ...theirs];
3615
+ }
3616
+ return merged;
3617
+ }
3618
+ //#endregion
3619
+ //#region src/core/ProteinStructureViewer/utils/structureFormat.ts
3620
+ /** How much of the file to inspect when guessing the format. */
3621
+ const DETECT_SAMPLE = 16384;
3622
+ /**
3623
+ * Infers whether `text` is PDB or mmCIF (PDBx).
3624
+ *
3625
+ * mmCIF documents start with a `data_` block and name their coordinates
3626
+ * `_atom_site.`. PDB never does either, so either marker is enough. A leading
3627
+ * comment (`# ...`) before `data_` is still mmCIF.
3628
+ */
3629
+ function detectStructureFormat(text) {
3630
+ const sample = text.slice(0, DETECT_SAMPLE);
3631
+ if (/(?:^|\n)\s*data_/.test(sample) || /_atom_site\./.test(sample)) return "mmcif";
3632
+ return "pdb";
3633
+ }
3634
+ //#endregion
3635
+ //#region src/core/ProteinStructureViewer/utils/chainColorTheme.ts
3636
+ /** Mol* color theme name under which per-chain coloring is registered. */
3637
+ const CHAIN_COLOR_THEME_NAME = "chain-color";
3638
+ /** Painted for a chain with no color assigned, or one assigned a bad value. */
3639
+ const DEFAULT_CHAIN_COLOR_HEX = "#808080";
3640
+ const DEFAULT_CHAIN_COLOR = Color.fromRgb(128, 128, 128);
3641
+ /**
3642
+ * Builds a Mol* color theme that paints each chain its own color.
3643
+ *
3644
+ * This stands in for Mol*'s built-in `chain-id` theme, which picks its own
3645
+ * colors from a palette we cannot read back. Owning the assignment is what
3646
+ * lets the chain legend show a swatch that matches the structure, rather than
3647
+ * a key for colors it has to guess at.
3648
+ *
3649
+ * Created per plugin instance, and its state read live inside `color()`, for
3650
+ * the same reasons as the residue value theme beside it: several viewers can
3651
+ * color chains differently on one page, and recoloring does not rebuild the
3652
+ * structure.
3653
+ */
3654
+ function createChainColorTheme() {
3655
+ const state = {
3656
+ colors: /* @__PURE__ */ new Map(),
3657
+ version: 0
3658
+ };
3659
+ const provider = {
3660
+ category: "chain property",
3661
+ defaultValues: {},
3662
+ factory() {
3663
+ const { colors } = state;
3664
+ const parsed = /* @__PURE__ */ new Map();
3665
+ for (const [chainId, hex] of colors) parsed.set(chainId, themeColor(hex, DEFAULT_CHAIN_COLOR_HEX));
3666
+ return {
3667
+ color(location) {
3668
+ var _parsed$get;
3669
+ if (!StructureElement.Location.is(location)) return DEFAULT_CHAIN_COLOR;
3670
+ const chainId = StructureProperties.chain.auth_asym_id(location);
3671
+ return (_parsed$get = parsed.get(chainId)) !== null && _parsed$get !== void 0 ? _parsed$get : DEFAULT_CHAIN_COLOR;
3672
+ },
3673
+ contextHash: state.version,
3674
+ description: "Color residues by the chain they sit on",
3675
+ factory: provider.factory,
3676
+ granularity: "group",
3677
+ props: {}
3678
+ };
3679
+ },
3680
+ getParams: () => ({}),
3681
+ isApplicable: () => true,
3682
+ label: "Chain Color",
3683
+ name: CHAIN_COLOR_THEME_NAME
3684
+ };
3685
+ return {
3686
+ provider,
3687
+ setState(colors) {
3688
+ state.colors = colors;
3689
+ state.version++;
3690
+ }
3691
+ };
2338
3692
  }
2339
3693
  //#endregion
2340
3694
  //#region src/core/ProteinStructureViewer/utils/plddt.ts
@@ -2370,6 +3724,14 @@ const PLDDT_COLOR_SCALE = {
2370
3724
  ]
2371
3725
  };
2372
3726
  const PLDDT_BANDS = PLDDT_COLOR_SCALE.kind === "stepped" ? PLDDT_COLOR_SCALE.stops : [];
3727
+ /**
3728
+ * The band colors alone, ascending from least to most confident.
3729
+ *
3730
+ * What the chain legend shows in place of a single color while pLDDT is
3731
+ * painting the structure: no one color stands for a chain then, so the swatch
3732
+ * carries the whole key instead.
3733
+ */
3734
+ const PLDDT_BAND_COLORS = PLDDT_BANDS.map((stop) => stop.color);
2373
3735
  const DEFAULT_PLDDT_COLOR = Color.fromRgb(128, 128, 128);
2374
3736
  /**
2375
3737
  * Maps a pLDDT confidence score on the 0-100 B-factor scale to its band color.
@@ -2408,9 +3770,183 @@ function injectPlddtIntoPdb(pdbData, plddtValues) {
2408
3770
  return paddedLine.substring(0, 60) + bfactorStr + paddedLine.substring(66);
2409
3771
  }).join("\n");
2410
3772
  }
3773
+ const ATOM_SITE_PREFIX = "_atom_site.";
3774
+ const B_FACTOR_COLUMN = "B_iso_or_equiv";
3775
+ function skipCifWhitespace(line, index) {
3776
+ let i = index;
3777
+ while (i < line.length && /\s/.test(line.charAt(i))) i += 1;
3778
+ return i;
3779
+ }
3780
+ function readCifToken(line, start) {
3781
+ const quote = line.charAt(start);
3782
+ if (quote === "'" || quote === "\"") {
3783
+ const end = line.indexOf(quote, start + 1);
3784
+ if (end < 0) return {
3785
+ next: line.length,
3786
+ token: line.slice(start + 1)
3787
+ };
3788
+ return {
3789
+ next: end + 1,
3790
+ token: line.slice(start + 1, end)
3791
+ };
3792
+ }
3793
+ let i = start;
3794
+ while (i < line.length && !/\s/.test(line.charAt(i))) i += 1;
3795
+ return {
3796
+ next: i,
3797
+ token: line.slice(start, i)
3798
+ };
3799
+ }
3800
+ /**
3801
+ * Splits one CIF line into tokens, honouring `'quoted'` and `"quoted"` values.
3802
+ * Atom-site rows are one line each in practice; multiline `;text;` fields are
3803
+ * not used there and are not handled.
3804
+ */
3805
+ function tokenizeCifLine(line) {
3806
+ const tokens = [];
3807
+ let i = skipCifWhitespace(line, 0);
3808
+ while (i < line.length) {
3809
+ const { next, token } = readCifToken(line, i);
3810
+ tokens.push(token);
3811
+ i = skipCifWhitespace(line, next);
3812
+ }
3813
+ return tokens;
3814
+ }
3815
+ function isCifNull(value) {
3816
+ return value === void 0 || value === "." || value === "?";
3817
+ }
3818
+ function columnIndex(columns, name) {
3819
+ return columns.indexOf(name);
3820
+ }
3821
+ /**
3822
+ * Residue identity matching `injectPlddtIntoPdb`: chain + sequence number +
3823
+ * insertion code. Prefers the `auth_*` columns Mol* reports on the parsed
3824
+ * model, falling back to `label_*` when a file omitted them. `.` / `?`
3825
+ * insertion codes count as empty, the way a blank PDB column 27 does.
3826
+ */
3827
+ function mmcifResidueKey(tokens, columns) {
3828
+ var _ref, _ref2, _ref3, _ref4;
3829
+ const authAsym = columnIndex(columns, "auth_asym_id");
3830
+ const labelAsym = columnIndex(columns, "label_asym_id");
3831
+ const authSeq = columnIndex(columns, "auth_seq_id");
3832
+ const labelSeq = columnIndex(columns, "label_seq_id");
3833
+ const ins = columnIndex(columns, "pdbx_PDB_ins_code");
3834
+ 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]}`;
3835
+ }
3836
+ function isAtomSiteRow(tokens, columns) {
3837
+ const group = columnIndex(columns, "group_PDB");
3838
+ if (group < 0) return true;
3839
+ const value = tokens[group];
3840
+ return value === "ATOM" || value === "HETATM";
3841
+ }
3842
+ function plddtBFactor(residueIndex, plddtValues) {
3843
+ var _plddtValues$residueI2;
3844
+ return (residueIndex < plddtValues.length ? ((_plddtValues$residueI2 = plddtValues[residueIndex]) !== null && _plddtValues$residueI2 !== void 0 ? _plddtValues$residueI2 : 0) * 100 : 50).toFixed(2);
3845
+ }
3846
+ function isLoopStart(line) {
3847
+ return line.trim() === "loop_" || line.trim().startsWith("loop_");
3848
+ }
3849
+ function isAtomSiteColumn(line) {
3850
+ return line.trim().startsWith(ATOM_SITE_PREFIX);
3851
+ }
3852
+ function endsAtomSiteLoop(line) {
3853
+ const trimmed = line.trim();
3854
+ if (trimmed === "") return false;
3855
+ if (trimmed.startsWith("#")) return true;
3856
+ if (isLoopStart(trimmed)) return true;
3857
+ if (trimmed.startsWith("data_") || trimmed.startsWith("save_")) return true;
3858
+ return trimmed.startsWith("_") && !trimmed.startsWith(ATOM_SITE_PREFIX);
3859
+ }
3860
+ function isAtomSiteLoop(lines, loopIndex) {
3861
+ let peek = loopIndex + 1;
3862
+ while (peek < lines.length && lines[peek].trim() === "") peek += 1;
3863
+ return peek < lines.length && isAtomSiteColumn(lines[peek]);
3864
+ }
3865
+ function ensureBFactorColumn(columns, headerLines) {
3866
+ const existing = columnIndex(columns, B_FACTOR_COLUMN);
3867
+ if (existing >= 0) return existing;
3868
+ columns.push(B_FACTOR_COLUMN);
3869
+ headerLines.push(`${ATOM_SITE_PREFIX}${B_FACTOR_COLUMN}`);
3870
+ return columns.length - 1;
3871
+ }
3872
+ function rewriteAtomSiteRow(dataLine, columns, bIndex, plddtValues, walk) {
3873
+ if (dataLine.trim() === "") return dataLine;
3874
+ const tokens = tokenizeCifLine(dataLine);
3875
+ if (tokens.length === 0) return dataLine;
3876
+ while (tokens.length < columns.length) tokens.push(".");
3877
+ if (isAtomSiteRow(tokens, columns)) {
3878
+ const residue = mmcifResidueKey(tokens, columns);
3879
+ if (residue !== walk.lastResidue) {
3880
+ walk.residueIndex += 1;
3881
+ walk.lastResidue = residue;
3882
+ }
3883
+ tokens[bIndex] = plddtBFactor(walk.residueIndex, plddtValues);
3884
+ }
3885
+ return tokens.join(" ");
3886
+ }
3887
+ function rewriteAtomSiteLoop(lines, loopIndex, plddtValues, walk) {
3888
+ const rows = [lines[loopIndex]];
3889
+ let i = loopIndex + 1;
3890
+ const columns = [];
3891
+ while (i < lines.length && isAtomSiteColumn(lines[i])) {
3892
+ columns.push(lines[i].trim().slice(11));
3893
+ rows.push(lines[i]);
3894
+ i += 1;
3895
+ }
3896
+ const bIndex = ensureBFactorColumn(columns, rows);
3897
+ while (i < lines.length && !endsAtomSiteLoop(lines[i])) {
3898
+ rows.push(rewriteAtomSiteRow(lines[i], columns, bIndex, plddtValues, walk));
3899
+ i += 1;
3900
+ }
3901
+ return {
3902
+ next: i,
3903
+ rows
3904
+ };
3905
+ }
3906
+ /**
3907
+ * Rewrites an mmCIF (PDBx) file's `_atom_site.B_iso_or_equiv` column with
3908
+ * pLDDT scores so Mol* can read them off the parsed model, the same way
3909
+ * `injectPlddtIntoPdb` rewrites the PDB B-factor column. Scores arrive on a
3910
+ * 0-1 scale and are stored on the conventional 0-100 one. Residues past the
3911
+ * end of `plddtValues` fall back to a mid-confidence 50.
3912
+ *
3913
+ * If the file has no B-factor column, one is appended to the atom-site loop
3914
+ * rather than leaving the scores behind.
3915
+ */
3916
+ function injectPlddtIntoMmcif(mmcifData, plddtValues) {
3917
+ const lines = mmcifData.split("\n");
3918
+ const result = [];
3919
+ const walk = {
3920
+ lastResidue: "",
3921
+ residueIndex: -1
3922
+ };
3923
+ let i = 0;
3924
+ let rewrittenLoop = false;
3925
+ while (i < lines.length) {
3926
+ const line = lines[i];
3927
+ if (!rewrittenLoop && isLoopStart(line) && isAtomSiteLoop(lines, i)) {
3928
+ const rewritten = rewriteAtomSiteLoop(lines, i, plddtValues, walk);
3929
+ result.push(...rewritten.rows);
3930
+ i = rewritten.next;
3931
+ rewrittenLoop = true;
3932
+ continue;
3933
+ }
3934
+ result.push(line);
3935
+ i += 1;
3936
+ }
3937
+ return result.join("\n");
3938
+ }
3939
+ /**
3940
+ * Rewrites a structure file's B-factors with pLDDT scores. Dispatches to
3941
+ * `injectPlddtIntoPdb` or `injectPlddtIntoMmcif` from `format`, or from
3942
+ * detecting the format of `data` when `format` is omitted.
3943
+ */
3944
+ function injectPlddt(data, plddtValues, format = detectStructureFormat(data)) {
3945
+ return format === "mmcif" ? injectPlddtIntoMmcif(data, plddtValues) : injectPlddtIntoPdb(data, plddtValues);
3946
+ }
2411
3947
  /**
2412
3948
  * Mol* color theme that reads pLDDT scores out of the B-factor column, paired
2413
- * with `injectPlddtIntoPdb`. Registered per plugin instance.
3949
+ * with `injectPlddt`. Registered per plugin instance.
2414
3950
  */
2415
3951
  const PlddtColoring = CustomElementProperty.create({
2416
3952
  coloring: {
@@ -2427,31 +3963,7 @@ const PlddtColoring = CustomElementProperty.create({
2427
3963
  },
2428
3964
  label: "pLDDT",
2429
3965
  name: PLDDT_THEME_NAME
2430
- });
2431
- //#endregion
2432
- //#region src/core/ProteinStructureViewer/utils/color.ts
2433
- /** Parses `#RRGGBB` (or `RRGGBB`) into a Mol* `Color`. */
2434
- function parseHexColor(hex) {
2435
- const h = hex.replace("#", "");
2436
- return Color.fromRgb(parseInt(h.substring(0, 2), 16), parseInt(h.substring(2, 4), 16), parseInt(h.substring(4, 6), 16));
2437
- }
2438
- /**
2439
- * Parses a theme color into a Mol* `Color`, falling back when the token is
2440
- * missing or is a format Mol* cannot consume (theme values are hex in practice,
2441
- * but the palette types allow any CSS color string).
2442
- */
2443
- function themeColor(value, fallback) {
2444
- const candidate = value === null || value === void 0 ? void 0 : value.trim();
2445
- return parseHexColor(candidate !== void 0 && /^#?[0-9a-f]{6}$/i.test(candidate) ? candidate : fallback);
2446
- }
2447
- /**
2448
- * Neutral fill for residues with no overlay value. Sits between the light and
2449
- * dark backgrounds so unhighlighted geometry stays legible in both modes.
2450
- */
2451
- function neutralResidueColor(mode) {
2452
- const g = mode === "dark" ? 100 : 180;
2453
- return Color.fromRgb(g, g, g);
2454
- }
3966
+ });
2455
3967
  //#endregion
2456
3968
  //#region src/core/ProteinStructureViewer/utils/residueValueTheme.ts
2457
3969
  /** Mol* color theme name under which residue value overlays are registered. */
@@ -2510,10 +4022,13 @@ function createResidueValueTheme(mode) {
2510
4022
  }
2511
4023
  //#endregion
2512
4024
  //#region src/core/ProteinStructureViewer/hooks/useMolstarPlugin.ts
2513
- /** Structure representation Mol* builds for the loaded model. */
2514
- const REPRESENTATION_PRESET = "polymer-cartoon";
2515
- /** Theme used when no pLDDT scores are supplied. */
2516
- const FALLBACK_THEME_NAME = "chain-id";
4025
+ /**
4026
+ * Theme used when neither pLDDT scores nor an overlay are supplied. Our own
4027
+ * per-chain theme rather than Mol*'s built-in `chain-id`, so the chain legend
4028
+ * can show swatches that match the structure instead of guessing at the colors
4029
+ * Mol* picked.
4030
+ */
4031
+ const FALLBACK_THEME_NAME = CHAIN_COLOR_THEME_NAME;
2517
4032
  /** Delay before retrying initialization while the container has no size. */
2518
4033
  const LAYOUT_RETRY_MS = 100;
2519
4034
  /** How long to wait for a frame before starting without one. */
@@ -2550,38 +4065,6 @@ function nextFrame() {
2550
4065
  */
2551
4066
  const HIGHLIGHT_STRENGTH = .2;
2552
4067
  const SELECT_STRENGTH = 0;
2553
- const AXES_ON = {
2554
- name: "on",
2555
- params: {
2556
- alpha: .51,
2557
- colorX: 16711680,
2558
- colorY: 32768,
2559
- colorZ: 255,
2560
- labelColorX: 8421504,
2561
- labelColorY: 8421504,
2562
- labelColorZ: 8421504,
2563
- labelOpacity: 1,
2564
- labelScale: .25,
2565
- labelX: "X",
2566
- labelY: "Y",
2567
- labelZ: "Z",
2568
- location: "bottom-left",
2569
- locationOffsetX: 0,
2570
- locationOffsetY: 0,
2571
- originColor: 8421504,
2572
- planeColorXY: 8421504,
2573
- planeColorXZ: 8421504,
2574
- planeColorYZ: 8421504,
2575
- radiusScale: .075,
2576
- scale: .15,
2577
- showLabels: false,
2578
- showPlanes: true
2579
- }
2580
- };
2581
- const AXES_OFF = {
2582
- name: "off",
2583
- params: {}
2584
- };
2585
4068
  /**
2586
4069
  * Turns the screenshot controls off, on the versions of Mol* that have them.
2587
4070
  *
@@ -2607,13 +4090,13 @@ function createViewer(_x) {
2607
4090
  return _createViewer.apply(this, arguments);
2608
4091
  }
2609
4092
  function _createViewer() {
2610
- _createViewer = _asyncToGenerator(function* ({ backgroundColor, edgeColor, highlightColor, residueValueTheme, root, showAxes, showSequenceViewer, viewSettings }) {
4093
+ _createViewer = _asyncToGenerator(function* ({ backgroundColor, chainColorTheme, edgeColor, highlightColor, molstarSpec, residueValueTheme, root, showAxes, showSequenceViewer, viewSettings }) {
2611
4094
  var _spec$config;
2612
4095
  const spec = DefaultPluginUISpec();
2613
4096
  const behaviors = spec.behaviors.filter((b) => b.transformer !== PluginBehaviors.Camera.FocusLoci);
2614
4097
  const plugin = yield createPluginUI({
2615
4098
  render: renderReact18,
2616
- spec: _objectSpread2(_objectSpread2({}, spec), {}, {
4099
+ spec: mergeMolstarSpec(_objectSpread2(_objectSpread2({}, spec), {}, {
2617
4100
  behaviors,
2618
4101
  canvas3d: {
2619
4102
  camera: { helper: { axes: showAxes ? AXES_ON : AXES_OFF } },
@@ -2629,10 +4112,16 @@ function _createViewer() {
2629
4112
  selectStrength: SELECT_STRENGTH
2630
4113
  }
2631
4114
  },
2632
- components: _objectSpread2({
4115
+ components: {
4116
+ controls: {
4117
+ bottom: "none",
4118
+ left: "none",
4119
+ right: "none"
4120
+ },
2633
4121
  remoteState: "none",
2634
- sequenceViewer: { view: createSequenceView(viewSettings) }
2635
- }, showAxes && { viewport: { view: createViewportView(viewSettings) } }),
4122
+ sequenceViewer: { view: createSequenceView(viewSettings) },
4123
+ viewport: { view: createViewportView(viewSettings) }
4124
+ },
2636
4125
  config: [
2637
4126
  ...(_spec$config = spec.config) !== null && _spec$config !== void 0 ? _spec$config : [],
2638
4127
  [PluginConfig.Viewport.ShowExpand, false],
@@ -2653,12 +4142,13 @@ function _createViewer() {
2653
4142
  top: showSequenceViewer ? "full" : "hidden"
2654
4143
  }
2655
4144
  } }
2656
- }),
4145
+ }), molstarSpec),
2657
4146
  target: root
2658
4147
  });
2659
4148
  const registry = plugin.representation.structure.themes.colorThemeRegistry;
2660
4149
  if (PlddtColoring.colorThemeProvider) registry.add(PlddtColoring.colorThemeProvider);
2661
4150
  registry.add(residueValueTheme.provider);
4151
+ registry.add(chainColorTheme.provider);
2662
4152
  for (const p of [...plugin.managers.lociLabels.providers]) plugin.managers.lociLabels.removeProvider(p);
2663
4153
  plugin.managers.structure.focus.behaviors.current.subscribe((entry) => {
2664
4154
  const select = plugin.managers.interactivity.lociSelects;
@@ -2669,44 +4159,190 @@ function _createViewer() {
2669
4159
  });
2670
4160
  return _createViewer.apply(this, arguments);
2671
4161
  }
2672
- function loadStructure(_x2, _x3, _x4, _x5) {
4162
+ /**
4163
+ * The representation parameters Mol*'s own presets compute, read from the same
4164
+ * manager state they read. Ported rather than hardcoded so a chain drawn here
4165
+ * looks exactly like the one the preset used to draw. Mol* hands the same set
4166
+ * to its cartoons and its ball-and-sticks, and so does this.
4167
+ */
4168
+ function representationTypeParams(plugin) {
4169
+ const { hydrogens, ignoreLight, visualQuality } = plugin.managers.structure.component.state.options;
4170
+ return {
4171
+ ignoreHydrogens: hydrogens !== "all",
4172
+ ignoreHydrogensVariant: hydrogens === "only-polar" ? "non-polar" : "all",
4173
+ ignoreLight,
4174
+ quality: visualQuality
4175
+ };
4176
+ }
4177
+ /**
4178
+ * The two halves of a chain the viewer draws. Each names the component its
4179
+ * half is built under and tags the representation drawn over it, and it is
4180
+ * that tag `applyColorTheme` reads back to tell the two apart.
4181
+ */
4182
+ const POLYMER_PART = "polymer";
4183
+ const LIGAND_PART = "ligand";
4184
+ /**
4185
+ * True for the representation drawing a chain's heteroatoms.
4186
+ *
4187
+ * Read off the tag put on the representation when it was built, rather than
4188
+ * off the component's key. Mol* does not store the key as it was given: it
4189
+ * files components under `structure-component-<key>`, so a test against the
4190
+ * key as written here silently matches nothing, and every ligand quietly takes
4191
+ * the structure-wide theme instead. The tag survives untouched.
4192
+ */
4193
+ function isLigandRepresentation(representation) {
4194
+ var _representation$cell$;
4195
+ return ((_representation$cell$ = representation.cell.transform.tags) === null || _representation$cell$ === void 0 ? void 0 : _representation$cell$.includes(LIGAND_PART)) === true;
4196
+ }
4197
+ /**
4198
+ * How heteroatoms are colored: the theme Mol* puts on a ball-and-stick when
4199
+ * left to itself, with the parameters it chooses too.
4200
+ *
4201
+ * Named rather than left blank only so that it survives `applyColorTheme`,
4202
+ * which would otherwise repaint the ligands along with everything else. The
4203
+ * structure-wide theme is the wrong answer for them twice over: a heme reads
4204
+ * as a heme because its iron is orange and its nitrogens are blue, which one
4205
+ * flat color throws away, and pLDDT and residue overlays have no value for a
4206
+ * HETATM to be colored by at all.
4207
+ */
4208
+ const ELEMENT_THEME = "element-symbol";
4209
+ /**
4210
+ * Draws one chain: its polymer as a cartoon, its ligands and ions as
4211
+ * ball-and-stick.
4212
+ *
4213
+ * Two components rather than one, because a component is what a representation
4214
+ * attaches to and neither representation suits both halves - a cartoon has no
4215
+ * backbone to trace through a heme, and a ball-and-stick over the whole chain
4216
+ * would draw every protein atom as a sphere.
4217
+ *
4218
+ * Hands back the refs of whichever components the chain turned out to have,
4219
+ * which is what `setSubtreeVisibility` is later pointed at. Grouping them
4220
+ * under the chain is what makes hiding a chain take its ligands with it.
4221
+ */
4222
+ function buildChainComponents(_x5, _x6, _x7, _x8) {
4223
+ return _buildChainComponents.apply(this, arguments);
4224
+ }
4225
+ function _buildChainComponents() {
4226
+ _buildChainComponents = _asyncToGenerator(function* (plugin, structure, chain, typeParams) {
4227
+ const builders = plugin.builders.structure;
4228
+ const refs = [];
4229
+ const addPart = function() {
4230
+ var _ref = _asyncToGenerator(function* (part, expression, props) {
4231
+ const component = yield builders.tryCreateComponentFromExpression(structure, expression, `${part}-${chain.chainId}`, { label: chain.label });
4232
+ if (!component) return;
4233
+ yield builders.representation.addRepresentation(component, props, { tag: part });
4234
+ refs.push(component.ref);
4235
+ });
4236
+ return function addPart(_x2, _x3, _x4) {
4237
+ return _ref.apply(this, arguments);
4238
+ };
4239
+ }();
4240
+ yield addPart(POLYMER_PART, chainPolymerExpression(chain.chainId), {
4241
+ type: "cartoon",
4242
+ typeParams
4243
+ });
4244
+ yield addPart(LIGAND_PART, chainLigandExpression(chain.chainId), {
4245
+ color: ELEMENT_THEME,
4246
+ type: "ball-and-stick",
4247
+ typeParams
4248
+ });
4249
+ return refs;
4250
+ });
4251
+ return _buildChainComponents.apply(this, arguments);
4252
+ }
4253
+ const NOTHING_LOADED = {
4254
+ chains: [],
4255
+ componentRefs: /* @__PURE__ */ new Map(),
4256
+ residuesByChain: /* @__PURE__ */ new Map()
4257
+ };
4258
+ /**
4259
+ * Parses the structure and draws each chain: a cartoon over its polymer, and
4260
+ * ball-and-stick over its ligands and ions.
4261
+ *
4262
+ * Mol*'s `default` hierarchy preset would be shorter, but it groups every
4263
+ * polymer chain into a single component, and a component is the unit Mol* can
4264
+ * hide. Building them per chain is what makes a chain individually hideable;
4265
+ * the refs handed back are what `setSubtreeVisibility` is later pointed at.
4266
+ *
4267
+ * The wrapper detects PDB vs mmCIF from the text; this just forwards that
4268
+ * guess to Mol*.
4269
+ */
4270
+ function loadStructure(_x9, _x10, _x11, _x12) {
2673
4271
  return _loadStructure.apply(this, arguments);
2674
4272
  }
2675
4273
  function _loadStructure() {
2676
- _loadStructure = _asyncToGenerator(function* (plugin, pdbData, usePlddtColoring, showAxes) {
4274
+ _loadStructure = _asyncToGenerator(function* (plugin, structureText, usePlddtColoring, showAxes) {
2677
4275
  try {
2678
4276
  var _plugin$canvas3d;
2679
4277
  yield plugin.clear();
2680
4278
  const data = yield plugin.builders.data.rawData({
2681
- data: pdbData,
4279
+ data: structureText,
2682
4280
  label: "Structure"
2683
4281
  });
2684
- const trajectory = yield plugin.builders.structure.parseTrajectory(data, "pdb");
2685
- yield plugin.builders.structure.hierarchy.applyPreset(trajectory, "default", {
2686
- representationPreset: REPRESENTATION_PRESET,
2687
- showUnitcell: false,
2688
- structure: {
2689
- name: "model",
2690
- params: {}
2691
- }
4282
+ const trajectory = yield plugin.builders.structure.parseTrajectory(data, detectStructureFormat(structureText));
4283
+ const model = yield plugin.builders.structure.createModel(trajectory);
4284
+ const structure = yield plugin.builders.structure.createStructure(model, {
4285
+ name: "model",
4286
+ params: {}
2692
4287
  });
4288
+ const data3d = structure.data;
4289
+ if (!data3d) return NOTHING_LOADED;
4290
+ const { chainLabels, chains, residuesByChain } = scanChains(data3d);
4291
+ const typeParams = representationTypeParams(plugin);
4292
+ const componentRefs = /* @__PURE__ */ new Map();
4293
+ for (const [chainId, label] of chainLabels) {
4294
+ const refs = yield buildChainComponents(plugin, structure, {
4295
+ chainId,
4296
+ label
4297
+ }, typeParams);
4298
+ if (refs.length > 0) componentRefs.set(chainId, refs);
4299
+ }
2693
4300
  if (usePlddtColoring) yield applyColorTheme(plugin, PLDDT_THEME_NAME);
2694
4301
  (_plugin$canvas3d = plugin.canvas3d) === null || _plugin$canvas3d === void 0 || _plugin$canvas3d.requestCameraReset();
2695
4302
  setAxes(plugin, showAxes);
4303
+ return {
4304
+ chains,
4305
+ componentRefs,
4306
+ residuesByChain
4307
+ };
2696
4308
  } catch (error) {
2697
4309
  console.error("Failed to load structure:", error);
4310
+ return NOTHING_LOADED;
2698
4311
  }
2699
4312
  });
2700
4313
  return _loadStructure.apply(this, arguments);
2701
4314
  }
2702
- /** Recolors every loaded structure's representations with the named theme. */
2703
- function applyColorTheme(_x6, _x7) {
4315
+ /**
4316
+ * Shows or hides everything each chain is drawn with, cartoon and sticks
4317
+ * alike. Every component under the chain, so hiding it takes its ligands with
4318
+ * it rather than leaving a heme floating where its protein used to be.
4319
+ *
4320
+ * The whole subtree of each, not just the component cell: visibility is
4321
+ * per-cell, and it is the representation underneath that actually draws.
4322
+ *
4323
+ * Set outright rather than through the component manager's `toggleVisibility`,
4324
+ * which flips whatever it finds: the hidden set is derived from props on every
4325
+ * pass, so it has to be applied as a statement of what should be true and not
4326
+ * as a change to what already is.
4327
+ */
4328
+ function applyChainVisibility(plugin, componentRefs, hidden) {
4329
+ for (const [chainId, refs] of componentRefs) for (const ref of refs) setSubtreeVisibility(plugin.state.data, ref, hidden.has(chainId));
4330
+ }
4331
+ /**
4332
+ * Recolors every loaded structure's representations with the named theme,
4333
+ * leaving the heteroatoms on `ELEMENT_THEME`.
4334
+ *
4335
+ * The per-representation form of `updateRepresentationsTheme`, so the two can
4336
+ * be told apart in one pass; handing it a filtered list instead would leave
4337
+ * the ligands on whichever theme happened to be current when they were built.
4338
+ */
4339
+ function applyColorTheme(_x13, _x14) {
2704
4340
  return _applyColorTheme.apply(this, arguments);
2705
4341
  }
2706
4342
  function _applyColorTheme() {
2707
4343
  _applyColorTheme = _asyncToGenerator(function* (plugin, colorTheme) {
2708
4344
  yield plugin.dataTransaction(_asyncToGenerator(function* () {
2709
- for (const s of plugin.managers.structure.hierarchy.current.structures) yield plugin.managers.structure.component.updateRepresentationsTheme(s.components, { color: colorTheme });
4345
+ 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 }));
2710
4346
  }));
2711
4347
  });
2712
4348
  return _applyColorTheme.apply(this, arguments);
@@ -2717,14 +4353,39 @@ function _applyColorTheme() {
2717
4353
  *
2718
4354
  * The plugin is built once and then mutated in place. Creating it is expensive
2719
4355
  * and destroys the camera, so prop changes that Mol* can absorb (background,
2720
- * axes, coloring, new PDB) are pushed in through the effects below and in the
2721
- * sibling hooks rather than by rebuilding.
4356
+ * axes, coloring, new structure) are pushed in through the effects below and in
4357
+ * the sibling hooks rather than by rebuilding.
2722
4358
  */
2723
- function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt, highlightColor, mode, onResidueClick, onResidueHover, onSelectionClear, pdb, sequenceViewerBackgroundColor, showAxes, showSequenceViewer }) {
4359
+ function useMolstarPlugin({ backgroundColor, chainColors, containerRef, download, edgeColor, hasPlddt, hiddenChains, highlightColor, mode, molstarSpec, onChainHover, onChainSelect, onChainToggle, onResidueClick, onResidueHover, onSelectionChange, onSelectionClear, selectedChains, sequenceViewerBackgroundColor, showAxes, showSequenceViewer, structure }) {
2724
4360
  const pluginRef = useRef(null);
2725
4361
  const residueValueThemeRef = useRef(null);
2726
- const currentPdbRef = useRef(null);
4362
+ const chainColorThemeRef = useRef(null);
4363
+ const currentStructureRef = useRef(null);
2727
4364
  const [isReady, setIsReady] = useState(false);
4365
+ const [chains, setChains] = useState([]);
4366
+ const [loadCount, setLoadCount] = useState(0);
4367
+ /**
4368
+ * Where each chain's components live in the state tree, which is what the
4369
+ * visibility effect points `setSubtreeVisibility` at. Rewritten by every
4370
+ * load, since the refs do not survive `plugin.clear()`.
4371
+ */
4372
+ const componentRefsRef = useRef(/* @__PURE__ */ new Map());
4373
+ /**
4374
+ * Which residues sit on each chain, for the readout to average a score over
4375
+ * a whole-chain selection. A ref rather than state: nothing renders from it
4376
+ * directly, and it is rewritten in step with `chains`, which does.
4377
+ */
4378
+ const residuesByChainRef = useRef(/* @__PURE__ */ new Map());
4379
+ /**
4380
+ * The visibility and coloring to apply as soon as a structure exists. Read
4381
+ * through refs because both arrive as fresh objects on every render, and a
4382
+ * load has to be able to consult them without the load effect depending on
4383
+ * them - a new Set each render would reload the structure on every pass.
4384
+ */
4385
+ const hiddenChainsRef = useRef(hiddenChains);
4386
+ hiddenChainsRef.current = hiddenChains;
4387
+ const chainColorsRef = useRef(chainColors);
4388
+ chainColorsRef.current = chainColors;
2728
4389
  /**
2729
4390
  * Carries the theme-dependent props into the views Mol* renders in its own
2730
4391
  * React root. They cannot read them from context, and rebuilding the plugin
@@ -2733,7 +4394,8 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2733
4394
  const viewSettingsRef = useRef(null);
2734
4395
  if (viewSettingsRef.current === null) viewSettingsRef.current = new BehaviorSubject({
2735
4396
  mode,
2736
- sequenceViewerBackgroundColor
4397
+ sequenceViewerBackgroundColor,
4398
+ showAxes
2737
4399
  });
2738
4400
  const viewSettings = viewSettingsRef.current;
2739
4401
  /**
@@ -2744,10 +4406,28 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2744
4406
  const setClipRatio = useCallback((ratio) => {
2745
4407
  clipRatioRef.current = ratio;
2746
4408
  }, []);
4409
+ /**
4410
+ * Takes up what a load produced: the component refs the chain-keyed props
4411
+ * address, the visibility they were already asking for, and the chain list
4412
+ * the consumer is told about.
4413
+ *
4414
+ * Chains are published only when they actually differ, so reloading the same
4415
+ * structure - a theme switch that happens to reload, a parent handing back an
4416
+ * equal PDB string - does not hand every consumer a new array to react to.
4417
+ */
4418
+ const adoptLoadedStructure = useCallback((plugin, loaded) => {
4419
+ componentRefsRef.current = loaded.componentRefs;
4420
+ residuesByChainRef.current = loaded.residuesByChain;
4421
+ applyChainVisibility(plugin, loaded.componentRefs, hiddenChainsRef.current);
4422
+ setChains((prev) => chainsEqual(prev, loaded.chains) ? prev : loaded.chains);
4423
+ setLoadCount((count) => count + 1);
4424
+ }, []);
2747
4425
  const onResidueClickRef = useRef(onResidueClick);
2748
4426
  onResidueClickRef.current = onResidueClick;
2749
4427
  const onSelectionClearRef = useRef(onSelectionClear);
2750
4428
  onSelectionClearRef.current = onSelectionClear;
4429
+ const onSelectionChangeRef = useRef(onSelectionChange);
4430
+ onSelectionChangeRef.current = onSelectionChange;
2751
4431
  const onResidueHoverRef = useRef(onResidueHover);
2752
4432
  onResidueHoverRef.current = onResidueHover;
2753
4433
  /** Last residue reported to `onResidueHover`, to suppress repeats. */
@@ -2758,9 +4438,10 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2758
4438
  hasPlddt,
2759
4439
  highlightColor,
2760
4440
  mode,
2761
- pdb,
4441
+ molstarSpec,
2762
4442
  showAxes,
2763
- showSequenceViewer
4443
+ showSequenceViewer,
4444
+ structure
2764
4445
  });
2765
4446
  initialPropsRef.current = {
2766
4447
  backgroundColor,
@@ -2768,17 +4449,32 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2768
4449
  hasPlddt,
2769
4450
  highlightColor,
2770
4451
  mode,
2771
- pdb,
4452
+ molstarSpec,
2772
4453
  showAxes,
2773
- showSequenceViewer
4454
+ showSequenceViewer,
4455
+ structure
2774
4456
  };
4457
+ /**
4458
+ * The consumer's `canvas3d` overrides, keyed by content. Unlike the rest of
4459
+ * the spec these are re-applied when they change, and they commonly arrive
4460
+ * as an object written inline - so the effect below turns on what they say
4461
+ * rather than on the identity of the object saying it.
4462
+ */
4463
+ const canvas3dOverrideKey = (() => {
4464
+ try {
4465
+ var _molstarSpec$canvas3d;
4466
+ return JSON.stringify((_molstarSpec$canvas3d = molstarSpec === null || molstarSpec === void 0 ? void 0 : molstarSpec.canvas3d) !== null && _molstarSpec$canvas3d !== void 0 ? _molstarSpec$canvas3d : null);
4467
+ } catch (_unused) {
4468
+ return String(Date.now());
4469
+ }
4470
+ })();
2775
4471
  useEffect(() => {
2776
4472
  const container = containerRef.current;
2777
4473
  if (!container) return;
2778
4474
  let cancelled = false;
2779
4475
  let clipSubscription;
2780
4476
  const init = function() {
2781
- var _ref = _asyncToGenerator(function* () {
4477
+ var _ref2 = _asyncToGenerator(function* () {
2782
4478
  yield nextFrame();
2783
4479
  if (cancelled) return;
2784
4480
  const rect = container.getBoundingClientRect();
@@ -2790,10 +4486,13 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2790
4486
  try {
2791
4487
  var _plugin$canvas3d2;
2792
4488
  const residueValueTheme = createResidueValueTheme(initial.mode);
4489
+ const chainColorTheme = createChainColorTheme();
2793
4490
  const plugin = yield createViewer({
2794
4491
  backgroundColor: initial.backgroundColor,
4492
+ chainColorTheme,
2795
4493
  edgeColor: initial.edgeColor,
2796
4494
  highlightColor: initial.highlightColor,
4495
+ molstarSpec: initial.molstarSpec,
2797
4496
  residueValueTheme,
2798
4497
  root: container,
2799
4498
  showAxes: initial.showAxes,
@@ -2806,11 +4505,28 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2806
4505
  }
2807
4506
  pluginRef.current = plugin;
2808
4507
  residueValueThemeRef.current = residueValueTheme;
4508
+ chainColorThemeRef.current = chainColorTheme;
2809
4509
  const latest = initialPropsRef.current;
2810
- yield loadStructure(plugin, latest.pdb, latest.hasPlddt, latest.showAxes);
2811
- currentPdbRef.current = latest.pdb;
4510
+ const loaded = yield loadStructure(plugin, latest.structure, latest.hasPlddt, latest.showAxes);
4511
+ currentStructureRef.current = latest.structure;
4512
+ adoptLoadedStructure(plugin, loaded);
4513
+ /**
4514
+ * Mol*'s click behavior is a BehaviorSubject, so subscribing replays
4515
+ * whatever it is currently holding - which, before anything has been
4516
+ * clicked, is an empty click. Acting on that would read as the user
4517
+ * clicking empty space and clear a selection the consumer had set
4518
+ * before the viewer was even interactive.
4519
+ *
4520
+ * Only the replay is skipped, not every empty click: clicking away
4521
+ * from the structure is how a selection is meant to be cleared.
4522
+ */
4523
+ let clickReplayConsumed = false;
2812
4524
  plugin.behaviors.interaction.click.subscribe((e) => {
2813
- var _onResidueClickRef$cu;
4525
+ var _onResidueClickRef$cu, _onSelectionChangeRef;
4526
+ if (!clickReplayConsumed) {
4527
+ clickReplayConsumed = true;
4528
+ if (Representation.Loci.isEmpty(e.current)) return;
4529
+ }
2814
4530
  if (Representation.Loci.isEmpty(e.current)) {
2815
4531
  var _onSelectionClearRef$;
2816
4532
  (_onSelectionClearRef$ = onSelectionClearRef.current) === null || _onSelectionClearRef$ === void 0 || _onSelectionClearRef$.call(onSelectionClearRef);
@@ -2821,6 +4537,7 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2821
4537
  const residue = residueRefFromLoci(loci);
2822
4538
  if (!residue) return;
2823
4539
  (_onResidueClickRef$cu = onResidueClickRef.current) === null || _onResidueClickRef$cu === void 0 || _onResidueClickRef$cu.call(onResidueClickRef, residue);
4540
+ (_onSelectionChangeRef = onSelectionChangeRef.current) === null || _onSelectionChangeRef === void 0 || _onSelectionChangeRef.call(onSelectionChangeRef, selectionFromLoci(loci));
2824
4541
  });
2825
4542
  plugin.behaviors.interaction.hover.subscribe((e) => {
2826
4543
  var _lastHoverRef$current, _onResidueHoverRef$cu;
@@ -2839,7 +4556,7 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2839
4556
  }
2840
4557
  });
2841
4558
  return function init() {
2842
- return _ref.apply(this, arguments);
4559
+ return _ref2.apply(this, arguments);
2843
4560
  };
2844
4561
  }();
2845
4562
  init();
@@ -2850,13 +4567,16 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2850
4567
  (_pluginRef$current = pluginRef.current) === null || _pluginRef$current === void 0 || _pluginRef$current.dispose();
2851
4568
  pluginRef.current = null;
2852
4569
  residueValueThemeRef.current = null;
2853
- currentPdbRef.current = null;
4570
+ chainColorThemeRef.current = null;
4571
+ componentRefsRef.current = /* @__PURE__ */ new Map();
4572
+ residuesByChainRef.current = /* @__PURE__ */ new Map();
4573
+ currentStructureRef.current = null;
2854
4574
  clipRatioRef.current = null;
2855
4575
  setIsReady(false);
2856
4576
  };
2857
4577
  }, []);
2858
4578
  useEffect(() => {
2859
- var _pluginRef$current2;
4579
+ var _pluginRef$current2, _initialPropsRef$curr;
2860
4580
  const canvas3d = (_pluginRef$current2 = pluginRef.current) === null || _pluginRef$current2 === void 0 ? void 0 : _pluginRef$current2.canvas3d;
2861
4581
  if (!canvas3d || !isReady) return;
2862
4582
  canvas3d.setProps({
@@ -2869,20 +4589,37 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2869
4589
  highlightColor
2870
4590
  }
2871
4591
  });
4592
+ const override = (_initialPropsRef$curr = initialPropsRef.current.molstarSpec) === null || _initialPropsRef$curr === void 0 ? void 0 : _initialPropsRef$curr.canvas3d;
4593
+ if (override) canvas3d.setProps(override);
2872
4594
  }, [
2873
4595
  backgroundColor,
4596
+ canvas3dOverrideKey,
2874
4597
  edgeColor,
2875
4598
  highlightColor,
2876
4599
  isReady
2877
4600
  ]);
2878
4601
  useEffect(() => {
2879
4602
  viewSettings.next({
4603
+ download,
4604
+ hiddenChains,
2880
4605
  mode,
2881
- sequenceViewerBackgroundColor
4606
+ onChainHover,
4607
+ onChainSelect,
4608
+ onChainToggle,
4609
+ selectedChains,
4610
+ sequenceViewerBackgroundColor,
4611
+ showAxes
2882
4612
  });
2883
4613
  }, [
4614
+ download,
4615
+ hiddenChains,
2884
4616
  mode,
4617
+ onChainHover,
4618
+ onChainSelect,
4619
+ onChainToggle,
4620
+ selectedChains,
2885
4621
  sequenceViewerBackgroundColor,
4622
+ showAxes,
2886
4623
  viewSettings
2887
4624
  ]);
2888
4625
  useEffect(() => {
@@ -2892,124 +4629,333 @@ function useMolstarPlugin({ backgroundColor, containerRef, edgeColor, hasPlddt,
2892
4629
  useEffect(() => {
2893
4630
  const plugin = pluginRef.current;
2894
4631
  if (!plugin || !isReady) return;
2895
- if (pdb === currentPdbRef.current) return;
2896
- currentPdbRef.current = pdb;
4632
+ if (structure === currentStructureRef.current) return;
4633
+ currentStructureRef.current = structure;
2897
4634
  clipRatioRef.current = null;
2898
4635
  lastHoverRef.current = null;
2899
- loadStructure(plugin, pdb, hasPlddt, showAxes);
4636
+ loadStructure(plugin, structure, hasPlddt, showAxes).then((loaded) => {
4637
+ if (pluginRef.current !== plugin) return;
4638
+ adoptLoadedStructure(plugin, loaded);
4639
+ });
2900
4640
  }, [
2901
- pdb,
4641
+ structure,
2902
4642
  hasPlddt,
2903
- isReady
4643
+ isReady,
4644
+ adoptLoadedStructure
2904
4645
  ]);
4646
+ useEffect(() => {
4647
+ const plugin = pluginRef.current;
4648
+ if (!plugin || !isReady) return;
4649
+ applyChainVisibility(plugin, componentRefsRef.current, hiddenChains);
4650
+ }, [hiddenChains, isReady]);
2905
4651
  return {
4652
+ chainColorThemeRef,
4653
+ chains,
2906
4654
  isReady,
4655
+ loadCount,
2907
4656
  pluginRef,
4657
+ residuesByChainRef,
2908
4658
  residueValueThemeRef,
2909
4659
  setClipRatio
2910
4660
  };
2911
4661
  }
2912
4662
  //#endregion
2913
- //#region src/core/ProteinStructureViewer/utils/residueLoci.ts
4663
+ //#region src/core/ProteinStructureViewer/utils/focusRepresentation.ts
4664
+ /**
4665
+ * What Mol* draws around a focused selection, as ball-and-stick over the
4666
+ * cartoon: the selection itself, the residues near it, and the non-covalent
4667
+ * contacts between the two. All three stay on; what changes is how far "near"
4668
+ * reaches.
4669
+ */
4670
+ const FOCUS_COMPONENTS = [
4671
+ "target",
4672
+ "surroundings",
4673
+ "interactions"
4674
+ ];
4675
+ /** Mol*'s own default, in angstroms. */
4676
+ const NEIGHBOUR_RADIUS = 5;
2914
4677
  /**
2915
- * Every atom of the residue at a 0-based index, as geometry Mol* can focus and
2916
- * frame, or undefined when the structure has no such residue.
4678
+ * Mol* builds the surroundings as `includeSurroundings(target, radius)` with
4679
+ * whole residues, so a radius of zero resolves to the residues of the target
4680
+ * and nothing else.
4681
+ */
4682
+ const OWN_RESIDUES_ONLY = 0;
4683
+ /**
4684
+ * Chooses how far the focus shell reaches around a selection.
2917
4685
  *
2918
- * The inverse of `residueRefFromLoci`, and keyed on the same residue ordinal,
2919
- * so a `selectedResidue` echoed back from a click resolves to the residue that
2920
- * was clicked - on a complex as much as on a single chain.
4686
+ * A residue, or a short range, is a site: the 5A shell around it is the point
4687
+ * of looking at it, and Mol*'s default earns its keep. A whole chain is a
4688
+ * structural unit instead, and its neighbours are the chain bound to it - so
4689
+ * on a complex the shell reaches straight across the interface and draws the
4690
+ * partner's contact face in atoms, which reads as the partner being selected
4691
+ * too.
2921
4692
  *
2922
- * The whole residue is collected rather than one atom, since the caller frames
2923
- * the camera on the loci's bounding sphere and a single atom would zoom far
2924
- * closer than the residue warrants.
4693
+ * Taking the radius to zero confines the shell to the selection rather than
4694
+ * turning it off: the surroundings and the interactions are still drawn, over
4695
+ * the selected chain's own residues, so a chain shows its own atoms and
4696
+ * contacts and no others'.
2925
4697
  */
2926
- function lociForResidueIndex(plugin, residueIndex) {
2927
- for (const entry of plugin.managers.structure.hierarchy.current.structures) {
2928
- var _entry$cell$obj;
2929
- const structure = (_entry$cell$obj = entry.cell.obj) === null || _entry$cell$obj === void 0 ? void 0 : _entry$cell$obj.data;
2930
- if (!structure) continue;
2931
- const location = StructureElement.Location.create(structure);
2932
- for (const unit of structure.units) {
2933
- location.unit = unit;
2934
- const indices = [];
2935
- for (let i = 0; i < unit.elements.length; i++) {
2936
- location.element = unit.elements[i];
2937
- if (StructureProperties.residue.key(location) === residueIndex) indices.push(i);
2938
- }
2939
- if (indices.length > 0) return StructureElement.Loci(structure, [{
2940
- indices: OrderedSet.ofSortedArray(indices),
2941
- unit
2942
- }]);
2943
- }
2944
- }
4698
+ function setFocusNeighbourhood(_x, _x2) {
4699
+ return _setFocusNeighbourhood.apply(this, arguments);
4700
+ }
4701
+ function _setFocusNeighbourhood() {
4702
+ _setFocusNeighbourhood = _asyncToGenerator(function* (plugin, includeNeighbours) {
4703
+ const expandRadius = includeNeighbours ? NEIGHBOUR_RADIUS : OWN_RESIDUES_ONLY;
4704
+ yield plugin.state.updateBehavior(StructureFocusRepresentation, (params) => {
4705
+ params.components = FOCUS_COMPONENTS;
4706
+ params.expandRadius = expandRadius;
4707
+ });
4708
+ });
4709
+ return _setFocusNeighbourhood.apply(this, arguments);
2945
4710
  }
2946
4711
  //#endregion
2947
- //#region src/core/ProteinStructureViewer/hooks/useResidueFocus.ts
4712
+ //#region src/core/ProteinStructureViewer/hooks/useSelectionFocus.ts
2948
4713
  /**
2949
- * Makes `selectedResidue` the one thing that decides where the camera sits.
4714
+ * Points the camera at a loci and marks it.
2950
4715
  *
2951
- * Setting the prop zooms in on that residue and marks it; clearing it drops the
2952
- * focus and zooms back out. The click subscription only reports the residue it
2953
- * was given, so a click moves the camera only once the consumer accepts it and
2954
- * echoes it back - which is what the prop being controlled is supposed to mean.
4716
+ * A click has already focused what the consumer echoes back by the time it
4717
+ * arrives, so the focus is only set when it is not already what is marked;
4718
+ * setting it again would restate the selection and repaint the sequence panel
4719
+ * for nothing.
4720
+ */
4721
+ function focusLoci(plugin, loci, setClipRatio) {
4722
+ const focused = plugin.managers.structure.focus.behaviors.current.value;
4723
+ if (!focused || !StructureElement.Loci.areEqual(focused.loci, loci)) plugin.managers.structure.focus.setFromLoci(loci);
4724
+ setClipRatio(focusResidue(plugin, loci));
4725
+ }
4726
+ /**
4727
+ * Drops the focus, and the depth clipping anchored to it.
4728
+ *
4729
+ * `resetCamera` separates the two ways this happens. The consumer clearing the
4730
+ * selection means there is nothing to look at, so the view goes back to the
4731
+ * default. A selection that merely resolved to nothing visible - the chain it
4732
+ * covers having been hidden - still stands, so throwing the camera back would
4733
+ * be answering a question nobody asked.
4734
+ */
4735
+ function clearFocus(plugin, setClipRatio, resetCamera) {
4736
+ var _plugin$canvas3d;
4737
+ setClipRatio(null);
4738
+ plugin.managers.structure.focus.clear();
4739
+ if (resetCamera) (_plugin$canvas3d = plugin.canvas3d) === null || _plugin$canvas3d === void 0 || _plugin$canvas3d.requestCameraReset();
4740
+ }
4741
+ /**
4742
+ * Focuses a loci, resizing the focus shell first when this selection wants a
4743
+ * different reach than the last one did.
4744
+ *
4745
+ * The resize is asynchronous and the focus has to follow it - the shell is
4746
+ * sized before focusing so it is not drawn at the old reach and rebuilt - so
4747
+ * this hands back a teardown that abandons the focus if the effect is torn
4748
+ * down while the resize is still in flight.
4749
+ *
4750
+ * `currentShell` is the reach already configured, carried in a ref so that two
4751
+ * selections of the same kind do not each restate it.
4752
+ */
4753
+ function focusWithShell(plugin, loci, includeNeighbours, currentShell, pluginRef, setClipRatio) {
4754
+ if (currentShell.current === includeNeighbours) {
4755
+ focusLoci(plugin, loci, setClipRatio);
4756
+ return;
4757
+ }
4758
+ let cancelled = false;
4759
+ currentShell.current = includeNeighbours;
4760
+ setFocusNeighbourhood(plugin, includeNeighbours).then(() => {
4761
+ if (cancelled || pluginRef.current !== plugin) return;
4762
+ focusLoci(plugin, loci, setClipRatio);
4763
+ });
4764
+ return () => {
4765
+ cancelled = true;
4766
+ };
4767
+ }
4768
+ /**
4769
+ * Makes `selection` the one thing that decides where the camera sits.
4770
+ *
4771
+ * Setting the prop frames whatever it covers; clearing it drops the focus and
4772
+ * zooms back out. The camera frames the selection's bounding sphere, so a range
4773
+ * or a whole chain is fitted rather than approached as a point - one residue is
4774
+ * just the smallest case of that.
2955
4775
  *
2956
- * Clicking still marks the residue immediately, through Mol*'s own focus
2957
- * behavior, so the structure responds to a click whether or not the consumer
2958
- * wires the prop up.
4776
+ * Residues are also marked, which is what draws Mol*'s ball-and-stick and
4777
+ * outline over them. Whole chains are not: those are shown by dimming the
4778
+ * chains around them instead, in `useChainHighlight`.
4779
+ *
4780
+ * The click subscription only reports the selection it was given, so a click
4781
+ * moves the camera only once the consumer accepts it and echoes it back -
4782
+ * which is what the prop being controlled is supposed to mean. Clicking still
4783
+ * marks immediately, through Mol*'s own focus behavior, so the structure
4784
+ * responds to a click whether or not the consumer wires the prop up.
2959
4785
  */
2960
- function useResidueFocus({ isReady, pluginRef, selectedResidue, setClipRatio }) {
4786
+ function useSelectionFocus({ hiddenChains, isReady, pluginRef, selection, setClipRatio }) {
4787
+ var _selection$chains, _selection$residues;
2961
4788
  /**
2962
- * The residue this hook last pointed the camera at. Tracked rather than
2963
- * compared against the previous prop value so that a selection made before
2964
- * the plugin was ready is still applied once it is, and so that a plugin
2965
- * rebuilt underneath us - which comes up focused on nothing - is not assumed
2966
- * to still be holding the old one.
4789
+ * What this hook last pointed the camera at, as a key rather than the object
4790
+ * itself: a consumer echoing a selection back builds a new object each time,
4791
+ * and comparing identity would refocus on every render.
4792
+ *
4793
+ * Tracked here rather than compared against the previous prop so that a
4794
+ * selection made before the plugin was ready is still applied once it is,
4795
+ * and so that a plugin rebuilt underneath us - which comes up focused on
4796
+ * nothing - is not assumed to still be holding the old one.
2967
4797
  */
2968
4798
  const focusedRef = useRef(null);
4799
+ /**
4800
+ * Whether the focus shell currently reaches beyond the selection, so the
4801
+ * behavior is only updated when the answer actually changes rather than on
4802
+ * every selection.
4803
+ */
4804
+ const neighbourhoodRef = useRef(null);
4805
+ /**
4806
+ * What the camera should be pointed at, as a string. Hiding a chain changes
4807
+ * what there is to focus, so it belongs in here alongside the selection
4808
+ * itself - and comparing strings rather than objects is what keeps a consumer
4809
+ * echoing an equal selection back from refocusing on every render.
4810
+ */
4811
+ const focusKey = selection ? `${selectionKey(selection)}#${[...hiddenChains].sort().join(",")}` : null;
4812
+ /**
4813
+ * Whether the selection names chains and nothing else, which is the shape
4814
+ * shown by dimming the chains around it rather than by focusing it.
4815
+ */
4816
+ 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));
2969
4817
  useEffect(() => {
4818
+ var _chosen$chains;
2970
4819
  const plugin = pluginRef.current;
2971
4820
  if (!plugin || !isReady) {
2972
4821
  focusedRef.current = null;
4822
+ neighbourhoodRef.current = null;
2973
4823
  return;
2974
4824
  }
2975
- const residue = selectedResidue !== null && selectedResidue !== void 0 ? selectedResidue : null;
2976
- if (residue === focusedRef.current) return;
2977
- focusedRef.current = residue;
2978
- if (residue === null) {
2979
- var _plugin$canvas3d;
2980
- setClipRatio(null);
4825
+ if (focusKey === focusedRef.current) return;
4826
+ focusedRef.current = focusKey;
4827
+ if (focusKey === null) {
4828
+ clearFocus(plugin, setClipRatio, true);
4829
+ return;
4830
+ }
4831
+ const chosen = selection;
4832
+ const loci = lociForSelection(plugin, chosen, hiddenChains);
4833
+ if (!loci) {
4834
+ clearFocus(plugin, setClipRatio, false);
4835
+ return;
4836
+ }
4837
+ if (chainsOnly) {
2981
4838
  plugin.managers.structure.focus.clear();
2982
- (_plugin$canvas3d = plugin.canvas3d) === null || _plugin$canvas3d === void 0 || _plugin$canvas3d.requestCameraReset();
4839
+ frameLoci(plugin, loci);
4840
+ setClipRatio(null);
2983
4841
  return;
2984
4842
  }
2985
- const loci = lociForResidueIndex(plugin, residue);
2986
- if (!loci) return;
2987
- const focused = plugin.managers.structure.focus.behaviors.current.value;
2988
- if (!focused || !StructureElement.Loci.areEqual(focused.loci, loci)) plugin.managers.structure.focus.setFromLoci(loci);
2989
- setClipRatio(focusResidue(plugin, loci));
4843
+ return focusWithShell(plugin, loci, !((_chosen$chains = chosen.chains) === null || _chosen$chains === void 0 ? void 0 : _chosen$chains.length), neighbourhoodRef, pluginRef, setClipRatio);
2990
4844
  }, [
2991
- selectedResidue,
4845
+ focusKey,
2992
4846
  isReady,
2993
4847
  setClipRatio
2994
4848
  ]);
2995
4849
  }
2996
4850
  //#endregion
2997
- //#region src/core/ProteinStructureViewer/hooks/useResidueOverlay.ts
4851
+ //#region src/core/ProteinStructureViewer/hooks/useSelectionReadout.ts
4852
+ /**
4853
+ * Tracks the residue under the pointer, deduplicated, and passes the event on
4854
+ * to the consumer.
4855
+ *
4856
+ * Mol* emits hover events continuously, so a residue the pointer is resting on
4857
+ * would otherwise cost a state update per event. The index alone does not
4858
+ * identify one: loading a new structure into the same plugin renumbers from
4859
+ * zero, so the residue now at an index is not the one that was there before.
4860
+ * Comparing the label as well is enough, because the readout this drives is
4861
+ * built from the label and the index and from nothing else.
4862
+ */
4863
+ function useResidueHoverState(onResidueHover) {
4864
+ const [hoveredResidue, setHoveredResidue] = useState(null);
4865
+ return {
4866
+ handleResidueHover: useCallback((residue) => {
4867
+ setHoveredResidue((prev) => {
4868
+ if (residue === null) return prev === null ? prev : null;
4869
+ const label = residueLabel(residue);
4870
+ return prev !== null && prev.index === residue.index && prev.label === label ? prev : {
4871
+ index: residue.index,
4872
+ label
4873
+ };
4874
+ });
4875
+ onResidueHover === null || onResidueHover === void 0 || onResidueHover(residue);
4876
+ }, [onResidueHover]),
4877
+ hoveredResidue
4878
+ };
4879
+ }
4880
+ /**
4881
+ * Derives the legend's readouts from what is hovered and what is selected.
4882
+ *
4883
+ * The viewer already knows everything they need - the label, the pLDDT, the
4884
+ * overlay value - so they are worked out here rather than asked of the
4885
+ * consumer. A readout covering several residues reports the mean of each,
4886
+ * which is the only reading that survives a range or a whole chain.
4887
+ */
4888
+ function useSelectionReadout({ hoveredResidue, isReady, plddt, pluginRef, residueOverlay, residuesByChainRef, selection }) {
4889
+ const [resolved, setResolved] = useState(null);
4890
+ /**
4891
+ * What the selection covers has to be read off the structure, since a
4892
+ * selection can be made without a click ever naming anything: a lone residue
4893
+ * is named the way the click path names it, so the two readouts cannot
4894
+ * disagree, and a chain is expanded to the residues it actually holds rather
4895
+ * than to the span between its ends.
4896
+ */
4897
+ useEffect(() => {
4898
+ var _residuesByChainRef$c;
4899
+ const plugin = pluginRef.current;
4900
+ if (!plugin || !isReady || isEmptySelection(selection)) {
4901
+ setResolved(null);
4902
+ return;
4903
+ }
4904
+ const chosen = selection;
4905
+ const residues = selectionResidues(chosen, (_residuesByChainRef$c = residuesByChainRef.current) !== null && _residuesByChainRef$c !== void 0 ? _residuesByChainRef$c : /* @__PURE__ */ new Map());
4906
+ if (residues.length === 0) {
4907
+ setResolved(null);
4908
+ return;
4909
+ }
4910
+ if (residues.length > 1) {
4911
+ setResolved({
4912
+ label: selectionLabel(chosen, residues.length),
4913
+ residues
4914
+ });
4915
+ return;
4916
+ }
4917
+ const loci = lociForSelection(plugin, chosen);
4918
+ const residue = loci && residueRefFromLoci(loci);
4919
+ setResolved(residue ? {
4920
+ label: residueLabel(residue),
4921
+ residues
4922
+ } : null);
4923
+ }, [isReady, selection && selectionKey(selection)]);
4924
+ const buildReadout = useCallback((label, residues) => ({
4925
+ label,
4926
+ plddt: meanOverResidues(residues, (i) => plddt === null || plddt === void 0 ? void 0 : plddt[i]),
4927
+ value: meanOverResidues(residues, (i) => residueOverlay === null || residueOverlay === void 0 ? void 0 : residueOverlay.values.get(i)),
4928
+ residueCount: residues.length
4929
+ }), [plddt, residueOverlay]);
4930
+ return {
4931
+ hoveredReadout: useMemo(() => hoveredResidue === null ? null : buildReadout(hoveredResidue.label, [hoveredResidue.index]), [hoveredResidue, buildReadout]),
4932
+ selectedReadout: useMemo(() => resolved === null ? null : buildReadout(resolved.label, resolved.residues), [resolved, buildReadout])
4933
+ };
4934
+ }
4935
+ //#endregion
4936
+ //#region src/core/ProteinStructureViewer/hooks/useStructureColoring.ts
2998
4937
  /**
2999
- * Switches the structure's coloring between the residue value overlay and the
3000
- * default (pLDDT, or chain-id when no scores were supplied).
4938
+ * Decides what is coloring the structure and keeps that theme's data current.
4939
+ *
4940
+ * Three themes compete for the same representations, in a fixed order: a
4941
+ * residue value overlay, then pLDDT scores, then per-chain colors. Only one
4942
+ * can be applied, so the precedence lives here rather than being spread across
4943
+ * the hooks that own each theme's data - and the legend resolves what to
4944
+ * describe the same way, so the two cannot disagree about what is on screen.
3001
4945
  *
3002
4946
  * Recoloring happens in place: the camera is left where it is, so selecting or
3003
4947
  * switching an overlay does not zoom back out to the default view.
3004
4948
  */
3005
- function useResidueOverlay({ hasPlddt, isReady, mode, overlay, pluginRef, residueValueThemeRef }) {
4949
+ function useStructureColoring({ chainColorThemeRef, chainColors, hasPlddt, isReady, mode, overlay, pluginRef, residueValueThemeRef }) {
3006
4950
  useEffect(() => {
3007
4951
  const plugin = pluginRef.current;
3008
- const theme = residueValueThemeRef.current;
3009
- if (!plugin || !theme || !isReady) return;
4952
+ const residueTheme = residueValueThemeRef.current;
4953
+ const chainTheme = chainColorThemeRef.current;
4954
+ if (!plugin || !residueTheme || !chainTheme || !isReady) return;
4955
+ chainTheme.setState(chainColors);
3010
4956
  if (overlay) {
3011
4957
  var _overlay$colorScale, _overlay$min;
3012
- theme.setState({
4958
+ residueTheme.setState({
3013
4959
  colorScale: (_overlay$colorScale = overlay.colorScale) !== null && _overlay$colorScale !== void 0 ? _overlay$colorScale : PLASMA_COLOR_SCALE,
3014
4960
  max: overlay.max,
3015
4961
  min: (_overlay$min = overlay.min) !== null && _overlay$min !== void 0 ? _overlay$min : 0,
@@ -3017,33 +4963,51 @@ function useResidueOverlay({ hasPlddt, isReady, mode, overlay, pluginRef, residu
3017
4963
  values: overlay.values
3018
4964
  });
3019
4965
  applyColorTheme(plugin, RESIDUE_VALUE_THEME_NAME);
3020
- } else {
3021
- theme.setState({
3022
- mode,
3023
- values: /* @__PURE__ */ new Map()
3024
- });
3025
- applyColorTheme(plugin, hasPlddt ? PLDDT_THEME_NAME : FALLBACK_THEME_NAME);
4966
+ return;
3026
4967
  }
4968
+ residueTheme.setState({
4969
+ mode,
4970
+ values: /* @__PURE__ */ new Map()
4971
+ });
4972
+ applyColorTheme(plugin, hasPlddt ? PLDDT_THEME_NAME : FALLBACK_THEME_NAME);
3027
4973
  }, [
3028
4974
  overlay,
3029
4975
  hasPlddt,
3030
4976
  isReady,
3031
- mode
4977
+ mode,
4978
+ chainColors
3032
4979
  ]);
3033
4980
  }
3034
4981
  //#endregion
4982
+ //#region src/core/ProteinStructureViewer/ProteinStructureViewer.types.ts
4983
+ /** Pixel dimensions each resolution produces, for documentation and labels. */
4984
+ const DOWNLOAD_RESOLUTIONS = {
4985
+ high: "3840x2160",
4986
+ low: "1280x720",
4987
+ maximum: "7680x4320",
4988
+ medium: "1920x1080"
4989
+ };
4990
+ //#endregion
3035
4991
  //#region src/core/ProteinStructureViewer/index.tsx
3036
4992
  const _excluded$1 = [
3037
4993
  "backgroundColor",
4994
+ "chainColors",
4995
+ "disableChainHighlightOnHover",
4996
+ "download",
4997
+ "hiddenChains",
4998
+ "onChainVisibilityChange",
4999
+ "onChainsChange",
5000
+ "molstarSpec",
3038
5001
  "onResidueClick",
3039
5002
  "onResidueHover",
3040
- "onSelectionClear",
3041
- "pdb",
5003
+ "onSelectionChange",
5004
+ "structure",
3042
5005
  "plddt",
3043
5006
  "residueOverlay",
3044
- "selectedResidue",
5007
+ "selection",
3045
5008
  "sequenceViewerBackgroundColor",
3046
5009
  "showAxes",
5010
+ "showChainLegend",
3047
5011
  "showLegend",
3048
5012
  "showSequenceViewer",
3049
5013
  "stats"
@@ -3104,64 +5068,125 @@ function resolveScaleProps(overlay, hasPlddt) {
3104
5068
  };
3105
5069
  }
3106
5070
  var ProteinStructureViewer_default = memo(forwardRef((props, ref) => {
3107
- const { backgroundColor, onResidueClick, onResidueHover, onSelectionClear, pdb, plddt, residueOverlay, selectedResidue = null, sequenceViewerBackgroundColor, showAxes = true, showLegend = true, showSequenceViewer = true, stats } = props, rest = _objectWithoutProperties(props, _excluded$1);
5071
+ var _selection$chains;
5072
+ 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$1);
3108
5073
  const theme = useTheme();
3109
5074
  const mode = getMode({ theme });
3110
5075
  const semanticColors = getSemanticColors({ theme });
3111
5076
  const pluginMountRef = useRef(null);
3112
- const [hoveredResidue, setHoveredResidue] = useState(null);
3113
- /**
3114
- * Label for the selected residue, read back off the structure rather than
3115
- * remembered from the click that selected it, so the readout follows the
3116
- * prop however the selection was made.
3117
- */
3118
- const [selectedLabel, setSelectedLabel] = useState(null);
3119
5077
  const hasPlddt = Boolean(plddt && plddt.length > 0);
3120
- const processedPdb = useMemo(() => hasPlddt ? injectPlddtIntoPdb(pdb, plddt) : pdb, [
3121
- pdb,
5078
+ const processedStructure = useMemo(() => hasPlddt ? injectPlddt(structure, plddt) : structure, [
5079
+ structure,
3122
5080
  plddt,
3123
5081
  hasPlddt
3124
5082
  ]);
3125
- const { isReady, pluginRef, residueValueThemeRef, setClipRatio } = useMolstarPlugin({
3126
- backgroundColor: useMemo(() => {
3127
- var _semanticColors$base;
3128
- 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]);
3129
- }, [
3130
- backgroundColor,
3131
- mode,
3132
- semanticColors
3133
- ]),
5083
+ const bgColor = useMemo(() => {
5084
+ var _semanticColors$base;
5085
+ 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]);
5086
+ }, [
5087
+ backgroundColor,
5088
+ mode,
5089
+ semanticColors
5090
+ ]);
5091
+ const edgeColor = useMemo(() => {
5092
+ var _semanticColors$base2;
5093
+ return themeColor(semanticColors === null || semanticColors === void 0 || (_semanticColors$base2 = semanticColors.base) === null || _semanticColors$base2 === void 0 ? void 0 : _semanticColors$base2.borderPrimary, FALLBACK_EDGE_COLOR);
5094
+ }, [semanticColors]);
5095
+ const highlightColor = useMemo(() => {
5096
+ var _semanticColors$base3;
5097
+ return themeColor(semanticColors === null || semanticColors === void 0 || (_semanticColors$base3 = semanticColors.base) === null || _semanticColors$base3 === void 0 ? void 0 : _semanticColors$base3.fillSelected, FALLBACK_HIGHLIGHT_COLOR);
5098
+ }, [semanticColors]);
5099
+ const { handleResidueHover, hoveredResidue } = useResidueHoverState(onResidueHover);
5100
+ const handleSelectionClear = useCallback(() => {
5101
+ onSelectionChange === null || onSelectionChange === void 0 || onSelectionChange(null);
5102
+ }, [onSelectionChange]);
5103
+ /**
5104
+ * Chains the selection covers whole, which is what makes a chain caption a
5105
+ * toggle rather than a one-way switch. Keyed on its contents because the
5106
+ * set is pushed into the views Mol* renders, where a fresh object every
5107
+ * render would be a fresh push every render.
5108
+ */
5109
+ const selectedChainsKey = [...(_selection$chains = selection === null || selection === void 0 ? void 0 : selection.chains) !== null && _selection$chains !== void 0 ? _selection$chains : []].sort().join("\0");
5110
+ const selectedChains = useMemo(() => new Set(selectedChainsKey === "" ? [] : selectedChainsKey.split("\0")), [selectedChainsKey]);
5111
+ /**
5112
+ * Clicking a chain selects it; clicking the selected chain again clears it.
5113
+ *
5114
+ * A whole chain is reported as the chain it is, not as the hundreds of
5115
+ * residue indices it stands for, so echoing it back costs nothing. Only a
5116
+ * selection that is exactly this one chain toggles off - with a residue or
5117
+ * another chain also selected, the click is narrowing to this chain rather
5118
+ * than undoing itself.
5119
+ */
5120
+ const handleChainSelect = useCallback((chainId) => {
5121
+ var _selection$chains2, _selection$residues;
5122
+ 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);
5123
+ onSelectionChange === null || onSelectionChange === void 0 || onSelectionChange(isOnlyThisChain ? null : { chains: [chainId] });
5124
+ }, [onSelectionChange, selection]);
5125
+ /**
5126
+ * Dims every other chain while a chain's name is pointed at, in the legend
5127
+ * or in the sequence panel's captions, and leaves the selected chain lit
5128
+ * once the pointer has gone.
5129
+ *
5130
+ * Reached through a ref because the two ends need each other: dimming
5131
+ * other chains takes the plugin, which the hook below creates, and that
5132
+ * hook has to be handed the callback to give the captions it renders. This
5133
+ * one is stable and forwards to whatever the highlight hook installs once
5134
+ * there is a plugin for it to talk to.
5135
+ */
5136
+ const highlightChainRef = useRef(() => void 0);
5137
+ const highlightChain = useCallback((chainId) => {
5138
+ highlightChainRef.current(chainId);
5139
+ }, []);
5140
+ const [chains, setChains] = useState([]);
5141
+ const { colors: chainColors, hidden: hiddenChains, toggleChain } = useChains({
5142
+ chainColors: chainColorOverrides,
5143
+ chains,
5144
+ hiddenChains: hiddenChainsProp,
5145
+ onChainVisibilityChange
5146
+ });
5147
+ const { chainColorThemeRef, chains: loadedChains, isReady, loadCount, pluginRef, residuesByChainRef, residueValueThemeRef, setClipRatio } = useMolstarPlugin({
5148
+ backgroundColor: bgColor,
5149
+ chainColors,
3134
5150
  containerRef: pluginMountRef,
3135
- edgeColor: useMemo(() => {
3136
- var _semanticColors$base2;
3137
- return themeColor(semanticColors === null || semanticColors === void 0 || (_semanticColors$base2 = semanticColors.base) === null || _semanticColors$base2 === void 0 ? void 0 : _semanticColors$base2.borderPrimary, FALLBACK_EDGE_COLOR);
3138
- }, [semanticColors]),
5151
+ download,
5152
+ edgeColor,
3139
5153
  hasPlddt,
3140
- highlightColor: useMemo(() => {
3141
- var _semanticColors$base3;
3142
- return themeColor(semanticColors === null || semanticColors === void 0 || (_semanticColors$base3 = semanticColors.base) === null || _semanticColors$base3 === void 0 ? void 0 : _semanticColors$base3.fillSelected, FALLBACK_HIGHLIGHT_COLOR);
3143
- }, [semanticColors]),
5154
+ hiddenChains,
5155
+ highlightColor,
3144
5156
  mode,
5157
+ molstarSpec,
5158
+ onChainHover: highlightChain,
5159
+ onChainSelect: handleChainSelect,
5160
+ onChainToggle: toggleChain,
3145
5161
  onResidueClick,
3146
- onResidueHover: useCallback((residue) => {
3147
- setHoveredResidue((prev) => {
3148
- if (residue === null) return prev === null ? prev : null;
3149
- const label = residueLabel(residue);
3150
- if (prev !== null && prev.index === residue.index && prev.label === label) return prev;
3151
- return {
3152
- index: residue.index,
3153
- label
3154
- };
3155
- });
3156
- onResidueHover === null || onResidueHover === void 0 || onResidueHover(residue);
3157
- }, [onResidueHover]),
3158
- onSelectionClear,
3159
- pdb: processedPdb,
5162
+ onResidueHover: handleResidueHover,
5163
+ onSelectionChange,
5164
+ onSelectionClear: handleSelectionClear,
5165
+ selectedChains,
3160
5166
  sequenceViewerBackgroundColor,
3161
5167
  showAxes,
3162
- showSequenceViewer
5168
+ showSequenceViewer,
5169
+ structure: processedStructure
5170
+ });
5171
+ highlightChainRef.current = useChainHighlight({
5172
+ disabled: disableChainHighlightOnHover,
5173
+ hiddenChains,
5174
+ loadCount,
5175
+ pluginRef,
5176
+ selectedChains
3163
5177
  });
3164
- useResidueOverlay({
5178
+ useEffect(() => {
5179
+ setChains(loadedChains);
5180
+ }, [loadedChains]);
5181
+ const onChainsChangeRef = useRef(onChainsChange);
5182
+ onChainsChangeRef.current = onChainsChange;
5183
+ useEffect(() => {
5184
+ var _onChainsChangeRef$cu;
5185
+ (_onChainsChangeRef$cu = onChainsChangeRef.current) === null || _onChainsChangeRef$cu === void 0 || _onChainsChangeRef$cu.call(onChainsChangeRef, loadedChains);
5186
+ }, [loadedChains]);
5187
+ useStructureColoring({
5188
+ chainColorThemeRef,
5189
+ chainColors,
3165
5190
  hasPlddt,
3166
5191
  isReady,
3167
5192
  mode,
@@ -3169,46 +5194,49 @@ var ProteinStructureViewer_default = memo(forwardRef((props, ref) => {
3169
5194
  pluginRef,
3170
5195
  residueValueThemeRef
3171
5196
  });
3172
- useResidueFocus({
5197
+ useSelectionFocus({
5198
+ hiddenChains,
3173
5199
  isReady,
3174
5200
  pluginRef,
3175
- selectedResidue,
5201
+ selection,
3176
5202
  setClipRatio
3177
5203
  });
3178
- useEffect(() => {
3179
- const plugin = pluginRef.current;
3180
- if (!plugin || !isReady || selectedResidue === null) {
3181
- setSelectedLabel(null);
3182
- return;
3183
- }
3184
- const loci = lociForResidueIndex(plugin, selectedResidue);
3185
- const residue = loci && residueRefFromLoci(loci);
3186
- setSelectedLabel(residue ? residueLabel(residue) : null);
3187
- }, [
5204
+ const { hoveredReadout, selectedReadout } = useSelectionReadout({
5205
+ hoveredResidue,
3188
5206
  isReady,
5207
+ plddt,
3189
5208
  pluginRef,
3190
- selectedResidue
3191
- ]);
3192
- const buildReadout = useCallback((label, index) => {
3193
- var _plddt$index, _residueOverlay$value;
3194
- return {
3195
- label,
3196
- plddt: (_plddt$index = plddt === null || plddt === void 0 ? void 0 : plddt[index]) !== null && _plddt$index !== void 0 ? _plddt$index : null,
3197
- value: (_residueOverlay$value = residueOverlay === null || residueOverlay === void 0 ? void 0 : residueOverlay.values.get(index)) !== null && _residueOverlay$value !== void 0 ? _residueOverlay$value : null
3198
- };
3199
- }, [plddt, residueOverlay]);
3200
- const hoveredReadout = useMemo(() => hoveredResidue === null ? null : buildReadout(hoveredResidue.label, hoveredResidue.index), [hoveredResidue, buildReadout]);
3201
- const selectedReadout = useMemo(() => selectedResidue === null || selectedLabel === null ? null : buildReadout(selectedLabel, selectedResidue), [
3202
- selectedResidue,
3203
- selectedLabel,
3204
- buildReadout
3205
- ]);
5209
+ residueOverlay,
5210
+ residuesByChainRef,
5211
+ selection
5212
+ });
3206
5213
  const scaleProps = useMemo(() => resolveScaleProps(residueOverlay, hasPlddt), [residueOverlay, hasPlddt]);
5214
+ /**
5215
+ * What a chain's swatch can show follows whatever is painting the
5216
+ * structure, in the same order the color key resolves in.
5217
+ *
5218
+ * Chain coloring gives each chain one color of its own. pLDDT gives every
5219
+ * chain the same four bands, which says they are colored by confidence
5220
+ * rather than telling them apart - so the swatch carries the whole key,
5221
+ * quartered. An overlay is continuous and has no discrete colors to put in
5222
+ * a swatch at all, so the rows keep their labels and toggles and the color
5223
+ * key beside them does the describing.
5224
+ */
5225
+ const chainColoringActive = !residueOverlay && !hasPlddt;
5226
+ const plddtColoringActive = !residueOverlay && hasPlddt;
3207
5227
  return /* @__PURE__ */ jsxs(ViewerRoot, _objectSpread2(_objectSpread2({
3208
5228
  ref,
3209
5229
  showSequenceViewer
3210
5230
  }, rest), {}, { children: [/* @__PURE__ */ jsx(PluginMount, { ref: pluginMountRef }), showLegend && /* @__PURE__ */ jsx(StructureLegend, _objectSpread2({
5231
+ chainBandColors: plddtColoringActive ? PLDDT_BAND_COLORS : void 0,
5232
+ chainColors: chainColoringActive ? chainColors : void 0,
5233
+ chains: showChainLegend ? chains : [],
5234
+ hiddenChains,
3211
5235
  hoveredResidue: hoveredReadout,
5236
+ onChainHover: highlightChain,
5237
+ onChainSelect: handleChainSelect,
5238
+ onChainToggle: toggleChain,
5239
+ selectedChains,
3212
5240
  selectedResidue: selectedReadout,
3213
5241
  showSequenceViewer,
3214
5242
  stats: stats !== null && stats !== void 0 ? stats : []
@@ -3690,4 +5718,4 @@ const StackedBarChart = (props) => {
3690
5718
  return /* @__PURE__ */ jsxs(ChartWrapper, _objectSpread2(_objectSpread2({ width }, rest), {}, { children: [/* @__PURE__ */ jsxs(TitleContainer, { children: [/* @__PURE__ */ jsx(ChartTitle, { children: title }), !hideBadge && displayBadge && /* @__PURE__ */ jsx(StyledBadge, { children: displayBadge })] }), chartContent] }));
3691
5719
  };
3692
5720
  //#endregion
3693
- export { HeatmapChart_default as HeatmapChart, PLASMA_COLOR_SCALE, PLDDT_COLOR_SCALE, ProteinStructureViewer_default as ProteinStructureViewer, StackedBarChart, injectPlddtIntoPdb, sampleColorScale, toCssGradient };
5721
+ export { DOWNLOAD_RESOLUTIONS, HeatmapChart_default as HeatmapChart, PLASMA_COLOR_SCALE, PLDDT_COLOR_SCALE, ProteinStructureViewer_default as ProteinStructureViewer, StackedBarChart, detectStructureFormat, injectPlddt, injectPlddtIntoMmcif, injectPlddtIntoPdb, sampleColorScale, toCssGradient };