jbrowse-plugin-protein3d 1.14.0 → 1.15.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,6 +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
19
  import { showLoading } from './showLoading';
19
20
  import { readStoredSettings, storeSetting, withStoredSettings, } from './storedSettings';
20
21
  import { makeStructureLoader } from './structureLoader';
@@ -334,6 +335,20 @@ function stateModelFactory() {
334
335
  syncSiteSticks({ plugin, structures }).catch(reportPluginFailure(self, plugin));
335
336
  }
336
337
  }));
338
+ // The session's highlights, labelled in 3D on the residues each
339
+ // genome region codes for
340
+ addDisposer(self, autorun(() => {
341
+ const plugin = self.molstarPluginContext;
342
+ const structures = self.structures.flatMap(s => s.entities
343
+ ? s.molstarStructures.map(molstarStructure => ({
344
+ molstarStructure,
345
+ marks: s.sessionHighlightMarks,
346
+ }))
347
+ : []);
348
+ if (plugin && structures.length > 0) {
349
+ syncSessionHighlightMarks({ plugin, structures }).catch(reportPluginFailure(self, plugin));
350
+ }
351
+ }));
337
352
  addDisposer(self, autorun(() => {
338
353
  const plugin = self.molstarPluginContext;
339
354
  for (const s of self.structures) {
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The session's highlights on a structure. `session.highlights` is one list of
3
+ * labelled genome regions that every view draws on its own terms: a band on
4
+ * the genome, a column on the alignment, and here the residues the region
5
+ * codes for, drawn as sticks on every chain that has them with the
6
+ * highlight's label written once in 3D, so a figure or a shared session names
7
+ * the same position in each view.
8
+ *
9
+ * Each structure gets one component, one ball-and-stick and one label per
10
+ * highlight, all tagged `SESSION_HIGHLIGHTS_TAG`. A change rebuilds every one
11
+ * of them, since highlights change by hand and a structure holds a few.
12
+ */
13
+ import loadMolstar from './loadMolstar';
14
+ import { structureRootCell } from './structureCells';
15
+ export const SESSION_HIGHLIGHTS_TAG = 'jbrowse-session-highlights';
16
+ // core's default highlight color, which the genome view's band draws in
17
+ export const DEFAULT_HIGHLIGHT_COLOR = '#FFB11D';
18
+ /**
19
+ * Each highlight's residues on the mapped entity: genome base → transcript
20
+ * residue (`g2p`) → structure residue → `label_seq_id`. A highlight on
21
+ * another assembly or chromosome, or on residues the structure lacks, marks
22
+ * nothing.
23
+ */
24
+ export function sessionHighlightResidues({ highlights, mapping, naming, entity, transcriptToStructure, labels, }) {
25
+ const refName = naming.canonicalRefName(mapping.refName);
26
+ return highlights.flatMap(h => {
27
+ if (!naming.isAssembly(h.assemblyName) ||
28
+ naming.canonicalRefName(h.refName) !== refName) {
29
+ return [];
30
+ }
31
+ const labelSeqIds = new Set();
32
+ for (let base = h.start; base < h.end; base++) {
33
+ const residue = mapping.g2p[base];
34
+ const structurePos = residue === undefined ? undefined : transcriptToStructure[residue];
35
+ const labelSeqId = structurePos === undefined ? undefined : entity.seqIds[structurePos];
36
+ if (labelSeqId !== undefined) {
37
+ labelSeqIds.add(labelSeqId);
38
+ }
39
+ }
40
+ return labelSeqIds.size > 0
41
+ ? [
42
+ {
43
+ entityId: entity.entityId,
44
+ labelSeqIds: [...labelSeqIds].sort((a, b) => a - b),
45
+ label: labels && h.label ? h.label : undefined,
46
+ color: h.color ?? DEFAULT_HIGHLIGHT_COLOR,
47
+ },
48
+ ]
49
+ : [];
50
+ });
51
+ }
52
+ /**
53
+ * Make each structure's highlight marks match `marks`: the old ones go, and
54
+ * each mark gets its residues as sticks in its color and, when it has a
55
+ * label, the label in 3D over them.
56
+ */
57
+ export async function syncSessionHighlightMarks({ plugin, structures, }) {
58
+ const molstar = await loadMolstar();
59
+ const { Color, MolScriptBuilder: MS, StateSelection, StateTransforms, StructureElement, StructureProperties: SP, createStructureRepresentationParams, } = molstar;
60
+ // the first chain of an entity: a homo-oligomer such as haemoglobin's four
61
+ // β chains carries a highlighted residue once per chain, and one label per
62
+ // copy would stack four of them, so the label goes on the first
63
+ const firstChain = (structure, entityId) => {
64
+ const l = StructureElement.Location.create(structure);
65
+ for (const unit of structure.units) {
66
+ l.unit = unit;
67
+ l.element = unit.elements[0];
68
+ if (SP.entity.id(l) === entityId) {
69
+ return SP.chain.label_asym_id(l);
70
+ }
71
+ }
72
+ return undefined;
73
+ };
74
+ const update = plugin.state.data.build();
75
+ const existing = plugin.state.data.select(StateSelection.Generators.root.subtree().withTag(SESSION_HIGHLIGHTS_TAG));
76
+ for (const cell of existing) {
77
+ update.delete(cell.transform.ref);
78
+ }
79
+ for (const { molstarStructure, marks } of structures) {
80
+ const root = structureRootCell(plugin, molstar, molstarStructure);
81
+ if (!root) {
82
+ continue;
83
+ }
84
+ for (const { entityId, labelSeqIds, label, color } of marks) {
85
+ const expression = MS.struct.generator.atomGroups({
86
+ 'entity-test': MS.core.rel.eq([MS.ammp('label_entity_id'), entityId]),
87
+ 'residue-test': MS.core.set.has([
88
+ MS.set(...labelSeqIds),
89
+ MS.ammp('label_seq_id'),
90
+ ]),
91
+ });
92
+ update
93
+ .to(root)
94
+ .apply(StateTransforms.Model.StructureComponent, {
95
+ type: { name: 'expression', params: expression },
96
+ nullIfEmpty: true,
97
+ label: label ?? 'Session highlight',
98
+ }, { tags: [SESSION_HIGHLIGHTS_TAG] })
99
+ .apply(StateTransforms.Representation.StructureRepresentation3D, createStructureRepresentationParams(plugin, molstarStructure, {
100
+ type: 'ball-and-stick',
101
+ typeParams: { sizeFactor: 0.3, sizeAspectRatio: 0.6 },
102
+ color: 'uniform',
103
+ colorParams: { value: Color.fromHexStyle(color) },
104
+ }), { tags: [SESSION_HIGHLIGHTS_TAG] });
105
+ const chain = label ? firstChain(molstarStructure, entityId) : undefined;
106
+ if (label && chain) {
107
+ const labelled = MS.struct.generator.atomGroups({
108
+ 'chain-test': MS.core.rel.eq([MS.ammp('label_asym_id'), chain]),
109
+ 'residue-test': MS.core.set.has([
110
+ MS.set(...labelSeqIds),
111
+ MS.ammp('label_seq_id'),
112
+ ]),
113
+ });
114
+ update
115
+ .toRoot()
116
+ .apply(StateTransforms.Model.MultiStructureSelectionFromExpression, {
117
+ selections: [
118
+ { key: 'a', ref: root.transform.ref, expression: labelled },
119
+ ],
120
+ isTransitive: true,
121
+ label,
122
+ }, {
123
+ dependsOn: [root.transform.ref],
124
+ tags: [SESSION_HIGHLIGHTS_TAG],
125
+ })
126
+ .apply(StateTransforms.Representation.StructureSelectionsLabel3D, {
127
+ customText: label,
128
+ textSize: 4,
129
+ attachment: 'bottom-left',
130
+ scaleByRadius: false,
131
+ textColor: Color(0x000000),
132
+ borderWidth: 0,
133
+ background: true,
134
+ backgroundColor: Color(0xffffff),
135
+ backgroundOpacity: 0.85,
136
+ offsetZ: 10,
137
+ }, { tags: [SESSION_HIGHLIGHTS_TAG] });
138
+ }
139
+ }
140
+ }
141
+ await update.commit();
142
+ }
@@ -16,6 +16,7 @@ import { clickProteinToGenome, navigateToProteinPosition, structureRangesToGenom
16
16
  import { RESIDUE_COLORS } from './residueColors';
17
17
  import { positionRangeRuns, rangeList, residueRuns, transcriptRuns, } from './residueRanges';
18
18
  import { kyteDoolittleScores, mapResidueValuesToColumns } from './residueTracks';
19
+ import { sessionHighlightResidues } from './sessionHighlights';
19
20
  import { structureUniProt } from './structureUniProt';
20
21
  import { assemblyNaming, errorMessage } from './util';
21
22
  import { makeVariantEffectLoader } from './variantEffectLoader';
@@ -1061,6 +1062,29 @@ const Structure = types
1061
1062
  })
1062
1063
  : undefined;
1063
1064
  },
1065
+ /**
1066
+ * #getter
1067
+ * The session's highlights on the mapped entity, each with the residues
1068
+ * its genome region codes for; see sessionHighlights
1069
+ */
1070
+ get sessionHighlightMarks() {
1071
+ const session = getSession(self);
1072
+ const { genomeToTranscriptSeqMapping: mapping, mappedEntity: entity, transcriptSeqToStructureSeqPosition: transcriptToStructure, } = self;
1073
+ return session.highlightsVisible &&
1074
+ mapping &&
1075
+ entity &&
1076
+ transcriptToStructure
1077
+ ? sessionHighlightResidues({
1078
+ highlights: session.highlights,
1079
+ mapping,
1080
+ naming: self.genomeNaming,
1081
+ entity,
1082
+ transcriptToStructure,
1083
+ labels: !('highlightLabelsVisible' in session &&
1084
+ session.highlightLabelsVisible === false),
1085
+ })
1086
+ : [];
1087
+ },
1064
1088
  /**
1065
1089
  * #getter
1066
1090
  * The overview's "From the alignment" rows, one per accession, whatever
@@ -0,0 +1,2 @@
1
+ import{b as j}from"./chunk-5M4LVDLT.js";import{a as nt,b as rt,c as ot,d as it,e as at,f as st,h as dt,i as Z}from"./chunk-7SEZTF5X.js";import{b as lt}from"./chunk-NOFPQXHZ.js";import{a as te,b as F,c as pt,d as gt,o as ne,q as ft,r as St,s as re}from"./chunk-5YLRYIUR.js";import{c as ut,f as ct}from"./chunk-RL54DUYZ.js";import{a as h}from"./chunk-UTDQGJCS.js";import{c as ee,d as $,e as B,g as mt}from"./chunk-KXSOSKHQ.js";import{a as sn}from"./chunk-YCRC6WEC.js";import{a as q}from"./chunk-56ZPPPNO.js";import{a as an}from"./chunk-GVEKA5YG.js";import{b as je,c as ze,d as Je,f as Qe,g as Ze,i as et}from"./chunk-R64WXKZQ.js";import{a as tt}from"./chunk-LZTO76OW.js";import{b as fe,d as Se,e as D}from"./chunk-2RFFBSIA.js";import"./chunk-INWFM3CY.js";import"./chunk-5NBLSM7W.js";import{a as We,b as Ke,c as Ye,e as Xe}from"./chunk-ISVQX4IH.js";import{a as $e,b as Be}from"./chunk-UVDYWAS6.js";import{a as Ue,b as H}from"./chunk-7UQOTULP.js";import{$ as Ae,C as we,Da as He,Ga as Fe,Ha as Ne,L as Me,La as _e,N as K,O as Ie,Pa as Ge,Q as V,Qa as De,Ra as U,U as Y,Ua as Oe,V as Ee,X as O,_ as Ce,b as ye,ba as ke,c as he,ca as X,da as xe,ea as ve,fa as Re,ja as qe,ka as Le,l as be,la as Q,m as Pe,ma as Ve,p as Te}from"./chunk-WZCSPP5F.js";import{a as W}from"./chunk-B3HKXTGK.js";import"./chunk-SPXMXPSC.js";import{a as on,c as T}from"./chunk-KVMUXFPB.js";var ht=on((Rn,yt)=>{yt.exports=JBrowseExports["@jbrowse/core/util/types/mst"]});var ge=T(an()),tn=T(sn()),pe=T(W()),nn=T(ht()),f=T(q()),v=T(te());function E(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 N="jbrowse-alignment-sites",un={sizeFactor:.35,sizeAspectRatio:.6},bt=0;async function Pt({plugin:e,structures:t}){let n=await h(),{MolScriptBuilder:r,ProteinBackboneAtoms:o,StateSelection:i,StateTransforms:a,createStructureColorThemeParams:s,createStructureRepresentationParams:d,registerPlacedValues:u}=n;bt++;let c=e.state.data.build(),l=!1;for(let{molstarStructure:m,sites:g,color:b}of t){let S=E(e,n,m);if(!S)continue;let y=e.state.data.select(i.Generators.ofTransformer(a.Model.StructureComponent,S.transform.ref).withTag(N)),M=[...g?.byLabelSeqId.keys()??[]];if(u("alignment-sites",m,g),!g||!b||M.length===0){for(let A of y)c.delete(A.transform.ref),l=!0;continue}let P=A=>r.core.rel.eq([r.ammp("label_atom_id"),A]),w={type:{name:"expression",params:r.struct.generator.atomGroups({"entity-test":r.core.rel.eq([r.ammp("label_entity_id"),g.entityId]),"residue-test":r.core.set.has([r.set(...M),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")])]),P("CA"),r.core.logic.and([r.core.rel.eq([r.ammp("auth_comp_id"),"PRO"]),P("N")])])})},nullIfEmpty:!0,label:"Sites from the alignment"},I={...d(e,m,{type:"ball-and-stick",typeParams:un}),colorTheme:s(e,m,"ball-and-stick","alignment-domains",{revision:bt,color:b,mark:"atoms"})},[k]=y;if(k){c.to(k).update(w);for(let A of e.state.data.select(i.Generators.ofTransformer(a.Representation.StructureRepresentation3D,k.transform.ref)))c.to(A).update(I)}else c.to(S).apply(a.Model.StructureComponent,w,{tags:[N]}).apply(a.Representation.StructureRepresentation3D,I,{tags:[N]});l=!0}l&&await c.commit()}var cn=[...We,"alignment-domains"];function wt(e){return cn.some(t=>t===e)}function Mt(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??rt,mark:nt(o)}:i&&wt(B(e))?{revision:r,color:i}:i&&{color:i}}var Tt=0;async function It({plugin:e,color:t,structures:n}){let r=await h(),{StateSelection:o,StateTransforms:i,createStructureColorThemeParams:a,registerPlacedValues:s}=r,d=B(t),u=wt(d);u&&Tt++;let c=e.state.data.build(),l=0;for(let{molstarStructure:m,entityId:g,placedValues:b,placedSites:S,domainColor:y}of n){u&&s(d,m,b),t.field==="domain"&&s("alignment-sites",m,S);let M=E(e,r,m),P=M?e.state.data.select(o.Generators.ofTransformer(i.Representation.StructureRepresentation3D,M.transform.ref)):[];for(let w of P)!w.state.isGhost&&!w.transform.tags?.includes(N)&&(c.to(w).update(I=>{I.colorTheme=a(e,m,I.type.name,d,Mt(t,{entityId:g,domainColor:y,revision:Tt,representationType:I.type.name}))}),l++)}l>0&&await c.commit()}function Et({plugin:e,color:t,structure:n,entityId:r,domainColor:o}){let i=B(t);return i===void 0?void 0:e.representation.structure.themes.colorThemeRegistry.create(i,{structure:n},Mt(t,{entityId:r,domainColor:o})??{}).legend}function oe(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 Ct({interactivity:e,channel:t,targets:n}){let r=await h(),o=n.filter(s=>s.labelSeqIds.length>0).map(s=>oe(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 ie(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 ae(e,t,n=()=>!0){let r=await h();if(n()){let o=t.map(i=>oe(r,i));e.managers.camera.focusLoci(o),o[0]&&t[0]?.labelSeqIds.length===1&&e.managers.structure.focus.setFromLoci(o[0])}}function At(e){let t;return function(){let{molstarPluginContext:r,structures:o}=e;if(!r||r===t||!ie(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,ae(r,i,()=>e.molstarPluginContext===r).catch(a=>{console.error(a)}))}}function se(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&&Ct({interactivity:r.managers.interactivity,channel:t,targets:o}).catch(i=>{console.error(i)})}}async function z({plugin:e,molstarStructure:t}){if(!t)return;let n=await h(),{PluginCommands:r,PluginStateObject:o}=n,i=E(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 kt=T(q());function x(e,t){return n=>{console.error(n),(0,kt.isAlive)(e)&&e.molstarPluginContext===t&&e.setError(n)}}var _="jbrowse-session-highlights",dn="#FFB11D";function xt({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],l=c===void 0?void 0:o[c],m=l===void 0?void 0:r.seqIds[l];m!==void 0&&d.add(m)}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??dn}]:[]})}async function vt({plugin:e,structures:t}){let n=await h(),{Color:r,MolScriptBuilder:o,StateSelection:i,StateTransforms:a,StructureElement:s,StructureProperties:d,createStructureRepresentationParams:u}=n,c=(g,b)=>{let S=s.Location.create(g);for(let y of g.units)if(S.unit=y,S.element=y.elements[0],d.entity.id(S)===b)return d.chain.label_asym_id(S)},l=e.state.data.build(),m=e.state.data.select(i.Generators.root.subtree().withTag(_));for(let g of m)l.delete(g.transform.ref);for(let{molstarStructure:g,marks:b}of t){let S=E(e,n,g);if(S)for(let{entityId:y,labelSeqIds:M,label:P,color:w}of b){let I=o.struct.generator.atomGroups({"entity-test":o.core.rel.eq([o.ammp("label_entity_id"),y]),"residue-test":o.core.set.has([o.set(...M),o.ammp("label_seq_id")])});l.to(S).apply(a.Model.StructureComponent,{type:{name:"expression",params:I},nullIfEmpty:!0,label:P??"Session highlight"},{tags:[_]}).apply(a.Representation.StructureRepresentation3D,u(e,g,{type:"ball-and-stick",typeParams:{sizeFactor:.3,sizeAspectRatio:.6},color:"uniform",colorParams:{value:r.fromHexStyle(w)}}),{tags:[_]});let k=P?c(g,y):void 0;if(P&&k){let A=o.struct.generator.atomGroups({"chain-test":o.core.rel.eq([o.ammp("label_asym_id"),k]),"residue-test":o.core.set.has([o.set(...M),o.ammp("label_seq_id")])});l.toRoot().apply(a.Model.MultiStructureSelectionFromExpression,{selections:[{key:"a",ref:S.transform.ref,expression:A}],isTransitive:!0,label:P},{dependsOn:[S.transform.ref],tags:[_]}).apply(a.Representation.StructureSelectionsLabel3D,{customText:P,textSize:4,attachment:"bottom-left",scaleByRadius:!1,textColor:r(0),borderWidth:0,background:!0,backgroundColor:r(16777215),backgroundOpacity:.85,offsetZ:10},{tags:[_]})}}}await l.commit()}function Rt(e){return!e.minimized&&!e.error&&e.structures.some(t=>t.loading)}var qt="proteinView-settings",Lt=["showAlignment","showProteinTracks","showControls","autoScrollAlignment","compactTracks","showAllFeatureTracks"];function Vt(e,t){if(!t)return e;let n={...e};for(let r of Lt)n[r]===void 0&&t[r]!==void 0&&(n[r]=t[r]);return n}function ue(){let e=ze(qt);if(typeof e!="object"||e===null)return;let t={};for(let n of Lt){let r=Reflect.get(e,n);typeof r=="boolean"&&(t[n]=r)}return t}function Ht(e,t){je(qt,JSON.stringify({...ue(),[e]:t}))}var L=T(q());function ln(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 mn(e,t){if(!e||!t.MmcifFormat.is(e))return[];let{db:n,source:r}=e.data;return[...Array.from(n.exptl.method.toArray()),...r?ln(r,t):[]]}async function ce({structure:e,plugin:t}){let{data:n,url:r}=e,{model:o,structures:i,modelIds:a}=await lt({plugin:t,data:n||void 0,url:r}),s=mn(o?.obj?.data.sourceData,await h()).some(d=>d!=="THEORETICAL MODEL");return{entities:o?Ce(o):void 0,confidence:o&&!s?ve(o):void 0,molstarStructures:i,modelIds:a}}function Ft(e,t=Fe){let n=new Map,r=new WeakMap;function o(u){let{url:c,data:l,uniprotId:m}=u;return c===void 0&&l===void 0?m:void 0}async function i(u,c){let l=await t(c).catch(()=>{});if(!(0,L.isAlive)(u))return;if(l===void 0){u.setUrl(_e(c));return}let m=Ne(l,{transcript:{seq:u.userProvidedTranscriptSequence}});if(!m)throw new Error(`AlphaFold DB has no model for ${c}`);u.setUrl(m.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 l=o(u);(l===void 0?ce({structure:u,plugin:c}):i(u,l).then(()=>(0,L.isAlive)(u)?ce({structure:u,plugin:c}):void 0)).then(g=>{if(!g){a(u,c);return}if(!(0,L.isAlive)(u)){a(u,c),z({plugin:c,molstarStructure:g.molstarStructures?.[0]}).catch(S=>{console.error(S)});return}let b=e.molstarPluginContext;b===c&&(u.setStructureData(g),u.setLoadedToMolstar(!0)),a(u,c),b&&b!==c&&!u.loadedToMolstar&&s(u,b)}).catch(g=>{if(a(u,c),!(0,L.isAlive)(e)||!(0,L.isAlive)(u))return;let b=e.molstarPluginContext;b&&b!==c?s(u,b):(r.set(u,c),u.setError(g),console.error(g))})}return function(){let{structures:c,molstarPluginContext:l}=e;if(l)for(let m of c)!m.loadedToMolstar&&n.get(m)!==l&&r.get(m)!==l&&d(m,l)}}var C=T(W()),p=T(q()),R=T(te());function Nt(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=j(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:H(t,a.seq)}:{kind:"discard",problem:i.problem}}return{kind:"choose",transcript:t,entities:n,identical:n.some(o=>!o.nucleicAcid&&H(t,o.seq))}}function _t({hovered:e,views:t,mapping:n,connectedViewId:r,genomeViewReady:o,naming:i}){let a=o?Se(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 Gt(e,t){if(!e||t===void 0)return;let n=Te(e.p2gCodon,t);return n?`${e.refName}:${n[0]+1}-${n[1]}`:void 0}function Dt({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=O(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 Ot=T(W());function Ut(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 Be(n.p2gCodon,r)}function $t({ranges:e,assemblyName:t,model:n}){let r=n.genomeToTranscriptSeqMapping?.refName;return t&&r?Ut(n,e).map(([o,i])=>({assemblyName:t,refName:r,start:o,end:i})):[]}async function de({model:e,structureSeqPos:t,structureSeqEndPos:n,zoomToBaseLevel:r}){let o=(0,Ot.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=Ut(e,[{start:t,end:n??t+1}]),l=c[0]?.[0],m=c.at(-1)?.[1];if(!(l===void 0||m===void 0))if(r)await i.navToLocString(`${d}:${l+1}-${m}${s===-1?"[rev]":""}`,void 0,.2);else{let{assemblyManager:g}=o,S=g.get(u)?.getCanonicalRefName(d)??d;i.centerAt((l+m)/2,S)}}async function J({model:e,structureSeqPos:t,structureSeqEndPos:n}){e.setClickedStructureRanges([{start:t,end:n??t+1}]),await de({model:e,structureSeqPos:t,structureSeqEndPos:n,zoomToBaseLevel:e.zoomToBaseLevel})}var Bt=/-\d+$/;function jt({uniprotId:e,pdbId:t,modelAccession:n,uniProtMappings:r,uniProtMappingsError:o,mappedEntity:i}){if(e&&!t){let s=[n,e].find(d=>d!==void 0&&Bt.test(d));return{uniprotId:e.replace(Bt,""),uniprotName:void 0,mapUniProtPosition:s?()=>{}:Q,isLoading:!1,error:void 0,isoformAccession:s}}let a=r?qe(r,i):void 0;return{uniprotId:a?.accession,uniprotName:a?.name,mapUniProtPosition:a?Ve(a.segments):Q,isLoading:!!t&&!r&&!o,error:o}}function zt(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 Jt({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=Ke[a.scheme],{error:u}=s??{};if(u!==void 0)return{pending:!1,message:u instanceof Ye?u.message:`Could not fetch ${d} for ${a.label}: ${D(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 l=c.numbering==="uniprot"?o:i&&(m=>i[m]);return{pending:!1,placed:n&&l?Xe(c.byPosition,l,n):void 0}}function gn(e){return"assemblyNames"in e}var fn=[],Sn=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,C.getSession)(e);return t.filter(gn).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 Oe(e)},get pdbId(){let{url:t}=e;return t&&!U(t)?De(t):void 0},get uniProtEntry(){return jt({uniprotId:e.uniprotId,pdbId:this.pdbId,modelAccession:e.url?U(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:Pe(t,Le(e.uniProtMappings,this.mappedEntity,be(t)))},get coordinateMapper(){let{alignment:t}=this;return t?Ie(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 Re(r.filter(o=>o!==void 0))?Z(r,this.structurePositionToAlignmentMap):[]},get hydrophobicityCells(){let t=this.mappedStructureSeq;return t&&!this.mappedEntity?.nucleicAcid?Z(dt(V(t)),this.structurePositionToAlignmentMap):[]},get pairwiseAlignmentToStructurePosition(){return this.coordinateMapper?.maps.alignmentToStructurePosition},get hoverString(){let t=e.hoverPosition;return t?Dt({hover:t,entity:this.mappedEntity,structureToTranscript:this.structureSeqToTranscriptSeqPosition,transcript:e.userProvidedTranscriptSequence,locus:this.hoverGenomeLocus}):""},get hoverGenomeLocus(){let t=this.structureSeqHoverPos;return Gt(this.genomeToTranscriptSeqMapping,t===void 0?void 0:this.structureSeqToTranscriptSeqPosition?.[t])},get genomeToTranscriptSeqMapping(){return e.feature?$e(new C.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(Me(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 xe(this.mappedEntity)},get selectLabelSeqIds(){let t=this.mappedEntity;if(e.clickedStructureRanges.length)return this.clickedLabelSeqIds;let n=this.structureSeqToTranscriptSeqPosition;return this.showHighlight&&n?ke(t,Object.keys(n).map(Number)):[]},get clickedLabelSeqIds(){let t=this.mappedEntity;return e.clickedStructureRanges.flatMap(n=>X(t,n))},get seededSelection(){return[e.initialSelection,e.initialResidues,e.initialTranscriptResidues].some(t=>ne(t).length>0)},get hoverLabelSeqIds(){return X(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?we(t):void 0},get exactMatch(){let t=V(e.userProvidedTranscriptSequence),n=this.mappedStructureSeq?V(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([...gt,...e.hiddenFeatureTypes])},get columnWidth(){return 6},get trackHeight(){return F(this.parentView)},get trackGap(){return pt(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 O(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 $t({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"?fn:e.structureRangesToGenomeHighlight(ne(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)??tt.hydrophobicity;return{title:n.title??"",paint:ut(n),key:ct(n)}},get variantEffectAsk(){let{field:t}=e.parentView.color;if(t==="alphaMissense")return Qe(e.uniProtEntry);if(t==="clinvarPathogenicCount"){let n=e.connectedView?.assemblyNames[0],r=n?(0,C.getSession)(e).assemblyManager.get(n):void 0;return Ze({feature:e.feature,assemblyName:n,assemblyNames:[...n?[n]:[],...r?[r.name,...r.aliases]:[]]})}}})).views(e=>({get variantEffectStatus(){return Jt({ask:e.variantEffectAsk,state:e.variantEffects,entity:e.mappedEntity,pdbId:e.pdbId,mapUniProtPosition:e.uniProtEntry.mapUniProtPosition,transcriptToStructure:e.transcriptSeqToStructureSeqPosition})},get genomeNaming(){return fe((0,C.getSession)(e).assemblyManager,e.connectedView?.assemblyNames[0])},get alignmentDomains(){return ot((0,C.getSession)(e).views,e.connectedViewId).domains}})).views(e=>({get alignmentDomainStatus(){return e.parentView.color.field==="domain"?it({views:(0,C.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,C.getSession)(e),{genomeToTranscriptSeqMapping:n,mappedEntity:r,transcriptSeqToStructureSeqPosition:o}=e;return t.highlightsVisible&&n&&r&&o?xt({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?at({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:D(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 re([...re(t??[]),...n?ft(e.mappedEntity,n):[],...i&&r?St(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(m){console.error(m),e.setError(m)}return}let c=++t,l=()=>c===t&&(0,p.isAlive)(e);e.setAligning(!0,u),Ue({rpcManager:(0,C.getSession)(e).rpcManager,name:o,args:i,inPlace:a,current:l}).then(m=>{if(l())try{e.settleAlignment(()=>{s(m)})}catch(g){console.error(g),e.setError(g)}},m=>{l()&&(console.error(m),e.settleAlignment(()=>{d(m)}))})}}}}).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=>Ae(o)).join(", ")} exceed the alignment size limit against this ${V(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?j(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(K(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=()=>Y(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:H(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(),J({model:e,structureSeqPos:t,structureSeqEndPos:n}).catch(r=>{console.error(r),e.parentView.setError(r)})}})).actions(e=>({clickAlignmentPosition(t){let n=e.coordinateMapper?.alignmentToStructure(K(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&&ae(s,[{structure:d,entityId:e.mappedEntity?.entityId,labelSeqIds:u}],()=>e.molstarPluginContext===s).catch(c=>{console.error(c)}),i&&a&&de({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)(zt(e,()=>(0,p.isAlive)(e),o=>et(o,(0,C.getSession)(e))))),t&&He(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=Nt(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:()=>Y(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:()=>Ee(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,C.getSession)(e),a=_t({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)}))}})),yn=p.types.snapshotProcessor(Sn,{preProcessor({pdbId:e,uniprotId:t,...n}){let r=Ge({...n,uniprotId:t,pdbId:e});return{...n,url:r,uniprotId:t??(r?U(r):void 0),alignmentImported:n.alignmentImported??n.pairwiseAlignment!==void 0}}}),le=yn;var Kt=T(q());var hn="SuperpositionTransform";async function Wt(e,t){let n=await h(),{QueryContext:r,StateTransforms:o,StructureElement:i,StructureSelection:a,StructureSelectionQueries:s,PluginCommands:d,tmAlign:u}=n,{query:c}=s.trace,l=t.flatMap(y=>{let[M]=y,P=y.flatMap(A=>E(e,n,A)??[]),[w]=P,I=w?.obj?.data;if(!M||!w||!I)return[];let k=a.toLociWithSourceUnits(c(new r(M)));return[{rootCell:w,cells:P,loci:i.Loci.remap(k,I)}]}),[m,...g]=l;if(!m||g.length===0)return;let S=e.state.data.selectQ(y=>y.byValue(m.rootCell).subtree().withTransformer(o.Model.TransformStructureConformation))[0]?.obj?.data.coordinateSystem;for(let{cells:y,loci:M}of g){let{bTransform:P,tmScoreA:w,tmScoreB:I,rmsd:k,alignedLength:A}=u(m.loci,M);for(let rn of y)await bn(n,e,rn,P,S);e.log.info(`TM-align: TM-score=${w.toFixed(4)}/${I.toFixed(4)}, RMSD=${k.toFixed(2)} \xC5, aligned ${A} residues.`)}await new Promise(y=>{requestAnimationFrame(y),setTimeout(y,100)}),await d.Camera.Reset(e)}async function bn({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(m=>m.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}}},l=d?r.state.data.build().to(d).update(c):r.state.data.build().to(o).insert(n.Model.TransformStructureConformation,c,{tags:hn});await r.runTask(r.state.data.updateTree(l))}function Yt(e){let t=!1,n,r=[];function o(){let{molstarPluginContext:i,structures:a}=e,s=a.filter(l=>l.loadedToMolstar).map(l=>l.molstarStructures),d=s.length;i!==n&&(n=i,e.setSuperposedCount(0));let u=e.superposedCount,c=d!==u||s.some((l,m)=>l!==r[m]);i&&!t&&d>=2&&c&&(t=!0,Wt(i,s).catch(x(e,i)).finally(()=>{t=!1,(0,Kt.isAlive)(e)&&(e.molstarPluginContext===i&&e.superposedCount===u&&(r=s,e.setSuperposedCount(d)),o())}))}return o}async function Xt({plugin:e,structures:t,hidden:n}){let r=await h();for(let o of t){let i=E(e,r,o);i&&i.state.isHidden!==n&&r.setSubtreeVisibility(e.state.data,i.transform.ref,n)}}var G=T(q()),Qt=T(te());function Pn(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 me({plugin:e,kind:t,onUpdate:n}){let r=await h(),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?Pn(r,s):void 0)}else n(void 0)});return o=!0,()=>{i.unsubscribe()}}function Zt(e,t){let n=t&&e.interactionPosition(t);return n===void 0?void 0:{...t,structureSeqPos:n}}function Tn(e,t){let n=Zt(e,t);e.setSelectedFeatureId(void 0),n?(e.setHoveredPosition(n),J({model:e,structureSeqPos:n.structureSeqPos}).catch(r=>{console.error(r),e.setViewError(r)})):e.setClickedStructureRanges([])}function en(e){let t=(n,r)=>{let o;(0,G.addDisposer)(e,()=>{o?.()}),(0,G.addDisposer)(e,(0,Qt.autorun)(()=>{let{molstarPluginContext:i}=e;o?.(),o=void 0,i&&me({plugin:i,kind:n,onUpdate:r}).then(a=>{(0,G.isAlive)(e)&&e.molstarPluginContext===i?o=a:a()},x(e,i))}))};t("click",n=>{for(let r of e.structures)Tn(r,n)}),t("hover",n=>{for(let r of e.structures)r.setHoveredPosition(Zt(r,n))})}var En=100,Cn=(0,ge.lazy)(()=>import("./AddStructureDialog-C4AV64MD.js")),An=(0,ge.lazy)(()=>import("./ManualAlignmentDialog-A6M3SJGN.js")),kn=[{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"}],xn=[["showHighlight","Highlight aligned residues"],["zoomToBaseLevel","Zoom to base level on click"]];function vn(){return f.types.compose("ProteinView",tn.BaseViewModel,f.types.model({id:nn.ElementId,type:f.types.literal("ProteinView"),structures:f.types.array(le),showControls:!1,height:f.types.optional(f.types.number,650),showHighlight:!1,zoomToBaseLevel:!0,autoScrollAlignment:!1,color:f.types.optional(f.types.frozen(),{}),showAlignment:!0,showProteinTracks:!0,compactTracks:!0,trackHeight:f.types.maybe(f.types.number),showAllFeatureTracks:!1,alignmentStructureIndex:f.types.maybe(f.types.number),alignmentAlgorithm:f.types.optional(f.types.enumeration("AlignmentAlgorithm",he),ye)})).preProcessSnapshot(({colorScheme:e,...t})=>Vt({...t,displayName:t.displayName??Je(t.structures??[]),color:ee(t.color??(e===void 0?{}:mt(e)))},ue())).volatile(()=>({error:void 0,molstarPluginContext:void 0,superposedCount:0})).actions(e=>({setHeight(t){e.height=Math.max(t,En)},resizeTracks(t){e.trackHeight=Math.min(40,Math.max(2,F(e)+t))},setError(t){e.error=t},setColor(t){e.color=ee(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(le.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&&z({plugin:n,molstarStructure:r}).catch(x(e,n))}})).views(e=>({get tracksCompact(){return F(e)<12}})).actions(e=>({toggleSetting(t){let n=t==="compactTracks"?!e.tracksCompact:!e[t];e[t]=n,t==="compactTracks"&&(e.trackHeight=void 0),Ht(t,n)},toggleBehavior(t){e[t]=!e[t]}})).actions(e=>({afterAttach(){(0,f.addDisposer)(e,(0,v.autorun)(()=>{let{molstarPluginContext:t,color:n}=e,r=e.structures.flatMap(o=>o.entities?o.molstarStructures.map(i=>({molstarStructure:i,entityId:o.mappedEntity?.entityId,placedValues:o.placedValues,placedSites:o.alignmentDomainStatus?.placedSites,domainColor:o.alignmentDomainStatus?.domains?.color})):[]);t&&r.length>0&&It({plugin:t,color:n,structures:r}).catch(x(e,t))})),(0,f.addDisposer)(e,(0,v.autorun)(()=>{let t=e.molstarPluginContext,n=e.structures.flatMap(r=>r.entities?r.molstarStructures.map(o=>({molstarStructure:o,sites:r.alignmentDomainStatus?.placedSites,color:r.alignmentDomainStatus?.domains?.color})):[]);t&&n.length>0&&Pt({plugin:t,structures:n}).catch(x(e,t))})),(0,f.addDisposer)(e,(0,v.autorun)(()=>{let t=e.molstarPluginContext,n=e.structures.flatMap(r=>r.entities?r.molstarStructures.map(o=>({molstarStructure:o,marks:r.sessionHighlightMarks})):[]);t&&n.length>0&&vt({plugin:t,structures:n}).catch(x(e,t))})),(0,f.addDisposer)(e,(0,v.autorun)(()=>{let t=e.molstarPluginContext;for(let n of e.structures){let{hidden:r,molstarStructures:o}=n;t&&o.length>0&&Xt({plugin:t,structures:o,hidden:r}).catch(x(e,t))}})),(0,f.addDisposer)(e,(0,v.autorun)(Ft(e))),(0,f.addDisposer)(e,(0,v.autorun)(Yt(e))),(0,f.addDisposer)(e,(0,v.autorun)(At(e))),(0,f.addDisposer)(e,(0,v.autorun)(se(e,"select"))),(0,f.addDisposer)(e,(0,v.autorun)(se(e,"highlight"))),en(e)}})).views(e=>({get primaryStructure(){return e.structures[0]},get showLoading(){return Rt(e)},get settled(){return ie(e)},get loadingMessages(){return e.structures.flatMap(t=>t.loadingMessage===void 0?[]:[{id:(0,f.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?Et({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?st(t):void 0},get displayToggles(){return kn.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 xn.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,pe.getSession)(e).queueDialog(t=>[Cn,{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,pe.getSession)(e).queueDialog(t=>[An,{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 Lo=vn;export{Lo as default};
2
+ //# sourceMappingURL=model-V2G4S6EP.js.map