jbrowse-plugin-protein3d 1.17.0 → 1.18.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.
@@ -15,7 +15,7 @@ import { checkedColor, colorOfScheme } from './proteinColor';
15
15
  import { defaultDisplayName } from './proteinViewSpec';
16
16
  import { removeMolstarStructure } from './removeStructure';
17
17
  import { reportPluginFailure } from './reportPluginFailure';
18
- import { syncSessionHighlightMarks } from './sessionHighlights';
18
+ import { fitLabelDepths, syncSessionHighlightMarks } from './sessionHighlights';
19
19
  import { showLoading } from './showLoading';
20
20
  import { readStoredSettings, storeSetting, withStoredSettings, } from './storedSettings';
21
21
  import { makeStructureLoader } from './structureLoader';
@@ -346,9 +346,34 @@ function stateModelFactory() {
346
346
  }))
347
347
  : []);
348
348
  if (plugin && structures.length > 0) {
349
- syncSessionHighlightMarks({ plugin, structures }).catch(reportPluginFailure(self, plugin));
349
+ syncSessionHighlightMarks({ plugin, structures })
350
+ .then(() => fitLabelDepths(plugin))
351
+ .catch(reportPluginFailure(self, plugin));
350
352
  }
351
353
  }));
354
+ // A label's depth follows the camera, once it settles
355
+ let stopFollowingCamera;
356
+ addDisposer(self, () => stopFollowingCamera?.());
357
+ addDisposer(self, autorun(() => {
358
+ stopFollowingCamera?.();
359
+ stopFollowingCamera = undefined;
360
+ const plugin = self.molstarPluginContext;
361
+ const camera = plugin?.canvas3d?.camera;
362
+ if (!plugin || !camera) {
363
+ return;
364
+ }
365
+ let timer;
366
+ const subscription = camera.stateChanged.subscribe(() => {
367
+ clearTimeout(timer);
368
+ timer = setTimeout(() => {
369
+ fitLabelDepths(plugin).catch(reportPluginFailure(self, plugin));
370
+ }, 200);
371
+ });
372
+ stopFollowingCamera = () => {
373
+ clearTimeout(timer);
374
+ subscription.unsubscribe();
375
+ };
376
+ }));
352
377
  addDisposer(self, autorun(() => {
353
378
  const plugin = self.molstarPluginContext;
354
379
  for (const s of self.structures) {
@@ -21,6 +21,15 @@ export const LABEL_CORNERS = [
21
21
  'top-left',
22
22
  'bottom-right',
23
23
  ];
24
+ /**
25
+ * How far a label moves toward the camera: the most that keeps it inside a
26
+ * sphere of `radius`, for a residue `depth` in front of its centre. Given the
27
+ * residue's distance from the centre in place of its depth, it holds from
28
+ * any side
29
+ */
30
+ export function labelOffsetZ(radius, depth) {
31
+ return Math.max(0, radius - depth);
32
+ }
24
33
  /**
25
34
  * Label text in Å, in proportion to the structure, so a label reads at about
26
35
  * one size whether the structure is one domain or a complex on DNA
@@ -86,6 +95,28 @@ export async function syncSessionHighlightMarks({ plugin, structures, }) {
86
95
  }
87
96
  return undefined;
88
97
  };
98
+ // how far a residue's atoms on `chain` sit from the structure's centre, on
99
+ // average
100
+ const distanceFromCentre = (structure, chain, labelSeqIds) => {
101
+ const { center } = structure.boundary.sphere;
102
+ const l = StructureElement.Location.create(structure);
103
+ const p = [0, 0, 0];
104
+ let sum = 0;
105
+ let n = 0;
106
+ for (const unit of structure.units) {
107
+ l.unit = unit;
108
+ for (const element of Array.from(unit.elements)) {
109
+ l.element = element;
110
+ if (SP.chain.label_asym_id(l) === chain &&
111
+ labelSeqIds.has(SP.residue.label_seq_id(l))) {
112
+ unit.conformation.position(element, p);
113
+ sum += Math.hypot(p[0] - center[0], p[1] - center[1], p[2] - center[2]);
114
+ n++;
115
+ }
116
+ }
117
+ }
118
+ return n > 0 ? sum / n : 0;
119
+ };
89
120
  const update = plugin.state.data.build();
90
121
  const existing = plugin.state.data.select(StateSelection.Generators.root.subtree().withTag(SESSION_HIGHLIGHTS_TAG));
91
122
  for (const cell of existing) {
@@ -152,15 +183,55 @@ export async function syncSessionHighlightMarks({ plugin, structures, }) {
152
183
  background: true,
153
184
  backgroundColor: Color(0xffffff),
154
185
  backgroundOpacity: 0.85,
155
- // toward the camera by the structure's radius, past
156
- // everything the structure draws: Mol* depth-tests text, so
157
- // a label behind a helix or a DNA strand would hide. The
158
- // parameter's 10 Å bound is the UI's; the shader takes any
159
- // distance, and the camera sits outside the bounding sphere
160
- offsetZ: radius,
186
+ // safe from any side until fitLabelDepths knows the camera
187
+ offsetZ: labelOffsetZ(radius, distanceFromCentre(molstarStructure, chain, new Set(labelSeqIds))),
161
188
  }, { tags: [SESSION_HIGHLIGHTS_TAG] });
162
189
  }
163
190
  }
164
191
  }
165
192
  await update.commit();
166
193
  }
194
+ /**
195
+ * Move each session-highlight label toward the camera as far as the near
196
+ * clipping plane allows. Mol* depth-tests text, so a label behind a helix or
197
+ * a DNA strand would hide, and Mol* puts the near plane at the front of the
198
+ * camera's radius, so a label pushed past it disappears. The distance depends
199
+ * on which side the camera faces, so the view calls this when the camera
200
+ * settles. The parameter's 10 Å bound is the UI's; the shader takes any
201
+ * distance.
202
+ */
203
+ export async function fitLabelDepths(plugin) {
204
+ const camera = plugin.canvas3d?.camera;
205
+ if (!camera) {
206
+ return;
207
+ }
208
+ const { StateSelection, StateTransforms, StructureElement } = await loadMolstar();
209
+ const labels = plugin.state.data.select(StateSelection.Generators.root
210
+ .subtree()
211
+ .withTag(SESSION_HIGHLIGHTS_TAG)
212
+ .withTransformer(StateTransforms.Representation.StructureSelectionsLabel3D));
213
+ const { position, target, radius } = camera.state;
214
+ const toCamera = [0, 1, 2].map(k => position[k] - target[k]);
215
+ const length = Math.hypot(...toCamera) || 1;
216
+ const update = plugin.state.data.build();
217
+ let changed = false;
218
+ for (const cell of labels) {
219
+ const parent = plugin.state.data.cells.get(plugin.state.data.tree.transforms.get(cell.transform.ref).parent);
220
+ const selections = parent?.obj?.data;
221
+ const loci = selections?.[0]?.loci;
222
+ const params = cell.transform.params;
223
+ if (!loci || !params) {
224
+ continue;
225
+ }
226
+ const { center } = StructureElement.Loci.getBoundary(loci).sphere;
227
+ const depth = [0, 1, 2].reduce((sum, k) => sum + (center[k] - target[k]) * toCamera[k], 0) / length;
228
+ const offsetZ = labelOffsetZ(radius - params.textSize, depth);
229
+ if (Math.abs(offsetZ - params.offsetZ) > 1) {
230
+ update.to(cell).update({ ...params, offsetZ });
231
+ changed = true;
232
+ }
233
+ }
234
+ if (changed) {
235
+ await update.commit();
236
+ }
237
+ }
@@ -0,0 +1,2 @@
1
+ import{b as z}from"./chunk-5M4LVDLT.js";import{a as it,b as at,c as st,d as ut,e as ct,f as dt,h as pt,i as te}from"./chunk-7SEZTF5X.js";import{b as gt}from"./chunk-NOFPQXHZ.js";import{a as re,b as _,c as St,d as yt,o as oe,q as ht,r as bt,s as ie}from"./chunk-5YLRYIUR.js";import{c as lt,f as mt}from"./chunk-RL54DUYZ.js";import{a as T}from"./chunk-UTDQGJCS.js";import{c as ne,d as $,e as j,g as ft}from"./chunk-KXSOSKHQ.js";import{a as pn}from"./chunk-YCRC6WEC.js";import{a as L}from"./chunk-56ZPPPNO.js";import{a as mn}from"./chunk-GVEKA5YG.js";import{b as We,c as Ke,d as Ze,f as tt,g as nt,i as rt}from"./chunk-R64WXKZQ.js";import{a as ot}from"./chunk-LZTO76OW.js";import{b as he,d as be,e as O}from"./chunk-2RFFBSIA.js";import"./chunk-INWFM3CY.js";import"./chunk-5NBLSM7W.js";import{a as Ye,b as Xe,c as Qe,e as et}from"./chunk-ISVQX4IH.js";import{a as ze,b as Je}from"./chunk-UVDYWAS6.js";import{a as je,b as N}from"./chunk-7UQOTULP.js";import{$ as ve,C as Ee,Da as _e,Ga as Ge,Ha as De,L as Ce,La as Oe,N as Y,O as Ae,Pa as Ue,Q as F,Qa as Be,Ra as B,U as X,Ua as $e,V as ke,X as U,_ as xe,b as Pe,ba as Re,c as Te,ca as Q,da as qe,ea as Le,fa as Ve,ja as He,ka as Fe,l as we,la as ee,m as Me,ma as Ne,p as Ie}from"./chunk-WZCSPP5F.js";import{a as Z}from"./chunk-B3HKXTGK.js";import"./chunk-SPXMXPSC.js";import{a as ln,c as C}from"./chunk-KVMUXFPB.js";var Tt=ln((_n,Pt)=>{Pt.exports=JBrowseExports["@jbrowse/core/util/types/mst"]});var ye=C(mn()),sn=C(pn()),Se=C(Z()),un=C(Tt()),y=C(L()),v=C(re());function A(e,t,n){let r=e.helpers.substructureParent.get(n);return r?e.state.data.selectQ(o=>o.byValue(r).rootOfType(t.PluginStateObject.Molecule.Structure))[0]:void 0}var G="jbrowse-alignment-sites",gn={sizeFactor:.35,sizeAspectRatio:.6},wt=0;async function Mt({plugin:e,structures:t}){let n=await T(),{MolScriptBuilder:r,ProteinBackboneAtoms:o,StateSelection:i,StateTransforms:a,createStructureColorThemeParams:s,createStructureRepresentationParams:d,registerPlacedValues:u}=n;wt++;let c=e.state.data.build(),m=!1;for(let{molstarStructure:l,sites:f,color:g}of t){let M=A(e,n,l);if(!M)continue;let S=e.state.data.select(i.Generators.ofTransformer(a.Model.StructureComponent,M.transform.ref).withTag(G)),h=[...f?.byLabelSeqId.keys()??[]];if(u("alignment-sites",l,f),!f||!g||h.length===0){for(let b of S)c.delete(b.transform.ref),m=!0;continue}let I=b=>r.core.rel.eq([r.ammp("label_atom_id"),b]),P={type:{name:"expression",params:r.struct.generator.atomGroups({"entity-test":r.core.rel.eq([r.ammp("label_entity_id"),f.entityId]),"residue-test":r.core.set.has([r.set(...h),r.ammp("label_seq_id")]),"atom-test":r.core.logic.or([r.core.logic.not([r.core.set.has([r.set(...o),r.ammp("label_atom_id")])]),I("CA"),r.core.logic.and([r.core.rel.eq([r.ammp("auth_comp_id"),"PRO"]),I("N")])])})},nullIfEmpty:!0,label:"Sites from the alignment"},w={...d(e,l,{type:"ball-and-stick",typeParams:gn}),colorTheme:s(e,l,"ball-and-stick","alignment-domains",{revision:wt,color:g,mark:"atoms"})},[E]=S;if(E){c.to(E).update(P);for(let b of e.state.data.select(i.Generators.ofTransformer(a.Representation.StructureRepresentation3D,E.transform.ref)))c.to(b).update(w)}else c.to(M).apply(a.Model.StructureComponent,P,{tags:[G]}).apply(a.Representation.StructureRepresentation3D,w,{tags:[G]});m=!0}m&&await c.commit()}var fn=[...Ye,"alignment-domains"];function Et(e){return fn.some(t=>t===e)}function Ct(e,{entityId:t,domainColor:n,revision:r,representationType:o=""}){let i=$(e);return e.field==="mappedChain"?{entityId:t??""}:e.field==="domain"?{revision:r,color:n??at,mark:it(o)}:i&&Et(j(e))?{revision:r,color:i}:i&&{color:i}}var It=0;async function At({plugin:e,color:t,structures:n}){let r=await T(),{StateSelection:o,StateTransforms:i,createStructureColorThemeParams:a,registerPlacedValues:s}=r,d=j(t),u=Et(d);u&&It++;let c=e.state.data.build(),m=0;for(let{molstarStructure:l,entityId:f,placedValues:g,placedSites:M,domainColor:S}of n){u&&s(d,l,g),t.field==="domain"&&s("alignment-sites",l,M);let h=A(e,r,l),I=h?e.state.data.select(o.Generators.ofTransformer(i.Representation.StructureRepresentation3D,h.transform.ref)):[];for(let P of I)!P.state.isGhost&&!P.transform.tags?.includes(G)&&(c.to(P).update(w=>{w.colorTheme=a(e,l,w.type.name,d,Ct(t,{entityId:f,domainColor:S,revision:It,representationType:w.type.name}))}),m++)}m>0&&await c.commit()}function kt({plugin:e,color:t,structure:n,entityId:r,domainColor:o}){let i=j(t);return i===void 0?void 0:e.representation.structure.themes.colorThemeRegistry.create(i,{structure:n},Ct(t,{entityId:r,domainColor:o})??{}).legend}function ae(e,{structure:t,entityId:n,labelSeqIds:r}){let o=e.Script.getStructureSelection(i=>i.struct.generator.atomGroups({...n?{"chain-test":i.core.rel.eq([i.struct.atomProperty.macromolecular.label_entity_id(),n])}:{},"residue-test":i.core.set.has([i.core.type.set([...new Set(r)]),i.struct.atomProperty.macromolecular.label_seq_id()]),"group-by":i.struct.atomProperty.macromolecular.residueKey()}),t);return e.StructureSelection.toLociWithSourceUnits(o)}async function xt({interactivity:e,channel:t,targets:n}){let r=await T(),o=n.filter(s=>s.labelSeqIds.length>0).map(s=>ae(r,s)),{lociHighlights:i,lociSelects:a}=e;if(t==="highlight"){i.clearHighlights();for(let s of o)i.highlight({loci:s},!1)}else{a.deselectAll();for(let s of o)a.select({loci:s},!1)}}function se(e){let{structures:t,superposedCount:n}=e,r=t.filter(o=>o.loadedToMolstar).length;return t.length>0&&t.every(o=>!o.loading)&&(r<2||n===r)}async function ue(e,t,n=()=>!0){let r=await T();if(n()){let o=t.map(i=>ae(r,i));e.managers.camera.focusLoci(o),o[0]&&t[0]?.labelSeqIds.length===1&&e.managers.structure.focus.setFromLoci(o[0])}}function vt(e){let t;return function(){let{molstarPluginContext:r,structures:o}=e;if(!r||r===t||!se(e))return;let i=o.flatMap(a=>a.seedLit&&!a.hidden&&a.molstarStructure&&a.clickedLabelSeqIds.length?[{structure:a.molstarStructure,entityId:a.mappedEntity?.entityId,labelSeqIds:a.clickedLabelSeqIds}]:[]);i.length!==0&&(t=r,ue(r,i,()=>e.molstarPluginContext===r).catch(a=>{console.error(a)}))}}function ce(e,t){return function(){let r=e.molstarPluginContext,o=e.structures.flatMap(i=>i.molstarStructures.map(a=>({structure:a,entityId:i.mappedEntity?.entityId,labelSeqIds:t==="select"?i.selectLabelSeqIds:i.hoverLabelSeqIds})));r&&xt({interactivity:r.managers.interactivity,channel:t,targets:o}).catch(i=>{console.error(i)})}}async function J({plugin:e,molstarStructure:t}){if(!t)return;let n=await T(),{PluginCommands:r,PluginStateObject:o}=n,i=A(e,n,t),s=(i&&e.state.data.selectQ(d=>d.byValue(i).ancestorOfType(o.Molecule.Trajectory))[0])??i;s&&await r.State.RemoveObject(e,{state:e.state.data,ref:s.transform.ref,removeParentGhosts:!0})}var Rt=C(L());function x(e,t){return n=>{console.error(n),(0,Rt.isAlive)(e)&&e.molstarPluginContext===t&&e.setError(n)}}var V="jbrowse-session-highlights",qt=["bottom-left","top-right","top-left","bottom-right"];function Lt(e,t){return Math.max(0,e-t)}function Sn(e){return Math.min(8,Math.max(3,e/10))}var yn="#FFB11D";function Vt({highlights:e,mapping:t,naming:n,entity:r,transcriptToStructure:o,labels:i}){let a=n.canonicalRefName(t.refName);return e.flatMap(s=>{if(!n.isAssembly(s.assemblyName)||n.canonicalRefName(s.refName)!==a)return[];let d=new Set;for(let u=s.start;u<s.end;u++){let c=t.g2p[u],m=c===void 0?void 0:o[c],l=m===void 0?void 0:r.seqIds[m];l!==void 0&&d.add(l)}return d.size>0?[{entityId:r.entityId,labelSeqIds:[...d].sort((u,c)=>u-c),label:i&&s.label?s.label:void 0,color:s.color??yn}]:[]})}async function Ht({plugin:e,structures:t}){let n=await T(),{Color:r,MolScriptBuilder:o,StateSelection:i,StateTransforms:a,StructureElement:s,StructureProperties:d,createStructureRepresentationParams:u}=n,c=(g,M)=>{let S=s.Location.create(g);for(let h of g.units)if(S.unit=h,S.element=h.elements[0],d.entity.id(S)===M)return d.chain.label_asym_id(S)},m=(g,M,S)=>{let{center:h}=g.boundary.sphere,I=s.Location.create(g),P=[0,0,0],w=0,E=0;for(let b of g.units){I.unit=b;for(let q of Array.from(b.elements))I.element=q,d.chain.label_asym_id(I)===M&&S.has(d.residue.label_seq_id(I))&&(b.conformation.position(q,P),w+=Math.hypot(P[0]-h[0],P[1]-h[1],P[2]-h[2]),E++)}return E>0?w/E:0},l=e.state.data.build(),f=e.state.data.select(i.Generators.root.subtree().withTag(V));for(let g of f)l.delete(g.transform.ref);for(let{molstarStructure:g,marks:M}of t){let S=A(e,n,g);if(!S)continue;let{radius:h}=g.boundary.sphere,I=Sn(h);for(let[P,{entityId:w,labelSeqIds:E,label:b,color:q}]of M.entries()){let cn=o.struct.generator.atomGroups({"entity-test":o.core.rel.eq([o.ammp("label_entity_id"),w]),"residue-test":o.core.set.has([o.set(...E),o.ammp("label_seq_id")])});l.to(S).apply(a.Model.StructureComponent,{type:{name:"expression",params:cn},nullIfEmpty:!0,label:b??"Session highlight"},{tags:[V]}).apply(a.Representation.StructureRepresentation3D,u(e,g,{type:"ball-and-stick",typeParams:{sizeFactor:.3,sizeAspectRatio:.6},color:"uniform",colorParams:{value:r.fromHexStyle(q)}}),{tags:[V]});let K=b?c(g,w):void 0;if(b&&K){let dn=o.struct.generator.atomGroups({"chain-test":o.core.rel.eq([o.ammp("label_asym_id"),K]),"residue-test":o.core.set.has([o.set(...E),o.ammp("label_seq_id")])});l.toRoot().apply(a.Model.MultiStructureSelectionFromExpression,{selections:[{key:"a",ref:S.transform.ref,expression:dn}],isTransitive:!0,label:b},{dependsOn:[S.transform.ref],tags:[V]}).apply(a.Representation.StructureSelectionsLabel3D,{customText:b,textSize:I,attachment:qt[P%qt.length],tether:!0,tetherLength:3,scaleByRadius:!1,textColor:r(0),borderWidth:0,background:!0,backgroundColor:r(16777215),backgroundOpacity:.85,offsetZ:Lt(h,m(g,K,new Set(E)))},{tags:[V]})}}}await l.commit()}async function de(e){let t=e.canvas3d?.camera;if(!t)return;let{StateSelection:n,StateTransforms:r,StructureElement:o}=await T(),i=e.state.data.select(n.Generators.root.subtree().withTag(V).withTransformer(r.Representation.StructureSelectionsLabel3D)),{position:a,target:s,radius:d}=t.state,u=[0,1,2].map(f=>a[f]-s[f]),c=Math.hypot(...u)||1,m=e.state.data.build(),l=!1;for(let f of i){let S=e.state.data.cells.get(e.state.data.tree.transforms.get(f.transform.ref).parent)?.obj?.data?.[0]?.loci,h=f.transform.params;if(!S||!h)continue;let{center:I}=o.Loci.getBoundary(S).sphere,P=[0,1,2].reduce((E,b)=>E+(I[b]-s[b])*u[b],0)/c,w=Lt(d-h.textSize,P);Math.abs(w-h.offsetZ)>1&&(m.to(f).update({...h,offsetZ:w}),l=!0)}l&&await m.commit()}function Ft(e){return!e.minimized&&!e.error&&e.structures.some(t=>t.loading)}var Nt="proteinView-settings",_t=["showAlignment","showProteinTracks","showControls","autoScrollAlignment","compactTracks","showAllFeatureTracks"];function Gt(e,t){if(!t)return e;let n={...e};for(let r of _t)n[r]===void 0&&t[r]!==void 0&&(n[r]=t[r]);return n}function le(){let e=Ke(Nt);if(typeof e!="object"||e===null)return;let t={};for(let n of _t){let r=Reflect.get(e,n);typeof r=="boolean"&&(t[n]=r)}return t}function Dt(e,t){We(Nt,JSON.stringify({...le(),[e]:t}))}var H=C(L());function hn(e,{PdbFormat:t}){if(!t.is(e))return[];let{data:n,indices:r,count:o}=e.data.lines,i=[];for(let a=0;a<o;a++){let s=n.substring(r[2*a],r[2*a+1]);if(s.startsWith("EXPDTA"))i.push(...s.slice(10).split(";"));else if(s.startsWith("ATOM")||s.startsWith("HETATM"))break}return i.map(a=>a.trim()).filter(a=>a!=="")}function bn(e,t){if(!e||!t.MmcifFormat.is(e))return[];let{db:n,source:r}=e.data;return[...Array.from(n.exptl.method.toArray()),...r?hn(r,t):[]]}async function me({structure:e,plugin:t}){let{data:n,url:r}=e,{model:o,structures:i,modelIds:a}=await gt({plugin:t,data:n||void 0,url:r}),s=bn(o?.obj?.data.sourceData,await T()).some(d=>d!=="THEORETICAL MODEL");return{entities:o?xe(o):void 0,confidence:o&&!s?Le(o):void 0,molstarStructures:i,modelIds:a}}function Ot(e,t=Ge){let n=new Map,r=new WeakMap;function o(u){let{url:c,data:m,uniprotId:l}=u;return c===void 0&&m===void 0?l:void 0}async function i(u,c){let m=await t(c).catch(()=>{});if(!(0,H.isAlive)(u))return;if(m===void 0){u.setUrl(Oe(c));return}let l=De(m,{transcript:{seq:u.userProvidedTranscriptSequence}});if(!l)throw new Error(`AlphaFold DB has no model for ${c}`);u.setUrl(l.url)}function a(u,c){n.get(u)===c&&n.delete(u)}function s(u,c){n.get(u)!==c&&d(u,c)}function d(u,c){n.set(u,c),u.setError(void 0);let m=o(u);(m===void 0?me({structure:u,plugin:c}):i(u,m).then(()=>(0,H.isAlive)(u)?me({structure:u,plugin:c}):void 0)).then(f=>{if(!f){a(u,c);return}if(!(0,H.isAlive)(u)){a(u,c),J({plugin:c,molstarStructure:f.molstarStructures?.[0]}).catch(M=>{console.error(M)});return}let g=e.molstarPluginContext;g===c&&(u.setStructureData(f),u.setLoadedToMolstar(!0)),a(u,c),g&&g!==c&&!u.loadedToMolstar&&s(u,g)}).catch(f=>{if(a(u,c),!(0,H.isAlive)(e)||!(0,H.isAlive)(u))return;let g=e.molstarPluginContext;g&&g!==c?s(u,g):(r.set(u,c),u.setError(f),console.error(f))})}return function(){let{structures:c,molstarPluginContext:m}=e;if(m)for(let l of c)!l.loadedToMolstar&&n.get(l)!==m&&r.get(l)!==m&&d(l,m)}}var k=C(Z()),p=C(L()),R=C(re());function Ut(e){let{userProvidedTranscriptSequence:t,entities:n,pairwiseAlignment:r}=e;if(!t||!n?.length)return{kind:"nothingToAlign"};if(r){if(!e.alignmentImported)return{kind:"keep"};let{mappedEntityId:o}=e,i=z(r,t,n,o);if("entityId"in i)return{kind:"adopt",entityId:i.entityId};let a=n.find(s=>s.entityId===o&&!s.nucleicAcid);return a?{kind:"realign",problem:i.problem,transcript:t,entity:a,identical:N(t,a.seq)}:{kind:"discard",problem:i.problem}}return{kind:"choose",transcript:t,entities:n,identical:n.some(o=>!o.nucleicAcid&&N(t,o.seq))}}function Bt({hovered:e,views:t,mapping:n,connectedViewId:r,genomeViewReady:o,naming:i}){let a=o?be(e,n,i):void 0;if(a!==void 0)return{transcriptPos:a,source:"genome"};let s=r?t.find(c=>c.type==="MsaView"&&c.connectedViewId===r&&!!c.connectedHoverHighlights?.length)?.connectedHoverHighlights?.[0]:void 0,{canonicalRefName:d}=i,u=n&&s&&d(s.refName)===d(n.refName)?n.g2p[s.start]:void 0;return u===void 0?void 0:{transcriptPos:u,source:"msa"}}function $t(e,t){if(!e||t===void 0)return;let n=Ie(e.p2gCodon,t);return n?`${e.refName}:${n[0]+1}-${n[1]}`:void 0}function jt({hover:e,entity:t,structureToTranscript:n,transcript:r,locus:o}){let i=e.structureSeqPos,a=i===void 0?void 0:n?.[i],s=i===void 0?void 0:t?.seq[i],d=a===void 0?void 0:r[a],u=[];if(i!==void 0){let c=U(t,i);u.push(`${c}`),a!==void 0&&a+1!==c&&u.push(`Transcript residue: ${a+1}`)}return s&&u.push(`Structure: ${s}`),d&&s&&d!==s&&u.push(`Genome: ${d}`),e.chain&&u.push(`Chain: ${e.chain}`),o&&u.push(o),u.join(", ")}var zt=C(Z());function Jt(e,t){let n=e.genomeToTranscriptSeqMapping;if(!n)return[];let r=[];for(let o of t)for(let i=o.start;i<o.end;i++){let a=e.structureSeqToTranscriptSeqPosition?.[i];a!==void 0&&r.push(a)}return Je(n.p2gCodon,r)}function Wt({ranges:e,assemblyName:t,model:n}){let r=n.genomeToTranscriptSeqMapping?.refName;return t&&r?Jt(n,e).map(([o,i])=>({assemblyName:t,refName:r,start:o,end:i})):[]}async function pe({model:e,structureSeqPos:t,structureSeqEndPos:n,zoomToBaseLevel:r}){let o=(0,zt.getSession)(e),{connectedView:i,genomeToTranscriptSeqMapping:a}=e;if(!a||!i)return;let{strand:s,refName:d}=a,u=i.assemblyNames[0];if(!u)return;let c=Jt(e,[{start:t,end:n??t+1}]),m=c[0]?.[0],l=c.at(-1)?.[1];if(!(m===void 0||l===void 0))if(r)await i.navToLocString(`${d}:${m+1}-${l}${s===-1?"[rev]":""}`,void 0,.2);else{let{assemblyManager:f}=o,M=f.get(u)?.getCanonicalRefName(d)??d;i.centerAt((m+l)/2,M)}}async function W({model:e,structureSeqPos:t,structureSeqEndPos:n}){e.setClickedStructureRanges([{start:t,end:n??t+1}]),await pe({model:e,structureSeqPos:t,structureSeqEndPos:n,zoomToBaseLevel:e.zoomToBaseLevel})}var Kt=/-\d+$/;function Zt({uniprotId:e,pdbId:t,modelAccession:n,uniProtMappings:r,uniProtMappingsError:o,mappedEntity:i}){if(e&&!t){let s=[n,e].find(d=>d!==void 0&&Kt.test(d));return{uniprotId:e.replace(Kt,""),uniprotName:void 0,mapUniProtPosition:s?()=>{}:ee,isLoading:!1,error:void 0,isoformAccession:s}}let a=r?He(r,i):void 0;return{uniprotId:a?.accession,uniprotName:a?.name,mapUniProtPosition:a?Ne(a.segments):ee,isLoading:!!t&&!r&&!o,error:o}}function Yt(e,t,n){return function(){let o=e.variantEffectAsk,i=e.variantEffects;if(!o){i&&e.setVariantEffects(void 0);return}if(o.status!=="ready"||i?.key===o.request.key)return;let{request:a}=o,{key:s}=a;e.setVariantEffects({key:s});let d=u=>{t()&&e.variantEffects?.key===s&&e.setVariantEffects({key:s,...u})};n(a).then(u=>{d({values:u})},u=>{d({error:u})})}}function Xt({ask:e,state:t,entity:n,pdbId:r,mapUniProtPosition:o,transcriptToStructure:i}){if(e?.status!=="ready")return{pending:e?.status==="waiting",message:e?.status==="unavailable"?e.reason:void 0};let{request:a}=e,s=t?.key===a.key?t:void 0,d=Xe[a.scheme],{error:u}=s??{};if(u!==void 0)return{pending:!1,message:u instanceof Qe?u.message:`Could not fetch ${d} for ${a.label}: ${O(u)}`};let c=s?.values;if(!c)return{pending:!0};if(c.numbering==="uniprot"&&!r&&n&&c.sequence!==n.seq)return{pending:!1,message:`${d} for ${a.label} number a sequence that differs from this model's`};let m=c.numbering==="uniprot"?o:i&&(l=>i[l]);return{pending:!1,placed:n&&m?et(c.byPosition,m,n):void 0}}function Tn(e){return"assemblyNames"in e}var wn=[],Mn=p.types.model({url:p.types.maybe(p.types.string),data:p.types.maybe(p.types.string),uniprotId:p.types.maybe(p.types.string),connectedViewId:p.types.maybe(p.types.string),pairwiseAlignment:p.types.frozen(),feature:p.types.frozen(),userProvidedTranscriptSequence:p.types.optional(p.types.string,""),initialSelection:p.types.frozen(),initialResidues:p.types.frozen(),initialTranscriptResidues:p.types.frozen(),mappedEntityId:p.types.maybe(p.types.string),alignmentImported:p.types.optional(p.types.boolean,!1),hidden:p.types.optional(p.types.boolean,!1)}).volatile(()=>({clickedStructureRanges:[],seedLit:!1,selectionTouched:!1,hoverPosition:void 0,entities:void 0,structureConfidence:void 0,isMouseInAlignment:!1,alignmentSkipped:void 0,entityChosen:!1,aligning:!1,pendingEntityId:void 0,alignmentRedecisions:0,loadedToMolstar:!1,molstarStructures:new Array,molstarModelIds:new Array,alignmentHoverRange:void 0,selectedFeatureId:void 0,hiddenFeatureTypes:new Set,expandedFeatureTypes:new Set,uniProtMappings:void 0,uniProtMappingsError:void 0,variantEffects:void 0,error:void 0})).actions(e=>({setUrl(t){e.url=t},setError(t){e.error=t},setUniProtMappings(t,n){e.uniProtMappings=t,e.uniProtMappingsError=n},setVariantEffects(t){e.variantEffects=t},setStructureData(t){e.entities=t.entities,e.structureConfidence=t.confidence,e.molstarStructures=t.molstarStructures??[],e.molstarModelIds=t.modelIds??new Array},hideFeatureType(t){e.hiddenFeatureTypes=new Set([...e.hiddenFeatureTypes,t])},showAllFeatureTypes(){e.hiddenFeatureTypes=new Set},toggleFeatureTypeExpanded(t){let n=new Set(e.expandedFeatureTypes);n.has(t)?n.delete(t):n.add(t),e.expandedFeatureTypes=n},setLoadedToMolstar(t){e.loadedToMolstar=t,t||(e.molstarStructures=[],e.molstarModelIds=new Array)}})).views(e=>({get molstarStructure(){return e.molstarStructures[0]},get connectedView(){let{views:t}=(0,k.getSession)(e);return t.filter(Tn).find(n=>n.id===e.connectedViewId)}})).actions(e=>({setClickedStructureRanges(t){e.clickedStructureRanges=t,e.selectionTouched=!0,e.seedLit=!1},applySeed(t){e.selectionTouched||(e.clickedStructureRanges=t,e.seedLit=t.length>0)},setAlignmentHoverRange(t){e.alignmentHoverRange=t},setSelectedFeatureId(t){e.selectedFeatureId=t},setHoveredPosition(t){let n=e.hoverPosition;(t===void 0?n!==void 0:n?.source!=="structure"||n.structureSeqPos!==t.structureSeqPos||n.chain!==t.chain)&&(e.hoverPosition=t?{...t,source:"structure"}:void 0)},setConnectedHoveredPosition(t,n="genome"){let r=t===void 0?void 0:{structureSeqPos:t,source:n},o=e.hoverPosition;(r?.structureSeqPos!==o?.structureSeqPos||r?.source!==o?.source)&&(e.hoverPosition=r)},setAlignment(t,n=!1){e.pairwiseAlignment=t,e.alignmentImported=n,e.alignmentSkipped=void 0},setAlignmentSkipped(t){e.alignmentSkipped=t},setEntityChosen(){e.entityChosen=!0},setAligning(t,n){e.aligning=t,e.pendingEntityId=n},settleAlignment(t){e.aligning=!1,e.pendingEntityId=void 0,t()},setHidden(t){e.hidden=t},setMappedEntityId(t){e.mappedEntityId=t},setIsMouseInAlignment(t){e.isMouseInAlignment=t},leaveAlignment(){e.hoverPosition=void 0,e.isMouseInAlignment=!1}})).views(e=>({get mappedEntity(){let{entities:t,mappedEntityId:n}=e;return t?.find(r=>r.entityId===n)??t?.find(r=>!r.nucleicAcid)??t?.[0]},get mappedStructureSeq(){return this.mappedEntity?.seq},get label(){return $e(e)},get pdbId(){let{url:t}=e;return t&&!B(t)?Be(t):void 0},get uniProtEntry(){return Zt({uniprotId:e.uniprotId,pdbId:this.pdbId,modelAccession:e.url?B(e.url):void 0,uniProtMappings:e.uniProtMappings,uniProtMappingsError:e.uniProtMappingsError,mappedEntity:this.mappedEntity})},get alignment(){let t=e.pairwiseAlignment;return!t||!e.uniProtMappings||e.alignmentImported?t:Me(t,Fe(e.uniProtMappings,this.mappedEntity,we(t)))},get coordinateMapper(){let{alignment:t}=this;return t?Ae(t):void 0},get structureSeqToTranscriptSeqPosition(){return this.coordinateMapper?.maps.structureSeqToTranscriptSeqPosition},get transcriptSeqToStructureSeqPosition(){return this.coordinateMapper?.maps.transcriptSeqToStructureSeqPosition},get structurePositionToAlignmentMap(){return this.coordinateMapper?.maps.structurePositionToAlignmentMap},get confidenceCells(){let t=this.mappedEntity,n=e.structureConfidence?.find(o=>o.entityId===t?.entityId);if(!t||!n)return[];let r=t.seqIds.map(o=>n.byLabelSeqId.get(o));return Ve(r.filter(o=>o!==void 0))?te(r,this.structurePositionToAlignmentMap):[]},get hydrophobicityCells(){let t=this.mappedStructureSeq;return t&&!this.mappedEntity?.nucleicAcid?te(pt(F(t)),this.structurePositionToAlignmentMap):[]},get pairwiseAlignmentToStructurePosition(){return this.coordinateMapper?.maps.alignmentToStructurePosition},get hoverString(){let t=e.hoverPosition;return t?jt({hover:t,entity:this.mappedEntity,structureToTranscript:this.structureSeqToTranscriptSeqPosition,transcript:e.userProvidedTranscriptSequence,locus:this.hoverGenomeLocus}):""},get hoverGenomeLocus(){let t=this.structureSeqHoverPos;return $t(this.genomeToTranscriptSeqMapping,t===void 0?void 0:this.structureSeqToTranscriptSeqPosition?.[t])},get genomeToTranscriptSeqMapping(){return e.feature?ze(new k.SimpleFeature(e.feature)):void 0},get structureSeqHoverPos(){return e.hoverPosition?.structureSeqPos},get alignmentHoverPos(){let t=this.structureSeqHoverPos;return t===void 0?void 0:this.coordinateMapper?.structureToAlignment(Ce(t))},get hoverStructureRange(){let{alignmentHoverRange:t}=e,n=this.pairwiseAlignmentToStructurePosition;if(!t||!n)return;let r=n[t.start],o=n[t.end];return r===void 0||o===void 0?void 0:{start:r,end:o+1}},get hoverHighlightRange(){let t=this.structureSeqHoverPos;return this.hoverStructureRange??(t===void 0?void 0:{start:t,end:t+1})},get labelSeqIdIndex(){return qe(this.mappedEntity)},get selectLabelSeqIds(){let t=this.mappedEntity;if(e.clickedStructureRanges.length)return this.clickedLabelSeqIds;let n=this.structureSeqToTranscriptSeqPosition;return this.showHighlight&&n?Re(t,Object.keys(n).map(Number)):[]},get clickedLabelSeqIds(){let t=this.mappedEntity;return e.clickedStructureRanges.flatMap(n=>Q(t,n))},get seededSelection(){return[e.initialSelection,e.initialResidues,e.initialTranscriptResidues].some(t=>oe(t).length>0)},get hoverLabelSeqIds(){return Q(this.mappedEntity,this.hoverHighlightRange)},get clickAlignmentRanges(){let t=this.structurePositionToAlignmentMap;return t?e.clickedStructureRanges.flatMap(n=>{let r=t[n.start],o=t[n.end-1];return r===void 0||o===void 0?[]:[{start:r,end:o}]}):[]},get alignmentMatchSet(){let t=this.alignment?.consensus;if(!t)return;let n=new Set;for(let r=0;r<t.length;r++)(t[r]==="|"||t[r]===":")&&n.add(r);return n},get alignmentPending(){return e.aligning||!e.pairwiseAlignment&&!e.alignmentSkipped&&!!e.userProvidedTranscriptSequence&&!!e.entities?.length},get loading(){return e.error!==void 0?!1:!e.loadedToMolstar||this.alignmentPending||!!this.pdbId&&e.uniProtMappings===void 0&&e.uniProtMappingsError===void 0},get loadingMessage(){if(this.loading){if(!e.loadedToMolstar)return e.url===void 0&&e.data===void 0&&e.uniprotId?`Resolving AlphaFold model for ${e.uniprotId}`:`Loading ${this.label}`;if(this.alignmentPending){let t=e.feature?.name;return typeof t=="string"?`Aligning ${this.label} to ${t}`:`Aligning ${this.label}`}return`Mapping ${this.label} to UniProt`}},get alignmentQuality(){let{alignment:t}=this;return t?Ee(t):void 0},get exactMatch(){let t=F(e.userProvidedTranscriptSequence),n=this.mappedStructureSeq?F(this.mappedStructureSeq):void 0;return t===n},get parentView(){return(0,p.getParent)(e,2)},get zoomToBaseLevel(){return this.parentView.zoomToBaseLevel},get autoScrollAlignment(){return this.parentView.autoScrollAlignment},get showHighlight(){return this.parentView.showHighlight},get showProteinTracks(){return this.parentView.showProteinTracks},get showAllFeatureTracks(){return this.parentView.showAllFeatureTracks},get omittedFeatureTypes(){return this.showAllFeatureTracks?e.hiddenFeatureTypes:new Set([...yt,...e.hiddenFeatureTypes])},get columnWidth(){return 6},get trackHeight(){return _(this.parentView)},get trackGap(){return St(this.trackHeight)},get laneHeight(){return this.trackHeight+this.trackGap},get alignmentAlgorithm(){return this.parentView.alignmentAlgorithm},get molstarPluginContext(){return this.parentView.molstarPluginContext}})).views(e=>({residueNumber(t){return U(e.mappedEntity,t)},interactionPosition(t){return e.molstarModelIds.includes(t.modelId)&&t.entityId===e.mappedEntity?.entityId?e.labelSeqIdIndex.get(t.labelSeqId):void 0},structureRangesToGenomeHighlight(t){return Wt({ranges:t,assemblyName:e.connectedView?.assemblyNames[0],model:{genomeToTranscriptSeqMapping:e.genomeToTranscriptSeqMapping,structureSeqToTranscriptSeqPosition:e.structureSeqToTranscriptSeqPosition}})}})).views(e=>({get hoverGenomeHighlights(){let t=e.hoverPosition?.source;return t==="genome"||t==="msa"?wn:e.structureRangesToGenomeHighlight(oe(e.hoverHighlightRange))},get clickGenomeHighlights(){return e.structureRangesToGenomeHighlight(e.clickedStructureRanges)}})).views(e=>({get hydrophobicityScale(){let{color:t}=e.parentView,n=(t.field==="hydrophobicity"?$(t):void 0)??ot.hydrophobicity;return{title:n.title??"",paint:lt(n),key:mt(n)}},get variantEffectAsk(){let{field:t}=e.parentView.color;if(t==="alphaMissense")return tt(e.uniProtEntry);if(t==="clinvarPathogenicCount"){let n=e.connectedView?.assemblyNames[0],r=n?(0,k.getSession)(e).assemblyManager.get(n):void 0;return nt({feature:e.feature,assemblyName:n,assemblyNames:[...n?[n]:[],...r?[r.name,...r.aliases]:[]]})}}})).views(e=>({get variantEffectStatus(){return Xt({ask:e.variantEffectAsk,state:e.variantEffects,entity:e.mappedEntity,pdbId:e.pdbId,mapUniProtPosition:e.uniProtEntry.mapUniProtPosition,transcriptToStructure:e.transcriptSeqToStructureSeqPosition})},get genomeNaming(){return he((0,k.getSession)(e).assemblyManager,e.connectedView?.assemblyNames[0])},get alignmentDomains(){return st((0,k.getSession)(e).views,e.connectedViewId).domains}})).views(e=>({get alignmentDomainStatus(){return e.parentView.color.field==="domain"?ut({views:(0,k.getSession)(e).views,connectedViewId:e.connectedViewId,mapping:e.genomeToTranscriptSeqMapping,naming:e.genomeNaming,entity:e.mappedEntity,transcriptToStructure:e.transcriptSeqToStructureSeqPosition}):void 0},get sessionHighlightMarks(){let t=(0,k.getSession)(e),{genomeToTranscriptSeqMapping:n,mappedEntity:r,transcriptSeqToStructureSeqPosition:o}=e;return t.highlightsVisible&&n&&r&&o?Vt({highlights:t.highlights,mapping:n,naming:e.genomeNaming,entity:r,transcriptToStructure:o,labels:!("highlightLabelsVisible"in t&&t.highlightLabelsVisible===!1)}):[]},get domainRows(){let{alignmentDomains:t,genomeToTranscriptSeqMapping:n,transcriptSeqToStructureSeqPosition:r,structurePositionToAlignmentMap:o}=e;return t&&n&&r&&o?ct({domains:t,mapping:n,naming:e.genomeNaming,transcriptToStructure:r,structureToAlignment:o}):[]}})).views(e=>({get placedVariantEffects(){return e.variantEffectStatus.placed},get placedValues(){return e.alignmentDomainStatus?.placed??e.variantEffectStatus.placed},get variantEffectsPending(){return e.variantEffectStatus.pending},get statusMessage(){let{error:t}=e;return t===void 0?e.alignmentSkipped??e.variantEffectStatus.message??e.alignmentDomainStatus?.message:O(t)}})).views(e=>({resolveSelection({positions:t,residues:n,transcriptResidues:r}){let o=!!e.entities&&(e.entityChosen||!e.userProvidedTranscriptSequence),i=e.coordinateMapper;if(!(n&&!o)&&!(r&&e.loading))return ie([...ie(t??[]),...n?ht(e.mappedEntity,n):[],...i&&r?bt(i,r):[]])}})).extend(e=>{let t=0;function n(){t++,e.setAligning(!1)}return{actions:{supersedeAlignment:n,redecideAlignment(){t++,e.aligning=!1,e.pendingEntityId=void 0,e.alignmentRedecisions++},runAlignment({identical:r,name:o,args:i,inPlace:a,apply:s,fail:d,pendingEntityId:u}){if(r){n();try{s(a())}catch(l){console.error(l),e.setError(l)}return}let c=++t,m=()=>c===t&&(0,p.isAlive)(e);e.setAligning(!0,u),je({rpcManager:(0,k.getSession)(e).rpcManager,name:o,args:i,inPlace:a,current:m}).then(l=>{if(m())try{e.settleAlignment(()=>{s(l)})}catch(f){console.error(f),e.setError(f)}},l=>{m()&&(console.error(l),e.settleAlignment(()=>{d(l)}))})}}}}).actions(e=>({applyEntitySelection(t){let n=e.entities??[];if(t)e.setMappedEntityId(n[t.index]?.entityId),e.setAlignment(t.alignment);else{let r=n.filter(o=>!o.nucleicAcid&&o.seq.length>0);e.setAlignmentSkipped(r.length?`No chain could be aligned: ${r.map(o=>ve(o)).join(", ")} exceed the alignment size limit against this ${F(e.userProvidedTranscriptSequence).length} aa transcript`:"This structure has no protein chain to align the transcript to")}e.setEntityChosen()},applyRealignment(t){e.setAlignment(t?.alignment),t&&e.setEntityChosen()},switchEntity(t){e.setMappedEntityId(t),e.setClickedStructureRanges([]),e.setAlignmentHoverRange(void 0),e.setSelectedFeatureId(void 0),e.setHoveredPosition(void 0)}})).actions(e=>({applyChosenEntity(t,n){e.switchEntity(t),e.setAlignment(n)},importAlignment(t){let{entities:n,mappedEntityId:r}=e,o=n?z(t,e.userProvidedTranscriptSequence,n,r):void 0;o&&"entityId"in o&&o.entityId!==r&&e.switchEntity(o.entityId),e.supersedeAlignment(),e.setAlignment(t,!0)}})).actions(e=>({setViewError(t){e.parentView.setError(t)},resizeTracks(t){e.parentView.resizeTracks(t)},hoverAlignmentPosition(t){if(!e.alignmentHoverRange){let n=e.coordinateMapper?.alignmentToStructure(Y(t));e.setHoveredPosition(n!==void 0?{structureSeqPos:n}:void 0)}},chooseEntity(t){let n=e.entities?.find(s=>s.entityId===t),r=e.mappedEntity?.entityId;if(!n||t===(e.pendingEntityId??r))return;if(!e.userProvidedTranscriptSequence){e.switchEntity(t);return}if(e.pendingEntityId!==void 0&&t===r){e.redecideAlignment();return}let o=e.userProvidedTranscriptSequence,i=()=>X(o,n.seq,e.alignmentAlgorithm),a=s=>{s?e.applyChosenEntity(t,s.alignment):(e.parentView.setError(new Error(`${n.chains.join("/")||n.entityId} is too long to align to this transcript`)),e.redecideAlignment())};e.runAlignment({identical:N(o,n.seq),name:"ProteinAlignTranscriptToEntity",args:{transcript:o,entitySeq:n.seq,algorithm:e.alignmentAlgorithm},inPlace:i,apply:a,fail:s=>{e.parentView.setError(s),e.redecideAlignment()},pendingEntityId:t})},selectResidues(t,n){e.parentView.clearSelection(),W({model:e,structureSeqPos:t,structureSeqEndPos:n}).catch(r=>{console.error(r),e.parentView.setError(r)})}})).actions(e=>({clickAlignmentPosition(t){let n=e.coordinateMapper?.alignmentToStructure(Y(t));n===void 0?e.parentView.clearSelection():e.selectResidues(n)},toggleDomainRow(t){let n=`alignment:${t.accession}`;e.selectedFeatureId===n?(e.setSelectedFeatureId(void 0),e.setClickedStructureRanges([])):(e.parentView.clearSelection(),e.setClickedStructureRanges(t.bars.map(r=>({start:r.structureStart,end:r.structureEnd}))),e.setSelectedFeatureId(n))}})).actions(e=>({async focusResidues(t,{timeout:n=12e4}={}){let r=()=>(e.entityChosen||!e.userProvidedTranscriptSequence)&&e.parentView.settled&&e.resolveSelection(t)!==void 0;try{await(0,R.when)(()=>!(0,p.isAlive)(e)||e.error!==void 0||r(),{timeout:n})}catch{throw new Error(`${e.label} did not finish loading`)}if(!(0,p.isAlive)(e))return[];if(e.error!==void 0)throw new Error(`${e.label} failed`,{cause:e.error});let o=e.resolveSelection(t)??[];e.parentView.clearSelection(),e.setClickedStructureRanges(o),e.setHidden(!1);let i=o[0],a=o.at(-1),s=e.molstarPluginContext,d=e.molstarStructure,u=e.clickedLabelSeqIds;return s&&d&&u.length&&ue(s,[{structure:d,entityId:e.mappedEntity?.entityId,labelSeqIds:u}],()=>e.molstarPluginContext===s).catch(c=>{console.error(c)}),i&&a&&pe({model:e,structureSeqPos:i.start,structureSeqEndPos:a.end,zoomToBaseLevel:e.zoomToBaseLevel}).catch(c=>{console.error(c),e.parentView.setError(c)}),o}})).actions(e=>({afterAttach(){let{pdbId:t}=e;(0,p.addDisposer)(e,(0,R.autorun)(Yt(e,()=>(0,p.isAlive)(e),o=>rt(o,(0,k.getSession)(e))))),t&&_e(t).then(o=>{(0,p.isAlive)(e)&&e.setUniProtMappings(o)},o=>{(0,p.isAlive)(e)&&e.setUniProtMappings(void 0,o)});let n={positions:e.initialSelection,residues:e.initialResidues,transcriptResidues:e.initialTranscriptResidues};e.seededSelection&&(0,p.addDisposer)(e,(0,R.when)(()=>e.selectionTouched||e.resolveSelection(n)!==void 0,()=>{e.applySeed(e.resolveSelection(n)??[])}));let r;(0,p.addDisposer)(e,(0,R.autorun)(()=>{try{let{alignmentAlgorithm:o}=e;e.alignmentRedecisions;let i=Ut(e),a=s=>{e.setViewError(new Error(`The alignment stored for ${e.label} no longer matches its chain and was recomputed: ${s}`))};switch(i.kind){case"nothingToAlign":e.supersedeAlignment();break;case"keep":e.setEntityChosen();break;case"adopt":e.setMappedEntityId(i.entityId),e.setEntityChosen();break;case"discard":a(i.problem),e.supersedeAlignment(),e.applyRealignment(void 0);break;case"realign":{let{transcript:s,entity:{seq:d}}=i,u=`${o}:${s}:${d}`;if(u===r&&e.aligning)break;r=u,a(i.problem),e.runAlignment({identical:i.identical,name:"ProteinAlignTranscriptToEntity",args:{transcript:s,entitySeq:d,algorithm:o},inPlace:()=>X(s,d,o),apply:c=>{e.applyRealignment(c)},fail:c=>{e.setError(c)}});break}case"choose":{let{transcript:s,entities:d}=i;e.runAlignment({identical:i.identical,name:"ProteinChooseMappedEntity",args:{transcript:s,entities:d.map(({seq:u,nucleicAcid:c})=>({seq:u,nucleicAcid:c})),algorithm:o},inPlace:()=>ke(s,d,o),apply:u=>{e.applyEntitySelection(u)},fail:u=>{e.setError(u)}});break}}}catch(o){console.error(o),e.setError(o)}})),(0,p.addDisposer)(e,(0,R.autorun)(()=>{let{hovered:o,views:i}=(0,k.getSession)(e),a=Bt({hovered:o,views:i,mapping:e.genomeToTranscriptSeqMapping,connectedViewId:e.connectedViewId,genomeViewReady:!!e.connectedView?.initialized,naming:e.genomeNaming});a?e.setConnectedHoveredPosition(e.transcriptSeqToStructureSeqPosition?.[a.transcriptPos],a.source):e.hoverPosition?.source!=="structure"&&e.setConnectedHoveredPosition(void 0)}))}})),In=p.types.snapshotProcessor(Mn,{preProcessor({pdbId:e,uniprotId:t,...n}){let r=Ue({...n,uniprotId:t,pdbId:e});return{...n,url:r,uniprotId:t??(r?B(r):void 0),alignmentImported:n.alignmentImported??n.pairwiseAlignment!==void 0}}}),ge=In;var en=C(L());var En="SuperpositionTransform";async function Qt(e,t){let n=await T(),{QueryContext:r,StateTransforms:o,StructureElement:i,StructureSelection:a,StructureSelectionQueries:s,PluginCommands:d,tmAlign:u}=n,{query:c}=s.trace,m=t.flatMap(S=>{let[h]=S,I=S.flatMap(b=>A(e,n,b)??[]),[P]=I,w=P?.obj?.data;if(!h||!P||!w)return[];let E=a.toLociWithSourceUnits(c(new r(h)));return[{rootCell:P,cells:I,loci:i.Loci.remap(E,w)}]}),[l,...f]=m;if(!l||f.length===0)return;let M=e.state.data.selectQ(S=>S.byValue(l.rootCell).subtree().withTransformer(o.Model.TransformStructureConformation))[0]?.obj?.data.coordinateSystem;for(let{cells:S,loci:h}of f){let{bTransform:I,tmScoreA:P,tmScoreB:w,rmsd:E,alignedLength:b}=u(l.loci,h);for(let q of S)await Cn(n,e,q,I,M);e.log.info(`TM-align: TM-score=${P.toFixed(4)}/${w.toFixed(4)}, RMSD=${E.toFixed(2)} \xC5, aligned ${b} residues.`)}await new Promise(S=>{requestAnimationFrame(S),setTimeout(S,100)}),await d.Camera.Reset(e)}async function Cn({Mat4:e,StateObjectRef:t,StateTransforms:n},r,o,i,a){let s=t.resolveAndCheck(r.state.data,o);if(!s)return;let d=r.state.data.selectQ(l=>l.byRef(s.transform.ref).subtree().withTransformer(n.Model.TransformStructureConformation))[0],c={transform:{name:"matrix",params:{data:a&&!e.isIdentity(a.matrix)?e.mul(e(),a.matrix,i):i,transpose:!1}}},m=d?r.state.data.build().to(d).update(c):r.state.data.build().to(o).insert(n.Model.TransformStructureConformation,c,{tags:En});await r.runTask(r.state.data.updateTree(m))}function tn(e){let t=!1,n,r=[];function o(){let{molstarPluginContext:i,structures:a}=e,s=a.filter(m=>m.loadedToMolstar).map(m=>m.molstarStructures),d=s.length;i!==n&&(n=i,e.setSuperposedCount(0));let u=e.superposedCount,c=d!==u||s.some((m,l)=>m!==r[l]);i&&!t&&d>=2&&c&&(t=!0,Qt(i,s).catch(x(e,i)).finally(()=>{t=!1,(0,en.isAlive)(e)&&(e.molstarPluginContext===i&&e.superposedCount===u&&(r=s,e.setSuperposedCount(d)),o())}))}return o}async function nn({plugin:e,structures:t,hidden:n}){let r=await T();for(let o of t){let i=A(e,r,o);i&&i.state.isHidden!==n&&r.setSubtreeVisibility(e.state.data,i.transform.ref,n)}}var D=C(L()),rn=C(re());function An(e,t){return{labelSeqId:e.StructureProperties.residue.label_seq_id(t),code:e.StructureProperties.atom.label_comp_id(t),chain:e.StructureProperties.chain.auth_asym_id(t),entityId:e.StructureProperties.entity.id(t),modelId:t.unit.model.id}}async function fe({plugin:e,kind:t,onUpdate:n}){let r=await T(),o=!1,i=e.behaviors.interaction[t].subscribe(a=>{if(o)if(r.StructureElement.Loci.is(a.current.loci)){let s=r.StructureElement.Loci.getFirstLocation(a.current.loci);n(s?An(r,s):void 0)}else n(void 0)});return o=!0,()=>{i.unsubscribe()}}function on(e,t){let n=t&&e.interactionPosition(t);return n===void 0?void 0:{...t,structureSeqPos:n}}function kn(e,t){let n=on(e,t);e.setSelectedFeatureId(void 0),n?(e.setHoveredPosition(n),W({model:e,structureSeqPos:n.structureSeqPos}).catch(r=>{console.error(r),e.setViewError(r)})):e.setClickedStructureRanges([])}function an(e){let t=(n,r)=>{let o;(0,D.addDisposer)(e,()=>{o?.()}),(0,D.addDisposer)(e,(0,rn.autorun)(()=>{let{molstarPluginContext:i}=e;o?.(),o=void 0,i&&fe({plugin:i,kind:n,onUpdate:r}).then(a=>{(0,D.isAlive)(e)&&e.molstarPluginContext===i?o=a:a()},x(e,i))}))};t("click",n=>{for(let r of e.structures)kn(r,n)}),t("hover",n=>{for(let r of e.structures)r.setHoveredPosition(on(r,n))})}var qn=100,Ln=(0,ye.lazy)(()=>import("./AddStructureDialog-C4AV64MD.js")),Vn=(0,ye.lazy)(()=>import("./ManualAlignmentDialog-A6M3SJGN.js")),Hn=[{key:"showAlignment",label:"Show alignment"},{key:"showProteinTracks",label:"Show feature tracks",requires:["showAlignment"]},{key:"showAllFeatureTracks",label:"Show all feature tracks",requires:["showAlignment","showProteinTracks"]},{key:"compactTracks",label:"Compact tracks",requires:["showAlignment","showProteinTracks"]},{key:"autoScrollAlignment",label:"Auto-scroll alignment to hovered position",requires:["showAlignment"]},{key:"showControls",label:"Show Mol* controls"}],Fn=[["showHighlight","Highlight aligned residues"],["zoomToBaseLevel","Zoom to base level on click"]];function Nn(){return y.types.compose("ProteinView",sn.BaseViewModel,y.types.model({id:un.ElementId,type:y.types.literal("ProteinView"),structures:y.types.array(ge),showControls:!1,height:y.types.optional(y.types.number,650),showHighlight:!1,zoomToBaseLevel:!0,autoScrollAlignment:!1,color:y.types.optional(y.types.frozen(),{}),showAlignment:!0,showProteinTracks:!0,compactTracks:!0,trackHeight:y.types.maybe(y.types.number),showAllFeatureTracks:!1,alignmentStructureIndex:y.types.maybe(y.types.number),alignmentAlgorithm:y.types.optional(y.types.enumeration("AlignmentAlgorithm",Te),Pe)})).preProcessSnapshot(({colorScheme:e,...t})=>Gt({...t,displayName:t.displayName??Ze(t.structures??[]),color:ne(t.color??(e===void 0?{}:ft(e)))},le())).volatile(()=>({error:void 0,molstarPluginContext:void 0,superposedCount:0})).actions(e=>({setHeight(t){e.height=Math.max(t,qn)},resizeTracks(t){e.trackHeight=Math.min(40,Math.max(2,_(e)+t))},setError(t){e.error=t},setColor(t){e.color=ne(t)},setMolstarPluginContext(t){if(t!==e.molstarPluginContext)for(let n of e.structures)n.setLoadedToMolstar(!1);e.molstarPluginContext=t},setSuperposedCount(t){e.superposedCount=t},addStructure(t){e.structures.push(ge.create(t))},clearSelection(){for(let t of e.structures)t.setClickedStructureRanges([]),t.setSelectedFeatureId(void 0)},openAlignmentOf(t){e.alignmentStructureIndex=e.structures.indexOf(t)}})).actions(e=>({removeStructure(t){let n=e.molstarPluginContext,r=t.molstarStructure,o=e.structures.indexOf(t),i=e.alignmentStructureIndex;i!==void 0&&(e.alignmentStructureIndex=o===i?void 0:o<i?i-1:i),e.structures.remove(t),e.setSuperposedCount(0),n&&J({plugin:n,molstarStructure:r}).catch(x(e,n))}})).views(e=>({get tracksCompact(){return _(e)<12}})).actions(e=>({toggleSetting(t){let n=t==="compactTracks"?!e.tracksCompact:!e[t];e[t]=n,t==="compactTracks"&&(e.trackHeight=void 0),Dt(t,n)},toggleBehavior(t){e[t]=!e[t]}})).actions(e=>({afterAttach(){(0,y.addDisposer)(e,(0,v.autorun)(()=>{let{molstarPluginContext:n,color:r}=e,o=e.structures.flatMap(i=>i.entities?i.molstarStructures.map(a=>({molstarStructure:a,entityId:i.mappedEntity?.entityId,placedValues:i.placedValues,placedSites:i.alignmentDomainStatus?.placedSites,domainColor:i.alignmentDomainStatus?.domains?.color})):[]);n&&o.length>0&&At({plugin:n,color:r,structures:o}).catch(x(e,n))})),(0,y.addDisposer)(e,(0,v.autorun)(()=>{let n=e.molstarPluginContext,r=e.structures.flatMap(o=>o.entities?o.molstarStructures.map(i=>({molstarStructure:i,sites:o.alignmentDomainStatus?.placedSites,color:o.alignmentDomainStatus?.domains?.color})):[]);n&&r.length>0&&Mt({plugin:n,structures:r}).catch(x(e,n))})),(0,y.addDisposer)(e,(0,v.autorun)(()=>{let n=e.molstarPluginContext,r=e.structures.flatMap(o=>o.entities?o.molstarStructures.map(i=>({molstarStructure:i,marks:o.sessionHighlightMarks})):[]);n&&r.length>0&&Ht({plugin:n,structures:r}).then(()=>de(n)).catch(x(e,n))}));let t;(0,y.addDisposer)(e,()=>t?.()),(0,y.addDisposer)(e,(0,v.autorun)(()=>{t?.(),t=void 0;let n=e.molstarPluginContext,r=n?.canvas3d?.camera;if(!n||!r)return;let o,i=r.stateChanged.subscribe(()=>{clearTimeout(o),o=setTimeout(()=>{de(n).catch(x(e,n))},200)});t=()=>{clearTimeout(o),i.unsubscribe()}})),(0,y.addDisposer)(e,(0,v.autorun)(()=>{let n=e.molstarPluginContext;for(let r of e.structures){let{hidden:o,molstarStructures:i}=r;n&&i.length>0&&nn({plugin:n,structures:i,hidden:o}).catch(x(e,n))}})),(0,y.addDisposer)(e,(0,v.autorun)(Ot(e))),(0,y.addDisposer)(e,(0,v.autorun)(tn(e))),(0,y.addDisposer)(e,(0,v.autorun)(vt(e))),(0,y.addDisposer)(e,(0,v.autorun)(ce(e,"select"))),(0,y.addDisposer)(e,(0,v.autorun)(ce(e,"highlight"))),an(e)}})).views(e=>({get primaryStructure(){return e.structures[0]},get showLoading(){return Ft(e)},get settled(){return se(e)},get loadingMessages(){return e.structures.flatMap(t=>t.loadingMessage===void 0?[]:[{id:(0,y.getPath)(t),message:t.loadingMessage}])},get alignmentStructure(){let{structures:t,alignmentStructureIndex:n}=e;return(n===void 0?void 0:t[n])??t.find(r=>r.seededSelection)??t[0]},get colorLegend(){let t=e.molstarPluginContext,n=e.structures.find(o=>o.entities),r=n?.molstarStructures[0];return t&&r?kt({plugin:t,color:e.color,structure:r,entityId:n.mappedEntity?.entityId,domainColor:n.alignmentDomainStatus?.domains?.color}):void 0},get domainLegend(){let t=e.color.field==="domain"?e.structures.find(n=>n.alignmentDomains)?.alignmentDomains:void 0;return t?dt(t):void 0},get displayToggles(){return Hn.map(({key:t,label:n,requires:r=[]})=>{let o=r.some(i=>!e[i]);return{key:t,label:n,checked:t==="compactTracks"?e.tracksCompact:e[t],disabled:o,toggle:()=>{o||e.toggleSetting(t)}}})},get behaviorToggles(){return Fn.map(([t,n])=>({label:n,checked:e[t],toggle:()=>{e.toggleBehavior(t)}}))}})).views(e=>({offersChainPicker(t){return!e.showAlignment||e.alignmentStructure===t||!t.userProvidedTranscriptSequence},menuItems(){return[{label:"Add structure...",onClick:()=>{(0,Se.getSession)(e).queueDialog(t=>[Ln,{model:e,handleClose:t}])}},...e.structures.length>0?[{label:"Remove structure",subMenu:e.structures.map(t=>({label:t.label,onClick:()=>{e.removeStructure(t)}}))}]:[],{label:"Clear selection",onClick:()=>{e.clearSelection()}},{label:"Import manual alignment...",onClick:()=>{(0,Se.getSession)(e).queueDialog(t=>[Vn,{model:e,handleClose:t}])}},{label:"Re-align structures (TM-align)",onClick:()=>{e.setSuperposedCount(0)}},{label:"Restore hidden feature tracks",onClick:()=>{for(let t of e.structures)t.showAllFeatureTypes()}}]}}))}var Do=Nn;export{Do as default};
2
+ //# sourceMappingURL=model-6JF6QJWV.js.map