@apollo-annotation/jbrowse-plugin-apollo 0.3.6 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.esm.js +2679 -850
- package/dist/index.esm.js.map +1 -1
- package/dist/jbrowse-plugin-apollo.cjs.development.js +2676 -847
- package/dist/jbrowse-plugin-apollo.cjs.development.js.map +1 -1
- package/dist/jbrowse-plugin-apollo.cjs.production.min.js +1 -1
- package/dist/jbrowse-plugin-apollo.cjs.production.min.js.map +1 -1
- package/dist/jbrowse-plugin-apollo.umd.development.js +5194 -1258
- package/dist/jbrowse-plugin-apollo.umd.development.js.map +1 -1
- package/dist/jbrowse-plugin-apollo.umd.production.min.js +1 -1
- package/dist/jbrowse-plugin-apollo.umd.production.min.js.map +1 -1
- package/package.json +4 -4
- package/src/ApolloInternetAccount/addMenuItems.ts +18 -0
- package/src/ChangeManager.ts +10 -6
- package/src/FeatureDetailsWidget/Attributes.tsx +8 -3
- package/src/FeatureDetailsWidget/TranscriptSequence.tsx +12 -20
- package/src/FeatureDetailsWidget/TranscriptWidgetEditLocation.tsx +929 -175
- package/src/FeatureDetailsWidget/TranscriptWidgetSummary.tsx +4 -0
- package/src/LinearApolloDisplay/components/LinearApolloDisplay.tsx +1 -1
- package/src/LinearApolloDisplay/glyphs/BoxGlyph.ts +48 -60
- package/src/LinearApolloDisplay/glyphs/GeneGlyph.ts +244 -51
- package/src/LinearApolloDisplay/glyphs/GenericChildGlyph.ts +46 -1
- package/src/LinearApolloDisplay/glyphs/Glyph.ts +9 -1
- package/src/LinearApolloDisplay/stateModel/base.ts +29 -0
- package/src/LinearApolloDisplay/stateModel/mouseEvents.ts +51 -35
- package/src/LinearApolloDisplay/stateModel/rendering.ts +2 -1
- package/src/LinearApolloSixFrameDisplay/components/LinearApolloSixFrameDisplay.tsx +7 -2
- package/src/LinearApolloSixFrameDisplay/components/TrackLines.tsx +12 -20
- package/src/LinearApolloSixFrameDisplay/glyphs/GeneGlyph.ts +243 -124
- package/src/LinearApolloSixFrameDisplay/stateModel/base.ts +42 -1
- package/src/LinearApolloSixFrameDisplay/stateModel/layouts.ts +19 -3
- package/src/LinearApolloSixFrameDisplay/stateModel/mouseEvents.ts +53 -34
- package/src/LinearApolloSixFrameDisplay/stateModel/rendering.ts +4 -2
- package/src/OntologyManager/index.ts +4 -1
- package/src/TabularEditor/HybridGrid/Feature.tsx +4 -0
- package/src/TabularEditor/HybridGrid/featureContextMenuItems.ts +108 -16
- package/src/components/AddAssemblyAliases.tsx +114 -0
- package/src/components/AddChildFeature.tsx +3 -6
- package/src/components/AddFeature.tsx +14 -15
- package/src/components/CopyFeature.tsx +2 -4
- package/src/components/CreateApolloAnnotation.tsx +334 -151
- package/src/components/DeleteFeature.tsx +358 -11
- package/src/components/DownloadGFF3.tsx +20 -1
- package/src/components/FilterTranscripts.tsx +86 -0
- package/src/components/MergeExons.tsx +193 -0
- package/src/components/MergeTranscripts.tsx +185 -0
- package/src/components/SplitExon.tsx +134 -0
- package/src/components/index.ts +3 -0
- package/src/config.ts +5 -0
- package/src/extensions/annotationFromJBrowseFeature.ts +2 -0
- package/src/extensions/annotationFromPileup.ts +99 -89
- package/src/session/session.ts +26 -13
- package/src/util/annotationFeatureUtils.ts +65 -0
- package/src/util/copyToClipboard.ts +21 -0
- package/src/util/glyphUtils.ts +49 -0
- package/src/util/index.ts +2 -0
- package/src/util/mouseEventsUtils.ts +113 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@apollo-annotation/common"),t=require("@apollo-annotation/shared"),n=require("@jbrowse/core/Plugin"),a=require("@jbrowse/core/configuration"),o=require("@jbrowse/core/pluggableElementTypes"),r=require("@jbrowse/core/util"),l=require("@mui/icons-material/Add"),s=require("mobx"),i=require("mobx-state-tree"),c=require("socket.io-client"),u=require("@gmod/gff"),d=require("@mui/icons-material/Info"),f=require("@mui/icons-material/Link"),m=require("@mui/icons-material/RadioButtonChecked"),g=require("@mui/icons-material/RadioButtonUnchecked"),p=require("@mui/material"),h=require("bson-objectid"),y=require("react"),b=require("tss-react/mui"),S=require("@jbrowse/core/ui"),w=require("@mui/icons-material/Close"),v=require("mobx-react"),E=require("@jbrowse/core/util/types/mst"),C=require("idb/with-async-ittr"),x=require("@jbrowse/core/util/aborting"),T=require("jsonpath"),A=require("@jbrowse/core/util/io"),N=require("fast-deep-equal/es6"),F=require("file-saver"),k=require("@mui/material/Checkbox"),D=require("@mui/material/FormControlLabel"),R=require("@mui/material/LinearProgress"),M=require("@mui/icons-material/Delete"),I=require("@mui/x-data-grid"),P=require("nanoid"),q=require("@mui/icons-material/AccountCircle"),L=require("@jbrowse/core/pluggableElementTypes/AdapterType"),B=require("@jbrowse/core/data_adapters/BaseAdapter"),O=require("@jbrowse/core/util/rxjs"),_=require("@jbrowse/core/util/simpleFeature"),U=require("@jbrowse/core/TextSearch/BaseResults"),$=require("@mui/icons-material/ExpandMore"),j=require("@mui/icons-material/Edit"),G=require("@mui/icons-material/MoreHoriz"),W=require("@mui/icons-material/AddBox"),H=require("@apollo-annotation/mst"),z=require("@emotion/styled"),J=require("@mui/icons-material/ContentCopy"),V=require("@mui/icons-material/ContentCut"),X=require("@mui/icons-material/Remove"),K=require("@mui/icons-material/Clear"),Y=require("@mui/icons-material/UnfoldLess"),Z=require("@jbrowse/core/util/tracks"),Q=require("@mui/icons-material/ExpandLess"),ee=require("@mui/icons-material/Error"),te=require("@mui/icons-material/Save");function ne(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var ae=ne(n),oe=ne(l),re=ne(u),le=ne(d),se=ne(f),ie=ne(m),ce=ne(g),ue=ne(h),de=ne(y),fe=ne(w),me=ne(T),ge=ne(N),pe=ne(k),he=ne(D),ye=ne(R),be=ne(M),Se=ne(q),we=ne(L),ve=ne(_),Ee=ne(U),Ce=ne($),xe=ne(j),Te=ne(G),Ae=ne(W),Ne=ne(z),Fe=ne(J),ke=ne(V),De=ne(X),Re=ne(K),Me=ne(Y),Ie=ne(Q),Pe=ne(ee),qe=ne(te);const Le=a.ConfigurationSchema("ApolloInternetAccount",{baseURL:{description:"Location of Apollo server",type:"string",defaultValue:""},tokenType:{description:"A custom name for a token to include in the header",type:"string",defaultValue:"Bearer"}},{baseConfiguration:o.BaseInternetAccountConfig,explicitlyTyped:!0});async function Be(e,n,a){const o=re.default.parseStringSync(n,{parseSequences:!0,parseComments:!0,parseDirectives:!1,parseFeatures:!0});if(0===o.length)throw new Error("No features found in GFF3 file");let r=0,l=a.assemblies.get(e);l||(l=a.addAssembly(e,"InMemoryFileDriver"));for(const e of o)if(Array.isArray(e)){const n=t.gff3ToAnnotationFeature(e),a=l.refSeqs.get(n.refSeq)??l.addRefSeq(n.refSeq,n.refSeq);a.features.has(n._id)||a.addFeature(n)}else if("comment"in e)l.addComment(e.comment);else{r++;let t=l.refSeqs.get(e.id);t||(t=l.addRefSeq(e.id,e.id,e.description)),e.description&&!t.description&&t.setDescription(e.description),t.addSequence({start:0,stop:e.sequence.length,sequence:e.sequence})}if(0===r)throw new Error("No embedded FASTA section found in GFF3");const s=await Oe(l);return a.addCheckResults(s),l}async function Oe(t){const n=[];for(const a of t.refSeqs.values())for(const t of a.features.values())for(const o of e.checkRegistry.getChecks().values()){const e=await o.checkFeature(i.getSnapshot(t),((e,t)=>Promise.resolve(a.getSequence(e,t))));n.push(...e)}return n}function _e(e){const{attributes:t}=e,n=t.get("gff_name");return n?n[0]:""}function Ue(e){const{attributes:t}=e,n=t.get("gff_id"),a=t.get("transcript_id"),o=t.get("exon_id"),r=t.get("protein_id");return n?n[0]:a?a[0]:o?o[0]:r?r[0]:""}function $e(e){const t=_e(e),n=Ue(e);return t?`: ${t}`:n?`: ${n}`:""}async function je(e,t){let n;try{n=await e.text()}catch{n=""}return`${t?`${t} — `:""}${e.status} ${e.statusText}${n?` (${n})`:""}`}const Ge=b.makeStyles()((e=>({dialogTitle:{background:e.palette.primary.main,color:e.palette.primary.contrastText,padding:e.spacing(2)},closeButton:{position:"absolute",right:e.spacing(1),top:e.spacing(1.5),color:e.palette.primary.contrastText}}))),We=v.observer((function(e){const{classes:t}=Ge(),{handleClose:n,title:a,...o}=e;return de.default.createElement(S.Dialog,{...o,header:de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogTitle,{className:t.dialogTitle},a),de.default.createElement(p.IconButton,{"aria-label":"close",onClick:n,className:t.closeButton},de.default.createElement(fe.default,null)))})}));var He;!function(e){e.GFF3="text/x-gff3",e.FASTA="text/x-fasta",e.BGZIP_FASTA="application/x-bgzip-fasta",e.FAI="text/x-fai",e.GZI="application/x-gzi",e.EXTERNAL="text/x-external"}(He||(He={}));const ze=b.makeStyles()((e=>({accordion:{border:`1px solid ${e.palette.divider}`,"&:not(:last-child)":{borderBottom:0}},accordionSummary:{flexDirection:"row-reverse"},accordionDetails:{padding:e.spacing(2),borderTop:"1px solid rgba(0, 0, 0, .125)"},radioIcon:{color:e?.palette?.tertiary?.contrastText},dialog:{minWidth:550,maxWidth:800}})));function Je(e,t,n,a,o,r,l,s,i){return!(!e||!(t&&a||n===He.GFF3&&a||a&&o&&r||l&&s&&i))}function Ve({changeManager:e,handleClose:n,session:o}){const{classes:r}=ze(),{internetAccounts:l}=i.getRoot(o),{notify:s}=o,c=l.filter((e=>"ApolloInternetAccount"===e.type));if(0===c.length)throw new Error("No Apollo internet account found");const[u,d]=y.useState(""),[f,m]=y.useState(""),[g,h]=y.useState(!1),[b,S]=y.useState(He.BGZIP_FASTA),[w,v]=y.useState(!0),[E,C]=y.useState(!1),[x,T]=y.useState(!1),[A,N]=y.useState(null),[F,k]=y.useState(null),[D,R]=y.useState(null),[M,I]=y.useState(""),[P,q]=y.useState(""),[L,B]=y.useState(""),[O,_]=y.useState(!1),[U,$]=y.useState(!1);async function j(e,t){const{jobsManager:n}=o,a=new AbortController,[{baseURL:r,getFetcher:l}]=c,s=new URL("files",r);s.searchParams.set("type",t);const i=s.href,d=new FormData;let f=e.name;t===He.FAI||t===He.GZI?f=`${f}.txt`:U&&!e.name.toLocaleLowerCase().endsWith(".gz")?f=`${f}.gz`:!U&&e.name.toLocaleLowerCase().endsWith(".gz")&&(f=`${f}.txt`),d.append("file",e,f),d.append("type",t);const g=l({locationType:"UriLocation",uri:i});if(g){const t={name:`UploadAssemblyFile for ${u}`,statusMessage:"Pre-validating",progressPct:0,cancelCallback:()=>{a.abort(),n.abortJob(t.name)}};n.runJob(t),n.update(t.name,`Uploading ${e.name}, this may take awhile`);const{signal:o}=a,r=await g(i,{method:"POST",body:d,signal:o});if(!r.ok){const e=await je(r,"Error when inserting new assembly (while uploading file)");return n.abortJob(t.name,e),m(e),""}const l=(await r.json())._id;return n.done(t),l}throw new Error("Failed to fetch")}y.useEffect((()=>{q(M?`${M}.fai`:"")}),[M]),y.useEffect((()=>{B(M?`${M}.gzi`:"")}),[M]),y.useEffect((()=>{$(!E&&b!==He.GFF3||!!A?.name.toLocaleLowerCase().endsWith(".gz"))}),[A,E,b]);let G=!1;try{const e=new URL(M);"http:"!==e.protocol&&"https:"!==e.protocol||(G=!0)}catch{}let W=!1;try{const e=new URL(P);"http:"!==e.protocol&&"https:"!==e.protocol||(W=!0)}catch{}let H=!1;try{const e=new URL(L);"http:"!==e.protocol&&"https:"!==e.protocol||(H=!0)}catch{}const[z,J]=de.default.useState("panelFastaInput"),V=e=>(t,n)=>{n&&J(e),$("panelGffInput"!==e)};return de.default.createElement(We,{open:!0,handleClose:n,"data-testid":"add-assembly-dialog",title:"Add new assembly",maxWidth:!1},de.default.createElement("form",{onSubmit:async function(a){let o;if(a.preventDefault(),m(""),T(!0),_(!0),s(`Assembly "${u}" is being added`,"info"),n(),a.preventDefault(),b===He.EXTERNAL)o=new t.AddAssemblyFromExternalChange({typeName:"AddAssemblyFromExternalChange",assembly:(new ue.default).toHexString(),assemblyName:u,externalLocation:{fa:M,fai:P,gzi:L}});else{if(!A)throw new Error("Missing fasta file");if(b===He.GFF3&&w){const e=await j(A,He.GFF3);o=new t.AddAssemblyAndFeaturesFromFileChange({typeName:"AddAssemblyAndFeaturesFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e}})}else if(b===He.GFF3){const e=await j(A,He.GFF3);o=new t.AddAssemblyFromFileChange({typeName:"AddAssemblyFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e}})}else if(E){const e=await j(A,He.FASTA);o=new t.AddAssemblyFromFileChange({typeName:"AddAssemblyFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e}})}else{if(!F||!D)throw new Error("Missing fasta index files");const e=await j(A,He.BGZIP_FASTA),n=await j(F,He.FAI),a=await j(D,He.GZI);o=new t.AddAssemblyFromFileChange({typeName:"AddAssemblyFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e,fai:n,gzi:a}})}}const[{internetAccountId:r}]=c;await e.submit(o,{internetAccountId:r,updateJobsManager:!0}),T(!1),_(!1)},"data-testid":"submit-form"},de.default.createElement(p.DialogContent,{className:r.dialog},O?de.default.createElement(p.LinearProgress,null):null,de.default.createElement(p.TextField,{margin:"dense",id:"name",label:"Assembly name",type:"TextField",fullWidth:!0,variant:"outlined",onChange:e=>{T(!1),d(e.target.value),function(e){const{assemblies:t}=o;t.find((t=>a.readConfObject(t,"displayName")===e))?(h(!1),m(`Assembly ${e} already exists.`)):(h(!0),m(""))}(e.target.value)},disabled:x&&!f}),de.default.createElement(p.Accordion,{disableGutters:!0,elevation:0,square:!0,className:r.accordion,expanded:"panelFastaInput"===z,onChange:V("panelFastaInput")},de.default.createElement(p.AccordionSummary,{className:r.accordionSummary,expandIcon:"panelFastaInput"===z?de.default.createElement(ie.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",ml:5}}):de.default.createElement(ce.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",mr:5}}),"aria-controls":"panelFastaInputd-content",id:"panelFastaInputd-header"},de.default.createElement(p.Typography,{component:"span"},"FASTA input")),de.default.createElement(p.AccordionDetails,{className:r.accordionDetails},de.default.createElement(p.FormGroup,null,de.default.createElement(p.FormControlLabel,{"data-testid":"files-on-url-checkbox",control:de.default.createElement(p.Checkbox,{onChange:()=>{S(b===He.EXTERNAL?He.BGZIP_FASTA:He.EXTERNAL),b===He.EXTERNAL&&C(!1)},checked:b===He.EXTERNAL,disabled:E&&b!==He.GFF3}),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Use external URLs",de.default.createElement(p.Tooltip,{title:"Use external URLs to provide FASTA and index files. Does not copy the files to the Apollo collaboration server, so ensure the URLs are stable.",placement:"top-start"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{"data-testid":"sequence-is-editable-checkbox",control:de.default.createElement(p.Checkbox,{onChange:()=>{C(!E)}}),checked:E,disabled:b===He.EXTERNAL,label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Store sequence in database",de.default.createElement(p.Tooltip,{title:"Enables users to edit the genomic sequence, but comes with performance impacts. Use with care.",placement:"top-start"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{"data-testid":"fasta-is-gzip-checkbox",control:de.default.createElement(p.Checkbox,{checked:U,onChange:()=>{$(!E||!U)},disabled:!E}),label:"FASTA is gzip compressed"}),de.default.createElement(p.Table,{size:"small",sx:{mt:2}},b===He.BGZIP_FASTA||b===He.GFF3?de.default.createElement(p.TableBody,null,de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.Box,{display:"flex",alignItems:"center"},de.default.createElement("span",null,"FASTA"),de.default.createElement(p.Tooltip,{title:'Unless "Store sequence in database" enabled, FASTA input must be compressed with bgzip and indexed with samtools faidx (or equivalent). Compression is optional for sequences stored in the database.'},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement("input",{"data-testid":"fasta-input-file",type:"file",onChange:e=>{N(e.target.files?.item(0)??null)},disabled:x&&!f}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA index (.fai)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement("input",{"data-testid":"fai-input-file",type:"file",onChange:e=>{k(e.target.files?.item(0)??null)},disabled:x&&!f||E}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA binary index (.gzi)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement("input",{"data-testid":"gzi-input-file",type:"file",onChange:e=>{R(e.target.files?.item(0)??null)},disabled:x&&!f||E})))):de.default.createElement(p.TableBody,null,de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.Box,{display:"flex",alignItems:"center"},de.default.createElement("span",null,"FASTA"),de.default.createElement(p.Tooltip,{title:"Remote FASTA input must be compressed with bgzip and indexed with samtools faidx (or equivalent)"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.TextField,{"data-testid":"fasta-input-url",variant:"outlined",value:M,error:!G,onChange:e=>{I(e.target.value)},disabled:x&&!f,slotProps:{input:{startAdornment:de.default.createElement(p.InputAdornment,{position:"start"},de.default.createElement(se.default,null))}}}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA index (.fai)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.TextField,{"data-testid":"fai-input-url",variant:"outlined",value:P,error:!W,onChange:e=>{q(e.target.value)},disabled:x&&!f,slotProps:{input:{startAdornment:de.default.createElement(p.InputAdornment,{position:"start"},de.default.createElement(se.default,null))}}}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA binary index (.gzi)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.TextField,{"data-testid":"gzi-input-url",variant:"outlined",value:L,error:!H,onChange:e=>{B(e.target.value)},disabled:x&&!f,slotProps:{input:{startAdornment:de.default.createElement(p.InputAdornment,{position:"start"},de.default.createElement(se.default,null))}}})))))))),de.default.createElement(p.Accordion,{disableGutters:!0,elevation:0,square:!0,className:r.accordion,expanded:"panelGffInput"===z,onChange:V("panelGffInput")},de.default.createElement(p.AccordionSummary,{className:r.accordionSummary,expandIcon:"panelGffInput"===z?de.default.createElement(ie.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",ml:5}}):de.default.createElement(ce.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",mr:5}}),"aria-controls":"panelGffInputd-content"},de.default.createElement(p.Typography,{component:"span"},"GFF3 input",de.default.createElement(p.Tooltip,{title:"GFF3 must includes FASTA sequences. File can be gzip compressed."},de.default.createElement(le.default,{className:r.radioIcon,sx:{fontSize:18}})))),de.default.createElement(p.AccordionDetails,{className:r.accordionDetails},de.default.createElement(p.Box,{style:{marginTop:20}},de.default.createElement("input",{"data-testid":"gff3-input-file",type:"file",disabled:x&&!f,onChange:e=>{N(e.target.files?.item(0)??null),S(He.GFF3)}}),de.default.createElement(p.FormGroup,{style:{display:"grid"}},de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{checked:w,onChange:()=>{v(!w)},disabled:x&&!f}),label:"Load features from GFF3 file"}),de.default.createElement(p.FormControlLabel,{"data-testid":"gff3-is-gzip-checkbox",control:de.default.createElement(p.Checkbox,{checked:U,onChange:()=>{$(!U)},disabled:x&&!f}),label:"GFF3 is gzip compressed"})))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!Je(g,E,b,A,F,D,G,W,H)||x,variant:"contained",type:"submit","data-testid":"submit-button"},x?"Submitting...":"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),f?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},f)):null)}const Xe=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now","0","1","2","3","4","5","6","7","8","9"]);function Ke(e,t){for(const[n,a]of t.entries())if(e.startsWith(a))return e.replace(a,String(n));return e}const Ye="$PREFIXED_ID";function Ze(e,t,n){return t===Ye?[Ke(e.id,n)]:me.default.query(e,t)}function Qe(e){return e.toLowerCase().split(/[^\d:A-Za-z]+/).filter((e=>e&&!Xe.has(e)))}function*et(e){for(const t of e)yield*Qe(t)}function*tt(e){for(const t of e)if("string"==typeof t)yield t;else if("object"==typeof t){const e=me.default.query(t,"$..*");yield*tt(e)}}function*nt(e,t,n){for(const a of t){const t=Ze(e,a,n);if(t.length>0)for(const e of et(tt(t)))yield[a,e]}}async function at(e,t,n){const a=await this.db,o=t??a.transaction(["nodes"]);x.checkAbortSignal(n);const r=[...Qe(e)],l=[],s=new Map;l.push(...r.map((async(e,t)=>{x.checkAbortSignal(n);const a=o.objectStore("nodes").index("full-text-words");for await(const o of a.iterate(IDBKeyRange.bound(e,`${e}`,!1,!1))){x.checkAbortSignal(n);const e=o.value,a=s.get(e.id)??[e,new Set];a[1].add(t),s.set(e.id,a)}}))),await Promise.all(l),x.checkAbortSignal(n);const i=[];for(const[,[e,t]]of s)x.checkAbortSignal(n),i.push(...ot(this.textIndexFields,e,t,r,this.prefixes));return i.sort(((e,t)=>t.score-e.score)),i.slice(0,this.options.maxSearchResults??this.DEFAULT_MAX_SEARCH_RESULTS)}function ot(e,t,n,a,o){const r=[...n].sort().map((e=>a[e])),l=r.map((e=>{const t=e.replaceAll(/[$()*+./?[\\\]^{|}-]/g,String.raw`\$&`);return new RegExp(`\\b${t}`,"gi")}));let s=[],i=0;for(const[n,r]of e.entries()){const c=new Set,u=e.length-n-1,d=[...tt(Ze(t,r.jsonPath,o))];for(const e of d){let n=0;const o=[];for(const[t,r]of l.entries())for(const l of e.matchAll(r)){n+=1+1*u,c.add(t);const r=l.index,s=a[t];void 0!==r&&(n+=.01*s.length,n+=s.length/e.length*100*.05,o.push({wordIndex:t,position:r}))}n+=100*c.size,i<n&&(i=n),o.sort(((e,t)=>e.position-t.position)),o.length>0&&s.push({term:t,field:r,str:e,score:n,wordMatches:o})}}s=s.filter((e=>e.score===i));for(const e of s){const{wordMatches:t}=e;for(let n=0;n<t.length-1;n++){const a=t[n],o=t[n+1],l=o.wordIndex-a.wordIndex;if(1===l||-1===l){e.score+=1,1===l&&(e.score+=1);const t=Math.abs(o.position-(a.position+r[a.wordIndex].length))-1;e.score-=.05*t}}}return s}function rt(e){return"string"==typeof e.id}function lt(e){return"string"==typeof e.sub&&"string"==typeof e.pred&&"string"==typeof e.obj}function st(e){return Boolean(e.meta?.deprecated)}async function it(e){return C.openDB(e,2,{upgrade(e,t,n,a,o){if(t<2&&(e.objectStoreNames.contains("meta")&&e.deleteObjectStore("meta"),e.objectStoreNames.contains("nodes")&&e.deleteObjectStore("nodes"),e.objectStoreNames.contains("edges")&&e.deleteObjectStore("edges")),e.objectStoreNames.contains("meta")||e.createObjectStore("meta"),!e.objectStoreNames.contains("nodes")){e.createObjectStore("nodes",{keyPath:"id"});const t=a.objectStore("nodes");t.createIndex("by-label","lbl"),t.createIndex("by-type","type"),t.createIndex("by-synonym",["meta","synonyms","val"]),t.createIndex("full-text-words","fullTextWords",{multiEntry:!0})}if(!e.objectStoreNames.contains("edges")){e.createObjectStore("edges",{autoIncrement:!0});const t=a.objectStore("edges");t.createIndex("by-subject","sub"),t.createIndex("by-object","obj"),t.createIndex("by-predicate","pred")}}})}function ct(e){const t=new Set;for(const[,n]of e)t.add(n);return[...t]}async function ut(e){const t=Date.now();let n,a=1;this.options.update?.("Parsing JSON",a);try{n=JSON.parse(await A.openLocation(this.sourceLocation).readFile("utf8"))}catch{throw new Error("Error in loading ontology")}a+=5,this.options.update?.("Parsing JSON complete",a);const o=Date.now(),[r,...l]=n.graphs??[];if(r){if(l.length>0)throw new Error("multiple graphs not supported");try{const n=e.transaction(["meta","nodes","edges"],"readwrite");await n.objectStore("meta").clear(),await n.objectStore("nodes").clear(),await n.objectStore("edges").clear();const l=n.objectStore("nodes"),s=dt.call(this).map((e=>e.jsonPath));if(r.nodes){let e=Math.round(a);for(const[,t]of r.nodes.entries())a+=1/r.nodes.length*64,Math.round(a)!=e&&a<100&&(this.options.update?.("Processing nodes",a),e=Math.round(a)),rt(t)&&await l.add({...t,fullTextWords:ct(nt(t,s,this.prefixes))})}const i=n.objectStore("edges");if(r.edges){let e=Math.round(a);for(const[,t]of r.edges.entries())a+=1/r.edges.length*30,Math.round(a)!=e&&a<100&&(this.options.update?.("Processing edges",a),e=Math.round(a)),lt(t)&&await i.add(t)}await n.done;const c=e.transaction("meta","readwrite"),{update:u,...d}=this.options;await c.objectStore("meta").add({ontologyRecord:{name:this.ontologyName,version:this.ontologyVersion,sourceLocation:this.sourceLocation},storeOptions:d,graphMeta:r.meta,timestamp:String(new Date),schemaVersion:2,timings:{overall:Date.now()-t,load:Date.now()-o}},"meta"),await c.done}catch(t){throw await e.transaction("meta","readwrite").objectStore("meta").clear(),t}}}function dt(){return[{displayName:"ID",jsonPath:Ye},...this.options.textIndexing?.indexFields??ht]}async function ft(e){const[t]=await e.transaction("meta").objectStore("meta").getAll();return!!t&&ge.default(this.options.prefixes,t.storeOptions.prefixes)&&ge.default(this.options.textIndexing,t.storeOptions.textIndexing)}class mt{ontologyName;ontologyVersion;sourceLocation;db;options;loadOboGraphJson=ut;getTermsByFulltext=at;openDatabase=it;isDatabaseCurrent=ft;get textIndexFields(){return dt.call(this)}get prefixes(){return this.options.prefixes??new Map}DEFAULT_MAX_SEARCH_RESULTS=100;constructor(e,t,n,a){this.ontologyName=e,this.ontologyVersion=t,this.sourceLocation=n,this.options=a??{},this.db=this.prepareDatabase()}validate(){const e=[],{sourceLocation:t,sourceType:n}=this;return n?"obo-graph-json"!==n&&e.push(new Error(`ontology source file ${JSON.stringify(t)} has type ${n}, which is not yet supported`)):e.push(new Error(`unable to determine format of ontology source file ${JSON.stringify(t)}, file name must end with ".json", ".obo", or ".owl"`)),e}get sourceType(){if(r.isUriLocation(this.sourceLocation)){if(this.sourceLocation.uri.endsWith(".json"))return"obo-graph-json"}else if(r.isLocalPathLocation(this.sourceLocation)&&this.sourceLocation.localPath.endsWith(".json"))return"obo-graph-json"}get dbName(){return`Apollo Ontology "${this.ontologyName}" "${this.ontologyVersion}"`}async prepareDatabase(){const e=this.validate();if(e.length>0)throw e;const t=await this.openDatabase(this.dbName);if(await this.isDatabaseCurrent(t))return t;try{const{options:e,sourceLocation:n,sourceType:a}=this;if("obo-graph-json"!==a)throw new Error(`ontology source file ${JSON.stringify(n)} has type ${a}, which is not yet supported`);return e.update?.("",0),await this.loadOboGraphJson(t),e.update?.("",100),t}catch(e){throw t.close(),await C.deleteDB(this.dbName),e}}async termCount(e){const t=await this.db;return(e??t.transaction("nodes")).objectStore("nodes").count()}unique(e){const t=new Map,n=[];for(const a of e)t.has(a.id)||(t.set(a.id,!0),n.push(a));return n}async getTermsWithLabelOrSynonym(e,t,n){const a=t?.includeSubclasses??!0,o=await this.db,r=n??o.transaction(["nodes","edges"]),l=r.objectStore("nodes"),s=[...await l.index("by-label").getAll(e),...await l.index("by-synonym").getAll(e)];if(a){const e=await this.recurseEdges("by-object",s.map((e=>e.id)),(e=>"is_a"===e.pred),"sub",r);for(const t of e){const e=await l.get(t);e&&s.push(e)}}return s}async getPropertiesByLabel(e,t,n){const a=t?.includeSubProperties??!0,o=await this.db,r=n??o.transaction(["nodes","edges"]),l=(await this.getTermsWithLabelOrSynonym(e,{includeSubclasses:!1},r)).filter((e=>St(e)));if(a){const e=await this.recurseEdges("by-object",l.map((e=>e.id)),(e=>"subPropertyOf"===e.pred),"sub",r),t=r.objectStore("nodes");for(const n of e){const e=await t.get(n);e&&St(e)&&l.push(e)}}return l}async recurseEdges(e,t,n,a,o){const r=new Set;return await async function t(l){await Promise.all([...l].map((async l=>{const s=(await o.objectStore("edges").index(e).getAll(l)).filter((e=>n(e))).map((e=>e[a]));if(s.length>0){for(const e of s)r.add(e);await t(s)}})))}(t),r.values()}async*expandNodeSet(e,t="is_a",n,a){const o=await this.db,r=a??o.transaction(["edges"]),l=[...e],s=await this.recurseEdges("subclasses"===n?"by-object":"by-subject",l,(e=>e.pred===t),"subclasses"===n?"sub":"obj",r);for(const e of l)yield e;for(const e of s)yield e}expandSubclasses(e,t="is_a",n){return this.expandNodeSet(e,t,"subclasses",n)}expandSuperclasses(e,t="is_a",n){return this.expandNodeSet(e,t,"superclasses",n)}async getClassesThat(e,t,n){const a=await this.db,o=n??a.transaction(["nodes","edges"]),r=await this.getPropertiesByLabel(e,{includeSubProperties:!0},o),l=new Set(r.map((e=>e.id))),s=await async function(e){const t=[];for await(const n of e)t.push(n);return t}(this.expandSuperclasses(t.map((e=>e.id)),"is_a",o)),i=await this.recurseEdges("by-object",s,(e=>l.has(e.pred)),"sub",o),c=this.expandSubclasses(i,"is_a",o),u=[];for await(const e of c){const t=await o.objectStore("nodes").get(e);t&&bt(t)&&!st(t)&&u.push(t)}return u}async getClassesWithoutPropertyLabeled(e,t,n){const a=await this.db,o=n??a.transaction(["nodes","edges"]),r=o.objectStore("nodes"),l=o.objectStore("edges"),s=(await this.getPropertiesByLabel(e,t,o)).map((e=>e.id)),i=await(async()=>{const e=new Set;for(const t of s)for await(const n of l.index("by-predicate").iterate(t))e.add(n.value.sub);const t=new Set;for await(const n of this.expandSubclasses(e,"is_a",o))t.add(n);return t})(),c=[];for await(const e of r){const t=e.value;bt(t)&&!i.has(t.id)&&c.push(t.id)}const u=[];for(const e of c){const t=await o.objectStore("nodes").get(e);t&&bt(t)&&!st(t)&&u.push(t)}return u}async getAllClasses(e){const t=await this.db,n=e??t.transaction(["nodes"]);return(await n.objectStore("nodes").index("by-type").getAll("CLASS")).filter((e=>!st(e)))}async getAllTerms(e){const t=await this.db,n=e??t.transaction(["nodes"]);return(await n.objectStore("nodes").getAll()).filter((e=>!st(e)))}}const gt=i.types.model("OntologyRecord",{name:i.types.string,version:"unversioned",source:i.types.union(E.LocalPathLocation,E.UriLocation,E.BlobLocation),options:i.types.frozen(),equivalentTypes:i.types.map(i.types.array(i.types.string))}).volatile((e=>({dataStore:void 0,startedEquivalentTypeRequests:new Set}))).actions((e=>({ping(){},initDataStore(){e.dataStore=new mt(e.name,e.version,i.getSnapshot(e.source),e.options)},afterCreate(){i.addDisposer(e,s.autorun((()=>{this.initDataStore()})))},setEquivalentTypes(t,n){e.equivalentTypes.set(t,n)}}))).actions((e=>({loadEquivalentTypes:i.flow((function*(t){if(!e.dataStore)return;if(e.startedEquivalentTypeRequests.has(t))return;e.startedEquivalentTypeRequests.add(t);const n=(yield e.dataStore.getTermsWithLabelOrSynonym(t)).map((e=>e.lbl)).filter((e=>null!=e));e.setEquivalentTypes(t,n)}))}))).actions((e=>({afterCreate(){s.autorun((t=>{e.dataStore&&(e.loadEquivalentTypes("gene"),e.loadEquivalentTypes("pseudogene"),e.loadEquivalentTypes("transcript"),e.loadEquivalentTypes("pseudogenic_transcript"),e.loadEquivalentTypes("CDS"),e.loadEquivalentTypes("mRNA"),t.dispose())}))},setEquivalentTypes(t,n){e.equivalentTypes.set(t,n)}}))).views((e=>({isTypeOf(t,n){if(t===n)return!0;if(!e.dataStore)return!1;const a=e.equivalentTypes.get(n);return a?a.includes(t):(e.loadEquivalentTypes(n),!1)}}))),pt=i.types.model("OntologyManager",{ontologies:i.types.array(gt),prefixes:i.types.optional(i.types.map(i.types.string),{"GO:":"http://purl.obolibrary.org/obo/GO_","SO:":"http://purl.obolibrary.org/obo/SO_"})}).views((e=>({get featureTypeOntologyName(){const t=i.getRoot(e).jbrowse.configuration;return a.readConfObject(t.ApolloPlugin,"featureTypeOntologyName")}}))).views((e=>({get featureTypeOntology(){return this.findOntology(e.featureTypeOntologyName)},findOntology:(t,n)=>e.ontologies.find((e=>e.name===t&&(void 0===n||e.version===n))),openOntology(e,t){return this.findOntology(e,t)?.dataStore},applyPrefixes:t=>Ke(t,e.prefixes),expandPrefixes:t=>function(e,t){for(const[n,a]of t.entries())if(e.startsWith(String(n)))return e.replace(String(n),a);return e}(t,e.prefixes)}))).actions((e=>({addOntology(t,n,a,o){const r=e.ontologies.push({name:t,version:n,source:a,options:{prefixes:new Map(e.prefixes.entries()),...o}});e.ontologies[r-1].ping()}}))),ht=[{displayName:"Label",jsonPath:"$.lbl"},{displayName:"Synonym",jsonPath:"$.meta.synonyms[*].val"},{displayName:"Definition",jsonPath:"$.meta.definition.val"}],yt=a.ConfigurationSchema("OntologyRecord",{name:{type:"string",description:'the full name of the ontology, e.g. "Gene Ontology"',defaultValue:"My Ontology"},version:{type:"string",description:"the ontology's version string",defaultValue:"unversioned"},source:{type:"fileLocation",description:"the download location for the ontology's source file",defaultValue:{locationType:"UriLocation",uri:"http://example.com/myontology.json"}},textIndexFields:{type:"frozen",description:"JSON paths for text fields that will be indexed for text searching",defaultValue:ht}});function bt(e){return"CLASS"===e.type}function St(e){return"PROPERTY"===e.type}async function wt(e,t,n){if(!e)return;const a=await t.getTermsWithLabelOrSynonym(e.type,{includeSubclasses:!1}),o=a.filter(bt);if(0===a.length)return;const r=await t.getClassesThat("part_of",o);return 0!==r.length?r:void 0}function vt({fetchValidTerms:e,filterTerms:t,includeDeprecated:n,onChange:a,ontologyName:o,ontologyVersion:r,renderInput:l,session:s,style:i,value:c}){const[u,d]=y.useState(!1),[f,m]=y.useState(),[g,h]=y.useState(""),[b,S]=y.useState(),{ontologyManager:w}=s.apolloDataStore,v=w.findOntology(o,r)?.dataStore,E=v&&u&&!f,C=v&&!b,T=y.useCallback((e=>(n||!st(e))&&(!t||t(e))),[t,n]);y.useEffect((()=>{u||m(void 0)}),[u]),y.useEffect((()=>{const e=new AbortController,{signal:t}=e;return C&&(h(""),async function(e,t,n,a){if(!t)return;const o=(await e.getTermsWithLabelOrSynonym(t,{includeSubclasses:!1})).find((e=>(n??(()=>!0))(e)));if(!o)throw new Error(`not a valid ${e.ontologyName} term`);return o}(v,c,T).then((e=>{t.aborted||S(e)}),(e=>{t.aborted||x.isAbortException(e)||h(String(e))}))),()=>{e.abort()}}),[s,c,T,v,C]),y.useEffect((()=>{const t=new AbortController,{signal:n}=t;return E&&async function(e,t,n,a){let o;if(t){const n=await t(e,a);n&&(o=n)}return o||(o=await e.getAllTerms()),n?o.filter((e=>n(e))):o}(v,e,T,n).then((e=>{e&&!n.aborted&&m(e)}),(e=>{n.aborted||x.isAbortException(e)||s.notify(e instanceof Error?e.message:String(e),"error")})),()=>{t.abort()}}),[E,T,v,s,e]);const A={};return g&&(A.error=!0,A.helperText=g),de.default.createElement(p.Autocomplete,{style:i,autoComplete:!0,filterSelectedOptions:!0,disableClearable:!0,selectOnFocus:!0,clearOnBlur:!0,handleHomeEndKeys:!0,freeSolo:!0,value:c,options:f??[],onOpen:()=>{d(!0)},onClose:()=>{d(!1)},loading:E,renderInput:l??(e=>de.default.createElement(p.TextField,{...e,...A})),getOptionLabel:e=>"string"==typeof e?e:e.lbl??"",isOptionEqualToValue:(e,t)=>e.lbl===t.lbl,onChange:(e,t)=>{t&&("string"==typeof t?(S(void 0),a(c,t)):t.lbl!==c&&(h(""),S(t),a(c,t.lbl)))}})}function Et({changeManager:e,handleClose:n,session:a,sourceAssemblyId:o,sourceFeature:r}){const{notify:l}=a,[s,i]=y.useState(String(r.max)),[c,u]=y.useState(String(r.min+1)),[d,f]=y.useState(""),[m,g]=y.useState(""),[h,b]=y.useState(""),S=Number(s)<=Number(c);return de.default.createElement(We,{open:!0,title:"Add new child feature",handleClose:n,maxWidth:!1,"data-testid":"add-feature-dialog"},de.default.createElement("form",{onSubmit:async function(a){a.preventDefault(),g("");const i=new t.AddFeatureChange({changedIds:[r._id],typeName:"AddFeatureChange",assembly:o,addedFeature:{_id:(new ue.default).toHexString(),refSeq:r.refSeq,min:Number(c)-1,max:Number(s),type:d},parentFeatureId:r._id});await e.submit(i),l("Feature added successfully","success"),n(),a.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.TextField,{margin:"dense",id:"start",label:"Start",type:"number",fullWidth:!0,variant:"outlined",value:c,onChange:e=>{u(e.target.value)}}),de.default.createElement(p.TextField,{margin:"dense",id:"end",label:"End",type:"number",fullWidth:!0,variant:"outlined",value:s,onChange:e=>{i(e.target.value)},error:S,helperText:S?'"End" must be greater than "Start"':null}),de.default.createElement(vt,{session:a,ontologyName:"Sequence Ontology",style:{width:170},value:d,filterTerms:bt,fetchValidTerms:async function(e,t,n){const a=await wt(e,t);if(a)return a;b(`Type "${e?.type}" does not have any children in the ontology`)}.bind(null,r),renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Type",variant:"outlined",fullWidth:!0,error:Boolean(h),helperText:h}),onChange:(e,t)=>{var n;t&&(n=t,g(""),f(n))}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:S||!(c&&s&&d)},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),m?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},m)):null)}var Ct;function xt(e,t,n,a){const o={_id:(new ue.default).toHexString(),refSeq:e,type:"CDS",min:n,max:a,strand:t},r={_id:(new ue.default).toHexString(),refSeq:e,type:"exon",min:n,max:a,strand:t},l={};return l[o._id]=o,l[r._id]=r,{_id:(new ue.default).toHexString(),refSeq:e,type:"mRNA",min:n,max:a,strand:t,children:l}}function Tt({changeManager:e,handleClose:n,region:a,session:o}){const{notify:r}=o,[l,s]=y.useState(String(a.end)),[i,c]=y.useState(String(a.start+1)),[u,d]=y.useState(Ct.GENE_AND_SUBFEATURES),[f,m]=y.useState(),[g,h]=y.useState(),[b,S]=y.useState(""),w=Number(l)<=Number(i);let v=Boolean(w)||!(i&&l&&u);return u!==Ct.CUSTOM||f||(v=!0),de.default.createElement(We,{open:!0,title:"Add new feature",handleClose:n,maxWidth:!1,"data-testid":"add-feature-dialog"},de.default.createElement("form",{onSubmit:async function(s){let c;s.preventDefault(),S("");for(const[,e]of o.apolloDataStore.assemblies??new Map)if(e._id===a.assemblyName)for(const[,t]of e.refSeqs??new Map)t.name===a.refName&&(c=t._id);if(!c)return void S("Invalid refseq id");if(u===Ct.GENE_AND_SUBFEATURES){const o=xt(c,g,Number(i)-1,Number(l)),s={};s[o._id]=o;const u=(new ue.default).toHexString(),d=new t.AddFeatureChange({changedIds:[u],typeName:"AddFeatureChange",assembly:a.assemblyName,addedFeature:{_id:u,refSeq:c,min:Number(i)-1,max:Number(l),type:"gene",strand:g,children:s}});return await e.submit(d),r("Feature added successfully","success"),void n()}if(u===Ct.TRANSCRIPT_AND_SUBFEATURES){const o=xt(c,g,Number(i)-1,Number(l)),s=new t.AddFeatureChange({changedIds:[o._id],typeName:"AddFeatureChange",assembly:a.assemblyName,addedFeature:o});return await e.submit(s),r("Feature added successfully","success"),void n()}if(!f)return void S("No type selected");const d=(new ue.default).toHexString(),m=new t.AddFeatureChange({changedIds:[d],typeName:"AddFeatureChange",assembly:a.assemblyName,addedFeature:{_id:d,refSeq:c,min:Number(i)-1,max:Number(l),type:f,strand:g}});await e.submit(m),r("Feature added successfully","success"),n()},"data-testid":"submit-form"},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.TextField,{margin:"dense",id:"start",label:"Start",type:"number",fullWidth:!0,variant:"outlined",value:Number(i),onChange:e=>{c(e.target.value)}}),de.default.createElement(p.TextField,{margin:"dense",id:"end",label:"End",type:"number",fullWidth:!0,variant:"outlined",value:l,onChange:e=>{s(e.target.value)},error:w,helperText:w?'"End" must be greater than "Start"':null}),de.default.createElement(p.FormControl,null,de.default.createElement(p.InputLabel,{id:"demo-simple-select-label"},"Strand"),de.default.createElement(p.Select,{labelId:"demo-simple-select-label",id:"demo-simple-select",label:"Strand",value:g?.toString(),onChange:function(e){switch(S(""),Number(e.target.value)){case 1:h(1);break;case-1:h(-1);break;default:h(void 0)}}},de.default.createElement(p.MenuItem,{value:void 0}),de.default.createElement(p.MenuItem,{value:1},"+"),de.default.createElement(p.MenuItem,{value:-1},"-"))),de.default.createElement(p.FormControl,{style:{marginTop:20}},de.default.createElement(p.RadioGroup,{"aria-labelledby":"demo-radio-buttons-group-label",defaultValue:Ct.GENE_AND_SUBFEATURES,name:"radio-buttons-group",value:u,onChange:e=>{S("");const{value:t}=e.target;Object.keys(Ct).includes(t)&&d(Ct[t])}},de.default.createElement(p.FormControlLabel,{value:Ct.GENE_AND_SUBFEATURES,control:de.default.createElement(p.Radio,null),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Add gene and sub-features",de.default.createElement(p.Tooltip,{title:"This is a shortcut to create a gene with a single mRNA, exon, and CDS"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{value:Ct.TRANSCRIPT_AND_SUBFEATURES,control:de.default.createElement(p.Radio,null),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Add transcript and sub-features",de.default.createElement(p.Tooltip,{title:"This is a shortcut to create a single mRNA with exon and CDS, but without a parent gene"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{value:Ct.CUSTOM,checked:u!==Ct.GENE_AND_SUBFEATURES&&u!==Ct.TRANSCRIPT_AND_SUBFEATURES,control:de.default.createElement(p.Radio,null),label:"Add feature with a sequence ontology type"}))),u===Ct.CUSTOM?de.default.createElement(vt,{session:o,ontologyName:"Sequence Ontology",style:{width:170},value:"",filterTerms:bt,renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Type",variant:"outlined",fullWidth:!0}),onChange:(e,t)=>{var n;t&&(n=t,S(""),m(n))}}):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:v},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),b?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},b)):null)}function At(e,t){const n=(new ue.default).toHexString();t.push(n);const a={};if(e.children)for(const n of Object.values(e.children)){const e=At(n,t);a[e._id]=e}const o="string"==typeof e.refSeq?e.refSeq:e.refSeq.toHexString();return{...e,refSeq:o,children:e.children&&a,_id:n}}function Nt({changeManager:e,handleClose:n,session:o,sourceAssemblyId:r,sourceFeature:l}){const{assemblyManager:s,notify:c}=o,u=s.assemblyList,[d,f]=y.useState(u.find((e=>e.name!==r))?.name),[m,g]=y.useState([]),[h,b]=y.useState(""),[S,w]=y.useState(l.min),[v,E]=y.useState("");function C(e,t){const n={};if(e.children)for(const a of Object.values(e.children)){const e=C(a,t);e.refSeq=h,e.min=e.min+t,e.max=e.max+t,n[e._id]=e}const a="string"==typeof e.refSeq?e.refSeq:e.refSeq.toHexString(),o="string"==typeof e._id?e._id:e._id.toHexString();return{...e,refSeq:a,children:e.children&&n,_id:o}}return y.useEffect((()=>{b(""),async function(){if(!d)return void E("No assemblies to copy to");const e=await s.waitForAssembly(d);if(!e)return;const{refNameAliases:t}=e;if(!t)return;const n=[...Object.entries(t)].filter((([e,t])=>e!==t)).map((([e,t])=>({_id:e,name:t})));g(n),b(n[0]?._id||"")}().catch((e=>{E(String(e))}))}),[d,s]),de.default.createElement(We,{open:!0,title:"Copy features and annotations",handleClose:n,maxWidth:!1,"data-testid":"copy-feature"},de.default.createElement("form",{onSubmit:async function(a){if(!d)return;a.preventDefault(),E("");const o=l.length,r=await s.waitForAssembly(d);if(!r)return void E(`Assembly not found: ${d}.`);const u=r.getCanonicalRefName(h),f=r.regions?.find((e=>e.refName===u));if(!f)return void E(`RefSeq not found: ${h}.`);const m=S+o;if(m>f.end)return void E(`Feature would extend beyond the bounds of the selected reference sequence. (Feature would end at ${m}, but reference sequence ends at ${f.end})`);if(S<f.start)return void E(`Reference sequence starts at ${f.start}, feature cannot start before that.`);const g=[],p=At(i.getSnapshot(l),g),y={...p.attributes};"Parent"in y&&delete y.Parent,p.refSeq=h;const b=S-p.min;p.min=S,p.max=S+o;const w=C(p,b),v=new t.AddFeatureChange({changedIds:[p._id],typeName:"AddFeatureChange",assembly:d,addedFeature:{_id:p._id,refSeq:p.refSeq,min:p.min,max:p.max,type:p.type,children:w.children,attributes:y,strand:p.strand},copyFeature:!0,allIds:g});await e.submit(v),c("Feature copied successfully","success"),n(),a.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Target assembly"),de.default.createElement(p.Select,{labelId:"label",value:d,onChange:function(e){f(e.target.value)}},u.filter((e=>e.name!==r)).map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},a.readConfObject(e,"displayName"))))),de.default.createElement(p.DialogContentText,null,"Target reference sequence"),de.default.createElement(p.Select,{labelId:"label",value:h,onChange:function(e){b(e.target.value)}},m.map((e=>de.default.createElement(p.MenuItem,{key:e._id,value:e._id},e.name)))),de.default.createElement(p.DialogContentText,null,"Start position in target reference sequence"),de.default.createElement(p.TextField,{margin:"dense",type:"number",fullWidth:!0,variant:"outlined",value:S,onChange:e=>{w(Number(e.target.value))}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!d||!h||!S,variant:"contained",type:"submit"},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),v?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},v)):null)}function Ft({changeManager:e,handleClose:n,session:a}){const{internetAccounts:o}=i.getRoot(a),[r,l]=y.useState(),[s,c]=y.useState(""),[u,d]=y.useState(!1),[f,m]=y.useState(!1),g=o.filter((e=>"ApolloInternetAccount"===e.type));if(0===g.length)throw new Error("No Apollo internet account found");const[h,b]=y.useState(g[0]),{collaborationServerDriver:S}=a.apolloDataStore,w=S.getAssemblies();return y.useEffect((()=>{w.length>0&&void 0===r&&l(w[0])}),[w,r]),de.default.createElement(We,{open:!0,title:"Delete Assembly",handleClose:n,maxWidth:!1,"data-testid":"delete-assembly"},de.default.createElement("form",{onSubmit:async function(a){if(a.preventDefault(),m(!0),c(""),!r)return void c("Must select assembly!");const o=new t.DeleteAssemblyChange({typeName:"DeleteAssemblyChange",assembly:r.name});await e.submit(o,{internetAccountId:h.internetAccountId}),n(),a.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},g.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:h.internetAccountId,onChange:function(e){m(!1);const t=g.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);b(t)},disabled:f&&!s},o.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{labelId:"label",value:r?.name??"",onChange:function(e){const t=w.find((t=>t.name===e.target.value));l(t)},disabled:0===w.length},w.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement(p.DialogContentText,null,de.default.createElement("strong",{style:{color:"red"}},"NOTE: All assembly data will be deleted and this operation cannot be undone!")),de.default.createElement(p.FormGroup,null,de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{checked:u,onChange:()=>{d(!u)}}),label:"I understand that all assembly data will be deleted"}))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!r||!u,variant:"contained",type:"submit"},"Delete"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}function kt({changeManager:e,handleClose:n,selectedFeature:a,session:o,setSelectedFeature:r,sourceAssemblyId:l,sourceFeature:s}){const{notify:c}=o,[u,d]=y.useState("");return de.default.createElement(We,{open:!0,title:"Delete feature",handleClose:n,maxWidth:!1,"data-testid":"delete-feature"},de.default.createElement("form",{onSubmit:async function(o){o.preventDefault(),d(""),a?._id===s._id&&r();const u=new t.DeleteFeatureChange({changedIds:[s._id],typeName:"DeleteFeatureChange",assembly:l,deletedFeature:i.getSnapshot(s),parentFeatureId:s.parent?._id});await e.submit(u),c("Feature deleted successfully","success"),n(),o.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Are you sure you want to delete the selected feature?")),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit"},"Yes"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),u?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},u)):null)}function Dt({handleClose:e,session:n}){const[o,r]=y.useState(),[l,s]=y.useState(""),{collaborationServerDriver:c,getInternetAccount:u,inMemoryFileDriver:d}=n.apolloDataStore,f=[...c.getAssemblies(),...d.getAssemblies()];return de.default.createElement(We,{open:!0,title:"Export GFF3",handleClose:e,maxWidth:!1,"data-testid":"download-gff3"},de.default.createElement("form",{onSubmit:async function(r){if(r.preventDefault(),s(""),!o)return void s("Must select assembly to download");const{internetAccountConfigId:l}=a.getConf(o,["sequence","metadata"]);l?await async function(e){if(!o)return void s("Must select assembly to download");const t=u(o.configuration.name,e),n=new URL("export/getID",t.baseURL),a=new URLSearchParams({assembly:o.name});n.search=a.toString();const r=n.toString(),l=t.getFetcher({locationType:"UriLocation",uri:r}),i=await l(r,{method:"GET"});if(!i.ok){const e=await je(i,"Error when exporting ID");return void s(e)}const{exportID:c}=await i.json(),d=new URL("export",t.baseURL),f=new URLSearchParams({exportID:c,includeFASTA:"true"});d.search=f.toString();const m=d.toString();window.open(m,"_blank")}(l):function(e){if(!o)return void s("Must select assembly to download");const{assemblies:n}=e.apolloDataStore,r=n.get(o.name),l=r?.refSeqs;if(!l)return void s(`No refSeqs found for assembly "${o.name}"`);const c=[{directive:"gff-version",value:"3"}],u=a.getConf(o,["sequence","adapter","features"]);for(const e of u){const{end:t,refName:n,start:a}=e;c.push({directive:"sequence-region",value:`${n} ${a+1} ${t}`})}for(const[,e]of l){const{features:n}=e;if(n)for(const[,e]of n)c.push(t.annotationFeatureToGFF3(i.getSnapshot(e)))}for(const e of u){const{refName:t,seq:n}=e;c.push({id:t,description:"",sequence:n})}const d=re.default.formatSync(c),f=new Blob([d],{type:"text/plain;charset=utf-8"});F.saveAs(f,`${o.displayName??o.name}.gff3`)}(n),e()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{labelId:"label",value:o?.name??"",onChange:function(e){const t=f.find((t=>t.name===e.target.value));r(t)},disabled:0===f.length},f.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement(p.DialogContentText,null,"Select assembly to export to GFF3")),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!o,variant:"contained",type:"submit"},"Download"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Cancel"))),l?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},l)):null)}function Rt({changeManager:e,handleClose:n,session:o}){const{apolloDataStore:r}=o,[l,s]=y.useState(),[i,c]=y.useState(),[u,d]=y.useState(""),[f,m]=y.useState(!1),[g,h]=y.useState(),[b,S]=y.useState(!1),[w,v]=y.useState(!1),{collaborationServerDriver:E,getInternetAccount:C}=r,x=E.getAssemblies();return y.useEffect((()=>{i&&(async()=>{const{internetAccountConfigId:e}=a.getConf(i,["sequence","metadata"]),t=C(i.name,e);if(!t)throw new Error("No Apollo internet account found");const{baseURL:n}=t,o=new URL("features/count",n),r=new URLSearchParams({assemblyId:i.name});o.search=r.toString();const l=t.getFetcher({locationType:"UriLocation",uri:o.toString()});v(!0);const s=await l(o.toString(),{method:"GET"});if(!s.ok)throw new Error(await je(s));{const e=await s.json();h(e.count)}v(!1)})().catch((e=>{console.error(e),d(e.message??e)}))}),[C,o,i]),de.default.createElement(We,{open:!0,title:"Import Features from GFF3 file",handleClose:n,maxWidth:!1,"data-testid":"import-features-dialog"},w?de.default.createElement(ye.default,null):null,de.default.createElement("form",{onSubmit:async function(r){r.preventDefault(),d(""),v(!0),m(!0);let s="";if(!l)return void d("must select a file");if(!i)return void d("Must select assembly to download");const{internetAccountConfigId:c}=a.getConf(i,["sequence","metadata"]),u=C(i.name,c),{baseURL:f}=u,g=new URL("files",f);g.searchParams.set("type","text/x-gff3");const p=g.href,h=new FormData;h.append("file",l),h.append("fileName",l.name),h.append("type","text/x-gff3");const y=u.getFetcher({locationType:"UriLocation",uri:p});n();const{jobsManager:S}=o,w=new AbortController,E={name:`Importing features for ${i.displayName}`,statusMessage:"Uploading file, this may take awhile",progressPct:0,cancelCallback:()=>{w.abort(),S.abortJob(E.name)}};if(S.runJob(E),y){const{signal:e}=w,t=await y(p,{method:"POST",body:h,signal:e});if(!t.ok){const e=await je(t,"Error when inserting new features (while uploading file)");return S.abortJob(E.name,e),void d(e)}s=(await t.json())._id}const x=new t.AddFeaturesFromFileChange({typeName:"AddFeaturesFromFileChange",assembly:i.name,fileId:s,deleteExistingFeatures:b});S.done(E),await e.submit(x,{updateJobsManager:!0})}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{labelId:"label",value:i?.name??"",onChange:function(e){const t=x.find((t=>t.name===e.target.value));c(t),m(!1)},disabled:f&&!u},x.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name))))),de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Upload GFF3 to load features"),de.default.createElement("input",{type:"file",onChange:function(e){m(!1),e.target.files&&s(e.target.files[0])},disabled:f&&!u})),g&&g>0?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,null,"This assembly already has ",g," features, would you like to delete the existing features before importing new ones?"),de.default.createElement(he.default,{label:"Yes, delete existing features",disabled:f&&!u,control:de.default.createElement(pe.default,{checked:b,onChange:function(e){S(e.target.checked)},inputProps:{"aria-label":"controlled"},color:"warning"})})):null,de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!(i&&l&&void 0!==g)||f,variant:"contained",type:"submit"},f?"Submitting...":"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Close"))),u?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},u)):null)}function Mt({handleClose:e,session:t}){const{internetAccounts:n}=i.getRoot(t),[a,o]=y.useState(""),r=n.filter((e=>"ApolloInternetAccount"===e.type));if(0===r.length)throw new Error("No Apollo internet account found");const[l,s]=y.useState(r[0]);return de.default.createElement(We,{open:!0,title:"Log out",handleClose:e,maxWidth:!1,"data-testid":"log-out"},de.default.createElement("form",{onSubmit:function(e){e.preventDefault(),o(""),l.removeToken(),globalThis.location.reload()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},r.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:l.internetAccountId,onChange:function(e){const t=r.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);s(t)}},n.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement(p.DialogContentText,null,"Are you sure you want to log out?")),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!l,variant:"contained",type:"submit"},"Log Out"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Cancel"))),a?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},a)):null)}function It({handleClose:e,session:t}){const{internetAccounts:n}=i.getRoot(t),[a,o]=y.useState(),[r,l]=y.useState(""),[s,c]=y.useState(!1),u=n.filter((e=>"ApolloInternetAccount"===e.type));if(0===u.length)throw new Error("No Apollo internet account found");const[d,f]=y.useState(u[0]),[m,g]=y.useState([]),[h,b]=y.useState([]),{collaborationServerDriver:S}=t.apolloDataStore,w=S.getAssemblies();function v(e,t){const n=[...h],a=e.target.value;if(t)n.includes(a)||(n.push(a),b(n));else{const e=n.indexOf(a,0);-1!==e&&n.splice(e,1),b(n)}}return y.useEffect((()=>{(async function(){const{baseURL:e,getFetcher:t}=d,n=new URL("checks/types",e).href,a=t({locationType:"UriLocation",uri:n}),o=await a(n,{method:"GET"});if(!o.ok){const e=await je(o,"Error when retrieving checks from server");return void l(e)}const r=await o.json();g(r)})().catch((e=>{l(String(e))}))}),[d]),y.useEffect((()=>{w.length>0&&void 0===a&&o(w[0])}),[w,a]),y.useEffect((()=>{(async function(){if(!a)return;const{baseURL:e,getFetcher:t}=d,n=new URL(`/assemblies/${a.name}`,e).href,o=t({locationType:"UriLocation",uri:n}),r=await o(n,{method:"GET"});if(!r.ok){const e=await je(r,"Error when retrieving assembly from server");return void l(e)}const s=await r.json();b(s.checks)})().catch((e=>{l(String(e))}))}),[a,d]),de.default.createElement(We,{open:!0,title:"Manage Checks",handleClose:e,"data-testid":"manage-checks"},de.default.createElement("form",{onSubmit:async function(n){if(n.preventDefault(),!a)return void l("Must select assembly!");const{notify:o}=t,{baseURL:r,getFetcher:s}=d,i=new URL("assemblies/checks",r).href,c=s({locationType:"UriLocation",uri:i}),u=await c(i,{method:"POST",body:JSON.stringify({_id:a.name,checks:h,name:""}),headers:{"Content-Type":"application/json"}});if(u.ok)o("Assembly checks updated successfully","success"),e();else{const e=await je(u,"Error when updating assembly checks");l(e)}}},de.default.createElement(p.DialogContent,null,u.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:d.internetAccountId,onChange:function(e){c(!1);const t=u.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);f(t)},disabled:s&&!r},n.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{style:{width:300},labelId:"label",value:a?.name??"",onChange:function(e){const t=w.find((t=>t.name===e.target.value));o(t)},disabled:0===w.length},w.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement("br",null),de.default.createElement("br",null),de.default.createElement(p.TableContainer,{component:p.Paper},de.default.createElement(p.Table,null,de.default.createElement(p.TableHead,null,de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,null,"Check name"),de.default.createElement(p.TableCell,null,"Use check"))),de.default.createElement(p.TableBody,null,m.map((e=>de.default.createElement(p.TableRow,{key:e._id},de.default.createElement(p.TableCell,null,e.name),de.default.createElement(p.TableCell,null,de.default.createElement(p.Checkbox,{value:e._id,checked:h.includes(e._id),onChange:v}))))))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit"},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Cancel"))),r?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},r)):null)}function Pt({changeManager:e,handleClose:n,session:a}){const{internetAccounts:o}=i.getRoot(a),r=o.filter((e=>"ApolloInternetAccount"===e.type&&e.role?.includes("admin")));if(0===r.length)throw new Error("No Apollo internet account found");const[l,s]=y.useState(""),[c,u]=y.useState(r[0]),[d,f]=y.useState([]),m=y.useCallback((async()=>{const{baseURL:e}=c,t=new URL("users",e).href,n=c.getFetcher({locationType:"UriLocation",uri:t});if(n){const e=await n(t,{method:"GET"});if(!e.ok){const t=await je(e,"Error when getting user data from db");return void s(t)}const a=await e.json();f(a.map((e=>void 0===e.role?{...e,role:""}:e)))}}),[c]);function g(e){return e===c.getUserId()}y.useEffect((()=>{m().catch((e=>{s(String(e))}))}),[m]);const h=[{field:"username",headerName:"User",width:140},{field:"email",headerName:"Email",width:160},{field:"role",headerName:"Role",width:140,type:"singleSelect",valueOptions:["readOnly","user","admin","none"],getOptionLabel(e){switch(e){case"readOnly":return"Read-only";case"user":return"User";case"admin":return"Admin";case"none":return"None";default:return"unknown"}},editable:!0},{field:"actions",type:"actions",getActions:n=>[de.default.createElement(I.GridActionsCellItem,{key:`delete-${n.id}`,icon:de.default.createElement(be.default,null),onClick:async()=>{globalThis.confirm("Delete this user?")&&await async function(n){const a=new t.DeleteUserChange({typeName:"DeleteUserChange",userId:n});await e.submit(a,{internetAccountId:c.internetAccountId}),f((e=>e.filter((e=>e._id!==n))))}(n.id)},disabled:g(n.id),label:"Delete"})]}];return de.default.createElement(We,{open:!0,fullScreen:!0,title:"Manage users",handleClose:n,"data-testid":"manage-users"},de.default.createElement(p.DialogContent,null,r.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:c.internetAccountId,onChange:function(e){const t=r.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);u(t)},disabled:!l},o.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement("div",{style:{height:"100%",width:"100%"}},de.default.createElement(I.DataGrid,{pagination:!0,rows:d,columns:h,getRowId:e=>e._id,slots:{toolbar:I.GridToolbar},getRowHeight:()=>"auto",isCellEditable:e=>!g(e.id),processRowUpdate:async function(n){const a=new t.UserChange({typeName:"UserChange",role:n.role,userId:n._id});return await e.submit(a,{internetAccountId:c.internetAccountId}),n},onProcessRowUpdateError:e=>{s(String(e))}}))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Close")),l?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},l)):null)}function qt({handleClose:e,session:t}){const{apolloDataStore:n}=t,{addAssembly:a,addSessionAssembly:o,assemblyManager:l,notify:s}=t,[i,c]=y.useState(null),[u,d]=y.useState(""),[f,m]=y.useState(""),[g,h]=y.useState(!1),b=p.useTheme();return de.default.createElement(We,{open:!0,title:"Open local GFF3 file",handleClose:e,maxWidth:!1,"data-testid":"open-local-file"},de.default.createElement("form",{onSubmit:async function(c){if(c.preventDefault(),m(""),h(!0),!i)throw new Error("No file selected");const d=await new Response(i).text(),f=`${u}-${i.name}-${P.nanoid(8)}`;try{await Be(f,d,n)}catch(t){return console.error(t),s(`Error loading GFF3 ${i.name}, ${String(t)}`,"error"),void e()}const g={name:f,aliases:[u],displayName:u,sequence:{trackId:`sequenceConfigId-${u}`,type:"ReferenceSequenceTrack",adapter:{type:"ApolloSequenceAdapter",assemblyId:f},metadata:{apollo:!0,...r.isElectron?{file:i.path}:{}}}};await(o||a)(g);const p=await l.waitForAssembly(g.name);p?(t.addApolloTrackConfig(p),s(`Loaded GFF3 ${i.name}`,"success")):s(`Error loading GFF3 ${i.name}`,"error"),e()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.FormControl,null,de.default.createElement("div",{style:{flexDirection:"row"}},de.default.createElement(p.Button,{variant:"contained",component:"label",style:{marginRight:b.spacing()}},"Choose File",de.default.createElement("input",{type:"file",required:!0,hidden:!0,onChange:function(e){const t=e.target.files?.item(0);if(t&&(m(""),c(t),!u)){const e=t.name,n=e.lastIndexOf(".");d(-1===n?e:e.slice(0,n))}}})),i?i.name:"No file chosen"),de.default.createElement(p.FormHelperText,null,"Make sure your GFF3 has an embedded FASTA section")),de.default.createElement(p.TextField,{required:!0,label:"Assembly name",value:u,onChange:function(e){d(e.target.value)}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!1,variant:"contained",type:"submit"},g?"Submitting...":"Submit"),de.default.createElement(p.Button,{disabled:g,variant:"outlined",type:"submit",onClick:e},"Cancel"))),f?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},f)):null)}!function(e){e.GENE_AND_SUBFEATURES="GENE_AND_SUBFEATURES",e.TRANSCRIPT_AND_SUBFEATURES="TRANSCRIPT_AND_SUBFEATURES",e.CUSTOM="CUSTOM"}(Ct||(Ct={}));const Lt=b.makeStyles()((e=>({changeTextarea:{fontFamily:"monospace",width:600,resize:"none",border:`1px solid ${e.palette.divider}`,borderRadius:e.shape.borderRadius}})));function Bt({handleClose:t,session:n}){const{internetAccounts:a}=i.getRoot(n),o=a.find((e=>"ApolloInternetAccount"===e.type));if(!o)throw new Error("No Apollo internet account found");const{baseURL:r}=o,{classes:l}=Lt(),[s,c]=y.useState(),[u,d]=y.useState([]),[f,m]=y.useState(""),[g,h]=y.useState([]),b=[{field:"sequence"},{field:"typeName",headerName:"Change type",width:200,type:"singleSelect",valueOptions:[...e.changeRegistry.changes.keys()]},{field:"changes",headerName:"Change JSON",width:600,renderCell:({value:e})=>de.default.createElement("textarea",{className:l.changeTextarea,value:JSON.stringify(e),readOnly:!0}),valueFormatter:({value:e})=>JSON.stringify(e)},{field:"user",headerName:"User",width:140},{field:"createdAt",headerName:"Time",width:160,type:"dateTime",valueGetter:e=>e&&new Date(e)}];return y.useEffect((()=>{(async function(){const e=new URL("assemblies",r).href,t=o?.getFetcher({locationType:"UriLocation",uri:e});if(t){const n=await t(e,{method:"GET"});if(!n.ok){const e=await je(n,"Error when retrieving assemblies from server");return void c(e)}const a=await n.json();d(a)}})().catch((e=>{c(String(e))}))}),[o,r]),y.useEffect((()=>{!f&&u.length>0&&m(u[0]._id)}),[f,u]),y.useEffect((()=>{(async function(){if(!f)return;const e=new URL("changes",r),t=new URLSearchParams({assembly:f});e.search=t.toString();const n=e.toString(),a=o?.getFetcher({locationType:"UriLocation",uri:n});if(a){const e=await a(n,{headers:new Headers({"Content-Type":"application/json"})});if(!e.ok){const t=await je(e,"Error when retrieving changes");return void c(t)}const t=await e.json();h(t)}})().catch((e=>{c(String(e))}))}),[f,o,r]),de.default.createElement(We,{open:!0,fullScreen:!0,title:"View change log",handleClose:t,"data-testid":"view-changelog"},de.default.createElement(p.Select,{style:{width:200,marginLeft:40},value:f,onChange:function(e){m(e.target.value)}},u.map((e=>de.default.createElement(p.MenuItem,{key:e._id,value:e._id},e.name)))),de.default.createElement(p.DialogContent,null,de.default.createElement(I.DataGrid,{pagination:!0,rows:g,columns:b,getRowId:e=>e._id,slots:{toolbar:I.GridToolbar},initialState:{sorting:{sortModel:[{field:"sequence",sort:"desc"}]},columns:{columnVisibilityModel:{sequence:!1}}}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:t},"Close")),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}const Ot=[{field:"refName",headerName:"Ref Name"},{field:"aliases",headerName:"Aliases",editable:!0}],_t=e=>/^[\da-f]{24}$/i.test(e);function Ut({changeManager:e,handleClose:n,session:a}){const o=y.useRef(null),[r,l]=y.useState(""),[s,i]=y.useState(!1),[c,u]=y.useState(),[d,f]=y.useState([]),[m,g]=y.useState(new Map),{apolloDataStore:h}=a,{collaborationServerDriver:b}=h,S=b.getAssemblies();y.useEffect((()=>{let e=0;const t=()=>{if(!c)return;const n=new Map;if(e<2&&!c.refNames&&(e++,setTimeout(t,50)),!c.refNames)return;const a=c.refNameAliases;for(const e in a){const t=a[e];if(t&&!_t(e))if(n.has(t)){const a=n.get(t)??[];n.set(t,[...a,e])}else n.set(t,[e])}g(n)};t()}),[c]);const w=()=>[...m].map(((e,t)=>({id:t,refName:e[0],aliases:e[1].filter((t=>t!==e[0])).join(", ")})));return de.default.createElement(We,{open:!0,title:"Add reference sequence aliases",handleClose:n,maxWidth:"sm","data-testid":"add-refseq-alias",fullWidth:!0},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.Grid2,{container:!0,spacing:2},de.default.createElement(p.Grid2,null,de.default.createElement(p.FormControl,{disabled:s&&!r,fullWidth:!0},de.default.createElement(p.InputLabel,{id:"demo-simple-select-label"},"Assembly"),de.default.createElement(p.Select,{labelId:"demo-simple-select-label",id:"demo-simple-select",label:"Assembly",value:c?.name??"",onChange:e=>{const t=S.find((t=>t.name===e.target.value));u(t),i(!1),l(""),o.current&&(o.current.value="")}},S.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))))),de.default.createElement(p.Grid2,null,de.default.createElement(p.InputLabel,null,"Load RefName alias"),de.default.createElement("input",{type:"file",onChange:e=>{(async e=>{if(!e.target.files)return;const t=e.target.files[0],n=(await t.text()).split("\n"),a=new Map(m);l("");for(const e of n){const t=e.split("\t");for(const e of t)a.has(e)&&a.set(e,[...a.get(e)??[],...t])}g(a)})(e).catch((()=>{l("Error reading file")}))},ref:o,disabled:s&&!r||!c}))),c&&m.size>0?de.default.createElement("div",{style:{height:200,width:"100%",marginTop:20}},de.default.createElement(p.InputLabel,null,"Refname aliases found for selected assembly."),de.default.createElement(I.DataGrid,{rows:w(),columns:Ot,initialState:{pagination:{paginationModel:{page:0,pageSize:5}}},pageSizeOptions:[5,10],onRowSelectionModelChange:e=>{(e=>{if(e.length>0){i(!0);const t=e.flatMap((e=>w().filter((t=>t.id===e))));f(t)}else i(!1),f([])})(e)},processRowUpdate:(e,t)=>{const n=new Map(m);return n.set(e.refName,e.aliases.split(",")),g(n),e},checkboxSelection:!0})):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:!s,onClick:()=>{const a=[];for(const e of d){const{refName:t}=e,n=e.aliases.split(",").map((e=>e.trim())).filter((e=>e.length>0));a.push({refName:t,aliases:n})}if(l(""),!c)return void l("No assembly selected");const o=new t.AddRefSeqAliasesChange({typeName:"AddRefSeqAliasesChange",assembly:c.name,refSeqAliases:a});e.submit(o).catch((()=>{l("Error submitting change")})),n()}},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Close")),r?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},r)):null)}function $t({handleClose:e,session:t}){const{internetAccounts:n}=i.getRoot(t),{collaborationServerDriver:a}=t.apolloDataStore,o=n.find((e=>"ApolloInternetAccount"===e.type));if(!o)throw new Error("No Apollo internet account found");const{baseURL:r}=o,[l,s]=y.useState(),[c,u]=y.useState(),[d,f]=y.useState([]),m=a.getAssemblies();return y.useEffect((()=>{!c&&m.length>0&&u(m[0])}),[m,c]),y.useEffect((()=>{(async function(){const e=c?.name;if(!e)return;const t=new URL("checks",r),n=new URLSearchParams({assembly:e});t.search=n.toString();const a=t.toString(),l=o?.getFetcher({locationType:"UriLocation",uri:a});if(l){const e=await l(a,{headers:new Headers({"Content-Type":"application/json"})});if(!e.ok){const t=await je(e,"Error when retrieving checks");return void s(t)}const t=await e.json();f(t)}})().catch((e=>{s(String(e))}))}),[c,o,r]),de.default.createElement(We,{open:!0,fullScreen:!0,title:"View check results",handleClose:e,"data-testid":"view-check-results"},de.default.createElement(p.Select,{style:{width:200,marginLeft:40},value:c?.name??"",onChange:function(e){const t=m.find((t=>t.name===e.target.value));u(t)},disabled:0===m.length},m.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement(p.DialogContent,null,de.default.createElement(I.DataGrid,{pagination:!0,rows:d,columns:[{field:"_id",headerName:"id",width:50},{field:"name",headerName:"Check name",width:200},{field:"refSeq",headerName:"Reference sequence ID",width:200},{field:"ids",headerName:"Feature IDs",width:200},{field:"message",headerName:"Message",flex:1}],getRowId:e=>e._id,slots:{toolbar:I.GridToolbar},initialState:{sorting:{sortModel:[{field:"name",sort:"asc"}]},columns:{columnVisibilityModel:{name:!0}}}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Close")),l?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},l)):null)}function jt(e){const{color:t}=e;return de.default.createElement(p.SvgIcon,{viewBox:"0 0 18 18",style:{fontSize:18,marginRight:4},...e},"disabled"===t?de.default.createElement("path",{d:"M9.001,10.71 l0,-3.348 l8.424,0 c0.126,0.567,0.225,1.098,0.225,1.845 c0,5.139,-3.447,8.793,-8.64,8.793 c-4.968,0,-9,-4.032,-9,-9 c0,-4.968,4.032,-9,9,-9 c2.43,0,4.464,0.891,6.021,2.349 l-2.556,2.484 c-0.648,-0.612,-1.782,-1.332,-3.465,-1.332 c-2.979,0,-5.409,2.475,-5.409,5.508 c0,3.033,2.43,5.508,5.409,5.508 c3.447,0,4.716,-2.385,4.95,-3.798 l-4.959,0 l0,-0.009 z"}):de.default.createElement(de.default.Fragment,null,de.default.createElement("path",{d:"M17.64,9.20454545 c0,-0.638,-0.057,-1.252,-0.164,-1.841 l-8.476,0 l0,3.481 l4.844,0 c-0.209,1.125,-0.843,2.079,-1.796,2.717 l0,2.258 l2.908,0 c1.702,-1.567,2.684,-3.874,2.684,-6.615 l0,0 z",fill:"#4285F4"}),de.default.createElement("path",{d:"M9,18 c2.43,0,4.467,-0.806,5.956,-2.18 l-2.908,-2.259 c-0.806,0.54,-1.837,0.859,-3.048,0.859 c-2.344,0,-4.328,-1.583,-5.036,-3.71 l-3.007,0 l0,2.332 c1.481,2.941,4.525,4.958,8.043,4.958 l0,0 z",fill:"#34A853"}),de.default.createElement("path",{d:"M3.96409091,10.71 c-0.18,-0.54,-0.282,-1.117,-0.282,-1.71 c0,-0.593,0.102,-1.17,0.282,-1.71 l0,-2.332 l-3.007,0 c-0.609,1.215,-0.957,2.59,-0.957,4.042 c0,1.452,0.348,2.827,0.957,4.042 l3.007,-2.332 l0,0 z",fill:"#FBBC05"}),de.default.createElement("path",{d:"M9,3.57954545 c1.321,0,2.508,0.454,3.44,1.346 l2.582,-2.581 c-1.559,-1.453,-3.596,-2.345,-6.022,-2.345 c-3.518,0,-6.562,2.017,-8.043,4.959 l3.007,2.331 c0.708,-2.127,2.692,-3.71,5.036,-3.71 l0,0 z",fill:"#EA4335"})))}function Gt(e){const{color:t}=e;return de.default.createElement(p.SvgIcon,{viewBox:"0 0 21 21",style:{fontSize:21},...e},de.default.createElement("rect",{x:"1",y:"1",width:"9",height:"9",fill:"disabled"===t?"#7B7B7B":"#F25022"}),de.default.createElement("rect",{x:"1",y:"11",width:"9",height:"9",fill:"disabled"===t?"#7B7B7B":"#00A4EF"}),de.default.createElement("rect",{x:"11",y:"1",width:"9",height:"9",fill:"disabled"===t?"#939393":"#7FBA00"}),de.default.createElement("rect",{x:"11",y:"11",width:"9",height:"9",fill:"disabled"===t?"#B9B9B9":"#FFB900"}))}const Wt=b.makeStyles()((e=>({loginButton:{marginBottom:e.spacing(1),width:"220px",height:"40px",fontSize:"16px",textTransform:"none",justifyContent:"left",padding:"3px 12px"}})));function Ht(e){const{classes:t}=Wt(),{disabled:n}=e;return de.default.createElement(p.Button,{className:t.loginButton,variant:"outlined",startIcon:de.default.createElement(jt,{color:n?"disabled":void 0}),...e},"Sign in with Google")}function zt(e){const{classes:t}=Wt(),{disabled:n}=e;return de.default.createElement(p.Button,{className:t.loginButton,variant:"outlined",startIcon:de.default.createElement(Gt,{color:n?"disabled":void 0}),...e},"Sign in with Microsoft")}function Jt(e){const{classes:t}=Wt();return de.default.createElement(p.Button,{className:t.loginButton,variant:"outlined",startIcon:de.default.createElement(Se.default,{fontSize:"small"}),...e},"Continue as Guest")}const Vt=b.makeStyles()((e=>({divider:{marginTop:e.spacing(4),marginBottom:e.spacing(5)}}))),Xt=({baseURL:e,handleClose:t,name:n})=>{const{classes:a}=Vt(),[o,r]=y.useState(""),[l,s]=y.useState([]);function i(e){t("google"===e?"google":"microsoft"===e?"microsoft":"guest")}y.useEffect((()=>{const t=new AbortController,{signal:n}=t;return async function(){const t=new URL("auth/types",e).href,a=await fetch(t,{method:"GET",signal:n});if(!a.ok){const e=await je(a,"Error when retrieving auth types from server");return void r(e)}const o=await a.json();s(o)}().catch((e=>{x.isAbortException(e)||r(String(e))})),()=>{t.abort()}}),[e]);const c=l.includes("google"),u=l.includes("microsoft"),d=l.includes("guest");return de.default.createElement(We,{open:!0,title:`Log in to ${n}`,handleClose:t,maxWidth:!1,"data-testid":"login-apollo"},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column",paddingTop:8}},c?de.default.createElement(Ht,{disabled:!c,onClick:()=>{i("google")}}):null,u?de.default.createElement(zt,{disabled:!u,onClick:()=>{i("microsoft")}}):null,d?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.Divider,{className:a.divider}),de.default.createElement(Jt,{onClick:()=>{i("guest")}})):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:()=>{t()}},"Cancel")),o?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},o)):null)},Kt="undefined"==typeof sessionStorage,Yt=n=>o.InternetAccount.named("ApolloInternetAccount").props({type:i.types.literal("ApolloInternetAccount"),configuration:a.ConfigurationReference(n)}).views((e=>({get baseURL(){return a.getConf(e,"baseURL")},getUserId(){const n=e.retrieveToken();if(n)return t.getDecodedToken(n).id}}))).volatile((()=>({role:void 0}))).actions((e=>{let n=!1;return{setRole(){const a=e.retrieveToken();if(!a)return void(e.role=void 0);const o=t.getDecodedToken(a),{role:r}=o;if(!r&&!n){const{session:t}=i.getRoot(e);t.notify("You have registered as a user but have not been given access. Ask your administrator to enable access for your account.","warning"),n=!0}e.role!==r&&(e.role=r)}}})).actions((e=>{let t;return{addMessageChannel(e,n){t=t=>{this.finishOAuthWindow(t,e,n)},window.addEventListener("message",t)},deleteMessageChannel(){window.removeEventListener("message",t)},finishOAuthWindow(t,n,a){if(t.data.name!==`JBrowseAuthWindow-${e.internetAccountId}`)return void this.deleteMessageChannel();const o=t.data.redirectUri.replace("#","?"),r=new URL(o),l=new URLSearchParams(r.search).get("access_token");this.deleteMessageChannel(),l?(e.storeToken(l),e.setRole(),n(l)):a(new Error("Error with token endpoint"))},async openAuthWindow(t,n,a){const o=r.isElectron?"http://localhost/auth":globalThis.location.origin+globalThis.location.pathname,l=new URL("auth/login",e.baseURL),s=new URLSearchParams({type:t,redirect_uri:o});l.search=s.toString();const i=`JBrowseAuthWindow-${e.internetAccountId}`;if(r.isElectron){const{ipcRenderer:t}=globalThis.require("electron"),r=await t.invoke("openAuthWindow",{internetAccountId:e.internetAccountId,data:{redirect_uri:o},url:l.toString()}),s=new MessageEvent("message",{data:{name:i,redirectUri:r}});this.finishOAuthWindow(s,n,a)}else this.addMessageChannel(n,a),window.open(l,i,"width=500,height=600")}}})).actions((e=>({async getTokenFromUser(t,n){const{baseURL:a}=e,o=await new Promise(((t,n)=>{const{session:a}=i.getRoot(e),{baseURL:o,name:r}=e;a.queueDialog((e=>[Xt,{name:r,handleClose:a=>{a?a instanceof Error?n(a):t(a):n(new Error("user cancelled entry")),e()},baseURL:o}]))}));if("guest"!==o)return void e.openAuthWindow(o,t,n);const r=new URL("auth/login",a),l=new URLSearchParams({type:o});r.search=l.toString();const s=r.toString(),c=await fetch(s);if(!c.ok){const e=await je(c,"Error when logging in");return void n(new Error(e))}const{token:u}=await c.json();t(u)}}))).volatile((()=>({lastChangeSequenceNumber:void 0}))).actions((e=>({setLastChangeSequenceNumber(t){e.lastChangeSequenceNumber=t}}))).actions((t=>({updateLastChangeSequenceNumber:i.flow((function*(){const{baseURL:e}=t,n=new URL("changes",e),a=new URLSearchParams({limit:"1"});n.search=a.toString();const o=n.toString(),r=t.getFetcher({locationType:"UriLocation",uri:o}),l=yield r(o,{method:"GET"});if(!l.ok){const e=yield je(l,"Error when fetching server LastChangeSequence");throw new Error(e)}const s=yield l.json();t.setLastChangeSequenceNumber(s.length>0?s[0].sequence:0)})),getMissingChanges:i.flow((function*(){const{session:n}=i.getRoot(t),{changeManager:a}=n.apolloDataStore;if(!t.lastChangeSequenceNumber)throw new Error("No LastChangeSequence stored in session. Please, refresh you browser to get last updates from server");const{baseURL:o,lastChangeSequenceNumber:r}=t,l=new URL("changes",o),s=new URLSearchParams({since:String(r),sort:"1"});l.search=s.toString();const c=l.toString(),u=t.getFetcher({locationType:"UriLocation",uri:c}),d=yield u(c,{method:"GET"});if(!d.ok)return void console.error(`Error when fetching the last updates to recover socket connection — ${d.status}`);const f=yield d.json();for(const t of f){const n=e.Change.fromJSON(t);a.submit(n,{submitToBackend:!1})}}))}))).volatile((e=>{const{origin:t,pathname:n}=new URL("socket.io/",e.baseURL);return{socket:c.io(t,{path:n})}})).actions((n=>({addSocketListeners(){const{session:a}=i.getRoot(n),{notify:o}=a,r=n.retrieveToken();if(!r)throw new Error("No Token found");const{socket:l}=n,{addCheckResult:s,changeManager:c,deleteCheckResult:u}=a.apolloDataStore;l.on("connect",(async()=>{await n.getMissingChanges()})),l.on("connect_error",(e=>{console.error(e),o("Could not connect to the Apollo server.","error")})),l.on("COMMON",(t=>{if("checkResult"in t)return void(t.deleted?u(t.checkResult._id.toString()):s(t.checkResult));if(sessionStorage.setItem("LastChangeSequence",String(t.changeSequence)),t.userSessionId===r)return;const n=e.Change.fromJSON(t.changeInfo);c.submit(n,{submitToBackend:!1})})),l.on("USER_LOCATION",(e=>{const{channel:n,locations:o,userName:l,userSessionId:s}=e,i=t.getDecodedToken(r),c=t.makeUserSessionId(i);"USER_LOCATION"===n&&s!==c&&a.addOrUpdateCollaborator({name:l,id:s,locations:o})})),l.on("REQUEST_INFORMATION",(e=>{const{channel:t,userSessionId:n}=e;"REQUEST_INFORMATION"===t&&n!==r&&a.broadcastLocations()}))}}))).actions((e=>({postUserLocation:(t=>{let n;return t=>{clearTimeout(n),n=setTimeout((()=>{!async function(t){const{baseURL:n}=e,a=new URL("users/userLocation",n).href,o=new URLSearchParams(JSON.stringify(t)),r=e.getFetcher({locationType:"UriLocation",uri:a});try{if(!(await r(a,{method:"POST",body:o})).ok)throw new Error("ignore")}catch{console.error("Broadcasting user location failed")}}(t)}),300)}})()}))).actions((e=>({initialize:i.flow((function*(t){if("admin"===t){const t=i.getRoot(e);r.isAbstractMenuManager(t)&&function(e){e.appendToMenu("Apollo",{label:"Add Assembly",onClick:e=>{e.queueDialog((t=>[Ve,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Delete Assembly",onClick:e=>{e.queueDialog((t=>[Ft,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Import Features",onClick:e=>{e.queueDialog((t=>[Rt,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Add reference sequence aliases",onClick:e=>{e.queueDialog((t=>[Ut,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Manage Users",onClick:e=>{e.queueDialog((t=>[Pt,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Undo",onClick:e=>{const{apolloDataStore:t}=e,{notify:n}=e;t.changeManager.recentChanges.length>0?t.changeManager.revertLastChange():n("No changes to undo","info")}})}(t)}yield e.updateLastChangeSequenceNumber(),e.addSocketListeners();const{baseURL:n}=e,a=new URL("users/locations",n).href,o=e.getFetcher({locationType:"UriLocation",uri:a});yield o(a,{method:"GET"}),window.addEventListener("beforeunload",(()=>{e.postUserLocation([])})),document.addEventListener("visibilitychange",(()=>{if("hidden"===document.visibilityState&&e.postUserLocation([]),"visible"===document.visibilityState){const{session:t}=i.getRoot(e);t.broadcastLocations()}}))}))}))).actions((e=>({afterAttach(){e.setRole(),s.autorun((async t=>{if(Kt)return;const{session:n}=i.getRoot(e);n&&e.role&&(await e.initialize(e.role),t.dispose())}),{name:"ApolloInternetAccount"})}}))),Zt="undefined"==typeof sessionStorage;class Qt extends B.BaseAdapter{refNameAliases;async getRefNameAliases(){const e=a.readConfObject(this.config,"assemblyId");if(!Zt){const t=this.pluginManager?.rootModel?.session?.apolloDataStore;if(!t)throw new Error("No Apollo data store found");const n=t.getBackendDriver(e);return await n.getRefNameAliases(e)}const t=await new Promise(((t,n)=>{const a=setTimeout((()=>{n(new Error("timeout"))}),2e4),o=P.nanoid(),r=e=>{const n=e.data;(function(e){return"object"==typeof e&&null!==e&&"apollo"in e&&!0===e.apollo&&"refNameAliases"in e})(n)&&n.messageId===o&&(clearTimeout(a),removeEventListener("message",r),t(n.refNameAliases))};addEventListener("message",r),rpcServer.emit("apollo",{apollo:!0,method:"getRefNameAliases",assembly:e,messageId:o})}));return this.refNameAliases=t,t}freeResources(){}}var en=a.ConfigurationSchema("ApolloRefNameAliasAdapter",{assemblyId:{type:"string",defaultValue:""}},{explicitlyTyped:!0});function tn(e){return"object"==typeof e&&null!==e&&"apollo"in e&&!0===e.apollo}const nn="undefined"==typeof sessionStorage;class an extends B.BaseSequenceAdapter{regions;async getRefNames(){return(await this.getRegions()).map((e=>e.refName))}async getRegions(){if(this.regions)return this.regions;const e=a.readConfObject(this.config,"assemblyId");if(!nn){const t=this.pluginManager?.rootModel?.session?.apolloDataStore;if(!t)throw new Error("No Apollo data store found");const n=t.getBackendDriver(e),a=await n.getRegions(e);return this.regions=a,a}const t=await new Promise(((t,n)=>{const a=setTimeout((()=>{n("timeout")}),2e4),o=P.nanoid(),r=e=>{const{data:n}=e;tn(n)&&n.messageId===o&&(clearTimeout(a),removeEventListener("message",r),t(n.regions))};addEventListener("message",r),globalThis.rpcServer.emit("apollo",{apollo:!0,method:"getRegions",assembly:e,messageId:o})}));return this.regions=t,t}getFeatures(e){const{end:t,refName:n,start:o}=e,r=a.readConfObject(this.config,"assemblyId"),l={...e,assemblyName:r};return O.ObservableCreate((async e=>{if(!nn){const a=this.pluginManager?.rootModel?.session?.apolloDataStore;if(!a)return void e.error("No Apollo data store found");const s=a.getBackendDriver(r),i=(await s.getRegions(l.assemblyName)).find((e=>e.refName===l.refName));if(!i)return void e.error("Cannot get region");l.end>i.end&&(l.end=i.end);const{seq:c}=await s.getSequence(l);return e.next(new ve.default({id:`${n} ${o}-${t}`,data:{refName:n,start:o,end:t,seq:c}})),void e.complete()}const a=await new Promise(((e,t)=>{const n=setTimeout((()=>{t("timeout")}),2e4),a=P.nanoid(),o=t=>{const{data:r}=t;tn(r)&&r.messageId===a&&(clearTimeout(n),removeEventListener("message",o),e(r.sequence))};addEventListener("message",o),globalThis.rpcServer.emit("apollo",{apollo:!0,method:"getSequence",region:l,messageId:a})}));e.next(new ve.default({id:`${n} ${o}-${t}`,data:{refName:n,start:o,end:t,seq:a}})),e.complete()}))}freeResources(){}}var on=a.ConfigurationSchema("ApolloSequenceAdapter",{assemblyId:{type:"string",defaultValue:""}},{explicitlyTyped:!0});class rn extends B.BaseAdapter{get baseURL(){return a.readConfObject(this.config,"baseURL").uri}get trackId(){return a.readConfObject(this.config,"trackId")}get assemblyNames(){return a.readConfObject(this.config,"assemblyNames")}mapBaseResult(e,t,n){return e.map((e=>{const a=t.getCanonicalRefName(e.refSeq);return new Ee.default({label:n,trackId:this.trackId,locString:`${a}:${e.min+1}..${e.max}`})}))}async searchIndex(e){const t=e.queryString,n=[],a=this.pluginManager?.rootModel?.session;if(!a)return n;const{apolloDataStore:o}=a,{assemblyManager:r}=a;for(const a of this.assemblyNames){const l=o.getBackendDriver(a),s=r.get(a);if(!l||!s)continue;const i=await l.searchFeatures(e.queryString,[a]);n.push(...this.mapBaseResult(i,s,t))}return n}freeResources(){}}var ln=a.ConfigurationSchema("ApolloTextSearchAdapter",{assemblyNames:{type:"stringArray",defaultValue:[],description:"List of assemblies covered by text search adapter"},trackId:{type:"string",defaultValue:""},baseURL:{type:"fileLocation",defaultValue:{uri:"",locationType:"UriLocation"}}},{explicitlyTyped:!0,explicitIdentifier:"textSearchAdapterId"});const sn=b.makeStyles()((e=>({attributeKey:{fontWeight:"bold",marginRight:e.spacing(2)}})));function cn({attributeKey:e}){const{classes:n}=sn(),a=/^[A-Z]/.test(e);let o,r=e;return t.isGFFInternalAttribute(e)?(r=t.internalToGFF[e],o=`On GFF3 export, this will be assigned to the GFF3's reserved "${r}" attribute`):t.isGFFColumnInternal(e)?(r=t.gffInternalToColumn[e],o=`On GFF3 export, this will be placed in the GFF3's "${r}" column`):a&&(o="On GFF3 export, this attribute will be changed to start with a lower-case letter because attributes starting with an upper-case letter are reserved in GFF3"),de.default.createElement("div",{style:{display:"flex"}},de.default.createElement(p.Typography,{className:n.attributeKey},r),o?de.default.createElement(p.Tooltip,{title:o},de.default.createElement(p.Chip,{icon:de.default.createElement(le.default,null),label:"GFF3",size:"small",variant:"outlined"})):null)}const un="Custom",dn={[un]:"custom"};for(const[e,n]of Object.entries(t.gffToInternal))dn[`GFF ${n}`]=e;for(const[e,n]of Object.entries(t.gffColumnToInternal))dn[`GFF ${n}`]=e;const fn=v.observer((function({setKey:e,session:t}){const{pluginManager:n}=r.getEnv(t),a=n.evaluateExtensionPoint("Apollo-ReservedAttributeKeys",dn),o=Object.keys(a).at(0)??un,[l,s]=y.useState(o),[i,c]=y.useState(),u=l===un;return de.default.createElement("form",{onSubmit:function(t){t.preventDefault(),e(u?i:a[l])}},de.default.createElement("div",{style:{display:"flex",flexDirection:"column",margin:8}},de.default.createElement(p.FormControl,{variant:"outlined"},de.default.createElement(p.InputLabel,{id:"attribute-key-select-label"},"Key"),de.default.createElement(p.Select,{labelId:"attribute-key-select-label",value:l,label:"Key",onChange:e=>{s(e.target.value)}},Object.keys(a).map((e=>de.default.createElement(p.MenuItem,{key:e,value:e},e))))),u?de.default.createElement(p.TextField,{label:"Attribute key",variant:"outlined",id:"attributeKey",onChange:e=>{c(e.target.value)}}):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{color:"primary",variant:"contained",type:"submit",disabled:u&&!i},"Add"),de.default.createElement(p.Button,{variant:"outlined",onClick:function(){e()}},"Cancel")))})),mn=v.observer((function({onChangeCommitted:e,value:t,...n}){const[a,o]=y.useState(String(t)),[r,l]=y.useState(!1),[s,i]=y.useState(null);return y.useEffect((()=>{o(String(t))}),[t]),y.useEffect((()=>{r&&(s?.blur(),l(!1))}),[r,s]),de.default.createElement(p.TextField,{...n,type:"text",onChange:function(e){o(e.target.value)},value:a,onKeyDown:e=>{"Enter"===e.key?s?.blur():"Escape"===e.key&&(o(String(t)),l(!0))},onBlur:()=>{a!==String(t)&&e(a)},inputRef:e=>{i(e)}})})),gn=v.observer((function({attributeValues:e,setAttribute:t,isNew:n=!1}){const[a,o]=y.useState(e&&e.length>0?e:[""]);return de.default.createElement(de.default.Fragment,null,a.map(((e,t)=>de.default.createElement("div",{key:`${t}-${e}`,style:{display:"flex"}},de.default.createElement(mn,{value:e,onChangeCommitted:e=>{!function(e,t){o((n=>{const a=[...n];return a[e]=t,a}))}(t,e)},variant:"outlined",fullWidth:!0}),de.default.createElement(p.IconButton,{"aria-label":"delete",size:"medium",edge:"end",onClick:()=>{!function(e){o((t=>{const n=[...t];return n.splice(e,1),n}))}(t)}},de.default.createElement(be.default,{fontSize:"inherit"}))))),de.default.createElement(p.IconButton,{"aria-label":"add",size:"medium",color:"secondary",edge:"start",onClick:function(){o((e=>{const t=[...e];return t.push(""),t}))}},de.default.createElement(Ae.default,{fontSize:"inherit"})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{color:"primary",variant:"contained",onClick:()=>{t(a.filter(Boolean))}},n?"Add":"Update"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:()=>{t()}},"Cancel")))}));function pn({values:e}){return de.default.createElement(de.default.Fragment,null,e?.map(((e,t)=>de.default.createElement(p.Typography,{key:`${t}.${e}`,variant:"body2",color:"textSecondary"},e))))}const hn=b.makeStyles()((e=>({list:{"li:nth-of-type(odd)":{backgroundColor:e.palette.action.focus},"li:nth-of-type(even)":{backgroundColor:e.palette.action.hover}}}))),yn=v.observer((function({assembly:e,editable:n,feature:a,session:o}){const{pluginManager:l}=r.getEnv(o),{classes:c}=hn(),[u,d]=y.useState(null),[f,m]=y.useState(null),[g,h]=y.useState(null),[b,S]=y.useState(!1),[w,v]=y.useState(),E=Boolean(u),{changeManager:C}=o.apolloDataStore,{notify:x}=o;function T(){d(null),m(null)}const{_id:A,attributes:N}=a,F=l.evaluateExtensionPoint("Apollo-AttributeEditorComponent",gn,{key:w});return de.default.createElement(de.default.Fragment,null,de.default.createElement(p.List,{className:c.list},s.entries(N).map((([r,s])=>{const c=l.evaluateExtensionPoint("Apollo-AttributeEditorComponent",gn,{key:r}),u=l.evaluateExtensionPoint("Apollo-AttributeViewerComponent",pn,{key:r});return de.default.createElement(p.ListItem,{key:r,secondaryAction:n&&!g?de.default.createElement(p.IconButton,{edge:"end",onClick:e=>{!function(e,t){d(e.currentTarget),m(t)}(e,r)}},de.default.createElement(Te.default,null)):null},de.default.createElement(p.ListItemText,{disableTypography:!0,primary:de.default.createElement(cn,{attributeKey:r}),secondary:g===r?de.default.createElement(c,{session:o,attributeValues:s,setAttribute:n=>{h(null),n&&function(n,o){const r={...i.getSnapshot(N)};if(!(n in r))return void x(`"${n}" not found in feature attributes`,"error");if(r[n].toString()===o.toString())return;r[n]=o;const l=new t.FeatureAttributeChange({changedIds:[a._id],typeName:"FeatureAttributeChange",assembly:e,featureId:a._id,attributes:r});C.submit(l)}(r,n)}}):de.default.createElement(u,{values:s})}))})),w?de.default.createElement(p.ListItem,null,de.default.createElement(p.ListItemText,{disableTypography:!0,primary:de.default.createElement(cn,{attributeKey:w}),secondary:de.default.createElement(F,{session:o,attributeValues:[],setAttribute:n=>{n&&function(n,o){const r={...i.getSnapshot(N)};if(n in r)return void x(`Feature already has attribute "${n}"`,"error");r[n]=o;const l=new t.FeatureAttributeChange({changedIds:[a._id],typeName:"FeatureAttributeChange",assembly:e,featureId:a._id,attributes:r});C.submit(l)}(w,n),v(void 0)},isNew:!0})})):null),n?de.default.createElement(p.Button,{color:"primary",variant:"contained",disabled:b||Boolean(w),onClick:()=>{S(!0)}},"Add new"):null,b?de.default.createElement(p.Paper,{variant:"outlined",style:{marginTop:8}},de.default.createElement(fn,{session:o,setKey:e=>{v(e),S(!1)}})):null,de.default.createElement(p.Menu,{anchorEl:u,open:E,onClose:T},de.default.createElement(p.MenuItem,{onClick:function(){f&&function(n){const a=i.getSnapshot(N),{[n]:o,...r}=a,l=new t.FeatureAttributeChange({changedIds:[A],typeName:"FeatureAttributeChange",assembly:e,featureId:A,attributes:r});C.submit(l)}(f),T()}},de.default.createElement(p.ListItemIcon,null,de.default.createElement(be.default,{fontSize:"small"})),de.default.createElement(p.Typography,{variant:"inherit"},"Delete")),de.default.createElement(p.MenuItem,{onClick:function(){f&&h(f),T()}},de.default.createElement(p.ListItemIcon,null,de.default.createElement(xe.default,{fontSize:"small"})),de.default.createElement(p.Typography,{variant:"inherit"},"Edit"))))})),bn=v.observer((function({onChangeCommitted:e,value:t,...n}){const[a,o]=y.useState(String(t)),[r,l]=y.useState(!1),[s,i]=y.useState(null);y.useEffect((()=>{o(String(t))}),[t]),y.useEffect((()=>{r&&(s?.blur(),l(!1))}),[r,s]);const c=Number.isNaN(Number(a));return de.default.createElement(p.TextField,{...n,type:"text",onChange:function(e){o(e.target.value)},value:a,onKeyDown:e=>{"Enter"===e.key?s?.blur():"Escape"===e.key&&(o(String(t)),l(!0))},onBlur:()=>{const n=Number(a);a!==String(t)&&(Number.isNaN(n)?o(String(t)):e(n))},inputRef:e=>{i(e)},error:c,helperText:c?"Not a valid number":void 0})})),Sn=v.observer((function({assembly:e,feature:n,session:a}){const[o,r]=y.useState(""),[l,s]=y.useState(""),{_id:i,assemblyId:c,max:u,min:d,strand:f,type:m}=n,g=e=>{a.notify(e.message,"error")},{changeManager:h}=a.apolloDataStore;function b(n){const{value:a}=n.target,o=a?Number(a):void 0,r=new t.StrandChange({typeName:"StrandChange",changedIds:[i],featureId:i,oldStrand:f,newStrand:o,assembly:e});return h.submit(r)}return de.default.createElement("div",{"data-testid":"basic_information"},de.default.createElement(bn,{margin:"dense",id:"start",label:"Start",fullWidth:!0,variant:"outlined",value:d+1,onChangeCommitted:function(n){n--;const a=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[i],featureId:i,oldStart:d,newStart:n,assembly:e});return h.submit(a)}}),de.default.createElement(bn,{margin:"dense",id:"end",label:"End",fullWidth:!0,variant:"outlined",value:u,onChangeCommitted:function(n){const a=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[i],featureId:i,oldEnd:u,newEnd:n,assembly:e});return h.submit(a)}}),de.default.createElement(vt,{session:a,ontologyName:"Sequence Ontology",value:m,filterTerms:bt,fetchValidTerms:async function(e,t,n){const a=await wt(e,t);if(a)return a;s(`Type "${e?.type}" does not have any children in the ontology`)}.bind(null,n),renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Type",variant:"outlined",fullWidth:!0,error:Boolean(l),helperText:l}),onChange:(e,n)=>{n&&function(e){r("");const n=new t.TypeChange({typeName:"TypeChange",changedIds:[i],featureId:i,oldType:m,newType:e,assembly:c});return h.submit(n)}(n).catch(g)}}),de.default.createElement("label",null,de.default.createElement("input",{type:"radio",value:"1",checked:1===f,onChange:b}),"Positive Strand (+)"),de.default.createElement("label",null,de.default.createElement("input",{type:"radio",value:"-1",checked:-1===f,onChange:b}),"Negative Strand (-)"),de.default.createElement("label",null,de.default.createElement("input",{type:"radio",value:"",checked:void 0===f,onChange:b}),"No Strand Information"),o?de.default.createElement(p.Typography,{color:"error"},o):null)})),wn=v.observer((function(e){const{feature:t,model:n}=e,{children:a,parent:o}=t,r=[];if(a)for(const[,e]of a)r.push(e);return o??r.length>0?de.default.createElement("div",{style:{marginTop:10}},o&&de.default.createElement("div",null,de.default.createElement(p.Typography,{variant:"h6"},"Parent:"),de.default.createElement(p.Button,{variant:"contained",onClick:()=>{n.setFeature(o)}},o.type,$e(o)," (",o.min,"..",o.max,")")),r.length>0&&de.default.createElement("div",null,de.default.createElement(p.Typography,{variant:"h6"},1===r.length?"Child":"Children",":"),r.map((e=>de.default.createElement("div",{key:e._id,style:{marginBottom:5}},de.default.createElement(p.Button,{variant:"contained",onClick:()=>{n.setFeature(e)}},e.type,$e(e)," (",e.min,"..",e.max,")")))))):null})),vn=b.makeStyles()({sequence:{width:"100%",resize:"vertical"}}),En=v.observer((function({assembly:e,feature:t,refName:n,session:a}){const o=a.apolloDataStore.assemblies.get(e),{classes:r}=vn();if(!t||!o)return null;const l=o.getByRefName(n);if(!l)return null;const{max:s,min:i}=t;let c=l.getSequence(i,s);return c?c=function(e,t,n,a,o){return`>${t}:${n+1}–${a}\n${e}`}(c,n,i,s):a.apolloDataStore.loadRefSeq([{assemblyName:e,refName:n,start:i,end:s}]),de.default.createElement("div",null,de.default.createElement("textarea",{readOnly:!0,rows:20,className:r.sequence,value:c}))})),Cn=b.makeStyles()((e=>({root:{padding:e.spacing(2)}}))),xn=v.observer((function(e){const{model:t}=e,{assembly:n,feature:a,refName:o}=t,l=r.getSession(t),s=l.apolloDataStore.assemblies.get(n),{classes:i}=Cn(),[c,u]=y.useState(["attributes"]);if(y.useEffect((()=>{u(["attributes"])}),[a]),!a||!s)return null;const d=s.getByRefName(o);if(!d)return null;const{max:f,min:m}=a;function g(e,t){u(e?[...c,t]:c.filter((e=>e!==t)))}return d.getSequence(m,f)||l.apolloDataStore.loadRefSeq([{assemblyName:n,refName:o,start:m,end:f}]),de.default.createElement("div",{className:i.root},de.default.createElement(Sn,{feature:a,session:l,assembly:s._id}),de.default.createElement(p.Accordion,{style:{marginTop:10},expanded:c.includes("attributes"),onChange:(e,t)=>{g(t,"attributes")}},de.default.createElement(p.AccordionSummary,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel1-content",id:"panel1-header"},de.default.createElement(p.Typography,{component:"span"},"Attributes")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(yn,{feature:a,session:l,assembly:s._id,editable:!0}))),de.default.createElement(p.Accordion,{style:{marginTop:10},expanded:c.includes("sequence"),onChange:(e,t)=>{g(t,"sequence")}},de.default.createElement(p.AccordionSummary,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel2-content",id:"panel2-header"},de.default.createElement(p.Typography,{component:"span"},"Sequence")),de.default.createElement(p.AccordionDetails,null,c.includes("sequence")&&de.default.createElement(En,{feature:a,session:l,assembly:s._id,refName:o}))),de.default.createElement(p.Accordion,{style:{marginTop:10},expanded:c.includes("related_features"),onChange:(e,t)=>{g(t,"related_features")}},de.default.createElement(p.AccordionSummary,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel3-content",id:"panel3-header"},de.default.createElement(p.Typography,{component:"span"},"Related features")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(wn,{model:t,feature:a}))))})),Tn=i.types.model("ApolloFeatureDetailsWidget",{id:E.ElementId,type:i.types.literal("ApolloFeatureDetailsWidget"),feature:i.types.maybe(i.types.reference(H.AnnotationFeatureModel,{onInvalidated(e){e.parent.setTryReload(e.invalidId),e.removeRef()}})),assembly:i.types.string,refName:i.types.string}).volatile((()=>({tryReload:void 0}))).actions((e=>({setFeature(t){e.feature=t},setTryReload(t){e.tryReload=t}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((t=>{if(!e.tryReload)return;const n=r.getSession(e),{apolloDataStore:a}=n;if(!a)return;const o=a.getFeature(e.tryReload);o&&(e.setFeature(o),e.setTryReload(),t.dispose())})))}}))),An=i.types.model("ApolloTranscriptDetails",{id:E.ElementId,type:i.types.literal("ApolloTranscriptDetails"),feature:i.types.maybe(i.types.reference(H.AnnotationFeatureModel,{onInvalidated(e){e.parent.setTryReload(e.invalidId),e.removeRef()}})),assembly:i.types.string,refName:i.types.string}).volatile((()=>({tryReload:void 0}))).actions((e=>({setFeature(t){e.feature=t},setTryReload(t){e.tryReload=t}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((t=>{if(!e.tryReload)return;const n=r.getSession(e),{apolloDataStore:a}=n;if(!a)return;const o=a.getFeature(e.tryReload);o&&(e.setFeature(o),e.setTryReload(),t.dispose())})))}}))),Nn=60;function Fn(e,n,a){const o=[],{cdsLocations:l,strand:s,transcriptParts:i}=n;switch(e){case"genomic":case"cDNA":{const[n]=i;for(const l of n){if("cDNA"===e&&"intron"===l.type)continue;let n=a(l.min,l.max);-1===s&&(n=r.revcom(n));const i="fivePrimeUTR"===l.type||"threePrimeUTR"===l.type?"UTR":l.type,c=o.at(-1);if(c)if(c.type===i){const[e,...a]=c.sequenceLines,o=a.join("")+n;c.sequenceLines=[e,...t.splitStringIntoChunks(o,Nn)],c.locs.push({min:l.min,max:l.max})}else{const e=o.reduce(((e,t)=>e+t.sequenceLines.reduce(((e,t)=>e+t.length),0)),0),a=Nn-e%Nn,r=n.slice(0,a),s=t.splitStringIntoChunks(n.slice(a),Nn);o.push({type:i,sequenceLines:[r,...s],locs:[{min:l.min,max:l.max}]})}else{const e=t.splitStringIntoChunks(n,Nn);o.push({type:i,sequenceLines:e,locs:[{min:l.min,max:l.max}]})}}return o}case"CDS":{let e="";const[n]=l,i=[];for(const t of n){let n=a(t.min,t.max);-1===s&&(n=r.revcom(n)),e+=n,i.push({min:t.min,max:t.max})}const c=t.splitStringIntoChunks(e,Nn);return o.push({type:"CDS",sequenceLines:c,locs:i}),o}case"protein":{let e="";const[n]=l,i=[];for(const t of n){let n=a(t.min,t.max);-1===s&&(n=r.revcom(n)),e+=n,i.push({min:t.min,max:t.max})}let c="";for(let t=0;t<e.length;t+=3){const n=e.slice(t,t+3).toUpperCase();c+=r.defaultCodonTable[n]||"&"}const u=t.splitStringIntoChunks(c,Nn);return o.push({type:"protein",sequenceLines:u,locs:i}),o}}}function kn(e){switch(e){case"upOrDownstream":return"rgb(255,255,255)";case"exon":case"UTR":return"rgb(194,106,119)";case"CDS":return"rgb(93,168,153)";case"intron":return"rgb(187,187,187)";case"protein":return"rgb(148,203,236)"}}function Dn(e){const t=[],n=e.flatMap((e=>e.locs));let[a]=n;for(let e=1;e<n.length;e++)a.min===n[e].max||a.max===n[e].min?a={min:Math.min(a.min,n[e].min),max:Math.max(a.max,n[e].max)}:(t.push(a),a=n[e]);return t.push(a),t}const Rn=v.observer((function({assembly:e,feature:t,refName:n,session:a}){const o=a.apolloDataStore.assemblies.get(e),r=o?.getByRefName(n),{featureTypeOntology:l}=a.apolloDataStore.ontologyManager,s="genomic",i=["genomic","cDNA"],[c,u]=y.useState(i),[d,f]=y.useState(s),[m,g]=y.useState((()=>r?Fn(s,t,((e,t)=>r.getSequence(e,t))):[])),[h,b]=y.useState((()=>Dn(m))),S=p.useTheme(),w=y.useRef(null);if(y.useEffect((()=>{const{cdsLocations:e}=t,[n]=e;u(n.length>0?[...i,"CDS","protein"]:i)}),[t]),!o||!r)return null;const v=o.getByRefName(n);if(!v)return null;if(!l)throw new Error("featureTypeOntology is undefined");return l.isTypeOf(t.type,"transcript")?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.Select,{defaultValue:"genomic",value:d,onChange:function(e){const n=e.target.value;f(n);const a=r?Fn(n,t,((e,t)=>r.getSequence(e,t))):[],o=Dn(a);g(a),b(o)},size:"small"},c.map((e=>de.default.createElement(p.MenuItem,{key:e,value:e},e)))),de.default.createElement(p.Button,{variant:"contained",onClick:()=>{const e=w.current;if(!e)return;const t=new Blob([e.outerText],{type:"text/plain"}),n=new Blob([e.outerHTML],{type:"text/html"}),a=new ClipboardItem({[t.type]:t,[n.type]:n});navigator.clipboard.write([a])},style:{marginLeft:10},size:"medium"},"Copy sequence"),de.default.createElement(p.Paper,{style:{fontFamily:"monospace",padding:S.spacing(),overflowX:"auto"},ref:w},">",v.name,":",h.map((e=>1===t.strand?`${e.min+1}-${e.max}`:`${e.max}-${e.min+1}`)).join(";"),"(",1===t.strand?"+":"-",")",de.default.createElement("br",null),m.map(((e,t)=>de.default.createElement("span",{key:`${e.type}-${t}`,style:{background:kn(e.type),color:S.palette.getContrastText(kn(e.type))}},e.sequenceLines.map(((t,n)=>de.default.createElement(de.default.Fragment,{key:`${t.slice(0,5)}-${n}`},t,n===e.sequenceLines.length-1&&t.length!==Nn?null:de.default.createElement("br",null))))))))):null})),Mn=Ne.default(bn)((()=>({"&.MuiFormControl-root":{marginTop:0,marginBottom:0,width:"100%"},"& .MuiInputBase-input":{fontSize:12,height:20,padding:1,paddingLeft:10}}))),In=Ne.default("div")({display:"flex",justifyContent:"center",alignItems:"center",textAlign:"left",width:"100%",overflowWrap:"break-word",wordWrap:"break-word",wordBreak:"break-all","& span":{fontSize:12}}),Pn=e=>{const{strand:t}=e;return de.default.createElement("div",null,1===t?de.default.createElement(oe.default,null):-1===t?de.default.createElement(De.default,null):de.default.createElement(p.Typography,{component:"span"},"N/A"))},qn=v.observer((function({assembly:e,feature:n,refName:a,session:o}){const{notify:l}=o,s=o.apolloDataStore.assemblies.get(e),i=s?.getByRefName(a),{changeManager:c}=o.apolloDataStore,u=y.useRef(null);function d(n,a,o,r){if(!o.children)throw new Error("Transcript should have child features");for(const[,s]of o.children)if("CDS"===s.type){if(r&&n===s.min){const n=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[s._id],featureId:o._id,oldStart:s.min,newStart:a,assembly:e});return void c.submit(n).catch((()=>{l("Error updating feature start position","error")}))}if(!r&&n===s.max){const n=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[s._id],featureId:o._id,oldEnd:s.max,newEnd:a,assembly:e});return void c.submit(n).catch((()=>{l("Error updating feature start position","error")}))}}}function f(n,a,o,r){if(!o.children)throw new Error("Transcript should have child features");for(const[,s]of o.children)if("exon"===s.type){if(r&&n===s.min){const n=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[s._id],featureId:o._id,oldStart:s.min,newStart:a,assembly:e});return void c.submit(n).catch((()=>{l("Error updating feature start position","error")}))}if(!r&&n===s.max){const n=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[s._id],featureId:o._id,oldEnd:s.max,newEnd:a,assembly:e});return void c.submit(n).catch((()=>{l("Error updating feature start position","error")}))}}}if(!i)return null;const{cdsLocations:m,transcriptExonParts:g,strand:h}=n,[b]=m,S=g.filter((e=>"exon"===e.type)).sort((({min:e},{min:t})=>e-t)),w=S[0]?.min,v=S[S.length-1]?.max;let E=w,C=v;const x=b.length>0;x&&(E=b[0].min,C=b[b.length-1].max);const T=()=>{let e="";const[t]=m;for(const n of t){let t=i.getSequence(n.min,n.max);-1===h&&(t=r.revcom(t)),e+=t}const a=[];for(let t=0;t<e.length;t+=3){const o=e.slice(t,t+3).toUpperCase(),l=r.defaultCodonTable[o]||"&";"ATG"===o?a.push(de.default.createElement(p.Typography,{component:"span",style:{backgroundColor:"yellow",cursor:"pointer",border:"1px solid black"},key:t,onClick:()=>{const e=A(t);e!==E&&d(E,e,n,!0)}},l)):["TAA","TAG","TGA"].includes(o)?a.push(de.default.createElement(p.Typography,{style:{backgroundColor:"red",color:"white"},component:"span",key:t},l)):a.push(de.default.createElement(p.Typography,{component:"span",key:t},l))}return a},A=e=>{const[t]=m;let n=0;for(const a of t){const t=a.max-a.min;if(n+t>e)return a.min+(e-n);n+=t}return E};return de.default.createElement("div",null,x&&de.default.createElement("div",null,de.default.createElement(p.Accordion,{defaultExpanded:!0},de.default.createElement(_n,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel1-content",id:"panel1-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Translation")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(In,null,de.default.createElement(p.Typography,{component:"span",ref:u},T())),de.default.createElement("div",{style:{marginTop:10,display:"flex",flexDirection:"row",alignItems:"center",gap:10}},de.default.createElement(p.Tooltip,{title:"Copy"},de.default.createElement(Fe.default,{style:{fontSize:15,cursor:"pointer"},onClick:()=>{const e=u.current;if(!e)return;const t=new Blob([e.outerText],{type:"text/plain"}),n=new Blob([e.outerHTML],{type:"text/html"}),a=new ClipboardItem({[t.type]:t,[n.type]:n});navigator.clipboard.write([a])}})),de.default.createElement(p.Tooltip,{title:"Trim"},de.default.createElement(ke.default,{style:{fontSize:15,cursor:"pointer"},onClick:()=>{const e=T(),t=e.map((e=>e.props.children)).join("");if(t.startsWith("M")&&t.endsWith("*"))return;const a=[];for(const t of e)a.push({codonGenomicPos:t.key,sequenceLetter:t.props.children});if(0===a.length)return;const o=t.indexOf("M"),r=t.lastIndexOf("*")+1,l=a[o].codonGenomicPos,s=a[r].codonGenomicPos;if(!l||!s)return;const i=A(l),c=(e=>{const[t]=m;let n=0;for(const a of t){const t=a.max-a.min;if(n+t>e)return a.min+(e-n);n+=t}return C})(s);i!==E&&d(E,i,n,!0),c!==C&&setTimeout((()=>{d(C,c,n,!1)}),1e3)}}))))),de.default.createElement(p.Grid2,{container:!0,justifyContent:"center",alignItems:"center",style:{textAlign:"center",marginTop:10}},de.default.createElement(p.Grid2,{size:1}),de.default.createElement(p.Grid2,{size:4},de.default.createElement(Mn,{margin:"dense",variant:"outlined",value:E,onChangeCommitted:e=>{d(E,e,n,!0)}})),de.default.createElement(p.Grid2,{size:2},de.default.createElement(p.Typography,{component:"span"},"CDS")),de.default.createElement(p.Grid2,{size:4},de.default.createElement(Mn,{margin:"dense",variant:"outlined",value:C,onChangeCommitted:e=>{d(C,e,n,!1)}})),de.default.createElement(p.Grid2,{size:1}))),de.default.createElement("div",{style:{marginTop:5}},g.map(((e,t)=>de.default.createElement("div",{key:t},"exon"===e.type&&de.default.createElement(p.Grid2,{container:!0,justifyContent:"center",alignItems:"center",style:{textAlign:"center"}},de.default.createElement(p.Grid2,{size:1},0!==t&&((e,t)=>{let n="";if(t>0){const a=g[t-1];1===h?"intron"===a.type&&(n=i.getSequence(e.min-2,e.min)):"intron"===a.type&&(n=r.revcom(i.getSequence(e.max,e.max+2)))}return[{spliceSite:n,color:"AG"===n?"green":"red"}]})(e,t).map(((e,t)=>de.default.createElement(p.Typography,{key:t,component:"span",color:e.color},e.spliceSite)))),de.default.createElement(p.Grid2,{size:4,style:{padding:0}},de.default.createElement(Mn,{margin:"dense",variant:"outlined",value:e.min,onChangeCommitted:t=>{f(e.min,t,n,!0)}})),de.default.createElement(p.Grid2,{size:2},de.default.createElement(Pn,{strand:n.strand})),de.default.createElement(p.Grid2,{size:4,style:{padding:0}},de.default.createElement(Mn,{margin:"dense",variant:"outlined",value:e.max,onChangeCommitted:t=>{f(e.max,t,n,!1)}})),de.default.createElement(p.Grid2,{size:1},t!==g.length-1&&((e,t)=>{let n="";if(t<g.length-1){const a=g[t+1];1===h?"intron"===a.type&&(n=i.getSequence(e.max,e.max+2)):"intron"===a.type&&(n=r.revcom(i.getSequence(e.min-2,e.min)))}return[{spliceSite:n,color:"GT"===n?"green":"red"}]})(e,t).map(((e,t)=>de.default.createElement(p.Typography,{key:t,component:"span",color:e.color},e.spliceSite))))))))))})),Ln=Ne.default(p.TableCell)((()=>({fontWeight:"bold"}))),Bn=v.observer((function(e){const{feature:t}=e,n=_e(t),a=Ue(t);return de.default.createElement(p.Table,{size:"small",sx:{fontSize:"0.75rem","& .MuiTableCell-root":{padding:"4px"}}},de.default.createElement(p.TableBody,null,""!==n&&de.default.createElement(p.TableRow,null,de.default.createElement(Ln,null,"Name"),de.default.createElement(p.TableCell,null,_e(t))),""!==a&&de.default.createElement(p.TableRow,null,de.default.createElement(Ln,null,"ID"),de.default.createElement(p.TableCell,null,Ue(t))),de.default.createElement(p.TableRow,null,de.default.createElement(Ln,null,"Location"),de.default.createElement(p.TableCell,null,e.refName,":",t.min,"..",t.max)),de.default.createElement(p.TableRow,null,de.default.createElement(Ln,null,"Strand"),de.default.createElement(p.TableCell,null,1===(o=t.strand)?"Forward":-1===o?"Reverse":""))));var o})),On=b.makeStyles()((e=>({root:{padding:e.spacing(2)}}))),_n=Ne.default(p.AccordionSummary)((()=>({minHeight:30,maxHeight:30,"&.Mui-expanded":{minHeight:30,maxHeight:30}})));function Un(e){return null}const $n=v.observer((function(e){const{classes:t}=On(),n=["summary","location","attrs"],[a,o]=y.useState(n),{model:l}=e,{assembly:s,feature:c,refName:u}=l;y.useEffect((()=>{o(n)}),[c]);const d=r.getSession(l),{pluginManager:f}=r.getEnv(d),m=r.getSession(l),g=m.apolloDataStore.assemblies.get(s),{internetAccounts:h}=i.getRoot(d),b=h.find((e=>"ApolloInternetAccount"===e.type)),S=["admin","user"].includes((b?b.role:"admin")??"");if(!c||!g)return null;const w=g.getByRefName(u);if(!w)return null;const{max:v,min:E}=c;function C(e,t){o(e?[...a,t]:a.filter((e=>e!==t)))}w.getSequence(E,v)||m.apolloDataStore.loadRefSeq([{assemblyName:s,refName:u,start:E,end:v}]);const x=f.evaluateExtensionPoint("Apollo-TranscriptDetailsCustomComponent",Un,e);return de.default.createElement("div",{className:t.root},de.default.createElement(p.Accordion,{expanded:a.includes("summary"),onChange:(e,t)=>{C(t,"summary")}},de.default.createElement(_n,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel1-content",id:"panel1-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Summary")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(Bn,{feature:c,refName:u}))),de.default.createElement(x,{session:d,feature:c}),de.default.createElement(p.Accordion,{style:{marginTop:5},expanded:a.includes("location"),onChange:(e,t)=>{C(t,"location")}},de.default.createElement(_n,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel2-content",id:"panel2-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Location")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(qn,{feature:c,refName:u,session:m,assembly:g._id||""}))),de.default.createElement(p.Accordion,{style:{marginTop:5},expanded:a.includes("attrs"),onChange:(e,t)=>{C(t,"attrs")}},de.default.createElement(_n,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel3-content",id:"panel3-header"},de.default.createElement("div",{style:{display:"flex",alignItems:"center"}},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Attributes"," "),de.default.createElement(p.Tooltip,{title:"Separate multiple values for the attribute with commas"},de.default.createElement(le.default,{style:{color:"white",fontSize:15,marginLeft:10}})))),de.default.createElement(p.AccordionDetails,null,de.default.createElement(yn,{feature:c,session:m,assembly:g._id||"",editable:S}))),de.default.createElement(p.Accordion,{style:{marginTop:5},expanded:a.includes("sequence"),onChange:(e,t)=>{C(t,"sequence")}},de.default.createElement(_n,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel4-content",id:"panel4-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Sequence")),de.default.createElement(p.AccordionDetails,null,a.includes("sequence")&&de.default.createElement(Rn,{feature:c,session:m,assembly:g._id||"",refName:u}))))})),jn=a.ConfigurationSchema("LinearApolloDisplay",{},{explicitIdentifier:"displayId",explicitlyTyped:!0}),Gn=b.makeStyles()({highlighted:{background:"orange"}}),Wn=({highlight:e,text:t})=>{const{classes:n}=Gn();if(!e)return de.default.createElement(de.default.Fragment,null,t);const a=t.split(e);if(1===a.length)return de.default.createElement(de.default.Fragment,null,t);const o=[];for(let t=0;t<a.length-1;t++)o.push(a[t],de.default.createElement("span",{className:n.highlighted},e));return de.default.createElement(de.default.Fragment,null,o,a.at(-1))},Hn=v.observer((function({feature:e,filterText:t}){const n=[...e.attributes.entries()].map((([e,t])=>{if(e.startsWith("gff_")){const n=e.slice(4);return[n.charAt(0).toUpperCase()+n.slice(1),i.getSnapshot(t)]}return"_id"===e?["ID",i.getSnapshot(t)]:[e,i.getSnapshot(t)]})).filter((([e])=>e)).map((([e,t])=>`${e}=${Array.isArray(t)?t.join(", "):t}`)).join(", ");return de.default.createElement(Wn,{text:n,highlight:t})})),zn=b.makeStyles()((e=>({inputWrapper:{position:"relative"},hiddenWidthSpan:{padding:e.spacing(.5),color:"transparent"},numberTextInput:{border:"none",background:"inherit",font:"inherit",position:"absolute",width:"100%",left:0}}))),Jn=v.observer((function({initialValue:e,notifyError:t,onChangeCommitted:n}){const[a,o]=y.useState(e),[r,l]=y.useState(!1),[s,i]=y.useState(null),{classes:c}=zn();return y.useEffect((()=>{e!==a&&o(e)}),[e]),y.useEffect((()=>{r&&(s?.blur(),l(!1))}),[r,s]),de.default.createElement("span",{className:c.inputWrapper},de.default.createElement("span",{className:c.hiddenWidthSpan,"aria-hidden":!0},a),de.default.createElement("input",{type:"text",value:a,className:c.numberTextInput,onChange:function(e){const t=Number(e.target.value);Number.isNaN(t)||o(t)},onKeyDown:t=>{"Enter"===t.key?s?.blur():"Escape"===t.key&&(o(e),l(!0))},onBlur:()=>{a!==e&&n(a).catch(t)},ref:e=>{i(e)}}))})),Vn=b.makeStyles()((e=>({typeContent:{display:"inline-block",width:"174px",height:"100%",cursor:"text"},feature:{td:{position:"relative",verticalAlign:"top",paddingLeft:"0.5em"}},arrow:{display:"inline-block",width:"1.6em",textAlign:"center",cursor:"pointer"},arrowExpanded:{transform:"rotate(90deg)"},hoveredFeature:{backgroundColor:e.palette.action.hover},typeInputElement:{border:"none",background:"none"},typeErrorMessage:{color:"red"}})));function Xn(e,t){const{changeManager:n,getAssemblyId:a,regions:o,selectedFeature:l,session:s,setSelectedFeature:c}=e;return function(e,t,n,a,o,l,s){const c=function(e){const{internetAccounts:t}=i.getParent(e);return t.find((e=>"ApolloInternetAccount"===e.type))}(l),u=c?c.role:"admin",d="admin"===u,f=!(u&&["admin","user"].includes(u)),m=[];if(e){const i=n(t.assemblyName),u=n(t.assemblyName);m.push({label:"Edit feature details",onClick:()=>{const n=l.addWidget("ApolloFeatureDetailsWidget","apolloFeatureDetailsWidget",{feature:e,assembly:u,refName:t.refName});l.showWidget(n)}},{label:"Add child feature",disabled:f,onClick:()=>{l.queueDialog((t=>[Et,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:i,internetAccount:c}]))}},{label:"Copy features and annotations",disabled:f,onClick:()=>{l.queueDialog((t=>[Nt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:u}]))}},{label:"Delete feature",disabled:!d,onClick:()=>{l.queueDialog((t=>[kt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:u,selectedFeature:a,setSelectedFeature:o}]))}});const{featureTypeOntology:g}=l.apolloDataStore.ontologyManager;if(!g)throw new Error("featureTypeOntology is undefined");(g.isTypeOf(e.type,"transcript")||g.isTypeOf(e.type,"pseudogenic_transcript"))&&r.isSessionModelWithWidgets(l)&&m.push({label:"Edit transcript details",onClick:()=>{const n=l.addWidget("ApolloTranscriptDetails","apolloTranscriptDetails",{feature:e,assembly:u,changeManager:s,refName:t.refName});l.showWidget(n)}})}return m}(t,o[0],a,l,c,s,n)}function Kn(e){let t=e;for(;t.parent;)t=t.parent;return t}const Yn=v.observer((function e({depth:n,feature:a,isHovered:o,isSelected:r,model:l,selectedFeatureClass:s,setContextMenu:i}){const{classes:c}=Vn(),{apolloHover:u,changeManager:d,selectedFeature:f,session:m,tabularEditor:g}=l,{featureCollapsed:p,filterText:h}=g,{_id:y,children:b,max:S,min:w,strand:v,type:E}=a,C=!p.get(y),x=e=>{m.notify(e.message,"error")};return de.default.createElement(de.default.Fragment,null,de.default.createElement("tr",{onMouseEnter:e=>{l.setApolloHover({feature:a,topLevelFeature:Kn(a),glyph:l.getGlyph(Kn(a))})},className:c.feature+(r?` ${s}`:o?` ${c.hoveredFeature}`:""),onClick:e=>{e.stopPropagation(),l.setSelectedFeature(a)},onContextMenu:e=>(e.preventDefault(),i({position:{left:e.clientX+2,top:e.clientY-6},items:Xn(l,a)}),!1)},de.default.createElement("td",{style:{whiteSpace:"nowrap",borderLeft:2*n+"em solid transparent"}},b?.size?de.default.createElement("div",{onClick:e=>{e.stopPropagation(),g.setFeatureCollapsed(y,C)},className:c.arrow+(C?` ${c.arrowExpanded}`:"")},"❯"):null,de.default.createElement("div",{className:c.typeContent},de.default.createElement(vt,{session:m,ontologyName:"Sequence Ontology",style:{width:170},value:E,filterTerms:bt,fetchValidTerms:Zn.bind(null,a),renderInput:e=>de.default.createElement("div",{ref:e.InputProps.ref},de.default.createElement("input",{type:"text",...e.inputProps,className:c.typeInputElement,style:{width:170}}),e.error?de.default.createElement("div",{className:c.typeErrorMessage},e.errorMessage??"unknown error"):null),onChange:(e,n)=>{n&&function(e,n,a,o){const r=n._id,l=new t.TypeChange({typeName:"TypeChange",changedIds:[r],featureId:r,oldType:String(a),newType:String(o),assembly:n.assemblyId});return e.submit(l)}(d,a,e,n).catch(x)}}))),de.default.createElement("td",null,de.default.createElement(Jn,{initialValue:w+1,notifyError:x,onChangeCommitted:e=>function(e,n,a,o){const r=n._id,l=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[r],featureId:r,oldStart:a,newStart:o,assembly:n.assemblyId});return e.submit(l)}(d,a,w,e-1)})),de.default.createElement("td",null,de.default.createElement(Jn,{initialValue:S,notifyError:x,onChangeCommitted:e=>function(e,n,a,o){const r=n._id,l=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[r],featureId:r,oldEnd:a,newEnd:o,assembly:n.assemblyId});return e.submit(l)}(d,a,S,e)})),de.default.createElement("td",null,1===v?"+":-1===v?"-":void 0),de.default.createElement("td",null,de.default.createElement(Hn,{filterText:h,feature:a}))),C&&b?[...b.entries()].filter((e=>{if(!h)return!0;const[,t]=e;return JSON.stringify(t).includes(h)})).map((([t,a])=>de.default.createElement(e,{isHovered:u?.feature._id===a._id,isSelected:f?._id===a._id,selectedFeatureClass:s,key:t,depth:(n||0)+1,feature:a,model:l,setContextMenu:i}))):null)}));async function Zn(e,t,n){const{parent:a}=e;if(a){const e=(await t.getTermsWithLabelOrSynonym(a.type,{includeSubclasses:!1})).filter(bt);if(e.length>0)return await t.getClassesThat("part_of",e)}}const Qn=b.makeStyles()((e=>({scrollableTable:{width:"100%",height:"100%",th:{position:"sticky",top:0,zIndex:2,textAlign:"left",background:e.palette.background.paper,paddingTop:"3.2em"},td:{whiteSpace:"normal"}},selectedFeature:{backgroundColor:e.palette.action.selected}}))),ea=v.observer((function({model:e}){const{apolloHover:t,seenFeatures:n,selectedFeature:a,tabularEditor:o}=e,r=p.useTheme(),{classes:l}=Qn(),s=y.useRef(null),[i,c]=y.useState(null),{filterText:u}=o;return y.useEffect((()=>{const e=s.current;if(e&&a){const t=e.querySelector(`.${l.selectedFeature}`);if(t){const n=e.scrollTop,a=t.offsetTop-25;a>n&&a<n+e.offsetHeight||e.scroll({top:a-40,behavior:"smooth"})}}}),[a,n,l.selectedFeature]),de.default.createElement("div",{ref:s,style:{width:"100%",overflowY:"auto",height:"100%"}},de.default.createElement("table",{className:l.scrollableTable},de.default.createElement("thead",null,de.default.createElement("tr",null,de.default.createElement("th",null,"Type"),de.default.createElement("th",null,"Start"),de.default.createElement("th",null,"End"),de.default.createElement("th",null,"Strand"),de.default.createElement("th",null,"Attributes"))),de.default.createElement("tbody",null,[...n.entries()].filter((e=>{if(!u)return!0;const[,t]=e;return JSON.stringify(t).includes(u)})).sort(((e,t)=>e[1].min-t[1].min)).map((([n,o])=>de.default.createElement(Yn,{key:n,isSelected:a?._id===n,isHovered:t?.feature._id===n,selectedFeatureClass:l.selectedFeature,feature:o,model:e,depth:0,setContextMenu:c}))))),de.default.createElement(S.Menu,{open:Boolean(i),onMenuItemClick:(e,t)=>{t(),c(null)},onClose:()=>{c(null)},TransitionProps:{onExit:()=>{c(null)}},style:{zIndex:r.zIndex.tooltip},menuItems:i?.items??[],anchorReference:"anchorPosition",anchorPosition:i?.position}))})),ta=b.makeStyles()({toolbar:{width:"100%",display:"flex",paddingRight:"2em",flexDirection:"row",justifyContent:"space-between",position:"absolute",zIndex:4},filterText:{}}),na=v.observer((function({model:e}){const t=e.tabularEditor,{classes:n}=ta();return de.default.createElement("div",{className:n.toolbar},de.default.createElement(p.Tooltip,{title:"Collapse all"},de.default.createElement(p.IconButton,{"aria-label":"collapse",sx:{marginTop:0},onClick:t.collapseAllFeatures},de.default.createElement(Me.default,null))),de.default.createElement(p.TextField,{className:n.filterText,label:"Filter features",value:t.filterText,sx:{marginTop:0},variant:"outlined",onChange:e=>{t.setFilterText(e.target.value)},slotProps:{input:{endAdornment:de.default.createElement(p.InputAdornment,{position:"end"},de.default.createElement(p.IconButton,{onClick:()=>{t.clearFilterText()}},de.default.createElement(Re.default,null)))}}}))}));function aa(e){e.stopPropagation()}const oa=v.observer((function({model:e}){return e.tabularEditor.isShown?de.default.createElement("div",{onMouseDown:aa,onClick:aa,style:{width:"100%",height:"100%",position:"relative"}},de.default.createElement(na,{model:e}),de.default.createElement(ea,{model:e})):null})),ra=i.types.model("TabularEditor",{isShown:!0,featureCollapsed:i.types.map(i.types.boolean),filterText:""}).actions((e=>({setFeatureCollapsed(t,n){e.featureCollapsed.set(t,n)},setFilterText(t){e.filterText=t},clearFilterText(){e.filterText=""},collapseAllFeatures(){const t=i.getParent(e);for(const[n]of t.seenFeatures.entries())e.featureCollapsed.set(n,!0)},togglePane(){e.isShown=!e.isShown},hidePane(){e.isShown=!1},showPane(){e.isShown=!0}})));function la(e,t){return Boolean(t&&e._id===t._id)}function sa(e,t){return t?e?.palette.text.primary??"black":e?.palette.background.default??"white"}function ia(e,t,n,a,o,r){e.fillStyle=r,e.fillRect(t,n,a,o)}function ca(e,t,n){const{refName:a,regionNumber:o,x:r}=e,{lgv:l}=n,{offsetPx:s}=l,i=l.bpToPx({refName:a,coord:t.min,regionNumber:o}),c=l.bpToPx({refName:a,coord:t.max,regionNumber:o});if(void 0!==i&&void 0!==c){const e=i.offsetPx-s,t=c.offsetPx-s;if(Math.abs(t-e)<8)return;if(Math.abs(e-r)<4)return"min";if(Math.abs(t-r)<4)return"max"}}const ua={draw:function(e,t,n,a,o){const{apolloRowHeight:r,lgv:l,session:s,theme:i}=a,{bpPerPx:c,displayedRegions:u,offsetPx:d}=l,f=u[o],m=(l.bpToPx({refName:f.refName,coord:t.min,regionNumber:o})?.offsetPx??0)-d,{reversed:g}=f,{apolloSelectedFeature:p}=s,h=t.length/c,y=g?m-h:m,b=n*r,S=la(t,p),w=sa(i,S),v=function(e,t){return t?e?.palette.getContrastText(sa(e,t))??"white":e?.palette.text.primary??"black"}(i,S);!function(e,t,n,a,o,r){ia(e,t,n,a,o,r),a<=2||e.clearRect(t+1,n+1,a-2,o-2)}(e,y,b,h,r,v),h<=2||(function(e,t,n,a,o,r){ia(e,t+1,n+1,a-2,o-2,r)}(e,y,b,h,r,w),function(e,t,n,a,o,r){e.fillStyle=o;const l=Math.max(t+1,0);e.fillText(r,l,n+11,t-1+a-l)}(e,y,b,h,v,t.type))},drawDragPreview:function(e,t){const{apolloDragging:n,apolloRowHeight:a,lgv:o,theme:r}=e,{bpPerPx:l,displayedRegions:s,offsetPx:i}=o;if(!n)return;const{current:c,edge:u,feature:d,start:f}=n,m=Math.floor(f.y/a),g=s[f.regionNumber],h=(g.reversed?g.end-d[u]:d[u]-g.start)/l-i,y=Math.min(c.x,h),b=m*a,S=Math.abs(c.x-h),w=1*a;t.strokeStyle=r?.palette.info.main??"rgb(255,0,0)",t.setLineDash([6]),t.strokeRect(y,b,S,w),t.fillStyle=p.alpha(r?.palette.info.main??"rgb(255,0,0)",.2),t.fillRect(y,b,S,w)},drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,theme:r}=e;if(!n)return;const{feature:l}=n,s=e.getFeatureLayoutPosition(l);if(!s)return;const{bpPerPx:i,displayedRegions:c,offsetPx:u}=o,{layoutIndex:d,layoutRow:f}=s,m=c[d],{refName:g,reversed:p}=m,{length:h,max:y,min:b}=l,S=(o.bpToPx({refName:g,coord:p?y:b,regionNumber:d})?.offsetPx??0)-u,w=f*a,v=h/i;t.fillStyle=r?.palette.action.focus??"rgba(0,0,0,0.04)",t.fillRect(S,w,v,a)},drawTooltip:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,theme:r}=e;if(!n)return;const{feature:l}=n,s=e.getFeatureLayoutPosition(l);if(!s)return;const{featureRow:i,layoutIndex:c,layoutRow:u}=s,{bpPerPx:d,displayedRegions:f,offsetPx:m}=o,g=f[c],{refName:h,reversed:y}=g;let b="Loc: ";const{length:S,max:w,min:v}=l;b+=`${v+1}–${w}`;let E=(o.bpToPx({refName:h,coord:y?w:v,regionNumber:c})?.offsetPx??0)-m;const C=(u+i)*a,x=S/d,T=`Type: ${l.type}`,{attributes:A}=l,N=A.get("gff_name")?.find((e=>""!==e)),F=[t.measureText(T).width,t.measureText(b).width];N&&F.push(t.measureText(`Name: ${N}`).width);const k=Math.max(...F);E=E+x+5,t.fillStyle=p.alpha(r?.palette.text.primary??"rgb(1, 1, 1)",.7),t.fillRect(E,C,k+4,3===F.length?45:35),t.beginPath(),t.moveTo(E,C),t.lineTo(E-5,C+5),t.lineTo(E,C+10),t.fill(),t.fillStyle=r?.palette.background.default??"rgba(255, 255, 255)";let D=C+12;t.fillText(T,E+2,D),N&&(D+=12,t.fillText(`Name: ${N}`,E+2,D)),D+=12,t.fillText(b,E+2,D)},getContextMenuItems:function(e){const{apolloHover:t,apolloInternetAccount:n,changeManager:a,regions:o,selectedFeature:l,session:s}=e,i=[];if(!t)return i;const{feature:c}=t,u=n?n.role:"admin",d="admin"===u,f=!(u&&["admin","user"].includes(u)),[m]=o,g=e.getAssemblyId(m.assemblyName),p=e.getAssemblyId(m.assemblyName);i.push({label:"Add child feature",disabled:f,onClick:()=>{s.queueDialog((e=>[Et,{session:s,handleClose:()=>{e()},changeManager:a,sourceFeature:c,sourceAssemblyId:g,internetAccount:n}]))}},{label:"Copy features and annotations",disabled:f,onClick:()=>{s.queueDialog((e=>[Nt,{session:s,handleClose:()=>{e()},changeManager:a,sourceFeature:c,sourceAssemblyId:p}]))}},{label:"Delete feature",disabled:!d,onClick:()=>{s.queueDialog((t=>[kt,{session:s,handleClose:()=>{t()},changeManager:a,sourceFeature:c,sourceAssemblyId:p,selectedFeature:l,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}},{label:"Edit feature details",onClick:()=>{const e=s.addWidget("ApolloFeatureDetailsWidget","apolloFeatureDetailsWidget",{feature:c,assembly:p,refName:m.refName});s.showWidget(e)}});const{featureTypeOntology:h}=s.apolloDataStore.ontologyManager;if(!h)throw new Error("featureTypeOntology is undefined");return(h.isTypeOf(c.type,"transcript")||h.isTypeOf(c.type,"pseudogenic_transcript"))&&r.isSessionModelWithWidgets(s)&&i.push({label:"Edit transcript details",onClick:()=>{const e=s.addWidget("ApolloTranscriptDetails","apolloTranscriptDetails",{feature:c,assembly:p,changeManager:a,refName:m.refName});s.showWidget(e)}}),i},getFeatureFromLayout:function(e,t,n){return e},getRowCount:function(e){return 1},getRowForFeature:function(e,t){return 0},onMouseDown:function(e,t,n){const{featureAndGlyphUnderMouse:a}=t,{feature:o}=a,r=ca(t,o,e);r&&(n.stopPropagation(),e.startDrag(t,o,r))},onMouseLeave:function(){},onMouseMove:function(e,t){if(Ga(t)){const{featureAndGlyphUnderMouse:n}=t;e.setApolloHover(n);const{feature:a}=n;if(ca(t,a,e))return void e.setCursor("col-resize")}e.setCursor()},onMouseUp:function(e,t){if(e.apolloDragging)return;const{featureAndGlyphUnderMouse:n}=t;n?.feature&&e.setSelectedFeature(n.feature)}};let da=null,fa=null,ma=null,ga=null;if("document"in globalThis)for(const e of["forward","backward"])for(const t of["light","dark"]){const n=document.createElement("canvas"),a=10;n.width=n.height=a;const o=n.getContext("2d");if(o){const r="light"===t?"rgba(0,0,0,0)":"rgba(0,0,0,0.75)",l="light"===t?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.50)",s="forward"===e?o.createLinearGradient(0,a,a,0):o.createLinearGradient(0,0,a,a);s.addColorStop(0,r),s.addColorStop(.25,r),s.addColorStop(.25,l),s.addColorStop(.5,l),s.addColorStop(.5,r),s.addColorStop(.75,r),s.addColorStop(.75,l),s.addColorStop(1,l),o.fillStyle=s,o.fillRect(0,0,10,10),"forward"===e?"light"===t?da=o.createPattern(n,"repeat"):ma=o.createPattern(n,"repeat"):"light"===t?fa=o.createPattern(n,"repeat"):ga=o.createPattern(n,"repeat")}}function pa(e,t,n,a,o,r,l,s,i){const{apolloRowHeight:c,lgv:u,session:d,theme:f}=t,{bpPerPx:m,displayedRegions:g,offsetPx:p}=u,h=g[n],{refName:y,reversed:b}=h,{apolloSelectedFeature:S}=d,w=(u.bpToPx({refName:y,coord:o.min,regionNumber:n})?.offsetPx??0)-p,v=o.length/m,E=b?w-v:w,C=(a+r)*c,x=Math.round(.6*c),T=C+(c-x)/2;if(e.fillStyle=f?.palette.text.primary??"black",e.fillRect(E,T,v,x),v>2&&(e.clearRect(E+1,T+1,v-2,x-2),e.fillStyle=S&&o._id===S._id?"rgb(0,0,0)":"rgb(211,211,211)",e.fillRect(E+1,T+1,v-2,x-2),s&&i&&l)){const t=b?-1:1,[n,a]=l*t==1?[s,i]:[i,s];e.fillStyle=n,e.fillRect(E+1,T+1,v-2,(x-2)/2),e.fillStyle=a,e.fillRect(E+1,T+1+(x-2)/2,v-2,(x-2)/2)}}function ha(e,t,n,a,o,r){const{apolloRowHeight:l,lgv:s,theme:i}=t,{bpPerPx:c,displayedRegions:u,offsetPx:d}=s,f=u[n],{refName:m,reversed:g}=f,p=(s.bpToPx({refName:m,coord:o.min,regionNumber:n})?.offsetPx??0)-d,h=o.length/c,y=g?p-h:p,b=Math.round((r+.5)*l)+a*l;e.strokeStyle=i?.palette.text.primary??"black",e.beginPath(),e.moveTo(y,b),e.lineTo(y+h,b),e.stroke()}function ya(e,t){const{children:n,type:a}=e;if(!n)return 0;let o=0;if(t.isTypeOf(a,"transcript"))for(const[,e]of n)t.isTypeOf(e.type,"CDS")&&(o+=1);return o}function ba(e,t,n){const{children:a,type:o}=e;if(!a)return 1;let r=0;if(t.isTypeOf(o,"transcript")||t.isTypeOf(o,"pseudogenic_transcript")){for(const[,e]of a)t.isTypeOf(e.type,"CDS")&&(r+=1);return 0===r?1:r}for(const[,e]of a)r+=ba(e,t);return r}function Sa(e,t){if(!t.isTypeOf(e.type,"gene")&&!t.isTypeOf(e.type,"pseudogene"))throw new Error('Top level feature for GeneGlyph must have type "gene"');const{children:n}=e;if(!n)return[[e]];const a=[];for(const[,o]of n){if(!t.isTypeOf(o.type,"transcript")&&!t.isTypeOf(o.type,"pseudogenic_transcript")){a.push([o,e]);continue}if(!o.children)continue;const n=[],r=[];for(const[,e]of o.children)t.isTypeOf(e.type,"CDS")?n.push(e):t.isTypeOf(e.type,"exon")&&r.push(e);for(const t of n)a.push([t,...r,o,e]);0===n.length&&a.push([...r,o,e])}return a}function wa(e,t,n){const{session:a}=n,{apolloDataStore:o}=a,{featureTypeOntology:l}=o.ontologyManager;if(!l)throw new Error("featureTypeOntology is undefined");const s=l.isTypeOf(t.type,"gene")||l.isTypeOf(t.type,"pseudogene"),i=l.isTypeOf(t.type,"transcript")||l.isTypeOf(t.type,"pseudogenic_transcript"),c=l.isTypeOf(t.type,"CDS");if(s||i)return;const{bp:u,refName:d,regionNumber:f,x:m}=e,{lgv:g}=n,{offsetPx:p}=g,h=g.bpToPx({refName:d,coord:t.min,regionNumber:f}),y=g.bpToPx({refName:d,coord:t.max,regionNumber:f});if(void 0===h||void 0===y)return;const b=h.offsetPx-p,S=y.offsetPx-p;if(!(Math.abs(S-b)<8)){if(Math.abs(b-m)<4)return{feature:t,edge:"min"};if(Math.abs(S-m)<4)return{feature:t,edge:"max"};if(c){const e=t.parent;if(!e?.children)return;const n=[];for(const t of e.children.values())l.isTypeOf(t.type,"exon")&&n.push(t);const a=n.find((e=>{const[t,n]=r.intersection2(u-1,u,e.min,e.max);return void 0!==t&&void 0!==n}));if(!a)return;const o=g.bpToPx({refName:d,coord:a.min,regionNumber:f}),s=g.bpToPx({refName:d,coord:a.max,regionNumber:f});if(void 0===o||void 0===s)return;const i=o.offsetPx-p,c=s.offsetPx-p;if(Math.abs(c-i)<8)return;if(Math.abs(i-m)<4)return{feature:a,edge:"min"};if(Math.abs(c-m)<4)return{feature:a,edge:"max"}}}}const{drawTooltip:va,getContextMenuItems:Ea,onMouseLeave:Ca}=ua,xa={draw:function(e,t,n,a,o){const{apolloRowHeight:l,lgv:s,session:i,theme:c}=a,{bpPerPx:u,displayedRegions:d,offsetPx:f}=s,m=d[o],{refName:g,reversed:h}=m,y=l,b=Math.round(.9*y),{children:S,min:w,strand:v}=t;if(!S)return;const{apolloSelectedFeature:E}=i,{apolloDataStore:C}=i,{featureTypeOntology:x}=C.ontologyManager;if(!x)throw new Error("featureTypeOntology is undefined");const T=(s.bpToPx({refName:g,coord:w,regionNumber:o})?.offsetPx??0)-f,A=t.length/u,N=h?T-A:T,F=n*y,k=ba(t,x)*y;e.fillStyle=p.alpha(c?.palette.background.paper??"#ffffff",.6),e.fillRect(N,F,A,k);let D=0;for(const[,t]of S){if(!x.isTypeOf(t.type,"transcript")&&!x.isTypeOf(t.type,"pseudogenic_transcript")){D+=1;continue}const{children:r}=t;if(!r)continue;const l=ya(t,x);for(const[,l]of r)x.isTypeOf(l.type,"CDS")&&(ha(e,a,o,n,t,D),D+=1);0===l&&(ha(e,a,o,n,t,D),D+=1)}const R="dark"===c?.palette.mode?ma:da,M="dark"===c?.palette.mode?ga:fa;D=0;for(const[,t]of S){if(!x.isTypeOf(t.type,"transcript")&&!x.isTypeOf(t.type,"pseudogenic_transcript")){ua.draw(e,t,n,a,o),D+=1;continue}const l=ya(t,x);if(0!=l)for(const l of t.cdsLocations){const{_id:i,children:d}=t;if(d){for(const[,t]of d)x.isTypeOf(t.type,"exon")&&pa(e,a,o,n,t,D,v,R,M);for(const a of l){const l=(a.max-a.min)/u,d=(s.bpToPx({refName:g,coord:a.min,regionNumber:o})?.offsetPx??0)-f,m=h?d-l:d;e.fillStyle=c?.palette.text.primary??"black";const p=(n+D)*y+(y-b)/2;if(e.fillRect(m,p,l,b),l>2){e.clearRect(m+1,p+1,l-2,b-2);const n=r.getFrame(a.min,a.max,t.strand??1,a.phase),o=c?.palette.framesCDS.at(n)?.main;if(e.fillStyle=E&&i===E._id?"rgb(0,0,0)":o??"rgb(171,71,188)",e.fillRect(m+1,p+1,l-2,b-2),R&&M&&v){const t=h?-1:1,[n,a]=v*t==1?[R,M]:[M,R];e.fillStyle=n,e.fillRect(m+1,p+1,l-2,(b-2)/2),e.fillStyle=a,e.fillRect(m+1,p+(b-2)/2,l-2,(b-2)/2)}}}D+=1}}const{children:i}=t;if(0===l&&i){for(const[,t]of i)x.isTypeOf(t.type,"exon")&&pa(e,a,o,n,t,D,v,R,M);D+=1}}},drawDragPreview:function(e,t){const{apolloDragging:n,apolloRowHeight:a,lgv:o,theme:r}=e,{bpPerPx:l,displayedRegions:s,offsetPx:i}=o;if(!n)return;const{current:c,edge:u,feature:d,start:f}=n,m=Math.floor(f.y/a),g=s[f.regionNumber],h=(g.reversed?g.end-d[u]:d[u]-g.start)/l-i,y=Math.min(c.x,h),b=m*a,S=Math.abs(c.x-h),w=1*a;t.strokeStyle=r?.palette.info.main??"rgb(255,0,0)",t.setLineDash([6]),t.strokeRect(y,b,S,w),t.fillStyle=p.alpha(r?.palette.info.main??"rgb(255,0,0)",.2),t.fillRect(y,b,S,w)},drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,session:r,theme:l}=e,{featureTypeOntology:s}=r.apolloDataStore.ontologyManager;if(!n)return;const{feature:i}=n,c=e.getFeatureLayoutPosition(i);if(!c)return;const{bpPerPx:u,displayedRegions:d,offsetPx:f}=o,{featureRow:m,layoutIndex:g,layoutRow:p}=c,h=d[g],{refName:y,reversed:b}=h,{length:S,max:w,min:v}=i,E=(o.bpToPx({refName:y,coord:b?w:v,regionNumber:g})?.offsetPx??0)-f,C=(p+m)*a,x=S/u;if(t.fillStyle=l?.palette.action.selected??"rgba(0,0,0,04)",!s)throw new Error("featureTypeOntology is undefined");t.fillRect(E,C,x,a*ba(i,s))},drawTooltip:va,getContextMenuItems:Ea,getFeatureFromLayout:function(e,t,n,a){const o=Sa(e,a)[n]||[];for(const e of o){let n;if(t>=e.min&&t<=e.max&&e.parent&&(n=e),n){if(a.isTypeOf(n.type,"CDS")&&n.parent&&(a.isTypeOf(n.parent.type,"transcript")||a.isTypeOf(n.parent.type,"pseudogenic_transcript"))){const{cdsLocations:e}=n.parent;for(const a of e)for(const e of a)if(t>=e.min&&t<=e.max)return n;return n.parent}return n}}return e},getRowCount:ba,getRowForFeature:function(e,t,n){const a=Sa(e,n);for(const[e,n]of a.entries())if(n.some((e=>e._id===t._id)))return e},onMouseDown:function(e,t,n){const{featureAndGlyphUnderMouse:a}=t,{feature:o}=a,r=wa(t,o,e);r&&(n.stopPropagation(),e.startDrag(t,r.feature,r.edge))},onMouseLeave:Ca,onMouseMove:function(e,t){if(Ga(t)){const{featureAndGlyphUnderMouse:n}=t;e.setApolloHover(n);const{feature:a}=n;if(wa(t,a,e))return void e.setCursor("col-resize")}e.setCursor()},onMouseUp:function(e,t){if(e.apolloDragging)return;const{featureAndGlyphUnderMouse:n}=t;n?.feature&&e.setSelectedFeature(n.feature)}};function Ta(e){const t=[[e]];if(e.children)for(const[,n]of e.children)t.push(...Ta(n));return t}function Aa(e){return Ta(e).length}function Na(e,t,n,a,o,r){const l=Ta(t)[n-a];for(const t of l)Fa(e,t,n,o,r)}function Fa(e,t,n,a,o){const{apolloRowHeight:r,lgv:l,session:s}=a,{bpPerPx:i,displayedRegions:c,offsetPx:u}=l,d=c[o],f=(l.bpToPx({refName:d.refName,coord:t.min,regionNumber:o})?.offsetPx??0)-u,{reversed:m}=d,{apolloSelectedFeature:g}=s,p=t.length/i,h=m?f-p:f,y=n*r,b=Aa(t),S=la(t,g);b>1&&ia(e,h,y,p,b*r,S?"rgba(130,0,0,0.45)":"rgba(255,0,0,0.25)"),ua.draw(e,t,n,a,o)}const{drawDragPreview:ka,drawTooltip:Da,getContextMenuItems:Ra,onMouseDown:Ma,onMouseLeave:Ia,onMouseMove:Pa,onMouseUp:qa}=ua,La={draw:function(e,t,n,a,o){for(let r=0;r<Aa(t);r++)Na(e,t,n+r,n,a,o)},drawDragPreview:ka,drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o}=e;if(!n)return;const{feature:r}=n,l=e.getFeatureLayoutPosition(r);if(!l)return;const{featureRow:s,layoutIndex:i,layoutRow:c}=l,{bpPerPx:u,displayedRegions:d,offsetPx:f}=o,m=d[i],{refName:g,reversed:p}=m,{length:h,max:y,min:b}=r,S=(o.bpToPx({refName:g,coord:p?y:b,regionNumber:i})?.offsetPx??0)-f,w=(c+s)*a,v=h/u;t.fillStyle="rgba(0,0,0,0.2)",t.fillRect(S,w,v,a*Aa(r))},drawTooltip:Da,getContextMenuItems:Ra,getFeatureFromLayout:function(e,t,n){return Ta(e)[n].find((e=>t>=e.min&&t<=e.max))},getRowCount:Aa,getRowForFeature:function(e,t){const n=Ta(e);for(const[e,a]of n.entries())if(a.some((e=>e._id===t._id)))return e},onMouseDown:Ma,onMouseLeave:Ia,onMouseMove:Pa,onMouseUp:qa},Ba=v.observer((function({featureTypes:e,handleClose:t,onUpdate:n,session:a}){const[o,r]=y.useState(""),[l,s]=y.useState(e);return de.default.createElement(We,{open:!0,maxWidth:!1,"data-testid":"filter-features-dialog",title:"Filter features by type",handleClose:t},de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,null,"Select the feature types you want to display in the apollo track"),de.default.createElement(p.Grid2,{container:!0,spacing:2},de.default.createElement(p.Grid2,{size:8},de.default.createElement(vt,{session:a,ontologyName:"Sequence Ontology",style:{width:"100%"},value:o,filterTerms:bt,renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Feature type",variant:"outlined",fullWidth:!0}),onChange:(e,t)=>{t&&r(t)}})),de.default.createElement(p.Grid2,{size:4},de.default.createElement(p.Button,{variant:"contained",onClick:()=>{if(o){if(l.includes(o))return;n([...l,o]),s([...l,o])}},disabled:!o,style:{marginTop:9},size:"medium"},"Add"))),l.length>0&&de.default.createElement("div",null,de.default.createElement("hr",null),de.default.createElement("div",{style:{width:300}},de.default.createElement(p.DialogContentText,null,"Selected feature types:"),de.default.createElement(p.Box,{sx:{display:"flex",flexWrap:"wrap",gap:.5}},l.map((e=>de.default.createElement(p.Chip,{key:e,label:e,onDelete:()=>{(e=>{const t=l.filter((t=>t!==e));n(t),s(t)})(e)}}))))))))}));function Oa(e,t,n){const a=[];for(let o=e;o<e+t;o++){const e=n.get(o);e&&a.push(e)}return a}function _a(e,t){for(const n of e)for(const[e,a]of n)if(r.doesIntersect2(t.min,t.max,e,a)||r.doesIntersect2(e,a,t.min,t.max))return!1;return!0}function Ua(e,t){return t?.palette.bases[e.toUpperCase()].main.toString()??"lightgray"}function $a(e,t,n,a,o){const r=Math.min(n,10);e.fillStyle="#000",e.font=`${r}px`;const l=e.measureText(a).width;e.fillText(a,t+(n-l)/2,o+10)}function ja(e,t,n,a,o,l,s,i,c,u,d,f){let m=s.slice(i,i+3).toUpperCase();c&&(m=function(e){return[...e].map((e=>r.revcom(e))).reverse().join("")}(m));const g=r.defaultCodonTable[m];if(!g)return;const p=function(e,t){return{M:"#33ee33","*":t?"#000000":"#f44336"}[e.toUpperCase()]}(g,f);p&&(d&&"*"==g||u&&"*"!=g)&&(e.fillStyle=p,e.fillRect(n,a,o,l)),t<=.1&&(e.rect(n,a,o,l),e.stroke(),$a(e,n,o,g,a))}function Ga(e){return"featureAndGlyphUnderMouse"in e}function Wa(e,t){const n=t<=1?2:0;switch(e){case 3:return 0;case 2:return 1;case 1:return 2;case-1:return 3+n;case-2:return 4+n;case-3:return 5+n}}function Ha(e,t){if(!(t>1||void 0===e))return 1===e?3:4}function za(e,t,n,a,o,r){void 0!==o&&(e.fillStyle=t?.palette.action.focus??"rgba(0,0,0,0.04)",e.fillRect(n,a*o,r,a))}function Ja(e,n){return function(e,n){const l=function(e,t){return function(e,t){const n=function(e,t){return function(e,t){const n=function(e,t){return function(e,t){const n=function(e,t){return o.BaseDisplay.named("BaseLinearApolloDisplay").props({type:i.types.literal("LinearApolloDisplay"),configuration:a.ConfigurationReference(t),graphical:!0,table:!1,showStartCodons:!1,showStopCodons:!0,highContrast:!1,heightPreConfig:i.types.maybe(i.types.refinement("displayHeight",i.types.number,(e=>e>=20))),filteredFeatureTypes:i.types.array(i.types.string),loadingState:!1}).views((e=>{const{configuration:t,renderProps:n}=e;return{renderProps:()=>({...n(),...Z.getParentRenderProps(e),config:t.renderer})}})).volatile((()=>({scrollTop:0}))).views((e=>({get lgv(){return r.getContainingView(e)},get height(){return e.heightPreConfig?e.heightPreConfig:e.graphical&&e.table?500:e.graphical?200:300},get loading(){return e.loadingState}}))).views((e=>({get rendererTypeName(){return e.configuration.renderer.type},get session(){return r.getSession(e)},get regions(){return e.lgv.dynamicBlocks.contentBlocks.map((({assemblyName:e,end:t,refName:n,start:a})=>({assemblyName:e,refName:n,start:Math.round(a),end:Math.round(t)})))},regionCannotBeRendered(){if(e.lgv&&e.lgv.bpPerPx>=200)return"Zoom in to see annotations"}}))).views((e=>({get apolloInternetAccount(){const[t]=e.regions,{internetAccounts:n}=i.getRoot(e),{assemblyName:o}=t,{assemblyManager:r}=e.session,l=r.get(o);if(!l)throw new Error(`No assembly found with name ${o}`);const{internetAccountConfigId:s}=a.getConf(l,["sequence","metadata"]);return n.find((e=>a.getConf(e,"internetAccountId")===s))},get changeManager(){return e.session.apolloDataStore.changeManager},getAssemblyId(t){const{assemblyManager:n}=e.session,a=n.get(t);if(!a)throw new Error(`Could not find assembly named ${t}`);return a.name},get selectedFeature(){return e.session.apolloSelectedFeature}}))).actions((e=>({setScrollTop(t){e.scrollTop=t},setHeight:t=>(e.heightPreConfig=Math.max(t,20),e.height),resizeHeight(t){const n=e.height;return this.setHeight(e.height+t)-n},showGraphicalOnly(){e.graphical=!0,e.table=!1},showTableOnly(){e.graphical=!1,e.table=!0},showGraphicalAndTable(){e.graphical=!0,e.table=!0},toggleShowStartCodons(){e.showStartCodons=!e.showStartCodons},toggleShowStopCodons(){e.showStopCodons=!e.showStopCodons},toggleHighContrast(){e.highContrast=!e.highContrast},updateFilteredFeatureTypes(t){e.filteredFeatureTypes=i.cast(t)},setLoading(t){e.loadingState=t}}))).views((e=>{const{filteredFeatureTypes:t,trackMenuItems:n}=e;return{trackMenuItems(){const{graphical:a,table:o,showStartCodons:r,showStopCodons:l,highContrast:s}=e;return[...n(),{type:"subMenu",label:"Appearance",subMenu:[{label:"Show graphical display",type:"radio",checked:a&&!o,onClick:()=>{e.showGraphicalOnly()}},{label:"Show table display",type:"radio",checked:o&&!a,onClick:()=>{e.showTableOnly()}},{label:"Show both graphical and table display",type:"radio",checked:o&&a,onClick:()=>{e.showGraphicalAndTable()}},{label:"Show start codons",type:"checkbox",checked:r,onClick:()=>{e.toggleShowStartCodons()}},{label:"Show stop codons",type:"checkbox",checked:l,onClick:()=>{e.toggleShowStopCodons()}},{label:"Use high contrast colors",type:"checkbox",checked:s,onClick:()=>{e.toggleHighContrast()}}]},{label:"Filter features by type",onClick:()=>{const n=e.session;e.session.queueDialog((a=>[Ba,{session:n,handleClose:()=>{a()},featureTypes:i.getSnapshot(t),onUpdate:t=>{e.updateFilteredFeatureTypes(t)}}]))}}]}}})).actions((e=>({setSelectedFeature(t){e.session.apolloSetSelectedFeature(t)},afterAttach(){i.addDisposer(e,s.autorun((()=>{e.lgv.initialized&&!e.regionCannotBeRendered()&&(e.setLoading(!0),e.session.apolloDataStore.loadFeatures(e.regions).then((()=>{setTimeout((()=>{e.setLoading(!1)}),1e3)})),e.lgv.bpPerPx<=3&&e.session.apolloDataStore.loadRefSeq(e.regions))}),{name:"LinearApolloDisplayLoadFeatures",delay:1e3}))}})))}(0,t);return n.named("LinearApolloDisplayLayouts").props({cleanupBoundary:2e5}).volatile((()=>({seenFeatures:s.observable.map()}))).views((e=>({getAnnotationFeatureById:t=>e.seenFeatures.get(t),getGlyph:e=>e.looksLikeGene?xa:e.children?.size?La:ua}))).actions((e=>({addSeenFeature(t){e.seenFeatures.set(t._id,t)},deleteSeenFeature(t){e.seenFeatures.delete(t)}}))).views((e=>({get featureLayouts(){const{assemblyManager:t}=e.session;return e.lgv.displayedRegions.map((n=>{const a=t.get(n.assemblyName),o=new Map,l=new Map,{end:s,refName:c,start:u}=n;for(const[t,n]of e.seenFeatures.entries()){if(!i.isAlive(n)){e.deleteSeenFeature(t);continue}if(c!==a?.getCanonicalRefName(n.refSeq)||!r.doesIntersect2(u,s,n.min,n.max)||e.filteredFeatureTypes.length>0&&!e.filteredFeatureTypes.includes(n.type))continue;const{featureTypeOntology:d}=e.session.apolloDataStore.ontologyManager;if(!d)throw new Error("featureTypeOntology is undefined");const f=e.getGlyph(n).getRowCount(n,d,e.lgv.bpPerPx);let m=0,g=!1;for(;!g;){let e=Oa(m,f,l);if(e.length<f){for(let t=0;t<f-e.length;t++){const e=l.size;l.set(e,[]),o.set(e,[])}e=Oa(m,f,l)}if(_a(e,n)){for(let e=m;e<m+f;e++){l.get(e)?.push([n.min,n.max]);const t=o.get(e);t?.push([e-m,n._id])}g=!0}else m+=1}}return o}))},getFeatureLayoutPosition(t){const{featureLayouts:n}=this,{featureTypeOntology:a}=e.session.apolloDataStore.ontologyManager;for(const[o,r]of n.entries())for(const[n,l]of r)for(const[r,s]of l){if(0!==r)continue;const l=e.getAnnotationFeatureById(s);if(l){if(t._id===l._id)return{layoutIndex:o,layoutRow:n,featureRow:r};if(l.hasDescendant(t._id)){if(!a)throw new Error("featureTypeOntology is undefined");const r=e.getGlyph(l).getRowForFeature(l,t,a);if(void 0!==r)return{layoutIndex:o,layoutRow:n,featureRow:r}}}}}}))).views((e=>({get highestRow(){return Math.max(0,...e.featureLayouts.map((e=>Math.max(...e.keys()))))}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(e.lgv.initialized&&!e.regionCannotBeRendered()){for(const[t,n]of e.seenFeatures.entries()){let a=!1;for(const t of e.regions)if(r.doesIntersect2(t.start-e.cleanupBoundary,t.end+e.cleanupBoundary,n.min,n.max)){a=!0;break}a||e.deleteSeenFeature(t)}for(const t of e.regions){const n=e.session.apolloDataStore.assemblies.get(t.assemblyName),a=n?.getByRefName(t.refName),o=a?.features;if(o)for(const[,n]of o)r.doesIntersect2(t.start,t.end,n.min,n.max)&&!e.seenFeatures.has(n._id)&&e.addSeenFeature(n)}}}),{name:"LinearApolloDisplaySetSeenFeatures",delay:1e3}))}})))}(0,t).named("LinearApolloDisplayRendering").props({sequenceRowHeight:15,apolloRowHeight:20,detailsMinHeight:200,detailsHeight:200,lastRowTooltipBufferHeight:40,isShown:!0}).volatile((()=>({canvas:null,overlayCanvas:null,collaboratorCanvas:null,seqTrackCanvas:null,seqTrackOverlayCanvas:null,theme:void 0}))).views((e=>({get featuresHeight(){return(e.highestRow+1)*e.apolloRowHeight+e.lastRowTooltipBufferHeight}}))).actions((e=>({toggleShown(){e.isShown=!e.isShown},setDetailsHeight(t){e.detailsHeight=e.isShown?Math.max(Math.min(t,e.height-100),Math.min(e.height,e.detailsMinHeight)):t},setCanvas(t){e.canvas=t},setOverlayCanvas(t){e.overlayCanvas=t},setCollaboratorCanvas(t){e.collaboratorCanvas=t},setSeqTrackCanvas(t){e.seqTrackCanvas=t},setSeqTrackOverlayCanvas(t){e.seqTrackOverlayCanvas=t},setTheme(t){e.theme=t},afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.collaboratorCanvas?.getContext("2d");if(t){t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);for(const n of e.session.collaborators){const{locations:a}=n;if(0===a.length)continue;let o=0;for(const r of e.lgv.displayedRegions){for(const l of a){if(l.refSeq!==r.refName)continue;const{end:a,refSeq:s,start:i}=l,c=e.lgv.bpToPx({refName:s,coord:i,regionNumber:o});if(!c)continue;const u=c.offsetPx-e.lgv.offsetPx,d=(a-i)/e.lgv.bpPerPx;t.fillStyle="rgba(0,255,0,.2)",t.fillRect(u,1,d,100),t.fillStyle="black",t.fillText(n.name,u+1,11,d-2)}o++}}}}),{name:"LinearApolloDisplayRenderCollaborators"}))}})))}(0,t);return n.actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{const{theme:t}=e;if(!e.lgv.initialized||e.regionCannotBeRendered())return;const n=3/e.lgv.bpPerPx;if(n<1)return;const a=e.seqTrackCanvas?.getContext("2d");if(!a)return;a.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.lgv.bpPerPx<=1?125:95);const o=e.lgv.bpPerPx<=1?[3,2,1,0,0,-1,-2,-3]:[3,2,1,-1,-2,-3];let l=0;if(t)for(const n of o){let o=t.palette.framesCDS.at(n)?.main;if(o){let n=0;e.highContrast&&(o="white",n=1,a.fillStyle=t.palette.grey[200],a.fillRect(0,l,e.lgv.dynamicBlocks.totalWidthPx,e.sequenceRowHeight)),a.fillStyle=o,a.fillRect(0+n,l+n,e.lgv.dynamicBlocks.totalWidthPx-2*n,e.sequenceRowHeight-2*n)}l+=e.sequenceRowHeight}for(const[t,o]of e.regions.entries()){const{apolloDataStore:l}=e.session,s=l.assemblies.get(o.assemblyName),i=s?.getByRefName(o.refName),c=i?.getSequence(o.start,o.end);if(!c)return;for(const[l,s]of[...c].entries()){const i=(e.lgv.bpToPx({refName:o.refName,coord:o.start+l,regionNumber:t})?.offsetPx??0)-e.lgv.offsetPx,u=e.lgv.displayedRegions[t].reversed?i-n:i;for(let t=2;t>=0;t--)(o.start+l)%3===t&&ja(a,e.lgv.bpPerPx,u,e.sequenceRowHeight*(2-t),n,e.sequenceRowHeight,c,l,!1,e.showStartCodons,e.showStopCodons,e.highContrast);if(e.lgv.bpPerPx<=1){const n=(e.lgv.bpToPx({refName:o.refName,coord:o.start+l,regionNumber:t})?.offsetPx??0)-e.lgv.offsetPx,i=1/e.lgv.bpPerPx,c=e.lgv.displayedRegions[t].reversed?n-i:n;a.beginPath(),a.fillStyle=Ua(s,e.theme),a.rect(c,3*e.sequenceRowHeight,i,e.sequenceRowHeight),a.fill(),e.lgv.bpPerPx<=.1&&(a.stroke(),$a(a,c,i,s,3*e.sequenceRowHeight));const u=r.revcom(s);a.beginPath(),a.fillStyle=Ua(u,e.theme),a.rect(c,4*e.sequenceRowHeight,i,e.sequenceRowHeight),a.fill(),e.lgv.bpPerPx<=.1&&(a.stroke(),$a(a,c,i,u,4*e.sequenceRowHeight))}for(let t=0;t<=2;t++)(o.start+l)%3===t&&ja(a,e.lgv.bpPerPx,u,e.sequenceRowHeight*((e.lgv.bpPerPx<=1?5:3)+t),n,e.sequenceRowHeight,c,l,!0,e.showStartCodons,e.showStopCodons,e.highContrast)}}}),{name:"LinearApolloDisplayRenderSequence"}))}})))}(0,t).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{const{canvas:t,featureLayouts:n,featuresHeight:a,lgv:o}=e;if(!o.initialized||e.regionCannotBeRendered())return;const{displayedRegions:l,dynamicBlocks:s}=o,i=t?.getContext("2d");if(i){i.clearRect(0,0,s.totalWidthPx,a);for(const[t,a]of n.entries()){const n=l[t];for(const[o,l]of a.entries())for(const[a,s]of l){const l=e.getAnnotationFeatureById(s);a>0||!l||r.doesIntersect2(n.start,n.end,l.min,l.max)&&e.getGlyph(l).draw(i,l,o,e,t)}}}}),{name:"LinearApolloDisplayRenderFeatures"}))}})))}(0,t);return n.named("LinearApolloDisplayMouseEvents").volatile((()=>({apolloDragging:null,cursor:void 0,apolloHover:void 0}))).views((e=>({getMousePosition(t){const n=function(e,t){const n=e.currentTarget,{clientX:a,clientY:o}=e,{left:r,top:l}=n.getBoundingClientRect(),s=a-r,i=o-l,{coord:c,index:u,refName:d}=t.pxToBp(s);return{x:s,y:i,refName:d,bp:c,regionNumber:u}}(t,e.lgv),{bp:a,regionNumber:o,y:r}=n,l=Math.floor(r/e.apolloRowHeight),s=e.featureLayouts[o].get(l);if(!s)return n;const i=s.find((t=>{const n=e.getAnnotationFeatureById(t[1]);return n&&a>=n.min&&a<=n.max}));if(!i)return n;const[c,u]=i,d=e.getAnnotationFeatureById(u);if(!d)return n;const f=e.getGlyph(d),{featureTypeOntology:m}=e.session.apolloDataStore.ontologyManager;if(!m)throw new Error("featureTypeOntology is undefined");const g=f.getFeatureFromLayout(d,a,c,m);return g?{...n,featureAndGlyphUnderMouse:{feature:g,topLevelFeature:d,glyph:f}}:n}}))).actions((e=>({continueDrag(t,n){if(!e.apolloDragging)throw new Error("continueDrag() called with no current drag in progress");n.stopPropagation(),e.apolloDragging={...e.apolloDragging,current:t}},setDragging(t){e.apolloDragging=t??null}}))).actions((e=>({setApolloHover(t){e.apolloHover=t},setCursor(t){e.cursor!==t&&(e.cursor=t)}}))).actions((()=>({onClick(){}})))}(0,t).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.seqTrackOverlayCanvas?.getContext("2d");if(!t)return;t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.lgv.bpPerPx<=1?125:95);const{apolloHover:n,lgv:a,regions:o,sequenceRowHeight:l,session:s,theme:i}=e;if(!n)return;const{feature:c}=n,{featureTypeOntology:u}=s.apolloDataStore.ontologyManager;if(!u)throw new Error("featureTypeOntology is undefined");for(const[e,n]of o.entries())if(u.isTypeOf(c.type,"CDS")){const o=c.parent;if(!o)continue;const s=o.cdsLocations.find((e=>c.min===e.at(0)?.min&&c.max===e.at(-1)?.max));if(!s)continue;for(const o of s){const s=Wa(r.getFrame(o.min,o.max,c.strand??1,o.phase),a.bpPerPx),u=(a.bpToPx({refName:n.refName,coord:o.min,regionNumber:e})?.offsetPx??0)-a.offsetPx,d=(o.max-o.min)/a.bpPerPx;za(t,i,a.displayedRegions[e].reversed?u-d:u,l,s,d)}}else{const o=Ha(c.strand,a.bpPerPx),r=(a.bpToPx({refName:n.refName,coord:c.min,regionNumber:e})?.offsetPx??0)-a.offsetPx,s=c.length/a.bpPerPx;za(t,i,a.displayedRegions[e].reversed?r-s:r,l,o,s)}}),{name:"LinearApolloDisplayRenderSeqHighlight"}))}})))}(0,n);return l.views((e=>({contextMenuItems(t){const{apolloHover:n}=e;if(!n||!t)return[];const{topLevelFeature:a}=n;return e.getGlyph(a).getContextMenuItems(e)}}))).actions((e=>({startDrag(t,n,a){e.apolloDragging={start:t,current:t,feature:n,edge:a}},endDrag(){if(!e.apolloDragging)throw new Error("endDrag() called with no current drag in progress");const{current:n,edge:a,feature:o,start:r}=e.apolloDragging;if(Math.abs(n.x-r.x)<=4)return e.setDragging(),void e.setCursor();const{displayedRegions:l}=e.lgv,s=e.getAssemblyId(l[r.regionNumber].assemblyName);let i;if("max"===a){const e=o._id;i=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[e],featureId:e,oldEnd:o.max,newEnd:n.bp,assembly:s})}else{const e=o._id;i=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[e],featureId:e,oldStart:o.min,newStart:n.bp,assembly:s})}e.changeManager.submit(i),e.setDragging(),e.setCursor()}}))).actions((e=>({onMouseDown(t){const n=e.getMousePosition(t);Ga(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseDown(e,n,t)},onMouseMove(t){const n=e.getMousePosition(t);if(e.apolloDragging)return e.setCursor("col-resize"),void e.continueDrag(n,t);Ga(n)?n.featureAndGlyphUnderMouse.glyph.onMouseMove(e,n,t):(e.setApolloHover(),e.setCursor())},onMouseLeave(t){e.setDragging(),e.setApolloHover();const n=e.getMousePosition(t);Ga(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseLeave(e,n,t)},onMouseUp(t){const n=e.getMousePosition(t);Ga(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseUp(e,n,t),e.apolloDragging&&e.endDrag()}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.overlayCanvas?.getContext("2d");if(!t)return;t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);const{apolloDragging:n,apolloHover:a}=e;if(!a)return;const{glyph:o}=a;o.drawHover(e,t),o.drawTooltip(e,t),n&&e.getGlyph(n.feature.topLevelFeature).drawDragPreview(e,t)}),{name:"LinearApolloDisplayRenderMouseoverAndDrag"}))}})))}(0,n).props({tabularEditor:i.types.optional(ra,{})}).named("LinearApolloDisplay")}const Va=a.ConfigurationSchema("LinearApolloSixFrameDisplay",{},{explicitIdentifier:"displayId",explicitlyTyped:!0});let Xa=null,Ka=null,Ya=null,Za=null;if("document"in globalThis)for(const e of["forward","backward"])for(const t of["light","dark"]){const n=document.createElement("canvas"),a=10;n.width=n.height=a;const o=n.getContext("2d");if(o){const r="light"===t?"rgba(0,0,0,0)":"rgba(0,0,0,0.75)",l="light"===t?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.50)",s="forward"===e?o.createLinearGradient(0,a,a,0):o.createLinearGradient(0,0,a,a);s.addColorStop(0,r),s.addColorStop(.25,r),s.addColorStop(.25,l),s.addColorStop(.5,l),s.addColorStop(.5,r),s.addColorStop(.75,r),s.addColorStop(.75,l),s.addColorStop(1,l),o.fillStyle=s,o.fillRect(0,0,10,10),"forward"===e?"light"===t?Xa=o.createPattern(n,"repeat"):Ya=o.createPattern(n,"repeat"):"light"===t?Ka=o.createPattern(n,"repeat"):Za=o.createPattern(n,"repeat")}}function Qa(e,t){for(const n of e)if(ge.default(n,t))return!0;return!1}function eo(e,t,n,a){const{session:o}=a,{apolloDataStore:l}=o,{featureTypeOntology:s}=l.ontologyManager;if(!s)throw new Error("featureTypeOntology is undefined");const i=s.isTypeOf(n.type,"transcript");if(null===t)return;const{bp:c,refName:u,regionNumber:d,x:f}=e,{lgv:m}=a,{offsetPx:g}=m,p=m.bpToPx({refName:u,coord:t.min,regionNumber:d}),h=m.bpToPx({refName:u,coord:t.max,regionNumber:d});if(void 0!==p&&void 0!==h&&!(Math.abs(h.offsetPx-g-(p.offsetPx-g))<8)&&i){const e=n;if(!e.children)return;const t=[];for(const n of e.children.values())s.isTypeOf(n.type,"exon")&&t.push(n);const a=t.find((e=>{const[t,n]=r.intersection2(c,c+1,e.min,e.max);return void 0!==t&&void 0!==n}));if(!a)return;const o=m.bpToPx({refName:u,coord:a.min,regionNumber:d}),l=m.bpToPx({refName:u,coord:a.max,regionNumber:d});if(void 0===o||void 0===l)return;const i=o.offsetPx-g,p=l.offsetPx-g;if(Math.abs(p-i)<8)return;if(Math.abs(i-f)<4)return{feature:a,edge:"min"};if(Math.abs(p-f)<4)return{feature:a,edge:"max"}}}const to={draw:function(e,t,n,a,o){const{apolloRowHeight:l,lgv:s,session:i,theme:c,highestRow:u}=a,{bpPerPx:d,displayedRegions:f,offsetPx:m}=s,g=f[o],{refName:h,reversed:y}=g,b=l,S=Math.round(.6*b),w=Math.round(.7*b),{children:v,min:E,strand:C,_id:x}=t;if(!v)return;const{apolloSelectedFeature:T}=i,{apolloDataStore:A}=i,{featureTypeOntology:N}=A.ontologyManager;if(!N)throw new Error("featureTypeOntology is undefined");const F=(s.bpToPx({refName:h,coord:E,regionNumber:o})?.offsetPx??0)-m,k=t.length/d,D=y?F-k:F,R=(1==C?3:4)*b,M=Math.round(.7*b);e.fillStyle=c?.palette.text.primary??"black",e.fillRect(D,R,k,M),e.fillStyle=p.alpha(T&&x===T._id?"rgb(0,0,0)":c?.palette.background.paper??"#ffffff",.7),e.fillRect(D+1,R+1,k-2,M-2);const I="dark"===c?.palette.mode?Ya:Xa,P="dark"===c?.palette.mode?Za:Ka,q=y?-1:1;let L=null,B=null;C&&([L,B]=C*q==1?[I,P]:[P,I]),L&&B&&(e.fillStyle=L,e.fillRect(D+1,R+1,k-2,(M-2)/2),e.fillStyle=B,e.fillRect(D+1,R+(M-2)/2,k-2,(M-2)/2));const O=new Set;for(const[,t]of v){if(!N.isTypeOf(t.type,"transcript")&&!N.isTypeOf(t.type,"pseudogenic_transcript"))continue;const{children:n,cdsLocations:a,_id:l}=t;if(n){for(const[,t]of n){if(!N.isTypeOf(t.type,"exon"))continue;const n=(s.bpToPx({refName:h,coord:t.min,regionNumber:o})?.offsetPx??0)-m,a=t.length/d,r=y?n-a:n,l=R+(M-S)/2;e.fillStyle=c?.palette.text.primary??"black",e.fillRect(r,l,a,S),a>2&&(e.clearRect(r+1,l+1,a-2,S-2),e.fillStyle=T&&t._id===T._id?"rgb(0,0,0)":p.alpha("#f5f500",.6),e.fillRect(r+1,l+1,a-2,S-2),L&&B&&(e.fillStyle=L,e.fillRect(r+1,l+1,a-2,(S-2)/2),e.fillStyle=B,e.fillRect(r+1,l+1+(S-2)/2,a-2,(S-2)/2)))}for(const n of a){let a=0,i=0,f=1;for(const g of n.sort(((e,t)=>e.max-t.max)))if(T&&N.isTypeOf(T.type,"CDS")&&l===T.parent?._id||!Qa(O,g)){const n=(g.max-g.min)/d,p=(s.bpToPx({refName:h,coord:g.min,regionNumber:o})?.offsetPx??0)-m,S=y?p-n:p;e.fillStyle=c?.palette.text.primary??"black";const v=r.getFrame(g.min,g.max,t.strand??1,g.phase),E=((v<0?-1*v+5:v)-1)*b+(b-w)/2;if(e.fillRect(S,E,n,w),n>2){e.clearRect(S+1,E+1,n-2,w-2);const t=c?.palette.framesCDS.at(v)?.main,o=t??"rgb(171,71,188)";if(e.fillStyle=o,e.fillStyle=T&&N.isTypeOf(T.type,"CDS")&&l===T.parent?._id?"rgb(0,0,0)":o,e.fillRect(S+1,E+1,n-2,w-2),f>1){const t=[(S-i)/2+i,Math.max(v<0?b*u+1:1,Math.min(a,E)-b/2)];e.strokeStyle="rgb(0, 128, 128)",e.beginPath(),e.moveTo(i,a),e.lineTo(...t),e.stroke(),e.moveTo(...t),e.lineTo(S,E+b/2),e.stroke()}i=S+n,a=E+b/2,f+=1,L&&B&&(e.fillStyle=L,e.fillRect(S+1,E+1,n-2,(w-2)/2),e.fillStyle=B,e.fillRect(S+1,E+(w-2)/2,n-2,(w-2)/2))}O.add(g)}}}}},drawDragPreview:function(e,t){const{apolloDragging:n,apolloRowHeight:a,lgv:o,theme:r}=e,{bpPerPx:l,displayedRegions:s,offsetPx:i}=o;if(!n)return;const{current:c,edge:u,feature:d,start:f}=n,m=Math.floor(f.y/a),g=s[f.regionNumber],h=(g.reversed?g.end-d[u]:d[u]-g.start)/l-i,y=Math.min(c.x,h),b=m*a,S=Math.abs(c.x-h),w=1*a;t.strokeStyle=r?.palette.info.main??"rgb(255,0,0)",t.setLineDash([6]),t.strokeRect(y,b,S,w),t.fillStyle=p.alpha(r?.palette.info.main??"rgb(255,0,0)",.2),t.fillRect(y,b,S,w)},drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,highestRow:l,session:s}=e;if(!n)return;const{apolloDataStore:i}=s,{featureTypeOntology:c}=i.ontologyManager;if(!c)throw new Error("featureTypeOntology is undefined");const{feature:u}=n;if(!c.isTypeOf(u.type,"transcript"))return;const d=e.getFeatureLayoutPosition(u);if(!d)return;const{bpPerPx:f,displayedRegions:m,offsetPx:g}=o,{layoutIndex:p}=d,h=m[p],{refName:y,reversed:b}=h,S=a,w=Math.round(.7*S),{cdsLocations:v,strand:E}=u;for(const e of v){let n=0,a=0,s=1;for(const i of e.sort(((e,t)=>e.max-t.max))){const e=(i.max-i.min)/f;if(e>2){const c=(o.bpToPx({refName:y,coord:i.min,regionNumber:p})?.offsetPx??0)-g,u=b?c-e:c,d=r.getFrame(i.min,i.max,E??1,i.phase),f=((d<0?-1*d+5:d)-1)*S+(S-w)/2;if(t.fillStyle="rgba(255,0,0,0.6)",t.fillRect(u,f,e,w),s>1){const e=[(u-a)/2+a,Math.max(d<0?S*l+1:1,Math.min(n,f)-S/2)];t.strokeStyle="rgb(0, 0, 0)",t.lineWidth=2,t.beginPath(),t.moveTo(a,n),t.lineTo(...e),t.stroke(),t.moveTo(...e),t.lineTo(u,f+S/2),t.stroke()}a=u+e,n=f+S/2,s+=1}}}},drawTooltip:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,theme:l}=e;if(!n)return;const{cds:s,feature:i}=n;if(!s)return;const c=e.getFeatureLayoutPosition(i);if(!c)return;const{layoutIndex:u}=c,{bpPerPx:d,displayedRegions:f,offsetPx:m}=o,g=f[u],{refName:h,reversed:y}=g,b=a,S=Math.round(.7*b);let w="Loc: ";const{strand:v}=i,{max:E,min:C,phase:x}=s;w+=`${C+1}–${E}`;let T=(o.bpToPx({refName:h,coord:y?E:C,regionNumber:u})?.offsetPx??0)-m;const A=r.getFrame(C,E,v??1,x),N=((A<0?-1*A+5:A)-1)*b+(b-S)/2,F=(E-C)/d,k=`Type: ${s.type}`,{attributes:D}=i,R=D.get("gff_name")?.find((e=>""!==e)),M=[t.measureText(k).width,t.measureText(w).width];R&&M.push(t.measureText(`Parent Type: ${i.type}`).width,t.measureText(`Parent Name: ${R}`).width);const I=Math.max(...M);T=T+F+5,t.fillStyle=p.alpha(l?.palette.text.primary??"rgb(1, 1, 1)",.7),t.fillRect(T,N,I+4,4===M.length?55:35),t.beginPath(),t.moveTo(T,N),t.lineTo(T-5,N+5),t.lineTo(T,N+10),t.fill(),t.fillStyle=l?.palette.background.default??"rgba(255, 255, 255)";let P=N+12;t.fillText(k,T+2,P),R&&(P+=12,t.fillText(`Parent Type: ${i.type}`,T+2,P),P+=12,t.fillText(`Parent Name: ${R}`,T+2,P)),P+=12,t.fillText(w,T+2,P)},getContextMenuItems:function(e){const{apolloHover:t,apolloInternetAccount:n,changeManager:a,regions:o,selectedFeature:l,session:s}=e,i=[];if(!t)return i;const{feature:c}=t,u=n?n.role:"admin",d="admin"===u,f=!(u&&["admin","user"].includes(u)),[m]=o,g=e.getAssemblyId(m.assemblyName),p=e.getAssemblyId(m.assemblyName);i.push({label:"Add child feature",disabled:f,onClick:()=>{s.queueDialog((e=>[Et,{session:s,handleClose:()=>{e()},changeManager:a,sourceFeature:c,sourceAssemblyId:g,internetAccount:n}]))}},{label:"Copy features and annotations",disabled:f,onClick:()=>{s.queueDialog((e=>[Nt,{session:s,handleClose:()=>{e()},changeManager:a,sourceFeature:c,sourceAssemblyId:p}]))}},{label:"Delete feature",disabled:!d,onClick:()=>{s.queueDialog((t=>[kt,{session:s,handleClose:()=>{t()},changeManager:a,sourceFeature:c,sourceAssemblyId:p,selectedFeature:l,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}},{label:"Edit feature details",onClick:()=>{const e=s.addWidget("ApolloFeatureDetailsWidget","apolloFeatureDetailsWidget",{feature:c,assembly:p,refName:m.refName});s.showWidget(e)}});const{featureTypeOntology:h}=s.apolloDataStore.ontologyManager;if(!h)throw new Error("featureTypeOntology is undefined");return h.isTypeOf(c.type,"transcript")&&r.isSessionModelWithWidgets(s)&&i.push({label:"Edit transcript details",onClick:()=>{const e=s.addWidget("ApolloTranscriptDetails","apolloTranscriptDetails",{feature:c,assembly:p,changeManager:a,refName:m.refName});s.showWidget(e)}}),i},onMouseDown:function(e,t,n){const{featureAndGlyphUnderMouse:a}=t,{cds:o,feature:r}=a,l=eo(t,o,r,e);l&&(n.stopPropagation(),e.startDrag(t,l.feature,l.edge))},onMouseLeave:function(){},onMouseMove:function(e,t){if(no(t)){const{featureAndGlyphUnderMouse:n}=t;e.setApolloHover(n);const{cds:a,feature:o}=n;if(eo(t,a,o,e))return void e.setCursor("col-resize")}e.setCursor()},onMouseUp:function(e,t){if(e.apolloDragging)return;const{featureAndGlyphUnderMouse:n}=t,{session:a}=e,{apolloDataStore:o}=a,{featureTypeOntology:r}=o.ontologyManager;if(n?.cds){const{cds:t,feature:a}=n;if(!r)throw new Error("featureTypeOntology is undefined");if(!a.children)return;for(const n of a.children.values())if(r.isTypeOf(n.type,"CDS")&&t.max<=n.max&&t.min>=n.min){e.setSelectedFeature(n);break}}else n?.feature&&e.setSelectedFeature(n.feature)}};function no(e){return"featureAndGlyphUnderMouse"in e}function ao(e,n){return function(e,n){const l=function(e,t){return function(e,t){const n=function(e,t){return function(e,t){const n=function(e,t){return o.BaseDisplay.named("BaseLinearApolloSixFrameDisplay").props({type:i.types.literal("LinearApolloSixFrameDisplay"),configuration:a.ConfigurationReference(t),graphical:!0,table:!1,heightPreConfig:i.types.maybe(i.types.refinement("displayHeight",i.types.number,(e=>e>=20))),filteredFeatureTypes:i.types.array(i.types.string)}).views((e=>{const{configuration:t,renderProps:n}=e;return{renderProps:()=>({...n(),...Z.getParentRenderProps(e),config:t.renderer})}})).volatile((()=>({scrollTop:0}))).views((e=>({get lgv(){return r.getContainingView(e)},get height(){return e.heightPreConfig?e.heightPreConfig:e.graphical&&e.table?500:e.graphical?200:300}}))).views((e=>({get rendererTypeName(){return e.configuration.renderer.type},get session(){return r.getSession(e)},get regions(){return e.lgv.dynamicBlocks.contentBlocks.map((({assemblyName:e,end:t,refName:n,start:a})=>({assemblyName:e,refName:n,start:Math.round(a),end:Math.round(t)})))},regionCannotBeRendered(){if(e.lgv&&e.lgv.bpPerPx>=200)return"Zoom in to see annotations"}}))).views((e=>({get apolloInternetAccount(){const[t]=e.regions,{internetAccounts:n}=i.getRoot(e),{assemblyName:o}=t,{assemblyManager:r}=e.session,l=r.get(o);if(!l)throw new Error(`No assembly found with name ${o}`);const{internetAccountConfigId:s}=a.getConf(l,["sequence","metadata"]);return n.find((e=>a.getConf(e,"internetAccountId")===s))},get changeManager(){return e.session.apolloDataStore.changeManager},getAssemblyId(t){const{assemblyManager:n}=e.session,a=n.get(t);if(!a)throw new Error(`Could not find assembly named ${t}`);return a.name},get selectedFeature(){return e.session.apolloSelectedFeature}}))).actions((e=>({setScrollTop(t){e.scrollTop=t},setHeight:t=>(e.heightPreConfig=Math.max(t,20),e.height),resizeHeight(t){const n=e.height;return this.setHeight(e.height+t)-n},showGraphicalOnly(){e.graphical=!0,e.table=!1},showTableOnly(){e.graphical=!1,e.table=!0},showGraphicalAndTable(){e.graphical=!0,e.table=!0},updateFilteredFeatureTypes(t){e.filteredFeatureTypes=i.cast(t)}}))).views((e=>{const{filteredFeatureTypes:t,trackMenuItems:n}=e;return{trackMenuItems(){const{graphical:a,table:o}=e;return[...n(),{type:"subMenu",label:"Appearance",subMenu:[{label:"Show graphical display",type:"radio",checked:a&&!o,onClick:()=>{e.showGraphicalOnly()}},{label:"Show table display",type:"radio",checked:o&&!a,onClick:()=>{e.showTableOnly()}},{label:"Show both graphical and table display",type:"radio",checked:o&&a,onClick:()=>{e.showGraphicalAndTable()}}]},{label:"Filter features by type",onClick:()=>{const n=e.session;e.session.queueDialog((a=>[Ba,{session:n,handleClose:()=>{a()},featureTypes:i.getSnapshot(t),onUpdate:t=>{e.updateFilteredFeatureTypes(t)}}]))}}]}}})).actions((e=>({setSelectedFeature(t){e.session.apolloSetSelectedFeature(t)},afterAttach(){i.addDisposer(e,s.autorun((()=>{e.lgv.initialized&&!e.regionCannotBeRendered()&&(e.session.apolloDataStore.loadFeatures(e.regions),e.lgv.bpPerPx<=3&&e.session.apolloDataStore.loadRefSeq(e.regions))}),{name:"LinearApolloSixFrameDisplayLoadFeatures",delay:1e3}))}})))}(0,t);return n.named("LinearApolloSixFrameDisplayLayouts").props({featuresMinMaxLimit:5e5}).volatile((()=>({seenFeatures:s.observable.map()}))).views((e=>({get featuresMinMax(){const{assemblyManager:t}=e.session;return e.lgv.displayedRegions.map((n=>{const a=t.get(n.assemblyName);let o,l;const{end:s,refName:i,start:c}=n;for(const[,t]of e.seenFeatures)i!==a?.getCanonicalRefName(t.refSeq)||!r.doesIntersect2(c,s,t.min,t.max)||t.length>e.featuresMinMaxLimit||(void 0===o&&({min:o}=t),void 0===l&&({max:l}=t),t.minWithChildren<o&&({min:o}=t),t.maxWithChildren>l&&({max:l}=t));if(void 0!==o&&void 0!==l)return[o,l]}))},getGlyph:e=>to}))).actions((e=>({addSeenFeature(t){e.seenFeatures.set(t._id,t)},deleteSeenFeature(t){e.seenFeatures.delete(t)}}))).views((e=>({get featureLayouts(){const{assemblyManager:t}=e.session;return e.lgv.displayedRegions.map(((n,a)=>{const o=t.get(n.assemblyName),l=new Map;if(!e.featuresMinMax[a])return l;const{end:s,refName:c,start:u}=n;for(const[t,n]of e.seenFeatures.entries()){if(!i.isAlive(n)){e.deleteSeenFeature(t);continue}if(c!==o?.getCanonicalRefName(n.refSeq)||!r.doesIntersect2(u,s,n.min,n.max))continue;const{featureTypeOntology:a}=e.session.apolloDataStore.ontologyManager;if(!a)throw new Error("featureTypeOntology is undefined");if(n.looksLikeGene){const e=1==n.strand?4:5;l.get(e)||l.set(e,[]);const t=l.get(e);t?.push({rowNum:e,feature:n,cds:null});const{children:o}=n;if(!o)continue;for(const[,e]of o)if(a.isTypeOf(e.type,"transcript")){const{cdsLocations:t,strand:n,children:o}=e;if(o)for(const[,e]of o){if(!a.isTypeOf(e.type,"exon"))continue;const t=1==e.strand?4:5,n=l.get(t);n?.push({rowNum:t,feature:e,cds:null})}for(const a of t)for(const t of a){let a=r.getFrame(t.min,t.max,n??1,t.phase);a=a<0?-1*a+5:a,l.get(a)||l.set(a,[]);const o=l.get(a);o?.push({rowNum:a,feature:e,cds:t})}}}}return l}))},getFeatureLayoutPosition(e){const{featureLayouts:t}=this;for(const[n,a]of t.entries())for(const[,t]of a)for(const{feature:a}of t)if(e._id===a._id)return{layoutIndex:n,layoutRow:0,featureRow:0}}}))).views((e=>({get highestRow(){return 5}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(e.lgv.initialized&&!e.regionCannotBeRendered())for(const t of e.regions){const n=e.session.apolloDataStore.assemblies.get(t.assemblyName),a=n?.getByRefName(t.refName),o=a?.features;if(o)for(const[,n]of o)r.doesIntersect2(t.start,t.end,n.min,n.max)&&!e.seenFeatures.has(n._id)&&e.addSeenFeature(n)}}),{name:"LinearApolloSixFrameDisplaySetSeenFeatures",delay:1e3}))}})))}(0,t).named("LinearApolloSixFrameDisplayRendering").props({sequenceRowHeight:15,apolloRowHeight:20,detailsMinHeight:200,detailsHeight:200,lastRowTooltipBufferHeight:80,isShown:!0}).volatile((()=>({canvas:null,overlayCanvas:null,collaboratorCanvas:null,theme:void 0}))).views((e=>({get featuresHeight(){return(e.highestRow+1)*e.apolloRowHeight+e.lastRowTooltipBufferHeight}}))).actions((e=>({toggleShown(){e.isShown=!e.isShown},setDetailsHeight(t){e.detailsHeight=e.isShown?Math.max(Math.min(t,e.height-100),Math.min(e.height,e.detailsMinHeight)):t},setCanvas(t){e.canvas=t},setOverlayCanvas(t){e.overlayCanvas=t},setCollaboratorCanvas(t){e.collaboratorCanvas=t},setTheme(t){e.theme=t},afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.collaboratorCanvas?.getContext("2d");if(t){t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);for(const n of e.session.collaborators){const{locations:a}=n;if(0===a.length)continue;let o=0;for(const r of e.lgv.displayedRegions){for(const l of a){if(l.refSeq!==r.refName)continue;const{end:a,refSeq:s,start:i}=l,c=e.lgv.bpToPx({refName:s,coord:i,regionNumber:o});if(!c)continue;const u=c.offsetPx-e.lgv.offsetPx,d=(a-i)/e.lgv.bpPerPx;t.fillStyle="rgba(0,255,0,.2)",t.fillRect(u,1,d,100),t.fillStyle="black",t.fillText(n.name,u+1,11,d-2)}o++}}}}),{name:"LinearApolloSixFrameDisplayRenderCollaborators"}))}})))}(0,t);return n.actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{const{canvas:t,featureLayouts:n,featuresHeight:a,lgv:o}=e;if(!o.initialized||e.regionCannotBeRendered())return;const{displayedRegions:l,dynamicBlocks:s}=o,i=t?.getContext("2d");if(i){i.clearRect(0,0,s.totalWidthPx,a);for(const[t,a]of n.entries()){const n=l[t];for(const[o,l]of a.entries())for(const{feature:a}of l){if(!a.looksLikeGene)continue;if(!r.doesIntersect2(n.start,n.end,a.min,a.max))continue;const{topLevelFeature:l}=a,s=e.getGlyph(l);void 0!==s&&s.draw(i,l,o,e,t)}}}}),{name:"LinearApolloSixFrameDisplayRenderFeatures"}))}})))}(0,t).named("LinearApolloSixFrameDisplayMouseEvents").volatile((()=>({apolloDragging:null,cursor:void 0,apolloHover:void 0}))).views((e=>({getMousePosition(t){const n=function(e,t){const n=e.currentTarget,{clientX:a,clientY:o}=e,{left:r,top:l}=n.getBoundingClientRect(),s=a-r,i=o-l,{coord:c,index:u,refName:d}=t.pxToBp(s);return{x:s,y:i,refName:d,bp:c,regionNumber:u}}(t,e.lgv),{bp:a,regionNumber:o,y:r}=n,l=Math.floor(r/e.apolloRowHeight)+1,s=e.featureLayouts[o].get(l);if(!s)return n;let i;if([4,5].includes(l)?(i=s.find((e=>"exon"==e.feature.type&&a>=e.feature.min&&a<=e.feature.max)),i||(i=s.find((e=>a>=e.feature.min&&a<=e.feature.max)))):i=s.find((e=>null!=e.cds&&a>=e.cds.min&&a<=e.cds.max)),!i)return n;const{feature:c,cds:u}=i,{topLevelFeature:d}=c,f=e.getGlyph(c);return{...n,featureAndGlyphUnderMouse:{cds:u,feature:c,topLevelFeature:d,glyph:f}}}}))).actions((e=>({continueDrag(t,n){if(!e.apolloDragging)throw new Error("continueDrag() called with no current drag in progress");n.stopPropagation(),e.apolloDragging={...e.apolloDragging,current:t}},setDragging(t){e.apolloDragging=t??null}}))).actions((e=>({setApolloHover(t){e.apolloHover=t},setCursor(t){e.cursor!==t&&(e.cursor=t)}}))).actions((()=>({onClick(){}})))}(0,n);return l.views((e=>({contextMenuItems(t){const{apolloHover:n}=e;if(!n||!t)return[];const{topLevelFeature:a}=n;return e.getGlyph(a).getContextMenuItems(e)}}))).actions((e=>({startDrag(t,n,a){e.apolloDragging={start:t,current:t,feature:n,edge:a}},endDrag(){if(!e.apolloDragging)throw new Error("endDrag() called with no current drag in progress");const{current:n,edge:a,feature:o,start:r}=e.apolloDragging;if(Math.abs(n.x-r.x)<=4)return e.setDragging(),void e.setCursor();const{displayedRegions:l}=e.lgv,s=e.getAssemblyId(l[r.regionNumber].assemblyName);let i;if("max"===a){const e=o._id;i=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[e],featureId:e,oldEnd:o.max,newEnd:n.bp,assembly:s})}else{const e=o._id;i=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[e],featureId:e,oldStart:o.min,newStart:n.bp,assembly:s})}e.changeManager.submit(i),e.setDragging(),e.setCursor()}}))).actions((e=>({onMouseDown(t){const n=e.getMousePosition(t);no(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseDown(e,n,t)},onMouseMove(t){const n=e.getMousePosition(t);if(e.apolloDragging)return e.setCursor("col-resize"),void e.continueDrag(n,t);no(n)?n.featureAndGlyphUnderMouse.glyph.onMouseMove(e,n,t):(e.setApolloHover(),e.setCursor())},onMouseLeave(t){e.setDragging(),e.setApolloHover();const n=e.getMousePosition(t);no(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseLeave(e,n,t)},onMouseUp(t){const n=e.getMousePosition(t);no(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseUp(e,n,t),e.apolloDragging&&e.endDrag()}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.overlayCanvas?.getContext("2d");if(!t)return;t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);const{apolloDragging:n,apolloHover:a}=e;if(!a)return;const{glyph:o}=a;o.drawHover(e,t),o.drawTooltip(e,t),n&&e.getGlyph(n.feature.topLevelFeature).drawDragPreview(e,t)}),{name:"LinearApolloSixFrameDisplayRenderMouseoverAndDrag"}))}})))}(0,n).props({tabularEditor:i.types.optional(ra,{})}).named("LinearApolloSixFrameDisplay")}const oo=a.ConfigurationSchema("ApolloPlugin",{ontologies:i.types.array(yt),featureTypeOntologyName:{description:"Name of the feature type ontology",type:"string",defaultValue:"Sequence Ontology"}});function ro(e){if("LinearPileupDisplay"!==e.name)return e;const{stateModel:n}=e,a=n.views((e=>({getFirstRegion:()=>r.getContainingView(e).dynamicBlocks.contentBlocks[0],getAssembly(){const t=e.getFirstRegion(),n=r.getSession(e),{assemblyManager:a}=n,{assemblyName:o}=t,l=a.get(o);if(!l)throw new Error(`Could not find assembly named ${o}`);return l},getRefSeqId(t){const n=e.getFirstRegion(),{refName:a}=n,{refNameAliases:o}=t;if(!o)throw new Error(`Could not find aliases for ${t.name}`);const r=[...Object.entries(o)].filter((([e,t])=>e!==t)).map((([e,t])=>({_id:e,name:t}))),l=r.find((e=>e.name===a))?._id;if(!l)throw new Error(`Could not find refSeqId named ${a}`);return l},createFeature(){const t=e.contextMenuFeature,n=e.getAssembly(),a=e.getRefSeqId(n),o=(t.get("CIGAR").toUpperCase().match(/\d+\D/g)??[]).map((e=>[(/\D/.exec(e)??[])[0],Number.parseInt(e,10)]));let r=0;const l=t.get("start");let s;const i=[];for(const[e,t]of o)"M"===e||"="===e?void 0===s&&(s=r+l):"N"===e&&void 0!==s&&(i.push({start:s,end:r+s}),s=void 0),"I"!==e&&(r+=t);void 0!==s&&i.push({start:s,end:r+l});const c={_id:ue.default().toHexString(),refSeq:a,min:t.get("start"),max:t.get("end"),type:"mRNA",strand:t.get("strand")};if(0===i.length)return c;c.children={};const[u]=i,d={_id:ue.default().toHexString(),refSeq:a,min:u.start,max:u.end,type:"CDS",strand:t.get("strand")};if(c.children[d._id]=d,1===i.length){const e={_id:ue.default().toHexString(),refSeq:a,min:u.start,max:u.end,type:"exon",strand:t.get("strand")};return c.children[e._id]=e,c}for(const e of i){d.min=Math.min(d.min,e.start),d.max=Math.max(d.max,e.end);const{end:n,start:o}=e,r={_id:ue.default().toHexString(),refSeq:a,min:o,max:n,type:"exon",strand:t.get("strand")};c.children[r._id]=r}return c},async onPileupFeatureContext(){const n=e.createFeature(),a=e.getAssembly(),o=new t.AddFeatureChange({changedIds:[n._id],typeName:"AddFeatureChange",assembly:a.name,addedFeature:n}),l=r.getSession(e);await l.apolloDataStore.changeManager.submit(o),l.notify("Annotation added successfully","success")}}))).views((e=>{const t=e.contextMenuItems;return{contextMenuItems:()=>e.contextMenuFeature?[...t(),{label:"Create Apollo annotation",icon:oe.default,onClick:e.onPileupFeatureContext}]:t()}}));return e.stateModel=a,e}const lo=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"gene")||n.isTypeOf(e.type,"transcript")||n.isTypeOf(e.type,"pseudogene")||n.isTypeOf(e.type,"pseudogenic_transcript")},so=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"gene")||n.isTypeOf(e.type,"pseudogene")},io=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"transcript")||n.isTypeOf(e.type,"pseudogenic_transcript")},co=e=>{const{attributes:t}=e,n=t?.id;return n?n[0]:e.type},uo=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)return co(e);let a="";n.isTypeOf(e.type,"gene")&&(a="gene_name"),n.isTypeOf(e.type,"transcript")&&(a="transcript_name");const{attributes:o}=e,r=o?.[a];return r?r[0]:co(e)};function fo({annotationFeature:e,assembly:n,handleClose:a,refSeqId:o,session:r}){const l=r,s=y.useMemo((()=>Object.keys(e.children??{})),[e]),c=y.useMemo((()=>{for(const[,e]of l.apolloDataStore.assemblies)if(e._id===n.name)for(const[,t]of e.refSeqs)if(t._id===o)return t.features;return[]}),[]),[u,d]=y.useState(!0),[f,m]=y.useState(s),[g,h]=y.useState(""),[b,S]=y.useState([]),[w,v]=y.useState();return y.useEffect((()=>{h("");let t=[],n=[];if(e.children){const a=Object.values(e.children).filter((e=>io(e,l))).filter((e=>f.includes(e._id)));t=a.map((e=>e.min)),n=a.map((e=>e.max))}const{featureTypeOntology:a}=l.apolloDataStore.ontologyManager;a&&a.isTypeOf(e.type,"transcript")&&(t=[e.min,...t],n=[e.max,...n]);const o=((e,t)=>{const n=[];for(const[,a]of c){if("chromosome"===a.type)continue;const o=i.getSnapshot(a);e>=o.min&&t<=o.max&&n.push(o)}return n})(Math.min(...t),Math.max(...n));S(o),v(o[0])}),[f,u]),de.default.createElement(We,{open:!0,title:"Create Apollo Annotation",handleClose:a,fullWidth:!0,maxWidth:"sm"},de.default.createElement(p.DialogTitle,{fontSize:15},"Select the feature to be copied to apollo track"),de.default.createElement(p.DialogContent,null,de.default.createElement(p.Box,{sx:{ml:3}},lo(e,l)&&de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{size:"small",checked:u,onChange:e=>{const t=e.target.checked;d(t),m(t?s:[])}}),label:`${uo(e,l)} (${e.min+1}..${e.max})`}),e.children&&de.default.createElement(p.Box,{sx:{display:"flex",flexDirection:"column",ml:3}},Object.values(e.children).filter((e=>io(e,l))).map((e=>de.default.createElement(p.FormControlLabel,{key:e._id,control:de.default.createElement(p.Checkbox,{size:"small",checked:f.includes(e._id),onChange:t=>{((e,t)=>{m((n=>e.target.checked?[...n,t._id]:n.filter((e=>e!==t._id))))})(t,e)}}),label:`${uo(e,l)} (${e.min+1}..${e.max})`}))))),b.length>0&&(!u&&f.length>0||u&&io(e,l))&&de.default.createElement(p.Box,{sx:{ml:3}},de.default.createElement(p.Typography,{variant:"caption",fontSize:12},"Select the destination feature to copy the selected features"),de.default.createElement(p.Box,{sx:{mt:1}},de.default.createElement(p.Select,{labelId:"label",style:{width:"100%"},value:w?._id??"",onChange:e=>{const t=b.find((t=>t._id===e.target.value));v(t)}},b.map((e=>de.default.createElement(p.MenuItem,{key:e._id,value:e._id},`${uo(e,l)} (${e.min}..${e.max})`))))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:0===f.length||!u&&f.length>0&&!w,onClick:async()=>{if(u){let o;if(so(e,l))if(e.children&&f.length!==Object.values(e.children).length){const a={};for(const t of f)a[t]=e.children[t];o=new t.AddFeatureChange({changedIds:[e._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:{...e,children:a}})}else o=new t.AddFeatureChange({changedIds:[e._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:e});if(io(e,l)){if(!w)return void h("There is no destination gene for this transcript");o=new t.AddFeatureChange({parentFeatureId:w._id,changedIds:[w._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:e})}if(!o)return;await l.apolloDataStore.changeManager.submit(o),r.notify("Annotation added successfully","success"),a()}else{if(!e.children)return;if(!w)return;for(const a of f){const o=new t.AddFeatureChange({parentFeatureId:w._id,changedIds:[w._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:e.children[a]});await l.apolloDataStore.changeManager.submit(o)}r.notify("Annotation added successfully","success"),a()}}},"Create"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:a},"Cancel")),g?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},g)):null)}function mo(e,t){const n=JSON.parse(JSON.stringify(e)),a=n.subfeatures;return[{start:n.start+1,end:n.end,seq_id:t,source:n.source??null,type:n.type??null,score:n.score??null,strand:n.strand?1===n.strand?"+":"-":null,phase:null!==n.phase||void 0!==n.phase?n.phase:null,attributes:po(n),derived_features:[],child_features:a?a.map((e=>mo(e,t))):[]}]}function go(e,n){return t.gff3ToAnnotationFeature(mo(e,n))}function po(e){const t={},n=new Set(["start","end","type","strand","refName","subfeatures","derived_features","phase","source","score"]);for(const[a,o]of Object.entries(e))n.has(a)||(t[a]=Array.isArray(o)?o.map(String):[String(o)]);return t}function ho(e){if("LinearBasicDisplay"!==e.name)return e;const{stateModel:t}=e,n=t.views((e=>({getFirstRegion:()=>r.getContainingView(e).dynamicBlocks.contentBlocks[0],getAssembly(){const t=e.getFirstRegion(),n=r.getSession(e),{assemblyManager:a}=n,{assemblyName:o}=t,l=a.get(o);if(!l)throw new Error(`Could not find assembly named ${o}`);return l},getRefSeqId(t){const n=e.getFirstRegion(),{refName:a}=n,{refNameAliases:o}=t;if(!o)throw new Error(`Could not find aliases for ${t.name}`);const r=[...Object.entries(o)].filter((([e,t])=>e!==t)).map((([e,t])=>({_id:e,name:t}))),l=r.find((e=>e.name===a))?._id;if(!l)throw new Error(`Could not find refSeqId named ${a}`);return l},getAnnotationFeature(t){const n=e.getRefSeqId(t);return go(e.contextMenuFeature.data,n)}}))).views((e=>{const t=e.contextMenuItems;return{contextMenuItems(){const n=r.getSession(e),a=e.getAssembly();return e.contextMenuFeature?[...t(),{label:"Create Apollo annotation",icon:oe.default,onClick:()=>{n.queueDialog((t=>[fo,{session:n,handleClose:()=>{t()},annotationFeature:e.getAnnotationFeature(a),assembly:a,refSeqId:e.getRefSeqId(a)}]))}}]:t()}}}));return e.stateModel=n,e}const yo=b.makeStyles()((e=>({canvasContainer:{position:"relative",left:0},canvas:{position:"absolute",left:0},ellipses:{textOverflow:"ellipsis",overflow:"hidden"},avatar:{position:"absolute",color:e.palette.warning.light,backgroundColor:e.palette.warning.contrastText},loading:{position:"absolute",right:e.spacing(3),zIndex:10,pointerEvents:"none",textAlign:"right"}}))),bo=v.observer((function(e){const t=p.useTheme(),{model:n}=e,{loading:a,apolloDragging:o,apolloRowHeight:l,contextMenuItems:s,cursor:i,featuresHeight:c,isShown:u,onMouseDown:d,onMouseLeave:f,onMouseMove:m,onMouseUp:g,regionCannotBeRendered:h,session:b,setCanvas:w,setCollaboratorCanvas:v,setOverlayCanvas:E,setSeqTrackCanvas:C,setSeqTrackOverlayCanvas:x,setTheme:T}=n,{classes:A}=yo(),N=r.getContainingView(n);y.useEffect((()=>{T(t)}),[t,T]);const[F,k]=y.useState(),[D,R]=y.useState([]),M=h();if(!u)return null;const{assemblyManager:I}=b;return de.default.createElement(de.default.Fragment,null,3/N.bpPerPx>=1?de.default.createElement("div",{className:A.canvasContainer,style:{width:N.dynamicBlocks.totalWidthPx,height:N.bpPerPx<=1?125:95}},de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),C(e)},width:N.dynamicBlocks.totalWidthPx,height:N.bpPerPx<=1?125:95,className:A.canvas,"data-testid":"seqTrackCanvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),x(e)},width:N.dynamicBlocks.totalWidthPx,height:N.bpPerPx<=1?125:95,className:A.canvas,"data-testid":"seqTrackOverlayCanvas"})):null,de.default.createElement("div",{className:A.canvasContainer,style:{width:N.dynamicBlocks.totalWidthPx,height:c},onContextMenu:e=>{if(e.preventDefault(),D.length>0)R([]);else{const t=[e.clientX,e.clientY];k(t),R(s(t))}}},a?de.default.createElement("div",{className:A.loading},de.default.createElement(p.CircularProgress,{size:"18px"})):null,M?de.default.createElement(p.Alert,{severity:"warning",classes:{message:A.ellipses}},de.default.createElement(p.Tooltip,{title:M},de.default.createElement("div",null,M))):de.default.createElement(de.default.Fragment,null,de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),v(e)},width:N.dynamicBlocks.totalWidthPx,height:c,className:A.canvas,"data-testid":"collaboratorCanvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),w(e)},width:N.dynamicBlocks.totalWidthPx,height:c,className:A.canvas,"data-testid":"canvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),E(e)},width:N.dynamicBlocks.totalWidthPx,height:c,onMouseMove:m,onMouseLeave:f,onMouseDown:d,onMouseUp:g,className:A.canvas,style:{cursor:i??"default"},"data-testid":"overlayCanvas"}),N.displayedRegions.flatMap(((e,t)=>{const a=I.get(e.assemblyName);return[...b.apolloDataStore.checkResults.values()].filter((t=>a?.isValidRefName(t.refSeq)&&a.getCanonicalRefName(t.refSeq)===e.refName&&r.doesIntersect2(e.start,e.end,t.start,t.end))).map((a=>{const r=(N.bpToPx({refName:e.refName,coord:a.start,regionNumber:t})?.offsetPx??0)-N.offsetPx,[s]=a.ids;if(!s)return null;let i=0;const c=n.getFeatureLayoutPosition(s);return c&&(i=c.layoutRow+c.featureRow),de.default.createElement(p.Tooltip,{key:a._id,title:a.message},de.default.createElement(p.Avatar,{className:A.avatar,style:{top:i*l,left:r,height:l,width:l,pointerEvents:o?"none":"auto"}},de.default.createElement(Pe.default,{"data-testid":"ErrorIcon"})))}))})),de.default.createElement(S.Menu,{open:D.length>0,onMenuItemClick:(e,t)=>{t(),R([])},onClose:()=>{R([])},TransitionProps:{onExit:()=>{R([])}},anchorReference:"anchorPosition",anchorPosition:F?{top:F[1],left:F[0]}:void 0,style:{zIndex:t.zIndex.tooltip},menuItems:D}))))})),So=v.observer((function({model:e,strand:t}){const{apolloRowHeight:n,highestRow:a,lastRowTooltipBufferHeight:o}=e;return de.default.createElement("div",1==t?{style:{position:"absolute",left:0,top:n*(a+1)/2-2,width:"100%"}}:{style:{position:"absolute",left:0,bottom:(n*(a+1)+o)/2+3,width:"100%"}},de.default.createElement("hr",{style:{margin:0,top:0,color:"black"}}))})),wo=b.makeStyles()((e=>({canvasContainer:{position:"relative",left:0},canvas:{position:"absolute",left:0},ellipses:{textOverflow:"ellipsis",overflow:"hidden"},avatar:{position:"absolute",color:e.palette.warning.light,backgroundColor:e.palette.warning.contrastText}}))),vo=v.observer((function(e){const t=p.useTheme(),{model:n}=e,{apolloRowHeight:a,contextMenuItems:o,cursor:l,featuresHeight:s,isShown:i,onMouseDown:c,onMouseLeave:u,onMouseMove:d,onMouseUp:f,regionCannotBeRendered:m,session:g,setCanvas:h,setCollaboratorCanvas:b,setOverlayCanvas:w,setTheme:v}=n,{classes:E}=wo(),C=r.getContainingView(n);y.useEffect((()=>{v(t)}),[t,v]);const[x,T]=y.useState(),[A,N]=y.useState([]),F=m();if(!i)return null;const{assemblyManager:k}=g;return de.default.createElement(de.default.Fragment,null,de.default.createElement("div",{className:E.canvasContainer,style:{width:C.dynamicBlocks.totalWidthPx,height:s},onContextMenu:e=>{if(e.preventDefault(),A.length>0)N([]);else{const t=[e.clientX,e.clientY];T(t),N(o(t))}}},F?de.default.createElement(p.Alert,{severity:"warning",classes:{message:E.ellipses}},de.default.createElement(p.Tooltip,{title:F},de.default.createElement("div",null,F))):de.default.createElement(de.default.Fragment,null,de.default.createElement(So,{model:n,strand:1}),de.default.createElement(So,{model:n,strand:-1}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),b(e)},width:C.dynamicBlocks.totalWidthPx,height:s,className:E.canvas,"data-testid":"collaboratorCanvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),h(e)},width:C.dynamicBlocks.totalWidthPx,height:s,className:E.canvas,"data-testid":"canvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),w(e)},width:C.dynamicBlocks.totalWidthPx,height:s,onMouseMove:d,onMouseLeave:u,onMouseDown:c,onMouseUp:f,className:E.canvas,style:{cursor:l??"default"},"data-testid":"overlayCanvas"}),C.displayedRegions.flatMap(((e,t)=>{const n=k.get(e.assemblyName);return[...g.apolloDataStore.checkResults.values()].filter((t=>n?.isValidRefName(t.refSeq)&&n.getCanonicalRefName(t.refSeq)===e.refName&&r.doesIntersect2(e.start,e.end,t.start,t.end))).map((n=>{const o=(C.bpToPx({refName:e.refName,coord:n.start,regionNumber:t})?.offsetPx??0)-C.offsetPx,[r]=n.ids;return r&&r.parent?.looksLikeGene?de.default.createElement(p.Tooltip,{key:n._id,title:n.message},de.default.createElement(p.Avatar,{className:E.avatar,style:{top:0,left:o,height:a,width:a}},de.default.createElement(Pe.default,null))):null}))})),de.default.createElement(S.Menu,{open:A.length>0,onMenuItemClick:(e,t)=>{t(),N([])},onClose:()=>{N([])},TransitionProps:{onExit:()=>{N([])}},anchorReference:"anchorPosition",anchorPosition:x?{top:x[1],left:x[0]}:void 0,style:{zIndex:t.zIndex.tooltip},menuItems:A}))))})),Eo=b.makeStyles()((e=>({shading:{background:p.alpha(e.palette.primary.main,.2),overflowY:"scroll",overflowX:"hidden"},details:{background:e.palette.background.paper},accordionControl:{height:12,width:"100%","&:hover":{background:e.palette.action.hover},display:"flex",alignItems:"center",justifyContent:"center"},accordionRoot:{background:e.palette.divider},resizeHandle:{width:"100%",height:4,position:"absolute",cursor:"row-resize",zIndex:100},expandIcon:{},title:{userSelect:"none"},alertContainer:{display:"flex",alignItems:"center",justifyContent:"center"}})));function Co(e,t){const{apolloRowHeight:n,selectedFeature:a}=e;if(t.current&&a){const o=e.getFeatureLayoutPosition(a);o&&t.current.scroll({top:(o.layoutRow+o.featureRow)*n,behavior:"smooth"})}}const xo=({onResize:e})=>{const{classes:t}=Eo(),n=y.useCallback((t=>{t.stopPropagation(),t.preventDefault(),e(t.movementY)}),[e]),a=y.useCallback((e=>{e.stopPropagation(),e.preventDefault(),globalThis.removeEventListener("mousemove",n),globalThis.removeEventListener("mouseup",a),globalThis.removeEventListener("mouseleave",a)}),[n]);return de.default.createElement("div",{onMouseDown:e=>{e.stopPropagation(),globalThis.addEventListener("mousemove",n),globalThis.addEventListener("mouseup",a),globalThis.addEventListener("mouseleave",a)},onClick:e=>{e.stopPropagation(),e.preventDefault()},className:t.resizeHandle})},To=v.observer((function({onClick:e,onResize:t,open:n,title:a}){const{classes:o}=Eo();return de.default.createElement("div",{className:o.accordionRoot},n&&t?de.default.createElement(xo,{onResize:t}):null,de.default.createElement("div",{className:o.accordionControl,onClick:e},de.default.createElement(n?Ie.default:Ce.default,{className:o.expandIcon}),a?de.default.createElement(p.Typography,{className:o.title,variant:"caption",component:"span"},a):null))})),Ao=v.observer((function({model:e,...t}){const n=r.getSession(e),{ontologyManager:a}=n.apolloDataStore,{featureTypeOntology:o}=a,l=o?.dataStore,{classes:s}=Eo(),{graphical:i,height:c,isShown:u,selectedFeature:d,table:f,tabularEditor:m,toggleShown:g}=e,h=y.useRef(null);y.useEffect((()=>{Co(e,h)}),[e,d]);const b=t=>{e.setDetailsHeight(e.detailsHeight-t)};if(!l)return de.default.createElement("div",{className:s.alertContainer},de.default.createElement(p.Alert,{severity:"error"},"Could not load feature type ontology."));if(i&&f){const n=m.isShown?e.detailsHeight:0,a=u?c-e.detailsHeight-24:0;return de.default.createElement("div",{style:{height:c}},de.default.createElement(To,{open:u,title:"Graphical",onClick:g}),de.default.createElement("div",{className:s.shading,ref:h,style:{height:a}},de.default.createElement(bo,{model:e,...t})),de.default.createElement(To,{title:"Table",open:m.isShown,onClick:m.togglePane,onResize:b}),de.default.createElement("div",{className:s.details,style:{height:n}},de.default.createElement(oa,{model:e})))}return i?de.default.createElement("div",{className:s.shading,ref:h,style:{height:c}},de.default.createElement(bo,{model:e,...t})):de.default.createElement("div",{className:s.details,style:{height:c}},de.default.createElement(oa,{model:e}))})),No=v.observer((function({model:e,...t}){const n=r.getSession(e),{ontologyManager:a}=n.apolloDataStore,{featureTypeOntology:o}=a,l=o?.dataStore,{classes:s}=Eo(),{detailsHeight:i,graphical:c,height:u,isShown:d,selectedFeature:f,table:m,tabularEditor:g,toggleShown:h}=e,b=y.useRef(null);y.useEffect((()=>{Co(e,b)}),[e,f]);const S=t=>{e.setDetailsHeight(i-t)};if(!l)return de.default.createElement("div",{className:s.alertContainer},de.default.createElement(p.Alert,{severity:"error"},"Could not load feature type ontology."));if(c&&m){const n=g.isShown?i:0,a=d?u-i-24:0;return de.default.createElement("div",{style:{height:u}},de.default.createElement(To,{open:d,title:"Graphical",onClick:h}),de.default.createElement("div",{className:s.shading,ref:b,style:{height:a}},de.default.createElement(vo,{model:e,...t})),de.default.createElement(To,{title:"Table",open:g.isShown,onClick:g.togglePane,onResize:S}),de.default.createElement("div",{className:s.details,style:{height:n}},de.default.createElement(oa,{model:e})))}return c?de.default.createElement("div",{className:s.shading,ref:b,style:{height:u}},de.default.createElement(vo,{model:e,...t})):de.default.createElement("div",{className:s.details,style:{height:u}},de.default.createElement(oa,{model:e}))})),Fo=i.types.model("JobsManager",{}).views((e=>({get jobStatusWidget(){const{widgets:t}=r.getSession(e);let n=t.get("JobsList");return n||(n=r.getSession(e).addWidget("JobsListWidget","JobsList")),n}}))).actions((e=>({update(t,n,a){e.jobStatusWidget.updateJobStatusMessage(t,n),a&&e.jobStatusWidget.updateJobProgressPct(t,a)},abortJob(t,n){const a=r.getSession(e);if(r.isSessionModelWithWidgets(a)){a.showWidget(e.jobStatusWidget),e.jobStatusWidget.updateJobStatusMessage(t,n??"Aborted unexpectedly");const o=e.jobStatusWidget.jobs.findIndex((e=>e.name===t));e.jobStatusWidget.addAbortedJob({...e.jobStatusWidget.jobs[o]}),e.jobStatusWidget.removeJob(t),a.notify("Job aborted","info")}},runJob(t){const n=r.getSession(e);r.isSessionModelWithWidgets(n)&&(n.showWidget(e.jobStatusWidget),e.jobStatusWidget.addJob(t))},done(t){const n=r.getSession(e);r.isSessionModelWithWidgets(n)&&(n.showWidget(e.jobStatusWidget),e.jobStatusWidget.removeJob(t.name),e.jobStatusWidget.addFinishedJob({name:t.name,statusMessage:"All operations successful",progressPct:100,cancelCallback:t.cancelCallback}))}})));class ko{clientStore;constructor(e){this.clientStore=e}}class Do{dataStore;constructor(e){this.dataStore=e}recentChanges=[];async submit(n,a={}){const{addToRecents:o=!0,submitToBackend:l=!0,updateJobsManager:s=!1}=a,i=r.getSession(this.dataStore),c=new AbortController,{jobsManager:u}=r.getSession(this.dataStore),d={name:n.typeName,statusMessage:"Pre-validating",progressPct:0,cancelCallback:()=>{c.abort()}};s&&u.runJob(d);const f=await t.validationRegistry.frontendPreValidate(n);if(!f.ok){const e=`Pre-validation failed: "${f.resultsMessages}"`;return s&&u.abortJob(d.name,e),void i.notify(e,"error")}try{await n.execute(this.dataStore)}catch(e){return s&&u.abortJob(d.name,String(e)),console.error(e),void i.notify(String(e),"error")}if((await t.validationRegistry.frontendPostValidate(n,this.dataStore)).ok||await this.revert(n),l){s&&u.update(d.name,"Submitting to driver");const{collaborationServerDriver:t,getBackendDriver:o}=this.dataStore,r=e.isAssemblySpecificChange(n)?o(n.assembly):t;let l;try{l=await r.submitChange(n,a)}catch(e){return s&&u.abortJob(d.name,String(e)),console.error(e),i.notify(String(e),"error"),void await this.revert(n,!1)}if(!l.ok){const e=`Post-validation failed: "${f.resultsMessages}"`;return s&&u.abortJob(d.name,e),i.notify(e,"error"),void await this.revert(n,!1)}n.notification&&i.notify(n.notification,"success")}o&&this.recentChanges.push(n),s&&u.done(d)}async revert(e,t=!0){const n=e.getInverse();return this.submit(n,{submitToBackend:t,addToRecents:!1})}async revertLastChange(){const e=this.recentChanges.pop();if(e)return this.revert(e);r.getSession(this.dataStore).notify("No changes to undo!","warning")}}class Ro extends ko{inFlight=new Map;async fetch(e,t,n){return e.getFetcher({locationType:"UriLocation",uri:t.toString()})(t,n)}async searchFeatures(e,t){const n=this.clientStore.getInternetAccount(t[0]),{baseURL:a}=n,o=new URL("features/searchFeatures",a),r=new URLSearchParams({assemblies:t.join(","),term:e});o.search=r.toString();const l=o.toString(),s=await this.fetch(n,l);if(!s.ok){const e=await je(s,"searchFeatures failed");throw new Error(e)}return s.json()}async getFeatures(e){const{assemblyName:t,end:n,refName:o,start:l}=e,{assemblyManager:s}=r.getSession(this.clientStore),i=s.get(t);if(!i)throw new Error(`Could not find assembly with name "${t}"`);const{ids:c}=a.getConf(i,["sequence","metadata"]),u=c[o];if(!u)throw new Error(`Could not find refSeq "${o}"`);const d=this.clientStore.getInternetAccount(t),{baseURL:f}=d,m=new URL("features/getFeatures",f),g=new URLSearchParams({refSeq:u,start:String(l),end:String(n)});m.search=g.toString();const p=m.toString(),h=await this.fetch(d,p);if(!h.ok){const e=await je(h,"getFeatures failed");throw new Error(e)}return this.checkSocket(t,o,d),h.json()}checkSocket(t,n,a){const{socket:o}=a,r=a.retrieveToken(),l=`${t}-${n}`,s=new Do(this.clientStore);o.hasListeners(l)||o.on(l,(async t=>{if(a.setLastChangeSequenceNumber(Number(t.changeSequence)),t.userSessionId!==r&&t.channel===l){const n=e.Change.fromJSON(t.changeInfo);await s.submit(n,{submitToBackend:!1})}}))}async getSequence(e){const t=`${e.refName}:${e.start}-${e.end}`,n=this.inFlight.get(t),{assemblyName:o,end:l,refName:s,start:i}=e,{assemblyManager:c}=r.getSession(this.clientStore),u=c.get(o);if(!u)throw new Error(`Could not find assembly with name "${o}"`);const{ids:d}=a.getConf(u,["sequence","metadata"]),f=d[s];if(!f)throw new Error(`Could not find refSeq "${s}"`);if(n)return{seq:await n,refSeq:f};let m=this.clientStore.assemblies.get(o);m||(m=this.clientStore.addAssembly(o));let g=m.refSeqs.get(f);g||(g=m.addRefSeq(f,s));const p=g.getSequence(i,l);if(p.length===l-i)return{seq:p,refSeq:f};const h=this.clientStore.getInternetAccount(o),{baseURL:y}=h,b=new URL("sequence",y),S=new URLSearchParams({refSeq:f,start:String(i),end:String(l)});b.search=S.toString();const w=b.toString(),v=this.getSeqFromServer(h,w,g,i,l);this.inFlight.set(t,v);const E=await v;return this.checkSocket(o,s,h),this.inFlight.delete(t),{seq:E,refSeq:f}}async getSeqFromServer(e,t,n,a,o){const r=await this.fetch(e,t);if(!r.ok){let e;try{e=await r.text()}catch{e=""}throw new Error(`getSequence failed: ${r.status} (${r.statusText})${e?` (${e})`:""}`)}const l=await r.text();return n.addSequence({sequence:l,start:a,stop:o}),l}async getRefNameAliases(e){const{assemblyManager:t}=r.getSession(this.clientStore);if(!t.get(e))throw new Error(`Could not find assembly with name "${e}"`);const n=this.clientStore.getInternetAccount(e),{baseURL:a}=n,o=new URL("refSeqs",a),l=new URLSearchParams({assembly:e});o.search=l.toString();const s=o.toString(),i=await this.fetch(n,s);if(!i.ok){let e;try{e=await i.text()}catch{e=""}throw new Error(`getRefNameAliases failed: ${i.status} (${i.statusText})${e?` (${e})`:""}`)}return(await i.json()).map((e=>({refName:e.name,aliases:[e._id,...e.aliases],uniqueId:`alias-${e._id}`})))}async getRegions(e){const{assemblyManager:t}=r.getSession(this.clientStore);if(!t.get(e))throw new Error(`Could not find assembly with name "${e}"`);const n=this.clientStore.getInternetAccount(e),{baseURL:a}=n,o=new URL("refSeqs",a),l=new URLSearchParams({assembly:e});o.search=l.toString();const s=o.toString(),i=await this.fetch(n,s);if(!i.ok){let e;try{e=await i.text()}catch{e=""}throw new Error(`getRegions failed: ${i.status} (${i.statusText})${e?` (${e})`:""}`)}return(await i.json()).map((e=>({refName:e.name,start:0,end:e.length})))}getAssemblies(e){const{assemblyManager:t}=r.getSession(this.clientStore);return t.assemblies.filter((t=>{const n=a.getConf(t,["sequence","metadata"]);return!(!(n&&n.apollo&&n.internetAccountConfigId)||e&&n.internetAccountConfigId!==e)}))}async submitChange(e,n={}){const{internetAccountId:a}=n,o=this.clientStore.getInternetAccount("assembly"in e?e.assembly:void 0,a),{baseURL:r}=o,l=new URL("changes",r).href,s=await this.fetch(o,l,{method:"POST",body:JSON.stringify(e.toJSON()),headers:{"Content-Type":"application/json"}});if(!s.ok){const e=await je(s,"submitChange failed");throw new Error(e)}const i=new t.ValidationResultSet;return s.ok||(i.ok=!1),i}}class Mo extends ko{async getFeatures(){return[[],[]]}async getSequence(e){const{assemblyName:t,end:n,refName:a,start:o}=e,r=this.clientStore.assemblies.get(t);if(!r)return{seq:"",refSeq:a};const l=r.refSeqs.get(a);return l?{seq:l.getSequence(o,n),refSeq:a}:{seq:"",refSeq:a}}async getRefNameAliases(e){const t=this.clientStore.assemblies.get(e),n=[];if(!t)return n;for(const[,e]of t.refSeqs)n.push({refName:e.name,aliases:[e._id],uniqueId:`alias-${e._id}`});return n}async getRegions(e){const t=this.clientStore.assemblies.get(e);if(!t)return[];const n=[];for(const[,a]of t.refSeqs)n.push({assemblyName:e,refName:a.name,start:a.sequence[0].start,end:a.sequence[0].stop});return n}getAssemblies(){const{assemblyManager:e}=r.getSession(this.clientStore);return e.assemblies.filter((e=>{const t=a.getConf(e,["sequence","metadata"]);return Boolean(t&&t.apollo&&!t.file&&!t.internetAccountConfigId)}))}async submitChange(e,n={}){const{clientStore:a}=this,{assemblies:o}=a;a.clearCheckResults();for(const[,e]of o)if("InMemoryFileDriver"===e.backendDriverType){const t=await Oe(e);a.addCheckResults(t)}return new t.ValidationResultSet}async searchFeatures(e,t){return[]}}class Io extends ko{async loadAssembly(e){const{assemblyManager:t}=r.getSession(this.clientStore),n=t.get(e);if(!n)throw new Error(`Assembly ${e} not found`);const{file:o}=a.getConf(n,["sequence","metadata"]),l=require("node:fs");return Be(e,await l.promises.readFile(o,"utf8"),this.clientStore)}async getAssembly(e){let t=this.clientStore.assemblies.get(e);return t||(t=await this.loadAssembly(e)),t}async getRefNameAliases(e){const t=await this.getAssembly(e),n=[];for(const[,e]of t.refSeqs)n.push({refName:e.name,aliases:[e._id],uniqueId:`alias-${e._id}`});return n}async getFeatures(e){return await this.getAssembly(e.assemblyName),[[],[]]}async getSequence(e){const{assemblyName:t,end:n,refName:a,start:o}=e,r=(await this.getAssembly(t)).refSeqs.get(a);if(!r)throw new Error(`refSeq ${a} not found in client data store`);return{seq:r.getSequence(o,n),refSeq:a}}async getRegions(e){const t=await this.getAssembly(e),n=[];for(const[,a]of t.refSeqs)n.push({assemblyName:e,refName:a.name,start:a.sequence[0].start,end:a.sequence[0].stop});return n}getAssemblies(){const{assemblyManager:e}=r.getSession(this.clientStore);return e.assemblies.filter((e=>{const t=a.getConf(e,["sequence","metadata"]);return Boolean(t&&t.apollo&&!t.internetAccountConfigId&&t.file)}))}async submitChange(n){if(!e.isAssemblySpecificChange(n))throw new Error(`Cannot use this type of change with local file: "${n.typeName}"`);const{assemblyManager:o}=r.getSession(this.clientStore),l=o.get(n.assembly);if(!l)throw new Error(`Could not find assembly with name "${n.assembly}"`);const{file:s}=a.getConf(l,["sequence","metadata"]),c=this.clientStore.assemblies.get(n.assembly);if(!c)throw new Error(`Could not find assembly in client with name "${n.assembly}"`);const u=new Set(...c.refSeqs.keys()),{checkResults:d}=this.clientStore;for(const e of d.values())u.has(e.refSeq)&&d.delete(e._id);const f=await Oe(c);this.clientStore.addCheckResults(f);const m=[{directive:"gff-version",value:"3"}];for(const[,e]of c.refSeqs)m.push({directive:"sequence-region",value:`${e.name} 1 ${e.sequence[0].stop}`});for(const e of c.comments)m.push({comment:e});for(const[,e]of c.refSeqs){const{features:n}=e;for(const[,e]of n)m.push(t.annotationFeatureToGFF3(i.getSnapshot(e)))}for(const[,e]of c.refSeqs){const[n]=e.sequence,a=t.splitStringIntoChunks(n.sequence,80).join("\n");m.push({id:e.name,description:e.description,sequence:a})}const g=re.default.formatSync(m),p=require("node:fs");return await p.promises.writeFile(s,g,"utf8"),new t.ValidationResultSet}async searchFeatures(e,t){return[]}}function Po(e,n){const o=new AbortController,{signal:l}=o,c=e.evaluateExtensionPoint("Apollo-extendAnnotationFeature",H.AnnotationFeatureModel),u=function(e){return i.types.model("ClientDataStore",{typeName:i.types.optional(i.types.literal("Client"),"Client"),assemblies:i.types.map(H.ApolloAssembly),checkResults:i.types.map(H.CheckResult),ontologyManager:i.types.optional(pt,{})}).views((t=>({get internetAccounts(){return i.getRoot(t).internetAccounts},get pluginConfiguration(){return i.getRoot(t).jbrowse.configuration.ApolloPlugin},getFeature:n=>i.resolveIdentifier(e,t.assemblies,n)}))).actions((e=>({addAssembly(t,n){const a={_id:t,refSeqs:{}};return n&&(a.backendDriverType=n),e.assemblies.put(a)},addFeature(t,n){const a=e.assemblies.get(t);if(!a)throw new Error(`Could not find assembly "${t}" to add feature "${n._id}"`);const o=a.refSeqs.get(n.refSeq);if(!o)throw new Error(`Could not find refSeq "${n.refSeq}" to add feature "${n._id}"`);o.features.put(n)},deleteFeature(t){const n=e.getFeature(t);if(!n)throw new Error(`Could not find feature "${t}" to delete`);const{_id:a,parent:o}=n;o?o.deleteChild(t):i.getParentOfType(n,H.ApolloRefSeq).deleteFeature(a)},deleteAssembly(t){e.assemblies.delete(t)},addCheckResult(t){e.checkResults.put(t)},addCheckResults(t){for(const n of t)e.checkResults.has(n._id)||e.checkResults.put(n)},deleteCheckResult(t){e.checkResults.delete(t)},clearCheckResults(){e.checkResults.clear()}}))).volatile((e=>({changeManager:new Do(e),collaborationServerDriver:new Ro(e),inMemoryFileDriver:new Mo(e),desktopFileDriver:r.isElectron?new Io(e):void 0}))).actions((e=>({afterCreate(){i.addDisposer(e,s.autorun((()=>{const{ontologyManager:t,pluginConfiguration:n}=e,o=n.ontologies;for(const n of o||[]){const[o,l,s,i]=[a.readConfObject(n,"name"),a.readConfObject(n,"version"),a.readConfObject(n,"source"),a.readConfObject(n,"textIndexFields")];if(!t.findOntology(o)){const n=r.getSession(e),{jobsManager:a}=n,c=new AbortController,u=`Loading ontology "${o}"`,d={name:u,statusMessage:`Loading ontology "${o}", version "${l}", this may take a while`,progressPct:0,cancelCallback:()=>{c.abort(),a.abortJob(d.name)}};t.addOntology(o,l,s,{textIndexing:{indexFields:i},update:(e,t)=>{0!==t?100!==t?a.update(u,e,t):a.done(d):a.runJob(d)}})}}})))}}))).views((e=>({getBackendDriver(t){if(!t)return e.collaborationServerDriver;const n=r.getSession(e),{assemblyManager:o}=n,l=o.get(t);if(!l)return e.collaborationServerDriver;const{file:s,internetAccountConfigId:i}=a.getConf(l,["sequence","metadata"]);return r.isElectron&&s?e.desktopFileDriver:i?e.collaborationServerDriver:e.inMemoryFileDriver},getInternetAccount(t,n){if(!(t??n))throw new Error("Must provide either assemblyName or internetAccountId");let o=n;if(t&&!o){const{assemblyManager:n}=r.getSession(e),l=n.get(t);if(!l)throw new Error(`No assembly found with name ${t}`);({internetAccountConfigId:o}=a.getConf(l,["sequence","metadata"]))}const{internetAccounts:l}=e,s=l.find((e=>e.internetAccountId===o));if(!s)throw new Error(`No InternetAccount found with config id ${n}`);return s}}))).actions((e=>({loadFeatures:i.flow((function*(t){for(const n of t){const t=e.getBackendDriver(n.assemblyName);if(!t)return;const[a,o]=yield t.getFeatures(n);if(0===a.length)continue;const{assemblyName:r,refName:l}=n;let s=e.assemblies.get(r);s||(s=e.assemblies.put({_id:r,refSeqs:{}}));const[i]=a;let c=s.refSeqs.get(i.refSeq);c||(c=s.refSeqs.put({_id:i.refSeq,name:l,features:{}}));for(const e of a)c.features.has(e._id)||c.features.put(e);e.addCheckResults(o)}})),loadRefSeq:i.flow((function*(t){for(const n of t){const t=e.getBackendDriver(n.assemblyName);if(!t)return;const{refSeq:a,seq:o}=yield t.getSequence(n),{assemblyName:r,end:l,refName:s,start:i}=n;let c=e.assemblies.get(r);c||(c=e.assemblies.put({_id:r,refSeqs:{}}));let u=c.refSeqs.get(a);u||(u=c.refSeqs.put({_id:a,name:s,sequence:[]})),u.addSequence({start:i,stop:l,sequence:o})}}))})))}(c),d=n.props({apolloDataStore:i.types.optional(u,{typeName:"Client"}),apolloSelectedFeature:i.types.safeReference(c),jobsManager:i.types.optional(Fo,{})}).extend((()=>{const e=s.observable.array([]);return{views:{get collaborators(){return e}},actions:{addOrUpdateCollaborator(t){const n=e.find((e=>e.id===t.id));n?n.locations=t.locations:e.push(t)}}}})).actions((e=>({apolloSetSelectedFeature(t){e.apolloSelectedFeature=t},addApolloTrackConfig(t,n){const o=`apollo_track_${t.name}`;e.tracks.some((e=>e.trackId===o))||e.addTrackConf({type:"ApolloTrack",trackId:o,name:`Annotations (${a.getConf(t,"displayName")||t.name})`,assemblyNames:[t.name],textSearching:{textSearchAdapter:{type:"ApolloTextSearchAdapter",trackId:o,assemblyNames:[t.name],textSearchAdapterId:`apollo_search_${t.name}`,...n?{baseURL:{uri:n,locationType:"UriLocation"}}:{}}}})},broadcastLocations(){const{internetAccounts:t}=i.getRoot(e),n=[];for(const t of e.views){if("LinearGenomeView"!==t.type)return;const a=t;if(a.initialized){const{dynamicBlocks:t}=a;t.forEach((t=>{if(void 0!==t.regionNumber){const{assemblyName:a,end:o,refName:r,start:l}=t,s=e.apolloDataStore.assemblies.get(a);s&&"CollaborationServerDriver"===s.backendDriverType&&n.push({assemblyName:a,refName:r,start:l,end:o})}}))}}if(0===n.length){for(const e of t)"baseURL"in e&&e.postUserLocation([]);return}const a=[];for(const e of t)if("baseURL"in e){for(const e of n)a.push({assemblyId:e.assemblyName,refSeq:e.refName,start:e.start,end:e.end});e.postUserLocation(a)}}}))).actions((e=>({afterCreate:i.flow((function*(){const t=i.getSnapshot(e),{id:n,name:a}=t;i.applySnapshot(e,{name:a,id:n});const{internetAccounts:o,jbrowse:r}=i.getRoot(e);s.autorun((()=>{const t=[];for(const n of e.views){if("LinearGenomeView"!==n.type)return;const a=n;if(a.initialized){const{dynamicBlocks:n}=a;n.forEach((n=>{if(void 0!==n.regionNumber){const{assemblyName:a,end:o,refName:r,start:l}=n,s=e.apolloDataStore.assemblies.get(a);s&&"CollaborationServerDriver"===s.backendDriverType&&t.push({assemblyName:a,refName:r,start:l,end:o})}}))}}if(0===t.length){for(const e of o)"baseURL"in e&&e.postUserLocation([]);return}const n=[];for(const e of o)if("baseURL"in e){for(const e of t)n.push({assemblyId:e.assemblyName,refSeq:e.refName,start:e.start,end:e.end});e.postUserLocation(n)}}),{name:"ApolloSession"});for(const n of o){if("ApolloInternetAccount"!==n.type)continue;const{baseURL:a}=n,o=new URL("jbrowse/config.json",a).href,s=n.getFetcher({locationType:"UriLocation",uri:o});let c,u;try{c=yield s(o,{signal:l})}catch(e){console.error(e);continue}if(c.ok){try{u=yield c.json()}catch(e){console.error(e);continue}i.applySnapshot(r,u),i.applySnapshot(e,t)}else{const e=yield je(c,"Failed to fetch assemblies");console.error(e)}}})),beforeDestroy(){o.abort("destroying session model")}}))).views((e=>{const n=e.getTrackActionMenuItems;return{getTrackActionMenuItems(o){if("ApolloTrack"===o.type||"ReferenceSequenceTrack"===o.type)return n?.(o);const r=a.readConfObject(o,"trackId");return r.endsWith("-sessionTrack")?[...n?.(o)??[],{label:"Save track to Apollo",onClick:async()=>{const{internetAccounts:n,jbrowse:a}=i.getRoot(e),l=i.getSnapshot(a);let s;s=t.filterJBrowseConfig(l),0===Object.keys(s).length&&(s=void 0);const c={...i.getSnapshot(o),trackId:r.slice(0,r.length-13)};for(const a of n){if("ApolloInternetAccount"!==a.type)continue;const n=new t.ImportJBrowseConfigChange({typeName:"ImportJBrowseConfigChange",oldJBrowseConfig:s,newJBrowseConfig:{...s,tracks:s?.tracks&&[...s.tracks,c]}}),{internetAccountId:o}=a;await e.apolloDataStore.changeManager.submit(n,{internetAccountId:o});const{notify:r}=e;r("Track added","success")}e.deleteTrackConf(o),a.addTrackConf(c)},icon:qe.default}]:[...n?.(o)??[],{label:"Remove track from Apollo",onClick:async()=>{const{internetAccounts:n,jbrowse:a}=i.getRoot(e),l=i.getSnapshot(a);let s;s=t.filterJBrowseConfig(l),0===Object.keys(s).length&&(s=void 0);const c=s?.tracks?.filter((e=>e.trackId!==r));for(const a of n){if("ApolloInternetAccount"!==a.type)continue;const n=new t.ImportJBrowseConfigChange({typeName:"ImportJBrowseConfigChange",oldJBrowseConfig:s,newJBrowseConfig:{...s,tracks:c}}),{internetAccountId:o}=a;await e.apolloDataStore.changeManager.submit(n,{internetAccountId:o});const{notify:r}=e;r("Track removed","success")}e.deleteTrackConf(o),a.deleteTrackConf(o)},icon:qe.default}]}}}));return i.types.snapshotProcessor(d,{postProcessor(e,t){e.apolloSelectedFeature=void 0;const n=Object.fromEntries(Object.entries(e.apolloDataStore.assemblies).filter((([,e])=>"InMemoryFileDriver"===e.backendDriverType)));if(e.apolloDataStore={typeName:"Client",assemblies:n,checkResults:{}},!t)return e;const{apolloDataStore:a}=t,{checkResults:o}=a;for(const[,t]of o){const[n]=t.ids;if(!n)continue;const o=a.assemblies.get(n.assemblyId);o&&"InMemoryFileDriver"===o.backendDriverType&&(e.apolloDataStore.checkResults[t._id]=i.getSnapshot(t))}return e}})}const qo="WorkerGlobalScope"in globalThis;for(const[n,a]of Object.entries(t.changes))e.changeRegistry.registerChange(n,a);const Lo=new t.CDSCheck;e.checkRegistry.registerCheck(Lo.name,Lo),t.validationRegistry.registerValidation(new t.CoreValidation),t.validationRegistry.registerValidation(new t.ParentChildValidation),exports.default=class extends ae.default{name="ApolloPlugin";version="0.3.6";configurationSchema=oo;install(e){!function(e){e.addAdapterType((()=>new we.default({name:"ApolloSequenceAdapter",configSchema:on,adapterMetadata:{category:void 0,hiddenFromGUI:!0,description:void 0},AdapterClass:an})))}(e),function(e){e.addAdapterType((()=>new we.default({name:"ApolloRefNameAliasAdapter",configSchema:en,adapterMetadata:{category:void 0,hiddenFromGUI:!0,description:void 0},AdapterClass:Qt})))}(e),function(e){e.addTextSearchAdapterType((()=>new o.TextSearchAdapterType({name:"ApolloTextSearchAdapter",displayName:"Apollo text search adapter",configSchema:ln,AdapterClass:rn,description:"Apollo Text Search adapter"})))}(e),e.addWidgetType((()=>{const e=a.ConfigurationSchema("ApolloFeatureDetailsWidget",{});return new o.WidgetType({name:"ApolloFeatureDetailsWidget",heading:"Apollo feature details",configSchema:e,stateModel:Tn,ReactComponent:xn})})),e.addWidgetType((()=>{const e=a.ConfigurationSchema("ApolloTranscriptDetails",{});return new o.WidgetType({name:"ApolloTranscriptDetails",heading:"Apollo transcript details",configSchema:e,stateModel:An,ReactComponent:$n})})),e.addTrackType((()=>{const t=a.ConfigurationSchema("ApolloTrack",{adapter:""},{baseConfiguration:o.createBaseTrackConfig(e),explicitIdentifier:"trackId"});return new o.TrackType({name:"ApolloTrack",configSchema:t,stateModel:o.createBaseTrackModel(e,"ApolloTrack",t)})})),e.addInternetAccountType((()=>new o.InternetAccountType({name:"ApolloInternetAccount",configSchema:Le,stateModel:Yt(Le)}))),e.addDisplayType((()=>new o.DisplayType({name:"LinearApolloDisplay",configSchema:jn,stateModel:Ja(0,jn),trackType:"ApolloTrack",viewType:"LinearGenomeView",ReactComponent:Ao}))),e.addDisplayType((()=>new o.DisplayType({name:"LinearApolloSixFrameDisplay",configSchema:Va,stateModel:ao(0,Va),trackType:"ApolloTrack",viewType:"LinearGenomeView",ReactComponent:No}))),e.addToExtensionPoint("Core-extendSession",Po.bind(this,e)),e.addToExtensionPoint("Core-extendPluggableElement",(e=>{if("LinearGenomeView"===e.name){const{stateModel:t}=e,n=t.views((e=>{const t=e.rubberBandMenuItems;return{rubberBandMenuItems:()=>[...t(),{label:"Add new feature",icon:oe.default,onClick:()=>{const t=r.getSession(e),{leftOffset:n,rightOffset:a}=e,o=e.getSelectedRegions(n,a);t.queueDialog((e=>[Tt,{session:t,handleClose:()=>{e()},region:o[0],changeManager:t.apolloDataStore.changeManager}]))}}]}}));e.stateModel=n}return e})),e.addToExtensionPoint("Core-extendPluggableElement",ro),e.addToExtensionPoint("Core-extendPluggableElement",ho),qo||e.addToExtensionPoint("Core-extendWorker",(t=>"on"in t&&t.on?(t.on("apollo",(async n=>{if("object"!=typeof(a=n)||null===a||!("apollo"in a)||!0!==a.apollo)return;var a;const{apollo:o,messageId:r,method:l}=n;switch(l){case"getSequence":{const{region:a}=n,{assemblyName:l}=a,s=e.rootModel?.session?.apolloDataStore;if(!s)break;const i=s.getBackendDriver(l),{seq:c}=await i.getSequence(a);t.workers[0].postMessage({apollo:o,messageId:r,sequence:c});break}case"getRegions":{const{assembly:a}=n,l=e.rootModel?.session?.apolloDataStore;if(!l)break;const s=l.getBackendDriver(a),i=await s.getRegions(a);t.workers[0].postMessage({apollo:o,messageId:r,regions:i});break}case"getRefNameAliases":{const{assembly:a}=n,l=e.rootModel?.session?.apolloDataStore;if(!l)break;const s=l.getBackendDriver(a),i=await s.getRefNameAliases(a);t.workers[0].postMessage({apollo:o,messageId:r,refNameAliases:i});break}}})),t):t))}configure(e){r.isAbstractMenuManager(e.rootModel)&&(e.rootModel.appendToMenu("Apollo",{label:"Download GFF3",onClick:e=>{e.queueDialog((t=>[Dt,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"Manage Checks",onClick:e=>{e.queueDialog((t=>[It,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"View Change Log",onClick:e=>{e.queueDialog((t=>[Bt,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"Open local GFF3 file",onClick:e=>{e.queueDialog((t=>[qt,{session:e,handleClose:()=>{t()},inMemoryFileDriver:e.apolloDataStore.inMemoryFileDriver}]))}}),e.rootModel.appendToMenu("Apollo",{label:"View check results",onClick:e=>{e.queueDialog((t=>[$t,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"Log out",onClick:e=>{e.queueDialog((t=>[Mt,{session:e,handleClose:()=>{t()}}]))}}))}};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("@apollo-annotation/common"),t=require("@apollo-annotation/shared"),n=require("@jbrowse/core/Plugin"),a=require("@jbrowse/core/configuration"),o=require("@jbrowse/core/pluggableElementTypes"),r=require("@jbrowse/core/util"),l=require("@mui/icons-material/Add"),s=require("mobx"),i=require("mobx-state-tree"),c=require("socket.io-client"),u=require("@gmod/gff"),d=require("@mui/icons-material/Info"),f=require("@mui/icons-material/Link"),m=require("@mui/icons-material/RadioButtonChecked"),g=require("@mui/icons-material/RadioButtonUnchecked"),p=require("@mui/material"),h=require("bson-objectid"),y=require("react"),b=require("tss-react/mui"),S=require("@jbrowse/core/ui"),w=require("@mui/icons-material/Close"),E=require("mobx-react"),v=require("@jbrowse/core/util/types/mst"),C=require("idb/with-async-ittr"),x=require("@jbrowse/core/util/aborting"),T=require("jsonpath"),A=require("@jbrowse/core/util/io"),F=require("fast-deep-equal/es6"),D=require("file-saver"),k=require("@mui/material/Checkbox"),N=require("@mui/material/FormControlLabel"),I=require("@mui/material/LinearProgress"),R=require("@mui/icons-material/Delete"),M=require("@mui/x-data-grid"),L=require("nanoid"),P=require("@mui/icons-material/AccountCircle"),q=require("@jbrowse/core/pluggableElementTypes/AdapterType"),O=require("@jbrowse/core/data_adapters/BaseAdapter"),_=require("@jbrowse/core/util/rxjs"),B=require("@jbrowse/core/util/simpleFeature"),U=require("@jbrowse/core/TextSearch/BaseResults"),$=require("@mui/icons-material/ExpandMore"),G=require("@mui/icons-material/Edit"),j=require("@mui/icons-material/MoreHoriz"),W=require("@mui/icons-material/AddBox"),H=require("@apollo-annotation/mst"),z=require("@emotion/styled"),J=require("@mui/icons-material/ContentCopy"),V=require("@mui/icons-material/ContentCut"),X=require("@mui/icons-material/Remove"),K=require("@mui/icons-material/Clear"),Y=require("@mui/icons-material/UnfoldLess"),Z=require("@jbrowse/core/util/tracks"),Q=require("@mui/icons-material/ExpandLess"),ee=require("@mui/icons-material/Error"),te=require("@mui/icons-material/Save");function ne(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var ae=ne(n),oe=ne(l),re=ne(u),le=ne(d),se=ne(f),ie=ne(m),ce=ne(g),ue=ne(h),de=ne(y),fe=ne(w),me=ne(T),ge=ne(F),pe=ne(k),he=ne(N),ye=ne(I),be=ne(R),Se=ne(P),we=ne(q),Ee=ne(B),ve=ne(U),Ce=ne($),xe=ne(G),Te=ne(j),Ae=ne(W),Fe=ne(z),De=ne(J),ke=ne(V),Ne=ne(X),Ie=ne(K),Re=ne(Y),Me=ne(Q),Le=ne(ee),Pe=ne(te);const qe=a.ConfigurationSchema("ApolloInternetAccount",{baseURL:{description:"Location of Apollo server",type:"string",defaultValue:""},tokenType:{description:"A custom name for a token to include in the header",type:"string",defaultValue:"Bearer"}},{baseConfiguration:o.BaseInternetAccountConfig,explicitlyTyped:!0});async function Oe(e,n,a){const o=re.default.parseStringSync(n,{parseSequences:!0,parseComments:!0,parseDirectives:!1,parseFeatures:!0});if(0===o.length)throw new Error("No features found in GFF3 file");let r=0,l=a.assemblies.get(e);l||(l=a.addAssembly(e,"InMemoryFileDriver"));for(const e of o)if(Array.isArray(e)){const n=t.gff3ToAnnotationFeature(e),a=l.refSeqs.get(n.refSeq)??l.addRefSeq(n.refSeq,n.refSeq);a.features.has(n._id)||a.addFeature(n)}else if("comment"in e)l.addComment(e.comment);else{r++;let t=l.refSeqs.get(e.id);t||(t=l.addRefSeq(e.id,e.id,e.description)),e.description&&!t.description&&t.setDescription(e.description),t.addSequence({start:0,stop:e.sequence.length,sequence:e.sequence})}if(0===r)throw new Error("No embedded FASTA section found in GFF3");const s=await _e(l);return a.addCheckResults(s),l}async function _e(t){const n=[];for(const a of t.refSeqs.values())for(const t of a.features.values())for(const o of e.checkRegistry.getChecks().values()){const e=await o.checkFeature(i.getSnapshot(t),((e,t)=>Promise.resolve(a.getSequence(e,t))));n.push(...e)}return n}function Be(e){const{attributes:t}=e,n=t.get("gff_name");return n?n[0]:""}function Ue(e){const{attributes:t}=e,n=t.get("gff_id"),a=t.get("transcript_id"),o=t.get("exon_id"),r=t.get("protein_id");return n?n[0]:a?a[0]:o?o[0]:r?r[0]:""}function $e(e){const t=Be(e),n=Ue(e);return t?`: ${t}`:n?`: ${n}`:""}function Ge(e,t=!1){const n=[];if(!e.featureAndGlyphUnderMouse)return n;n.push(e.featureAndGlyphUnderMouse.feature);for(const t of function(e){const t=[];let{parent:n}=e;for(;n;)t.push(n),({parent:n}=n);return t}(e.featureAndGlyphUnderMouse.feature))n.push(t);const{bp:a}=e,o=function(e){const t=[];if(e.children)for(const[,n]of e.children)t.push(n);return t}(e.featureAndGlyphUnderMouse.feature);for(const e of o)e.min<a&&e.max>=a&&n.push(e);if(!t)return n;if(e.featureAndGlyphUnderMouse.feature.parent){const t=e.featureAndGlyphUnderMouse.feature.parent.children;if(t)for(const[,o]of t)o._id!=e.featureAndGlyphUnderMouse.feature._id&&o.min<a&&o.max>=a&&n.push(o)}return n}function je(e,t,n,a){const o=a.bpToPx({refName:t,coord:e.min,regionNumber:n}),r=a.bpToPx({refName:t,coord:e.max,regionNumber:n});if(void 0===o||void 0===r)return;const{offsetPx:l}=a;return[o.offsetPx-l,r.offsetPx-l]}function We(e,t,n){const[a,o]=n;if(!(Math.abs(o-a)<8))return Math.abs(a-t)<4?{feature:e,edge:"min"}:Math.abs(o-t)<4?{feature:e,edge:"max"}:void 0}function He(e,t,n){const a=[{featureId:e._id,oldLocation:e[n],newLocation:t}],{parent:o}=e;return o&&("min"===n&&o[n]>t||"max"===n&&o[n]<t)&&a.push(...He(o,t,n)),a}function ze(e,t,n,a,o){const r=e._id,l=[{featureId:r,oldLocation:e[n],newLocation:t}],{parent:s,children:i}=e;if(i)for(const[,e]of i)e._id!==o&&("min"===n&&e[n]<t||"max"===n&&e[n]>t)&&l.push(...ze(e,t,n,a));if(s&&a){const e=[];if(s.children)for(const[,t]of s.children)t._id!==r&&e.push(t);if(0===e.length)l.push(...ze(s,t,n,a,r));else{const o=s[n],i=Math[n](...e.map((e=>e[n])),t);i!==o&&l.push(...ze(s,i,n,a,r))}}return l}function Je(e,t,n,a=!1){const o=e[n];if(t===o)throw new Error(`New and existing locations are the same: "${t}"`);return"min"===n?t>o?ze(e,t,n,a):He(e,t,n):t<o?ze(e,t,n,a):He(e,t,n)}async function Ve(e,t){let n;try{n=await e.text()}catch{n=""}return`${t?`${t} — `:""}${e.status} ${e.statusText}${n?` (${n})`:""}`}const Xe=b.makeStyles()((e=>({dialogTitle:{background:e.palette.primary.main,color:e.palette.primary.contrastText,padding:e.spacing(2)},closeButton:{position:"absolute",right:e.spacing(1),top:e.spacing(1.5),color:e.palette.primary.contrastText}}))),Ke=E.observer((function(e){const{classes:t}=Xe(),{handleClose:n,title:a,...o}=e;return de.default.createElement(S.Dialog,{...o,header:de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogTitle,{className:t.dialogTitle},a),de.default.createElement(p.IconButton,{"aria-label":"close",onClick:n,className:t.closeButton},de.default.createElement(fe.default,null)))})}));var Ye;!function(e){e.GFF3="text/x-gff3",e.FASTA="text/x-fasta",e.BGZIP_FASTA="application/x-bgzip-fasta",e.FAI="text/x-fai",e.GZI="application/x-gzi",e.EXTERNAL="text/x-external"}(Ye||(Ye={}));const Ze=b.makeStyles()((e=>({accordion:{border:`1px solid ${e.palette.divider}`,"&:not(:last-child)":{borderBottom:0}},accordionSummary:{flexDirection:"row-reverse"},accordionDetails:{padding:e.spacing(2),borderTop:"1px solid rgba(0, 0, 0, .125)"},radioIcon:{color:e?.palette?.tertiary?.contrastText},dialog:{minWidth:550,maxWidth:800}})));function Qe(e,t,n,a,o,r,l,s,i){return!(!e||!(t&&a||n===Ye.GFF3&&a||a&&o&&r||l&&s&&i))}function et({changeManager:e,handleClose:n,session:o}){const{classes:r}=Ze(),{internetAccounts:l}=i.getRoot(o),{notify:s}=o,c=l.filter((e=>"ApolloInternetAccount"===e.type));if(0===c.length)throw new Error("No Apollo internet account found");const[u,d]=y.useState(""),[f,m]=y.useState(""),[g,h]=y.useState(!1),[b,S]=y.useState(Ye.BGZIP_FASTA),[w,E]=y.useState(!0),[v,C]=y.useState(!1),[x,T]=y.useState(!1),[A,F]=y.useState(null),[D,k]=y.useState(null),[N,I]=y.useState(null),[R,M]=y.useState(""),[L,P]=y.useState(""),[q,O]=y.useState(""),[_,B]=y.useState(!1),[U,$]=y.useState(!1);async function G(e,t){const{jobsManager:n}=o,a=new AbortController,[{baseURL:r,getFetcher:l}]=c,s=new URL("files",r);s.searchParams.set("type",t);const i=s.href,d=new FormData;let f=e.name;t===Ye.FAI||t===Ye.GZI?f=`${f}.txt`:U&&!e.name.toLocaleLowerCase().endsWith(".gz")?f=`${f}.gz`:!U&&e.name.toLocaleLowerCase().endsWith(".gz")&&(f=`${f}.txt`),d.append("file",e,f),d.append("type",t);const g=l({locationType:"UriLocation",uri:i});if(g){const t={name:`UploadAssemblyFile for ${u}`,statusMessage:"Pre-validating",progressPct:0,cancelCallback:()=>{a.abort(),n.abortJob(t.name)}};n.runJob(t),n.update(t.name,`Uploading ${e.name}, this may take awhile`);const{signal:o}=a,r=await g(i,{method:"POST",body:d,signal:o});if(!r.ok){const e=await Ve(r,"Error when inserting new assembly (while uploading file)");return n.abortJob(t.name,e),m(e),""}const l=(await r.json())._id;return n.done(t),l}throw new Error("Failed to fetch")}y.useEffect((()=>{P(R?`${R}.fai`:"")}),[R]),y.useEffect((()=>{O(R?`${R}.gzi`:"")}),[R]),y.useEffect((()=>{$(!v&&b!==Ye.GFF3||!!A?.name.toLocaleLowerCase().endsWith(".gz"))}),[A,v,b]);let j=!1;try{const e=new URL(R);"http:"!==e.protocol&&"https:"!==e.protocol||(j=!0)}catch{}let W=!1;try{const e=new URL(L);"http:"!==e.protocol&&"https:"!==e.protocol||(W=!0)}catch{}let H=!1;try{const e=new URL(q);"http:"!==e.protocol&&"https:"!==e.protocol||(H=!0)}catch{}const[z,J]=de.default.useState("panelFastaInput"),V=e=>(t,n)=>{n&&J(e),$("panelGffInput"!==e)};return de.default.createElement(Ke,{open:!0,handleClose:n,"data-testid":"add-assembly-dialog",title:"Add new assembly",maxWidth:!1},de.default.createElement("form",{onSubmit:async function(a){let o;if(a.preventDefault(),m(""),T(!0),B(!0),s(`Assembly "${u}" is being added`,"info"),n(),a.preventDefault(),b===Ye.EXTERNAL)o=new t.AddAssemblyFromExternalChange({typeName:"AddAssemblyFromExternalChange",assembly:(new ue.default).toHexString(),assemblyName:u,externalLocation:{fa:R,fai:L,gzi:q}});else{if(!A)throw new Error("Missing fasta file");if(b===Ye.GFF3&&w){const e=await G(A,Ye.GFF3);o=new t.AddAssemblyAndFeaturesFromFileChange({typeName:"AddAssemblyAndFeaturesFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e}})}else if(b===Ye.GFF3){const e=await G(A,Ye.GFF3);o=new t.AddAssemblyFromFileChange({typeName:"AddAssemblyFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e}})}else if(v){const e=await G(A,Ye.FASTA);o=new t.AddAssemblyFromFileChange({typeName:"AddAssemblyFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e}})}else{if(!D||!N)throw new Error("Missing fasta index files");const e=await G(A,Ye.BGZIP_FASTA),n=await G(D,Ye.FAI),a=await G(N,Ye.GZI);o=new t.AddAssemblyFromFileChange({typeName:"AddAssemblyFromFileChange",assembly:(new ue.default).toHexString(),assemblyName:u,fileIds:{fa:e,fai:n,gzi:a}})}}const[{internetAccountId:r}]=c;await e.submit(o,{internetAccountId:r,updateJobsManager:!0}),T(!1),B(!1)},"data-testid":"submit-form"},de.default.createElement(p.DialogContent,{className:r.dialog},_?de.default.createElement(p.LinearProgress,null):null,de.default.createElement(p.TextField,{margin:"dense",id:"name",label:"Assembly name",type:"TextField",fullWidth:!0,variant:"outlined",onChange:e=>{T(!1),d(e.target.value),function(e){const{assemblies:t}=o;t.find((t=>a.readConfObject(t,"displayName")===e))?(h(!1),m(`Assembly ${e} already exists.`)):(h(!0),m(""))}(e.target.value)},disabled:x&&!f}),de.default.createElement(p.Accordion,{disableGutters:!0,elevation:0,square:!0,className:r.accordion,expanded:"panelFastaInput"===z,onChange:V("panelFastaInput")},de.default.createElement(p.AccordionSummary,{className:r.accordionSummary,expandIcon:"panelFastaInput"===z?de.default.createElement(ie.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",ml:5}}):de.default.createElement(ce.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",mr:5}}),"aria-controls":"panelFastaInputd-content",id:"panelFastaInputd-header"},de.default.createElement(p.Typography,{component:"span"},"FASTA input")),de.default.createElement(p.AccordionDetails,{className:r.accordionDetails},de.default.createElement(p.FormGroup,null,de.default.createElement(p.FormControlLabel,{"data-testid":"files-on-url-checkbox",control:de.default.createElement(p.Checkbox,{onChange:()=>{S(b===Ye.EXTERNAL?Ye.BGZIP_FASTA:Ye.EXTERNAL),b===Ye.EXTERNAL&&C(!1)},checked:b===Ye.EXTERNAL,disabled:v&&b!==Ye.GFF3}),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Use external URLs",de.default.createElement(p.Tooltip,{title:"Use external URLs to provide FASTA and index files. Does not copy the files to the Apollo collaboration server, so ensure the URLs are stable.",placement:"top-start"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{"data-testid":"sequence-is-editable-checkbox",control:de.default.createElement(p.Checkbox,{onChange:()=>{C(!v)}}),checked:v,disabled:b===Ye.EXTERNAL,label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Store sequence in database",de.default.createElement(p.Tooltip,{title:"Enables users to edit the genomic sequence, but comes with performance impacts. Use with care.",placement:"top-start"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{"data-testid":"fasta-is-gzip-checkbox",control:de.default.createElement(p.Checkbox,{checked:U,onChange:()=>{$(!v||!U)},disabled:!v}),label:"FASTA is gzip compressed"}),de.default.createElement(p.Table,{size:"small",sx:{mt:2}},b===Ye.BGZIP_FASTA||b===Ye.GFF3?de.default.createElement(p.TableBody,null,de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.Box,{display:"flex",alignItems:"center"},de.default.createElement("span",null,"FASTA"),de.default.createElement(p.Tooltip,{title:'Unless "Store sequence in database" enabled, FASTA input must be compressed with bgzip and indexed with samtools faidx (or equivalent). Compression is optional for sequences stored in the database.'},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement("input",{"data-testid":"fasta-input-file",type:"file",onChange:e=>{F(e.target.files?.item(0)??null)},disabled:x&&!f}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA index (.fai)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement("input",{"data-testid":"fai-input-file",type:"file",onChange:e=>{k(e.target.files?.item(0)??null)},disabled:x&&!f||v}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA binary index (.gzi)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement("input",{"data-testid":"gzi-input-file",type:"file",onChange:e=>{I(e.target.files?.item(0)??null)},disabled:x&&!f||v})))):de.default.createElement(p.TableBody,null,de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.Box,{display:"flex",alignItems:"center"},de.default.createElement("span",null,"FASTA"),de.default.createElement(p.Tooltip,{title:"Remote FASTA input must be compressed with bgzip and indexed with samtools faidx (or equivalent)"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.TextField,{"data-testid":"fasta-input-url",variant:"outlined",value:R,error:!j,onChange:e=>{M(e.target.value)},disabled:x&&!f,slotProps:{input:{startAdornment:de.default.createElement(p.InputAdornment,{position:"start"},de.default.createElement(se.default,null))}}}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA index (.fai)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.TextField,{"data-testid":"fai-input-url",variant:"outlined",value:L,error:!W,onChange:e=>{P(e.target.value)},disabled:x&&!f,slotProps:{input:{startAdornment:de.default.createElement(p.InputAdornment,{position:"start"},de.default.createElement(se.default,null))}}}))),de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},"FASTA binary index (.gzi)"),de.default.createElement(p.TableCell,{style:{borderBottomWidth:0}},de.default.createElement(p.TextField,{"data-testid":"gzi-input-url",variant:"outlined",value:q,error:!H,onChange:e=>{O(e.target.value)},disabled:x&&!f,slotProps:{input:{startAdornment:de.default.createElement(p.InputAdornment,{position:"start"},de.default.createElement(se.default,null))}}})))))))),de.default.createElement(p.Accordion,{disableGutters:!0,elevation:0,square:!0,className:r.accordion,expanded:"panelGffInput"===z,onChange:V("panelGffInput")},de.default.createElement(p.AccordionSummary,{className:r.accordionSummary,expandIcon:"panelGffInput"===z?de.default.createElement(ie.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",ml:5}}):de.default.createElement(ce.default,{className:r.radioIcon,sx:{fontSize:"1.2rem",mr:5}}),"aria-controls":"panelGffInputd-content"},de.default.createElement(p.Typography,{component:"span"},"GFF3 input",de.default.createElement(p.Tooltip,{title:"GFF3 must includes FASTA sequences. File can be gzip compressed."},de.default.createElement(le.default,{className:r.radioIcon,sx:{fontSize:18}})))),de.default.createElement(p.AccordionDetails,{className:r.accordionDetails},de.default.createElement(p.Box,{style:{marginTop:20}},de.default.createElement("input",{"data-testid":"gff3-input-file",type:"file",disabled:x&&!f,onChange:e=>{F(e.target.files?.item(0)??null),S(Ye.GFF3)}}),de.default.createElement(p.FormGroup,{style:{display:"grid"}},de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{checked:w,onChange:()=>{E(!w)},disabled:x&&!f}),label:"Load features from GFF3 file"}),de.default.createElement(p.FormControlLabel,{"data-testid":"gff3-is-gzip-checkbox",control:de.default.createElement(p.Checkbox,{checked:U,onChange:()=>{$(!U)},disabled:x&&!f}),label:"GFF3 is gzip compressed"})))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!Qe(g,v,b,A,D,N,j,W,H)||x,variant:"contained",type:"submit","data-testid":"submit-button"},x?"Submitting...":"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),f?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},f)):null)}const tt=new Set(["i","me","my","myself","we","our","ours","ourselves","you","your","yours","yourself","yourselves","he","him","his","himself","she","her","hers","herself","it","its","itself","they","them","their","theirs","themselves","what","which","who","whom","this","that","these","those","am","is","are","was","were","be","been","being","have","has","had","having","do","does","did","doing","a","an","the","and","but","if","or","because","as","until","while","of","at","by","for","with","about","against","between","into","through","during","before","after","above","below","to","from","up","down","in","out","on","off","over","under","again","further","then","once","here","there","when","where","why","how","all","any","both","each","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","s","t","can","will","just","don","should","now","0","1","2","3","4","5","6","7","8","9"]);function nt(e,t){for(const[n,a]of t.entries())if(e.startsWith(a))return e.replace(a,String(n));return e}const at="$PREFIXED_ID";function ot(e,t,n){return t===at?[nt(e.id,n)]:me.default.query(e,t)}function rt(e){return e.toLowerCase().split(/[^\d:A-Za-z]+/).filter((e=>e&&!tt.has(e)))}function*lt(e){for(const t of e)yield*rt(t)}function*st(e){for(const t of e)if("string"==typeof t)yield t;else if("object"==typeof t){const e=me.default.query(t,"$..*");yield*st(e)}}function*it(e,t,n){for(const a of t){const t=ot(e,a,n);if(t.length>0)for(const e of lt(st(t)))yield[a,e]}}async function ct(e,t,n){const a=await this.db,o=t??a.transaction(["nodes"]);x.checkAbortSignal(n);const r=[...rt(e)],l=[],s=new Map;l.push(...r.map((async(e,t)=>{x.checkAbortSignal(n);const a=o.objectStore("nodes").index("full-text-words");for await(const o of a.iterate(IDBKeyRange.bound(e,`${e}`,!1,!1))){x.checkAbortSignal(n);const e=o.value,a=s.get(e.id)??[e,new Set];a[1].add(t),s.set(e.id,a)}}))),await Promise.all(l),x.checkAbortSignal(n);const i=[];for(const[,[e,t]]of s)x.checkAbortSignal(n),i.push(...ut(this.textIndexFields,e,t,r,this.prefixes));return i.sort(((e,t)=>t.score-e.score)),i.slice(0,this.options.maxSearchResults??this.DEFAULT_MAX_SEARCH_RESULTS)}function ut(e,t,n,a,o){const r=[...n].sort().map((e=>a[e])),l=r.map((e=>{const t=e.replaceAll(/[$()*+./?[\\\]^{|}-]/g,String.raw`\$&`);return new RegExp(`\\b${t}`,"gi")}));let s=[],i=0;for(const[n,r]of e.entries()){const c=new Set,u=e.length-n-1,d=[...st(ot(t,r.jsonPath,o))];for(const e of d){let n=0;const o=[];for(const[t,r]of l.entries())for(const l of e.matchAll(r)){n+=1+1*u,c.add(t);const r=l.index,s=a[t];void 0!==r&&(n+=.01*s.length,n+=s.length/e.length*100*.05,o.push({wordIndex:t,position:r}))}n+=100*c.size,i<n&&(i=n),o.sort(((e,t)=>e.position-t.position)),o.length>0&&s.push({term:t,field:r,str:e,score:n,wordMatches:o})}}s=s.filter((e=>e.score===i));for(const e of s){const{wordMatches:t}=e;for(let n=0;n<t.length-1;n++){const a=t[n],o=t[n+1],l=o.wordIndex-a.wordIndex;if(1===l||-1===l){e.score+=1,1===l&&(e.score+=1);const t=Math.abs(o.position-(a.position+r[a.wordIndex].length))-1;e.score-=.05*t}}}return s}function dt(e){return"string"==typeof e.id}function ft(e){return"string"==typeof e.sub&&"string"==typeof e.pred&&"string"==typeof e.obj}function mt(e){return Boolean(e.meta?.deprecated)}async function gt(e){return C.openDB(e,2,{upgrade(e,t,n,a,o){if(t<2&&(e.objectStoreNames.contains("meta")&&e.deleteObjectStore("meta"),e.objectStoreNames.contains("nodes")&&e.deleteObjectStore("nodes"),e.objectStoreNames.contains("edges")&&e.deleteObjectStore("edges")),e.objectStoreNames.contains("meta")||e.createObjectStore("meta"),!e.objectStoreNames.contains("nodes")){e.createObjectStore("nodes",{keyPath:"id"});const t=a.objectStore("nodes");t.createIndex("by-label","lbl"),t.createIndex("by-type","type"),t.createIndex("by-synonym",["meta","synonyms","val"]),t.createIndex("full-text-words","fullTextWords",{multiEntry:!0})}if(!e.objectStoreNames.contains("edges")){e.createObjectStore("edges",{autoIncrement:!0});const t=a.objectStore("edges");t.createIndex("by-subject","sub"),t.createIndex("by-object","obj"),t.createIndex("by-predicate","pred")}}})}function pt(e){const t=new Set;for(const[,n]of e)t.add(n);return[...t]}async function ht(e){const t=Date.now();let n,a=1;this.options.update?.("Parsing JSON",a);try{n=JSON.parse(await A.openLocation(this.sourceLocation).readFile("utf8"))}catch{throw new Error("Error in loading ontology")}a+=5,this.options.update?.("Parsing JSON complete",a);const o=Date.now(),[r,...l]=n.graphs??[];if(r){if(l.length>0)throw new Error("multiple graphs not supported");try{const n=e.transaction(["meta","nodes","edges"],"readwrite");await n.objectStore("meta").clear(),await n.objectStore("nodes").clear(),await n.objectStore("edges").clear();const l=n.objectStore("nodes"),s=yt.call(this).map((e=>e.jsonPath));if(r.nodes){let e=Math.round(a);for(const[,t]of r.nodes.entries())a+=1/r.nodes.length*64,Math.round(a)!=e&&a<100&&(this.options.update?.("Processing nodes",a),e=Math.round(a)),dt(t)&&await l.add({...t,fullTextWords:pt(it(t,s,this.prefixes))})}const i=n.objectStore("edges");if(r.edges){let e=Math.round(a);for(const[,t]of r.edges.entries())a+=1/r.edges.length*30,Math.round(a)!=e&&a<100&&(this.options.update?.("Processing edges",a),e=Math.round(a)),ft(t)&&await i.add(t)}await n.done;const c=e.transaction("meta","readwrite"),{update:u,...d}=this.options;await c.objectStore("meta").add({ontologyRecord:{name:this.ontologyName,version:this.ontologyVersion,sourceLocation:this.sourceLocation},storeOptions:d,graphMeta:r.meta,timestamp:String(new Date),schemaVersion:2,timings:{overall:Date.now()-t,load:Date.now()-o}},"meta"),await c.done}catch(t){throw await e.transaction("meta","readwrite").objectStore("meta").clear(),t}}}function yt(){return[{displayName:"ID",jsonPath:at},...this.options.textIndexing?.indexFields??vt]}async function bt(e){const[t]=await e.transaction("meta").objectStore("meta").getAll();return!!t&&ge.default(this.options.prefixes,t.storeOptions.prefixes)&&ge.default(this.options.textIndexing,t.storeOptions.textIndexing)}class St{ontologyName;ontologyVersion;sourceLocation;db;options;loadOboGraphJson=ht;getTermsByFulltext=ct;openDatabase=gt;isDatabaseCurrent=bt;get textIndexFields(){return yt.call(this)}get prefixes(){return this.options.prefixes??new Map}DEFAULT_MAX_SEARCH_RESULTS=100;constructor(e,t,n,a){this.ontologyName=e,this.ontologyVersion=t,this.sourceLocation=n,this.options=a??{},this.db=this.prepareDatabase()}validate(){const e=[],{sourceLocation:t,sourceType:n}=this;return n?"obo-graph-json"!==n&&e.push(new Error(`ontology source file ${JSON.stringify(t)} has type ${n}, which is not yet supported`)):e.push(new Error(`unable to determine format of ontology source file ${JSON.stringify(t)}, file name must end with ".json", ".obo", or ".owl"`)),e}get sourceType(){if(r.isUriLocation(this.sourceLocation)){if(this.sourceLocation.uri.endsWith(".json"))return"obo-graph-json"}else if(r.isLocalPathLocation(this.sourceLocation)&&this.sourceLocation.localPath.endsWith(".json"))return"obo-graph-json"}get dbName(){return`Apollo Ontology "${this.ontologyName}" "${this.ontologyVersion}"`}async prepareDatabase(){const e=this.validate();if(e.length>0)throw e;const t=await this.openDatabase(this.dbName);if(await this.isDatabaseCurrent(t))return t;try{const{options:e,sourceLocation:n,sourceType:a}=this;if("obo-graph-json"!==a)throw new Error(`ontology source file ${JSON.stringify(n)} has type ${a}, which is not yet supported`);return e.update?.("",0),await this.loadOboGraphJson(t),e.update?.("",100),t}catch(e){throw t.close(),await C.deleteDB(this.dbName),e}}async termCount(e){const t=await this.db;return(e??t.transaction("nodes")).objectStore("nodes").count()}unique(e){const t=new Map,n=[];for(const a of e)t.has(a.id)||(t.set(a.id,!0),n.push(a));return n}async getTermsWithLabelOrSynonym(e,t,n){const a=t?.includeSubclasses??!0,o=await this.db,r=n??o.transaction(["nodes","edges"]),l=r.objectStore("nodes"),s=[...await l.index("by-label").getAll(e),...await l.index("by-synonym").getAll(e)];if(a){const e=await this.recurseEdges("by-object",s.map((e=>e.id)),(e=>"is_a"===e.pred),"sub",r);for(const t of e){const e=await l.get(t);e&&s.push(e)}}return s}async getPropertiesByLabel(e,t,n){const a=t?.includeSubProperties??!0,o=await this.db,r=n??o.transaction(["nodes","edges"]),l=(await this.getTermsWithLabelOrSynonym(e,{includeSubclasses:!1},r)).filter((e=>Tt(e)));if(a){const e=await this.recurseEdges("by-object",l.map((e=>e.id)),(e=>"subPropertyOf"===e.pred),"sub",r),t=r.objectStore("nodes");for(const n of e){const e=await t.get(n);e&&Tt(e)&&l.push(e)}}return l}async recurseEdges(e,t,n,a,o){const r=new Set;return await async function t(l){await Promise.all([...l].map((async l=>{const s=(await o.objectStore("edges").index(e).getAll(l)).filter((e=>n(e))).map((e=>e[a]));if(s.length>0){for(const e of s)r.add(e);await t(s)}})))}(t),r.values()}async*expandNodeSet(e,t="is_a",n,a){const o=await this.db,r=a??o.transaction(["edges"]),l=[...e],s=await this.recurseEdges("subclasses"===n?"by-object":"by-subject",l,(e=>e.pred===t),"subclasses"===n?"sub":"obj",r);for(const e of l)yield e;for(const e of s)yield e}expandSubclasses(e,t="is_a",n){return this.expandNodeSet(e,t,"subclasses",n)}expandSuperclasses(e,t="is_a",n){return this.expandNodeSet(e,t,"superclasses",n)}async getClassesThat(e,t,n){const a=await this.db,o=n??a.transaction(["nodes","edges"]),r=await this.getPropertiesByLabel(e,{includeSubProperties:!0},o),l=new Set(r.map((e=>e.id))),s=await async function(e){const t=[];for await(const n of e)t.push(n);return t}(this.expandSuperclasses(t.map((e=>e.id)),"is_a",o)),i=await this.recurseEdges("by-object",s,(e=>l.has(e.pred)),"sub",o),c=this.expandSubclasses(i,"is_a",o),u=[];for await(const e of c){const t=await o.objectStore("nodes").get(e);t&&xt(t)&&!mt(t)&&u.push(t)}return u}async getClassesWithoutPropertyLabeled(e,t,n){const a=await this.db,o=n??a.transaction(["nodes","edges"]),r=o.objectStore("nodes"),l=o.objectStore("edges"),s=(await this.getPropertiesByLabel(e,t,o)).map((e=>e.id)),i=await(async()=>{const e=new Set;for(const t of s)for await(const n of l.index("by-predicate").iterate(t))e.add(n.value.sub);const t=new Set;for await(const n of this.expandSubclasses(e,"is_a",o))t.add(n);return t})(),c=[];for await(const e of r){const t=e.value;xt(t)&&!i.has(t.id)&&c.push(t.id)}const u=[];for(const e of c){const t=await o.objectStore("nodes").get(e);t&&xt(t)&&!mt(t)&&u.push(t)}return u}async getAllClasses(e){const t=await this.db,n=e??t.transaction(["nodes"]);return(await n.objectStore("nodes").index("by-type").getAll("CLASS")).filter((e=>!mt(e)))}async getAllTerms(e){const t=await this.db,n=e??t.transaction(["nodes"]);return(await n.objectStore("nodes").getAll()).filter((e=>!mt(e)))}}const wt=i.types.model("OntologyRecord",{name:i.types.string,version:"unversioned",source:i.types.union(v.LocalPathLocation,v.UriLocation,v.BlobLocation),options:i.types.frozen(),equivalentTypes:i.types.map(i.types.array(i.types.string))}).volatile((e=>({dataStore:void 0,startedEquivalentTypeRequests:new Set}))).actions((e=>({ping(){},initDataStore(){e.dataStore=new St(e.name,e.version,i.getSnapshot(e.source),e.options)},afterCreate(){i.addDisposer(e,s.autorun((()=>{this.initDataStore()})))},setEquivalentTypes(t,n){e.equivalentTypes.set(t,n)}}))).actions((e=>({loadEquivalentTypes:i.flow((function*(t){if(!e.dataStore)return;if(e.startedEquivalentTypeRequests.has(t))return;e.startedEquivalentTypeRequests.add(t);const n=(yield e.dataStore.getTermsWithLabelOrSynonym(t)).map((e=>e.lbl)).filter((e=>null!=e));i.isAlive(e)&&e.setEquivalentTypes(t,n)}))}))).actions((e=>({afterCreate(){s.autorun((t=>{e.dataStore&&(e.loadEquivalentTypes("gene"),e.loadEquivalentTypes("pseudogene"),e.loadEquivalentTypes("transcript"),e.loadEquivalentTypes("pseudogenic_transcript"),e.loadEquivalentTypes("CDS"),e.loadEquivalentTypes("mRNA"),t.dispose())}))},setEquivalentTypes(t,n){e.equivalentTypes.set(t,n)}}))).views((e=>({isTypeOf(t,n){if(t===n)return!0;if(!e.dataStore)return!1;const a=e.equivalentTypes.get(n);return a?a.includes(t):(e.loadEquivalentTypes(n),!1)}}))),Et=i.types.model("OntologyManager",{ontologies:i.types.array(wt),prefixes:i.types.optional(i.types.map(i.types.string),{"GO:":"http://purl.obolibrary.org/obo/GO_","SO:":"http://purl.obolibrary.org/obo/SO_"})}).views((e=>({get featureTypeOntologyName(){const t=i.getRoot(e).jbrowse.configuration;return a.readConfObject(t.ApolloPlugin,"featureTypeOntologyName")}}))).views((e=>({get featureTypeOntology(){return this.findOntology(e.featureTypeOntologyName)},findOntology:(t,n)=>e.ontologies.find((e=>e.name===t&&(void 0===n||e.version===n))),openOntology(e,t){return this.findOntology(e,t)?.dataStore},applyPrefixes:t=>nt(t,e.prefixes),expandPrefixes:t=>function(e,t){for(const[n,a]of t.entries())if(e.startsWith(String(n)))return e.replace(String(n),a);return e}(t,e.prefixes)}))).actions((e=>({addOntology(t,n,a,o){const r=e.ontologies.push({name:t,version:n,source:a,options:{prefixes:new Map(e.prefixes.entries()),...o}});e.ontologies[r-1].ping()}}))),vt=[{displayName:"Label",jsonPath:"$.lbl"},{displayName:"Synonym",jsonPath:"$.meta.synonyms[*].val"},{displayName:"Definition",jsonPath:"$.meta.definition.val"}],Ct=a.ConfigurationSchema("OntologyRecord",{name:{type:"string",description:'the full name of the ontology, e.g. "Gene Ontology"',defaultValue:"My Ontology"},version:{type:"string",description:"the ontology's version string",defaultValue:"unversioned"},source:{type:"fileLocation",description:"the download location for the ontology's source file",defaultValue:{locationType:"UriLocation",uri:"http://example.com/myontology.json"}},textIndexFields:{type:"frozen",description:"JSON paths for text fields that will be indexed for text searching",defaultValue:vt}});function xt(e){return"CLASS"===e.type}function Tt(e){return"PROPERTY"===e.type}async function At(e,t,n){if(!e)return;const a=await t.getTermsWithLabelOrSynonym(e.type,{includeSubclasses:!1}),o=a.filter(xt);if(0===a.length)return;const r=await t.getClassesThat("part_of",o);return 0!==r.length?r:void 0}function Ft({fetchValidTerms:e,filterTerms:t,includeDeprecated:n,onChange:a,ontologyName:o,ontologyVersion:r,renderInput:l,session:s,style:i,value:c}){const[u,d]=y.useState(!1),[f,m]=y.useState(),[g,h]=y.useState(""),[b,S]=y.useState(),{ontologyManager:w}=s.apolloDataStore,E=w.findOntology(o,r)?.dataStore,v=E&&u&&!f,C=E&&!b,T=y.useCallback((e=>(n||!mt(e))&&(!t||t(e))),[t,n]);y.useEffect((()=>{u||m(void 0)}),[u]),y.useEffect((()=>{const e=new AbortController,{signal:t}=e;return C&&(h(""),async function(e,t,n,a){if(!t)return;const o=(await e.getTermsWithLabelOrSynonym(t,{includeSubclasses:!1})).find((e=>(n??(()=>!0))(e)));if(!o)throw new Error(`not a valid ${e.ontologyName} term`);return o}(E,c,T).then((e=>{t.aborted||S(e)}),(e=>{t.aborted||x.isAbortException(e)||h(String(e))}))),()=>{e.abort()}}),[s,c,T,E,C]),y.useEffect((()=>{const t=new AbortController,{signal:n}=t;return v&&async function(e,t,n,a){let o;if(t){const n=await t(e,a);n&&(o=n)}return o||(o=await e.getAllTerms()),n?o.filter((e=>n(e))):o}(E,e,T,n).then((e=>{e&&!n.aborted&&m(e)}),(e=>{n.aborted||x.isAbortException(e)||s.notify(e instanceof Error?e.message:String(e),"error")})),()=>{t.abort()}}),[v,T,E,s,e]);const A={};return g&&(A.error=!0,A.helperText=g),de.default.createElement(p.Autocomplete,{style:i,autoComplete:!0,filterSelectedOptions:!0,disableClearable:!0,selectOnFocus:!0,clearOnBlur:!0,handleHomeEndKeys:!0,freeSolo:!0,value:c,options:f??[],onOpen:()=>{d(!0)},onClose:()=>{d(!1)},loading:v,renderInput:l??(e=>de.default.createElement(p.TextField,{...e,...A})),getOptionLabel:e=>"string"==typeof e?e:e.lbl??"",isOptionEqualToValue:(e,t)=>e.lbl===t.lbl,onChange:(e,t)=>{t&&("string"==typeof t?(S(void 0),a(c,t)):t.lbl!==c&&(h(""),S(t),a(c,t.lbl)))}})}function Dt({changeManager:e,handleClose:n,session:a,sourceAssemblyId:o,sourceFeature:r}){const[l,s]=y.useState(String(r.max)),[i,c]=y.useState(String(r.min+1)),[u,d]=y.useState(""),[f,m]=y.useState(""),[g,h]=y.useState(""),b=Number(l)<=Number(i);return de.default.createElement(Ke,{open:!0,title:"Add new child feature",handleClose:n,maxWidth:!1,"data-testid":"add-feature-dialog"},de.default.createElement("form",{onSubmit:function(a){a.preventDefault(),m("");const s=new t.AddFeatureChange({changedIds:[r._id],typeName:"AddFeatureChange",assembly:o,addedFeature:{_id:(new ue.default).toHexString(),refSeq:r.refSeq,min:Number(i)-1,max:Number(l),type:u},parentFeatureId:r._id});e.submit(s),n(),a.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.TextField,{margin:"dense",id:"start",label:"Start",type:"number",fullWidth:!0,variant:"outlined",value:i,onChange:e=>{c(e.target.value)}}),de.default.createElement(p.TextField,{margin:"dense",id:"end",label:"End",type:"number",fullWidth:!0,variant:"outlined",value:l,onChange:e=>{s(e.target.value)},error:b,helperText:b?'"End" must be greater than "Start"':null}),de.default.createElement(Ft,{session:a,ontologyName:"Sequence Ontology",style:{width:170},value:u,filterTerms:xt,fetchValidTerms:async function(e,t,n){const a=await At(e,t);if(a)return a;h(`Type "${e?.type}" does not have any children in the ontology`)}.bind(null,r),renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Type",variant:"outlined",fullWidth:!0,error:Boolean(g),helperText:g}),onChange:(e,t)=>{var n;t&&(n=t,m(""),d(n))}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:b||!(i&&l&&u)},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),f?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},f)):null)}var kt;function Nt(e,t,n,a){const o={_id:(new ue.default).toHexString(),refSeq:e,type:"CDS",min:n,max:a,strand:t},r={_id:(new ue.default).toHexString(),refSeq:e,type:"exon",min:n,max:a,strand:t},l={};return l[o._id]=o,l[r._id]=r,{_id:(new ue.default).toHexString(),refSeq:e,type:"mRNA",min:n,max:a,strand:t,children:l}}function It({changeManager:e,handleClose:n,region:a,session:o}){const[r,l]=y.useState(String(a.end)),[s,i]=y.useState(String(a.start+1)),[c,u]=y.useState(kt.GENE_AND_SUBFEATURES),[d,f]=y.useState(),[m,g]=y.useState(),[h,b]=y.useState(""),S=Number(r)<=Number(s);let w=Boolean(S)||!(s&&r&&c);return(c===kt.CUSTOM&&!d||!m&&c===kt.GENE_AND_SUBFEATURES||!m&&c===kt.TRANSCRIPT_AND_SUBFEATURES)&&(w=!0),de.default.createElement(Ke,{open:!0,title:"Add new feature",handleClose:n,maxWidth:!1,"data-testid":"add-feature-dialog"},de.default.createElement("form",{onSubmit:function(l){let i;l.preventDefault(),b("");for(const[,e]of o.apolloDataStore.assemblies??new Map)if(e._id===a.assemblyName)for(const[,t]of e.refSeqs??new Map)t.name===a.refName&&(i=t._id);if(!i)return void b("Invalid refseq id. Make sure you have the Apollo annotation track open");if(c===kt.GENE_AND_SUBFEATURES){const o=Nt(i,m,Number(s)-1,Number(r)),l={};l[o._id]=o;const c=(new ue.default).toHexString(),u=new t.AddFeatureChange({changedIds:[c],typeName:"AddFeatureChange",assembly:a.assemblyName,addedFeature:{_id:c,refSeq:i,min:Number(s)-1,max:Number(r),type:"gene",strand:m,children:l}});return e.submit(u),void n()}if(c===kt.TRANSCRIPT_AND_SUBFEATURES){const o=Nt(i,m,Number(s)-1,Number(r)),l=new t.AddFeatureChange({changedIds:[o._id],typeName:"AddFeatureChange",assembly:a.assemblyName,addedFeature:o});return e.submit(l),void n()}if(!d)return void b("No type selected");const u=(new ue.default).toHexString(),f=new t.AddFeatureChange({changedIds:[u],typeName:"AddFeatureChange",assembly:a.assemblyName,addedFeature:{_id:u,refSeq:i,min:Number(s)-1,max:Number(r),type:d,strand:m}});e.submit(f),n()},"data-testid":"submit-form"},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.TextField,{margin:"dense",id:"start",label:"Start",type:"number",fullWidth:!0,variant:"outlined",value:Number(s),onChange:e=>{i(e.target.value)}}),de.default.createElement(p.TextField,{margin:"dense",id:"end",label:"End",type:"number",fullWidth:!0,variant:"outlined",value:r,onChange:e=>{l(e.target.value)},error:S,helperText:S?'"End" must be greater than "Start"':null}),de.default.createElement(p.FormControl,null,de.default.createElement(p.InputLabel,{id:"demo-simple-select-label"},"Strand"),de.default.createElement(p.Select,{labelId:"demo-simple-select-label",id:"demo-simple-select",label:"Strand",value:m?.toString(),onChange:function(e){switch(b(""),Number(e.target.value)){case 1:g(1);break;case-1:g(-1);break;default:g(void 0)}}},de.default.createElement(p.MenuItem,{value:void 0}),de.default.createElement(p.MenuItem,{value:1},"+"),de.default.createElement(p.MenuItem,{value:-1},"-"))),de.default.createElement(p.FormControl,{style:{marginTop:20}},de.default.createElement(p.RadioGroup,{"aria-labelledby":"demo-radio-buttons-group-label",defaultValue:kt.GENE_AND_SUBFEATURES,name:"radio-buttons-group",value:c,onChange:e=>{b("");const{value:t}=e.target;Object.keys(kt).includes(t)&&u(kt[t])}},de.default.createElement(p.FormControlLabel,{value:kt.GENE_AND_SUBFEATURES,control:de.default.createElement(p.Radio,null),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Add gene and sub-features",de.default.createElement(p.Tooltip,{title:"This is a shortcut to create a gene with a single mRNA, exon, and CDS"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{value:kt.TRANSCRIPT_AND_SUBFEATURES,control:de.default.createElement(p.Radio,null),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},"Add transcript and sub-features",de.default.createElement(p.Tooltip,{title:"This is a shortcut to create a single mRNA with exon and CDS, but without a parent gene"},de.default.createElement(p.IconButton,{size:"small"},de.default.createElement(le.default,{sx:{fontSize:18}}))))}),de.default.createElement(p.FormControlLabel,{value:kt.CUSTOM,checked:c!==kt.GENE_AND_SUBFEATURES&&c!==kt.TRANSCRIPT_AND_SUBFEATURES,control:de.default.createElement(p.Radio,null),label:"Add feature with a sequence ontology type"}))),c===kt.CUSTOM?de.default.createElement(Ft,{session:o,ontologyName:"Sequence Ontology",style:{width:170},value:"",filterTerms:xt,renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Type",variant:"outlined",fullWidth:!0}),onChange:(e,t)=>{var n;t&&(n=t,b(""),f(n))}}):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:w},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),h?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},h)):null)}function Rt(e,t){const n=(new ue.default).toHexString();t.push(n);const a={};if(e.children)for(const n of Object.values(e.children)){const e=Rt(n,t);a[e._id]=e}const o="string"==typeof e.refSeq?e.refSeq:e.refSeq.toHexString();return{...e,refSeq:o,children:e.children&&a,_id:n}}function Mt({changeManager:e,handleClose:n,session:o,sourceAssemblyId:r,sourceFeature:l}){const{assemblyManager:s}=o,c=s.assemblyList,[u,d]=y.useState(c.find((e=>e.name!==r))?.name),[f,m]=y.useState([]),[g,h]=y.useState(""),[b,S]=y.useState(l.min),[w,E]=y.useState("");function v(e,t){const n={};if(e.children)for(const a of Object.values(e.children)){const e=v(a,t);e.refSeq=g,e.min=e.min+t,e.max=e.max+t,n[e._id]=e}const a="string"==typeof e.refSeq?e.refSeq:e.refSeq.toHexString(),o="string"==typeof e._id?e._id:e._id.toHexString();return{...e,refSeq:a,children:e.children&&n,_id:o}}return y.useEffect((()=>{h(""),async function(){if(!u)return void E("No assemblies to copy to");const e=await s.waitForAssembly(u);if(!e)return;const{refNameAliases:t}=e;if(!t)return;const n=[...Object.entries(t)].filter((([e,t])=>e!==t)).map((([e,t])=>({_id:e,name:t})));m(n),h(n[0]?._id||"")}().catch((e=>{E(String(e))}))}),[u,s]),de.default.createElement(Ke,{open:!0,title:"Copy features and annotations",handleClose:n,maxWidth:!1,"data-testid":"copy-feature"},de.default.createElement("form",{onSubmit:async function(a){if(!u)return;a.preventDefault(),E("");const o=l.length,r=await s.waitForAssembly(u);if(!r)return void E(`Assembly not found: ${u}.`);const c=r.getCanonicalRefName(g),d=r.regions?.find((e=>e.refName===c));if(!d)return void E(`RefSeq not found: ${g}.`);const f=b+o;if(f>d.end)return void E(`Feature would extend beyond the bounds of the selected reference sequence. (Feature would end at ${f}, but reference sequence ends at ${d.end})`);if(b<d.start)return void E(`Reference sequence starts at ${d.start}, feature cannot start before that.`);const m=[],p=Rt(i.getSnapshot(l),m),h={...p.attributes};"Parent"in h&&delete h.Parent,p.refSeq=g;const y=b-p.min;p.min=b,p.max=b+o;const S=v(p,y),w=new t.AddFeatureChange({changedIds:[p._id],typeName:"AddFeatureChange",assembly:u,addedFeature:{_id:p._id,refSeq:p.refSeq,min:p.min,max:p.max,type:p.type,children:S.children,attributes:h,strand:p.strand},copyFeature:!0,allIds:m});e.submit(w),n(),a.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Target assembly"),de.default.createElement(p.Select,{labelId:"label",value:u,onChange:function(e){d(e.target.value)}},c.filter((e=>e.name!==r)).map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},a.readConfObject(e,"displayName"))))),de.default.createElement(p.DialogContentText,null,"Target reference sequence"),de.default.createElement(p.Select,{labelId:"label",value:g,onChange:function(e){h(e.target.value)}},f.map((e=>de.default.createElement(p.MenuItem,{key:e._id,value:e._id},e.name)))),de.default.createElement(p.DialogContentText,null,"Start position in target reference sequence"),de.default.createElement(p.TextField,{margin:"dense",type:"number",fullWidth:!0,variant:"outlined",value:b,onChange:e=>{S(Number(e.target.value))}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!u||!g||!b,variant:"contained",type:"submit"},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),w?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},w)):null)}function Lt({changeManager:e,handleClose:n,session:a}){const{internetAccounts:o}=i.getRoot(a),[r,l]=y.useState(),[s,c]=y.useState(""),[u,d]=y.useState(!1),[f,m]=y.useState(!1),g=o.filter((e=>"ApolloInternetAccount"===e.type));if(0===g.length)throw new Error("No Apollo internet account found");const[h,b]=y.useState(g[0]),{collaborationServerDriver:S}=a.apolloDataStore,w=S.getAssemblies();return y.useEffect((()=>{w.length>0&&void 0===r&&l(w[0])}),[w,r]),de.default.createElement(Ke,{open:!0,title:"Delete Assembly",handleClose:n,maxWidth:!1,"data-testid":"delete-assembly"},de.default.createElement("form",{onSubmit:async function(a){if(a.preventDefault(),m(!0),c(""),!r)return void c("Must select assembly!");const o=new t.DeleteAssemblyChange({typeName:"DeleteAssemblyChange",assembly:r.name});await e.submit(o,{internetAccountId:h.internetAccountId}),n(),a.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},g.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:h.internetAccountId,onChange:function(e){m(!1);const t=g.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);b(t)},disabled:f&&!s},o.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{labelId:"label",value:r?.name??"",onChange:function(e){const t=w.find((t=>t.name===e.target.value));l(t)},disabled:0===w.length},w.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement(p.DialogContentText,null,de.default.createElement("strong",{style:{color:"red"}},"NOTE: All assembly data will be deleted and this operation cannot be undone!")),de.default.createElement(p.FormGroup,null,de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{checked:u,onChange:()=>{d(!u)}}),label:"I understand that all assembly data will be deleted"}))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!r||!u,variant:"contained",type:"submit"},"Delete"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}function Pt({changeManager:e,handleClose:n,selectedFeature:a,session:o,setSelectedFeature:r,sourceAssemblyId:l,sourceFeature:s}){const[c,u]=y.useState(""),{ontologyManager:d}=o.apolloDataStore,{featureTypeOntology:f}=d;function m(e){if(!e.parent?.children||1===e.parent.children.size)return;const t=[];for(const n of e.parent.children.values())f?.isTypeOf(n.type,"CDS")||t.push(n);t.sort(((e,t)=>e.min-t.min));const n=[];for(const t of e.parent.children.values())f?.isTypeOf(t.type,"CDS")||n.push(t);if(n.sort(((e,t)=>t.max-e.max)),e.min===t[0].min){let n;for(const a of t)if(a._id!==e._id&&a.min>=e.min){n=a.min;break}if(n&&n!=e.parent.min)return{typeName:"LocationStartChange",changedId:e.parent._id,featureId:e.parent._id,oldLocation:e.parent.min,newLocation:n}}if(e.max===n[0].max){let t;for(const a of n)if(a._id!=e._id&&a.max<=e.max){t=a.max;break}if(t&&t!=e.parent.max)return{typeName:"LocationEndChange",changedId:e.parent._id,featureId:e.parent._id,oldLocation:e.parent.max,newLocation:t}}}return de.default.createElement(Ke,{open:!0,title:"Delete feature",handleClose:n,maxWidth:!1,"data-testid":"delete-feature"},de.default.createElement("form",{onSubmit:o=>{!async function(o){o.preventDefault(),u(""),a?._id===s._id&&r();const c=[],d=new t.DeleteFeatureChange({changedIds:[s._id],typeName:"DeleteFeatureChange",assembly:l,changes:[{deletedFeature:i.getSnapshot(s),parentFeatureId:s.parent?._id}]});if(f&&(f.isTypeOf(s.type,"transcript")||f.isTypeOf(s.type,"pseudogenic_transcript"))){const e=m(s);e&&c.push(e)}if(f&&f.isTypeOf(s.type,"exon")){const e=function(e){if(!f)return;if(!f.isTypeOf(e.type,"exon"))return;if(!e.parent?.cdsLocations||0===e.parent.cdsLocations.length||0===e.parent.cdsLocations[0].length)return;if(!e.parent.children)throw new Error("Unable to find parent of CDS");if(1!=e.parent.cdsLocations.length)throw new Error("Unable to handle a transcript with multiple CDSs");const n=(e.parent.cdsLocations.at(0)??[]).sort((({min:e},{min:t})=>e-t));let a;for(const t of e.parent.children.values())if(t.type===n[0].type){a=t;break}if(!a)throw new Error("Unable to find CDS");const o=n[0].min,r=n[n.length-1].max;if(!(e.min>o&&e.max<r||e.max<o||e.min>r)){if(e.min<=o&&e.max>=r)return new t.DeleteFeatureChange({changedIds:[a._id],typeName:"DeleteFeatureChange",assembly:l,changes:[{deletedFeature:i.getSnapshot(a),parentFeatureId:a.parent?._id}]});if(e.min<=o&&e.max>o){let t;for(const a of n)if(a.min>e.max){t=a.min;break}if(!t)throw new Error("Error setting new CDS start");return{typeName:"LocationStartChange",changedId:a._id,featureId:a._id,oldLocation:a.min,newLocation:t}}if(e.min<r&&e.max>=r){let t;for(const a of n.reverse())if(a.max<e.min){t=a.max;break}if(!t)throw new Error("Error setting new CDS end");return{typeName:"LocationEndChange",changedId:a._id,featureId:a._id,oldLocation:a.max,newLocation:t}}throw new Error("Unexpected relationship between exon and CDS")}}(s);e&&("DeleteFeatureChange"===e.typeName?(d.changedIds.push(...e.changedIds),d.changes.push(...e.changes)):c.push(e));const n=m(s);if(n){c.push(n);const e=s.parent?.parent;if(e?.children)if("LocationStartChange"===n.typeName){let t=n.newLocation;for(const[,a]of e.children)a._id!=n.featureId&&a.min<t&&(t=a.min);t!=e.min&&c.push({typeName:n.typeName,changedId:e._id,featureId:e._id,oldLocation:e.min,newLocation:t})}else{let t=n.newLocation;for(const[,a]of e.children)a._id!=n.featureId&&a.max>t&&(t=a.max);t!=e.max&&c.push({typeName:n.typeName,changedId:e._id,featureId:e._id,oldLocation:e.max,newLocation:t})}}}const g=function(e,n){if(0===e.length)return;const a=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[],changes:[],assembly:n}),o=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[],changes:[],assembly:n});for(const t of e)"LocationStartChange"===t.typeName&&(a.changedIds.push(t.changedId),a.changes.push({featureId:t.featureId,oldStart:t.oldLocation,newStart:t.newLocation})),"LocationEndChange"===t.typeName&&(o.changedIds.push(t.changedId),o.changes.push({featureId:t.featureId,oldEnd:t.oldLocation,newEnd:t.newLocation}));if(a.changedIds.length>0&&0===o.changedIds.length)return a;if(o.changedIds.length>0&&0===a.changedIds.length)return o;throw new Error("Unexpected list of changes")}(c,l);await e.submit(d),g&&await e.submit(g),n(),o.preventDefault()}(o)}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Are you sure you want to delete the selected feature?")),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit"},"Yes"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),c?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},c)):null)}function qt({handleClose:e,session:n}){const[o,r]=y.useState(!1),[l,s]=y.useState(),[c,u]=y.useState(""),{collaborationServerDriver:d,getInternetAccount:f,inMemoryFileDriver:m}=n.apolloDataStore,g=[...d.getAssemblies(),...m.getAssemblies()];return de.default.createElement(Ke,{open:!0,title:"Export GFF3",handleClose:e,maxWidth:!1,"data-testid":"download-gff3"},de.default.createElement("form",{onSubmit:async function(r){if(r.preventDefault(),u(""),!l)return void u("Must select assembly to download");const{internetAccountConfigId:s}=a.getConf(l,["sequence","metadata"]);s?await async function(e){if(!l)return void u("Must select assembly to download");const t=f(l.configuration.name,e),n=new URL("export/getID",t.baseURL),a=new URLSearchParams({assembly:l.name});n.search=a.toString();const r=n.toString(),s=t.getFetcher({locationType:"UriLocation",uri:r}),i=await s(r,{method:"GET"});if(!i.ok){const e=await Ve(i,"Error when exporting ID");return void u(e)}const{exportID:c}=await i.json(),d=new URL("export",t.baseURL),m=new URLSearchParams({exportID:c,includeFASTA:o?"true":"false"});d.search=m.toString();const g=d.toString();window.open(g,"_blank")}(s):function(e){if(!l)return void u("Must select assembly to download");const{assemblies:n}=e.apolloDataStore,o=n.get(l.name),r=o?.refSeqs;if(!r)return void u(`No refSeqs found for assembly "${l.name}"`);const s=[{directive:"gff-version",value:"3"}],c=a.getConf(l,["sequence","adapter","features"]);for(const e of c){const{end:t,refName:n,start:a}=e;s.push({directive:"sequence-region",value:`${n} ${a+1} ${t}`})}for(const[,e]of r){const{features:n}=e;if(n)for(const[,e]of n)s.push(t.annotationFeatureToGFF3(i.getSnapshot(e)))}for(const e of c){const{refName:t,seq:n}=e;s.push({id:t,description:"",sequence:n})}const d=re.default.formatSync(s),f=new Blob([d],{type:"text/plain;charset=utf-8"});D.saveAs(f,`${l.displayName??l.name}.gff3`)}(n),e()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{labelId:"label",value:l?.name??"",onChange:function(e){const t=g.find((t=>t.name===e.target.value));s(t)},disabled:0===g.length},g.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement(p.DialogContentText,null,"Select assembly to export to GFF3"),de.default.createElement(p.FormGroup,null,de.default.createElement(p.FormControlLabel,{"data-testid":"include-fasta-checkbox",control:de.default.createElement(p.Checkbox,{checked:o,onChange:()=>{r(!o)}}),label:"Include fasta sequence in GFF output"}))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!l,variant:"contained",type:"submit"},"Download"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Cancel"))),c?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},c)):null)}function Ot({changeManager:e,handleClose:n,session:o}){const{apolloDataStore:r}=o,[l,s]=y.useState(),[i,c]=y.useState(),[u,d]=y.useState(""),[f,m]=y.useState(!1),[g,h]=y.useState(),[b,S]=y.useState(!1),[w,E]=y.useState(!1),{collaborationServerDriver:v,getInternetAccount:C}=r,x=v.getAssemblies();return y.useEffect((()=>{i&&(async()=>{const{internetAccountConfigId:e}=a.getConf(i,["sequence","metadata"]),t=C(i.name,e);if(!t)throw new Error("No Apollo internet account found");const{baseURL:n}=t,o=new URL("features/count",n),r=new URLSearchParams({assemblyId:i.name});o.search=r.toString();const l=t.getFetcher({locationType:"UriLocation",uri:o.toString()});E(!0);const s=await l(o.toString(),{method:"GET"});if(!s.ok)throw new Error(await Ve(s));{const e=await s.json();h(e.count)}E(!1)})().catch((e=>{console.error(e),d(e.message??e)}))}),[C,o,i]),de.default.createElement(Ke,{open:!0,title:"Import Features from GFF3 file",handleClose:n,maxWidth:!1,"data-testid":"import-features-dialog"},w?de.default.createElement(ye.default,null):null,de.default.createElement("form",{onSubmit:async function(r){r.preventDefault(),d(""),E(!0),m(!0);let s="";if(!l)return void d("must select a file");if(!i)return void d("Must select assembly to download");const{internetAccountConfigId:c}=a.getConf(i,["sequence","metadata"]),u=C(i.name,c),{baseURL:f}=u,g=new URL("files",f);g.searchParams.set("type","text/x-gff3");const p=g.href,h=new FormData;h.append("file",l),h.append("fileName",l.name),h.append("type","text/x-gff3");const y=u.getFetcher({locationType:"UriLocation",uri:p});n();const{jobsManager:S}=o,w=new AbortController,v={name:`Importing features for ${i.displayName}`,statusMessage:"Uploading file, this may take awhile",progressPct:0,cancelCallback:()=>{w.abort(),S.abortJob(v.name)}};if(S.runJob(v),y){const{signal:e}=w,t=await y(p,{method:"POST",body:h,signal:e});if(!t.ok){const e=await Ve(t,"Error when inserting new features (while uploading file)");return S.abortJob(v.name,e),void d(e)}s=(await t.json())._id}const x=new t.AddFeaturesFromFileChange({typeName:"AddFeaturesFromFileChange",assembly:i.name,fileId:s,deleteExistingFeatures:b});S.done(v),await e.submit(x,{updateJobsManager:!0})}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{labelId:"label",value:i?.name??"",onChange:function(e){const t=x.find((t=>t.name===e.target.value));c(t),m(!1)},disabled:f&&!u},x.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name))))),de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,"Upload GFF3 to load features"),de.default.createElement("input",{type:"file",onChange:function(e){m(!1),e.target.files&&s(e.target.files[0])},disabled:f&&!u})),g&&g>0?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,null,"This assembly already has ",g," features, would you like to delete the existing features before importing new ones?"),de.default.createElement(he.default,{label:"Yes, delete existing features",disabled:f&&!u,control:de.default.createElement(pe.default,{checked:b,onChange:function(e){S(e.target.checked)},inputProps:{"aria-label":"controlled"},color:"warning"})})):null,de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!(i&&l&&void 0!==g)||f,variant:"contained",type:"submit"},f?"Submitting...":"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Close"))),u?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},u)):null)}function _t({handleClose:e,session:t}){const{internetAccounts:n}=i.getRoot(t),[a,o]=y.useState(""),r=n.filter((e=>"ApolloInternetAccount"===e.type));if(0===r.length)throw new Error("No Apollo internet account found");const[l,s]=y.useState(r[0]);return de.default.createElement(Ke,{open:!0,title:"Log out",handleClose:e,maxWidth:!1,"data-testid":"log-out"},de.default.createElement("form",{onSubmit:function(e){e.preventDefault(),o(""),l.removeToken(),globalThis.location.reload()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},r.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:l.internetAccountId,onChange:function(e){const t=r.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);s(t)}},n.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement(p.DialogContentText,null,"Are you sure you want to log out?")),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!l,variant:"contained",type:"submit"},"Log Out"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Cancel"))),a?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},a)):null)}function Bt({handleClose:e,session:t}){const{internetAccounts:n}=i.getRoot(t),[a,o]=y.useState(),[r,l]=y.useState(""),[s,c]=y.useState(!1),u=n.filter((e=>"ApolloInternetAccount"===e.type));if(0===u.length)throw new Error("No Apollo internet account found");const[d,f]=y.useState(u[0]),[m,g]=y.useState([]),[h,b]=y.useState([]),{collaborationServerDriver:S}=t.apolloDataStore,w=S.getAssemblies();function E(e,t){const n=[...h],a=e.target.value;if(t)n.includes(a)||(n.push(a),b(n));else{const e=n.indexOf(a,0);-1!==e&&n.splice(e,1),b(n)}}return y.useEffect((()=>{(async function(){const{baseURL:e,getFetcher:t}=d,n=new URL("checks/types",e).href,a=t({locationType:"UriLocation",uri:n}),o=await a(n,{method:"GET"});if(!o.ok){const e=await Ve(o,"Error when retrieving checks from server");return void l(e)}const r=await o.json();g(r)})().catch((e=>{l(String(e))}))}),[d]),y.useEffect((()=>{w.length>0&&void 0===a&&o(w[0])}),[w,a]),y.useEffect((()=>{(async function(){if(!a)return;const{baseURL:e,getFetcher:t}=d,n=new URL(`/assemblies/${a.name}`,e).href,o=t({locationType:"UriLocation",uri:n}),r=await o(n,{method:"GET"});if(!r.ok){const e=await Ve(r,"Error when retrieving assembly from server");return void l(e)}const s=await r.json();b(s.checks)})().catch((e=>{l(String(e))}))}),[a,d]),de.default.createElement(Ke,{open:!0,title:"Manage Checks",handleClose:e,"data-testid":"manage-checks"},de.default.createElement("form",{onSubmit:async function(n){if(n.preventDefault(),!a)return void l("Must select assembly!");const{notify:o}=t,{baseURL:r,getFetcher:s}=d,i=new URL("assemblies/checks",r).href,c=s({locationType:"UriLocation",uri:i}),u=await c(i,{method:"POST",body:JSON.stringify({_id:a.name,checks:h,name:""}),headers:{"Content-Type":"application/json"}});if(u.ok)o("Assembly checks updated successfully","success"),e();else{const e=await Ve(u,"Error when updating assembly checks");l(e)}}},de.default.createElement(p.DialogContent,null,u.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:d.internetAccountId,onChange:function(e){c(!1);const t=u.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);f(t)},disabled:s&&!r},n.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement(p.DialogContentText,null,"Select assembly"),de.default.createElement(p.Select,{style:{width:300},labelId:"label",value:a?.name??"",onChange:function(e){const t=w.find((t=>t.name===e.target.value));o(t)},disabled:0===w.length},w.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement("br",null),de.default.createElement("br",null),de.default.createElement(p.TableContainer,{component:p.Paper},de.default.createElement(p.Table,null,de.default.createElement(p.TableHead,null,de.default.createElement(p.TableRow,null,de.default.createElement(p.TableCell,null,"Check name"),de.default.createElement(p.TableCell,null,"Use check"))),de.default.createElement(p.TableBody,null,m.map((e=>de.default.createElement(p.TableRow,{key:e._id},de.default.createElement(p.TableCell,null,e.name),de.default.createElement(p.TableCell,null,de.default.createElement(p.Checkbox,{value:e._id,checked:h.includes(e._id),onChange:E}))))))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit"},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Cancel"))),r?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},r)):null)}function Ut({changeManager:e,handleClose:n,session:a}){const{internetAccounts:o}=i.getRoot(a),r=o.filter((e=>"ApolloInternetAccount"===e.type&&e.role?.includes("admin")));if(0===r.length)throw new Error("No Apollo internet account found");const[l,s]=y.useState(""),[c,u]=y.useState(r[0]),[d,f]=y.useState([]),m=y.useCallback((async()=>{const{baseURL:e}=c,t=new URL("users",e).href,n=c.getFetcher({locationType:"UriLocation",uri:t});if(n){const e=await n(t,{method:"GET"});if(!e.ok){const t=await Ve(e,"Error when getting user data from db");return void s(t)}const a=await e.json();f(a.map((e=>void 0===e.role?{...e,role:""}:e)))}}),[c]);function g(e){return e===c.getUserId()}y.useEffect((()=>{m().catch((e=>{s(String(e))}))}),[m]);const h=[{field:"username",headerName:"User",width:140},{field:"email",headerName:"Email",width:160},{field:"role",headerName:"Role",width:140,type:"singleSelect",valueOptions:["readOnly","user","admin","none"],getOptionLabel(e){switch(e){case"readOnly":return"Read-only";case"user":return"User";case"admin":return"Admin";case"none":return"None";default:return"unknown"}},editable:!0},{field:"actions",type:"actions",getActions:n=>[de.default.createElement(M.GridActionsCellItem,{key:`delete-${n.id}`,icon:de.default.createElement(be.default,null),onClick:async()=>{globalThis.confirm("Delete this user?")&&await async function(n){const a=new t.DeleteUserChange({typeName:"DeleteUserChange",userId:n});await e.submit(a,{internetAccountId:c.internetAccountId}),f((e=>e.filter((e=>e._id!==n))))}(n.id)},disabled:g(n.id),label:"Delete"})]}];return de.default.createElement(Ke,{open:!0,fullScreen:!0,title:"Manage users",handleClose:n,"data-testid":"manage-users"},de.default.createElement(p.DialogContent,null,r.length>1?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.DialogContentText,null,"Select account"),de.default.createElement(p.Select,{value:c.internetAccountId,onChange:function(e){const t=r.find((t=>t.internetAccountId===e.target.value));if(!t)throw new Error(`Could not find internetAccount with ID "${e.target.value}"`);u(t)},disabled:!l},o.map((e=>de.default.createElement(p.MenuItem,{key:e.id,value:e.internetAccountId},e.name))))):null,de.default.createElement("div",{style:{height:"100%",width:"100%"}},de.default.createElement(M.DataGrid,{pagination:!0,rows:d,columns:h,getRowId:e=>e._id,slots:{toolbar:M.GridToolbar},getRowHeight:()=>"auto",isCellEditable:e=>!g(e.id),processRowUpdate:async function(n){const a=new t.UserChange({typeName:"UserChange",role:n.role,userId:n._id});return await e.submit(a,{internetAccountId:c.internetAccountId}),n},onProcessRowUpdateError:e=>{s(String(e))}}))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Close")),l?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},l)):null)}function $t(e,t){const n=t[e];let a;if("three_prime"===e)a=`3'end (coords: ${n.min+1}-${n.max})`;else{if("five_prime"!==e)throw new Error(`Unexpected direction: "${e}"`);a=`5'end (coords: ${n.min+1}-${n.max})`}return a}function Gt({changeManager:e,handleClose:n,selectedFeature:a,setSelectedFeature:o,sourceAssemblyId:r,sourceFeature:l}){const[s,c]=y.useState(""),[u,d]=y.useState(),f=function(e){const t={},n=e.parent;if(!n)throw new Error("Unable to find parent of reference exon");let a=[];if(n.children)for(const[,e]of n.children)"exon"===e.type&&a.push(e);a=a.sort(((e,t)=>e.min===t.min?e.max-t.max:e.min-t.min)),n.strand&&-1===n.strand&&(a=a.reverse());let o=0;for(const n of a){if(n._id===e._id){a.length>o+1&&(t.three_prime=a[o+1]),o>0&&(t.five_prime=a[o-1]);break}o++}return t}(l);return de.default.createElement(Ke,{open:!0,title:"Merge exons",handleClose:n,maxWidth:!1,"data-testid":"merge-exons"},de.default.createElement("form",{onSubmit:function(s){s.preventDefault(),c("");const{parent:d}=l;if(!u||!d)return;a?._id===l._id&&o();const f=new t.MergeExonsChange({changedIds:[l._id],typeName:"MergeExonsChange",assembly:r,firstExon:i.getSnapshot(l),secondExon:i.getSnapshot(u),parentFeatureId:d._id});e.submit(f),n(),s.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},0===Object.keys(f).length?"There are no neighbouring exons to merge with":"Merge with exon on:",de.default.createElement(p.FormControl,{style:{marginTop:5}},de.default.createElement(p.RadioGroup,{"aria-labelledby":"demo-radio-buttons-group-label",name:"radio-buttons-group",value:u,onChange:e=>{c("");const{value:t}=e.target;d(f[t])}},Object.keys(f).map((e=>de.default.createElement(p.FormControlLabel,{value:e,key:e,control:de.default.createElement(p.Radio,null),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},$t(e,f))})))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:0===Object.keys(f).length||void 0===u},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}function jt(e){let t;return t=e.attributes.get("gff_name")?e.attributes.get("gff_name")?.join(","):e.attributes.get("gff_id")?e.attributes.get("gff_id")?.join(","):e._id,`${t} [${e.min+1}-${e.max}]`}function Wt({changeManager:e,handleClose:n,selectedFeature:a,session:o,setSelectedFeature:r,sourceAssemblyId:l,sourceFeature:s}){const{notify:c}=o,[u,d]=y.useState(""),[f,m]=y.useState(),g=function(e,t){const n=e.parent;if(!n)throw new Error("Unable to find parent of reference transcript");const{featureTypeOntology:a}=t.apolloDataStore.ontologyManager;if(!a)throw new Error("featureTypeOntology is undefined");const o={};if(n.children)for(const[,t]of n.children)a.isTypeOf(t.type,"transcript")&&t._id!==e._id&&(o[t._id]=t);return o}(s,o);return de.default.createElement(Ke,{open:!0,title:"Merge transcripts",handleClose:n,maxWidth:!1,"data-testid":"merge-transcripts"},de.default.createElement("form",{onSubmit:async function(o){if(o.preventDefault(),d(""),!f)return;if(a?._id===s._id&&r(),!s.parent)throw new Error("Cannot find parent");const u=new t.MergeTranscriptsChange({changedIds:[s._id],typeName:"MergeTranscriptsChange",assembly:l,firstTranscript:i.getSnapshot(s),secondTranscript:i.getSnapshot(f),parentFeatureId:s.parent._id});await e.submit(u),c("Transcripts successfully merged","success"),n(),o.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},0===Object.keys(g).length?"There are no transcripts to merge with":"Merge with transcript:",de.default.createElement(p.FormControl,{style:{marginTop:5}},de.default.createElement(p.RadioGroup,{"aria-labelledby":"demo-radio-buttons-group-label",name:"radio-buttons-group",value:f,onChange:e=>{d("");const{value:t}=e.target;m(g[t])}},Object.keys(g).map((e=>de.default.createElement(p.FormControlLabel,{value:e,key:e,control:de.default.createElement(p.Radio,null),label:de.default.createElement(p.Box,{display:"flex",alignItems:"center"},jt(g[e]))})))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:0===Object.keys(g).length||void 0===f},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),u?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},u)):null)}function Ht({handleClose:e,session:t}){const{apolloDataStore:n}=t,{addAssembly:a,addSessionAssembly:o,assemblyManager:l,notify:s}=t,[i,c]=y.useState(null),[u,d]=y.useState(""),[f,m]=y.useState(""),[g,h]=y.useState(!1),b=p.useTheme();return de.default.createElement(Ke,{open:!0,title:"Open local GFF3 file",handleClose:e,maxWidth:!1,"data-testid":"open-local-file"},de.default.createElement("form",{onSubmit:async function(c){if(c.preventDefault(),m(""),h(!0),!i)throw new Error("No file selected");const d=await new Response(i).text(),f=`${u}-${i.name}-${L.nanoid(8)}`;try{await Oe(f,d,n)}catch(t){return console.error(t),s(`Error loading GFF3 ${i.name}, ${String(t)}`,"error"),void e()}const g={name:f,aliases:[u],displayName:u,sequence:{trackId:`sequenceConfigId-${u}`,type:"ReferenceSequenceTrack",adapter:{type:"ApolloSequenceAdapter",assemblyId:f},metadata:{apollo:!0,...r.isElectron?{file:i.path}:{}}}};await(o||a)(g);const p=await l.waitForAssembly(g.name);p?(t.addApolloTrackConfig(p),s(`Loaded GFF3 ${i.name}`,"success")):s(`Error loading GFF3 ${i.name}`,"error"),e()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.FormControl,null,de.default.createElement("div",{style:{flexDirection:"row"}},de.default.createElement(p.Button,{variant:"contained",component:"label",style:{marginRight:b.spacing()}},"Choose File",de.default.createElement("input",{type:"file",required:!0,hidden:!0,onChange:function(e){const t=e.target.files?.item(0);if(t&&(m(""),c(t),!u)){const e=t.name,n=e.lastIndexOf(".");d(-1===n?e:e.slice(0,n))}}})),i?i.name:"No file chosen"),de.default.createElement(p.FormHelperText,null,"Make sure your GFF3 has an embedded FASTA section")),de.default.createElement(p.TextField,{required:!0,label:"Assembly name",value:u,onChange:function(e){d(e.target.value)}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{disabled:!1,variant:"contained",type:"submit"},g?"Submitting...":"Submit"),de.default.createElement(p.Button,{disabled:g,variant:"outlined",type:"submit",onClick:e},"Cancel"))),f?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},f)):null)}!function(e){e.GENE_AND_SUBFEATURES="GENE_AND_SUBFEATURES",e.TRANSCRIPT_AND_SUBFEATURES="TRANSCRIPT_AND_SUBFEATURES",e.CUSTOM="CUSTOM"}(kt||(kt={}));const zt=b.makeStyles()((e=>({changeTextarea:{fontFamily:"monospace",width:600,resize:"none",border:`1px solid ${e.palette.divider}`,borderRadius:e.shape.borderRadius}})));function Jt({handleClose:t,session:n}){const{internetAccounts:a}=i.getRoot(n),o=a.find((e=>"ApolloInternetAccount"===e.type));if(!o)throw new Error("No Apollo internet account found");const{baseURL:r}=o,{classes:l}=zt(),[s,c]=y.useState(),[u,d]=y.useState([]),[f,m]=y.useState(""),[g,h]=y.useState([]),b=[{field:"sequence"},{field:"typeName",headerName:"Change type",width:200,type:"singleSelect",valueOptions:[...e.changeRegistry.changes.keys()]},{field:"changes",headerName:"Change JSON",width:600,renderCell:({value:e})=>de.default.createElement("textarea",{className:l.changeTextarea,value:JSON.stringify(e),readOnly:!0}),valueFormatter:({value:e})=>JSON.stringify(e)},{field:"user",headerName:"User",width:140},{field:"createdAt",headerName:"Time",width:160,type:"dateTime",valueGetter:e=>e&&new Date(e)}];return y.useEffect((()=>{(async function(){const e=new URL("assemblies",r).href,t=o?.getFetcher({locationType:"UriLocation",uri:e});if(t){const n=await t(e,{method:"GET"});if(!n.ok){const e=await Ve(n,"Error when retrieving assemblies from server");return void c(e)}const a=await n.json();d(a)}})().catch((e=>{c(String(e))}))}),[o,r]),y.useEffect((()=>{!f&&u.length>0&&m(u[0]._id)}),[f,u]),y.useEffect((()=>{(async function(){if(!f)return;const e=new URL("changes",r),t=new URLSearchParams({assembly:f});e.search=t.toString();const n=e.toString(),a=o?.getFetcher({locationType:"UriLocation",uri:n});if(a){const e=await a(n,{headers:new Headers({"Content-Type":"application/json"})});if(!e.ok){const t=await Ve(e,"Error when retrieving changes");return void c(t)}const t=await e.json();h(t)}})().catch((e=>{c(String(e))}))}),[f,o,r]),de.default.createElement(Ke,{open:!0,fullScreen:!0,title:"View change log",handleClose:t,"data-testid":"view-changelog"},de.default.createElement(p.Select,{style:{width:200,marginLeft:40},value:f,onChange:function(e){m(e.target.value)}},u.map((e=>de.default.createElement(p.MenuItem,{key:e._id,value:e._id},e.name)))),de.default.createElement(p.DialogContent,null,de.default.createElement(M.DataGrid,{pagination:!0,rows:g,columns:b,getRowId:e=>e._id,slots:{toolbar:M.GridToolbar},initialState:{sorting:{sortModel:[{field:"sequence",sort:"desc"}]},columns:{columnVisibilityModel:{sequence:!1}}}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:t},"Close")),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}const Vt=[{field:"refName",headerName:"Ref Name"},{field:"aliases",headerName:"Aliases",editable:!0}],Xt=e=>/^[\da-f]{24}$/i.test(e);function Kt({changeManager:e,handleClose:n,session:a}){const o=y.useRef(null),[r,l]=y.useState(""),[s,i]=y.useState(!1),[c,u]=y.useState(),[d,f]=y.useState([]),[m,g]=y.useState(new Map),{apolloDataStore:h}=a,{collaborationServerDriver:b}=h,S=b.getAssemblies();y.useEffect((()=>{let e=0;const t=()=>{if(!c)return;const n=new Map;if(e<2&&!c.refNames&&(e++,setTimeout(t,50)),!c.refNames)return;const a=c.refNameAliases;for(const e in a){const t=a[e];if(t&&!Xt(e))if(n.has(t)){const a=n.get(t)??[];n.set(t,[...a,e])}else n.set(t,[e])}g(n)};t()}),[c]);const w=()=>[...m].map(((e,t)=>({id:t,refName:e[0],aliases:e[1].filter((t=>t!==e[0])).join(", ")})));return de.default.createElement(Ke,{open:!0,title:"Add reference sequence aliases",handleClose:n,maxWidth:"sm","data-testid":"add-refseq-alias",fullWidth:!0},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.Grid2,{container:!0,spacing:2},de.default.createElement(p.Grid2,null,de.default.createElement(p.FormControl,{disabled:s&&!r,fullWidth:!0},de.default.createElement(p.InputLabel,{id:"demo-simple-select-label"},"Assembly"),de.default.createElement(p.Select,{labelId:"demo-simple-select-label",id:"demo-simple-select",label:"Assembly",value:c?.name??"",onChange:e=>{const t=S.find((t=>t.name===e.target.value));u(t),i(!1),l(""),o.current&&(o.current.value="")}},S.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))))),de.default.createElement(p.Grid2,null,de.default.createElement(p.InputLabel,null,"Load RefName alias"),de.default.createElement("input",{type:"file",onChange:e=>{(async e=>{if(!e.target.files)return;const t=e.target.files[0],n=(await t.text()).split("\n"),a=new Map(m);l("");for(const e of n){const t=e.split("\t");for(const e of t)a.has(e)&&a.set(e,[...a.get(e)??[],...t])}g(a)})(e).catch((()=>{l("Error reading file")}))},ref:o,disabled:s&&!r||!c}))),c&&m.size>0?de.default.createElement("div",{style:{height:200,width:"100%",marginTop:20}},de.default.createElement(p.InputLabel,null,"Refname aliases found for selected assembly."),de.default.createElement(M.DataGrid,{rows:w(),columns:Vt,initialState:{pagination:{paginationModel:{page:0,pageSize:5}}},pageSizeOptions:[5,10],onRowSelectionModelChange:e=>{(e=>{if(e.length>0){i(!0);const t=e.flatMap((e=>w().filter((t=>t.id===e))));f(t)}else i(!1),f([])})(e)},processRowUpdate:(e,t)=>{const n=new Map(m);return n.set(e.refName,e.aliases.split(",")),g(n),e},checkboxSelection:!0})):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:!s,onClick:()=>{const a=[];for(const e of d){const{refName:t}=e,n=e.aliases.split(",").map((e=>e.trim())).filter((e=>e.length>0));a.push({refName:t,aliases:n})}if(l(""),!c)return void l("No assembly selected");const o=new t.AddRefSeqAliasesChange({typeName:"AddRefSeqAliasesChange",assembly:c.name,refSeqAliases:a});e.submit(o).catch((()=>{l("Error submitting change")})),n()}},"Submit"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Close")),r?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},r)):null)}function Yt({handleClose:e,session:t}){const{internetAccounts:n}=i.getRoot(t),{collaborationServerDriver:a}=t.apolloDataStore,o=n.find((e=>"ApolloInternetAccount"===e.type));if(!o)throw new Error("No Apollo internet account found");const{baseURL:r}=o,[l,s]=y.useState(),[c,u]=y.useState(),[d,f]=y.useState([]),m=a.getAssemblies();return y.useEffect((()=>{!c&&m.length>0&&u(m[0])}),[m,c]),y.useEffect((()=>{(async function(){const e=c?.name;if(!e)return;const t=new URL("checks",r),n=new URLSearchParams({assembly:e});t.search=n.toString();const a=t.toString(),l=o?.getFetcher({locationType:"UriLocation",uri:a});if(l){const e=await l(a,{headers:new Headers({"Content-Type":"application/json"})});if(!e.ok){const t=await Ve(e,"Error when retrieving checks");return void s(t)}const t=await e.json();f(t)}})().catch((e=>{s(String(e))}))}),[c,o,r]),de.default.createElement(Ke,{open:!0,fullScreen:!0,title:"View check results",handleClose:e,"data-testid":"view-check-results"},de.default.createElement(p.Select,{style:{width:200,marginLeft:40},value:c?.name??"",onChange:function(e){const t=m.find((t=>t.name===e.target.value));u(t)},disabled:0===m.length},m.map((e=>de.default.createElement(p.MenuItem,{key:e.name,value:e.name},e.displayName??e.name)))),de.default.createElement(p.DialogContent,null,de.default.createElement(M.DataGrid,{pagination:!0,rows:d,columns:[{field:"_id",headerName:"id",width:50},{field:"name",headerName:"Check name",width:200},{field:"refSeq",headerName:"Reference sequence ID",width:200},{field:"ids",headerName:"Feature IDs",width:200},{field:"message",headerName:"Message",flex:1}],getRowId:e=>e._id,slots:{toolbar:M.GridToolbar},initialState:{sorting:{sortModel:[{field:"name",sort:"asc"}]},columns:{columnVisibilityModel:{name:!0}}}})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:e},"Close")),l?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},l)):null)}function Zt(e){return e.max-e.min<2?{isSplittable:!1,comment:"This exon is too short to be split"}:{isSplittable:!0,comment:""}}function Qt({changeManager:e,handleClose:n,selectedFeature:a,setSelectedFeature:o,sourceAssemblyId:r,sourceFeature:l}){const[s,c]=y.useState(""),u=i.getSnapshot(l);return de.default.createElement(Ke,{open:!0,title:"Split exon",handleClose:n,maxWidth:!1,"data-testid":"split-exon"},de.default.createElement("form",{onSubmit:function(s){s.preventDefault(),c(""),a?._id===l._id&&o();const i=u.min+(u.max-u.min)/2,d=Math.floor(i),f=Math.ceil(i);if(!l.parent?._id)throw new Error("Splitting an exon without parent is not possible yet");const m=new t.SplitExonChange({changedIds:[l._id],typeName:"SplitExonChange",assembly:r,exonToBeSplit:u,parentFeatureId:l.parent._id,upstreamCut:d,downstreamCut:f,leftExonId:(new ue.default).toHexString(),rightExonId:(new ue.default).toHexString()});e.submit(m),n(),s.preventDefault()}},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.DialogContentText,null,function(e){const t=Zt(e);return t.isSplittable?"Are you sure you want to split the selected exon?":t.comment}(u))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:!Zt(u).isSplittable},"Yes"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:n},"Cancel"))),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}const en=[{field:"name",headerName:"Assembly Name",width:150,editable:!1},{field:"aliases",headerName:"Aliases",width:300,editable:!0}];function tn({changeManager:e,handleClose:n,session:a}){const{apolloDataStore:o}=a,{collaborationServerDriver:r}=o,l=r.getAssemblies().map((e=>({id:e.name,name:e.displayName??e.name,aliases:e.aliases.join(", ")}))),[s,i]=de.default.useState("");return de.default.createElement(Ke,{open:!0,title:"Add assembly aliases",handleClose:n,maxWidth:"sm","data-testid":"add-assembly-alias",fullWidth:!0},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column"}},de.default.createElement(p.Box,{sx:{height:400,width:"100%"}},de.default.createElement(M.DataGrid,{rows:l,columns:en,initialState:{pagination:{paginationModel:{pageSize:5}}},pageSizeOptions:[5],processRowUpdate:(a,o)=>{const r=new t.AddAssemblyAliasesChange({typeName:"AddAssemblyAliasesChange",assembly:a.id,aliases:a.aliases.split(",")});return e.submit(r).catch((()=>{i("Error submitting change")})),n(),a},disableRowSelectionOnClick:!0}))),s?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},s)):null)}function nn(e){const{color:t}=e;return de.default.createElement(p.SvgIcon,{viewBox:"0 0 18 18",style:{fontSize:18,marginRight:4},...e},"disabled"===t?de.default.createElement("path",{d:"M9.001,10.71 l0,-3.348 l8.424,0 c0.126,0.567,0.225,1.098,0.225,1.845 c0,5.139,-3.447,8.793,-8.64,8.793 c-4.968,0,-9,-4.032,-9,-9 c0,-4.968,4.032,-9,9,-9 c2.43,0,4.464,0.891,6.021,2.349 l-2.556,2.484 c-0.648,-0.612,-1.782,-1.332,-3.465,-1.332 c-2.979,0,-5.409,2.475,-5.409,5.508 c0,3.033,2.43,5.508,5.409,5.508 c3.447,0,4.716,-2.385,4.95,-3.798 l-4.959,0 l0,-0.009 z"}):de.default.createElement(de.default.Fragment,null,de.default.createElement("path",{d:"M17.64,9.20454545 c0,-0.638,-0.057,-1.252,-0.164,-1.841 l-8.476,0 l0,3.481 l4.844,0 c-0.209,1.125,-0.843,2.079,-1.796,2.717 l0,2.258 l2.908,0 c1.702,-1.567,2.684,-3.874,2.684,-6.615 l0,0 z",fill:"#4285F4"}),de.default.createElement("path",{d:"M9,18 c2.43,0,4.467,-0.806,5.956,-2.18 l-2.908,-2.259 c-0.806,0.54,-1.837,0.859,-3.048,0.859 c-2.344,0,-4.328,-1.583,-5.036,-3.71 l-3.007,0 l0,2.332 c1.481,2.941,4.525,4.958,8.043,4.958 l0,0 z",fill:"#34A853"}),de.default.createElement("path",{d:"M3.96409091,10.71 c-0.18,-0.54,-0.282,-1.117,-0.282,-1.71 c0,-0.593,0.102,-1.17,0.282,-1.71 l0,-2.332 l-3.007,0 c-0.609,1.215,-0.957,2.59,-0.957,4.042 c0,1.452,0.348,2.827,0.957,4.042 l3.007,-2.332 l0,0 z",fill:"#FBBC05"}),de.default.createElement("path",{d:"M9,3.57954545 c1.321,0,2.508,0.454,3.44,1.346 l2.582,-2.581 c-1.559,-1.453,-3.596,-2.345,-6.022,-2.345 c-3.518,0,-6.562,2.017,-8.043,4.959 l3.007,2.331 c0.708,-2.127,2.692,-3.71,5.036,-3.71 l0,0 z",fill:"#EA4335"})))}function an(e){const{color:t}=e;return de.default.createElement(p.SvgIcon,{viewBox:"0 0 21 21",style:{fontSize:21},...e},de.default.createElement("rect",{x:"1",y:"1",width:"9",height:"9",fill:"disabled"===t?"#7B7B7B":"#F25022"}),de.default.createElement("rect",{x:"1",y:"11",width:"9",height:"9",fill:"disabled"===t?"#7B7B7B":"#00A4EF"}),de.default.createElement("rect",{x:"11",y:"1",width:"9",height:"9",fill:"disabled"===t?"#939393":"#7FBA00"}),de.default.createElement("rect",{x:"11",y:"11",width:"9",height:"9",fill:"disabled"===t?"#B9B9B9":"#FFB900"}))}const on=b.makeStyles()((e=>({loginButton:{marginBottom:e.spacing(1),width:"220px",height:"40px",fontSize:"16px",textTransform:"none",justifyContent:"left",padding:"3px 12px"}})));function rn(e){const{classes:t}=on(),{disabled:n}=e;return de.default.createElement(p.Button,{className:t.loginButton,variant:"outlined",startIcon:de.default.createElement(nn,{color:n?"disabled":void 0}),...e},"Sign in with Google")}function ln(e){const{classes:t}=on(),{disabled:n}=e;return de.default.createElement(p.Button,{className:t.loginButton,variant:"outlined",startIcon:de.default.createElement(an,{color:n?"disabled":void 0}),...e},"Sign in with Microsoft")}function sn(e){const{classes:t}=on();return de.default.createElement(p.Button,{className:t.loginButton,variant:"outlined",startIcon:de.default.createElement(Se.default,{fontSize:"small"}),...e},"Continue as Guest")}const cn=b.makeStyles()((e=>({divider:{marginTop:e.spacing(4),marginBottom:e.spacing(5)}}))),un=({baseURL:e,handleClose:t,name:n})=>{const{classes:a}=cn(),[o,r]=y.useState(""),[l,s]=y.useState([]);function i(e){t("google"===e?"google":"microsoft"===e?"microsoft":"guest")}y.useEffect((()=>{const t=new AbortController,{signal:n}=t;return async function(){const t=new URL("auth/types",e).href,a=await fetch(t,{method:"GET",signal:n});if(!a.ok){const e=await Ve(a,"Error when retrieving auth types from server");return void r(e)}const o=await a.json();s(o)}().catch((e=>{x.isAbortException(e)||r(String(e))})),()=>{t.abort()}}),[e]);const c=l.includes("google"),u=l.includes("microsoft"),d=l.includes("guest");return de.default.createElement(Ke,{open:!0,title:`Log in to ${n}`,handleClose:t,maxWidth:!1,"data-testid":"login-apollo"},de.default.createElement(p.DialogContent,{style:{display:"flex",flexDirection:"column",paddingTop:8}},c?de.default.createElement(rn,{disabled:!c,onClick:()=>{i("google")}}):null,u?de.default.createElement(ln,{disabled:!u,onClick:()=>{i("microsoft")}}):null,d?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.Divider,{className:a.divider}),de.default.createElement(sn,{onClick:()=>{i("guest")}})):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:()=>{t()}},"Cancel")),o?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},o)):null)},dn="undefined"==typeof sessionStorage,fn=n=>o.InternetAccount.named("ApolloInternetAccount").props({type:i.types.literal("ApolloInternetAccount"),configuration:a.ConfigurationReference(n)}).views((e=>({get baseURL(){return a.getConf(e,"baseURL")},getUserId(){const n=e.retrieveToken();if(n)return t.getDecodedToken(n).id}}))).volatile((()=>({role:void 0}))).actions((e=>{let n=!1;return{setRole(){const a=e.retrieveToken();if(!a)return void(e.role=void 0);const o=t.getDecodedToken(a),{role:r}=o;if(!r&&!n){const{session:t}=i.getRoot(e);t.notify("You have registered as a user but have not been given access. Ask your administrator to enable access for your account.","warning"),n=!0}e.role!==r&&(e.role=r)}}})).actions((e=>{let t;return{addMessageChannel(e,n){t=t=>{this.finishOAuthWindow(t,e,n)},window.addEventListener("message",t)},deleteMessageChannel(){window.removeEventListener("message",t)},finishOAuthWindow(t,n,a){if(t.data.name!==`JBrowseAuthWindow-${e.internetAccountId}`)return void this.deleteMessageChannel();const o=t.data.redirectUri.replace("#","?"),r=new URL(o),l=new URLSearchParams(r.search).get("access_token");this.deleteMessageChannel(),l?(e.storeToken(l),e.setRole(),n(l)):a(new Error("Error with token endpoint"))},async openAuthWindow(t,n,a){const o=r.isElectron?"http://localhost/auth":globalThis.location.origin+globalThis.location.pathname,l=new URL("auth/login",e.baseURL),s=new URLSearchParams({type:t,redirect_uri:o});l.search=s.toString();const i=`JBrowseAuthWindow-${e.internetAccountId}`;if(r.isElectron){const{ipcRenderer:t}=globalThis.require("electron"),r=await t.invoke("openAuthWindow",{internetAccountId:e.internetAccountId,data:{redirect_uri:o},url:l.toString()}),s=new MessageEvent("message",{data:{name:i,redirectUri:r}});this.finishOAuthWindow(s,n,a)}else this.addMessageChannel(n,a),window.open(l,i,"width=500,height=600")}}})).actions((e=>({async getTokenFromUser(t,n){const{baseURL:a}=e,o=await new Promise(((t,n)=>{const{session:a}=i.getRoot(e),{baseURL:o,name:r}=e;a.queueDialog((e=>[un,{name:r,handleClose:a=>{a?a instanceof Error?n(a):t(a):n(new Error("user cancelled entry")),e()},baseURL:o}]))}));if("guest"!==o)return void e.openAuthWindow(o,t,n);const r=new URL("auth/login",a),l=new URLSearchParams({type:o});r.search=l.toString();const s=r.toString(),c=await fetch(s);if(!c.ok){const e=await Ve(c,"Error when logging in");return void n(new Error(e))}const{token:u}=await c.json();t(u)}}))).volatile((()=>({lastChangeSequenceNumber:void 0}))).actions((e=>({setLastChangeSequenceNumber(t){e.lastChangeSequenceNumber=t}}))).actions((t=>({updateLastChangeSequenceNumber:i.flow((function*(){const{baseURL:e}=t,n=new URL("changes",e),a=new URLSearchParams({limit:"1"});n.search=a.toString();const o=n.toString(),r=t.getFetcher({locationType:"UriLocation",uri:o}),l=yield r(o,{method:"GET"});if(!l.ok){const e=yield Ve(l,"Error when fetching server LastChangeSequence");throw new Error(e)}const s=yield l.json();t.setLastChangeSequenceNumber(s.length>0?s[0].sequence:0)})),getMissingChanges:i.flow((function*(){const{session:n}=i.getRoot(t),{changeManager:a}=n.apolloDataStore;if(!t.lastChangeSequenceNumber)throw new Error("No LastChangeSequence stored in session. Please, refresh you browser to get last updates from server");const{baseURL:o,lastChangeSequenceNumber:r}=t,l=new URL("changes",o),s=new URLSearchParams({since:String(r),sort:"1"});l.search=s.toString();const c=l.toString(),u=t.getFetcher({locationType:"UriLocation",uri:c}),d=yield u(c,{method:"GET"});if(!d.ok)return void console.error(`Error when fetching the last updates to recover socket connection — ${d.status}`);const f=yield d.json();for(const t of f){const n=e.Change.fromJSON(t);a.submit(n,{submitToBackend:!1})}}))}))).volatile((e=>{const{origin:t,pathname:n}=new URL("socket.io/",e.baseURL);return{socket:c.io(t,{path:n})}})).actions((n=>({addSocketListeners(){const{session:a}=i.getRoot(n),{notify:o}=a,r=n.retrieveToken();if(!r)throw new Error("No Token found");const{socket:l}=n,{addCheckResult:s,changeManager:c,deleteCheckResult:u}=a.apolloDataStore;l.on("connect",(async()=>{await n.getMissingChanges()})),l.on("connect_error",(e=>{console.error(e),o("Could not connect to the Apollo server.","error")})),l.on("COMMON",(t=>{if("checkResult"in t)return void(t.deleted?u(t.checkResult._id.toString()):s(t.checkResult));if(sessionStorage.setItem("LastChangeSequence",String(t.changeSequence)),t.userSessionId===r)return;const n=e.Change.fromJSON(t.changeInfo);c.submit(n,{submitToBackend:!1})})),l.on("USER_LOCATION",(e=>{const{channel:n,locations:o,userName:l,userSessionId:s}=e,i=t.getDecodedToken(r),c=t.makeUserSessionId(i);"USER_LOCATION"===n&&s!==c&&a.addOrUpdateCollaborator({name:l,id:s,locations:o})})),l.on("REQUEST_INFORMATION",(e=>{const{channel:t,userSessionId:n}=e;"REQUEST_INFORMATION"===t&&n!==r&&a.broadcastLocations()}))}}))).actions((e=>({postUserLocation:(t=>{let n;return t=>{clearTimeout(n),n=setTimeout((()=>{!async function(t){const{baseURL:n}=e,a=new URL("users/userLocation",n).href,o=new URLSearchParams(JSON.stringify(t)),r=e.getFetcher({locationType:"UriLocation",uri:a});try{if(!(await r(a,{method:"POST",body:o})).ok)throw new Error("ignore")}catch{console.error("Broadcasting user location failed")}}(t)}),300)}})()}))).actions((e=>({initialize:i.flow((function*(t){if("admin"===t){const t=i.getRoot(e);r.isAbstractMenuManager(t)&&function(e){e.appendToMenu("Apollo",{label:"Add Assembly",onClick:e=>{e.queueDialog((t=>[et,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Delete Assembly",onClick:e=>{e.queueDialog((t=>[Lt,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Import Features",onClick:e=>{e.queueDialog((t=>[Ot,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Add reference sequence aliases",onClick:e=>{e.queueDialog((t=>[Kt,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Add Assembly aliases",onClick:e=>{e.queueDialog((t=>[tn,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Manage Users",onClick:e=>{e.queueDialog((t=>[Ut,{session:e,handleClose:()=>{t()},changeManager:e.apolloDataStore.changeManager}]))}}),e.appendToMenu("Apollo",{label:"Undo",onClick:e=>{const{apolloDataStore:t}=e,{notify:n}=e;t.changeManager.recentChanges.length>0?t.changeManager.revertLastChange():n("No changes to undo","info")}})}(t)}yield e.updateLastChangeSequenceNumber(),e.addSocketListeners();const{baseURL:n}=e,a=new URL("users/locations",n).href,o=e.getFetcher({locationType:"UriLocation",uri:a});yield o(a,{method:"GET"}),window.addEventListener("beforeunload",(()=>{e.postUserLocation([])})),document.addEventListener("visibilitychange",(()=>{if("hidden"===document.visibilityState&&e.postUserLocation([]),"visible"===document.visibilityState){const{session:t}=i.getRoot(e);t.broadcastLocations()}}))}))}))).actions((e=>({afterAttach(){e.setRole(),s.autorun((async t=>{if(dn)return;const{session:n}=i.getRoot(e);n&&e.role&&(await e.initialize(e.role),t.dispose())}),{name:"ApolloInternetAccount"})}}))),mn="undefined"==typeof sessionStorage;class gn extends O.BaseAdapter{refNameAliases;async getRefNameAliases(){const e=a.readConfObject(this.config,"assemblyId");if(!mn){const t=this.pluginManager?.rootModel?.session?.apolloDataStore;if(!t)throw new Error("No Apollo data store found");const n=t.getBackendDriver(e);return await n.getRefNameAliases(e)}const t=await new Promise(((t,n)=>{const a=setTimeout((()=>{n(new Error("timeout"))}),2e4),o=L.nanoid(),r=e=>{const n=e.data;(function(e){return"object"==typeof e&&null!==e&&"apollo"in e&&!0===e.apollo&&"refNameAliases"in e})(n)&&n.messageId===o&&(clearTimeout(a),removeEventListener("message",r),t(n.refNameAliases))};addEventListener("message",r),rpcServer.emit("apollo",{apollo:!0,method:"getRefNameAliases",assembly:e,messageId:o})}));return this.refNameAliases=t,t}freeResources(){}}var pn=a.ConfigurationSchema("ApolloRefNameAliasAdapter",{assemblyId:{type:"string",defaultValue:""}},{explicitlyTyped:!0});function hn(e){return"object"==typeof e&&null!==e&&"apollo"in e&&!0===e.apollo}const yn="undefined"==typeof sessionStorage;class bn extends O.BaseSequenceAdapter{regions;async getRefNames(){return(await this.getRegions()).map((e=>e.refName))}async getRegions(){if(this.regions)return this.regions;const e=a.readConfObject(this.config,"assemblyId");if(!yn){const t=this.pluginManager?.rootModel?.session?.apolloDataStore;if(!t)throw new Error("No Apollo data store found");const n=t.getBackendDriver(e),a=await n.getRegions(e);return this.regions=a,a}const t=await new Promise(((t,n)=>{const a=setTimeout((()=>{n("timeout")}),2e4),o=L.nanoid(),r=e=>{const{data:n}=e;hn(n)&&n.messageId===o&&(clearTimeout(a),removeEventListener("message",r),t(n.regions))};addEventListener("message",r),globalThis.rpcServer.emit("apollo",{apollo:!0,method:"getRegions",assembly:e,messageId:o})}));return this.regions=t,t}getFeatures(e){const{end:t,refName:n,start:o}=e,r=a.readConfObject(this.config,"assemblyId"),l={...e,assemblyName:r};return _.ObservableCreate((async e=>{if(!yn){const a=this.pluginManager?.rootModel?.session?.apolloDataStore;if(!a)return void e.error("No Apollo data store found");const s=a.getBackendDriver(r),i=(await s.getRegions(l.assemblyName)).find((e=>e.refName===l.refName));if(!i)return void e.error("Cannot get region");l.end>i.end&&(l.end=i.end);const{seq:c}=await s.getSequence(l);return e.next(new Ee.default({id:`${n} ${o}-${t}`,data:{refName:n,start:o,end:t,seq:c}})),void e.complete()}const a=await new Promise(((e,t)=>{const n=setTimeout((()=>{t("timeout")}),2e4),a=L.nanoid(),o=t=>{const{data:r}=t;hn(r)&&r.messageId===a&&(clearTimeout(n),removeEventListener("message",o),e(r.sequence))};addEventListener("message",o),globalThis.rpcServer.emit("apollo",{apollo:!0,method:"getSequence",region:l,messageId:a})}));e.next(new Ee.default({id:`${n} ${o}-${t}`,data:{refName:n,start:o,end:t,seq:a}})),e.complete()}))}freeResources(){}}var Sn=a.ConfigurationSchema("ApolloSequenceAdapter",{assemblyId:{type:"string",defaultValue:""}},{explicitlyTyped:!0});class wn extends O.BaseAdapter{get baseURL(){return a.readConfObject(this.config,"baseURL").uri}get trackId(){return a.readConfObject(this.config,"trackId")}get assemblyNames(){return a.readConfObject(this.config,"assemblyNames")}mapBaseResult(e,t,n){return e.map((e=>{const a=t.getCanonicalRefName(e.refSeq);return new ve.default({label:n,trackId:this.trackId,locString:`${a}:${e.min+1}..${e.max}`})}))}async searchIndex(e){const t=e.queryString,n=[],a=this.pluginManager?.rootModel?.session;if(!a)return n;const{apolloDataStore:o}=a,{assemblyManager:r}=a;for(const a of this.assemblyNames){const l=o.getBackendDriver(a),s=r.get(a);if(!l||!s)continue;const i=await l.searchFeatures(e.queryString,[a]);n.push(...this.mapBaseResult(i,s,t))}return n}freeResources(){}}var En=a.ConfigurationSchema("ApolloTextSearchAdapter",{assemblyNames:{type:"stringArray",defaultValue:[],description:"List of assemblies covered by text search adapter"},trackId:{type:"string",defaultValue:""},baseURL:{type:"fileLocation",defaultValue:{uri:"",locationType:"UriLocation"}}},{explicitlyTyped:!0,explicitIdentifier:"textSearchAdapterId"});const vn=b.makeStyles()((e=>({attributeKey:{fontWeight:"bold",marginRight:e.spacing(2)}})));function Cn({attributeKey:e}){const{classes:n}=vn(),a=/^[A-Z]/.test(e);let o,r=e;return t.isGFFInternalAttribute(e)?(r=t.internalToGFF[e],o=`On GFF3 export, this will be assigned to the GFF3's reserved "${r}" attribute`):t.isGFFColumnInternal(e)?(r=t.gffInternalToColumn[e],o=`On GFF3 export, this will be placed in the GFF3's "${r}" column`):a&&(o="On GFF3 export, this attribute will be changed to start with a lower-case letter because attributes starting with an upper-case letter are reserved in GFF3"),de.default.createElement("div",{style:{display:"flex"}},de.default.createElement(p.Typography,{className:n.attributeKey},r),o?de.default.createElement(p.Tooltip,{title:o},de.default.createElement(p.Chip,{icon:de.default.createElement(le.default,null),label:"GFF3",size:"small",variant:"outlined"})):null)}const xn="Custom",Tn={[xn]:"custom"};for(const[e,n]of Object.entries(t.gffToInternal))Tn[`GFF ${n}`]=e;for(const[e,n]of Object.entries(t.gffColumnToInternal))Tn[`GFF ${n}`]=e;const An=E.observer((function({setKey:e,session:t}){const{pluginManager:n}=r.getEnv(t),a=n.evaluateExtensionPoint("Apollo-ReservedAttributeKeys",Tn),o=Object.keys(a).at(0)??xn,[l,s]=y.useState(o),[i,c]=y.useState(),u=l===xn;return de.default.createElement("form",{onSubmit:function(t){t.preventDefault(),e(u?i:a[l])}},de.default.createElement("div",{style:{display:"flex",flexDirection:"column",margin:8}},de.default.createElement(p.FormControl,{variant:"outlined"},de.default.createElement(p.InputLabel,{id:"attribute-key-select-label"},"Key"),de.default.createElement(p.Select,{labelId:"attribute-key-select-label",value:l,label:"Key",onChange:e=>{s(e.target.value)}},Object.keys(a).map((e=>de.default.createElement(p.MenuItem,{key:e,value:e},e))))),u?de.default.createElement(p.TextField,{label:"Attribute key",variant:"outlined",id:"attributeKey",onChange:e=>{c(e.target.value)}}):null),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{color:"primary",variant:"contained",type:"submit",disabled:u&&!i},"Add"),de.default.createElement(p.Button,{variant:"outlined",onClick:function(){e()}},"Cancel")))})),Fn=E.observer((function({onChangeCommitted:e,value:t,...n}){const[a,o]=y.useState(String(t)),[r,l]=y.useState(!1),[s,i]=y.useState(null);return y.useEffect((()=>{o(String(t))}),[t]),y.useEffect((()=>{r&&(s?.blur(),l(!1))}),[r,s]),de.default.createElement(p.TextField,{...n,type:"text",onChange:function(e){o(e.target.value)},value:a,onKeyDown:e=>{"Enter"===e.key?s?.blur():"Escape"===e.key&&(o(String(t)),l(!0))},onBlur:()=>{a!==String(t)&&e(a)},inputRef:e=>{i(e)}})})),Dn=E.observer((function({attributeValues:e,setAttribute:t,isNew:n=!1}){const[a,o]=y.useState(e&&e.length>0?e:[""]);return de.default.createElement(de.default.Fragment,null,a.map(((e,t)=>de.default.createElement("div",{key:`${t}-${e}`,style:{display:"flex"}},de.default.createElement(Fn,{value:e,onChangeCommitted:e=>{!function(e,t){o((n=>{const a=[...n];return a[e]=t,a}))}(t,e)},variant:"outlined",fullWidth:!0}),de.default.createElement(p.IconButton,{"aria-label":"delete",size:"medium",edge:"end",onClick:()=>{!function(e){o((t=>{const n=[...t];return n.splice(e,1),n}))}(t)}},de.default.createElement(be.default,{fontSize:"inherit"}))))),de.default.createElement(p.IconButton,{"aria-label":"add",size:"medium",color:"secondary",edge:"start",onClick:function(){o((e=>{const t=[...e];return t.push(""),t}))}},de.default.createElement(Ae.default,{fontSize:"inherit"})),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{color:"primary",variant:"contained",onClick:()=>{t(a.filter(Boolean))}},n?"Add":"Update"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:()=>{t()}},"Cancel")))}));function kn({values:e}){return de.default.createElement(de.default.Fragment,null,e?.map(((e,t)=>de.default.createElement(p.Typography,{key:`${t}.${e}`,variant:"body2",color:"textSecondary"},e))))}const Nn=b.makeStyles()((e=>({list:{"li:nth-of-type(odd)":{backgroundColor:e.palette.action.focus},"li:nth-of-type(even)":{backgroundColor:e.palette.action.hover}}}))),In=E.observer((function({assembly:e,editable:n,feature:a,session:o}){const{pluginManager:l}=r.getEnv(o),{classes:c}=Nn(),[u,d]=y.useState(null),[f,m]=y.useState(null),[g,h]=y.useState(null),[b,S]=y.useState(!1),[w,E]=y.useState(),v=Boolean(u),{changeManager:C}=o.apolloDataStore,{notify:x}=o;function T(){d(null),m(null)}const{_id:A,attributes:F}=a,D=l.evaluateExtensionPoint("Apollo-AttributeEditorComponent",Dn,{key:w});return de.default.createElement(de.default.Fragment,null,de.default.createElement(p.List,{className:c.list},s.entries(F).map((([r,s])=>{const c=l.evaluateExtensionPoint("Apollo-AttributeEditorComponent",Dn,{key:r}),u=l.evaluateExtensionPoint("Apollo-AttributeViewerComponent",kn,{key:r});return de.default.createElement(p.ListItem,{key:r,secondaryAction:n&&!g?de.default.createElement(p.IconButton,{edge:"end",onClick:e=>{!function(e,t){d(e.currentTarget),m(t)}(e,r)}},de.default.createElement(Te.default,null)):null},de.default.createElement(p.ListItemText,{disableTypography:!0,primary:de.default.createElement(Cn,{attributeKey:r}),secondary:g===r?de.default.createElement(c,{session:o,attributeValues:s,setAttribute:n=>{h(null),n&&function(n,o){const r={...i.getSnapshot(F)},l=structuredClone(r);if(!(n in r))return void x(`"${n}" not found in feature attributes`,"error");if(r[n].toString()===o.toString())return;r[n]=o;const s=new t.FeatureAttributeChange({changedIds:[a._id],typeName:"FeatureAttributeChange",assembly:e,featureId:a._id,oldAttributes:l,newAttributes:r});C.submit(s)}(r,n)}}):de.default.createElement(u,{values:s})}))})),w?de.default.createElement(p.ListItem,null,de.default.createElement(p.ListItemText,{disableTypography:!0,primary:de.default.createElement(Cn,{attributeKey:w}),secondary:de.default.createElement(D,{session:o,attributeValues:[],setAttribute:n=>{n&&function(n,o){const r={...i.getSnapshot(F)},l=structuredClone(r);if(n in r)return void x(`Feature already has attribute "${n}"`,"error");r[n]=o;const s=new t.FeatureAttributeChange({changedIds:[a._id],typeName:"FeatureAttributeChange",assembly:e,featureId:a._id,oldAttributes:l,newAttributes:r});C.submit(s)}(w,n),E(void 0)},isNew:!0})})):null),n?de.default.createElement(p.Button,{color:"primary",variant:"contained",disabled:b||Boolean(w),onClick:()=>{S(!0)}},"Add new"):null,b?de.default.createElement(p.Paper,{variant:"outlined",style:{marginTop:8}},de.default.createElement(An,{session:o,setKey:e=>{E(e),S(!1)}})):null,de.default.createElement(p.Menu,{anchorEl:u,open:v,onClose:T},de.default.createElement(p.MenuItem,{onClick:function(){f&&function(n){const a=i.getSnapshot(F),{[n]:o,...r}=a,l=new t.FeatureAttributeChange({changedIds:[A],typeName:"FeatureAttributeChange",assembly:e,featureId:A,oldAttributes:a,newAttributes:r});C.submit(l)}(f),T()}},de.default.createElement(p.ListItemIcon,null,de.default.createElement(be.default,{fontSize:"small"})),de.default.createElement(p.Typography,{variant:"inherit"},"Delete")),de.default.createElement(p.MenuItem,{onClick:function(){f&&h(f),T()}},de.default.createElement(p.ListItemIcon,null,de.default.createElement(xe.default,{fontSize:"small"})),de.default.createElement(p.Typography,{variant:"inherit"},"Edit"))))})),Rn=E.observer((function({onChangeCommitted:e,value:t,...n}){const[a,o]=y.useState(String(t)),[r,l]=y.useState(!1),[s,i]=y.useState(null);y.useEffect((()=>{o(String(t))}),[t]),y.useEffect((()=>{r&&(s?.blur(),l(!1))}),[r,s]);const c=Number.isNaN(Number(a));return de.default.createElement(p.TextField,{...n,type:"text",onChange:function(e){o(e.target.value)},value:a,onKeyDown:e=>{"Enter"===e.key?s?.blur():"Escape"===e.key&&(o(String(t)),l(!0))},onBlur:()=>{const n=Number(a);a!==String(t)&&(Number.isNaN(n)?o(String(t)):e(n))},inputRef:e=>{i(e)},error:c,helperText:c?"Not a valid number":void 0})})),Mn=E.observer((function({assembly:e,feature:n,session:a}){const[o,r]=y.useState(""),[l,s]=y.useState(""),{_id:i,assemblyId:c,max:u,min:d,strand:f,type:m}=n,g=e=>{a.notify(e.message,"error")},{changeManager:h}=a.apolloDataStore;function b(n){const{value:a}=n.target,o=a?Number(a):void 0,r=new t.StrandChange({typeName:"StrandChange",changedIds:[i],featureId:i,oldStrand:f,newStrand:o,assembly:e});return h.submit(r)}return de.default.createElement("div",{"data-testid":"basic_information"},de.default.createElement(Rn,{margin:"dense",id:"start",label:"Start",fullWidth:!0,variant:"outlined",value:d+1,onChangeCommitted:function(n){n--;const a=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[i],featureId:i,oldStart:d,newStart:n,assembly:e});return h.submit(a)}}),de.default.createElement(Rn,{margin:"dense",id:"end",label:"End",fullWidth:!0,variant:"outlined",value:u,onChangeCommitted:function(n){const a=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[i],featureId:i,oldEnd:u,newEnd:n,assembly:e});return h.submit(a)}}),de.default.createElement(Ft,{session:a,ontologyName:"Sequence Ontology",value:m,filterTerms:xt,fetchValidTerms:async function(e,t,n){const a=await At(e,t);if(a)return a;s(`Type "${e?.type}" does not have any children in the ontology`)}.bind(null,n),renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Type",variant:"outlined",fullWidth:!0,error:Boolean(l),helperText:l}),onChange:(e,n)=>{n&&function(e){r("");const n=new t.TypeChange({typeName:"TypeChange",changedIds:[i],featureId:i,oldType:m,newType:e,assembly:c});return h.submit(n)}(n).catch(g)}}),de.default.createElement("label",null,de.default.createElement("input",{type:"radio",value:"1",checked:1===f,onChange:b}),"Positive Strand (+)"),de.default.createElement("label",null,de.default.createElement("input",{type:"radio",value:"-1",checked:-1===f,onChange:b}),"Negative Strand (-)"),de.default.createElement("label",null,de.default.createElement("input",{type:"radio",value:"",checked:void 0===f,onChange:b}),"No Strand Information"),o?de.default.createElement(p.Typography,{color:"error"},o):null)})),Ln=E.observer((function(e){const{feature:t,model:n}=e,{children:a,parent:o}=t,r=[];if(a)for(const[,e]of a)r.push(e);return o??r.length>0?de.default.createElement("div",{style:{marginTop:10}},o&&de.default.createElement("div",null,de.default.createElement(p.Typography,{variant:"h6"},"Parent:"),de.default.createElement(p.Button,{variant:"contained",onClick:()=>{n.setFeature(o)}},o.type,$e(o)," (",o.min,"..",o.max,")")),r.length>0&&de.default.createElement("div",null,de.default.createElement(p.Typography,{variant:"h6"},1===r.length?"Child":"Children",":"),r.map((e=>de.default.createElement("div",{key:e._id,style:{marginBottom:5}},de.default.createElement(p.Button,{variant:"contained",onClick:()=>{n.setFeature(e)}},e.type,$e(e)," (",e.min,"..",e.max,")")))))):null})),Pn=b.makeStyles()({sequence:{width:"100%",resize:"vertical"}}),qn=E.observer((function({assembly:e,feature:t,refName:n,session:a}){const o=a.apolloDataStore.assemblies.get(e),{classes:r}=Pn();if(!t||!o)return null;const l=o.getByRefName(n);if(!l)return null;const{max:s,min:i}=t;let c=l.getSequence(i,s);return c?c=function(e,t,n,a,o){return`>${t}:${n+1}–${a}\n${e}`}(c,n,i,s):a.apolloDataStore.loadRefSeq([{assemblyName:e,refName:n,start:i,end:s}]),de.default.createElement("div",null,de.default.createElement("textarea",{readOnly:!0,rows:20,className:r.sequence,value:c}))})),On=b.makeStyles()((e=>({root:{padding:e.spacing(2)}}))),_n=E.observer((function(e){const{model:t}=e,{assembly:n,feature:a,refName:o}=t,l=r.getSession(t),s=l.apolloDataStore.assemblies.get(n),{classes:i}=On(),[c,u]=y.useState(["attributes"]);if(y.useEffect((()=>{u(["attributes"])}),[a]),!a||!s)return null;const d=s.getByRefName(o);if(!d)return null;const{max:f,min:m}=a;function g(e,t){u(e?[...c,t]:c.filter((e=>e!==t)))}return d.getSequence(m,f)||l.apolloDataStore.loadRefSeq([{assemblyName:n,refName:o,start:m,end:f}]),de.default.createElement("div",{className:i.root},de.default.createElement(Mn,{feature:a,session:l,assembly:s._id}),de.default.createElement(p.Accordion,{style:{marginTop:10},expanded:c.includes("attributes"),onChange:(e,t)=>{g(t,"attributes")}},de.default.createElement(p.AccordionSummary,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel1-content",id:"panel1-header"},de.default.createElement(p.Typography,{component:"span"},"Attributes")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(In,{feature:a,session:l,assembly:s._id,editable:!0}))),de.default.createElement(p.Accordion,{style:{marginTop:10},expanded:c.includes("sequence"),onChange:(e,t)=>{g(t,"sequence")}},de.default.createElement(p.AccordionSummary,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel2-content",id:"panel2-header"},de.default.createElement(p.Typography,{component:"span"},"Sequence")),de.default.createElement(p.AccordionDetails,null,c.includes("sequence")&&de.default.createElement(qn,{feature:a,session:l,assembly:s._id,refName:o}))),de.default.createElement(p.Accordion,{style:{marginTop:10},expanded:c.includes("related_features"),onChange:(e,t)=>{g(t,"related_features")}},de.default.createElement(p.AccordionSummary,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel3-content",id:"panel3-header"},de.default.createElement(p.Typography,{component:"span"},"Related features")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(Ln,{model:t,feature:a}))))})),Bn=i.types.model("ApolloFeatureDetailsWidget",{id:v.ElementId,type:i.types.literal("ApolloFeatureDetailsWidget"),feature:i.types.maybe(i.types.reference(H.AnnotationFeatureModel,{onInvalidated(e){e.parent.setTryReload(e.invalidId),e.removeRef()}})),assembly:i.types.string,refName:i.types.string}).volatile((()=>({tryReload:void 0}))).actions((e=>({setFeature(t){e.feature=t},setTryReload(t){e.tryReload=t}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((t=>{if(!e.tryReload)return;const n=r.getSession(e),{apolloDataStore:a}=n;if(!a)return;const o=a.getFeature(e.tryReload);o&&(e.setFeature(o),e.setTryReload(),t.dispose())})))}}))),Un=i.types.model("ApolloTranscriptDetails",{id:v.ElementId,type:i.types.literal("ApolloTranscriptDetails"),feature:i.types.maybe(i.types.reference(H.AnnotationFeatureModel,{onInvalidated(e){e.parent.setTryReload(e.invalidId),e.removeRef()}})),assembly:i.types.string,refName:i.types.string}).volatile((()=>({tryReload:void 0}))).actions((e=>({setFeature(t){e.feature=t},setTryReload(t){e.tryReload=t}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((t=>{if(!e.tryReload)return;const n=r.getSession(e),{apolloDataStore:a}=n;if(!a)return;const o=a.getFeature(e.tryReload);o&&(e.setFeature(o),e.setTryReload(),t.dispose())})))}})));async function $n(e){if(isSecureContext){const t=new Blob([e.outerText],{type:"text/plain"}),n=new Blob([e.outerHTML],{type:"text/html"}),a=new ClipboardItem({[t.type]:t,[n.type]:n});return navigator.clipboard.write([a])}const t=t=>{t.clipboardData?.setData("text/plain",e.outerText),t.clipboardData?.setData("text/html",e.outerHTML),t.preventDefault()};document.addEventListener("copy",t),document.execCommand("copy"),document.removeEventListener("copy",t)}const Gn=60;function jn(e,n,a){const o=[],{cdsLocations:l,strand:s,transcriptParts:i}=n;switch(e){case"genomic":case"cDNA":{const[n]=i;for(const l of n){if("cDNA"===e&&"intron"===l.type)continue;let n=a(l.min,l.max);-1===s&&(n=r.revcom(n));const i="fivePrimeUTR"===l.type||"threePrimeUTR"===l.type?"UTR":l.type,c=o.at(-1);if(c)if(c.type===i){const[e,...a]=c.sequenceLines,o=a.join("")+n;c.sequenceLines=[e,...t.splitStringIntoChunks(o,Gn)],c.locs.push({min:l.min,max:l.max})}else{const e=o.reduce(((e,t)=>e+t.sequenceLines.reduce(((e,t)=>e+t.length),0)),0),a=Gn-e%Gn,r=n.slice(0,a),s=t.splitStringIntoChunks(n.slice(a),Gn);o.push({type:i,sequenceLines:[r,...s],locs:[{min:l.min,max:l.max}]})}else{const e=t.splitStringIntoChunks(n,Gn);o.push({type:i,sequenceLines:e,locs:[{min:l.min,max:l.max}]})}}return o}case"CDS":{let e="";const[n]=l,i=[];for(const t of n)e+=a(t.min,t.max),i.push({min:t.min,max:t.max});-1===s&&(e=r.revcom(e));const c=t.splitStringIntoChunks(e,Gn);return o.push({type:"CDS",sequenceLines:c,locs:i}),o}case"protein":{let e="";const[n]=l,i=[];for(const t of n)e+=a(t.min,t.max),i.push({min:t.min,max:t.max});-1===s&&(e=r.revcom(e));let c="";for(let t=0;t<e.length;t+=3){const n=e.slice(t,t+3).toUpperCase();c+=r.defaultCodonTable[n]||"&"}const u=t.splitStringIntoChunks(c,Gn);return o.push({type:"protein",sequenceLines:u,locs:i}),o}}}function Wn(e){switch(e){case"upOrDownstream":return"rgb(255,255,255)";case"exon":case"UTR":return"rgb(194,106,119)";case"CDS":return"rgb(93,168,153)";case"intron":return"rgb(187,187,187)";case"protein":return"rgb(148,203,236)"}}function Hn(e){const t=[],n=e.flatMap((e=>e.locs));let[a]=n;for(let e=1;e<n.length;e++)a.min===n[e].max||a.max===n[e].min?a={min:Math.min(a.min,n[e].min),max:Math.max(a.max,n[e].max)}:(t.push(a),a=n[e]);return t.push(a),t}const zn=E.observer((function({assembly:e,feature:t,refName:n,session:a}){const o=a.apolloDataStore.assemblies.get(e),r=o?.getByRefName(n),{featureTypeOntology:l}=a.apolloDataStore.ontologyManager,s="genomic",i=["genomic","cDNA"],[c,u]=y.useState(i),[d,f]=y.useState(s),[m,g]=y.useState((()=>r?jn(s,t,((e,t)=>r.getSequence(e,t))):[])),[h,b]=y.useState((()=>Hn(m))),S=p.useTheme(),w=y.useRef(null);if(y.useEffect((()=>{const{cdsLocations:e}=t,[n]=e;u(n.length>0?[...i,"CDS","protein"]:i)}),[t]),!o||!r)return null;const E=o.getByRefName(n);if(!E)return null;if(!l)throw new Error("featureTypeOntology is undefined");return l.isTypeOf(t.type,"transcript")?de.default.createElement(de.default.Fragment,null,de.default.createElement(p.Select,{defaultValue:"genomic",value:d,onChange:function(e){const n=e.target.value;f(n);const a=r?jn(n,t,((e,t)=>r.getSequence(e,t))):[],o=Hn(a);g(a),b(o)},size:"small"},c.map((e=>de.default.createElement(p.MenuItem,{key:e,value:e},e)))),de.default.createElement(p.Button,{variant:"contained",onClick:()=>{const e=w.current;e&&$n(e)},style:{marginLeft:10},size:"medium"},"Copy sequence"),de.default.createElement(p.Paper,{style:{fontFamily:"monospace",padding:S.spacing(),overflowX:"auto"},ref:w},">",E.name,":",h.map((e=>1===t.strand?`${e.min+1}-${e.max}`:`${e.max}-${e.min+1}`)).join(";"),"(",1===t.strand?"+":"-",")",de.default.createElement("br",null),m.map(((e,t)=>de.default.createElement("span",{key:`${e.type}-${t}`,style:{background:Wn(e.type),color:S.palette.getContrastText(Wn(e.type))}},e.sequenceLines.map(((t,n)=>de.default.createElement(de.default.Fragment,{key:`${t.slice(0,5)}-${n}`},t,n===e.sequenceLines.length-1&&t.length!==Gn?null:de.default.createElement("br",null))))))))):null})),Jn=Fe.default(Rn)((()=>({"&.MuiFormControl-root":{marginTop:0,marginBottom:0,width:"100%"},"& .MuiInputBase-input":{fontSize:12,height:20,padding:1,paddingLeft:10}}))),Vn=Fe.default("div")({display:"flex",justifyContent:"center",alignItems:"center",textAlign:"left",width:"100%",overflowWrap:"break-word",wordWrap:"break-word",wordBreak:"break-all","& span":{fontSize:12}}),Xn=e=>{const{strand:t}=e;return de.default.createElement("div",null,1===t?de.default.createElement(oe.default,null):-1===t?de.default.createElement(Ne.default,null):de.default.createElement(p.Typography,{component:"span"},"N/A"))},Kn=E.observer((function({assembly:e,feature:n,refName:a,session:o}){const{notify:l}=o,s=o.apolloDataStore.assemblies.get(e),i=s?.getByRefName(a),{changeManager:c}=o.apolloDataStore,u=y.useRef(null);if(!i)return null;const{apolloDataStore:d}=o,{featureTypeOntology:f}=d.ontologyManager;if(!f.isTypeOf(n.type,"transcript")&&!f.isTypeOf(n.type,"pseudogenic_transcript"))throw new Error("Feature is not a transcript or equivalent");const{cdsLocations:m,transcriptExonParts:g,strand:h}=n,[b]=m,[S,w]=((e,t)=>{const{transcriptExonParts:n}=e,a=n.filter((e=>t.isTypeOf(e.type,"exon"))).sort((({min:e},{min:t})=>e-t)),o=a[0]?.min,r=a[a.length-1]?.max;return[o,r]})(n,f);let E=S,v=w;const C=b.length>0;if(C){const e=b.toSorted((({min:e},{min:t})=>e-t));E=e[0].min,v=e[e.length-1].max}function x(n,a,o,r){if(!o.children)throw new Error("Transcript should have child features");const s=M(o,f,n,r);if(!s)return void l("No matching exon found","error");const i=r?s.min:s.max,{prevExon:u,nextExon:d}=L(o,f,i,r);if(r&&a>=s.max)return void l("Start location should be less than overlapping exon end location","error");if(!r&&a<=s.min)return void l("End location should be greater than overlapping exon start location","error");if(u&&u.max+2>a)return void l("Start location should be greater than previous exon end location","error");if(d&&d.min-2<a)return void l("End location should be less than next exon start location","error");const m=k(o,f,n,r);if(!m)return void l("No matching CDS feature found","error");if(!r&&a<=m.min)return void l("End location should be greater than CDS start location","error");if(r&&a>=m.max)return void l("Start location should be less than CDS end location","error");const g=I(o,s.min,s.max,f);if(g){if(r&&a!==m.min){const n=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[],changes:[],assembly:e});if(a<s.min)if(u)D(g,n,a),D(m,n,a);else{const e=o.parent;a<o.min&&(e&&a<e.min&&D(e,n,a),D(o,n,a),D(g,n,a),D(m,n,a))}else D(m,n,a);c.submit(n).catch((()=>{l("Error updating feature CDS start position","error")}))}if(!r&&a!==m.max){const n=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[],changes:[],assembly:e});if(a>s.max)if(d)F(g,n,a),F(m,n,a);else{const e=o.parent;a>o.max&&(e&&a>e.max&&F(e,n,a),F(o,n,a),F(g,n,a),F(m,n,a))}else F(m,n,a);c.submit(n).catch((()=>{l("Error updating feature CDS end position","error")}))}}else l("No matching exon feature found","error")}const T=(n,a,o,r,s)=>{if(!o.children)throw new Error("Transcript should have child features");if(n===a)return;const i=k(o,f,n,r);if(!i)return void l("No matching CDS feature found","error");const u=r?new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[i._id],featureId:i._id,oldStart:i.min,newStart:a,assembly:e}):new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[i._id],featureId:i._id,oldEnd:i.max,newEnd:a,assembly:e});c.submit(u).then((()=>{s&&s()})).catch((()=>{l("Error updating feature CDS position","error")}))};function A(n,a,o,r){if(!o.children)throw new Error("Transcript should have child features");const{matchingExon:s,prevExon:i,nextExon:u}=L(o,f,n,r);if(!s)return void l("No matching exon found","error");if(r&&a>=s.max)return void l("Start location should be less than end location","error");if(!r&&a<=s.min)return void l("End location should be greater than start location","error");if(i&&i.max+2>a)return void l("Error while changing start location","error");if(u&&u.min-2<a)return void l("Error while changing end location","error");const d=I(o,s.min,s.max,f);if(!d)return void l("No matching exon feature found","error");const m=N(o,f);if(r&&a!==s.min){const n=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[],changes:[],assembly:e});if(i)D(d,n,a);else{const e=o.min,t=o.parent;if(a<e)t&&a<t.min&&D(t,n,a),D(o,n,a),D(d,n,a);else if(a>e&&(D(d,n,a),D(o,n,a),t)){const[e]=R(t,o,a,f,r);t.min!=e&&D(t,n,e)}}m&&m.min>=s.min&&m.min<=s.max&&a>m.min&&D(m,n,a),c.submit(n).catch((()=>{l("Error updating feature exon start position","error")}))}if(!r&&a!==s.max){const n=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[],changes:[],assembly:e});if(u)F(d,n,a);else{const e=o.max,t=o.parent;if(a>e)t&&a>t.max&&F(t,n,a),F(o,n,a),F(d,n,a);else if(a<e&&(F(d,n,a),F(o,n,a),t)){const[,e]=R(t,o,a,f,r);t.max!=e&&F(t,n,e)}}m&&m.max>=s.min&&m.max<=s.max&&a<m.max&&F(m,n,a),c.submit(n).catch((()=>{l("Error updating feature exon end position","error")}))}}const F=(e,t,n)=>{t.changedIds.push(e._id),t.changes.push({featureId:e._id,oldEnd:e.max,newEnd:n})},D=(e,t,n)=>{t.changedIds.push(e._id),t.changes.push({featureId:e._id,oldStart:e.min,newStart:n})},k=(e,t,n,a)=>{let o;for(const[,r]of e.children??[])if(t.isTypeOf(r.type,"CDS")){if(a&&n===r.min){o=r;break}if(!a&&n===r.max){o=r;break}}return o},N=(e,t)=>{let n;for(const[,a]of e.children??[])if(t.isTypeOf(a.type,"CDS")){n=a;break}return n},I=(e,t,n,a)=>{let o;for(const[,r]of e.children??[])if(a.isTypeOf(r.type,"exon")&&t===r.min&&n===r.max){o=r;break}return o},R=(e,t,n,a,o)=>{const r=[],l=[];for(const[,s]of e.children?.entries()??[])a.isTypeOf(s.type,"transcript")&&(s._id===t._id?o?(r.push(n),l.push(s.max)):(l.push(n),r.push(s.min)):(r.push(s.min),l.push(s.max)));return[Math.min(...r),Math.max(...l)]},M=(e,t,n,a)=>{const{transcriptExonParts:o}=e;let r;for(const[,e]of o.entries())if(t.isTypeOf(e.type,"exon")){if(!a&&n>=e.min&&n<=e.max){r=e;break}if(a&&n>=e.min&&n<=e.max){r=e;break}}return r},L=(e,t,n,a)=>{const{transcriptExonParts:o,strand:r}=e;let l,s,i,c;for(const[e,r]of o.entries())if(t.isTypeOf(r.type,"exon")){if(a&&r.min===n){l=r,s=e;break}if(!a&&r.max===n){l=r,s=e;break}}if(l&&void 0!==s){if(1===r&&s>0)for(let e=s-1;e>=0;e--){const n=o[e];if(t.isTypeOf(n.type,"exon")){i=n;break}}if(-1===r&&s<o.length-1)for(let e=s+1;e<o.length;e++){const n=o[e];if(t.isTypeOf(n.type,"exon")){i=n;break}}if(1===r&&s<o.length-1)for(let e=s+1;e<o.length;e++){const n=o[e];if(t.isTypeOf(n.type,"exon")){c=n;break}}if(-1===r&&s>0)for(let e=s-1;e>=0;e--){const n=o[e];if(t.isTypeOf(n.type,"exon")){c=n;break}}}return{matchingExon:l,prevExon:i,nextExon:c}},P=()=>{let e="";const[t]=m,a=t.toSorted((({min:e},{min:t})=>e-t));for(const t of a)e+=i.getSequence(t.min,t.max);-1===h&&(e=r.revcom(e));const o=[];for(let t=0;t<e.length;t+=3){const a=e.slice(t,t+3).toUpperCase(),l=r.defaultCodonTable[a]||"&";"ATG"===a?o.push(de.default.createElement(p.Typography,{component:"span",style:{backgroundColor:"yellow",cursor:"pointer",border:"1px solid black"},key:t,onClick:()=>{const e=q(t);e!==E&&1===h&&T(E,e,n,!0),e!==v&&-1===h&&T(v,e,n,!1)}},l)):["TAA","TAG","TGA"].includes(a)?o.push(de.default.createElement(p.Typography,{style:{backgroundColor:"red",color:"white"},component:"span",key:t},l)):o.push(de.default.createElement(p.Typography,{component:"span",key:t},l))}return o},q=e=>{const[t]=m;let n=0;const a=t.toSorted((({min:e},{min:t})=>e-t));if(1===h)for(const t of a){const a=t.max-t.min;if(n+a>e)return t.min+(e-n);n+=a}else if(-1===h)for(let t=a.length-1;t>=0;t--){const o=a[t],r=o.max-o.min;if(n+r>e)return o.max-(e-n);n+=r}return 1===h?E:v};return de.default.createElement("div",null,C&&de.default.createElement("div",null,de.default.createElement(p.Accordion,null,de.default.createElement(ea,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel1-content",id:"panel1-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Translation")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(Vn,null,de.default.createElement(p.Typography,{component:"span",ref:u,style:{maxHeight:120,overflowY:"scroll"}},P())),de.default.createElement("div",{style:{marginTop:10,display:"flex",flexDirection:"row",alignItems:"center",gap:10}},de.default.createElement(p.Tooltip,{title:"Copy"},de.default.createElement(De.default,{style:{fontSize:15,cursor:"pointer"},onClick:()=>{const e=u.current;e&&$n(e)}})),de.default.createElement(p.Tooltip,{title:"Trim"},de.default.createElement(ke.default,{style:{fontSize:15,cursor:"pointer"},onClick:()=>{const e=P(),t=e.map((e=>e.props.children)).join("");if(t.startsWith("M")&&t.endsWith("*"))return;const a=[];for(const t of e)a.push({codonGenomicPos:t.key,sequenceLetter:t.props.children});if(0===a.length)return;const o=t.indexOf("M"),r=t.indexOf("*")+1,s=a[o].codonGenomicPos,i=a[r].codonGenomicPos;if(!s||!i)return;const c=q(s),u=q(i);if(1===h){if(c>u)return void l("Start codon genomic location should be less than stop codon genomic location","error");let e;c!==E&&(e=new Promise((e=>{T(E,c,n,!0,(()=>{e(!0)}))}))),u!==v&&(e?e.then((()=>{T(v,u,n,!1)})):T(v,u,n,!1))}if(-1===h){if(c<u)return void l("Start codon genomic location should be less than stop codon genomic location","error");let e;c!==v&&(e=new Promise((e=>{T(v,c,n,!1,(()=>{e(!0)}))}))),u!==E&&(e?e.then((()=>{T(E,u,n,!0)})):T(E,u,n,!0))}l("Translation sequence trimmed to start and stop codons","success")}}))))),de.default.createElement(p.Grid2,{container:!0,justifyContent:"center",alignItems:"center",style:{textAlign:"center",marginTop:10}},de.default.createElement(p.Grid2,{size:1}),de.default.createElement(p.Grid2,{size:4},de.default.createElement(Jn,1===h?{margin:"dense",variant:"outlined",value:E+1,onChangeCommitted:e=>{x(E,e-1,n,!0)},style:{border:"1px solid black",borderRadius:5}}:{margin:"dense",variant:"outlined",value:v,onChangeCommitted:e=>{x(v,e,n,!1)},style:{border:"1px solid black",borderRadius:5}})),de.default.createElement(p.Grid2,{size:2},de.default.createElement(p.Typography,{component:"span"},"CDS")),de.default.createElement(p.Grid2,{size:4},de.default.createElement(Jn,1===h?{margin:"dense",variant:"outlined",value:v,onChangeCommitted:e=>{x(v,e,n,!1)},style:{border:"1px solid black",borderRadius:5}}:{margin:"dense",variant:"outlined",value:E+1,onChangeCommitted:e=>{x(E,e-1,n,!0)},style:{border:"1px solid black",borderRadius:5}})),de.default.createElement(p.Grid2,{size:1}))),de.default.createElement("div",{style:{marginTop:5}},g.map(((e,t)=>de.default.createElement("div",{key:t},"exon"===e.type&&de.default.createElement(p.Grid2,{container:!0,justifyContent:"center",alignItems:"center",style:{textAlign:"center"}},de.default.createElement(p.Grid2,{size:1},0!==t&&((e,t)=>{let n="";if(t>0){const a=g[t-1];1===h?"intron"===a.type&&(n=i.getSequence(e.min-2,e.min)):"intron"===a.type&&(n=r.revcom(i.getSequence(e.max,e.max+2)))}return[{spliceSite:n,color:"AG"===n?"green":"red"}]})(e,t).map(((e,t)=>de.default.createElement(p.Typography,{key:t,component:"span",color:e.color},e.spliceSite)))),de.default.createElement(p.Grid2,{size:4,style:{padding:0}},de.default.createElement(Jn,1===h?{margin:"dense",variant:"outlined",value:e.min+1,onChangeCommitted:t=>{A(e.min,t-1,n,!0)}}:{margin:"dense",variant:"outlined",value:e.max,onChangeCommitted:t=>{A(e.max,t,n,!1)}})),de.default.createElement(p.Grid2,{size:2},de.default.createElement(Xn,{strand:n.strand})),de.default.createElement(p.Grid2,{size:4,style:{padding:0}},de.default.createElement(Jn,1===h?{margin:"dense",variant:"outlined",value:e.max,onChangeCommitted:t=>{A(e.max,t,n,!1)}}:{margin:"dense",variant:"outlined",value:e.min+1,onChangeCommitted:t=>{A(e.min,t-1,n,!0)}})),de.default.createElement(p.Grid2,{size:1},t!==g.length-1&&((e,t)=>{let n="";if(t<g.length-1){const a=g[t+1];1===h?"intron"===a.type&&(n=i.getSequence(e.max,e.max+2)):"intron"===a.type&&(n=r.revcom(i.getSequence(e.min-2,e.min)))}return[{spliceSite:n,color:"GT"===n?"green":"red"}]})(e,t).map(((e,t)=>de.default.createElement(p.Typography,{key:t,component:"span",color:e.color},e.spliceSite))))))))))})),Yn=Fe.default(p.TableCell)((()=>({fontWeight:"bold"}))),Zn=E.observer((function(e){const{feature:t}=e,n=Be(t),a=Ue(t);return de.default.createElement(p.Table,{size:"small",sx:{fontSize:"0.75rem","& .MuiTableCell-root":{padding:"4px"}}},de.default.createElement(p.TableBody,null,""!==n&&de.default.createElement(p.TableRow,null,de.default.createElement(Yn,null,"Name"),de.default.createElement(p.TableCell,null,Be(t))),""!==a&&de.default.createElement(p.TableRow,null,de.default.createElement(Yn,null,"ID"),de.default.createElement(p.TableCell,null,Ue(t))),de.default.createElement(p.TableRow,null,de.default.createElement(Yn,null,"Type"),de.default.createElement(p.TableCell,null,t.type)),de.default.createElement(p.TableRow,null,de.default.createElement(Yn,null,"Location"),de.default.createElement(p.TableCell,null,e.refName,":",t.min,"..",t.max)),de.default.createElement(p.TableRow,null,de.default.createElement(Yn,null,"Strand"),de.default.createElement(p.TableCell,null,1===(o=t.strand)?"Forward":-1===o?"Reverse":""))));var o})),Qn=b.makeStyles()((e=>({root:{padding:e.spacing(2)}}))),ea=Fe.default(p.AccordionSummary)((()=>({minHeight:30,maxHeight:30,"&.Mui-expanded":{minHeight:30,maxHeight:30}})));function ta(e){return null}const na=E.observer((function(e){const{classes:t}=Qn(),n=["summary","location","attrs"],[a,o]=y.useState(n),{model:l}=e,{assembly:s,feature:c,refName:u}=l;y.useEffect((()=>{o(n)}),[c]);const d=r.getSession(l),{pluginManager:f}=r.getEnv(d),m=r.getSession(l),g=m.apolloDataStore.assemblies.get(s),{internetAccounts:h}=i.getRoot(d),b=h.find((e=>"ApolloInternetAccount"===e.type)),S=["admin","user"].includes((b?b.role:"admin")??"");if(!c||!g)return null;const w=g.getByRefName(u);if(!w)return null;const{max:E,min:v}=c;function C(e,t){o(e?[...a,t]:a.filter((e=>e!==t)))}w.getSequence(v,E)||m.apolloDataStore.loadRefSeq([{assemblyName:s,refName:u,start:v,end:E}]);const x=f.evaluateExtensionPoint("Apollo-TranscriptDetailsCustomComponent",ta,e);return de.default.createElement("div",{className:t.root},de.default.createElement(p.Accordion,{expanded:a.includes("summary"),onChange:(e,t)=>{C(t,"summary")}},de.default.createElement(ea,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel1-content",id:"panel1-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Summary")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(Zn,{feature:c,refName:u}))),de.default.createElement(x,{session:d,feature:c}),de.default.createElement(p.Accordion,{style:{marginTop:5},expanded:a.includes("location"),onChange:(e,t)=>{C(t,"location")}},de.default.createElement(ea,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel2-content",id:"panel2-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Location")),de.default.createElement(p.AccordionDetails,null,de.default.createElement(Kn,{feature:c,refName:u,session:m,assembly:g._id||""}))),de.default.createElement(p.Accordion,{style:{marginTop:5},expanded:a.includes("attrs"),onChange:(e,t)=>{C(t,"attrs")}},de.default.createElement(ea,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel3-content",id:"panel3-header"},de.default.createElement("div",{style:{display:"flex",alignItems:"center"}},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Attributes"," "),de.default.createElement(p.Tooltip,{title:"Separate multiple values for the attribute with commas"},de.default.createElement(le.default,{style:{color:"white",fontSize:15,marginLeft:10}})))),de.default.createElement(p.AccordionDetails,null,de.default.createElement(In,{feature:c,session:m,assembly:g._id||"",editable:S}))),de.default.createElement(p.Accordion,{style:{marginTop:5},expanded:a.includes("sequence"),onChange:(e,t)=>{C(t,"sequence")}},de.default.createElement(ea,{expandIcon:de.default.createElement(Ce.default,{style:{color:"white"}}),"aria-controls":"panel4-content",id:"panel4-header"},de.default.createElement(p.Typography,{component:"span",fontWeight:"bold"},"Sequence")),de.default.createElement(p.AccordionDetails,null,a.includes("sequence")&&de.default.createElement(zn,{feature:c,session:m,assembly:g._id||"",refName:u}))))})),aa=a.ConfigurationSchema("LinearApolloDisplay",{},{explicitIdentifier:"displayId",explicitlyTyped:!0}),oa=b.makeStyles()({highlighted:{background:"orange"}}),ra=({highlight:e,text:t})=>{const{classes:n}=oa();if(!e)return de.default.createElement(de.default.Fragment,null,t);const a=t.split(e);if(1===a.length)return de.default.createElement(de.default.Fragment,null,t);const o=[];for(let t=0;t<a.length-1;t++)o.push(a[t],de.default.createElement("span",{className:n.highlighted},e));return de.default.createElement(de.default.Fragment,null,o,a.at(-1))},la=E.observer((function({feature:e,filterText:t}){const n=[...e.attributes.entries()].map((([e,t])=>{if(e.startsWith("gff_")){const n=e.slice(4);return[n.charAt(0).toUpperCase()+n.slice(1),i.getSnapshot(t)]}return"_id"===e?["ID",i.getSnapshot(t)]:[e,i.getSnapshot(t)]})).filter((([e])=>e)).map((([e,t])=>`${e}=${Array.isArray(t)?t.join(", "):t}`)).join(", ");return de.default.createElement(ra,{text:n,highlight:t})})),sa=b.makeStyles()((e=>({inputWrapper:{position:"relative"},hiddenWidthSpan:{padding:e.spacing(.5),color:"transparent"},numberTextInput:{border:"none",background:"inherit",font:"inherit",position:"absolute",width:"100%",left:0}}))),ia=E.observer((function({initialValue:e,notifyError:t,onChangeCommitted:n}){const[a,o]=y.useState(e),[r,l]=y.useState(!1),[s,i]=y.useState(null),{classes:c}=sa();return y.useEffect((()=>{e!==a&&o(e)}),[e]),y.useEffect((()=>{r&&(s?.blur(),l(!1))}),[r,s]),de.default.createElement("span",{className:c.inputWrapper},de.default.createElement("span",{className:c.hiddenWidthSpan,"aria-hidden":!0},a),de.default.createElement("input",{type:"text",value:a,className:c.numberTextInput,onChange:function(e){const t=Number(e.target.value);Number.isNaN(t)||o(t)},onKeyDown:t=>{"Enter"===t.key?s?.blur():"Escape"===t.key&&(o(e),l(!0))},onBlur:()=>{a!==e&&n(a).catch(t)},ref:e=>{i(e)}}))})),ca=b.makeStyles()((e=>({typeContent:{display:"inline-block",width:"174px",height:"100%",cursor:"text"},feature:{td:{position:"relative",verticalAlign:"top",paddingLeft:"0.5em"}},arrow:{display:"inline-block",width:"1.6em",textAlign:"center",cursor:"pointer"},arrowExpanded:{transform:"rotate(90deg)"},hoveredFeature:{backgroundColor:e.palette.action.hover},typeInputElement:{border:"none",background:"none"},typeErrorMessage:{color:"red"}})));function ua(e,t){const{changeManager:n,getAssemblyId:a,regions:o,selectedFeature:l,session:s,setSelectedFeature:c,filteredTranscripts:u,updateFilteredTranscripts:d}=e;return function(e,t,n,a,o,l,s,c,u){const d=function(e){const{internetAccounts:t}=i.getParent(e);return t.find((e=>"ApolloInternetAccount"===e.type))}(l),f=d?d.role:"admin",m="admin"===f,g=!(f&&["admin","user"].includes(f)),p=[];if(e){const i=e.attributes.get("gff_id")?.toString(),f=n(t.assemblyName),h=n(t.assemblyName);p.push({label:"Edit feature details",onClick:()=>{const n=l.addWidget("ApolloFeatureDetailsWidget","apolloFeatureDetailsWidget",{feature:e,assembly:h,refName:t.refName});l.showWidget(n)}},{label:"Add child feature",disabled:g,onClick:()=>{l.queueDialog((t=>[Dt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:f,internetAccount:d}]))}},{label:"Copy features and annotations",disabled:g,onClick:()=>{l.queueDialog((t=>[Mt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:h}]))}},{label:"Delete feature",disabled:!m,onClick:()=>{l.queueDialog((t=>[Pt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:h,selectedFeature:a,setSelectedFeature:o}]))}},{label:"Merge transcripts",disabled:!m,onClick:()=>{l.queueDialog((t=>[Wt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:h,selectedFeature:a,setSelectedFeature:o}]))}},{label:"Merge exons",disabled:!m,onClick:()=>{l.queueDialog((t=>[Gt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:h,selectedFeature:a,setSelectedFeature:o}]))}},{label:"Split exon",disabled:!m,onClick:()=>{l.queueDialog((t=>[Qt,{session:l,handleClose:()=>{t()},changeManager:s,sourceFeature:e,sourceAssemblyId:h,selectedFeature:a,setSelectedFeature:o}]))}});const{featureTypeOntology:y}=l.apolloDataStore.ontologyManager;if(!y)throw new Error("featureTypeOntology is undefined");(y.isTypeOf(e.type,"transcript")||y.isTypeOf(e.type,"pseudogenic_transcript"))&&r.isSessionModelWithWidgets(l)&&p.push({label:"Edit transcript details",onClick:()=>{const n=l.addWidget("ApolloTranscriptDetails","apolloTranscriptDetails",{feature:e,assembly:h,changeManager:s,refName:t.refName});l.showWidget(n)}},{label:"Visible",type:"checkbox",checked:!i||!c.includes(i),onClick:()=>{if(i){const e=c.includes(i)?c.filter((e=>e!==i)):[...c,i];u(e)}}})}return p}(t,o[0],a,l,c,s,n,u,d)}function da(e){let t=e;for(;t.parent;)t=t.parent;return t}const fa=E.observer((function e({depth:n,feature:a,isHovered:o,isSelected:r,model:l,selectedFeatureClass:s,setContextMenu:i}){const{classes:c}=ca(),{apolloHover:u,changeManager:d,selectedFeature:f,session:m,tabularEditor:g}=l,{featureCollapsed:p,filterText:h}=g,{_id:y,children:b,max:S,min:w,strand:E,type:v}=a,C=!p.get(y),x=e=>{m.notify(e.message,"error")};return de.default.createElement(de.default.Fragment,null,de.default.createElement("tr",{onMouseEnter:e=>{l.setApolloHover({feature:a,topLevelFeature:da(a),glyph:l.getGlyph(da(a))})},className:c.feature+(r?` ${s}`:o?` ${c.hoveredFeature}`:""),onClick:e=>{e.stopPropagation(),l.setSelectedFeature(a)},onContextMenu:e=>(e.preventDefault(),i({position:{left:e.clientX+2,top:e.clientY-6},items:ua(l,a)}),!1)},de.default.createElement("td",{style:{whiteSpace:"nowrap",borderLeft:2*n+"em solid transparent"}},b?.size?de.default.createElement("div",{onClick:e=>{e.stopPropagation(),g.setFeatureCollapsed(y,C)},className:c.arrow+(C?` ${c.arrowExpanded}`:"")},"❯"):null,de.default.createElement("div",{className:c.typeContent},de.default.createElement(Ft,{session:m,ontologyName:"Sequence Ontology",style:{width:170},value:v,filterTerms:xt,fetchValidTerms:ma.bind(null,a),renderInput:e=>de.default.createElement("div",{ref:e.InputProps.ref},de.default.createElement("input",{type:"text",...e.inputProps,className:c.typeInputElement,style:{width:170}}),e.error?de.default.createElement("div",{className:c.typeErrorMessage},e.errorMessage??"unknown error"):null),onChange:(e,n)=>{n&&function(e,n,a,o){const r=n._id,l=new t.TypeChange({typeName:"TypeChange",changedIds:[r],featureId:r,oldType:String(a),newType:String(o),assembly:n.assemblyId});return e.submit(l)}(d,a,e,n).catch(x)}}))),de.default.createElement("td",null,de.default.createElement(ia,{initialValue:w+1,notifyError:x,onChangeCommitted:e=>function(e,n,a,o){const r=n._id,l=new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[r],featureId:r,oldStart:a,newStart:o,assembly:n.assemblyId});return e.submit(l)}(d,a,w,e-1)})),de.default.createElement("td",null,de.default.createElement(ia,{initialValue:S,notifyError:x,onChangeCommitted:e=>function(e,n,a,o){const r=n._id,l=new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[r],featureId:r,oldEnd:a,newEnd:o,assembly:n.assemblyId});return e.submit(l)}(d,a,S,e)})),de.default.createElement("td",null,1===E?"+":-1===E?"-":void 0),de.default.createElement("td",null,de.default.createElement(la,{filterText:h,feature:a}))),C&&b?[...b.entries()].filter((e=>{if(!h)return!0;const[,t]=e;return JSON.stringify(t).includes(h)})).map((([t,a])=>de.default.createElement(e,{isHovered:u?.feature._id===a._id,isSelected:f?._id===a._id,selectedFeatureClass:s,key:t,depth:(n||0)+1,feature:a,model:l,setContextMenu:i}))):null)}));async function ma(e,t,n){const{parent:a}=e;if(a){const e=(await t.getTermsWithLabelOrSynonym(a.type,{includeSubclasses:!1})).filter(xt);if(e.length>0)return await t.getClassesThat("part_of",e)}}const ga=b.makeStyles()((e=>({scrollableTable:{width:"100%",height:"100%",th:{position:"sticky",top:0,zIndex:2,textAlign:"left",background:e.palette.background.paper,paddingTop:"3.2em"},td:{whiteSpace:"normal"}},selectedFeature:{backgroundColor:e.palette.action.selected}}))),pa=E.observer((function({model:e}){const{apolloHover:t,seenFeatures:n,selectedFeature:a,tabularEditor:o}=e,r=p.useTheme(),{classes:l}=ga(),s=y.useRef(null),[i,c]=y.useState(null),{filterText:u}=o;return y.useEffect((()=>{const e=s.current;if(e&&a){const t=e.querySelector(`.${l.selectedFeature}`);if(t){const n=e.scrollTop,a=t.offsetTop-25;a>n&&a<n+e.offsetHeight||e.scroll({top:a-40,behavior:"smooth"})}}}),[a,n,l.selectedFeature]),de.default.createElement("div",{ref:s,style:{width:"100%",overflowY:"auto",height:"100%"}},de.default.createElement("table",{className:l.scrollableTable},de.default.createElement("thead",null,de.default.createElement("tr",null,de.default.createElement("th",null,"Type"),de.default.createElement("th",null,"Start"),de.default.createElement("th",null,"End"),de.default.createElement("th",null,"Strand"),de.default.createElement("th",null,"Attributes"))),de.default.createElement("tbody",null,[...n.entries()].filter((e=>{if(!u)return!0;const[,t]=e;return JSON.stringify(t).includes(u)})).sort(((e,t)=>e[1].min-t[1].min)).map((([n,o])=>de.default.createElement(fa,{key:n,isSelected:a?._id===n,isHovered:t?.feature._id===n,selectedFeatureClass:l.selectedFeature,feature:o,model:e,depth:0,setContextMenu:c}))))),de.default.createElement(S.Menu,{open:Boolean(i),onMenuItemClick:(e,t)=>{t(),c(null)},onClose:()=>{c(null)},TransitionProps:{onExit:()=>{c(null)}},style:{zIndex:r.zIndex.tooltip},menuItems:i?.items??[],anchorReference:"anchorPosition",anchorPosition:i?.position}))})),ha=b.makeStyles()({toolbar:{width:"100%",display:"flex",paddingRight:"2em",flexDirection:"row",justifyContent:"space-between",position:"absolute",zIndex:4},filterText:{}}),ya=E.observer((function({model:e}){const t=e.tabularEditor,{classes:n}=ha();return de.default.createElement("div",{className:n.toolbar},de.default.createElement(p.Tooltip,{title:"Collapse all"},de.default.createElement(p.IconButton,{"aria-label":"collapse",sx:{marginTop:0},onClick:t.collapseAllFeatures},de.default.createElement(Re.default,null))),de.default.createElement(p.TextField,{className:n.filterText,label:"Filter features",value:t.filterText,sx:{marginTop:0},variant:"outlined",onChange:e=>{t.setFilterText(e.target.value)},slotProps:{input:{endAdornment:de.default.createElement(p.InputAdornment,{position:"end"},de.default.createElement(p.IconButton,{onClick:()=>{t.clearFilterText()}},de.default.createElement(Ie.default,null)))}}}))}));function ba(e){e.stopPropagation()}const Sa=E.observer((function({model:e}){return e.tabularEditor.isShown?de.default.createElement("div",{onMouseDown:ba,onClick:ba,style:{width:"100%",height:"100%",position:"relative"}},de.default.createElement(ya,{model:e}),de.default.createElement(pa,{model:e})):null})),wa=i.types.model("TabularEditor",{isShown:!0,featureCollapsed:i.types.map(i.types.boolean),filterText:""}).actions((e=>({setFeatureCollapsed(t,n){e.featureCollapsed.set(t,n)},setFilterText(t){e.filterText=t},clearFilterText(){e.filterText=""},collapseAllFeatures(){const t=i.getParent(e);for(const[n]of t.seenFeatures.entries())e.featureCollapsed.set(n,!0)},togglePane(){e.isShown=!e.isShown},hidePane(){e.isShown=!1},showPane(){e.isShown=!0}})));function Ea(e,t){return Boolean(t&&e._id===t._id)}function va(e,t){return t?e?.palette.text.primary??"black":e?.palette.background.default??"white"}function Ca(e,t,n,a,o,r){e.fillStyle=r,e.fillRect(t,n,a,o)}function xa(e){let t;t=e.attributes.get("gff_name")?e.attributes.get("gff_name")?.join(","):e.attributes.get("gff_id")?e.attributes.get("gff_id")?.join(","):e._id;const n=`(${(e.min+1).toLocaleString("en")}..${e.max.toLocaleString("en")})`;if(t&&t.length+n.length>65){const e=60-n.length;t=e>0?t.slice(0,e):"",t=`${t}[...]`}return`${t} ${n}`}function Ta(e,t){const{apolloInternetAccount:n,changeManager:a,regions:o,selectedFeature:r,session:l}=e,s=[],i=n?n.role:"admin",c="admin"===i,u=!(i&&["admin","user"].includes(i)),[d]=o,f=e.getAssemblyId(d.assemblyName),m=e.getAssemblyId(d.assemblyName),{featureTypeOntology:g}=l.apolloDataStore.ontologyManager;if(!g)throw new Error("featureTypeOntology is undefined");return s.push({label:xa(t),type:"subHeader"},{label:"Add child feature",disabled:u,onClick:()=>{l.queueDialog((e=>[Dt,{session:l,handleClose:()=>{e()},changeManager:a,sourceFeature:t,sourceAssemblyId:f,internetAccount:n}]))}},{label:"Copy features and annotations",disabled:u,onClick:()=>{l.queueDialog((e=>[Mt,{session:l,handleClose:()=>{e()},changeManager:a,sourceFeature:t,sourceAssemblyId:m}]))}},{label:"Delete feature",disabled:!c,onClick:()=>{l.queueDialog((n=>[Pt,{session:l,handleClose:()=>{n()},changeManager:a,sourceFeature:t,sourceAssemblyId:m,selectedFeature:r,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}}),s}function Aa(e,t,n){const{refName:a,regionNumber:o,x:r}=e,{lgv:l}=n,{offsetPx:s}=l,i=l.bpToPx({refName:a,coord:t.min,regionNumber:o}),c=l.bpToPx({refName:a,coord:t.max,regionNumber:o});if(void 0!==i&&void 0!==c){const e=i.offsetPx-s,t=c.offsetPx-s;if(Math.abs(t-e)<8)return;if(Math.abs(e-r)<4)return"min";if(Math.abs(t-r)<4)return"max"}}const Fa={draw:function(e,t,n,a,o){const{apolloRowHeight:r,lgv:l,session:s,theme:i}=a,{bpPerPx:c,displayedRegions:u,offsetPx:d}=l,f=u[o],m=(l.bpToPx({refName:f.refName,coord:t.min,regionNumber:o})?.offsetPx??0)-d,{reversed:g}=f,{apolloSelectedFeature:p}=s,h=t.length/c,y=g?m-h:m,b=n*r,S=Ea(t,p),w=va(i,S),E=function(e,t){return t?e?.palette.getContrastText(va(e,t))??"white":e?.palette.text.primary??"black"}(i,S);!function(e,t,n,a,o,r){Ca(e,t,n,a,o,r),a<=2||e.clearRect(t+1,n+1,a-2,o-2)}(e,y,b,h,r,E),h<=2||(function(e,t,n,a,o,r){Ca(e,t+1,n+1,a-2,o-2,r)}(e,y,b,h,r,w),function(e,t,n,a,o,r){e.fillStyle=o;const l=Math.max(t+1,0);e.fillText(r,l,n+11,t-1+a-l)}(e,y,b,h,E,t.type))},drawDragPreview:function(e,t){const{apolloDragging:n,apolloRowHeight:a,lgv:o,theme:r}=e,{bpPerPx:l,displayedRegions:s,offsetPx:i}=o;if(!n)return;const{current:c,edge:u,feature:d,start:f}=n,m=Math.floor(f.y/a),g=s[f.regionNumber],h=(g.reversed?g.end-d[u]:d[u]-g.start)/l-i,y=Math.min(c.x,h),b=m*a,S=Math.abs(c.x-h),w=1*a;t.strokeStyle=r?.palette.info.main??"rgb(255,0,0)",t.setLineDash([6]),t.strokeRect(y,b,S,w),t.fillStyle=p.alpha(r?.palette.info.main??"rgb(255,0,0)",.2),t.fillRect(y,b,S,w)},drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,theme:r}=e;if(!n)return;const{feature:l}=n,s=e.getFeatureLayoutPosition(l);if(!s)return;const{bpPerPx:i,displayedRegions:c,offsetPx:u}=o,{layoutIndex:d,layoutRow:f}=s,m=c[d],{refName:g,reversed:p}=m,{length:h,max:y,min:b}=l,S=(o.bpToPx({refName:g,coord:p?y:b,regionNumber:d})?.offsetPx??0)-u,w=f*a,E=h/i;t.fillStyle=r?.palette.action.focus??"rgba(0,0,0,0.04)",t.fillRect(S,w,E,a)},drawTooltip:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,theme:r}=e;if(!n)return;const{feature:l}=n,s=e.getFeatureLayoutPosition(l);if(!s)return;const{featureRow:i,layoutIndex:c,layoutRow:u}=s,{bpPerPx:d,displayedRegions:f,offsetPx:m}=o,g=f[c],{refName:h,reversed:y}=g;let b="Loc: ";const{length:S,max:w,min:E}=l;b+=`${E+1}–${w}`;let v=(o.bpToPx({refName:h,coord:y?w:E,regionNumber:c})?.offsetPx??0)-m;const C=(u+i)*a,x=S/d,T=`Type: ${l.type}`,{attributes:A}=l,F=A.get("gff_name")?.find((e=>""!==e)),D=[t.measureText(T).width,t.measureText(b).width];F&&D.push(t.measureText(`Name: ${F}`).width);const k=Math.max(...D);v=v+x+5,t.fillStyle=p.alpha(r?.palette.text.primary??"rgb(1, 1, 1)",.7),t.fillRect(v,C,k+4,3===D.length?45:35),t.beginPath(),t.moveTo(v,C),t.lineTo(v-5,C+5),t.lineTo(v,C+10),t.fill(),t.fillStyle=r?.palette.background.default??"rgba(255, 255, 255)";let N=C+12;t.fillText(T,v+2,N),F&&(N+=12,t.fillText(`Name: ${F}`,v+2,N)),N+=12,t.fillText(b,v+2,N)},getContextMenuItemsForFeature:Ta,getContextMenuItems:function(e){const{apolloHover:t}=e;if(!t)return[];const{feature:n}=t;return Ta(e,n)},getFeatureFromLayout:function(e,t,n){return e},getRowCount:function(e){return 1},getRowForFeature:function(e,t){return 0},onMouseDown:function(e,t,n){const{featureAndGlyphUnderMouse:a}=t,{feature:o}=a,r=Aa(t,o,e);r&&(n.stopPropagation(),e.startDrag(t,o,r))},onMouseLeave:function(){},onMouseMove:function(e,t){if(co(t)){const{featureAndGlyphUnderMouse:n}=t;e.setApolloHover(n);const{feature:a}=n;if(Aa(t,a,e))return void e.setCursor("col-resize")}e.setCursor()},onMouseUp:function(e,t){if(e.apolloDragging)return;const{featureAndGlyphUnderMouse:n}=t;if(!n)return;const{feature:a}=n;e.setSelectedFeature(a),e.showFeatureDetailsWidget(a)}};let Da=null,ka=null,Na=null,Ia=null;const Ra=globalThis.document.createElement("canvas");if(Ra?.getContext)for(const e of["forward","backward"])for(const t of["light","dark"]){const n=document.createElement("canvas"),a=10;n.width=n.height=a;const o=n.getContext("2d");if(o){const r="light"===t?"rgba(0,0,0,0)":"rgba(0,0,0,0.75)",l="light"===t?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.50)",s="forward"===e?o.createLinearGradient(0,a,a,0):o.createLinearGradient(0,0,a,a);s.addColorStop(0,r),s.addColorStop(.25,r),s.addColorStop(.25,l),s.addColorStop(.5,l),s.addColorStop(.5,r),s.addColorStop(.75,r),s.addColorStop(.75,l),s.addColorStop(1,l),o.fillStyle=s,o.fillRect(0,0,10,10),"forward"===e?"light"===t?Da=o.createPattern(n,"repeat"):Na=o.createPattern(n,"repeat"):"light"===t?ka=o.createPattern(n,"repeat"):Ia=o.createPattern(n,"repeat")}}function Ma(e,t,n,a,o,r,l,s,i){const{apolloRowHeight:c,lgv:u,session:d,theme:f}=t,{bpPerPx:m,displayedRegions:g,offsetPx:p}=u,h=g[n],{refName:y,reversed:b}=h,{apolloSelectedFeature:S}=d,w=(u.bpToPx({refName:y,coord:o.min,regionNumber:n})?.offsetPx??0)-p,E=o.length/m,v=b?w-E:w,C=(a+r)*c,x=Math.round(.6*c),T=C+(c-x)/2;if(e.fillStyle=f?.palette.text.primary??"black",e.fillRect(v,T,E,x),E>2&&(e.clearRect(v+1,T+1,E-2,x-2),e.fillStyle=S&&o._id===S._id?"rgb(0,0,0)":"rgb(211,211,211)",e.fillRect(v+1,T+1,E-2,x-2),s&&i&&l)){const t=b?-1:1,[n,a]=l*t==1?[s,i]:[i,s];e.fillStyle=n,e.fillRect(v+1,T+1,E-2,(x-2)/2),e.fillStyle=a,e.fillRect(v+1,T+1+(x-2)/2,E-2,(x-2)/2)}}function La(e,t,n,a,o,r){const{apolloRowHeight:l,lgv:s,theme:i}=t,{bpPerPx:c,displayedRegions:u,offsetPx:d}=s,f=u[n],{refName:m,reversed:g}=f,p=(s.bpToPx({refName:m,coord:o.min,regionNumber:n})?.offsetPx??0)-d,h=o.length/c,y=g?p-h:p,b=Math.round((r+.5)*l)+a*l;e.strokeStyle=i?.palette.text.primary??"black",e.beginPath(),e.moveTo(y,b),e.lineTo(y+h,b),e.stroke()}function Pa(e,t){const{children:n,type:a}=e;if(!n)return 0;let o=0;if(t.isTypeOf(a,"transcript"))for(const[,e]of n)t.isTypeOf(e.type,"CDS")&&(o+=1);return o}function qa(e,t,n){const{children:a,type:o}=e;if(!a)return 1;let r=0;if(t.isTypeOf(o,"transcript")||t.isTypeOf(o,"pseudogenic_transcript")){for(const[,e]of a)t.isTypeOf(e.type,"CDS")&&(r+=1);return 0===r?1:r}for(const[,e]of a)r+=qa(e,t);return r}function Oa(e,t){if(!t.isTypeOf(e.type,"gene")&&!t.isTypeOf(e.type,"pseudogene"))throw new Error('Top level feature for GeneGlyph must have type "gene"');const{children:n}=e;if(!n)return[[e]];const a=[];for(const[,o]of n){if(!t.isTypeOf(o.type,"transcript")&&!t.isTypeOf(o.type,"pseudogenic_transcript")){a.push([o,e]);continue}if(!o.children)continue;const n=[],r=[];for(const[,e]of o.children)t.isTypeOf(e.type,"CDS")?n.push(e):t.isTypeOf(e.type,"exon")&&r.push(e);for(const t of n)a.push([t,...r,o,e]);0===n.length&&a.push([...r,o,e])}return a}function _a(e,t,n){const{session:a}=n,{apolloDataStore:o}=a,{featureTypeOntology:l}=o.ontologyManager;if(!l)throw new Error("featureTypeOntology is undefined");const s=l.isTypeOf(t.type,"gene")||l.isTypeOf(t.type,"pseudogene"),i=l.isTypeOf(t.type,"transcript")||l.isTypeOf(t.type,"pseudogenic_transcript"),c=l.isTypeOf(t.type,"CDS");if(s||i)return;const{bp:u,refName:d,regionNumber:f,x:m}=e,{lgv:g}=n;if(c){const e=t.parent;if(!e?.children)return;const n=[];for(const t of e.children.values())l.isTypeOf(t.type,"exon")&&n.push(t);const a=n.find((e=>{const[t,n]=r.intersection2(u-1,u,e.min,e.max);return void 0!==t&&void 0!==n}));if(a){const e=je(a,d,f,g);if(e){const t=We(a,m,e);if(t)return t}}}const p=je(t,d,f,g);if(p){const e=We(t,m,p);if(e)return e}}function Ba(e,t){const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"transcript")||n.isTypeOf(e.type,"pseudogenic_transcript")}function Ua(e,t){const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"exon")}const{drawTooltip:$a,getContextMenuItemsForFeature:Ga,onMouseLeave:ja}=Fa,Wa={draw:function(e,t,n,a,o){const{apolloRowHeight:l,lgv:s,session:i,theme:c}=a,{bpPerPx:u,displayedRegions:d,offsetPx:f}=s,m=d[o],{refName:g,reversed:h}=m,y=l,b=Math.round(.9*y),{children:S,min:w,strand:E}=t;if(!S)return;const{apolloSelectedFeature:v}=i,{apolloDataStore:C}=i,{featureTypeOntology:x}=C.ontologyManager;if(!x)throw new Error("featureTypeOntology is undefined");const T=(s.bpToPx({refName:g,coord:w,regionNumber:o})?.offsetPx??0)-f,A=t.length/u,F=h?T-A:T,D=n*y,k=qa(t,x)*y;e.fillStyle=p.alpha(c?.palette.background.paper??"#ffffff",.6),e.fillRect(F,D,A,k);let N=0;for(const[,t]of S){if(!x.isTypeOf(t.type,"transcript")&&!x.isTypeOf(t.type,"pseudogenic_transcript")){N+=1;continue}const{children:r}=t;if(!r)continue;const l=Pa(t,x);for(const[,l]of r)x.isTypeOf(l.type,"CDS")&&(La(e,a,o,n,t,N),N+=1);0===l&&(La(e,a,o,n,t,N),N+=1)}const I="dark"===c?.palette.mode?Na:Da,R="dark"===c?.palette.mode?Ia:ka;N=0;for(const[,t]of S){if(!x.isTypeOf(t.type,"transcript")&&!x.isTypeOf(t.type,"pseudogenic_transcript")){Fa.draw(e,t,n,a,o),N+=1;continue}const l=Pa(t,x);if(0!=l)for(const l of t.cdsLocations){const{_id:i,children:d}=t;if(d){for(const[,t]of d)x.isTypeOf(t.type,"exon")&&Ma(e,a,o,n,t,N,E,I,R);for(const a of l){const l=(a.max-a.min)/u,d=(s.bpToPx({refName:g,coord:a.min,regionNumber:o})?.offsetPx??0)-f,m=h?d-l:d;e.fillStyle=c?.palette.text.primary??"black";const p=(n+N)*y+(y-b)/2;if(e.fillRect(m,p,l,b),l>2){e.clearRect(m+1,p+1,l-2,b-2);const n=r.getFrame(a.min,a.max,t.strand??1,a.phase),o=c?.palette.framesCDS.at(n)?.main;if(e.fillStyle=v&&i===v._id?"rgb(0,0,0)":o??"rgb(171,71,188)",e.fillRect(m+1,p+1,l-2,b-2),I&&R&&E){const t=h?-1:1,[n,a]=E*t==1?[I,R]:[R,I];e.fillStyle=n,e.fillRect(m+1,p+1,l-2,(b-2)/2),e.fillStyle=a,e.fillRect(m+1,p+(b-2)/2,l-2,(b-2)/2)}}}N+=1}}const{children:i}=t;if(0===l&&i){for(const[,t]of i)x.isTypeOf(t.type,"exon")&&Ma(e,a,o,n,t,N,E,I,R);N+=1}}},drawDragPreview:function(e,t){const{apolloDragging:n,apolloRowHeight:a,lgv:o,theme:r}=e,{bpPerPx:l,displayedRegions:s,offsetPx:i}=o;if(!n)return;const{current:c,edge:u,feature:d,start:f}=n,m=Math.floor(f.y/a),g=s[f.regionNumber],h=(g.reversed?g.end-d[u]:d[u]-g.start)/l-i,y=Math.min(c.x,h),b=m*a,S=Math.abs(c.x-h),w=1*a;t.strokeStyle=r?.palette.info.main??"rgb(255,0,0)",t.setLineDash([6]),t.strokeRect(y,b,S,w),t.fillStyle=p.alpha(r?.palette.info.main??"rgb(255,0,0)",.2),t.fillRect(y,b,S,w)},drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o,session:r,theme:l}=e,{featureTypeOntology:s}=r.apolloDataStore.ontologyManager;if(!n)return;const{feature:i}=n,c=e.getFeatureLayoutPosition(i);if(!c)return;const{bpPerPx:u,displayedRegions:d,offsetPx:f}=o,{featureRow:m,layoutIndex:g,layoutRow:p}=c,h=d[g],{refName:y,reversed:b}=h,{length:S,max:w,min:E}=i,v=(o.bpToPx({refName:y,coord:b?w:E,regionNumber:g})?.offsetPx??0)-f,C=(p+m)*a,x=S/u;if(t.fillStyle=l?.palette.action.selected??"rgba(0,0,0,04)",!s)throw new Error("featureTypeOntology is undefined");t.fillRect(v,C,x,a*qa(i,s))},drawTooltip:$a,getContextMenuItems:function(e,t){const{apolloInternetAccount:n,apolloHover:a,changeManager:o,regions:l,selectedFeature:s,session:i}=e,[c]=l,u=e.getAssemblyId(c.assemblyName),d=[],f="admin"===(n?n.role:"admin");if(!a)return d;let m=Ge(t);(function(e,t){const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"CDS")})(t.featureAndGlyphUnderMouse.feature,i)&&(m=Ge(t,!0));for(const t of m){const n=Fa.getContextMenuItemsForFeature(e,t);Ua(t,i)&&n.push({label:"Merge exons",disabled:!f,onClick:()=>{i.queueDialog((n=>[Gt,{session:i,handleClose:()=>{n()},changeManager:o,sourceFeature:t,sourceAssemblyId:u,selectedFeature:s,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}},{label:"Split exon",disabled:!f,onClick:()=>{i.queueDialog((n=>[Qt,{session:i,handleClose:()=>{n()},changeManager:o,sourceFeature:t,sourceAssemblyId:u,selectedFeature:s,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}}),Ba(t,i)&&(n.push({label:"Merge transcript",onClick:()=>{i.queueDialog((n=>[Wt,{session:i,handleClose:()=>{n()},changeManager:o,sourceFeature:t,sourceAssemblyId:u,selectedFeature:s,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}}),r.isSessionModelWithWidgets(i)&&n.push({label:"Open transcript details",onClick:()=>{const e=i.addWidget("ApolloTranscriptDetails","apolloTranscriptDetails",{feature:t,assembly:u,changeManager:o,refName:c.refName});i.showWidget(e)}})),d.push({label:t.type,subMenu:n})}return d},getContextMenuItemsForFeature:Ga,getFeatureFromLayout:function(e,t,n,a){const o=Oa(e,a)[n]||[];for(const e of o){let n;if(t>=e.min&&t<=e.max&&e.parent&&(n=e),n){if(a.isTypeOf(n.type,"CDS")&&n.parent&&(a.isTypeOf(n.parent.type,"transcript")||a.isTypeOf(n.parent.type,"pseudogenic_transcript"))){const{cdsLocations:e}=n.parent;for(const a of e)for(const e of a)if(t>=e.min&&t<=e.max)return n;return n.parent}return n}}return e},getRowCount:qa,getRowForFeature:function(e,t,n){const a=Oa(e,n);for(const[e,n]of a.entries())if(n.some((e=>e._id===t._id)))return e},onMouseDown:function(e,t,n){const{featureAndGlyphUnderMouse:a}=t,{feature:o}=a,r=_a(t,o,e);r&&(n.stopPropagation(),e.startDrag(t,r.feature,r.edge,!0))},onMouseLeave:ja,onMouseMove:function(e,t){if(co(t)){const{featureAndGlyphUnderMouse:n}=t;e.setApolloHover(n);const{feature:a}=n;if(_a(t,a,e))return void e.setCursor("col-resize")}e.setCursor()},onMouseUp:function(e,t){if(e.apolloDragging)return;const{featureAndGlyphUnderMouse:n}=t;if(!n)return;const{feature:a}=n;e.setSelectedFeature(a);const{session:o}=e,{apolloDataStore:r}=o,{featureTypeOntology:l}=r.ontologyManager;if(!l)throw new Error("featureTypeOntology is undefined");let s=!1;for(const[,e]of a.children??[])if(l.isTypeOf(e.type,"CDS")||l.isTypeOf(e.type,"exon")){s=!0;break}(l.isTypeOf(a.type,"transcript")||l.isTypeOf(a.type,"pseudogenic_transcript"))&&s?e.showFeatureDetailsWidget(a,["ApolloTranscriptDetails","apolloTranscriptDetails"]):e.showFeatureDetailsWidget(a)}};function Ha(e){const t=[[e]];if(e.children)for(const[,n]of e.children)t.push(...Ha(n));return t}function za(e){return Ha(e).length}function Ja(e,t,n,a,o,r){const l=Ha(t)[n-a];for(const t of l)Va(e,t,n,o,r)}function Va(e,t,n,a,o){const{apolloRowHeight:r,lgv:l,session:s}=a,{bpPerPx:i,displayedRegions:c,offsetPx:u}=l,d=c[o],f=(l.bpToPx({refName:d.refName,coord:t.min,regionNumber:o})?.offsetPx??0)-u,{reversed:m}=d,{apolloSelectedFeature:g}=s,p=t.length/i,h=m?f-p:f,y=n*r,b=za(t),S=Ea(t,g);b>1&&Ca(e,h,y,p,b*r,S?"rgba(130,0,0,0.45)":"rgba(255,0,0,0.25)"),Fa.draw(e,t,n,a,o)}const{drawDragPreview:Xa,drawTooltip:Ka,getContextMenuItemsForFeature:Ya,onMouseDown:Za,onMouseLeave:Qa,onMouseMove:eo,onMouseUp:to}=Fa,no={draw:function(e,t,n,a,o){for(let r=0;r<za(t);r++)Ja(e,t,n+r,n,a,o)},drawDragPreview:Xa,drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,lgv:o}=e;if(!n)return;const{feature:r}=n,l=e.getFeatureLayoutPosition(r);if(!l)return;const{featureRow:s,layoutIndex:i,layoutRow:c}=l,{bpPerPx:u,displayedRegions:d,offsetPx:f}=o,m=d[i],{refName:g,reversed:p}=m,{length:h,max:y,min:b}=r,S=(o.bpToPx({refName:g,coord:p?y:b,regionNumber:i})?.offsetPx??0)-f,w=(c+s)*a,E=h/u;t.fillStyle="rgba(0,0,0,0.2)",t.fillRect(S,w,E,a*za(r))},drawTooltip:Ka,getContextMenuItemsForFeature:Ya,getContextMenuItems:function(e,t){const{apolloHover:n,session:a}=e,o=[];if(!n)return o;const{feature:r}=n,{featureTypeOntology:l}=a.apolloDataStore.ontologyManager;if(!l)throw new Error("featureTypeOntology is undefined");const s=Fa.getContextMenuItems(e,t);o.push({label:r.type,subMenu:s});for(const n of Ge(t)){if(n._id===r._id)continue;const t=Fa.getContextMenuItemsForFeature(e,n);o.push({label:n.type,subMenu:t})}return o},getFeatureFromLayout:function(e,t,n){return Ha(e)[n].find((e=>t>=e.min&&t<=e.max))},getRowCount:za,getRowForFeature:function(e,t){const n=Ha(e);for(const[e,a]of n.entries())if(a.some((e=>e._id===t._id)))return e},onMouseDown:Za,onMouseLeave:Qa,onMouseMove:eo,onMouseUp:to},ao=E.observer((function({featureTypes:e,handleClose:t,onUpdate:n,session:a}){const[o,r]=y.useState(""),[l,s]=y.useState(e);return de.default.createElement(Ke,{open:!0,maxWidth:!1,"data-testid":"filter-features-dialog",title:"Filter features by type",handleClose:t},de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,null,"Select the feature types you want to display in the apollo track"),de.default.createElement(p.Grid2,{container:!0,spacing:2},de.default.createElement(p.Grid2,{size:8},de.default.createElement(Ft,{session:a,ontologyName:"Sequence Ontology",style:{width:"100%"},value:o,filterTerms:xt,renderInput:e=>de.default.createElement(p.TextField,{...e,label:"Feature type",variant:"outlined",fullWidth:!0}),onChange:(e,t)=>{t&&r(t)}})),de.default.createElement(p.Grid2,{size:4},de.default.createElement(p.Button,{variant:"contained",onClick:()=>{if(o){if(l.includes(o))return;n([...l,o]),s([...l,o])}},disabled:!o,style:{marginTop:9},size:"medium"},"Add"))),l.length>0&&de.default.createElement("div",null,de.default.createElement("hr",null),de.default.createElement("div",{style:{width:300}},de.default.createElement(p.DialogContentText,null,"Selected feature types:"),de.default.createElement(p.Box,{sx:{display:"flex",flexWrap:"wrap",gap:.5}},l.map((e=>de.default.createElement(p.Chip,{key:e,label:e,onDelete:()=>{(e=>{const t=l.filter((t=>t!==e));n(t),s(t)})(e)}}))))))))}));function oo(e,t,n){const a=[];for(let o=e;o<e+t;o++){const e=n.get(o);e&&a.push(e)}return a}function ro(e,t){for(const n of e)for(const[e,a]of n)if(r.doesIntersect2(t.min,t.max,e,a)||r.doesIntersect2(e,a,t.min,t.max))return!1;return!0}function lo(e,t){return t?.palette.bases[e.toUpperCase()].main.toString()??"lightgray"}function so(e,t,n,a,o){const r=Math.min(n,10);e.fillStyle="#000",e.font=`${r}px`;const l=e.measureText(a).width;e.fillText(a,t+(n-l)/2,o+10)}function io(e,t,n,a,o,l,s,i,c,u,d,f){let m=s.slice(i,i+3).toUpperCase();c&&(m=function(e){return[...e].map((e=>r.revcom(e))).reverse().join("")}(m));const g=r.defaultCodonTable[m];if(!g)return;const p=function(e,t){return{M:"#33ee33","*":t?"#000000":"#f44336"}[e.toUpperCase()]}(g,f);p&&(d&&"*"==g||u&&"*"!=g)&&(e.fillStyle=p,e.fillRect(n,a,o,l)),t<=.1&&(e.rect(n,a,o,l),e.stroke(),so(e,n,o,g,a))}function co(e){return"featureAndGlyphUnderMouse"in e}function uo(e,t){const n=t<=1?2:0;switch(e){case 3:return 0;case 2:return 1;case 1:return 2;case-1:return 3+n;case-2:return 4+n;case-3:return 5+n}}function fo(e,t){if(!(t>1||void 0===e))return 1===e?3:4}function mo(e,t,n,a,o,r){void 0!==o&&(e.fillStyle=t?.palette.action.focus??"rgba(0,0,0,0.04)",e.fillRect(n,a*o,r,a))}function go(e,n){return function(e,n){const l=function(e,t){return function(e,t){const n=function(e,t){return function(e,t){const n=function(e,t){return function(e,t){const n=function(e,t){return o.BaseDisplay.named("BaseLinearApolloDisplay").props({type:i.types.literal("LinearApolloDisplay"),configuration:a.ConfigurationReference(t),graphical:!0,table:!1,showStartCodons:!1,showStopCodons:!0,highContrast:!1,heightPreConfig:i.types.maybe(i.types.refinement("displayHeight",i.types.number,(e=>e>=20))),filteredFeatureTypes:i.types.array(i.types.string),loadingState:!1}).views((e=>{const{configuration:t,renderProps:n}=e;return{renderProps:()=>({...n(),...Z.getParentRenderProps(e),config:t.renderer})}})).volatile((()=>({scrollTop:0}))).views((e=>({get lgv(){return r.getContainingView(e)},get height(){return e.heightPreConfig?e.heightPreConfig:e.graphical&&e.table?500:e.graphical?200:300},get loading(){return e.loadingState}}))).views((e=>({get rendererTypeName(){return e.configuration.renderer.type},get session(){return r.getSession(e)},get regions(){return e.lgv.dynamicBlocks.contentBlocks.map((({assemblyName:e,end:t,refName:n,start:a})=>({assemblyName:e,refName:n,start:Math.round(a),end:Math.round(t)})))},regionCannotBeRendered(){if(e.lgv&&e.lgv.bpPerPx>=200)return"Zoom in to see annotations"}}))).views((e=>({get apolloInternetAccount(){const[t]=e.regions,{internetAccounts:n}=i.getRoot(e),{assemblyName:o}=t,{assemblyManager:r}=e.session,l=r.get(o);if(!l)throw new Error(`No assembly found with name ${o}`);const{internetAccountConfigId:s}=a.getConf(l,["sequence","metadata"]);return n.find((e=>a.getConf(e,"internetAccountId")===s))},get changeManager(){return e.session.apolloDataStore.changeManager},getAssemblyId(t){const{assemblyManager:n}=e.session,a=n.get(t);if(!a)throw new Error(`Could not find assembly named ${t}`);return a.name},get selectedFeature(){return e.session.apolloSelectedFeature}}))).actions((e=>({setScrollTop(t){e.scrollTop=t},setHeight:t=>(e.heightPreConfig=Math.max(t,20),e.height),resizeHeight(t){const n=e.height;return this.setHeight(e.height+t)-n},showGraphicalOnly(){e.graphical=!0,e.table=!1},showTableOnly(){e.graphical=!1,e.table=!0},showGraphicalAndTable(){e.graphical=!0,e.table=!0},toggleShowStartCodons(){e.showStartCodons=!e.showStartCodons},toggleShowStopCodons(){e.showStopCodons=!e.showStopCodons},toggleHighContrast(){e.highContrast=!e.highContrast},updateFilteredFeatureTypes(t){e.filteredFeatureTypes=i.cast(t)},setLoading(t){e.loadingState=t}}))).views((e=>{const{filteredFeatureTypes:t,trackMenuItems:n}=e;return{trackMenuItems(){const{graphical:a,table:o,showStartCodons:r,showStopCodons:l,highContrast:s}=e;return[...n(),{type:"subMenu",label:"Appearance",subMenu:[{label:"Show graphical display",type:"radio",checked:a&&!o,onClick:()=>{e.showGraphicalOnly()}},{label:"Show table display",type:"radio",checked:o&&!a,onClick:()=>{e.showTableOnly()}},{label:"Show both graphical and table display",type:"radio",checked:o&&a,onClick:()=>{e.showGraphicalAndTable()}},{label:"Show start codons",type:"checkbox",checked:r,onClick:()=>{e.toggleShowStartCodons()}},{label:"Show stop codons",type:"checkbox",checked:l,onClick:()=>{e.toggleShowStopCodons()}},{label:"Use high contrast colors",type:"checkbox",checked:s,onClick:()=>{e.toggleHighContrast()}}]},{label:"Filter features by type",onClick:()=>{const n=e.session;e.session.queueDialog((a=>[ao,{session:n,handleClose:()=>{a()},featureTypes:i.getSnapshot(t),onUpdate:t=>{e.updateFilteredFeatureTypes(t)}}]))}}]}}})).actions((e=>({setSelectedFeature(t){e.session.apolloSetSelectedFeature(t)},showFeatureDetailsWidget(t,n){const[a]=e.regions,{assemblyName:o,refName:r}=a,l=e.getAssemblyId(o);if(!l)return;const{session:s}=e,{changeManager:i}=s.apolloDataStore,[c,u]=n??["ApolloFeatureDetailsWidget","apolloFeatureDetailsWidget"],d=s.addWidget(c,u,{feature:t,assembly:l,refName:r,changeManager:i});s.showWidget(d)},afterAttach(){i.addDisposer(e,s.autorun((()=>{e.lgv.initialized&&!e.regionCannotBeRendered()&&(e.setLoading(!0),e.session.apolloDataStore.loadFeatures(e.regions).then((()=>{setTimeout((()=>{e.setLoading(!1)}),1e3)})),e.lgv.bpPerPx<=3&&e.session.apolloDataStore.loadRefSeq(e.regions))}),{name:"LinearApolloDisplayLoadFeatures",delay:1e3}))}})))}(0,t);return n.named("LinearApolloDisplayLayouts").props({cleanupBoundary:2e5}).volatile((()=>({seenFeatures:s.observable.map()}))).views((e=>({getAnnotationFeatureById:t=>e.seenFeatures.get(t),getGlyph:e=>e.looksLikeGene?Wa:e.children?.size?no:Fa}))).actions((e=>({addSeenFeature(t){e.seenFeatures.set(t._id,t)},deleteSeenFeature(t){e.seenFeatures.delete(t)}}))).views((e=>({get featureLayouts(){const{assemblyManager:t}=e.session;return e.lgv.displayedRegions.map((n=>{const a=t.get(n.assemblyName),o=new Map,l=new Map,{end:s,refName:c,start:u}=n;for(const[t,n]of e.seenFeatures.entries()){if(!i.isAlive(n)){e.deleteSeenFeature(t);continue}if(c!==a?.getCanonicalRefName(n.refSeq)||!r.doesIntersect2(u,s,n.min,n.max)||e.filteredFeatureTypes.length>0&&!e.filteredFeatureTypes.includes(n.type))continue;const{featureTypeOntology:d}=e.session.apolloDataStore.ontologyManager;if(!d)throw new Error("featureTypeOntology is undefined");const f=e.getGlyph(n).getRowCount(n,d,e.lgv.bpPerPx);let m=0,g=!1;for(;!g;){let e=oo(m,f,l);if(e.length<f){for(let t=0;t<f-e.length;t++){const e=l.size;l.set(e,[]),o.set(e,[])}e=oo(m,f,l)}if(ro(e,n)){for(let e=m;e<m+f;e++){l.get(e)?.push([n.min,n.max]);const t=o.get(e);t?.push([e-m,n._id])}g=!0}else m+=1}}return o}))},getFeatureLayoutPosition(t){const{featureLayouts:n}=this,{featureTypeOntology:a}=e.session.apolloDataStore.ontologyManager;for(const[o,r]of n.entries())for(const[n,l]of r)for(const[r,s]of l){if(0!==r)continue;const l=e.getAnnotationFeatureById(s);if(l){if(t._id===l._id)return{layoutIndex:o,layoutRow:n,featureRow:r};if(l.hasDescendant(t._id)){if(!a)throw new Error("featureTypeOntology is undefined");const r=e.getGlyph(l).getRowForFeature(l,t,a);if(void 0!==r)return{layoutIndex:o,layoutRow:n,featureRow:r}}}}}}))).views((e=>({get highestRow(){return Math.max(0,...e.featureLayouts.map((e=>Math.max(...e.keys()))))}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(e.lgv.initialized&&!e.regionCannotBeRendered()){for(const[t,n]of e.seenFeatures.entries()){let a=!1;for(const t of e.regions)if(r.doesIntersect2(t.start-e.cleanupBoundary,t.end+e.cleanupBoundary,n.min,n.max)){a=!0;break}a||e.deleteSeenFeature(t)}for(const t of e.regions){const n=e.session.apolloDataStore.assemblies.get(t.assemblyName),a=n?.getByRefName(t.refName),o=a?.features;if(o)for(const[,n]of o)r.doesIntersect2(t.start,t.end,n.min,n.max)&&!e.seenFeatures.has(n._id)&&e.addSeenFeature(n)}}}),{name:"LinearApolloDisplaySetSeenFeatures",delay:1e3}))}})))}(0,t).named("LinearApolloDisplayRendering").props({sequenceRowHeight:15,apolloRowHeight:20,detailsMinHeight:200,detailsHeight:200,lastRowTooltipBufferHeight:40,isShown:!0,filteredTranscripts:i.types.array(i.types.string)}).volatile((()=>({canvas:null,overlayCanvas:null,collaboratorCanvas:null,seqTrackCanvas:null,seqTrackOverlayCanvas:null,theme:void 0}))).views((e=>({get featuresHeight(){return(e.highestRow+1)*e.apolloRowHeight+e.lastRowTooltipBufferHeight}}))).actions((e=>({toggleShown(){e.isShown=!e.isShown},setDetailsHeight(t){e.detailsHeight=e.isShown?Math.max(Math.min(t,e.height-100),Math.min(e.height,e.detailsMinHeight)):t},setCanvas(t){e.canvas=t},setOverlayCanvas(t){e.overlayCanvas=t},setCollaboratorCanvas(t){e.collaboratorCanvas=t},setSeqTrackCanvas(t){e.seqTrackCanvas=t},setSeqTrackOverlayCanvas(t){e.seqTrackOverlayCanvas=t},setTheme(t){e.theme=t},afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.collaboratorCanvas?.getContext("2d");if(t){t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);for(const n of e.session.collaborators){const{locations:a}=n;if(0===a.length)continue;let o=0;for(const r of e.lgv.displayedRegions){for(const l of a){if(l.refSeq!==r.refName)continue;const{end:a,refSeq:s,start:i}=l,c=e.lgv.bpToPx({refName:s,coord:i,regionNumber:o});if(!c)continue;const u=c.offsetPx-e.lgv.offsetPx,d=(a-i)/e.lgv.bpPerPx;t.fillStyle="rgba(0,255,0,.2)",t.fillRect(u,1,d,100),t.fillStyle="black",t.fillText(n.name,u+1,11,d-2)}o++}}}}),{name:"LinearApolloDisplayRenderCollaborators"}))}})))}(0,t);return n.actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{const{theme:t}=e;if(!e.lgv.initialized||e.regionCannotBeRendered())return;const n=3/e.lgv.bpPerPx;if(n<1)return;const a=e.seqTrackCanvas?.getContext("2d");if(!a)return;a.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.lgv.bpPerPx<=1?125:95);const o=e.lgv.bpPerPx<=1?[3,2,1,0,0,-1,-2,-3]:[3,2,1,-1,-2,-3];let l=0;if(t)for(const n of o){let o=t.palette.framesCDS.at(n)?.main;if(o){let n=0;e.highContrast&&(o="white",n=1,a.fillStyle=t.palette.grey[200],a.fillRect(0,l,e.lgv.dynamicBlocks.totalWidthPx,e.sequenceRowHeight)),a.fillStyle=o,a.fillRect(0+n,l+n,e.lgv.dynamicBlocks.totalWidthPx-2*n,e.sequenceRowHeight-2*n)}l+=e.sequenceRowHeight}for(const[t,o]of e.regions.entries()){const{apolloDataStore:l}=e.session,s=l.assemblies.get(o.assemblyName),i=s?.getByRefName(o.refName),c=i?.getSequence(o.start,o.end);if(!c)return;for(const[l,s]of[...c].entries()){const i=(e.lgv.bpToPx({refName:o.refName,coord:o.start+l,regionNumber:t})?.offsetPx??0)-e.lgv.offsetPx,u=e.lgv.displayedRegions[t].reversed?i-n:i;for(let t=2;t>=0;t--)(o.start+l)%3===t&&io(a,e.lgv.bpPerPx,u,e.sequenceRowHeight*(2-t),n,e.sequenceRowHeight,c,l,!1,e.showStartCodons,e.showStopCodons,e.highContrast);if(e.lgv.bpPerPx<=1){const n=(e.lgv.bpToPx({refName:o.refName,coord:o.start+l,regionNumber:t})?.offsetPx??0)-e.lgv.offsetPx,i=1/e.lgv.bpPerPx,c=e.lgv.displayedRegions[t].reversed?n-i:n;a.beginPath(),a.fillStyle=lo(s,e.theme),a.rect(c,3*e.sequenceRowHeight,i,e.sequenceRowHeight),a.fill(),e.lgv.bpPerPx<=.1&&(a.stroke(),so(a,c,i,s,3*e.sequenceRowHeight));const u=r.revcom(s);a.beginPath(),a.fillStyle=lo(u,e.theme),a.rect(c,4*e.sequenceRowHeight,i,e.sequenceRowHeight),a.fill(),e.lgv.bpPerPx<=.1&&(a.stroke(),so(a,c,i,u,4*e.sequenceRowHeight))}for(let t=0;t<=2;t++)(o.start+l)%3===t&&io(a,e.lgv.bpPerPx,u,e.sequenceRowHeight*((e.lgv.bpPerPx<=1?5:3)+t),n,e.sequenceRowHeight,c,l,!0,e.showStartCodons,e.showStopCodons,e.highContrast)}}}),{name:"LinearApolloDisplayRenderSequence"}))}})))}(0,t).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{const{canvas:t,featureLayouts:n,featuresHeight:a,lgv:o}=e;if(!o.initialized||e.regionCannotBeRendered())return;const{displayedRegions:l,dynamicBlocks:s}=o,i=t?.getContext("2d");if(i){i.clearRect(0,0,s.totalWidthPx,a);for(const[t,a]of n.entries()){const n=l[t];for(const[o,l]of a.entries())for(const[a,s]of l){const l=e.getAnnotationFeatureById(s);a>0||!l||r.doesIntersect2(n.start,n.end,l.min,l.max)&&e.getGlyph(l).draw(i,l,o,e,t)}}}}),{name:"LinearApolloDisplayRenderFeatures"}))}})))}(0,t);return n.named("LinearApolloDisplayMouseEvents").volatile((()=>({apolloDragging:null,cursor:void 0,apolloHover:void 0}))).views((e=>({getMousePosition(t){const n=function(e,t){const n=e.currentTarget,{clientX:a,clientY:o}=e,{left:r,top:l}=n.getBoundingClientRect(),s=a-r,i=o-l,{coord:c,index:u,refName:d}=t.pxToBp(s);return{x:s,y:i,refName:d,bp:c,regionNumber:u}}(t,e.lgv),{bp:a,regionNumber:o,y:r}=n,l=Math.floor(r/e.apolloRowHeight),s=e.featureLayouts[o].get(l);if(!s)return n;const i=s.find((t=>{const n=e.getAnnotationFeatureById(t[1]);return n&&a>=n.min&&a<=n.max}));if(!i)return n;const[c,u]=i,d=e.getAnnotationFeatureById(u);if(!d)return n;const f=e.getGlyph(d),{featureTypeOntology:m}=e.session.apolloDataStore.ontologyManager;if(!m)throw new Error("featureTypeOntology is undefined");const g=f.getFeatureFromLayout(d,a,c,m);return g?{...n,featureAndGlyphUnderMouse:{feature:g,topLevelFeature:d,glyph:f}}:n}}))).actions((e=>({continueDrag(t,n){if(!e.apolloDragging)throw new Error("continueDrag() called with no current drag in progress");n.stopPropagation(),e.apolloDragging={...e.apolloDragging,current:t}},setDragging(t){e.apolloDragging=t??null}}))).actions((e=>({setApolloHover(t){e.apolloHover=t},setCursor(t){e.cursor!==t&&(e.cursor=t)},updateFilteredTranscripts(e){}}))).actions((()=>({onClick(){}})))}(0,t).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.seqTrackOverlayCanvas?.getContext("2d");if(!t)return;t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.lgv.bpPerPx<=1?125:95);const{apolloHover:n,lgv:a,regions:o,sequenceRowHeight:l,session:s,theme:i}=e;if(!n)return;const{feature:c}=n,{featureTypeOntology:u}=s.apolloDataStore.ontologyManager;if(!u)throw new Error("featureTypeOntology is undefined");for(const[e,n]of o.entries())if(u.isTypeOf(c.type,"CDS")){const o=c.parent;if(!o)continue;const s=o.cdsLocations.find((e=>c.min===e.at(0)?.min&&c.max===e.at(-1)?.max));if(!s)continue;for(const o of s){const s=uo(r.getFrame(o.min,o.max,c.strand??1,o.phase),a.bpPerPx),u=(a.bpToPx({refName:n.refName,coord:o.min,regionNumber:e})?.offsetPx??0)-a.offsetPx,d=(o.max-o.min)/a.bpPerPx;mo(t,i,a.displayedRegions[e].reversed?u-d:u,l,s,d)}}else{const o=fo(c.strand,a.bpPerPx),r=(a.bpToPx({refName:n.refName,coord:c.min,regionNumber:e})?.offsetPx??0)-a.offsetPx,s=c.length/a.bpPerPx;mo(t,i,a.displayedRegions[e].reversed?r-s:r,l,o,s)}}),{name:"LinearApolloDisplayRenderSeqHighlight"}))}})))}(0,n);return l.views((e=>({contextMenuItems(t){const{apolloHover:n}=e;if(!n)return[];const a=e.getMousePosition(t),{topLevelFeature:o}=n,r=e.getGlyph(o);return co(a)?r.getContextMenuItems(e,a):[]}}))).actions((e=>({startDrag(t,n,a,o=!1){e.apolloDragging={start:t,current:t,feature:n,edge:a,shrinkParent:o}},endDrag(){if(!e.apolloDragging)throw new Error("endDrag() called with no current drag in progress");const{current:n,edge:a,feature:o,start:r,shrinkParent:l}=e.apolloDragging;if(Math.abs(n.x-r.x)<=4)return e.setDragging(),void e.setCursor();const{displayedRegions:s}=e.lgv,i=e.getAssemblyId(s[r.regionNumber].assemblyName),c=Je(o,n.bp,a,l),u="max"===a?new t.LocationEndChange({typeName:"LocationEndChange",changedIds:c.map((e=>e.featureId)),changes:c.map((e=>({featureId:e.featureId,oldEnd:e.oldLocation,newEnd:e.newLocation}))),assembly:i}):new t.LocationStartChange({typeName:"LocationStartChange",changedIds:c.map((e=>e.featureId)),changes:c.map((e=>({featureId:e.featureId,oldStart:e.oldLocation,newStart:e.newLocation}))),assembly:i});e.changeManager.submit(u),e.setDragging(),e.setCursor()}}))).actions((e=>({onMouseDown(t){const n=e.getMousePosition(t);co(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseDown(e,n,t)},onMouseMove(t){const n=e.getMousePosition(t);if(e.apolloDragging)return e.setCursor("col-resize"),void e.continueDrag(n,t);co(n)?n.featureAndGlyphUnderMouse.glyph.onMouseMove(e,n,t):(e.setApolloHover(),e.setCursor())},onMouseLeave(t){e.setDragging(),e.setApolloHover();const n=e.getMousePosition(t);co(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseLeave(e,n,t)},onMouseUp(t){const n=e.getMousePosition(t);co(n)?n.featureAndGlyphUnderMouse.glyph.onMouseUp(e,n,t):e.setSelectedFeature(),e.apolloDragging&&e.endDrag()}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.overlayCanvas?.getContext("2d");if(!t)return;t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);const{apolloDragging:n,apolloHover:a}=e;if(!a)return;const{glyph:o}=a;o.drawHover(e,t),o.drawTooltip(e,t),n&&e.getGlyph(n.feature.topLevelFeature).drawDragPreview(e,t)}),{name:"LinearApolloDisplayRenderMouseoverAndDrag"}))}})))}(0,n).props({tabularEditor:i.types.optional(wa,{})}).named("LinearApolloDisplay")}const po=a.ConfigurationSchema("LinearApolloSixFrameDisplay",{},{explicitIdentifier:"displayId",explicitlyTyped:!0}),ho=E.observer((function({sourceFeature:e,filteredTranscripts:t,handleClose:n,onUpdate:a}){const o=[];if(e.children)for(const[,t]of e.children){const e=t.attributes.get("gff_id")?.toString();e&&o.push(e)}const[r,l]=y.useState(t);return de.default.createElement(Ke,{open:!0,maxWidth:!1,"data-testid":"filter-transcripts-dialog",title:"Filter transcripts by ID",handleClose:n},de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,null,"Select the alternate transcripts you want to display in the apollo track"),de.default.createElement(p.Grid2,{container:!0,spacing:2},de.default.createElement(p.Grid2,{size:8},de.default.createElement(p.FormGroup,null,o.map((e=>de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{checked:!r.includes(e),onChange:()=>{(e=>{const t=r.includes(e)?r.filter((t=>t!==e)):[...r,e];a(t),l(t)})(e)},inputProps:{"aria-label":"controlled"}}),label:e}))))))))}));let yo=null,bo=null,So=null,wo=null;const Eo=globalThis.document.createElement("canvas");if(Eo?.getContext)for(const e of["forward","backward"])for(const t of["light","dark"]){const n=document.createElement("canvas"),a=10;n.width=n.height=a;const o=n.getContext("2d");if(o){const r="light"===t?"rgba(0,0,0,0)":"rgba(0,0,0,0.75)",l="light"===t?"rgba(255,255,255,0.25)":"rgba(0,0,0,0.50)",s="forward"===e?o.createLinearGradient(0,a,a,0):o.createLinearGradient(0,0,a,a);s.addColorStop(0,r),s.addColorStop(.25,r),s.addColorStop(.25,l),s.addColorStop(.5,l),s.addColorStop(.5,r),s.addColorStop(.75,r),s.addColorStop(.75,l),s.addColorStop(1,l),o.fillStyle=s,o.fillRect(0,0,10,10),"forward"===e?"light"===t?yo=o.createPattern(n,"repeat"):So=o.createPattern(n,"repeat"):"light"===t?bo=o.createPattern(n,"repeat"):wo=o.createPattern(n,"repeat")}}function vo(e,t){for(const n of e)if(ge.default(n,t))return!0;return!1}function Co(e,t){return Boolean(t&&e._id===t._id)}function xo(e,t,n,a){const{filteredTranscripts:o,session:l}=a,{apolloDataStore:s}=l,{featureTypeOntology:i}=s.ontologyManager;if(!i)throw new Error("featureTypeOntology is undefined");const c=i.isTypeOf(n.type,"transcript");if(null===t)return;const u=n.attributes.get("gff_id")?.toString();if(u&&o.includes(u))return;const{bp:d,refName:f,regionNumber:m,x:g}=e,{lgv:p}=a;if(c){const e=n;if(!e.children)return;const a=[],o=[];for(const t of e.children.values()){const e=i.isTypeOf(t.type,"exon"),n=i.isTypeOf(t.type,"CDS");e?a.push(t):n&&o.push(t)}const l=a.find((e=>{const[t,n]=r.intersection2(d,d+1,e.min,e.max);return void 0!==t&&void 0!==n}));if(l){const e=je(l,f,m,p);if(e){const t=We(l,g,e);if(t)return t}}const s=je(t,f,m,p);if(s){const e=o.find((e=>{const[t,n]=r.intersection2(d,d+1,e.min,e.max);return void 0!==t&&void 0!==n}));if(e){const t=We(e,g,s);if(t)return t}}}}const To={draw:function(e,t,n,a,o){const{apolloRowHeight:l,lgv:s,session:i,theme:c,highestRow:u,filteredTranscripts:d,showFeatureLabels:f}=a,{bpPerPx:m,displayedRegions:g,offsetPx:h}=s,y=g[o],{refName:b,reversed:S}=y,w=l,E=w,v=w,C=w,x=f?2:1,T=c?.palette.text.primary??"black",{attributes:A,children:F,min:D,strand:k}=t;if(!F)return;const{apolloSelectedFeature:N}=i,{apolloDataStore:I}=i,{featureTypeOntology:R}=I.ontologyManager;if(!R)throw new Error("featureTypeOntology is undefined");const M=[],L=(s.bpToPx({refName:b,coord:D,regionNumber:o})?.offsetPx??0)-h,P=t.length/m,q=S?L-P:L,O=(1==k?3:4)*x*w;e.fillStyle=c?.palette.text.primary??"black",e.fillRect(q,O,P,C),e.fillStyle=Co(t,N)?p.alpha("rgb(0,0,0)",.7):p.alpha(c?.palette.background.paper??"#ffffff",.7),e.fillRect(q+1,O+1,P-2,C-2);const _=Co(t,N),B={x:q,y:O,h:C,text:A.get("gff_id")?.toString(),color:T,isSelected:_};_?M.unshift(B):M.push(B);const U="dark"===c?.palette.mode?So:yo,$="dark"===c?.palette.mode?wo:bo,G=S?-1:1;let j=null,W=null;k&&([j,W]=k*G==1?[U,$]:[$,U]),j&&W&&(e.fillStyle=j,e.fillRect(q+1,O+1,P-2,(C-2)/2),e.fillStyle=W,e.fillRect(q+1,O+(C-2)/2,P-2,(C-2)/2));const H=new Set;for(const[,t]of F){if(!R.isTypeOf(t.type,"transcript")&&!R.isTypeOf(t.type,"pseudogenic_transcript"))continue;const{children:n,cdsLocations:a}=t;if(!n)continue;const l=t.attributes.get("gff_id")?.toString();if(l&&d.includes(l))continue;for(const[,t]of n){if(!R.isTypeOf(t.type,"exon"))continue;const n=(s.bpToPx({refName:b,coord:t.min,regionNumber:o})?.offsetPx??0)-h,a=t.length/m,r=S?n-a:n,l=O+(C-E)/2,i=Co(t,N);if(e.fillStyle=c?.palette.text.primary??"black",e.fillRect(r,l,a,E),a>2){e.clearRect(r+1,l+1,a-2,E-2),e.fillStyle=i?"rgb(0,0,0)":p.alpha("#f5f500",.6),e.fillRect(r+1,l+1,a-2,E-2),j&&W&&(e.fillStyle=j,e.fillRect(r+1,l+1,a-2,(E-2)/2),e.fillStyle=W,e.fillRect(r+1,l+1+(E-2)/2,a-2,(E-2)/2));const n={x:r,y:l,h:E,text:t.attributes.get("gff_id")?.toString(),color:T,isSelected:i};i?M.unshift(n):M.push(n)}}const i=Co(t,N?.parent);let f=0,g=0;for(const n of a){let a=0,l=0,d=1;for(const p of n.sort(((e,t)=>e.max-t.max)))if(N&&i&&R.isTypeOf(N.type,"CDS")||!vo(H,p)){const n=(p.max-p.min)/m,y=(s.bpToPx({refName:b,coord:p.min,regionNumber:o})?.offsetPx??0)-h;f=S?y-n:y,e.fillStyle=c?.palette.text.primary??"black";const E=r.getFrame(p.min,p.max,t.strand??1,p.phase);if(g=((E<0?-1*E+5:E)*x-x)*w,e.fillRect(f,g,n,v),n>2){e.clearRect(f+1,g+1,n-2,v-2);const t=c?.palette.framesCDS.at(E)?.main,o=t??"rgb(171,71,188)";if(e.fillStyle=o,e.fillStyle=N&&i&&R.isTypeOf(N.type,"CDS")?"rgb(0,0,0)":o,e.fillRect(f+1,g+1,n-2,v-2),d>1){const t=[(f-l)/2+l,Math.max(E<0?w*x*u+1:1,Math.min(a,g)-w/2)];e.strokeStyle="rgb(0, 128, 128)",e.beginPath(),e.moveTo(l,a),e.lineTo(...t),e.stroke(),e.moveTo(...t),e.lineTo(f,g+w/2),e.stroke()}l=f+n,a=g+w/2,d+=1,j&&W&&(e.fillStyle=j,e.fillRect(f+1,g+1,n-2,(v-2)/2),e.fillStyle=W,e.fillRect(f+1,g+(v-2)/2,n-2,(v-2)/2))}H.add(p)}}const y={x:f,y:g,h:v,text:t.attributes.get("gff_id")?.toString(),color:T,isSelected:i};i?M.unshift(y):M.push(y)}f&&function(e,t,n="10px sans-serif"){for(let a=t.length-1;a>=0;--a){const o=t[a];e.fillStyle=o.color;const l=Math.max(o.x+1,0),s=o.y+o.h,i=r.measureText(o.text,10);o.isSelected&&(e.clearRect(l-5,s,i+10,o.h),e.font="bold ".concat(n)),o.text&&(e.fillText(o.text,l,s+11,i),e.font=n)}}(e,M)},drawDragPreview:function(e,t){const{apolloDragging:n,apolloRowHeight:a,lgv:o,theme:r}=e,{bpPerPx:l,displayedRegions:s,offsetPx:i}=o;if(!n)return;const{current:c,edge:u,feature:d,start:f}=n,m=Math.floor(f.y/a),g=s[f.regionNumber],h=(g.reversed?g.end-d[u]:d[u]-g.start)/l-i,y=Math.min(c.x,h),b=m*a,S=Math.abs(c.x-h),w=1*a;t.strokeStyle=r?.palette.info.main??"rgb(255,0,0)",t.setLineDash([6]),t.strokeRect(y,b,S,w),t.fillStyle=p.alpha(r?.palette.info.main??"rgb(255,0,0)",.2),t.fillRect(y,b,S,w)},drawHover:function(e,t){const{apolloHover:n,apolloRowHeight:a,filteredTranscripts:o,lgv:l,highestRow:s,session:i,showFeatureLabels:c}=e;if(!n)return;const{apolloDataStore:u}=i,{featureTypeOntology:d}=u.ontologyManager;if(!d)throw new Error("featureTypeOntology is undefined");const{feature:f}=n;if(!d.isTypeOf(f.type,"transcript"))return;const m=f.attributes.get("gff_id")?.toString();if(m&&o.includes(m))return;const g=e.getFeatureLayoutPosition(f);if(!g)return;const{bpPerPx:p,displayedRegions:h,offsetPx:y}=l,{layoutIndex:b}=g,S=h[b],{refName:w,reversed:E}=S,v=a,C=v,x=c?2:1,{cdsLocations:T,strand:A}=f;for(const e of T){let n=0,a=0,o=1;for(const i of e.sort(((e,t)=>e.max-t.max))){const e=(i.max-i.min)/p;if(e>2){const c=(l.bpToPx({refName:w,coord:i.min,regionNumber:b})?.offsetPx??0)-y,u=E?c-e:c,d=r.getFrame(i.min,i.max,A??1,i.phase),f=((d<0?-1*d+5:d)*x-x)*v;if(t.fillStyle="rgba(255,0,0,0.6)",t.fillRect(u,f,e,C),o>1){const e=[(u-a)/2+a,Math.max(d<0?v*x*s+1:1,Math.min(n,f)-v/2)];t.strokeStyle="rgb(0, 0, 0)",t.lineWidth=2,t.beginPath(),t.moveTo(a,n),t.lineTo(...e),t.stroke(),t.moveTo(...e),t.lineTo(u,f+v/2),t.stroke()}a=u+e,n=f+v/2,o+=1}}}},drawTooltip:function(e,t){const{apolloHover:n,apolloRowHeight:a,filteredTranscripts:o,lgv:l,theme:s}=e;if(!n)return;const{cds:i,feature:c}=n;if(!i)return;const u=e.getFeatureLayoutPosition(c);if(!u)return;const d=c.attributes.get("gff_id")?.toString();if(d&&o.includes(d))return;const{layoutIndex:f}=u,{bpPerPx:m,displayedRegions:g,offsetPx:h}=l,y=g[f],{refName:b,reversed:S}=y,w=a,E=Math.round(.7*w);let v="Loc: ";const{strand:C}=c,{max:x,min:T,phase:A}=i;v+=`${T+1}–${x}`;let F=(l.bpToPx({refName:b,coord:S?x:T,regionNumber:f})?.offsetPx??0)-h;const D=r.getFrame(T,x,C??1,A),k=((D<0?-1*D+5:D)-1)*w+(w-E)/2,N=(x-T)/m,I=`Type: ${i.type}`,{attributes:R}=c,M=R.get("gff_name")?.find((e=>""!==e)),L=[t.measureText(I).width,t.measureText(v).width];M&&L.push(t.measureText(`Parent Type: ${c.type}`).width,t.measureText(`Parent Name: ${M}`).width);const P=Math.max(...L);F=F+N+5,t.fillStyle=p.alpha(s?.palette.text.primary??"rgb(1, 1, 1)",.7),t.fillRect(F,k,P+4,4===L.length?55:35),t.beginPath(),t.moveTo(F,k),t.lineTo(F-5,k+5),t.lineTo(F,k+10),t.fill(),t.fillStyle=s?.palette.background.default??"rgba(255, 255, 255)";let q=k+12;t.fillText(I,F+2,q),M&&(q+=12,t.fillText(`Parent Type: ${c.type}`,F+2,q),q+=12,t.fillText(`Parent Name: ${M}`,F+2,q)),q+=12,t.fillText(v,F+2,q)},getContextMenuItems:function(e){const{apolloHover:t,apolloInternetAccount:n,changeManager:a,filteredTranscripts:o,regions:r,selectedFeature:l,session:s}=e,c=[];if(!t)return c;const{feature:u}=t,d=n?n.role:"admin",f="admin"===d,m=!(d&&["admin","user"].includes(d)),[g]=r,p=e.getAssemblyId(g.assemblyName),h=e.getAssemblyId(g.assemblyName);c.push({label:"Add child feature",disabled:m,onClick:()=>{s.queueDialog((e=>[Dt,{session:s,handleClose:()=>{e()},changeManager:a,sourceFeature:u,sourceAssemblyId:p,internetAccount:n}]))}},{label:"Copy features and annotations",disabled:m,onClick:()=>{s.queueDialog((e=>[Mt,{session:s,handleClose:()=>{e()},changeManager:a,sourceFeature:u,sourceAssemblyId:h}]))}},{label:"Delete feature",disabled:!f,onClick:()=>{s.queueDialog((t=>[Pt,{session:s,handleClose:()=>{t()},changeManager:a,sourceFeature:u,sourceAssemblyId:h,selectedFeature:l,setSelectedFeature:t=>{e.setSelectedFeature(t)}}]))}});const{featureTypeOntology:y}=s.apolloDataStore.ontologyManager;if(!y)throw new Error("featureTypeOntology is undefined");return y.isTypeOf(u.type,"gene")&&c.push({label:"Filter alternate transcripts",onClick:()=>{s.queueDialog((t=>[ho,{handleClose:()=>{t()},sourceFeature:u,filteredTranscripts:i.getSnapshot(o),onUpdate:t=>{e.updateFilteredTranscripts(t)}}]))}}),c},onMouseDown:function(e,t,n){const{featureAndGlyphUnderMouse:a}=t,{cds:o,feature:r}=a,l=xo(t,o,r,e);l&&(n.stopPropagation(),e.startDrag(t,l.feature,l.edge,!0))},onMouseLeave:function(){},onMouseMove:function(e,t){if(Ao(t)){const{featureAndGlyphUnderMouse:n}=t;e.setApolloHover(n);const{cds:a,feature:o}=n;if(xo(t,a,o,e))return void e.setCursor("col-resize")}e.setCursor()},onMouseUp:function(e,t){if(e.apolloDragging)return;const{featureAndGlyphUnderMouse:n}=t,{session:a}=e,{apolloDataStore:o}=a,{featureTypeOntology:r}=o.ontologyManager;if(!n)return;const{feature:l}=n;if(e.setSelectedFeature(l),!r)throw new Error("featureTypeOntology is undefined");let s=!1;for(const[,e]of l.children??[])if(r.isTypeOf(e.type,"CDS")||r.isTypeOf(e.type,"exon")){s=!0;break}(r.isTypeOf(l.type,"transcript")||r.isTypeOf(l.type,"pseudogenic_transcript"))&&s?e.showFeatureDetailsWidget(l,["ApolloTranscriptDetails","apolloTranscriptDetails"]):e.showFeatureDetailsWidget(l)}};function Ao(e){return"featureAndGlyphUnderMouse"in e}function Fo(e,n){return function(e,n){const l=function(e,t){return function(e,t){const n=function(e,t){return function(e,t){const n=function(e,t){return o.BaseDisplay.named("BaseLinearApolloSixFrameDisplay").props({type:i.types.literal("LinearApolloSixFrameDisplay"),configuration:a.ConfigurationReference(t),graphical:!0,table:!1,showFeatureLabels:!0,heightPreConfig:i.types.maybe(i.types.refinement("displayHeight",i.types.number,(e=>e>=20))),filteredFeatureTypes:i.types.array(i.types.string)}).views((e=>{const{configuration:t,renderProps:n}=e;return{renderProps:()=>({...n(),...Z.getParentRenderProps(e),config:t.renderer})}})).volatile((()=>({scrollTop:0}))).views((e=>({get lgv(){return r.getContainingView(e)},get height(){return e.heightPreConfig?e.heightPreConfig:e.graphical&&e.table?500:e.graphical?200:300}}))).views((e=>({get rendererTypeName(){return e.configuration.renderer.type},get session(){return r.getSession(e)},get regions(){return e.lgv.dynamicBlocks.contentBlocks.map((({assemblyName:e,end:t,refName:n,start:a})=>({assemblyName:e,refName:n,start:Math.round(a),end:Math.round(t)})))},regionCannotBeRendered(){if(e.lgv&&e.lgv.bpPerPx>=200)return"Zoom in to see annotations"}}))).views((e=>({get apolloInternetAccount(){const[t]=e.regions,{internetAccounts:n}=i.getRoot(e),{assemblyName:o}=t,{assemblyManager:r}=e.session,l=r.get(o);if(!l)throw new Error(`No assembly found with name ${o}`);const{internetAccountConfigId:s}=a.getConf(l,["sequence","metadata"]);return n.find((e=>a.getConf(e,"internetAccountId")===s))},get changeManager(){return e.session.apolloDataStore.changeManager},getAssemblyId(t){const{assemblyManager:n}=e.session,a=n.get(t);if(!a)throw new Error(`Could not find assembly named ${t}`);return a.name},get selectedFeature(){return e.session.apolloSelectedFeature}}))).actions((e=>({setScrollTop(t){e.scrollTop=t},setHeight:t=>(e.heightPreConfig=Math.max(t,20),e.height),resizeHeight(t){const n=e.height;return this.setHeight(e.height+t)-n},showGraphicalOnly(){e.graphical=!0,e.table=!1},showTableOnly(){e.graphical=!1,e.table=!0},showGraphicalAndTable(){e.graphical=!0,e.table=!0},toggleShowFeatureLabels(){e.showFeatureLabels=!e.showFeatureLabels},updateFilteredFeatureTypes(t){e.filteredFeatureTypes=i.cast(t)}}))).views((e=>{const{filteredFeatureTypes:t,trackMenuItems:n}=e;return{trackMenuItems(){const{graphical:a,table:o,showFeatureLabels:r}=e;return[...n(),{type:"subMenu",label:"Appearance",subMenu:[{label:"Show graphical display",type:"radio",checked:a&&!o,onClick:()=>{e.showGraphicalOnly()}},{label:"Show table display",type:"radio",checked:o&&!a,onClick:()=>{e.showTableOnly()}},{label:"Show both graphical and table display",type:"radio",checked:o&&a,onClick:()=>{e.showGraphicalAndTable()}},{label:"Feature Labels",type:"checkbox",checked:r,onClick:()=>{e.toggleShowFeatureLabels()}}]},{label:"Filter features by type",onClick:()=>{const n=e.session;e.session.queueDialog((a=>[ao,{session:n,handleClose:()=>{a()},featureTypes:i.getSnapshot(t),onUpdate:t=>{e.updateFilteredFeatureTypes(t)}}]))}}]}}})).actions((e=>({setSelectedFeature(t){e.session.apolloSetSelectedFeature(t)},showFeatureDetailsWidget(t,n){const[a]=e.regions,{assemblyName:o,refName:r}=a,l=e.getAssemblyId(o);if(!l)return;const{session:s}=e,{changeManager:i}=s.apolloDataStore,[c,u]=n??["ApolloFeatureDetailsWidget","apolloFeatureDetailsWidget"],d=s.addWidget(c,u,{feature:t,assembly:l,refName:r,changeManager:i});s.showWidget(d)},afterAttach(){i.addDisposer(e,s.autorun((()=>{e.lgv.initialized&&!e.regionCannotBeRendered()&&(e.session.apolloDataStore.loadFeatures(e.regions),e.lgv.bpPerPx<=3&&e.session.apolloDataStore.loadRefSeq(e.regions))}),{name:"LinearApolloSixFrameDisplayLoadFeatures",delay:1e3}))}})))}(0,t);return n.named("LinearApolloSixFrameDisplayLayouts").props({featuresMinMaxLimit:5e5}).volatile((()=>({seenFeatures:s.observable.map()}))).views((e=>({get featuresMinMax(){const{assemblyManager:t}=e.session;return e.lgv.displayedRegions.map((n=>{const a=t.get(n.assemblyName);let o,l;const{end:s,refName:i,start:c}=n;for(const[,t]of e.seenFeatures)i!==a?.getCanonicalRefName(t.refSeq)||!r.doesIntersect2(c,s,t.min,t.max)||t.length>e.featuresMinMaxLimit||(void 0===o&&({min:o}=t),void 0===l&&({max:l}=t),t.minWithChildren<o&&({min:o}=t),t.maxWithChildren>l&&({max:l}=t));if(void 0!==o&&void 0!==l)return[o,l]}))},getGlyph:e=>To,featureLabelSpacer:t=>e.showFeatureLabels?2*t-1:t}))).actions((e=>({addSeenFeature(t){e.seenFeatures.set(t._id,t)},deleteSeenFeature(t){e.seenFeatures.delete(t)}}))).views((e=>({get geneTrackRowNums(){return[4,5].map((t=>e.featureLabelSpacer(t)))}}))).views((e=>({get featureLayouts(){const{assemblyManager:t}=e.session;return e.lgv.displayedRegions.map(((n,a)=>{const o=t.get(n.assemblyName),l=new Map;if(!e.featuresMinMax[a])return l;const{end:s,refName:c,start:u}=n;for(const[t,n]of e.seenFeatures.entries()){if(!i.isAlive(n)){e.deleteSeenFeature(t);continue}if(c!==o?.getCanonicalRefName(n.refSeq)||!r.doesIntersect2(u,s,n.min,n.max))continue;const{featureTypeOntology:a}=e.session.apolloDataStore.ontologyManager;if(!a)throw new Error("featureTypeOntology is undefined");if(n.looksLikeGene){const t=1==n.strand?e.geneTrackRowNums[0]:e.geneTrackRowNums[1];l.get(t)||l.set(t,[]);const o=l.get(t);o?.push({rowNum:t,feature:n,cds:null});const{children:s}=n;if(!s)continue;for(const[,t]of s)if(a.isTypeOf(t.type,"transcript")){const{cdsLocations:n,strand:o,children:s}=t;if(s)for(const[,t]of s){if(!a.isTypeOf(t.type,"exon"))continue;const n=1==t.strand?e.geneTrackRowNums[0]:e.geneTrackRowNums[1],o=l.get(n);o?.push({rowNum:n,feature:t,cds:null})}for(const a of n)for(const n of a){let a=r.getFrame(n.min,n.max,o??1,n.phase);a=e.featureLabelSpacer(a<0?-1*a+5:a),l.get(a)||l.set(a,[]);const s=l.get(a);s?.push({rowNum:a,feature:t,cds:n})}}}}return l}))},getFeatureLayoutPosition(e){const{featureLayouts:t}=this;for(const[n,a]of t.entries())for(const[,t]of a)for(const{feature:a}of t)if(e._id===a._id)return{layoutIndex:n,layoutRow:0,featureRow:0}}}))).views((e=>({get highestRow(){return 5}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(e.lgv.initialized&&!e.regionCannotBeRendered())for(const t of e.regions){const n=e.session.apolloDataStore.assemblies.get(t.assemblyName),a=n?.getByRefName(t.refName),o=a?.features;if(o)for(const[,n]of o)r.doesIntersect2(t.start,t.end,n.min,n.max)&&!e.seenFeatures.has(n._id)&&e.addSeenFeature(n)}}),{name:"LinearApolloSixFrameDisplaySetSeenFeatures",delay:1e3}))}})))}(0,t).named("LinearApolloSixFrameDisplayRendering").props({sequenceRowHeight:15,apolloRowHeight:20,detailsMinHeight:200,detailsHeight:200,lastRowTooltipBufferHeight:80,isShown:!0,filteredTranscripts:i.types.array(i.types.string)}).volatile((()=>({canvas:null,overlayCanvas:null,collaboratorCanvas:null,theme:void 0}))).views((e=>({get featuresHeight(){return(e.highestRow+1)*e.apolloRowHeight*(e.showFeatureLabels?2:1)+e.lastRowTooltipBufferHeight}}))).actions((e=>({toggleShown(){e.isShown=!e.isShown},setDetailsHeight(t){e.detailsHeight=e.isShown?Math.max(Math.min(t,e.height-100),Math.min(e.height,e.detailsMinHeight)):t},setCanvas(t){e.canvas=t},setOverlayCanvas(t){e.overlayCanvas=t},setCollaboratorCanvas(t){e.collaboratorCanvas=t},setTheme(t){e.theme=t},afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.collaboratorCanvas?.getContext("2d");if(t){t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);for(const n of e.session.collaborators){const{locations:a}=n;if(0===a.length)continue;let o=0;for(const r of e.lgv.displayedRegions){for(const l of a){if(l.refSeq!==r.refName)continue;const{end:a,refSeq:s,start:i}=l,c=e.lgv.bpToPx({refName:s,coord:i,regionNumber:o});if(!c)continue;const u=c.offsetPx-e.lgv.offsetPx,d=(a-i)/e.lgv.bpPerPx;t.fillStyle="rgba(0,255,0,.2)",t.fillRect(u,1,d,100),t.fillStyle="black",t.fillText(n.name,u+1,11,d-2)}o++}}}}),{name:"LinearApolloSixFrameDisplayRenderCollaborators"}))}})))}(0,t);return n.actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{const{canvas:t,featureLayouts:n,featuresHeight:a,lgv:o}=e;if(!o.initialized||e.regionCannotBeRendered())return;const{displayedRegions:l,dynamicBlocks:s}=o,i=t?.getContext("2d");if(i){i.clearRect(0,0,s.totalWidthPx,a);for(const[t,a]of n.entries()){const n=l[t];for(const[o,l]of a.entries())for(const{feature:a}of l){if(!a.looksLikeGene)continue;if(!r.doesIntersect2(n.start,n.end,a.min,a.max))continue;const{topLevelFeature:l}=a,s=e.getGlyph(l);void 0!==s&&s.draw(i,l,o,e,t)}}}}),{name:"LinearApolloSixFrameDisplayRenderFeatures"}))}})))}(0,t).named("LinearApolloSixFrameDisplayMouseEvents").volatile((()=>({apolloDragging:null,cursor:void 0,apolloHover:void 0}))).views((e=>({getMousePosition(t){const n=function(e,t){const n=e.currentTarget,{clientX:a,clientY:o}=e,{left:r,top:l}=n.getBoundingClientRect(),s=a-r,i=o-l,{coord:c,index:u,refName:d}=t.pxToBp(s);return{x:s,y:i,refName:d,bp:c,regionNumber:u}}(t,e.lgv),{bp:a,regionNumber:o,y:r}=n,l=Math.floor(r/e.apolloRowHeight)+1,s=e.featureLayouts[o].get(l);if(!s)return n;let i;if(e.geneTrackRowNums.includes(l)?(i=s.find((e=>"exon"==e.feature.type&&a>=e.feature.min&&a<=e.feature.max)),i||(i=s.find((e=>a>=e.feature.min&&a<=e.feature.max)))):i=s.find((t=>{const n=t.feature.attributes.get("gff_id")?.toString();return null!=t.cds&&a>=t.cds.min&&a<=t.cds.max&&(void 0===n||!e.filteredTranscripts.includes(n))})),!i)return n;const{feature:c,cds:u}=i,{topLevelFeature:d}=c,f=e.getGlyph(c);return{...n,featureAndGlyphUnderMouse:{cds:u,feature:c,topLevelFeature:d,glyph:f}}}}))).actions((e=>({continueDrag(t,n){if(!e.apolloDragging)throw new Error("continueDrag() called with no current drag in progress");n.stopPropagation(),e.apolloDragging={...e.apolloDragging,current:t}},setDragging(t){e.apolloDragging=t??null}}))).actions((e=>({setApolloHover(t){e.apolloHover=t},setCursor(t){e.cursor!==t&&(e.cursor=t)},updateFilteredTranscripts(t){e.filteredTranscripts=i.cast(t)}}))).actions((()=>({onClick(){}})))}(0,n);return l.views((e=>({contextMenuItems(t){const{apolloHover:n}=e;if(!n||!t)return[];const{topLevelFeature:a}=n;return e.getGlyph(a).getContextMenuItems(e)}}))).actions((e=>({startDrag(t,n,a,o=!1){e.apolloDragging={start:t,current:t,feature:n,edge:a,shrinkParent:o}},endDrag(){if(!e.apolloDragging)throw new Error("endDrag() called with no current drag in progress");const{current:n,edge:a,feature:o,start:r,shrinkParent:l}=e.apolloDragging;if(Math.abs(n.x-r.x)<=4)return e.setDragging(),void e.setCursor();const{displayedRegions:s}=e.lgv,i=e.getAssemblyId(s[r.regionNumber].assemblyName),c=Je(o,n.bp,a,l),u="max"===a?new t.LocationEndChange({typeName:"LocationEndChange",changedIds:c.map((e=>e.featureId)),changes:c.map((e=>({featureId:e.featureId,oldEnd:e.oldLocation,newEnd:e.newLocation}))),assembly:i}):new t.LocationStartChange({typeName:"LocationStartChange",changedIds:c.map((e=>e.featureId)),changes:c.map((e=>({featureId:e.featureId,oldStart:e.oldLocation,newStart:e.newLocation}))),assembly:i});e.changeManager.submit(u),e.setDragging(),e.setCursor()}}))).actions((e=>({onMouseDown(t){const n=e.getMousePosition(t);Ao(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseDown(e,n,t)},onMouseMove(t){const n=e.getMousePosition(t);if(e.apolloDragging)return e.setCursor("col-resize"),void e.continueDrag(n,t);Ao(n)?n.featureAndGlyphUnderMouse.glyph.onMouseMove(e,n,t):(e.setApolloHover(),e.setCursor())},onMouseLeave(t){e.setDragging(),e.setApolloHover();const n=e.getMousePosition(t);Ao(n)&&n.featureAndGlyphUnderMouse.glyph.onMouseLeave(e,n,t)},onMouseUp(t){const n=e.getMousePosition(t);Ao(n)?n.featureAndGlyphUnderMouse.glyph.onMouseUp(e,n,t):e.setSelectedFeature(),e.apolloDragging&&e.endDrag()}}))).actions((e=>({afterAttach(){i.addDisposer(e,s.autorun((()=>{if(!e.lgv.initialized||e.regionCannotBeRendered())return;const t=e.overlayCanvas?.getContext("2d");if(!t)return;t.clearRect(0,0,e.lgv.dynamicBlocks.totalWidthPx,e.featuresHeight);const{apolloDragging:n,apolloHover:a}=e;if(!a)return;const{glyph:o}=a;o.drawHover(e,t),o.drawTooltip(e,t),n&&e.getGlyph(n.feature.topLevelFeature).drawDragPreview(e,t)}),{name:"LinearApolloSixFrameDisplayRenderMouseoverAndDrag"}))}})))}(0,n).props({tabularEditor:i.types.optional(wa,{})}).named("LinearApolloSixFrameDisplay")}const Do=a.ConfigurationSchema("ApolloPlugin",{ontologies:i.types.array(Ct),featureTypeOntologyName:{description:"Name of the feature type ontology",type:"string",defaultValue:"Sequence Ontology"},hasRole:{description:"Flag used internally by jbrowse-plugin-apollo",type:"boolean",defaultValue:!1}}),ko=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"gene")||n.isTypeOf(e.type,"transcript")||n.isTypeOf(e.type,"pseudogene")||n.isTypeOf(e.type,"pseudogenic_transcript")},No=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"gene")||n.isTypeOf(e.type,"pseudogene")},Io=(e,t)=>{const{featureTypeOntology:n}=t.apolloDataStore.ontologyManager;if(!n)throw new Error("featureTypeOntology is undefined");return n.isTypeOf(e.type,"transcript")||n.isTypeOf(e.type,"pseudogenic_transcript")};function Ro(e){const{attributes:t}=e,n=["gene_name","gene_id","gene_stable_id"];for(const e of n){const n=t?.[e];if(n?.[0])return n[0]}return""}const Mo=e=>{const t=function(e){const{attributes:t}=e,n=["name","gff_name","transcript_name","gene_name"];for(const e of n){const n=t?.[e];if(n?.[0])return n[0]}return""}(e),n=function(e){const{attributes:t}=e,n=["id","gff_id","transcript_id","gene_id","gene_stable_id","stable_id"];for(const e of n){const n=t?.[e];if(n?.[0])return n[0]}return""}(e);return t?`${e.type} - ${t}`:n?`${e.type} - ${n}`:e.type};function Lo({annotationFeature:e,assembly:n,handleClose:a,refSeqId:o,session:r,region:l}){const s=r,{featureTypeOntology:c}=s.apolloDataStore.ontologyManager,u=y.useMemo((()=>Object.keys(e.children??{})),[e]),[d,f]=y.useState(!0),[m,g]=y.useState(u),[h,b]=y.useState(""),[S,w]=y.useState([]),[E,v]=y.useState(!1),[C,x]=y.useState(),T=s.apolloDataStore.assemblies.get(n.name),A=T?.refSeqs.get(o),F=A?.getFeatures(l.start,l.end),D=()=>{const t=[];for(const n of F??[])if(!(n.min>l.end||n.max<l.start)&&c?.isTypeOf(n.type,"gene")&&n.strand===e.strand){const e=i.getSnapshot(n);t.push(e)}return t};y.useEffect((()=>{b("");const e=D();w(e),x(e[0])}),[m,d,l]);const k=async e=>{if(C)for(const a of Object.keys(e)){const o=new t.AddFeatureChange({parentFeatureId:C._id,changedIds:[C._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:e[a]});await R(o)}},N=async a=>{const r=(new ue.default).toHexString(),l=Math.min(...Object.values(a).map((e=>e.min))),s=Math.max(...Object.values(a).map((e=>e.max))),i=new t.AddFeatureChange({changedIds:[r],typeName:"AddFeatureChange",assembly:n.name,addedFeature:{_id:r,refSeq:o,min:l,max:s,strand:e.strand,type:"gene",children:a,attributes:{name:[Ro(e)],gene_name:[Ro(e)]}}});await R(i)},I=async(e,a)=>{if(!C)return;const o=[];e!==C.min&&o.push(new t.LocationStartChange({typeName:"LocationStartChange",changedIds:[C._id],featureId:C._id,assembly:n.name,oldStart:C.min,newStart:e})),a!==C.max&&o.push(new t.LocationEndChange({typeName:"LocationEndChange",changedIds:[C._id],featureId:C._id,assembly:n.name,oldEnd:C.max,newEnd:a}));for(const e of o)await R(e)},R=async e=>{await s.apolloDataStore.changeManager.submit(e)};return de.default.createElement(Ke,{open:!0,title:"Create Apollo Annotation",handleClose:a,fullWidth:!0,maxWidth:"sm"},de.default.createElement(p.DialogTitle,{fontSize:15},"Select the feature to be copied to apollo track"),de.default.createElement(p.DialogContent,null,de.default.createElement(p.Box,{sx:{ml:3}},ko(e,s)&&de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{size:"small",checked:d,onChange:e=>{const t=e.target.checked;f(t),g(t?u:[])}}),label:`${Mo(e)} (${e.min+1}..${e.max})`}),e.children&&de.default.createElement(p.Box,{sx:{display:"flex",flexDirection:"column",ml:3}},Object.values(e.children).filter((e=>Io(e,s))).map((e=>de.default.createElement(p.FormControlLabel,{key:e._id,control:de.default.createElement(p.Checkbox,{size:"small",checked:m.includes(e._id),onChange:t=>{((e,t)=>{g((n=>e.target.checked?[...n,t._id]:n.filter((e=>e!==t._id))))})(t,e)}}),label:`${Mo(e)} (${e.min+1}..${e.max})`}))))),S.length>0&&(!d&&m.length>0||d&&Io(e,s))&&de.default.createElement("div",{style:{border:"1px solid #ccc",marginTop:20,padding:10,borderRadius:5}},de.default.createElement(p.Box,{sx:{ml:3}},de.default.createElement(p.Typography,{variant:"caption",fontSize:12},"Select the destination feature to copy the selected features"),de.default.createElement(p.Box,{sx:{mt:1}},de.default.createElement(p.Select,{labelId:"label",style:{width:"100%"},value:C?._id??"",onChange:e=>{const t=S.find((t=>t._id===e.target.value));x(t)},disabled:E},S.map((e=>de.default.createElement(p.MenuItem,{key:e._id,value:e._id},`${Mo(e)} (${e.min+1}..${e.max})`)))))),de.default.createElement(p.Box,{sx:{ml:3}},de.default.createElement(p.FormGroup,null,de.default.createElement(p.FormControlLabel,{control:de.default.createElement(p.Checkbox,{checked:E,onChange:e=>{v(e.target.checked)}}),label:"Create new gene"}))))),de.default.createElement(p.DialogActions,null,de.default.createElement(p.Button,{variant:"contained",type:"submit",disabled:0===m.length||!d&&m.length>0&&!C,onClick:async()=>{if(d){if(No(e,s)&&(await(async()=>{let a;if(e.children&&m.length!==Object.values(e.children).length){const o={};for(const t of m)o[t]=e.children[t];a=new t.AddFeatureChange({changedIds:[e._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:{...e,children:o}})}else a=new t.AddFeatureChange({changedIds:[e._id],typeName:"AddFeatureChange",assembly:n.name,addedFeature:e});await R(a)})(),r.notify("Successfully copied selected gene and transcript(s)","success")),Io(e,s))if(C&&!E){const t={};if(t[e._id]=e,C.max<e.max||C.min>e.min){const n=Math.min(C.min,e.min),a=Math.max(C.max,e.max);await I(n,a),await k(t)}else await k(t);r.notify("Successfully copied selected transcripts to destination gene","success")}else{const t={};t[e._id]=e,await N(t),r.notify("Successfully created a new gene with selected transcripts","success")}}else{if(!e.children)return;if(C&&!E){const t={};for(const n of m)t[n]=e.children[n];const n=Math.min(...Object.values(t).map((e=>e.min))),a=Math.max(...Object.values(t).map((e=>e.max)));if(C.min>n||C.max<a){const e=Math.min(C.min,n),o=Math.max(C.max,a);await I(e,o),await k(t)}else await k(t);r.notify("Successfully copied transcript to destination gene","success")}else{const t={};for(const n of m)t[n]=e.children[n];await N(t),r.notify("Successfully created a new gene with selected transcript","success")}}a()}},"Create"),de.default.createElement(p.Button,{variant:"outlined",type:"submit",onClick:a},"Cancel")),h?de.default.createElement(p.DialogContent,null,de.default.createElement(p.DialogContentText,{color:"error"},h)):null)}function Po(e){if("LinearPileupDisplay"!==e.name)return e;const{stateModel:t}=e,n=t.views((e=>({getFirstRegion:()=>r.getContainingView(e).dynamicBlocks.contentBlocks[0],getAssembly(){const t=e.getFirstRegion(),n=r.getSession(e),{assemblyManager:a}=n,{assemblyName:o}=t,l=a.get(o);if(!l)throw new Error(`Could not find assembly named ${o}`);return l},getRefSeqId(t){const n=e.getFirstRegion(),{refName:a}=n,{refNameAliases:o}=t;if(!o)throw new Error(`Could not find aliases for ${t.name}`);const r=[...Object.entries(o)].filter((([e,t])=>e!==t)).map((([e,t])=>({_id:e,name:t}))),l=r.find((e=>e.name===a))?._id;if(!l)throw new Error(`Could not find refSeqId named ${a}`);return l},getAnnotationFeature(){const t=e.contextMenuFeature,n=e.getAssembly(),a=e.getRefSeqId(n),o=t.get("start"),r=t.get("end"),l=t.get("strand"),s=t.get("name"),i=function(e){const t=/(\d+)([MIDNSHPX=])/g,n=[];let a;for(;null!==(a=t.exec(e));)n.push([a[2],Number.parseInt(a[1],10)]);return n}(t.get("CIGAR"));let c,u=o;const d=[];for(const[e,t]of i)switch(e){case"M":case"=":case"X":void 0===c&&(c=u),u+=t;break;case"N":void 0!==c&&(d.push({start:c,end:u}),c=void 0),u+=t;break;case"D":u+=t;break;case"I":case"S":case"H":case"P":break;default:throw new Error(`Unknown CIGAR operation: ${e}`)}void 0!==c&&d.push({start:c,end:u});const f={_id:ue.default().toHexString(),refSeq:a,min:o,max:r,type:"mRNA",strand:l,attributes:{name:[s]}};if(0===d.length)return f;f.children={};for(const e of d){const t={_id:ue.default().toHexString(),refSeq:a,min:e.start,max:e.end,type:"exon",strand:l};f.children[t._id]=t}return f}}))).views((e=>{const t=e.contextMenuItems;return{contextMenuItems(){const n=r.getSession(e),a=e.getAssembly(),o=e.getFirstRegion();return e.contextMenuFeature?[...t(),{label:"Create Apollo annotation",icon:oe.default,onClick:()=>{n.queueDialog((t=>[Lo,{session:n,handleClose:()=>{t()},annotationFeature:e.getAnnotationFeature(a),assembly:a,refSeqId:e.getRefSeqId(a),region:o}]))}}]:t()}}}));return e.stateModel=n,e}function qo(e,t){const n=JSON.parse(JSON.stringify(e)),a=n.subfeatures;return[{start:n.start+1,end:n.end,seq_id:t,source:n.source??null,type:n.type??null,score:n.score??null,strand:n.strand?1===n.strand?"+":"-":null,phase:null!==n.phase||void 0!==n.phase?n.phase:null,attributes:_o(n),derived_features:[],child_features:a?a.map((e=>qo(e,t))):[]}]}function Oo(e,n){return t.gff3ToAnnotationFeature(qo(e,n))}function _o(e){const t={},n=new Set(["start","end","type","strand","refName","subfeatures","derived_features","phase","source","score"]);for(const[a,o]of Object.entries(e))n.has(a)||(t[a]=Array.isArray(o)?o.map(String):[String(o)]);return t}function Bo(e){if("LinearBasicDisplay"!==e.name)return e;const{stateModel:t}=e,n=t.views((e=>({getFirstRegion:()=>r.getContainingView(e).dynamicBlocks.contentBlocks[0],getAssembly(){const t=e.getFirstRegion(),n=r.getSession(e),{assemblyManager:a}=n,{assemblyName:o}=t,l=a.get(o);if(!l)throw new Error(`Could not find assembly named ${o}`);return l},getRefSeqId(t){const n=e.getFirstRegion(),{refName:a}=n,{refNameAliases:o}=t;if(!o)throw new Error(`Could not find aliases for ${t.name}`);const r=[...Object.entries(o)].filter((([e,t])=>e!==t)).map((([e,t])=>({_id:e,name:t}))),l=r.find((e=>e.name===a))?._id;if(!l)throw new Error(`Could not find refSeqId named ${a}`);return l},getAnnotationFeature(t){const n=e.getRefSeqId(t);return Oo(e.contextMenuFeature.data,n)}}))).views((e=>{const t=e.contextMenuItems;return{contextMenuItems(){const n=r.getSession(e),a=e.getAssembly(),o=e.getFirstRegion();return e.contextMenuFeature?[...t(),{label:"Create Apollo annotation",icon:oe.default,onClick:()=>{n.queueDialog((t=>[Lo,{session:n,handleClose:()=>{t()},annotationFeature:e.getAnnotationFeature(a),assembly:a,refSeqId:e.getRefSeqId(a),region:o}]))}}]:t()}}}));return e.stateModel=n,e}const Uo=b.makeStyles()((e=>({canvasContainer:{position:"relative",left:0},canvas:{position:"absolute",left:0},ellipses:{textOverflow:"ellipsis",overflow:"hidden"},avatar:{position:"absolute",color:e.palette.warning.light,backgroundColor:e.palette.warning.contrastText},loading:{position:"absolute",right:e.spacing(3),zIndex:10,pointerEvents:"none",textAlign:"right"}}))),$o=E.observer((function(e){const t=p.useTheme(),{model:n}=e,{loading:a,apolloDragging:o,apolloRowHeight:l,contextMenuItems:s,cursor:i,featuresHeight:c,isShown:u,onMouseDown:d,onMouseLeave:f,onMouseMove:m,onMouseUp:g,regionCannotBeRendered:h,session:b,setCanvas:w,setCollaboratorCanvas:E,setOverlayCanvas:v,setSeqTrackCanvas:C,setSeqTrackOverlayCanvas:x,setTheme:T}=n,{classes:A}=Uo(),F=r.getContainingView(n);y.useEffect((()=>{T(t)}),[t,T]);const[D,k]=y.useState(),[N,I]=y.useState([]),R=h();if(!u)return null;const{assemblyManager:M}=b;return de.default.createElement(de.default.Fragment,null,3/F.bpPerPx>=1?de.default.createElement("div",{className:A.canvasContainer,style:{width:F.dynamicBlocks.totalWidthPx,height:F.bpPerPx<=1?125:95}},de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),C(e)},width:F.dynamicBlocks.totalWidthPx,height:F.bpPerPx<=1?125:95,className:A.canvas,"data-testid":"seqTrackCanvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),x(e)},width:F.dynamicBlocks.totalWidthPx,height:F.bpPerPx<=1?125:95,className:A.canvas,"data-testid":"seqTrackOverlayCanvas"})):null,de.default.createElement("div",{className:A.canvasContainer,style:{width:F.dynamicBlocks.totalWidthPx,height:c},onContextMenu:e=>{e.preventDefault(),N.length>0?I([]):(k([e.clientX,e.clientY]),I(s(e)))}},a?de.default.createElement("div",{className:A.loading},de.default.createElement(p.CircularProgress,{size:"18px"})):null,R?de.default.createElement(p.Alert,{severity:"warning",classes:{message:A.ellipses}},de.default.createElement(p.Tooltip,{title:R},de.default.createElement("div",null,R))):de.default.createElement(de.default.Fragment,null,de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),E(e)},width:F.dynamicBlocks.totalWidthPx,height:c,className:A.canvas,"data-testid":"collaboratorCanvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),w(e)},width:F.dynamicBlocks.totalWidthPx,height:c,className:A.canvas,"data-testid":"canvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),v(e)},width:F.dynamicBlocks.totalWidthPx,height:c,onMouseMove:m,onMouseLeave:f,onMouseDown:d,onMouseUp:g,className:A.canvas,style:{cursor:i??"default"},"data-testid":"overlayCanvas"}),F.displayedRegions.flatMap(((e,t)=>{const a=M.get(e.assemblyName);return[...b.apolloDataStore.checkResults.values()].filter((t=>a?.isValidRefName(t.refSeq)&&a.getCanonicalRefName(t.refSeq)===e.refName&&r.doesIntersect2(e.start,e.end,t.start,t.end))).map((a=>{const r=(F.bpToPx({refName:e.refName,coord:a.start,regionNumber:t})?.offsetPx??0)-F.offsetPx,[s]=a.ids;if(!s)return null;let i=0;const c=n.getFeatureLayoutPosition(s);return c&&(i=c.layoutRow+c.featureRow),de.default.createElement(p.Tooltip,{key:a._id,title:a.message},de.default.createElement(p.Avatar,{className:A.avatar,style:{top:i*l,left:r,height:l,width:l,pointerEvents:o?"none":"auto"}},de.default.createElement(Le.default,{"data-testid":"ErrorIcon"})))}))})),de.default.createElement(S.Menu,{open:N.length>0,onMenuItemClick:(e,t)=>{t(),I([])},onClose:()=>{I([])},TransitionProps:{onExit:()=>{I([])}},anchorReference:"anchorPosition",anchorPosition:D?{top:D[1],left:D[0]}:void 0,style:{zIndex:t.zIndex.tooltip},menuItems:N}))))})),Go=E.observer((function({model:e,hrStyle:t={margin:0,top:0,color:"black"},idx:n=0}){const{apolloRowHeight:a,highestRow:o,showFeatureLabels:r}=e,l=r?2:1;return de.default.createElement("div",{style:{position:"absolute",left:0,top:a*l*(o+1)/2+n*l*a,width:"100%"}},de.default.createElement("hr",{style:t}))})),jo=b.makeStyles()((e=>({canvasContainer:{position:"relative",left:0},canvas:{position:"absolute",left:0},ellipses:{textOverflow:"ellipsis",overflow:"hidden"},avatar:{position:"absolute",color:e.palette.warning.light,backgroundColor:e.palette.warning.contrastText}}))),Wo=E.observer((function(e){const t=p.useTheme(),{model:n}=e,{apolloRowHeight:a,contextMenuItems:o,cursor:l,featuresHeight:s,isShown:i,onMouseDown:c,onMouseLeave:u,onMouseMove:d,onMouseUp:f,regionCannotBeRendered:m,session:g,setCanvas:h,setCollaboratorCanvas:b,setOverlayCanvas:w,setTheme:E}=n,{classes:v}=jo(),C=r.getContainingView(n);y.useEffect((()=>{E(t)}),[t,E]);const[x,T]=y.useState(),[A,F]=y.useState([]),D=m();if(!i)return null;const{assemblyManager:k}=g;return de.default.createElement(de.default.Fragment,null,de.default.createElement("div",{className:v.canvasContainer,style:{width:C.dynamicBlocks.totalWidthPx,height:s},onContextMenu:e=>{if(e.preventDefault(),A.length>0)F([]);else{const t=[e.clientX,e.clientY];T(t),F(o(t))}}},D?de.default.createElement(p.Alert,{severity:"warning",classes:{message:v.ellipses}},de.default.createElement(p.Tooltip,{title:D},de.default.createElement("div",null,D))):de.default.createElement(de.default.Fragment,null,de.default.createElement(Go,{model:n,idx:0}),de.default.createElement(Go,{model:n,hrStyle:{margin:0,top:0,color:"grey",opacity:.4},idx:1}),de.default.createElement(Go,{model:n,idx:2}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),b(e)},width:C.dynamicBlocks.totalWidthPx,height:s,className:v.canvas,"data-testid":"collaboratorCanvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),h(e)},width:C.dynamicBlocks.totalWidthPx,height:s,className:v.canvas,"data-testid":"canvas"}),de.default.createElement("canvas",{ref:async e=>{await Promise.resolve(),w(e)},width:C.dynamicBlocks.totalWidthPx,height:s,onMouseMove:d,onMouseLeave:u,onMouseDown:c,onMouseUp:f,className:v.canvas,style:{cursor:l??"default"},"data-testid":"overlayCanvas"}),C.displayedRegions.flatMap(((e,t)=>{const n=k.get(e.assemblyName);return[...g.apolloDataStore.checkResults.values()].filter((t=>n?.isValidRefName(t.refSeq)&&n.getCanonicalRefName(t.refSeq)===e.refName&&r.doesIntersect2(e.start,e.end,t.start,t.end))).map((n=>{const o=(C.bpToPx({refName:e.refName,coord:n.start,regionNumber:t})?.offsetPx??0)-C.offsetPx,[r]=n.ids;return r&&r.parent?.looksLikeGene?de.default.createElement(p.Tooltip,{key:n._id,title:n.message},de.default.createElement(p.Avatar,{className:v.avatar,style:{top:0,left:o,height:a,width:a}},de.default.createElement(Le.default,null))):null}))})),de.default.createElement(S.Menu,{open:A.length>0,onMenuItemClick:(e,t)=>{t(),F([])},onClose:()=>{F([])},TransitionProps:{onExit:()=>{F([])}},anchorReference:"anchorPosition",anchorPosition:x?{top:x[1],left:x[0]}:void 0,style:{zIndex:t.zIndex.tooltip},menuItems:A}))))})),Ho=b.makeStyles()((e=>({shading:{background:p.alpha(e.palette.primary.main,.2),overflowY:"scroll",overflowX:"hidden"},details:{background:e.palette.background.paper},accordionControl:{height:12,width:"100%","&:hover":{background:e.palette.action.hover},display:"flex",alignItems:"center",justifyContent:"center"},accordionRoot:{background:e.palette.divider},resizeHandle:{width:"100%",height:4,position:"absolute",cursor:"row-resize",zIndex:100},expandIcon:{},title:{userSelect:"none"},alertContainer:{display:"flex",alignItems:"center",justifyContent:"center"}})));function zo(e,t){const{apolloRowHeight:n,selectedFeature:a}=e;if(t.current&&a){const o=e.getFeatureLayoutPosition(a);o&&t.current.scroll({top:(o.layoutRow+o.featureRow)*n,behavior:"smooth"})}}const Jo=({onResize:e})=>{const{classes:t}=Ho(),n=y.useCallback((t=>{t.stopPropagation(),t.preventDefault(),e(t.movementY)}),[e]),a=y.useCallback((e=>{e.stopPropagation(),e.preventDefault(),globalThis.removeEventListener("mousemove",n),globalThis.removeEventListener("mouseup",a),globalThis.removeEventListener("mouseleave",a)}),[n]);return de.default.createElement("div",{onMouseDown:e=>{e.stopPropagation(),globalThis.addEventListener("mousemove",n),globalThis.addEventListener("mouseup",a),globalThis.addEventListener("mouseleave",a)},onClick:e=>{e.stopPropagation(),e.preventDefault()},className:t.resizeHandle})},Vo=E.observer((function({onClick:e,onResize:t,open:n,title:a}){const{classes:o}=Ho();return de.default.createElement("div",{className:o.accordionRoot},n&&t?de.default.createElement(Jo,{onResize:t}):null,de.default.createElement("div",{className:o.accordionControl,onClick:e},de.default.createElement(n?Me.default:Ce.default,{className:o.expandIcon}),a?de.default.createElement(p.Typography,{className:o.title,variant:"caption",component:"span"},a):null))})),Xo=E.observer((function({model:e,...t}){const n=r.getSession(e),{ontologyManager:a}=n.apolloDataStore,{featureTypeOntology:o}=a,l=o?.dataStore,{classes:s}=Ho(),{graphical:i,height:c,isShown:u,selectedFeature:d,table:f,tabularEditor:m,toggleShown:g}=e,h=y.useRef(null);y.useEffect((()=>{zo(e,h)}),[e,d]);const b=t=>{e.setDetailsHeight(e.detailsHeight-t)};if(!l)return de.default.createElement("div",{className:s.alertContainer},de.default.createElement(p.Alert,{severity:"error"},"Could not load feature type ontology."));if(i&&f){const n=m.isShown?e.detailsHeight:0,a=u?c-e.detailsHeight-24:0;return de.default.createElement("div",{style:{height:c}},de.default.createElement(Vo,{open:u,title:"Graphical",onClick:g}),de.default.createElement("div",{className:s.shading,ref:h,style:{height:a}},de.default.createElement($o,{model:e,...t})),de.default.createElement(Vo,{title:"Table",open:m.isShown,onClick:m.togglePane,onResize:b}),de.default.createElement("div",{className:s.details,style:{height:n}},de.default.createElement(Sa,{model:e})))}return i?de.default.createElement("div",{className:s.shading,ref:h,style:{height:c}},de.default.createElement($o,{model:e,...t})):de.default.createElement("div",{className:s.details,style:{height:c}},de.default.createElement(Sa,{model:e}))})),Ko=E.observer((function({model:e,...t}){const n=r.getSession(e),{ontologyManager:a}=n.apolloDataStore,{featureTypeOntology:o}=a,l=o?.dataStore,{classes:s}=Ho(),{detailsHeight:i,graphical:c,height:u,isShown:d,selectedFeature:f,table:m,tabularEditor:g,toggleShown:h}=e,b=y.useRef(null);y.useEffect((()=>{zo(e,b)}),[e,f]);const S=t=>{e.setDetailsHeight(i-t)};if(!l)return de.default.createElement("div",{className:s.alertContainer},de.default.createElement(p.Alert,{severity:"error"},"Could not load feature type ontology."));if(c&&m){const n=g.isShown?i:0,a=d?u-i-24:0;return de.default.createElement("div",{style:{height:u}},de.default.createElement(Vo,{open:d,title:"Graphical",onClick:h}),de.default.createElement("div",{className:s.shading,ref:b,style:{height:a}},de.default.createElement(Wo,{model:e,...t})),de.default.createElement(Vo,{title:"Table",open:g.isShown,onClick:g.togglePane,onResize:S}),de.default.createElement("div",{className:s.details,style:{height:n}},de.default.createElement(Sa,{model:e})))}return c?de.default.createElement("div",{className:s.shading,ref:b,style:{height:u}},de.default.createElement(Wo,{model:e,...t})):de.default.createElement("div",{className:s.details,style:{height:u}},de.default.createElement(Sa,{model:e}))})),Yo=i.types.model("JobsManager",{}).views((e=>({get jobStatusWidget(){const{widgets:t}=r.getSession(e);let n=t.get("JobsList");return n||(n=r.getSession(e).addWidget("JobsListWidget","JobsList")),n}}))).actions((e=>({update(t,n,a){e.jobStatusWidget.updateJobStatusMessage(t,n),a&&e.jobStatusWidget.updateJobProgressPct(t,a)},abortJob(t,n){const a=r.getSession(e);if(r.isSessionModelWithWidgets(a)){a.showWidget(e.jobStatusWidget),e.jobStatusWidget.updateJobStatusMessage(t,n??"Aborted unexpectedly");const o=e.jobStatusWidget.jobs.findIndex((e=>e.name===t));e.jobStatusWidget.addAbortedJob({...e.jobStatusWidget.jobs[o]}),e.jobStatusWidget.removeJob(t),a.notify("Job aborted","info")}},runJob(t){const n=r.getSession(e);r.isSessionModelWithWidgets(n)&&(n.showWidget(e.jobStatusWidget),e.jobStatusWidget.addJob(t))},done(t){const n=r.getSession(e);r.isSessionModelWithWidgets(n)&&(n.showWidget(e.jobStatusWidget),e.jobStatusWidget.removeJob(t.name),e.jobStatusWidget.addFinishedJob({name:t.name,statusMessage:"All operations successful",progressPct:100,cancelCallback:t.cancelCallback}))}})));class Zo{clientStore;constructor(e){this.clientStore=e}}class Qo{dataStore;constructor(e){this.dataStore=e}recentChanges=[];async submit(n,a={}){const{addToRecents:o=!0,submitToBackend:l=!0,updateJobsManager:s=!1}=a,i=r.getSession(this.dataStore),c=new AbortController,{jobsManager:u}=r.getSession(this.dataStore),d={name:n.typeName,statusMessage:"Pre-validating",progressPct:0,cancelCallback:()=>{c.abort()}};s&&u.runJob(d);const f=await t.validationRegistry.frontendPreValidate(n);if(!f.ok){const e=`Pre-validation failed: "${f.resultsMessages}"`;return s&&u.abortJob(d.name,e),void i.notify(e,"error")}try{await n.execute(this.dataStore)}catch(e){return s&&u.abortJob(d.name,String(e)),console.error(e),void i.notify(`Error encountered in client: ${String(e)}. Data may be out of sync, please refresh the page`,"error")}if((await t.validationRegistry.frontendPostValidate(n,this.dataStore)).ok||await this.revert(n),l){s&&u.update(d.name,"Submitting to driver");const{collaborationServerDriver:t,getBackendDriver:r}=this.dataStore,l=e.isAssemblySpecificChange(n)?r(n.assembly):t;let c;try{c=await l.submitChange(n,a)}catch(e){return s&&u.abortJob(d.name,String(e)),console.error(e),i.notify(String(e),"error"),void await this.revert(n,!1)}if(!c.ok){const e=`Post-validation failed: "${f.resultsMessages}"`;return s&&u.abortJob(d.name,e),i.notify(e,"error"),void await this.revert(n,!1)}n.notification&&i.notify(n.notification,"success"),o&&this.recentChanges.push(n)}s&&u.done(d)}async revert(e,t=!0){const n=e.getInverse();return this.submit(n,{submitToBackend:t,addToRecents:!1})}async revertLastChange(){const e=this.recentChanges.pop();if(e)return this.revert(e);r.getSession(this.dataStore).notify("No changes to undo!","warning")}}class er extends Zo{inFlight=new Map;async fetch(e,t,n){return e.getFetcher({locationType:"UriLocation",uri:t.toString()})(t,n)}async searchFeatures(e,t){const n=this.clientStore.getInternetAccount(t[0]),{baseURL:a}=n,o=new URL("features/searchFeatures",a),r=new URLSearchParams({assemblies:t.join(","),term:e});o.search=r.toString();const l=o.toString(),s=await this.fetch(n,l);if(!s.ok){const e=await Ve(s,"searchFeatures failed");throw new Error(e)}return s.json()}async getFeatures(e){const{assemblyName:t,end:n,refName:o,start:l}=e,{assemblyManager:s}=r.getSession(this.clientStore),i=s.get(t);if(!i)throw new Error(`Could not find assembly with name "${t}"`);const{ids:c}=a.getConf(i,["sequence","metadata"]),u=c[o];if(!u)throw new Error(`Could not find refSeq "${o}"`);const d=this.clientStore.getInternetAccount(t),{baseURL:f}=d,m=new URL("features/getFeatures",f),g=new URLSearchParams({refSeq:u,start:String(l),end:String(n)});m.search=g.toString();const p=m.toString(),h=await this.fetch(d,p);if(!h.ok){const e=await Ve(h,"getFeatures failed");throw new Error(e)}return this.checkSocket(t,o,d),h.json()}checkSocket(t,n,a){const{socket:o}=a,r=a.retrieveToken(),l=`${t}-${n}`,s=new Qo(this.clientStore);o.hasListeners(l)||o.on(l,(async t=>{if(a.setLastChangeSequenceNumber(Number(t.changeSequence)),t.userSessionId!==r&&t.channel===l){const n=e.Change.fromJSON(t.changeInfo);await s.submit(n,{submitToBackend:!1})}}))}async getSequence(e){const t=`${e.refName}:${e.start}-${e.end}`,n=this.inFlight.get(t),{assemblyName:o,end:l,refName:s,start:i}=e,{assemblyManager:c}=r.getSession(this.clientStore),u=c.get(o);if(!u)throw new Error(`Could not find assembly with name "${o}"`);const{ids:d}=a.getConf(u,["sequence","metadata"]),f=d[s];if(!f)throw new Error(`Could not find refSeq "${s}"`);if(n)return{seq:await n,refSeq:f};let m=this.clientStore.assemblies.get(o);m||(m=this.clientStore.addAssembly(o));let g=m.refSeqs.get(f);g||(g=m.addRefSeq(f,s));const p=g.getSequence(i,l);if(p.length===l-i)return{seq:p,refSeq:f};const h=this.clientStore.getInternetAccount(o),{baseURL:y}=h,b=new URL("sequence",y),S=new URLSearchParams({refSeq:f,start:String(i),end:String(l)});b.search=S.toString();const w=b.toString(),E=this.getSeqFromServer(h,w,g,i,l);this.inFlight.set(t,E);const v=await E;return this.checkSocket(o,s,h),this.inFlight.delete(t),{seq:v,refSeq:f}}async getSeqFromServer(e,t,n,a,o){const r=await this.fetch(e,t);if(!r.ok){let e;try{e=await r.text()}catch{e=""}throw new Error(`getSequence failed: ${r.status} (${r.statusText})${e?` (${e})`:""}`)}const l=await r.text();return n.addSequence({sequence:l,start:a,stop:o}),l}async getRefNameAliases(e){const{assemblyManager:t}=r.getSession(this.clientStore);if(!t.get(e))throw new Error(`Could not find assembly with name "${e}"`);const n=this.clientStore.getInternetAccount(e),{baseURL:a}=n,o=new URL("refSeqs",a),l=new URLSearchParams({assembly:e});o.search=l.toString();const s=o.toString(),i=await this.fetch(n,s);if(!i.ok){let e;try{e=await i.text()}catch{e=""}throw new Error(`getRefNameAliases failed: ${i.status} (${i.statusText})${e?` (${e})`:""}`)}return(await i.json()).map((e=>({refName:e.name,aliases:[e._id,...e.aliases],uniqueId:`alias-${e._id}`})))}async getRegions(e){const{assemblyManager:t}=r.getSession(this.clientStore);if(!t.get(e))throw new Error(`Could not find assembly with name "${e}"`);const n=this.clientStore.getInternetAccount(e),{baseURL:a}=n,o=new URL("refSeqs",a),l=new URLSearchParams({assembly:e});o.search=l.toString();const s=o.toString(),i=await this.fetch(n,s);if(!i.ok){let e;try{e=await i.text()}catch{e=""}throw new Error(`getRegions failed: ${i.status} (${i.statusText})${e?` (${e})`:""}`)}return(await i.json()).map((e=>({refName:e.name,start:0,end:e.length})))}getAssemblies(e){const{assemblyManager:t}=r.getSession(this.clientStore);return t.assemblies.filter((t=>{const n=a.getConf(t,["sequence","metadata"]);return!(!(n&&n.apollo&&n.internetAccountConfigId)||e&&n.internetAccountConfigId!==e)}))}async submitChange(e,n={}){const{internetAccountId:a}=n,o=this.clientStore.getInternetAccount("assembly"in e?e.assembly:void 0,a),{baseURL:r}=o,l=new URL("changes",r).href,s=await this.fetch(o,l,{method:"POST",body:JSON.stringify(e.toJSON()),headers:{"Content-Type":"application/json"}});if(!s.ok){const e=await Ve(s,"submitChange failed");throw new Error(e)}const i=new t.ValidationResultSet;return s.ok||(i.ok=!1),i}}class tr extends Zo{async getFeatures(){return[[],[]]}async getSequence(e){const{assemblyName:t,end:n,refName:a,start:o}=e,r=this.clientStore.assemblies.get(t);if(!r)return{seq:"",refSeq:a};const l=r.refSeqs.get(a);return l?{seq:l.getSequence(o,n),refSeq:a}:{seq:"",refSeq:a}}async getRefNameAliases(e){const t=this.clientStore.assemblies.get(e),n=[];if(!t)return n;for(const[,e]of t.refSeqs)n.push({refName:e.name,aliases:[e._id],uniqueId:`alias-${e._id}`});return n}async getRegions(e){const t=this.clientStore.assemblies.get(e);if(!t)return[];const n=[];for(const[,a]of t.refSeqs)n.push({assemblyName:e,refName:a.name,start:a.sequence[0].start,end:a.sequence[0].stop});return n}getAssemblies(){const{assemblyManager:e}=r.getSession(this.clientStore);return e.assemblies.filter((e=>{const t=a.getConf(e,["sequence","metadata"]);return Boolean(t&&t.apollo&&!t.file&&!t.internetAccountConfigId)}))}async submitChange(e,n={}){const{clientStore:a}=this,{assemblies:o}=a;a.clearCheckResults();for(const[,e]of o)if("InMemoryFileDriver"===e.backendDriverType){const t=await _e(e);a.addCheckResults(t)}return new t.ValidationResultSet}async searchFeatures(e,t){return[]}}class nr extends Zo{async loadAssembly(e){const{assemblyManager:t}=r.getSession(this.clientStore),n=t.get(e);if(!n)throw new Error(`Assembly ${e} not found`);const{file:o}=a.getConf(n,["sequence","metadata"]),l=require("node:fs");return Oe(e,await l.promises.readFile(o,"utf8"),this.clientStore)}async getAssembly(e){let t=this.clientStore.assemblies.get(e);return t||(t=await this.loadAssembly(e)),t}async getRefNameAliases(e){const t=await this.getAssembly(e),n=[];for(const[,e]of t.refSeqs)n.push({refName:e.name,aliases:[e._id],uniqueId:`alias-${e._id}`});return n}async getFeatures(e){return await this.getAssembly(e.assemblyName),[[],[]]}async getSequence(e){const{assemblyName:t,end:n,refName:a,start:o}=e,r=(await this.getAssembly(t)).refSeqs.get(a);if(!r)throw new Error(`refSeq ${a} not found in client data store`);return{seq:r.getSequence(o,n),refSeq:a}}async getRegions(e){const t=await this.getAssembly(e),n=[];for(const[,a]of t.refSeqs)n.push({assemblyName:e,refName:a.name,start:a.sequence[0].start,end:a.sequence[0].stop});return n}getAssemblies(){const{assemblyManager:e}=r.getSession(this.clientStore);return e.assemblies.filter((e=>{const t=a.getConf(e,["sequence","metadata"]);return Boolean(t&&t.apollo&&!t.internetAccountConfigId&&t.file)}))}async submitChange(n){if(!e.isAssemblySpecificChange(n))throw new Error(`Cannot use this type of change with local file: "${n.typeName}"`);const{assemblyManager:o}=r.getSession(this.clientStore),l=o.get(n.assembly);if(!l)throw new Error(`Could not find assembly with name "${n.assembly}"`);const{file:s}=a.getConf(l,["sequence","metadata"]),c=this.clientStore.assemblies.get(n.assembly);if(!c)throw new Error(`Could not find assembly in client with name "${n.assembly}"`);const u=new Set(...c.refSeqs.keys()),{checkResults:d}=this.clientStore;for(const e of d.values())u.has(e.refSeq)&&d.delete(e._id);const f=await _e(c);this.clientStore.addCheckResults(f);const m=[{directive:"gff-version",value:"3"}];for(const[,e]of c.refSeqs)m.push({directive:"sequence-region",value:`${e.name} 1 ${e.sequence[0].stop}`});for(const e of c.comments)m.push({comment:e});for(const[,e]of c.refSeqs){const{features:n}=e;for(const[,e]of n)m.push(t.annotationFeatureToGFF3(i.getSnapshot(e)))}for(const[,e]of c.refSeqs){const[n]=e.sequence,a=t.splitStringIntoChunks(n.sequence,80).join("\n");m.push({id:e.name,description:e.description,sequence:a})}const g=re.default.formatSync(m),p=require("node:fs");return await p.promises.writeFile(s,g,"utf8"),new t.ValidationResultSet}async searchFeatures(e,t){return[]}}function ar(e,n){const o=new AbortController,{signal:l}=o,c=e.evaluateExtensionPoint("Apollo-extendAnnotationFeature",H.AnnotationFeatureModel),u=function(e){return i.types.model("ClientDataStore",{typeName:i.types.optional(i.types.literal("Client"),"Client"),assemblies:i.types.map(H.ApolloAssembly),checkResults:i.types.map(H.CheckResult),ontologyManager:i.types.optional(Et,{})}).views((t=>({get internetAccounts(){return i.getRoot(t).internetAccounts},get pluginConfiguration(){return i.getRoot(t).jbrowse.configuration.ApolloPlugin},getFeature:n=>i.resolveIdentifier(e,t.assemblies,n)}))).actions((e=>({addAssembly(t,n){const a={_id:t,refSeqs:{}};return n&&(a.backendDriverType=n),e.assemblies.put(a)},addFeature(t,n){const a=e.assemblies.get(t);if(!a)throw new Error(`Could not find assembly "${t}" to add feature "${n._id}"`);const o=a.refSeqs.get(n.refSeq);if(!o)throw new Error(`Could not find refSeq "${n.refSeq}" to add feature "${n._id}"`);o.features.put(n)},deleteFeature(t){const n=e.getFeature(t);if(!n)throw new Error(`Could not find feature "${t}" to delete`);const{_id:a,parent:o}=n;o?o.deleteChild(t):i.getParentOfType(n,H.ApolloRefSeq).deleteFeature(a)},deleteAssembly(t){e.assemblies.delete(t)},addCheckResult(t){e.checkResults.put(t)},addCheckResults(t){for(const n of t)e.checkResults.has(n._id)||e.checkResults.put(n)},deleteCheckResult(t){e.checkResults.delete(t)},clearCheckResults(){e.checkResults.clear()}}))).volatile((e=>({changeManager:new Qo(e),collaborationServerDriver:new er(e),inMemoryFileDriver:new tr(e),desktopFileDriver:r.isElectron?new nr(e):void 0}))).actions((e=>({afterCreate(){i.addDisposer(e,s.autorun((()=>{const{ontologyManager:t,pluginConfiguration:n}=e,o=n.ontologies;for(const n of o||[]){const[o,l,s,i]=[a.readConfObject(n,"name"),a.readConfObject(n,"version"),a.readConfObject(n,"source"),a.readConfObject(n,"textIndexFields")];if(!t.findOntology(o)){const n=r.getSession(e),{jobsManager:a}=n,c=new AbortController,u=`Loading ontology "${o}"`,d={name:u,statusMessage:`Loading ontology "${o}", version "${l}", this may take a while`,progressPct:0,cancelCallback:()=>{c.abort(),a.abortJob(d.name)}};t.addOntology(o,l,s,{textIndexing:{indexFields:i},update:(e,t)=>{0!==t?100!==t?a.update(u,e,t):a.done(d):a.runJob(d)}})}}})))}}))).views((e=>({getBackendDriver(t){if(!t)return e.collaborationServerDriver;const n=r.getSession(e),{assemblyManager:o}=n,l=o.get(t);if(!l)return e.collaborationServerDriver;const{file:s,internetAccountConfigId:i}=a.getConf(l,["sequence","metadata"]);return r.isElectron&&s?e.desktopFileDriver:i?e.collaborationServerDriver:e.inMemoryFileDriver},getInternetAccount(t,n){if(!(t??n))throw new Error("Must provide either assemblyName or internetAccountId");let o=n;if(t&&!o){const{assemblyManager:n}=r.getSession(e),l=n.get(t);if(!l)throw new Error(`No assembly found with name ${t}`);({internetAccountConfigId:o}=a.getConf(l,["sequence","metadata"]))}const{internetAccounts:l}=e,s=l.find((e=>e.internetAccountId===o));if(!s)throw new Error(`No InternetAccount found with config id ${n}`);return s}}))).actions((e=>({loadFeatures:i.flow((function*(t){for(const n of t){const t=e.getBackendDriver(n.assemblyName);if(!t)return;const[a,o]=yield t.getFeatures(n);if(0===a.length)continue;const{assemblyName:r,refName:l}=n;let s=e.assemblies.get(r);s||(s=e.assemblies.put({_id:r,refSeqs:{}}));const[i]=a;let c=s.refSeqs.get(i.refSeq);c||(c=s.refSeqs.put({_id:i.refSeq,name:l,features:{}}));for(const e of a)c.features.has(e._id)||c.features.put(e);e.addCheckResults(o)}})),loadRefSeq:i.flow((function*(t){for(const n of t){const t=e.getBackendDriver(n.assemblyName);if(!t)return;const{refSeq:a,seq:o}=yield t.getSequence(n),{assemblyName:r,end:l,refName:s,start:i}=n;let c=e.assemblies.get(r);c||(c=e.assemblies.put({_id:r,refSeqs:{}}));let u=c.refSeqs.get(a);u||(u=c.refSeqs.put({_id:a,name:s,sequence:[]})),u.addSequence({start:i,stop:l,sequence:o})}}))})))}(c),d=n.props({apolloDataStore:i.types.optional(u,{typeName:"Client"}),apolloSelectedFeature:i.types.safeReference(c),jobsManager:i.types.optional(Yo,{})}).extend((()=>{const e=s.observable.array([]);return{views:{get collaborators(){return e}},actions:{addOrUpdateCollaborator(t){const n=e.find((e=>e.id===t.id));n?n.locations=t.locations:e.push(t)}}}})).actions((e=>({apolloSetSelectedFeature(t){e.apolloSelectedFeature=t},addApolloTrackConfig(t,n){const o=`apollo_track_${t.name}`;e.tracks.some((e=>e.trackId===o))||e.addTrackConf({type:"ApolloTrack",trackId:o,name:`Annotations (${a.getConf(t,"displayName")||t.name})`,assemblyNames:[t.name],textSearching:{textSearchAdapter:{type:"ApolloTextSearchAdapter",trackId:o,assemblyNames:[t.name],textSearchAdapterId:`apollo_search_${t.name}`,...n?{baseURL:{uri:n,locationType:"UriLocation"}}:{}}}})},broadcastLocations(){const{internetAccounts:t}=i.getRoot(e),n=[];for(const t of e.views){if("LinearGenomeView"!==t.type)return;const a=t;if(a.initialized){const{dynamicBlocks:t}=a;t.forEach((t=>{if(void 0!==t.regionNumber){const{assemblyName:a,end:o,refName:r,start:l}=t,s=e.apolloDataStore.assemblies.get(a);s&&"CollaborationServerDriver"===s.backendDriverType&&n.push({assemblyName:a,refName:r,start:l,end:o})}}))}}if(0===n.length){for(const e of t)"baseURL"in e&&e.postUserLocation([]);return}const a=[];for(const e of t)if("baseURL"in e){for(const e of n)a.push({assemblyId:e.assemblyName,refSeq:e.refName,start:e.start,end:e.end});e.postUserLocation(a)}}}))).actions((e=>({afterCreate:i.flow((function*(){s.autorun((()=>{const n=[];for(const t of e.views){if("LinearGenomeView"!==t.type)return;const a=t;if(a.initialized){const{dynamicBlocks:t}=a;t.forEach((t=>{if(void 0!==t.regionNumber){const{assemblyName:a,end:o,refName:r,start:l}=t,s=e.apolloDataStore.assemblies.get(a);s&&"CollaborationServerDriver"===s.backendDriverType&&n.push({assemblyName:a,refName:r,start:l,end:o})}}))}}if(0===n.length){for(const e of t)"baseURL"in e&&e.postUserLocation([]);return}const a=[];for(const e of t)if("baseURL"in e){for(const e of n)a.push({assemblyId:e.assemblyName,refSeq:e.refName,start:e.start,end:e.end});e.postUserLocation(a)}}),{name:"ApolloSession"});const{internetAccounts:t,jbrowse:n,reloadPluginManagerCallback:o}=i.getRoot(e);if(a.readConfObject(n.configuration.ApolloPlugin,"hasRole"))return;const r=i.getSnapshot(e),{id:c,name:u}=r;i.applySnapshot(e,{name:u,id:c});for(const e of t){if("ApolloInternetAccount"!==e.type)continue;const{baseURL:t}=e,n=new URL("jbrowse/config.json",t).href,a=e.getFetcher({locationType:"UriLocation",uri:n});let s,i;try{s=yield a(n,{signal:l})}catch(e){console.error(e);continue}if(s.ok){try{i=yield s.json()}catch(e){console.error(e);continue}o(i,r)}else{const e=yield Ve(s,"Failed to fetch assemblies");console.error(e)}}})),beforeDestroy(){o.abort("destroying session model")}}))).views((e=>{const n=e.getTrackActionMenuItems;return{getTrackActionMenuItems(o){if("ApolloTrack"===o.type||"ReferenceSequenceTrack"===o.type)return n?.(o);const r=a.readConfObject(o,"trackId");return r.endsWith("-sessionTrack")?[...n?.(o)??[],{label:"Save track to Apollo",onClick:async()=>{const{internetAccounts:n,jbrowse:a}=i.getRoot(e),l=i.getSnapshot(a);let s;s=t.filterJBrowseConfig(l),0===Object.keys(s).length&&(s=void 0);const c={...i.getSnapshot(o),trackId:r.slice(0,r.length-13)};for(const a of n){if("ApolloInternetAccount"!==a.type)continue;const n=new t.ImportJBrowseConfigChange({typeName:"ImportJBrowseConfigChange",oldJBrowseConfig:s,newJBrowseConfig:{...s,tracks:s?.tracks&&[...s.tracks,c]}}),{internetAccountId:o}=a;await e.apolloDataStore.changeManager.submit(n,{internetAccountId:o});const{notify:r}=e;r("Track added","success")}e.deleteTrackConf(o),a.addTrackConf(c)},icon:Pe.default}]:[...n?.(o)??[],{label:"Remove track from Apollo",onClick:async()=>{const{internetAccounts:n,jbrowse:a}=i.getRoot(e),l=i.getSnapshot(a);let s;s=t.filterJBrowseConfig(l),0===Object.keys(s).length&&(s=void 0);const c=s?.tracks?.filter((e=>e.trackId!==r));for(const a of n){if("ApolloInternetAccount"!==a.type)continue;const n=new t.ImportJBrowseConfigChange({typeName:"ImportJBrowseConfigChange",oldJBrowseConfig:s,newJBrowseConfig:{...s,tracks:c}}),{internetAccountId:o}=a;await e.apolloDataStore.changeManager.submit(n,{internetAccountId:o});const{notify:r}=e;r("Track removed","success")}e.deleteTrackConf(o),a.deleteTrackConf(o)},icon:Pe.default}]}}}));return i.types.snapshotProcessor(d,{postProcessor(e,t){e.apolloSelectedFeature=void 0;const n=Object.fromEntries(Object.entries(e.apolloDataStore.assemblies).filter((([,e])=>"InMemoryFileDriver"===e.backendDriverType)));if(e.apolloDataStore={typeName:"Client",assemblies:n,checkResults:{}},!t)return e;const{apolloDataStore:a}=t,{checkResults:o}=a;for(const[,t]of o){const[n]=t.ids;if(!n)continue;const o=a.assemblies.get(n.assemblyId);o&&"InMemoryFileDriver"===o.backendDriverType&&(e.apolloDataStore.checkResults[t._id]=i.getSnapshot(t))}return e}})}const or="WorkerGlobalScope"in globalThis;for(const[n,a]of Object.entries(t.changes))e.changeRegistry.registerChange(n,a);const rr=new t.CDSCheck;e.checkRegistry.registerCheck(rr.name,rr),t.validationRegistry.registerValidation(new t.CoreValidation),t.validationRegistry.registerValidation(new t.ParentChildValidation),exports.default=class extends ae.default{name="ApolloPlugin";version="0.3.7";configurationSchema=Do;install(e){!function(e){e.addAdapterType((()=>new we.default({name:"ApolloSequenceAdapter",configSchema:Sn,adapterMetadata:{category:void 0,hiddenFromGUI:!0,description:void 0},AdapterClass:bn})))}(e),function(e){e.addAdapterType((()=>new we.default({name:"ApolloRefNameAliasAdapter",configSchema:pn,adapterMetadata:{category:void 0,hiddenFromGUI:!0,description:void 0},AdapterClass:gn})))}(e),function(e){e.addTextSearchAdapterType((()=>new o.TextSearchAdapterType({name:"ApolloTextSearchAdapter",displayName:"Apollo text search adapter",configSchema:En,AdapterClass:wn,description:"Apollo Text Search adapter"})))}(e),e.addWidgetType((()=>{const e=a.ConfigurationSchema("ApolloFeatureDetailsWidget",{});return new o.WidgetType({name:"ApolloFeatureDetailsWidget",heading:"Apollo feature details",configSchema:e,stateModel:Bn,ReactComponent:_n})})),e.addWidgetType((()=>{const e=a.ConfigurationSchema("ApolloTranscriptDetails",{});return new o.WidgetType({name:"ApolloTranscriptDetails",heading:"Apollo transcript details",configSchema:e,stateModel:Un,ReactComponent:na})})),e.addTrackType((()=>{const t=a.ConfigurationSchema("ApolloTrack",{adapter:""},{baseConfiguration:o.createBaseTrackConfig(e),explicitIdentifier:"trackId"});return new o.TrackType({name:"ApolloTrack",configSchema:t,stateModel:o.createBaseTrackModel(e,"ApolloTrack",t)})})),e.addInternetAccountType((()=>new o.InternetAccountType({name:"ApolloInternetAccount",configSchema:qe,stateModel:fn(qe)}))),e.addDisplayType((()=>new o.DisplayType({name:"LinearApolloDisplay",configSchema:aa,stateModel:go(0,aa),trackType:"ApolloTrack",viewType:"LinearGenomeView",ReactComponent:Xo}))),e.addDisplayType((()=>new o.DisplayType({name:"LinearApolloSixFrameDisplay",configSchema:po,stateModel:Fo(0,po),trackType:"ApolloTrack",viewType:"LinearGenomeView",ReactComponent:Ko}))),e.addToExtensionPoint("Core-extendSession",ar.bind(this,e)),e.addToExtensionPoint("Core-extendPluggableElement",(e=>{if("LinearGenomeView"===e.name){const{stateModel:t}=e,n=t.views((e=>{const t=e.rubberBandMenuItems;return{rubberBandMenuItems:()=>[...t(),{label:"Add new feature",icon:oe.default,onClick:()=>{const t=r.getSession(e),{leftOffset:n,rightOffset:a}=e,o=e.getSelectedRegions(n,a);t.queueDialog((e=>[It,{session:t,handleClose:()=>{e()},region:o[0],changeManager:t.apolloDataStore.changeManager}]))}}]}}));e.stateModel=n}return e})),e.addToExtensionPoint("Core-extendPluggableElement",Po),e.addToExtensionPoint("Core-extendPluggableElement",Bo),or||e.addToExtensionPoint("Core-extendWorker",(t=>"on"in t&&t.on?(t.on("apollo",(async n=>{if("object"!=typeof(a=n)||null===a||!("apollo"in a)||!0!==a.apollo)return;var a;const{apollo:o,messageId:r,method:l}=n;switch(l){case"getSequence":{const{region:a}=n,{assemblyName:l}=a,s=e.rootModel?.session?.apolloDataStore;if(!s)break;const i=s.getBackendDriver(l),{seq:c}=await i.getSequence(a);t.workers[0].postMessage({apollo:o,messageId:r,sequence:c});break}case"getRegions":{const{assembly:a}=n,l=e.rootModel?.session?.apolloDataStore;if(!l)break;const s=l.getBackendDriver(a),i=await s.getRegions(a);t.workers[0].postMessage({apollo:o,messageId:r,regions:i});break}case"getRefNameAliases":{const{assembly:a}=n,l=e.rootModel?.session?.apolloDataStore;if(!l)break;const s=l.getBackendDriver(a),i=await s.getRefNameAliases(a);t.workers[0].postMessage({apollo:o,messageId:r,refNameAliases:i});break}}})),t):t))}configure(e){r.isAbstractMenuManager(e.rootModel)&&(e.rootModel.appendToMenu("Apollo",{label:"Download GFF3",onClick:e=>{e.queueDialog((t=>[qt,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"Manage Checks",onClick:e=>{e.queueDialog((t=>[Bt,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"View Change Log",onClick:e=>{e.queueDialog((t=>[Jt,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"Open local GFF3 file",onClick:e=>{e.queueDialog((t=>[Ht,{session:e,handleClose:()=>{t()},inMemoryFileDriver:e.apolloDataStore.inMemoryFileDriver}]))}}),e.rootModel.appendToMenu("Apollo",{label:"View check results",onClick:e=>{e.queueDialog((t=>[Yt,{session:e,handleClose:()=>{t()}}]))}}),e.rootModel.appendToMenu("Apollo",{label:"Log out",onClick:e=>{e.queueDialog((t=>[_t,{session:e,handleClose:()=>{t()}}]))}}))}};
|
|
2
2
|
//# sourceMappingURL=jbrowse-plugin-apollo.cjs.production.min.js.map
|