diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 0e377d56..717936db 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -50,6 +50,7 @@ module.exports = { default: 'array', }, ], + '@typescript-eslint/no-explicit-any': 'error', 'import/consistent-type-specifier-style': [ 'error', 'prefer-top-level', @@ -70,8 +71,8 @@ module.exports = { }, }, { - // Main TypeScript (#67): full typing under non-strict — typed catch, typed exports. - files: ['src/main/**/*.{ts,tsx}', 'src/common/**/*.{ts,tsx}'], + // Full typing under non-strict for all TypeScript (#67 main process, #236 page): typed catch, typed exports. + files: ['src/**/*.{ts,tsx}'], rules: { '@typescript-eslint/explicit-module-boundary-types': 'error', 'no-restricted-syntax': [ diff --git a/e2e/modeltest-outcome.spec.js b/e2e/modeltest-outcome.spec.js index 0d050c61..2b354a56 100644 --- a/e2e/modeltest-outcome.spec.js +++ b/e2e/modeltest-outcome.spec.js @@ -14,7 +14,7 @@ const { checkFixture } = require('./helpers/fixtures'); const outputDir = path.join(repoRoot, 'static', 'test-results'); const modelTestOutput = path.join(outputDir, 'RAxML_GUI_ModelTest_nucleotide'); -// Same choice as src/app/store/Run.js +// Same choice as src/app/store/Run.ts const binary = process.platform === 'win32' ? 'modeltest-ng.exe' diff --git a/electron.vite.config.js b/electron.vite.config.js index 29a493ec..ef6879eb 100644 --- a/electron.vite.config.js +++ b/electron.vite.config.js @@ -38,25 +38,8 @@ export default defineConfig( ( { command } ) => ( { filenamify: resolve( __dirname, 'node_modules/filenamify/filenamify.js' ), }, }, - optimizeDeps: { - // The page keeps JSX in .js files. The dep scanner parses those only when .js is jsx. - rolldownOptions: { - moduleTypes: { - '.js': 'jsx', - }, - }, - }, plugins: [ - // plugin-react 5: its babel option compiles JSX in .js files. 6 dropped babel. - // Vite's oxc parser does not treat .js as JSX. - react( { - babel: { - plugins: [ - ['@babel/plugin-proposal-class-properties', { loose: false }], - ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }], - ], - }, - } ), + react(), ...sourceMapUpload( command ), ], build: { diff --git a/jest/babelTransform.js b/jest/babelTransform.js index 0802f01f..a5b91b8a 100644 --- a/jest/babelTransform.js +++ b/jest/babelTransform.js @@ -1,6 +1,6 @@ const babelJest = require( 'babel-jest' ); -// Plugins match the page build. preset-env and preset-typescript +// Define-semantics class fields and the automatic JSX runtime, as the page build emits. preset-env and preset-typescript // are what Jest needs to load the page's ESM and .tsx imports. module.exports = babelJest.default.createTransformer( { babelrc: false, diff --git a/package.json b/package.json index 2cc06336..d4c62b1e 100644 --- a/package.json +++ b/package.json @@ -77,7 +77,6 @@ "postinstall-postinstall": "^2.1.0", "prismjs": "^1.30.0", "prismjs-bibtex": "^2.1.0", - "prop-types": "^15.8.1", "react": "^19.3.1", "react-dom": "^19.3.1", "react-dropzone": "^20.2.0", @@ -94,6 +93,8 @@ "@electron/notarize": "^3.1.2", "@sentry/bundler-plugins": "11.12.0", "@sentry/cli": "^3.8.2", + "@types/d3-array": "^3.2.2", + "@types/lodash": "^4.17.27", "@types/node": "^22.19.1", "@types/prismjs": "^1.26.5", "@types/react": "^19.2.7", diff --git a/scripts/page-store-coverage.js b/scripts/page-store-coverage.js deleted file mode 100644 index 3358079d..00000000 --- a/scripts/page-store-coverage.js +++ /dev/null @@ -1,79 +0,0 @@ -// Lists every @computed and @action in the page store and reports which run -// under jest. Exits 1 when any member is not run. Also lists @observable -// fields whose name appears in no test file (a pointer, not proof). -const { spawnSync } = require( 'child_process' ); -const fs = require( 'fs' ); -const os = require( 'os' ); -const path = require( 'path' ); -const parser = require( '@babel/parser' ); - -const root = path.join( __dirname, '..' ); -const storeDir = path.join( root, 'src/app/store' ); -const files = fs.readdirSync( storeDir ).filter( f => f.endsWith( '.js' ) && !f.endsWith( '.test.js' ) ); -const tests = fs.readdirSync( storeDir ).filter( f => f.endsWith( '.test.js' ) ) - .map( f => fs.readFileSync( path.join( storeDir, f ), 'utf8' ) ).join( '\n' ); - -const covDir = fs.mkdtempSync( path.join( os.tmpdir(), 'page-store-cov-' ) ); -const jest = spawnSync( 'node', [ - 'node_modules/jest/bin/jest.js', '--watchAll=false', '--coverage', '--coverageReporters=json', - `--coverageDirectory=${covDir}`, '--collectCoverageFrom=src/app/store/*.js', - '--collectCoverageFrom=!src/app/store/*.test.js', -], { cwd: root, encoding: 'utf8' } ); -if ( jest.status !== 0 ) { - console.error( jest.stdout, jest.stderr ); - process.exit( 1 ); -} -const coverage = JSON.parse( fs.readFileSync( path.join( covDir, 'coverage-final.json' ), 'utf8' ) ); - -const decoratorName = d => { - let e = d.expression; - if ( e.type === 'CallExpression' ) e = e.callee; - while ( e.type === 'MemberExpression' ) e = e.object; - return e.name; -}; - -const notRun = []; -const noObservableTest = []; -let computeds = 0; -let actions = 0; -let observables = 0; -for ( const file of files ) { - const full = path.join( storeDir, file ); - const ast = parser.parse( fs.readFileSync( full, 'utf8' ), { - sourceType: 'module', plugins: [ 'jsx', 'typescript', [ 'decorators', { decoratorsBeforeExport: true } ], 'classProperties' ], - } ); - const cov = Object.entries( coverage ).find( ( [ p ] ) => p === full )?.[ 1 ]; - const walk = node => { - if ( !node || typeof node.type !== 'string' ) return; - if ( node.type === 'ClassDeclaration' || node.type === 'ClassExpression' ) { - for ( const m of node.body.body ) { - const kind = ( m.decorators || [] ).map( decoratorName ) - .find( n => [ 'computed', 'action', 'observable' ].includes( n ) ); - if ( !kind ) continue; - const name = `${node.id?.name}.${m.key.name}`; - if ( kind === 'observable' ) { - observables += 1; - if ( !new RegExp( `\\b${m.key.name}\\b` ).test( tests ) ) noObservableTest.push( `${file} ${name}` ); - continue; - } - if ( kind === 'computed' ) computeds += 1; else actions += 1; - // The member's own function is the earliest one inside its range. - const fns = cov ? Object.entries( cov.fnMap ) - .filter( ( [ , f ] ) => f.loc.start.line >= m.loc.start.line && f.loc.end.line <= m.loc.end.line ) - .sort( ( [ , a ], [ , b ] ) => a.loc.start.line - b.loc.start.line || a.loc.start.column - b.loc.start.column ) : []; - if ( !fns.length || !cov.f[fns[0][0]] ) notRun.push( `${file}:${m.loc.start.line} ${kind} ${name}` ); - } - } - for ( const v of Object.values( node ) ) { - if ( Array.isArray( v ) ) v.forEach( walk ); else if ( v && typeof v === 'object' ) walk( v ); - } - }; - walk( ast.program ); -} - -console.log( `computeds: ${computeds}, actions: ${actions}, observables: ${observables}` ); -console.log( `members not run: ${notRun.length}` ); -notRun.forEach( l => console.log( ` ${l}` ) ); -console.log( `observables named in no test: ${noObservableTest.length}` ); -noObservableTest.forEach( l => console.log( ` ${l}` ) ); -process.exit( notRun.length ? 1 : 0 ); diff --git a/scripts/typecheck-baseline.js b/scripts/typecheck-baseline.js index aa8ef106..8932aed8 100644 --- a/scripts/typecheck-baseline.js +++ b/scripts/typecheck-baseline.js @@ -66,18 +66,21 @@ function renameLines(known, actual, from, to) { return { renamed, missing }; } -function main() { - if (!fs.existsSync(baselinePath)) { - console.error('typecheck baseline is missing: ' + baselinePath); - process.exit(1); - } - const baseline = diagnosticLines(fs.readFileSync(baselinePath, 'utf8')); - if (baseline.length === 0) { - console.error('typecheck baseline is empty: ' + baselinePath); - process.exit(1); - } +/** Keep tsc diagnostics (and their continuation lines) reported in a .ts or .tsx file. */ +function typeScriptLines(lines) { + let inTypeScript = false; + return lines.filter((line) => { + const match = /^(src\/\S+?)\(/.exec(line); + if (match) { + inTypeScript = /\.tsx?$/.test(match[1]); + } + return inTypeScript; + }); +} + +function runTsc(args) { const tsc = path.join(root, 'node_modules', 'typescript', 'bin', 'tsc'); - const result = spawnSync(process.execPath, [tsc, '--noEmit', '--pretty', 'false'], { + const result = spawnSync(process.execPath, [tsc, '--noEmit', '--pretty', 'false', ...args], { cwd: root, encoding: 'utf8', }); @@ -85,7 +88,16 @@ function main() { console.error(result.error || result.stderr || result.stdout); process.exit(result.status || 1); } - const actual = diagnosticLines(`${result.stdout || ''}\n${result.stderr || ''}`); + return diagnosticLines(`${result.stdout || ''}\n${result.stderr || ''}`); +} + +function main() { + if (!fs.existsSync(baselinePath)) { + console.error('typecheck baseline is missing: ' + baselinePath); + process.exit(1); + } + const baseline = diagnosticLines(fs.readFileSync(baselinePath, 'utf8')); + const actual = runTsc([]); const renameAt = process.argv.indexOf('--rename'); if (renameAt !== -1) { const [from, to] = process.argv.slice(renameAt + 1, renameAt + 3); @@ -105,6 +117,21 @@ function main() { fs.writeFileSync(baselinePath, renamed.join('\n') + '\n'); return; } + if (process.argv.includes('--write')) { + const typed = typeScriptLines(actual); + if (typed.length) { + console.error('a .ts/.tsx file has diagnostics:\n' + typed.join('\n')); + process.exit(1); + } + fs.writeFileSync(baselinePath, actual.join('\n') + '\n'); + return; + } + // Second pass: no allowlist. A .ts/.tsx file may not have any diagnostic under --noImplicitAny. + const implicitAny = typeScriptLines(runTsc(['--noImplicitAny'])); + if (implicitAny.length) { + console.error('noImplicitAny:\n' + implicitAny.join('\n')); + process.exitCode = 1; + } const fresh = freshLines(actual, baseline); const unused = unusedLines(baseline, actual); if (fresh.length || unused.length) { @@ -116,10 +143,13 @@ function main() { } process.exit(1); } + if (process.exitCode) { + process.exit(process.exitCode); + } } if (require.main === module) { main(); } -module.exports = { diagnosticLines, freshLines, unusedLines, ownedFingerprints, renameLines }; +module.exports = { typeScriptLines, diagnosticLines, freshLines, unusedLines, ownedFingerprints, renameLines }; diff --git a/scripts/typecheck-baseline.txt b/scripts/typecheck-baseline.txt index ce174476..e69de29b 100644 --- a/scripts/typecheck-baseline.txt +++ b/scripts/typecheck-baseline.txt @@ -1,33 +0,0 @@ -src/app/App.js(322,24): error TS2769: No overload matches this call. - Overload 1 of 2, '(props: { component: ElementType; } & SvgIconOwnProps & CommonProps & Omit): Element', gave the following error. - Property 'component' is missing in type '{ onClick: any; sx: { '&:hover': { color: "#999"; }; }; title: string; }' but required in type '{ component: ElementType; }'. - Overload 2 of 2, '(props: DefaultComponentProps>): Element', gave the following error. - Type '{ onClick: any; sx: { '&:hover': { color: "#999"; }; }; title: string; }' is not assignable to type 'IntrinsicAttributes & SvgIconOwnProps & CommonProps & Omit, "fontSize" | ... 10 more ... | "titleAccess">'. - Property 'title' does not exist on type 'IntrinsicAttributes & SvgIconOwnProps & CommonProps & Omit, "fontSize" | ... 10 more ... | "titleAccess">'. -src/app/App.js(466,12): error TS2739: Type '{ error: any; onClose: any; }' is missing the following properties from type '{ error: any; onClose: any; needReload: any; title: any; }': needReload, title -src/app/App.js(512,10): error TS2741: Property 'needReload' is missing in type '{ error: any; title: any; onClose: () => void; }' but required in type '{ error: any; onClose: any; needReload: any; title: any; }'. -src/app/App.test.js(5,1): error TS2582: Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`. -src/app/App.test.js(13,3): error TS2304: Cannot find name 'expect'. -src/app/store/AlignmentOptions.js(10,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/AlignmentOptions.js(37,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/AlignmentOptions.js(121,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/index.js(5,8): error TS2551: Property 'store' does not exist on type 'Window & typeof globalThis'. Did you mean 'Storage'? -src/app/store/Option.js(12,14): error TS2304: Cannot find name 'yup'. -src/app/store/RunOptions.js(265,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(278,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(293,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(300,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(310,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(320,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(340,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(384,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(396,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(409,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(446,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/RunOptions.js(506,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/RunOptions.js(541,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/RunOptions.js(572,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/RunOptions.js(617,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(649,5): error TS2554: Expected 5-6 arguments, but got 4. -src/app/store/RunOptions.js(668,5): error TS2554: Expected 5-6 arguments, but got 3. -src/app/store/RunOptions.js(680,5): error TS2554: Expected 5-6 arguments, but got 4. diff --git a/src/app/AlignmentCard.js b/src/app/AlignmentCard.tsx similarity index 81% rename from src/app/AlignmentCard.js rename to src/app/AlignmentCard.tsx index f30ff52a..118d20d8 100644 --- a/src/app/AlignmentCard.js +++ b/src/app/AlignmentCard.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import IconButton from '@mui/material/IconButton'; import MoreVertIcon from '@mui/icons-material/MoreVert'; import DeleteForeverIcon from '@mui/icons-material/DeleteForever'; @@ -20,8 +19,82 @@ import OptionTextField from './components/OptionTextField'; import CardActions from '@mui/material/CardActions'; import Box from '@mui/material/Box'; import Button from '@mui/material/Button'; +import type { SxProps, Theme } from '@mui/material/styles'; +import type { OptionSelectOptionLike } from './components/OptionSelect'; +import type { OptionTextFieldOptionLike } from './components/OptionTextField'; -function _ModelTestButton( { alignment } ) { +interface CardModelExtra { + label: string; + options: readonly string[]; + value: string; + onChange: ( value: string ) => void; + notAvailable: boolean; + hoverInfo: string; + error: unknown; +} + +interface CardAlignment { + run: { usesRaxmlNg: boolean }; + dataType?: string; + numSequences: number; + numSequencesParsed: number; + length: number; + filename: string; + parsingComplete: boolean; + loading: boolean; + showPartition: boolean; + partition: { isComplete: boolean }; + substitutionModel: OptionSelectOptionLike; + multistateNumber: OptionTextFieldOptionLike; + ngStationaryFrequencies: OptionSelectOptionLike; + ngInvariantSites: OptionSelectOptionLike; + ngRateHeterogeneity: OptionSelectOptionLike; + ngAscertainmentBias: OptionSelectOptionLike; + modelExtra: CardModelExtra | null; + modelTestCanRun: boolean; + modeltestLoading: boolean; + modeltestDisabled: boolean; + runModelTest: () => void; + cancelModelTest: () => void; + openFile: () => void; + showFileInFolder: () => void; + remove: () => void; + setShowPartition: () => void; +} + +interface CardFinalAlignment { + dataType?: string; + numSequences: number; + // Absent on the store FinalAlignment; its parsingComplete is always true. + numSequencesParsed?: number; + length: number; + numAlignments: number; + filename: string; + parsingComplete: boolean; + fillTaxonGapsWithEmptySeqeunces: boolean; + setFillTaxonGapsWithEmptySeqeunces: ( checked: boolean ) => void; + partition: { text: string }; + openFile: () => void; + openPartition: () => void; + openFolder: () => void; +} + +export interface ModelTestButtonProps { + alignment: CardAlignment; +} + +export interface AlignmentCardProps { + alignment: CardAlignment; +} + +export interface FinalAlignmentCardProps { + alignment: CardFinalAlignment; + sx?: SxProps; +} + +function _ModelTestButton( { + alignment, +}: ModelTestButtonProps ): React.JSX.Element | null { if ( !alignment.modelTestCanRun ) { return null; } @@ -47,26 +120,22 @@ function _ModelTestButton( { alignment } ) { ); } -_ModelTestButton.propTypes = { - alignment: PropTypes.object.isRequired, -}; - const ModelTestButton = observer( _ModelTestButton ); -function AlignmentCard( { alignment } ) { +function AlignmentCard( { alignment }: AlignmentCardProps ): React.JSX.Element { const { dataType, numSequences, length } = alignment; - const [anchorEl, setAnchorEl] = React.useState( null ); + const [anchorEl, setAnchorEl] = React.useState( null ); - function handleMenuClick( event ) { + function handleMenuClick( event: React.MouseEvent ): void { setAnchorEl( event.currentTarget ); } - function handleMenuClose() { + function handleMenuClose(): void { setAnchorEl( null ); } - function closeMenuAndRun( callback ) { + function closeMenuAndRun( callback: () => void ): () => void { return () => { callback(); setAnchorEl( null ); @@ -291,18 +360,21 @@ function AlignmentCard( { alignment } ) { ); } -function FinalAlignmentCard( { sx, alignment } ) { - const [anchorEl, setAnchorEl] = React.useState( null ); +function FinalAlignmentCard( { + sx, + alignment, +}: FinalAlignmentCardProps ): React.JSX.Element { + const [anchorEl, setAnchorEl] = React.useState( null ); - function handleMenuClick( event ) { + function handleMenuClick( event: React.MouseEvent ): void { setAnchorEl( event.currentTarget ); } - function handleMenuClose() { + function handleMenuClose(): void { setAnchorEl( null ); } - function closeMenuAndRun( callback ) { + function closeMenuAndRun( callback: () => void ): () => void { return () => { callback(); setAnchorEl( null ); @@ -442,15 +514,6 @@ function FinalAlignmentCard( { sx, alignment } ) { } // {tree.name} -AlignmentCard.propTypes = { - alignment: PropTypes.object.isRequired, -}; - -FinalAlignmentCard.propTypes = { - alignment: PropTypes.object.isRequired, - sx: PropTypes.object, -}; - const AlignmentCardObserver = observer( AlignmentCard ); const FinalAlignmentCardObserver = observer( FinalAlignmentCard ); diff --git a/src/app/App.test.js b/src/app/App.test.js index 431e6449..380f08bf 100644 --- a/src/app/App.test.js +++ b/src/app/App.test.js @@ -1,3 +1,4 @@ +// @ts-nocheck — Jest globals. checkJs has no test runner types. import React, { act } from 'react'; import { createRoot } from 'react-dom/client'; import Page from './index'; diff --git a/src/app/App.js b/src/app/App.tsx similarity index 96% rename from src/app/App.js rename to src/app/App.tsx index ba38707d..ef2bae47 100644 --- a/src/app/App.js +++ b/src/app/App.tsx @@ -34,7 +34,7 @@ import ErrorBoundary from './components/ErrorBoundary'; import ErrorDialog from './components/ErrorDialog'; import ModifiedDialog from './components/ModifiedDialog'; -const VerticalHeading = styled( Typography )( ( { theme } ) => ( { +const VerticalHeading = styled( Typography )( () => ( { writingMode: 'vertical-rl', textOrientation: 'upright', padding: '10px 5px', @@ -43,7 +43,20 @@ const VerticalHeading = styled( Typography )( ( { theme } ) => ( { borderRight: '1px solid #ccc', } ) ); -const App = () => { +interface SnackRun { + converted: boolean; + convertedAlignmentFrom: string | null; + modified: boolean; + showModifiedSnack: boolean; + clearShowModified: () => void; +} + +interface SnackStore { + showAppSnack: boolean; + clearAppSnack: () => void; +} + +const App = (): React.JSX.Element => { const TabItems = store.runs.map( ( run ) => ( { /> ) ); - function fileModifiedSnack( run ) { + function fileModifiedSnack( run: SnackRun ): React.JSX.Element { let message = 'Something happened'; if ( run.converted ) { message = `Converted your ${run.convertedAlignmentFrom} alignment into fasta!`; @@ -107,7 +120,7 @@ const App = () => { ); } - function appSnack( store ) { + function appSnack( store: SnackStore ): React.JSX.Element { const message = 'Command copied'; return ( { color: '#999', }, }} - title="Clear console" + titleAccess="Clear console" /> )} diff --git a/src/app/AstralTreeCard.js b/src/app/AstralTreeCard.tsx similarity index 86% rename from src/app/AstralTreeCard.js rename to src/app/AstralTreeCard.tsx index 5d135aaf..9a8c5c92 100644 --- a/src/app/AstralTreeCard.js +++ b/src/app/AstralTreeCard.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import IconButton from '@mui/material/IconButton'; import MoreVertIcon from '@mui/icons-material/MoreVert'; import DeleteForeverIcon from '@mui/icons-material/DeleteForever'; @@ -14,18 +13,31 @@ import CardContent from '@mui/material/CardContent'; import CardActions from '@mui/material/CardActions'; import Box from '@mui/material/Box'; -function AstralTreeCard( { astralTree } ) { - const [anchorEl, setAnchorEl] = React.useState( null ); +interface CardAstralTree { + filename: string; + openFile: () => void; + showFileInFolder: () => void; + remove: () => void; +} + +export interface AstralTreeCardProps { + astralTree: CardAstralTree; +} - function handleMenuClick( event ) { +function AstralTreeCard( { + astralTree, +}: AstralTreeCardProps ): React.JSX.Element { + const [anchorEl, setAnchorEl] = React.useState( null ); + + function handleMenuClick( event: React.MouseEvent ): void { setAnchorEl( event.currentTarget ); } - function handleMenuClose() { + function handleMenuClose(): void { setAnchorEl( null ); } - function closeMenuAndRun( callback ) { + function closeMenuAndRun( callback: () => void ): () => void { return () => { callback(); setAnchorEl( null ); @@ -121,10 +133,6 @@ function AstralTreeCard( { astralTree } ) { ); } -AstralTreeCard.propTypes = { - astralTree: PropTypes.object.isRequired, -}; - const AstralTreeCardObserver = observer( AstralTreeCard ); export default AstralTreeCardObserver; diff --git a/src/app/CitationModal.js b/src/app/CitationModal.tsx similarity index 84% rename from src/app/CitationModal.js rename to src/app/CitationModal.tsx index b27e8d7d..d224804e 100644 --- a/src/app/CitationModal.js +++ b/src/app/CitationModal.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import Button from '@mui/material/Button'; import Card from '@mui/material/Card'; import CardContent from '@mui/material/CardContent'; @@ -12,7 +11,29 @@ import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'; import CodeHighlight from './components/CodeHighlight'; -function CitationModal( { citation } ) { +type CitationFormat = 'txt' | 'ris' | 'bib'; + +interface CitationArticle { + name: string; + bib: string; + ris: string; + txt: string; +} + +interface CitationLike { + format: CitationFormat; + formats: { value: CitationFormat; name: string }[]; + content: CitationArticle[]; + setFormat: ( format: CitationFormat ) => void; + copyToClipboard: () => void; + hide: () => void; +} + +export interface CitationModalProps { + citation: CitationLike; +} + +function CitationModal( { citation }: CitationModalProps ): React.JSX.Element { return ( { - const stdoutContainerRef = useRef( null ); +interface ConsoleRun { + stdout: string; + stderr: string; +} + +export interface ConsoleProps { + run: ConsoleRun; +} + +const Console = ( { run }: ConsoleProps ): React.JSX.Element => { + const stdoutContainerRef = useRef( null ); const scrollConsoleToBottom = useCallback( () => { if ( !stdoutContainerRef.current ) return; @@ -74,8 +82,4 @@ const Console = ( { run } ) => { ); }; -Console.propTypes = { - run: PropTypes.object.isRequired, -}; - export default observer( Console ); diff --git a/src/app/Input.js b/src/app/Input.tsx similarity index 86% rename from src/app/Input.js rename to src/app/Input.tsx index 979ce874..d0e3c917 100644 --- a/src/app/Input.js +++ b/src/app/Input.tsx @@ -1,21 +1,65 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import Button from '@mui/material/Button'; import AlignmentCard, { FinalAlignmentCard } from './AlignmentCard'; +import type { AlignmentCardProps, FinalAlignmentCardProps } from './AlignmentCard'; import AstralTreeCard from './AstralTreeCard'; +import type { AstralTreeCardProps } from './AstralTreeCard'; import PartitionFileCard from './PartitionFileCard'; +import type { PartitionFileCardProps } from './PartitionFileCard'; import Box from '@mui/material/Box'; import TreeCard from './TreeCard'; +import type { TreeCardProps } from './TreeCard'; import { Typography } from '@mui/material'; import Dropzone from 'react-dropzone'; +import type { SxProps, Theme } from '@mui/material/styles'; -function droppedPath( file ) { - const { rendererBridge } = /** @type {any} */ ( window ); +interface DroppedFile { + path: string; +} + +// Each child card's props name what it reads of the same store object. +type InputTree = TreeCardProps['tree'] & { + notAvailable: boolean; + haveFile: boolean; +}; + +type InputRun = PartitionFileCardProps['run'] & { + hasAstralTree: boolean; + addAlignments: ( files: DroppedFile[] ) => void; + addPartitionFiles: ( files: DroppedFile[] ) => void; + addTreeFiles: ( type: string, files: DroppedFile[] ) => void; + addAstralFiles: ( file: DroppedFile ) => void; + inputIsAlignment: boolean; + alignments: ( AlignmentCardProps['alignment'] & { path: string } )[]; + inputIsTree: boolean; + astralTree: AstralTreeCardProps['astralTree']; + canLoadAlignment: boolean; + haveAlignments: boolean; + canLoadPartitionFile: boolean; + loadAlignmentFiles: () => void; + canLoadAstralTree: boolean; + loadAstralTree: () => void; + loadPartitionFile: () => void; + tree: InputTree; + loadTreeFile: () => void; + backboneConstraint: InputTree; + loadBackboneConstraintFile: () => void; + multifurcatingConstraint: InputTree; + loadMultifurcatingConstraintFile: () => void; + finalAlignment: FinalAlignmentCardProps['alignment']; +}; + +export interface InputProps { + run: InputRun; +} + +function droppedPath( file: File ): string { + const { rendererBridge } = window; return rendererBridge.getPathForFile( file ); } -const Input = ( { run } ) => { +const Input = ( { run }: InputProps ): React.JSX.Element => { // run.hasAstralTree is the condition on which to show an astral tree card // For some reason when changed in the mobx store a rerender is not triggered with this boolean with the conditional below alone // With this if the component rerenders as should be @@ -23,28 +67,28 @@ const Input = ( { run } ) => { console.log( 'run.hasAstralTree :>> ', run.hasAstralTree ); } - const onAlignmentDrop = ( acceptedFiles ) => { + const onAlignmentDrop = ( acceptedFiles: File[] ) => { const droppedPathes = acceptedFiles.map( ( file ) => ( { path: droppedPath( file ), } ) ); run.addAlignments( droppedPathes ); }; - const onPartitionDrop = ( acceptedFiles ) => { + const onPartitionDrop = ( acceptedFiles: File[] ) => { const droppedPathes = acceptedFiles.map( ( file ) => ( { path: droppedPath( file ), } ) ); run.addPartitionFiles( droppedPathes ); }; - const onTreeDrop = ( type ) => ( acceptedFiles ) => { + const onTreeDrop = ( type: string ) => ( acceptedFiles: File[] ) => { const droppedPathes = acceptedFiles.map( ( file ) => ( { path: droppedPath( file ), } ) ); run.addTreeFiles( type, droppedPathes ); }; - const onAstralTreeDrop = ( acceptedFiles ) => { + const onAstralTreeDrop = ( acceptedFiles: File[] ) => { const droppedPathes = acceptedFiles.map( ( file ) => ( { path: droppedPath( file ), } ) ); @@ -53,15 +97,18 @@ const Input = ( { run } ) => { } }; - const dropzoneRootSx = ( isDragActive, extra = {} ) => ( { + const dropzoneRootSx = ( + isDragActive: boolean, + extra: Record = {}, + ): SxProps => ( { width: 'fit-content', alignSelf: 'flex-start', borderRadius: 1, - border: ( theme ) => + border: ( theme: Theme ) => isDragActive ? `2px dashed ${theme.palette.input.darker}` : '2px dashed transparent', - bgcolor: ( theme ) => + bgcolor: ( theme: Theme ) => isDragActive ? theme.palette.input.lighter : 'transparent', @@ -421,8 +468,4 @@ const Input = ( { run } ) => { ); }; -Input.propTypes = { - run: PropTypes.object.isRequired, -}; - export default observer( Input ); diff --git a/src/app/Model.js b/src/app/Model.tsx similarity index 75% rename from src/app/Model.js rename to src/app/Model.tsx index b60e6fbf..1c8c7394 100644 --- a/src/app/Model.js +++ b/src/app/Model.tsx @@ -1,13 +1,42 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import Box from '@mui/material/Box'; import OptionSelect from './components/OptionSelect'; +import type { OptionSelectOptionLike } from './components/OptionSelect'; import OptionCheck from './components/OptionCheck'; import TextField from '@mui/material/TextField'; import Typography from '@mui/material/Typography'; +import type { OptionCheckOptionLike } from './components/OptionCheck'; -const Model = ( { run } ) => { +interface ModelRun { + usesModeltestNg: boolean; + usesAstral: boolean; + analysis: OptionSelectOptionLike; + numRuns: OptionSelectOptionLike; + numRepetitions: OptionSelectOptionLike; + numRepetitionsNg: OptionSelectOptionLike; + branchLength: OptionCheckOptionLike; + sHlike: OptionCheckOptionLike; + combinedOutput: OptionCheckOptionLike; + startingTree: OptionSelectOptionLike; + outGroup: OptionSelectOptionLike; + haveRandomSeed: boolean; + randomSeed: number; + setRandomSeed: ( value: string ) => void; + substitutionMatrix: OptionSelectOptionLike; + substitutionRate: OptionSelectOptionLike; + substitutionI: OptionSelectOptionLike; + substitutionAscertainment: OptionSelectOptionLike; + multistateModel: OptionSelectOptionLike; + estimatedFrequencies: OptionCheckOptionLike; + baseFrequencies: OptionSelectOptionLike; +} + +export interface ModelProps { + run: ModelRun; +} + +const Model = ( { run }: ModelProps ): React.JSX.Element => { // TODO: Check marginTop: 2 hack, doesn't seem exactly aligned to top if ( run.usesModeltestNg ) { return ( @@ -132,8 +161,4 @@ const Model = ( { run } ) => { ); }; -Model.propTypes = { - run: PropTypes.object.isRequired, -}; - export default observer( Model ); diff --git a/src/app/Output.js b/src/app/Output.tsx similarity index 85% rename from src/app/Output.js rename to src/app/Output.tsx index 84de67fe..058662eb 100644 --- a/src/app/Output.js +++ b/src/app/Output.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import Box from '@mui/material/Box'; import TextField from '@mui/material/TextField'; import Button from '@mui/material/Button'; @@ -8,7 +7,25 @@ import { Link, Typography } from '@mui/material'; import FileIcon from '@mui/icons-material/InsertDriveFileSharp'; import { join } from './paths'; -const Output = ( { run } ) => { +interface OutputRun { + resultFilenames: string[]; + outputDir: string; + selectOutputDir: () => void; + outputNameNotice: string; + outputName: string; + outputNamePlaceholder: string; + setOutputName: ( value: string ) => void; + outputNameOk: boolean; + openFile: ( filePath: string ) => void; + haveAlignments: boolean; + openOutputDir: () => void; +} + +export interface OutputProps { + run: OutputRun; +} + +const Output = ( { run }: OutputProps ): React.JSX.Element => { const { resultFilenames } = run; const haveResult = resultFilenames.length > 0; @@ -98,8 +115,4 @@ const Output = ( { run } ) => { ); }; -Output.propTypes = { - run: PropTypes.object.isRequired, -}; - export default observer( Output ); diff --git a/src/app/PartitionEditor.js b/src/app/PartitionEditor.tsx similarity index 73% rename from src/app/PartitionEditor.js rename to src/app/PartitionEditor.tsx index 5d8787cb..c5949032 100644 --- a/src/app/PartitionEditor.js +++ b/src/app/PartitionEditor.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import Button from '@mui/material/Button'; import TextField from '@mui/material/TextField'; import Card from '@mui/material/Card'; @@ -12,9 +11,68 @@ import Box from '@mui/material/Box'; import Grid from '@mui/material/Grid'; import LinearProgress from '@mui/material/LinearProgress'; import Typography from '@mui/material/Typography'; +import type { OptionSelectOptionLike } from './components/OptionSelect'; +import type { OptionTextFieldOptionLike } from './components/OptionTextField'; -function PartitionEditor( { alignment } ) { - function handleAdd( event ) { +// Part start and end are numeric options that OptionTextField hands a string. +interface PartPositionOption extends Omit { + setValue: ( value: string | number ) => void; +} + +interface EditorPartition { + partToAdd: { + type: OptionSelectOptionLike; + aaType: OptionSelectOptionLike; + name: OptionTextFieldOptionLike; + start: PartPositionOption; + end: PartPositionOption; + codon: OptionSelectOptionLike; + }; + progress: number; + currentEndValue: number; + maxEndValue: number; + addPartDisabled: boolean; + errorMessage: string; + isDefault: boolean; + text: string; + addPart: () => void; + reset: () => void; +} + +interface EditorAlignment { + showPartition: boolean; + partition: EditorPartition; + filename: string; + numSequences: number; + length: number; + // Alignment defines no partitionHelperText, so this reads undefined. + partitionHelperText?: string; + hidePartition: () => void; +} + +interface OnCardAlignment { + partitionFileContent: string; + partitionText: string; + // Alignment defines no partitionHelperText, so this reads undefined. + partitionHelperText?: string; + setPartitionText: ( value: string ) => void; + setShowPartition: ( value: boolean ) => void; +} + +export interface PartitionEditorProps { + alignment: EditorAlignment; + className?: string; +} + +export interface PartitionOnCardProps { + alignment: OnCardAlignment; + className?: string; +} + +function PartitionEditor( { + alignment, +}: PartitionEditorProps ): React.JSX.Element | null { + function handleAdd( _event: React.MouseEvent ): void { alignment.partition.addPart(); } @@ -144,28 +202,27 @@ function PartitionEditor( { alignment } ) { ); } -PartitionEditor.propTypes = { - alignment: PropTypes.object.isRequired, - className: PropTypes.string, -}; - const PartitionEditorObserver = observer( PartitionEditor ); -function PartitionOnCard( { alignment } ) { +function PartitionOnCard( { + alignment, +}: PartitionOnCardProps ): React.JSX.Element { // const [partitionText, setPartitionText] = React.useState(alignment.partitionText); const [partitionText, setPartitionText] = React.useState( alignment.partitionFileContent, ); - function handleChange( event ) { + function handleChange( + event: React.ChangeEvent, + ): void { setPartitionText( event.target.value ); } - function onClickCancel( event ) { + function onClickCancel( _event: React.MouseEvent ): void { alignment.setShowPartition( false ); } - function onClickSave( event ) { + function onClickSave( _event: React.MouseEvent ): void { alignment.setPartitionText( partitionText ); alignment.setShowPartition( false ); } @@ -221,11 +278,6 @@ function PartitionOnCard( { alignment } ) { ); } -PartitionOnCard.propTypes = { - alignment: PropTypes.object.isRequired, - className: PropTypes.string, -}; - const PartitionOnCardObserver = observer( PartitionOnCard ); export { diff --git a/src/app/PartitionFileCard.js b/src/app/PartitionFileCard.tsx similarity index 89% rename from src/app/PartitionFileCard.js rename to src/app/PartitionFileCard.tsx index 4be9995c..0434f753 100644 --- a/src/app/PartitionFileCard.js +++ b/src/app/PartitionFileCard.tsx @@ -1,6 +1,5 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import DeleteForeverIcon from '@mui/icons-material/DeleteForever'; import Chip from '@mui/material/Chip'; import Card from '@mui/material/Card'; @@ -8,7 +7,20 @@ import CardHeader from '@mui/material/CardHeader'; import CardContent from '@mui/material/CardContent'; import Box from '@mui/material/Box'; -function PartitionFileCard( { run } ) { +interface CardRun { + havePartitionFile: boolean; + partitionFileName: string; + partitionFileContent: string; + removePartitionFile: () => void; +} + +export interface PartitionFileCardProps { + run: CardRun; +} + +function PartitionFileCard( { + run, +}: PartitionFileCardProps ): React.JSX.Element | null { if ( !run.havePartitionFile ) { return null; } @@ -83,10 +95,6 @@ function PartitionFileCard( { run } ) { ); } -PartitionFileCard.propTypes = { - run: PropTypes.object.isRequired, -}; - const PartitionFileCardObserver = observer( PartitionFileCard ); export default PartitionFileCardObserver; diff --git a/src/app/Raxml.js b/src/app/Raxml.tsx similarity index 80% rename from src/app/Raxml.js rename to src/app/Raxml.tsx index 32281c7a..50f7730d 100644 --- a/src/app/Raxml.js +++ b/src/app/Raxml.tsx @@ -1,8 +1,8 @@ import React, { useCallback } from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import Button from '@mui/material/Button'; import OptionSelect from './components/OptionSelect'; +import type { OptionSelectOptionLike } from './components/OptionSelect'; import Box from '@mui/material/Box'; import Typography from '@mui/material/Typography'; import Tooltip from '@mui/material/Tooltip'; @@ -10,9 +10,30 @@ import IconButton from '@mui/material/IconButton'; import FileCopyIcon from '@mui/icons-material/FileCopy'; import { FormHelperText } from '@mui/material'; -const Raxml = ( { run, store } ) => { +interface RaxmlRun { + command: string; + binary: OptionSelectOptionLike; + numThreads: OptionSelectOptionLike; + modelTestIsRunningOnAlignment: boolean; + cancelModeltestOnAlignment: () => void; + running: boolean; + cancel: () => void; + startDisabled: boolean; + start: () => void; +} + +interface RaxmlStore { + setAppSnack: () => void; +} + +export interface RaxmlProps { + run: RaxmlRun; + store: RaxmlStore; +} + +const Raxml = ( { run, store }: RaxmlProps ): React.JSX.Element => { const copyCommand = useCallback( async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.copyText( run.command ); store.setAppSnack(); }, [run.command, store] ); @@ -89,9 +110,4 @@ const Raxml = ( { run, store } ) => { ); }; -Raxml.propTypes = { - run: PropTypes.object.isRequired, - store: PropTypes.object.isRequired, -}; - export default observer( Raxml ); diff --git a/src/app/TreeCard.js b/src/app/TreeCard.tsx similarity index 79% rename from src/app/TreeCard.js rename to src/app/TreeCard.tsx index ecd3fcf9..3fef7220 100644 --- a/src/app/TreeCard.js +++ b/src/app/TreeCard.tsx @@ -1,9 +1,7 @@ import React from 'react'; import { observer } from 'mobx-react-lite'; -import PropTypes from 'prop-types'; import IconButton from '@mui/material/IconButton'; import MoreVertIcon from '@mui/icons-material/MoreVert'; -import CircularProgress from '@mui/material/CircularProgress'; import Chip from '@mui/material/Chip'; import Menu from '@mui/material/Menu'; import MenuItem from '@mui/material/MenuItem'; @@ -11,19 +9,32 @@ import Card from '@mui/material/Card'; import CardHeader from '@mui/material/CardHeader'; import CardContent from '@mui/material/CardContent'; import Box from '@mui/material/Box'; +import type { SxProps, Theme } from '@mui/material/styles'; -function TreeCard( { sx, tree } ) { - const [anchorEl, setAnchorEl] = React.useState( null ); +interface CardTree { + name: string; + openFile: () => void; + openFolder: () => void; + remove: () => void; +} + +export interface TreeCardProps { + tree: CardTree; + sx?: SxProps; +} - function handleMenuClick( event ) { +function TreeCard( { sx, tree }: TreeCardProps ): React.JSX.Element { + const [anchorEl, setAnchorEl] = React.useState( null ); + + function handleMenuClick( event: React.MouseEvent ): void { setAnchorEl( event.currentTarget ); } - function handleMenuClose() { + function handleMenuClose(): void { setAnchorEl( null ); } - function closeMenuAndRun( callback ) { + function closeMenuAndRun( callback: () => void ): () => void { return () => { callback(); setAnchorEl( null ); @@ -84,24 +95,10 @@ function TreeCard( { sx, tree } ) { title={tree.name} subheader={''} /> - - {tree.loading - ? ( - - - - ) - : null} - ); } // {tree.name} -TreeCard.propTypes = { - tree: PropTypes.object.isRequired, - sx: PropTypes.object, -}; - export default observer( TreeCard ); diff --git a/src/app/bootstrap.ts b/src/app/bootstrap.ts index 905d8596..e6ed79b2 100644 --- a/src/app/bootstrap.ts +++ b/src/app/bootstrap.ts @@ -1,12 +1,6 @@ import store from './store'; import { join } from './paths'; - -interface AlignmentExampleFilesPayload { - fasta: string[]; - phylip: string[]; - dir: string; - outdir: string; -} +import type { ExampleFilesPayload } from '../main/api'; interface AlignmentPathRef { path: string } @@ -15,15 +9,10 @@ const e2e = typeof window !== 'undefined' if ( process.env.NODE_ENV === 'development' || e2e ) { console.log( '\n========= Bootstrapping initial state... =========\n' ); - const { rendererBridge } = window as unknown as { - rendererBridge: { - getExampleFiles: () => Promise; - }; - }; - void rendererBridge.getExampleFiles().then( initDev ); + void window.rendererBridge.getExampleFiles().then( initDev ); } -function initDev( exampleFiles: AlignmentExampleFilesPayload ): void { +function initDev( exampleFiles: ExampleFilesPayload ): void { // if (exampleFiles.length === 0) { // return; // } diff --git a/src/app/components/CodeHighlight.tsx b/src/app/components/CodeHighlight.tsx index e0bec65c..d3e58b7e 100644 --- a/src/app/components/CodeHighlight.tsx +++ b/src/app/components/CodeHighlight.tsx @@ -13,7 +13,7 @@ export interface CodeHighlightProps { sx?: SxProps; } -function CodeHighlight( { code, language, sx }: CodeHighlightProps ) { +function CodeHighlight( { code, language, sx }: CodeHighlightProps ): React.JSX.Element { const codeNode = useRef( null ); useEffect( () => { diff --git a/src/app/components/ErrorBoundary.tsx b/src/app/components/ErrorBoundary.tsx index 8feff30e..606e707d 100644 --- a/src/app/components/ErrorBoundary.tsx +++ b/src/app/components/ErrorBoundary.tsx @@ -35,11 +35,11 @@ class ErrorBoundary extends React.Component< console.log( 'Error catched at React boundary:', error, info ); } - handleClose = () => { + handleClose = (): void => { this.setState( { error: null } ); }; - render() { + render(): React.ReactNode { const { error } = this.state; if ( !error ) { return this.props.children; diff --git a/src/app/components/ErrorDialog.js b/src/app/components/ErrorDialog.tsx similarity index 88% rename from src/app/components/ErrorDialog.js rename to src/app/components/ErrorDialog.tsx index 53034be8..2c817c06 100644 --- a/src/app/components/ErrorDialog.js +++ b/src/app/components/ErrorDialog.tsx @@ -1,5 +1,4 @@ import React from 'react'; -import PropTypes from 'prop-types'; import { Box } from '@mui/material'; import Dialog from '@mui/material/Dialog'; import DialogTitle from '@mui/material/DialogTitle'; @@ -17,11 +16,27 @@ import { getMailtoLinkToReportError } from '../report'; import { reportIssueToGitHub } from '../githubIssue'; const handleReload = () => { - const { rendererBridge } = /** @type {any} */ ( window ); - return rendererBridge.reload(); + return window.rendererBridge.reload(); }; -export default function ErrorDialog( { error, onClose, needReload, title } ) { +type DialogError = Error & { isUserFix?: boolean }; + +export interface ErrorDialogProps { + // Store errors are caught values (unknown) or serialized bridge errors. + error?: unknown; + onClose: () => void; + needReload?: boolean; + title?: string | null; +} + +export default function ErrorDialog( { + error: caught, + onClose, + needReload, + title, +}: ErrorDialogProps ): React.JSX.Element | null { + // The dialog reads name, message and isUserFix as the untyped component did. + const error = caught as DialogError | null | undefined; const [reported, setReported] = React.useState( false ); const mailtoContent = React.useMemo( () => ( error @@ -171,10 +186,3 @@ export default function ErrorDialog( { error, onClose, needReload, title } ) { return returnDialog; } - -ErrorDialog.propTypes = { - error: PropTypes.object, - onClose: PropTypes.func.isRequired, - needReload: PropTypes.bool, - title: PropTypes.string, -}; diff --git a/src/app/components/ModifiedDialog.tsx b/src/app/components/ModifiedDialog.tsx index 83ae1cc9..9181142a 100644 --- a/src/app/components/ModifiedDialog.tsx +++ b/src/app/components/ModifiedDialog.tsx @@ -21,7 +21,7 @@ export default function ModifiedDialog( { show, onClose, messages, -}: ModifiedDialogProps ) { +}: ModifiedDialogProps ): React.JSX.Element | null { if ( !show ) { return null; } diff --git a/src/app/components/OptionSelect.tsx b/src/app/components/OptionSelect.tsx index 4ea4b6bb..33866371 100644 --- a/src/app/components/OptionSelect.tsx +++ b/src/app/components/OptionSelect.tsx @@ -9,11 +9,11 @@ import TextField from '@mui/material/TextField'; export interface OptionSelectChoice { value: string | number; - title: string; + title: string | number; } export interface OptionSelectOptionLike { - notAvailable: boolean; + notAvailable?: boolean; title: string; hoverInfo: string; options: readonly OptionSelectChoice[]; diff --git a/src/app/githubIssue.js b/src/app/githubIssue.ts similarity index 67% rename from src/app/githubIssue.js rename to src/app/githubIssue.ts index 9a7aef35..a722ce8d 100644 --- a/src/app/githubIssue.js +++ b/src/app/githubIssue.ts @@ -1,12 +1,13 @@ import { serializeAndCleanError } from './report'; +import type { StateReport } from '../main/getActiveState'; -function fenced( value ) { +function fenced( value: unknown ): string { return `\`\`\`json ${JSON.stringify( value, null, ' ' )} \`\`\``; } -function githubIssueBody( error, activeState ) { +function githubIssueBody( error: Error, activeState: StateReport ): string { return `Autogenerated report: ${fenced( serializeAndCleanError( error ) )} @@ -18,8 +19,8 @@ ${fenced( activeState )} Process: renderer`; } -export async function reportIssueToGitHub( error ) { - const { rendererBridge, store } = /** @type {any} */ ( window ); +export async function reportIssueToGitHub( error: Error ): Promise { + const { rendererBridge, store } = window; const body = githubIssueBody( error, store.generateReport() ); const info = await rendererBridge.debugInfo(); const url = new URL( 'https://github.com/AntonelliLab/raxmlGUI/issues/new' ); diff --git a/src/app/index.js b/src/app/index.tsx similarity index 95% rename from src/app/index.js rename to src/app/index.tsx index 836d07db..efbd31d3 100644 --- a/src/app/index.js +++ b/src/app/index.tsx @@ -16,7 +16,7 @@ if ( process.env.NODE_ENV !== 'development' ) { } ); } -const Index = () => { +const Index = (): React.JSX.Element => { const { light, dark } = theme; const muiTheme = store.config.isDarkMode ? dark diff --git a/src/app/paths.js b/src/app/paths.ts similarity index 66% rename from src/app/paths.js rename to src/app/paths.ts index b27dc7f9..75abd603 100644 --- a/src/app/paths.js +++ b/src/app/paths.ts @@ -1,15 +1,15 @@ -const sepOf = ( filePath ) => ( filePath.includes( '\\' ) +const sepOf = ( filePath: string ): string => ( filePath.includes( '\\' ) ? '\\' : '/' ); -const stemOf = ( baseName ) => { +const stemOf = ( baseName: string ): string => { const dot = baseName.lastIndexOf( '.' ); return dot > 0 ? baseName.slice( 0, dot ) : baseName; }; -const parsed = ( filePath ) => { +const parsed = ( filePath: string ): { base: string; name: string; dir: string } => { const sep = sepOf( filePath ); const chunks = filePath.split( /[/\\]/ ); const baseName = chunks.pop(); @@ -37,12 +37,12 @@ const parsed = ( filePath ) => { }; }; -export const base = ( filePath ) => parsed( filePath ).base; -export const basename = base; -export const name = ( filePath ) => parsed( filePath ).name; -export const dir = ( filePath ) => parsed( filePath ).dir; +export const base = ( filePath: string ): string => parsed( filePath ).base; +export const basename: typeof base = base; +export const name = ( filePath: string ): string => parsed( filePath ).name; +export const dir = ( filePath: string ): string => parsed( filePath ).dir; -export const join = ( ...parts ) => { +export const join = ( ...parts: string[] ): string => { const present = parts.filter( ( part ) => part !== '' ); if ( present.length === 0 ) { return '.'; @@ -56,6 +56,6 @@ export const join = ( ...parts ) => { : joined; }; -export const quote = ( dir, { windows } ) => ( windows +export const quote = ( dir: string, { windows }: { windows: boolean } ): string => ( windows ? `"${dir}"` : dir ); diff --git a/src/app/promisedComputed.js b/src/app/promisedComputed.ts similarity index 62% rename from src/app/promisedComputed.js rename to src/app/promisedComputed.ts index fbded5c3..bbb8fdb1 100644 --- a/src/app/promisedComputed.js +++ b/src/app/promisedComputed.ts @@ -1,11 +1,16 @@ import { computed, makeObservable } from 'mobx'; import { fromPromise } from 'mobx-utils'; +import type { IPromiseBasedObservable } from 'mobx-utils'; // Replaces computed-async-mobx: its 7.0 build mixes decorators with annotations, which MobX 6 rejects. // Like a computed that unwraps a promise: `init` until the first resolve, then the latest resolved value. // Read it inside a reaction: outside one, every read re-runs `fetch` and returns `init`. -class PromisedComputed { - constructor( init, fetch ) { +class PromisedComputed { + fetch: () => Promise; + + cached: Partial; + + constructor( init: Partial, fetch: () => Promise ) { this.fetch = fetch; this.cached = init; makeObservable( this, { @@ -15,11 +20,11 @@ class PromisedComputed { } // fetch must return a promise (the only caller is async) - get currentState() { + get currentState(): IPromiseBasedObservable { return fromPromise( this.fetch() ); } - get value() { + get value(): T { const state = this.currentState; if ( state.state === 'rejected' ) { throw state.value; @@ -27,12 +32,15 @@ class PromisedComputed { if ( state.state === 'fulfilled' ) { this.cached = state.value; } - return this.cached; + return this.cached as T; // init is a partial placeholder until the first resolve } - get() { + get(): T { return this.value; } } -export const promisedComputed = ( init, fetch ) => new PromisedComputed( init, fetch ); +export const promisedComputed = ( + init: Partial, + fetch: () => Promise, +): PromisedComputed => new PromisedComputed( init, fetch ); diff --git a/src/app/report.js b/src/app/report.ts similarity index 74% rename from src/app/report.js rename to src/app/report.ts index 1818909e..50733f4e 100644 --- a/src/app/report.js +++ b/src/app/report.ts @@ -1,10 +1,12 @@ import { serializeError } from 'serialize-error'; +import type { ErrorObject } from 'serialize-error'; +import type { StateReport } from '../main/getActiveState'; // Mirrors clean-stack@3 default filtering. The page cannot import that package (it loads os). const extractPathRegex = /\s+at.*[(\s](.*)\)?/; const pathRegex = /^(?:(?:(?:node|(?:(?:node:)?internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)(?:\.js)?:\d+:\d+)|native)/; -export const cleanStack = ( stack ) => { +export const cleanStack = ( stack: string ): string => { if ( typeof stack !== 'string' ) { return stack; } @@ -29,7 +31,7 @@ export const cleanStack = ( stack ) => { .join( '\n' ); }; -export const serializeAndCleanError = ( error ) => { +export const serializeAndCleanError = ( error: Error ): ErrorObject => { const err = serializeError( error ); const stack = error && typeof error.stack === 'string' ? error.stack @@ -40,9 +42,9 @@ export const serializeAndCleanError = ( error ) => { return err; }; -const stringify = ( json ) => JSON.stringify( json, null, ' ' ); +const stringify = ( json: unknown ): string => JSON.stringify( json, null, ' ' ); -const createReportBodyForMail = ( error, activeState ) => encodeURI( `Autogenerated report: +const createReportBodyForMail = ( error: Error, activeState: StateReport | undefined ): string => encodeURI( `Autogenerated report: ${stringify( serializeAndCleanError( error ) )} Active state: @@ -52,8 +54,8 @@ ${stringify( activeState )} Process: renderer` ); -export const getMailtoLinkToReportError = ( error ) => { - const { store } = /** @type {any} */ ( window ); +export const getMailtoLinkToReportError = ( error: Error ): string => { + const { store } = window; const activeState = store && typeof store.generateReport === 'function' ? store.generateReport() : undefined; diff --git a/src/app/store/Alignment.js b/src/app/store/Alignment.ts similarity index 75% rename from src/app/store/Alignment.js rename to src/app/store/Alignment.ts index 8c94e42f..c66f1325 100644 --- a/src/app/store/Alignment.js +++ b/src/app/store/Alignment.ts @@ -16,12 +16,71 @@ import { runEvents } from './StoreBase'; import { getFinalDataType } from '../../common/typecheckAlignment'; import UserFixError from '../../common/errors'; import { host } from './host'; +import type { DataType } from '../../common/typecheckAlignment'; +import type { AlignmentSequence } from '../../main/parseAlignment'; +import type { ModelSelectionResult, ModelSelectionSuccessPayload, ModelSelectionFailurePayload } from '../../main/modelSelection'; +import type { RunOutputPayload } from '../../main/processHelpers'; -const raxmlMatrixOptions = raxmlSettings.matrixOptions; -const raxmlNgModelOptions = raxmlNgSettings.modelOptions; +const raxmlMatrixOptions = raxmlSettings.matrixOptions as Record; +const raxmlNgModelOptions = raxmlNgSettings.modelOptions as Record; -class Alignment extends InputFile { - constructor( run, path ) { +interface SettableOption { + value: Value; + setValue: ( value: Value ) => void; +} + +interface AlignmentOwner { + id: number; + haveAlignments: boolean; + usesRaxmlNg: boolean; + showPartitionFor: Alignment | null; + showPartition: ( alignment: Alignment | null ) => void; + parent: { onError: ( error: UserFixError ) => void }; + outputDir: string; + numThreads: { value: number }; + modeltestName: string | undefined; + baseFrequencies: SettableOption; + estimatedFrequencies: SettableOption; + substitutionAscertainment: SettableOption; + substitutionI: SettableOption; + substitutionRate: SettableOption; + substitutionMatrix: SettableOption; + alignments: Alignment[]; + dataType: string; + error: unknown; + afterRun: () => void; + removeAlignment: ( alignment: Alignment ) => void; + stdout: string; + stderr: string; +} + +interface ModelExtra { + label: string; + options: readonly string[]; + value: string; + onChange: ( value: string ) => void; + notAvailable: boolean; + hoverInfo: string; + error: unknown; +} + +// Merged, not class fields: assigned later, so no own property at construction. +interface Alignment { + numSequencesParsed: number; + model: string; +} + +class Alignment extends InputFile { + substitutionModel: RaxmlNgAlignmentSubstitutionModel; + multistateNumber: MultistateNumber; + ngStationaryFrequencies: RaxmlNgModelF; + ngInvariantSites: RaxmlNgModelI; + ngRateHeterogeneity: RaxmlNgModelG; + ngAscertainmentBias: RaxmlNgModelASC; + partition: Partition; + modeltestDisabled: boolean; + + constructor( run: AlignmentOwner, path: string ) { super( run, path ); makeObservable( this, { error: observable, @@ -52,7 +111,6 @@ class Alignment extends InputFile { partitionType: computed, partitionFileContent: computed, ngSubstitutionModelCmd: computed, - numSites: computed, status: computed, modelExtra: computed, modelTestCanRun: computed, @@ -87,27 +145,26 @@ class Alignment extends InputFile { this.listen(); } - error = null; + error: unknown = null; - dataType = undefined; - /** @type {string} */ - aaMatrixName = + dataType: DataType | undefined = undefined; + aaMatrixName: string = raxmlSettings.aminoAcidSubstitutionMatrixOptions.default; size = 0; - fileFormat = undefined; - convertedFrom = undefined; + fileFormat: string | undefined = undefined; + convertedFrom: string | undefined = undefined; converted = false; modified = false; - modificationMessages = []; + modificationMessages: string[] = []; showModifiedSnack = false; showModifiedDialog = false; length = 0; numSequences = 0; - sequences = []; + sequences: AlignmentSequence[] = []; hasInvariantSites = false; - get taxons() { + get taxons(): string[] { return this.sequences.map( ( seq ) => seq.taxon ); } @@ -120,31 +177,32 @@ class Alignment extends InputFile { checkRunSuccess = false; // Partition stuff - get showPartition() { + get showPartition(): boolean { return this.run.showPartitionFor === this; } - setShowPartition = ( value = true ) => { + setShowPartition = ( value = true ): void => { this.run.showPartition( value ? this : null ); }; - hidePartition = () => { + hidePartition = (): void => { this.setShowPartition( false ); }; - setPartitionText = ( value ) => { + setPartitionText = ( value: string ): void => { this.partitionText = value; }; partitionText = ''; - get partitionType() { + get partitionType(): string { if ( this.run.usesRaxmlNg ) { return this.ngSubstitutionModelCmd; } switch ( this.dataType ) { + // @ts-expect-error The parser never sets 'dna'; dead case kept, see #269. case 'dna': case 'nucleotide': return 'DNA'; @@ -159,7 +217,7 @@ class Alignment extends InputFile { } } - get partitionFileContent() { + get partitionFileContent(): string { /* DNA, gene1 = 1-3676 BIN, morph = 3677-3851 @@ -175,15 +233,11 @@ class Alignment extends InputFile { return partitionFileText; } - get ngSubstitutionModelCmd() { + get ngSubstitutionModelCmd(): string { return `${this.substitutionModel.cmdValue}${this.ngStationaryFrequencies.cmdValue}${this.ngInvariantSites.cmdValue}${this.ngRateHeterogeneity.cmdValue}${this.ngAscertainmentBias.cmdValue}`; } - get numSites() { - return this.length; - } - - get status() { + get status(): string { if ( this.error ) { return `Error: ${this.error}`; } @@ -199,7 +253,7 @@ class Alignment extends InputFile { return 'ok'; } - get modelExtra() { + get modelExtra(): ModelExtra | null { switch ( this.dataType ) { case 'protein': // Raxml-ng does not have the aa substitution matrix parameter @@ -211,19 +265,22 @@ class Alignment extends InputFile { options: raxmlSettings.aminoAcidSubstitutionMatrixOptions.options, value: this.aaMatrixName, onChange: this.onChangeAAMatrixName, + notAvailable: false, + hoverInfo: 'Amino Acid Substitution Matrix name', + error: null, }; default: return null; } } - get modelTestCanRun() { + get modelTestCanRun(): boolean { return this.dataType === 'nucleotide' || this.dataType === 'protein'; } modeltestLoading = false; - runModelTest = async () => { + runModelTest = async (): Promise => { // Show an error if there are not enough sequences and dont start the run if ( this.numSequences < 3 ) { this.run.parent.onError( @@ -234,7 +291,7 @@ class Alignment extends InputFile { return; } this.modeltestLoading = true; - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.startModelSelection( { id: this.id, filePath: this.path, @@ -245,15 +302,15 @@ class Alignment extends InputFile { } ); }; - cancelModelTest = () => { + cancelModelTest = (): void => { if ( this.modeltestLoading ) { this.modeltestLoading = false; - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; rendererBridge.cancelModelSelection( this.id ); } }; - setModelFromString = ( { raxml, extraFlag, raxmlNG } ) => { + setModelFromString = ( { raxml, extraFlag, raxmlNG }: ModelSelectionResult ): void => { this.modeltestLoading = false; // For raxml-ng let model = raxmlNG.split( '+' )[0]; @@ -333,8 +390,8 @@ class Alignment extends InputFile { } }; - loadParsedAlignment = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + loadParsedAlignment = async (): Promise => { + const { rendererBridge } = window; try { const parsed = await rendererBridge.parseAlignment( this.id, this.path ); const { alignment, change } = parsed; @@ -374,7 +431,7 @@ class Alignment extends InputFile { } } } ); - } catch ( error ) { + } catch ( error: unknown ) { runInAction( () => { console.error( `Error loading file '${this.path}':`, error ); this.error = error; @@ -385,7 +442,7 @@ class Alignment extends InputFile { } }; - onModelSelectionSuccess = ( { id, result } ) => { + onModelSelectionSuccess = ( { id, result }: ModelSelectionSuccessPayload ): void => { if ( id === this.id ) { console.log( id, 'Modeltest result:', result ); this.setModelFromString( result ); @@ -393,7 +450,7 @@ class Alignment extends InputFile { } }; - onModelSelectionFailure = ( { id, error } ) => { + onModelSelectionFailure = ( { id, error }: ModelSelectionFailurePayload ): void => { if ( id === this.id ) { this.modeltestLoading = false; console.log( id, 'Modeltest error:', error ); @@ -402,7 +459,7 @@ class Alignment extends InputFile { } }; - listen = () => { + listen = (): void => { this.loadParsedAlignment(); this.subscribe( runEvents.onModelSelectionSuccess, this.onModelSelectionSuccess ); this.subscribe( runEvents.onModelSelectionFailure, this.onModelSelectionFailure ); @@ -410,47 +467,47 @@ class Alignment extends InputFile { this.subscribe( runEvents.onRunStderr, this.onRunStderr ); }; - clearModified = () => { + clearModified = (): void => { this.showModifiedSnack = false; this.showModifiedDialog = false; }; - dispose() { + dispose(): void { this.unlisten(); if ( this.modeltestLoading ) { this.cancelModelTest(); } } - remove = () => { + remove = (): void => { this.dispose(); this.run.removeAlignment( this ); }; - onChangeModel = ( event ) => { + onChangeModel = ( event: { target: { value: string } } ): void => { console.log( 'onChangeModel' ); this.model = event.target.value; }; - onChangeAAMatrixName = ( value ) => { + onChangeAAMatrixName = ( value: string ): void => { console.log( 'onChangeAAMatrixName' ); this.aaMatrixName = value; }; - onRunStdout = ( { id, content } ) => { + onRunStdout = ( { id, content }: RunOutputPayload ): void => { if ( id === this.id ) { // TODO: Keep local log? this.run.stdout += content; } }; - onRunStderr = ( { id, content } ) => { + onRunStderr = ( { id, content }: RunOutputPayload ): void => { if ( id === this.id ) { this.run.stderr += content; } }; - getSequenceCode = ( taxon ) => { + getSequenceCode = ( taxon: string ): string => { // TODO: Sort sequences on taxon for quicker search, intersection and union const seq = this.sequences.find( ( seq ) => seq.taxon === taxon ); if ( seq !== undefined ) { diff --git a/src/app/store/AlignmentOptions.test.js b/src/app/store/AlignmentOptions.test.js index 4d5ae669..35057a04 100644 --- a/src/app/store/AlignmentOptions.test.js +++ b/src/app/store/AlignmentOptions.test.js @@ -185,20 +185,20 @@ describe( 'multistate number', () => { it( 'has an error for a missing value', () => { const { alignment } = setup(); - expect( alignment.multistateNumber.error ).toBe( true ); + expect( alignment.multistateNumber.haveError ).toBe( true ); } ); it( 'has an error for a non-integer value', () => { const { alignment } = setup(); alignment.multistateNumber.setValue( '2.5' ); - expect( alignment.multistateNumber.error ).toBe( true ); + expect( alignment.multistateNumber.haveError ).toBe( true ); alignment.multistateNumber.setValue( 'abc' ); - expect( alignment.multistateNumber.error ).toBe( true ); + expect( alignment.multistateNumber.haveError ).toBe( true ); } ); it( 'has no error for a valid value and follows value changes', () => { const { alignment } = setup(); - const { seen, stop } = watch( () => alignment.multistateNumber.error ); + const { seen, stop } = watch( () => alignment.multistateNumber.haveError ); alignment.multistateNumber.setValue( '4' ); stop(); expect( seen ).toEqual( [true, false] ); diff --git a/src/app/store/AlignmentOptions.js b/src/app/store/AlignmentOptions.ts similarity index 68% rename from src/app/store/AlignmentOptions.js rename to src/app/store/AlignmentOptions.ts index 6b8affae..fa86cae1 100644 --- a/src/app/store/AlignmentOptions.js +++ b/src/app/store/AlignmentOptions.ts @@ -1,12 +1,31 @@ import { computed, makeObservable, override } from 'mobx'; +import { ValidationError } from 'yup'; import Option from './Option'; import * as raxmlNgSettings from '../../settings/raxmlng'; const raxmlNgModelOptions = raxmlNgSettings.modelOptions; -class RaxmlNgAlignmentSubstitutionModel extends Option { - constructor( alignment ) { +interface Choice { + value: string; + title: string; +} + +interface RunLike { + haveAlignments: boolean; + usesRaxmlNg: boolean; +} + +interface AlignmentLike { + run: RunLike; + dataType: string; + hasInvariantSites: boolean; + multistateNumber: { value: string }; +} + +class RaxmlNgAlignmentSubstitutionModel extends Option { + alignment: AlignmentLike; + constructor( alignment: AlignmentLike ) { super( alignment.run, '', 'Substitution model' ); makeObservable( this, { options: computed, @@ -15,20 +34,20 @@ class RaxmlNgAlignmentSubstitutionModel extends Option { } ); this.alignment = alignment; } - get options() { + get options(): Choice[] { if ( !this.alignment.run.haveAlignments ) { return []; } - const modelSettings = raxmlNgModelOptions[this.alignment.dataType]; + const modelSettings = ( raxmlNgModelOptions as Record )[this.alignment.dataType]; if ( !modelSettings ) { return []; } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - get notAvailable() { + get notAvailable(): boolean { return !this.alignment.run.haveAlignments; } - get cmdValue() { + get cmdValue(): string { let model = this.value; if ( this.alignment.dataType === 'multistate' ) { model = model.replace( 'x', this.alignment.multistateNumber.value ); @@ -37,8 +56,16 @@ class RaxmlNgAlignmentSubstitutionModel extends Option { } } -class RaxmlNgModelExtraParam extends Option { - constructor( alignment, label, options, { addNone = true } = {} ) { +class RaxmlNgModelExtraParam extends Option { + alignment: AlignmentLike; + optionsSource: Choice[]; + addNone: boolean; + constructor( + alignment: AlignmentLike, + label: string, + options: Choice[], + { addNone = true }: { addNone?: boolean } = {}, + ) { super( alignment.run, addNone ? '' : options[0].value, label ); @@ -53,16 +80,16 @@ class RaxmlNgModelExtraParam extends Option { : options; this.addNone = addNone; } - get options() { + get options(): Choice[] { if ( !this.run.haveAlignments ) { return []; } return this.optionsSource; } - get notAvailable() { + get notAvailable(): boolean { return !this.run.haveAlignments || !this.run.usesRaxmlNg; } - get cmdValue() { + get cmdValue(): string { return this.value === '' ? '' : this.value; @@ -70,7 +97,7 @@ class RaxmlNgModelExtraParam extends Option { } class RaxmlNgModelF extends RaxmlNgModelExtraParam { - constructor( alignment ) { + constructor( alignment: AlignmentLike ) { super( alignment, 'Stationary frequencies', @@ -82,7 +109,7 @@ class RaxmlNgModelF extends RaxmlNgModelExtraParam { } class RaxmlNgModelI extends RaxmlNgModelExtraParam { - constructor( alignment ) { + constructor( alignment: AlignmentLike ) { super( alignment, 'Proportion of invariant sites', @@ -94,7 +121,7 @@ class RaxmlNgModelI extends RaxmlNgModelExtraParam { } class RaxmlNgModelG extends RaxmlNgModelExtraParam { - constructor( alignment ) { + constructor( alignment: AlignmentLike ) { super( alignment, 'Rate heterogeneity', @@ -106,7 +133,7 @@ class RaxmlNgModelG extends RaxmlNgModelExtraParam { } class RaxmlNgModelASC extends RaxmlNgModelExtraParam { - constructor( alignment ) { + constructor( alignment: AlignmentLike ) { super( alignment, 'Ascertainment bias', @@ -120,7 +147,7 @@ class RaxmlNgModelASC extends RaxmlNgModelExtraParam { notAvailable: override, } ); } - get notAvailable() { + get notAvailable(): boolean { return ( !this.run.haveAlignments || !this.run.usesRaxmlNg || @@ -129,8 +156,10 @@ class RaxmlNgModelASC extends RaxmlNgModelExtraParam { } } -class MultistateNumber extends Option { - constructor( alignment ) { +class MultistateNumber extends Option { + alignment: AlignmentLike; + placeholder: string; + constructor( alignment: AlignmentLike ) { super( alignment.run, '', 'Number of states' ); makeObservable( this, { notAvailable: computed, @@ -139,14 +168,16 @@ class MultistateNumber extends Option { this.alignment = alignment; this.placeholder = 'Integer'; } - get notAvailable() { + get notAvailable(): boolean { return ( this.alignment.dataType !== 'multistate' || !this.alignment.run.usesRaxmlNg ); } - get error() { - return !this.value || !Number.isInteger( Number( this.value ) ); + get error(): ValidationError | null { + return !this.value || !Number.isInteger( Number( this.value ) ) + ? new ValidationError( 'Enter an integer number of states' ) + : null; } } diff --git a/src/app/store/AppStore.js b/src/app/store/AppStore.ts similarity index 88% rename from src/app/store/AppStore.js rename to src/app/store/AppStore.ts index b5bc5aec..987ebaf2 100644 --- a/src/app/store/AppStore.js +++ b/src/app/store/AppStore.ts @@ -16,15 +16,13 @@ class AppStore extends StoreBase { citation = new Citation(); config = new Config(); - version = undefined; - showAppSnack = false; - setAppSnack = () => { + setAppSnack = (): void => { this.showAppSnack = true; }; - clearAppSnack = () => { + clearAppSnack = (): void => { this.showAppSnack = false; }; } diff --git a/src/app/store/AstralTree.js b/src/app/store/AstralTree.js deleted file mode 100644 index e1b7f400..00000000 --- a/src/app/store/AstralTree.js +++ /dev/null @@ -1,15 +0,0 @@ -import { action, makeObservable } from 'mobx'; - -import InputFile from './InputFile'; - -class AstralTree extends InputFile { - constructor( ...args ) { - super( ...args ); - makeObservable( this, { remove: action } ); - } - remove = () => { - this.run.removeAstralTree(); - }; -} - -export default AstralTree; diff --git a/src/app/store/AstralTree.ts b/src/app/store/AstralTree.ts new file mode 100644 index 00000000..b4e010e7 --- /dev/null +++ b/src/app/store/AstralTree.ts @@ -0,0 +1,20 @@ +import { action, makeObservable } from 'mobx'; + +import InputFile from './InputFile'; + +interface AstralTreeOwner { + id: number; + removeAstralTree: () => void; +} + +class AstralTree extends InputFile { + constructor( run: AstralTreeOwner, path: string ) { + super( run, path ); + makeObservable( this, { remove: action } ); + } + remove = (): void => { + this.run.removeAstralTree(); + }; +} + +export default AstralTree; diff --git a/src/app/store/Citation.js b/src/app/store/Citation.ts similarity index 93% rename from src/app/store/Citation.js rename to src/app/store/Citation.ts index 731b3013..720f0700 100644 --- a/src/app/store/Citation.js +++ b/src/app/store/Citation.ts @@ -1,5 +1,14 @@ import { observable, action, computed, makeObservable } from 'mobx'; +type CitationFormat = 'txt' | 'ris' | 'bib'; + +interface Reference { + name: string; + bib: string; + ris: string; + txt: string; +} + export default class Citation { constructor() { makeObservable( this, { @@ -13,18 +22,18 @@ export default class Citation { } visible = false; - formats = [ + formats: { value: CitationFormat; name: string }[] = [ { value: 'txt', name: 'Plain text' }, { value: 'ris', name: 'RIS/EndNote' }, { value: 'bib', name: 'BibTeX' }, ]; - format = 'txt'; - setFormat = ( format ) => { + format: CitationFormat = 'txt'; + setFormat = ( format: CitationFormat ): void => { this.format = format; }; - content = [ + content: Reference[] = [ { name: 'raxmlGUI', bib: `@article{https://doi.org/10.1111/2041-210X.13512, @@ -200,19 +209,19 @@ ER - `, }, ]; - get allText() { + get allText(): string { return this.content.map( ( ref ) => ref[this.format] ).join( '\n' ); } - show = () => { + show = (): void => { this.visible = true; }; - hide = () => { + hide = (): void => { this.visible = false; }; - copyToClipboard = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + copyToClipboard = async (): Promise => { + const { rendererBridge } = window; await rendererBridge.copyText( this.allText ); console.log( 'Copied citation to clipboard' ); }; diff --git a/src/app/store/Config.js b/src/app/store/Config.ts similarity index 78% rename from src/app/store/Config.js rename to src/app/store/Config.ts index ba9cd58e..eb9ffc1a 100644 --- a/src/app/store/Config.js +++ b/src/app/store/Config.ts @@ -9,7 +9,7 @@ export default class Config extends StoreBase { setDarkMode: action, } ); this.listen(); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; rendererBridge.getDarkMode().then( ( value ) => { runInAction( () => { this.isDarkMode = !!value; @@ -19,22 +19,22 @@ export default class Config extends StoreBase { isDarkMode = false; - setDarkMode = ( value ) => { + setDarkMode = ( value: boolean ): void => { value = !!value; this.isDarkMode = value; - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; void rendererBridge.setDarkMode( value ); }; - onLightMode = () => { + onLightMode = (): void => { this.setDarkMode( false ); }; - onDarkMode = () => { + onDarkMode = (): void => { this.setDarkMode( true ); }; - listen = () => { + listen = (): void => { this.subscribe( runEvents.onLightMode, this.onLightMode ); this.subscribe( runEvents.onDarkMode, this.onDarkMode ); }; diff --git a/src/app/store/FinalAlignment.js b/src/app/store/FinalAlignment.ts similarity index 72% rename from src/app/store/FinalAlignment.js rename to src/app/store/FinalAlignment.ts index 3a8892ad..77a6d9dc 100644 --- a/src/app/store/FinalAlignment.js +++ b/src/app/store/FinalAlignment.ts @@ -5,9 +5,38 @@ import intersection from 'lodash/intersection'; import FinalPartition from './FinalPartition'; import { getFinalDataType } from '../../common/typecheckAlignment'; import { join } from '../paths'; +import type { DataType } from '../../common/typecheckAlignment'; + +interface FinalAlignmentPart { + filename: string; + dir: string; + path: string; + taxons: string[]; + length: number; + hasInvariantSites: boolean; + dataType?: DataType; + // Read by FinalPartition, which this file hands the run to. + partition: { + isDefault: boolean; + isComplete: boolean; + transform( offset: number, prefix: string ): string; + }; + getSequenceCode: ( taxon: string ) => string; +} + +interface FinalAlignmentOwner { + // Read by FinalPartition, which this file hands the run to. + haveAlignments: boolean; + alignments: FinalAlignmentPart[]; + outputNameSafe: string; + outputDir: string; +} class FinalAlignment { - constructor( run ) { + run: FinalAlignmentOwner; + partition: FinalPartition; + + constructor( run: FinalAlignmentOwner ) { makeObservable( this, { filename: computed, dir: computed, @@ -21,7 +50,6 @@ class FinalAlignment { length: computed, hasInvariantSites: computed, dataType: computed, - modelFlagName: computed, partitionFilePath: computed, partitionFileContent: computed, openFile: action, @@ -36,21 +64,21 @@ class FinalAlignment { this.partition = new FinalPartition( run ); } - get filename() { + get filename(): string { if ( this.numAlignments === 1 ) { return this.run.alignments[0].filename; } return `RAxML_${this.run.outputNameSafe}_concat.txt`; } - get dir() { + get dir(): string { if ( this.numAlignments === 1 ) { return this.run.alignments[0].dir; } return this.run.outputDir; } - get path() { + get path(): string { if ( this.numAlignments === 1 ) { return this.run.alignments[0].path; } @@ -59,7 +87,7 @@ class FinalAlignment { parsingComplete = true; - get numAlignments() { + get numAlignments(): number { return this.run.alignments.length; } @@ -67,11 +95,11 @@ class FinalAlignment { // else drop taxons that doesn't exist in all alignments by taking the intersection fillTaxonGapsWithEmptySeqeunces = true; - setFillTaxonGapsWithEmptySeqeunces = ( checked ) => { + setFillTaxonGapsWithEmptySeqeunces = ( checked: boolean ): void => { this.fillTaxonGapsWithEmptySeqeunces = checked; }; - get taxons() { + get taxons(): string[] { const setMethod = this.fillTaxonGapsWithEmptySeqeunces ? union : intersection; @@ -81,18 +109,18 @@ class FinalAlignment { ); } - get numSequences() { + get numSequences(): number { return this.taxons.length; } - get length() { + get length(): number { return this.run.alignments.reduce( ( sumLength, alignment ) => sumLength + alignment.length, 0, ); } - get hasInvariantSites() { + get hasInvariantSites(): boolean { // If any one of the alignments has invariant sites return true for ( const alignment of this.run.alignments ) { if ( alignment.hasInvariantSites ) { @@ -119,25 +147,13 @@ class FinalAlignment { // return firstType; // } - get dataType() { + get dataType(): DataType | undefined { const { alignments } = this.run; const dataTypes = alignments.map( ( { dataType } ) => dataType ); return getFinalDataType( dataTypes ); } - get modelFlagName() { - const {numAlignments} = this; - if ( numAlignments === 0 ) { - return 'none'; - } - const first = this.run.alignments[0].modelFlagName; - if ( numAlignments === 1 ) { - return first; - } - return first; - } - - get partitionFilePath() { + get partitionFilePath(): string { if ( this.partition.isDefault ) { return ''; } @@ -150,40 +166,40 @@ class FinalAlignment { ); } - get partitionFileContent() { + get partitionFileContent(): string { return this.partition.text; } - openFile = async () => { + openFile = async (): Promise => { await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.openPath( this.path ); }; - openPartition = async () => { + openPartition = async (): Promise => { await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.openPath( this.partitionFilePath ); }; - showFileInFolder = async () => { + showFileInFolder = async (): Promise => { await this.writeConcatenatedAlignment(); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.showItemInFolder( this.path ); }; - openFolder = async () => { + openFolder = async (): Promise => { await this.writeConcatenatedAlignmentAndPartition(); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.showItemInFolder( this.dir ); }; - writeConcatenatedAlignmentAndPartition = async () => { + writeConcatenatedAlignmentAndPartition = async (): Promise => { await this.writeConcatenatedAlignment(); await this.writePartition(); }; - writeConcatenatedAlignment = async () => { + writeConcatenatedAlignment = async (): Promise => { const { taxons, numSequences } = this; try { console.log( @@ -201,20 +217,20 @@ class FinalAlignment { text += this.run.alignments[j].getSequenceCode( taxons[i] ); } } - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.writeFile( this.path, text ); - } catch ( err ) { + } catch ( err: unknown ) { console.error( 'Error writing concatenated alignment:', err ); throw err; } }; - writePartition = async () => { + writePartition = async (): Promise => { try { console.log( `Writing partition to ${this.partitionFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.writeFile( this.partitionFilePath, this.partitionFileContent ); - } catch ( err ) { + } catch ( err: unknown ) { console.error( 'Error writing partition:', err ); throw err; } diff --git a/src/app/store/FinalPartition.js b/src/app/store/FinalPartition.ts similarity index 67% rename from src/app/store/FinalPartition.js rename to src/app/store/FinalPartition.ts index 36bdfb68..2601e69c 100644 --- a/src/app/store/FinalPartition.js +++ b/src/app/store/FinalPartition.ts @@ -1,7 +1,20 @@ import { computed, makeObservable } from 'mobx'; +interface FinalPartitionRun { + haveAlignments: boolean; + alignments: { + length: number; + partition: { + isDefault: boolean; + isComplete: boolean; + transform( offset: number, prefix: string ): string; + }; + }[]; +} + class FinalPartition { - constructor( run ) { + run: FinalPartitionRun; + constructor( run: FinalPartitionRun ) { makeObservable( this, { text: computed, isDefault: computed, @@ -14,11 +27,11 @@ class FinalPartition { DNA, gene1 = 1-3676 BIN, morph = 3677-3851 */ - get text() { + get text(): string { if ( !this.run.haveAlignments ) { return ''; } - const partitionTexts = []; + const partitionTexts: string[] = []; let total = 0; this.run.alignments.forEach( ( alignment, index ) => { partitionTexts.push( alignment.partition.transform( total, `${index}_` ) ); @@ -26,14 +39,14 @@ class FinalPartition { } ); return partitionTexts.join( '\n' ); } - get isDefault() { + get isDefault(): boolean { return ( this.run.alignments.length === 0 || ( this.run.alignments.length === 1 && this.run.alignments[0].partition.isDefault ) ); } - get isComplete() { + get isComplete(): boolean { return this.run.alignments.every( ( alignment ) => alignment.partition.isComplete, ); diff --git a/src/app/store/InputFile.js b/src/app/store/InputFile.ts similarity index 64% rename from src/app/store/InputFile.js rename to src/app/store/InputFile.ts index d9f93945..3c75805e 100644 --- a/src/app/store/InputFile.js +++ b/src/app/store/InputFile.ts @@ -3,10 +3,14 @@ import { observable, computed, action, makeObservable } from 'mobx'; import { base, dir, name } from '../paths'; import StoreBase from './StoreBase'; -class InputFile extends StoreBase { - run = null; +interface InputFileOwner { + id: number; +} + +class InputFile extends StoreBase { + run: Owner = null; - constructor( run, path ) { + constructor( run: Owner, path: string ) { super(); makeObservable( this, { path: observable, @@ -26,37 +30,37 @@ class InputFile extends StoreBase { // Observable because it may change on correcting errors or reformating of alignments path = ''; - get id() { + get id(): string { return `${this.run.id}_${this.path}`; } - get name() { + get name(): string { return name( this.path ); } - get dir() { + get dir(): string { return dir( this.path ); } - get base() { + get base(): string { return base( this.path ); } - get filename() { + get filename(): string { return base( this.path ); } - get ok() { + get ok(): boolean { return this.path !== ''; } - openFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + openFile = async (): Promise => { + const { rendererBridge } = window; await rendererBridge.openPath( this.path ); }; - showFileInFolder = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + showFileInFolder = async (): Promise => { + const { rendererBridge } = window; await rendererBridge.showItemInFolder( this.path ); }; } diff --git a/src/app/store/Option.js b/src/app/store/Option.ts similarity index 56% rename from src/app/store/Option.js rename to src/app/store/Option.ts index 36aa7279..81d95bf6 100644 --- a/src/app/store/Option.js +++ b/src/app/store/Option.ts @@ -1,23 +1,32 @@ import { observable, computed, action, makeObservable } from 'mobx'; import { mixed } from 'yup'; +import type { Schema, ValidationError } from 'yup'; + +interface OptionSettings { + schema?: Schema; + allowOnlyValidChange?: boolean; + helperText?: string; +} + +/** Reactive option with optional validation */ +class Option { + run: Owner; + defaultValue: Value; + title: string; + description: string; + hoverInfo: string; + schema: Schema; + allowOnlyValidChange: boolean; + helperText: string; + value: Value; -class Option { - /** - * Reactive option with optional validation - * @param {Object} run - * @param {*} defaultValue - * @param {String} title - * @param {String} description - * @param {String} hoverInfo - * @param {yup|undefined} schema - */ constructor( - run, - defaultValue, - title, - description, - hoverInfo, - { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, + run: Owner, + defaultValue: Value, + title: string, + description?: string, + hoverInfo?: string, + { schema = undefined, allowOnlyValidChange = false, helperText = '' }: OptionSettings = {}, ) { makeObservable( this, { value: observable, @@ -40,8 +49,7 @@ class Option { this.helperText = helperText; this.value = defaultValue; } - value; - setValue( value ) { + setValue( value: Value ): void { const isValid = this.schema.isValidSync( value ); if ( !this.allowOnlyValidChange || isValid ) { this.value = isValid @@ -49,28 +57,29 @@ class Option { : value; } } - reset() { + reset(): void { this.value = this.defaultValue; } - get isDefault() { + get isDefault(): boolean { return this.value === this.defaultValue; } - get error() { + get error(): ValidationError | boolean | null { try { this.schema.validateSync( this.value ); return null; - } catch ( err ) { - return err; + } catch ( err: unknown ) { + return err as ValidationError; } } - get haveError() { + get haveError(): boolean { return this.error !== null; } - get errorMessage() { + get errorMessage(): string { return this.haveError - ? this.error.message + ? ( this.error as ValidationError ).message : ''; } } +export type { OptionSettings }; export { Option as default }; diff --git a/src/app/store/PartOptions.js b/src/app/store/PartOptions.ts similarity index 70% rename from src/app/store/PartOptions.js rename to src/app/store/PartOptions.ts index 6a6166a9..aad62b71 100644 --- a/src/app/store/PartOptions.js +++ b/src/app/store/PartOptions.ts @@ -1,5 +1,6 @@ import { computed, makeObservable } from 'mobx'; import Option from './Option'; +import type { OptionSettings } from './Option'; import * as raxmlSettings from '../../settings/raxml'; import * as yup from 'yup'; @@ -8,14 +9,35 @@ export const CODON_SPECIFIC = 'Codon specific'; export const CODON_THIRD = 'Third codon'; export const CodonModels = [CODON_NONE, CODON_SPECIFIC, CODON_THIRD]; -class PartBase extends Option { +interface Choice { + value: string; + title: string; +} + +interface AlignmentLike { + run: unknown; + dataType: string; + partitionType: string; + length: number; + partition: { partToAdd: { type: { value: string } } }; +} + +interface PartLike { + partition: { alignment: AlignmentLike }; + aaType: { value: string }; + start: { value: number }; + codon: { value: string }; +} + +class PartBase extends Option { + part: PartLike; constructor( - part, - defaultValue, - title, - description, - hoverInfo, - { schema = undefined, allowOnlyValidChange = false, helperText = '' } = {}, + part: PartLike, + defaultValue: Value, + title: string, + description: string, + hoverInfo: string, + { schema = undefined, allowOnlyValidChange = false, helperText = '' }: OptionSettings = {}, ) { super( part.partition.alignment.run, @@ -34,13 +56,13 @@ class PartBase extends Option { } ); this.part = part; } - get alignment() { + get alignment(): AlignmentLike { return this.part.partition.alignment; } } -class PartType extends PartBase { - constructor( part, value = 'DNA' ) { +class PartType extends PartBase { + constructor( part: PartLike, value = 'DNA' ) { super( part, value, 'Data type', 'Data type of the part', '', { schema: yup.string(), allowOnlyValidChange: true, @@ -51,7 +73,7 @@ class PartType extends PartBase { notAvailable: computed, } ); } - get finalValue() { + get finalValue(): string { const { dataType, partitionType } = this.alignment; if ( dataType === 'protein' || this.value === 'protein' ) { return this.part.aaType.value; @@ -61,7 +83,7 @@ class PartType extends PartBase { } return partitionType; } - get options() { + get options(): Choice[] { const { dataType } = this.alignment; let opts = [dataType]; if ( dataType === '' || dataType === 'mixed' ) { @@ -69,12 +91,12 @@ class PartType extends PartBase { } return opts.map( ( value ) => ( { value, title: value } ) ); } - get notAvailable() { + get notAvailable(): boolean { return this.alignment.dataType !== 'mixed'; } } -class PartAAType extends PartBase { - constructor( part, value = 'BLOSUM62' ) { +class PartAAType extends PartBase { + constructor( part: PartLike, value = 'BLOSUM62' ) { super( part, value, 'Model', 'Substitution model for the part', '', { schema: yup.string(), allowOnlyValidChange: true, @@ -86,12 +108,12 @@ class PartAAType extends PartBase { options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( ( value ) => ( { value, title: value } ), ); - get notAvailable() { + get notAvailable(): boolean { return this.alignment.dataType !== 'protein'; } } -class PartName extends PartBase { - constructor( part, value = 'part1' ) { +class PartName extends PartBase { + constructor( part: PartLike, value = 'part1' ) { super( part, value, 'Name', 'Name of part', '', { schema: yup.string(), // TODO: Check that it is unique within partition allowOnlyValidChange: true, @@ -100,12 +122,13 @@ class PartName extends PartBase { notAvailable: computed, } ); } - get notAvailable() { + get notAvailable(): boolean { return false; } } -class PartStart extends PartBase { - constructor( part, value = 1 ) { +class PartStart extends PartBase { + disabled: boolean; + constructor( part: PartLike, value = 1 ) { super( part, value, 'from', 'Start position for this part', '', { schema: yup.number(), allowOnlyValidChange: false, @@ -115,13 +138,13 @@ class PartStart extends PartBase { } ); this.disabled = true; } - get notAvailable() { + get notAvailable(): boolean { return false; } } -class PartEnd extends PartBase { - constructor( part, value = 1 ) { +class PartEnd extends PartBase { + constructor( part: PartLike, value = 1 ) { super( part, value, @@ -145,23 +168,23 @@ class PartEnd extends PartBase { notAvailable: computed, } ); } - get min() { + get min(): number { return ( this.part.start.value + ( this.part.codon.value === CODON_NONE ? 0 : 2 ) ); } - get max() { + get max(): number { return this.alignment.length; } - get notAvailable() { + get notAvailable(): boolean { return false; } } -class PartCodon extends PartBase { - constructor( part, value = 'None' ) { +class PartCodon extends PartBase { + constructor( part: PartLike, value = 'None' ) { super( part, value, 'Codon model', '', '', { schema: yup.string(), allowOnlyValidChange: true, @@ -171,7 +194,7 @@ class PartCodon extends PartBase { } ); } options = CodonModels.map( ( value ) => ( { value, title: value } ) ); - get notAvailable() { + get notAvailable(): boolean { return this.alignment.partition.partToAdd.type.value !== 'DNA'; } } diff --git a/src/app/store/Partition.js b/src/app/store/Partition.ts similarity index 79% rename from src/app/store/Partition.js rename to src/app/store/Partition.ts index a55f5e42..de45ae2a 100644 --- a/src/app/store/Partition.js +++ b/src/app/store/Partition.ts @@ -11,7 +11,26 @@ import { PartCodon, } from './PartOptions'; -const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { +interface PartitionAlignment { + // Read by the part options, which this file hands each part to. + run: unknown; + partition: Partition; + dataType: string; + partitionType: string; + aaMatrixName: string; + length: number; +} + +interface PartValues { + type: string; + aaType: string; + name: string; + start: number; + end: number; + codon: string; +} + +const getPartitionType = ( dataType: string, aaMatrixName = 'BLOSUM62' ): string => { // for old raxml switch ( dataType ) { case 'dna': @@ -29,7 +48,14 @@ const getPartitionType = ( dataType, aaMatrixName = 'BLOSUM62' ) => { }; class Part { - constructor( partition, { type, aaType, name, start, end, codon } ) { + partition: Partition; + type: PartType; + aaType: PartAAType; + name: PartName; + start: PartStart; + end: PartEnd; + codon: PartCodon; + constructor( partition: Partition, { type, aaType, name, start, end, codon }: PartValues ) { makeObservable( this, { typePadded: computed, text: computed, @@ -44,7 +70,7 @@ class Part { this.codon = new PartCodon( this, codon ); } - get typePadded() { + get typePadded(): string { return `${this.type.finalValue},`.padEnd( 12 ); } @@ -53,7 +79,7 @@ class Part { * codon 1,2 or 3: Codon specific, add offset 0,1 and 2 respectively and append \3 * codon 12: Third codon, add offset 1 on same row and append \3 on the two ranges */ - _transform = ( offset = 0, namePrefix = '', codon = 0 ) => { + _transform = ( offset = 0, namePrefix = '', codon = 0 ): string => { const nameSuffix = codon === 0 ? '' @@ -72,7 +98,7 @@ class Part { return `${partWithoutRange}${range}`; }; - transform = ( offset = 0, namePrefix = '' ) => { + transform = ( offset = 0, namePrefix = '' ): string => { switch ( this.codon.value ) { case CODON_NONE: return this._transform( offset, namePrefix ); @@ -89,14 +115,14 @@ class Part { } }; - get text() { + get text(): string { // return `${this.typePadded}${this.name.value} = ${this.start.value}-${this.end.value}`; return this.transform(); } - parse = ( row ) => {}; + parse = ( _row: string ): void => {}; - get values() { + get values(): PartValues { return { type: this.type.value, aaType: this.aaType.value, @@ -107,12 +133,15 @@ class Part { }; } - clone = () => { + clone = (): Part => { return new Part( this.partition, this.values ); }; } class Partition { - constructor( alignment ) { + alignment: PartitionAlignment; + defaultPartition: Part; + partToAdd: Part; + constructor( alignment: PartitionAlignment ) { makeObservable( this, { parts: observable, addPart: action, @@ -174,9 +203,9 @@ class Partition { { name: 'React to default partition type change' }, ); } - parts = []; + parts: Part[] = []; // Add current part values - addPart = () => { + addPart = (): void => { this.parts.push( this.partToAdd.clone() ); // Reset or update in partToAdd this.partToAdd.codon.value = CODON_NONE; @@ -188,7 +217,7 @@ class Partition { const oldName = this.partToAdd.name.value; let newName = oldName.replace( /(\d+)$/, - ( _, digits ) => `${Number( digits ) + 1}`, + ( _: string, digits: string ) => `${Number( digits ) + 1}`, ); if ( newName === oldName ) { newName = `${newName}_1`; @@ -196,58 +225,58 @@ class Partition { this.partToAdd.name.value = newName; } }; - get isMixed() { + get isMixed(): boolean { return this.alignment.dataType === 'mixed'; } - get isDefault() { + get isDefault(): boolean { return this.parts.length === 0; } - get maxEndValue() { + get maxEndValue(): number { return this.alignment.length; } - get currentEndValue() { + get currentEndValue(): number { return this.isDefault ? this.defaultPartition.end.value : this.parts[this.parts.length - 1].end.value; } - get isComplete() { + get isComplete(): boolean { return this.currentEndValue === this.maxEndValue; } - get nonDefaultPartitionComplete() { + get nonDefaultPartitionComplete(): boolean { return !this.isDefault && this.isComplete; } - get progress() { + get progress(): number { return this.isDefault ? 100 : ( this.currentEndValue * 100.0 ) / this.alignment.length; } - get haveError() { + get haveError(): boolean { return this.partToAdd.end.haveError; } - get errorMessage() { + get errorMessage(): string { return this.haveError ? `End position error: ${this.partToAdd.end.errorMessage}` : ''; } - get addPartDisabled() { + get addPartDisabled(): boolean { return this.nonDefaultPartitionComplete || this.haveError; } - get text() { + get text(): string { if ( this.isDefault ) { // return this.alignment.partitionFileContent; return this.defaultPartition.text; } return this.parts.map( ( part ) => part.text ).join( '\n' ); } - transform = ( offset = 0, prefix = '' ) => { + transform = ( offset = 0, prefix = '' ): string => { if ( this.isDefault ) { return this.defaultPartition.transform( offset, prefix ); } return this.parts.map( ( part ) => part.transform( offset, prefix ) ).join( '\n' ); }; - reset = () => { + reset = (): void => { if ( this.parts.length > 0 ) { this.parts.splice( 0 ); this.partToAdd.name.value = 'part_1'; diff --git a/src/app/store/Run.computeds.test.js b/src/app/store/Run.computeds.test.js index 5768779a..a0d94a96 100644 --- a/src/app/store/Run.computeds.test.js +++ b/src/app/store/Run.computeds.test.js @@ -119,7 +119,7 @@ describe( 'Run binary computeds', () => { } ); describe( 'Run alignment computeds', () => { - it( 'haveAlignments, taxons and numSites follow the alignments', () => { + it( 'haveAlignments and taxons follow the alignments', () => { const run = makeRun( { alignments: [] } ); expect( run.haveAlignments ).toBe( false ); expect( run.taxons ).toEqual( [] ); @@ -209,10 +209,6 @@ describe( 'Run alignment computeds', () => { expect( makeRun().ngSubstitutionModelCmd ).toBe( 'GTR+G' ); } ); - it( 'numSites is 0 without alignments', () => { - expect( makeRun( { alignments: [] } ).numSites ).toBe( 0 ); - } ); - it( 'needAlignment is always true', () => { expect( makeRun().needAlignment ).toBe( true ); } ); diff --git a/src/app/store/Run.js b/src/app/store/Run.ts similarity index 88% rename from src/app/store/Run.js rename to src/app/store/Run.ts index 35e8ae68..3ecd7361 100644 --- a/src/app/store/Run.js +++ b/src/app/store/Run.ts @@ -35,14 +35,36 @@ import { BackboneConstraintTree, MultifurcatingConstraintTree, } from './RunOptions'; +import type { AnalysisChoice } from './RunOptions'; import { basename, join, quote } from '../paths'; import remove from 'lodash/remove'; import UserFixError from '../../common/errors'; +import type { ErrorObject } from 'serialize-error'; +import type { AstralSuccessPayload } from '../../main/astral'; +import type { RunOutputPayload } from '../../main/processHelpers'; +import type { RunFinishedPayload, RunErrorPayload } from '../../main/startRun'; const { windows } = host; +interface RunParent { + onError: ( error: UserFixError ) => void; + deleteRun: ( run: Run ) => void; +} + +interface FilePathEntry { + path: string; +} +// A CLI argument: seeds and thread counts are pushed as numbers. +type CmdArg = string | number; + class Run extends StoreBase { - constructor( parent, id ) { + parent: RunParent; + finalAlignment: FinalAlignment; + outputNamePlaceholder: string; + modeltestName: string | undefined; + startToken: object | null | undefined; + + constructor( parent: RunParent, id: number ) { super(); makeObservable( this, { analysis: computed, @@ -123,7 +145,6 @@ class Run extends StoreBase { stderr: observable, useBackboneConstraint: observable, useMultifurcatingConstraint: observable, - numSites: computed, needAlignment: computed, removeRun: action, loadAlignmentFiles: action, @@ -168,23 +189,23 @@ class Run extends StoreBase { )[0]?.name; } - id = 0; + id: number = 0; - binary = new Binary( this ); + binary: Binary = new Binary( this ); numThreads = new NumThreads( this ); - raxmlNgSwitch = ( raxmlNgParam, raxmlParam ) => { + raxmlNgSwitch = ( raxmlNgParam: A, raxmlParam: B ): A | B => { if ( this.usesRaxmlNg ) { return raxmlNgParam; } return raxmlParam; }; - get analysis() { + get analysis(): RaxmlNgAnalysis | Analysis { return this.raxmlNgSwitch( new RaxmlNgAnalysis( this ), new Analysis( this ) ); } - get analysisOption() { + get analysisOption(): AnalysisChoice { return this.raxmlNgSwitch( raxmlNgAnalysisOptions.find( ( opt ) => opt.value === this.analysis.value ), analysisOptions.find( ( opt ) => opt.value === this.analysis.value ), @@ -192,10 +213,10 @@ class Run extends StoreBase { } // Analysis params - substitutionMatrix = new SubstitutionMatrix( this ); - substitutionI = new SubstitutionI( this ); + substitutionMatrix: SubstitutionMatrix = new SubstitutionMatrix( this ); + substitutionI: SubstitutionI = new SubstitutionI( this ); substitutionRate = new SubstitutionRate( this ); - substitutionAscertainment = new SubstitutionAscertainment( this ); + substitutionAscertainment: SubstitutionAscertainment = new SubstitutionAscertainment( this ); numRuns = new NumRuns( this ); numRepetitions = new NumRepetitions( this ); numRepetitionsNg = new NumRepetitionsNg( this ); @@ -207,14 +228,14 @@ class Run extends StoreBase { estimatedFrequencies = new EstimatedFrequencies( this ); baseFrequencies = new BaseFrequencies( this ); multistateModel = new MultistateModel( this ); - startingTree = new StartingTree( this ); + startingTree: StartingTree = new StartingTree( this ); tree = new Tree( this ); backboneConstraint = new BackboneConstraintTree( this ); multifurcatingConstraint = new MultifurcatingConstraintTree( this ); - chooseTree = async ( type ) => { - const { rendererBridge } = /** @type {any} */ ( window ); + chooseTree = async ( type: string ): Promise => { + const { rendererBridge } = window; const chosen = await rendererBridge.selectTree( this.id, type ); if ( !chosen ) { return; @@ -222,20 +243,20 @@ class Run extends StoreBase { this.addTreeFiles( chosen.type, [{ path: chosen.filePath }] ); }; - loadTreeFile = () => this.chooseTree( 'tree' ); + loadTreeFile = (): Promise => this.chooseTree( 'tree' ); - loadBackboneConstraintFile = () => this.chooseTree( 'backboneConstraint' ); + loadBackboneConstraintFile = (): Promise => this.chooseTree( 'backboneConstraint' ); - loadMultifurcatingConstraintFile = () => this.chooseTree( 'multifurcatingConstraint' ); + loadMultifurcatingConstraintFile = (): Promise => this.chooseTree( 'multifurcatingConstraint' ); disableCheckUndeterminedSequence = true; outputName = 'output'; - setOutputName = ( value ) => { + setOutputName = ( value: string ): void => { this.outputName = filenamify( value.replace( /\s+/g, '_' ).trim() ); }; - atomAfterRun; // Trigger atom when run is finished to re-run outputNameAvailable + atomAfterRun: ReturnType; // Trigger atom when run is finished to re-run outputNameAvailable outputNameAvailable = promisedComputed( { ok: false, resultFilenames: [] }, @@ -249,14 +270,14 @@ class Run extends StoreBase { ok: false, notice: 'Checking...', outputNameUnused: outputName, - resultFilenames: [], + resultFilenames: [] as string[], }; const outputNameToCheck = outputName || outputNamePlaceholder; const check = atomAfterRun.reportObserved() || outputNameToCheck; if ( !check ) { return defaultValue; } - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; return rendererBridge.checkOutput( { outputDir, outputName: outputNameToCheck, @@ -264,33 +285,33 @@ class Run extends StoreBase { }, ); - get outputNameOk() { + get outputNameOk(): boolean { return this.outputNameAvailable.get().ok; } - get outputNameSafe() { + get outputNameSafe(): string { return ( this.outputNameAvailable.get().outputNameUnused || this.outputNamePlaceholder ); } - get outputNameNotice() { + get outputNameNotice(): string { return this.outputNameOk ? '' : `Output with that id already exists. New run will use output id '${this.outputNameSafe}'`; } - get outputFilenameSafe() { + get outputFilenameSafe(): string { return `${this.outputNameSafe}.tre`; } outputDir = ''; - setOutputDir = ( dir ) => { + setOutputDir = ( dir: string ): void => { this.outputDir = dir; }; - selectOutputDir = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + selectOutputDir = async (): Promise => { + const { rendererBridge } = window; const outputDir = await rendererBridge.selectOutputDir( this.id ); if ( !outputDir ) { return; @@ -298,55 +319,55 @@ class Run extends StoreBase { this.setOutputDir( outputDir ); }; - openOutputDir = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + openOutputDir = async (): Promise => { + const { rendererBridge } = window; await rendererBridge.openPath( this.outputDir ); }; - showPartitionFor = null; - showPartition = ( alignment ) => { + showPartitionFor: Alignment | null = null; + showPartition = ( alignment: Alignment | null ): void => { this.showPartitionFor = alignment; }; - hidePartition = () => { + hidePartition = (): void => { this.showPartition( null ); }; // Result resultDir = ''; - get resultFilenames() { + get resultFilenames(): string[] { return this.outputNameAvailable.get().resultFilenames || []; } - get haveResult() { + get haveResult(): boolean { return this.resultFilenames.length > 0 && this.resultDir === this.outputDir; } - openFile = async ( filePath ) => { - const { rendererBridge } = /** @type {any} */ ( window ); + openFile = async ( filePath: string ): Promise => { + const { rendererBridge } = window; await rendererBridge.openPath( filePath ); }; - get haveAlignments() { + get haveAlignments(): boolean { return this.alignments.length > 0; } - get hasAstralTree() { + get hasAstralTree(): boolean { return !!this.astralTree; } - get taxons() { + get taxons(): string[] { return this.haveAlignments ? this.alignments[0].taxons : []; } - get dataType() { + get dataType(): string { return this.finalAlignment.dataType; } - error = null; + error: ErrorObject | null = null; - get missing() { + get missing(): "" | "Missing tree, please load one." { if ( !this.tree.notAvailable && !this.tree.filePath ) { return 'Missing tree, please load one.'; } @@ -355,18 +376,18 @@ class Run extends StoreBase { running = false; finished = false; - exitCode = 0; - clearFinished = () => { + exitCode: RunFinishedPayload['exitCode'] = 0; + clearFinished = (): void => { this.finished = false; this.exitCode = 0; }; - atomFinished; + atomFinished: ReturnType; - get ok() { + get ok(): boolean { return !this.error && !this.missing; } - get startDisabled() { + get startDisabled(): boolean { return ( ( this.alignments.length === 0 && !this.hasAstralTree ) || !this.ok || @@ -379,24 +400,24 @@ class Run extends StoreBase { } randomSeed = Math.floor( 1000000 * Math.random() ); - get seedParsimony() { + get seedParsimony(): number { return this.randomSeed; } - get seedRapidBootstrap() { + get seedRapidBootstrap(): number { return this.randomSeed; } - get seedBootstrap() { + get seedBootstrap(): number { return this.randomSeed; } - setRandomSeed = ( value ) => { + setRandomSeed = ( value: string | number ): void => { const v = Number( value ); if ( !Number.isNaN( v ) && v !== 0 && v < 1e6 ) { this.randomSeed = v; } }; - get haveRandomSeed() { + get haveRandomSeed(): boolean { const analysisWithSeed = [ 'FT', 'ML', @@ -412,50 +433,50 @@ class Run extends StoreBase { return analysisWithSeed.includes( this.analysis.value ); } - get usesRaxmlNg() { + get usesRaxmlNg(): boolean { return this.binary.value.includes( 'raxml-ng' ); } - get usesModeltestNg() { + get usesModeltestNg(): boolean { return this.binary.value.includes( 'modeltest-ng' ); } - get inputIsAlignment() { + get inputIsAlignment(): boolean { return this.usesModeltest || this.usesRaxml; } - get inputIsTree() { + get inputIsTree(): boolean { return this.usesAstral; } - get usesModeltest() { + get usesModeltest(): boolean { return this.binary.type === 'modeltest'; } - get usesRaxml() { + get usesRaxml(): boolean { return this.binary.type === 'raxml'; } - get usesAstral() { + get usesAstral(): boolean { return this.binary.type === 'astral'; } - get modelTestCanRun() { + get modelTestCanRun(): boolean { return this.dataType === 'nucleotide' || this.dataType === 'protein'; } - get modelTestIsRunningOnAlignment() { + get modelTestIsRunningOnAlignment(): boolean { const running = this.alignments.some( ( alignment ) => alignment.modeltestLoading, ); return running; } - cancelModeltestOnAlignment = () => { + cancelModeltestOnAlignment = (): void => { this.alignments.forEach( ( alignment ) => alignment.cancelModelTest() ); }; - get args() { + get args(): CmdArg[][] { if ( this.usesAstral ) { return this.astralArgs(); } @@ -468,28 +489,28 @@ class Run extends StoreBase { return this.raxmlArgs(); } - get ngSubstitutionModelCmd() { + get ngSubstitutionModelCmd(): string { return this.haveAlignments ? this.alignments[0].ngSubstitutionModelCmd : ''; } - get showModifiedSnack() { + get showModifiedSnack(): boolean { const shouldShow = this.alignments .map( ( a ) => a.showModifiedSnack ) .some( ( e ) => e ); return this.haveAlignments && shouldShow; } - get showModifiedDialog() { + get showModifiedDialog(): boolean { const shouldShow = this.alignments .map( ( a ) => a.showModifiedDialog ) .some( ( e ) => e ); return this.haveAlignments && shouldShow; } - get modificationMessages() { - const messages = []; + get modificationMessages(): string[] { + const messages: string[] = []; this.alignments.forEach( ( a ) => { messages.push( `${a.name}:\n` ); a.modificationMessages.forEach( ( b ) => { @@ -499,17 +520,17 @@ class Run extends StoreBase { return messages; } - get converted() { + get converted(): boolean { const converted = this.alignments.map( ( a ) => a.converted ).some( ( e ) => e ); return this.haveAlignments && converted; } - get modified() { + get modified(): boolean { const modified = this.alignments.map( ( a ) => a.modified ).some( ( e ) => e ); return this.haveAlignments && modified; } - get convertedAlignmentFrom() { + get convertedAlignmentFrom(): string | null { if ( !this.haveAlignments ) { return null; } @@ -517,13 +538,13 @@ class Run extends StoreBase { return convertedAlignments[0].convertedFrom; } - clearShowModified = () => { + clearShowModified = (): void => { for ( let i = 0; i < this.alignments.length; i++ ) { this.alignments[i].clearModified(); } }; - get raxmlSubstitutionModelCmd() { + get raxmlSubstitutionModelCmd(): string { let model = this.substitutionAscertainment.cmdValue + this.substitutionMatrix.cmdValue + @@ -543,8 +564,8 @@ class Run extends StoreBase { return model; } - astralArgs = () => { - const first = []; + astralArgs = (): string[][] => { + const first: string[] = []; first.push( '-i', quote( this.astralTree?.path, { windows } ) ); first.push( '-o', @@ -553,8 +574,8 @@ class Run extends StoreBase { return [first]; }; - modeltestNgArgs = () => { - const first = []; + modeltestNgArgs = (): CmdArg[][] => { + const first: CmdArg[] = []; // data type if ( this.dataType === 'nucleotide' ) { first.push( '-d', 'nt' ); @@ -578,10 +599,10 @@ class Run extends StoreBase { return [first]; }; - raxmlNgArgs = () => { - const first = []; - const second = []; - const third = []; + raxmlNgArgs = (): CmdArg[][] => { + const first: CmdArg[] = []; + const second: CmdArg[] = []; + const third: CmdArg[] = []; const cmdArgs = [first, second, third]; // Possibly empty ones removed in the end switch ( this.analysis.value ) { case 'SC': @@ -778,10 +799,10 @@ class Run extends StoreBase { return cmdArgs.filter( ( args ) => args.length > 0 ); }; - raxmlArgs = () => { - const first = []; - const second = []; - const third = []; + raxmlArgs = (): CmdArg[][] => { + const first: CmdArg[] = []; + const second: CmdArg[] = []; + const third: CmdArg[] = []; const cmdArgs = [first, second, third]; // Possibly empty ones removed in the end switch ( this.analysis.value ) { @@ -820,7 +841,7 @@ class Run extends StoreBase { this.outputDir, `RAxML_fastTree.${this.outputFilenameSafe}`, ); - const next = []; + const next: CmdArg[] = []; if ( !this.numThreads.notAvailable ) { next.push( '-T', this.numThreads.value ); } @@ -849,7 +870,7 @@ class Run extends StoreBase { `RAxML_result.brL.${this.outputFilenameSafe}`, ) : join( this.outputDir, `RAxML_fastTree.${this.outputFilenameSafe}` ); - const next = []; + const next: CmdArg[] = []; if ( !this.numThreads.notAvailable ) { next.push( '-T', this.numThreads.value ); } @@ -914,7 +935,7 @@ class Run extends StoreBase { this.outputDir, `RAxML_bestTree.${this.outputFilenameSafe}`, ); - const next = []; + const next: CmdArg[] = []; if ( !this.numThreads.notAvailable ) { next.push( '-T', this.numThreads.value ); } @@ -1271,7 +1292,7 @@ class Run extends StoreBase { return cmdArgs.filter( ( args ) => args.length > 0 ); }; - get command() { + get command(): string { if ( this.usesAstral ) { return this.args .map( ( cmdArgs ) => `java -jar ${this.binary.value} ${cmdArgs.join( ' ' )}` ) @@ -1282,7 +1303,7 @@ class Run extends StoreBase { .join( ' &&\\\n' ); } - get settingsFileContent() { + get settingsFileContent(): string { let text = `The analysis was run using raxmlGUI 2.0 (version ${this.version}) as follows: Analysis: ${this.analysisOption.title} Binary: ${this.binary.value} version ${this.binary.version} @@ -1300,37 +1321,38 @@ Results saved to: ${this.outputDir} return text; } - get settingsFilePath() { + get settingsFilePath(): string { return join( `${this.outputDir}`, `RAxML_GUI_Settings_${this.outputNameSafe}.txt`, ); } - writeSettings = async () => { + writeSettings = async (): Promise => { try { console.log( `Writing settings to ${this.settingsFilePath}...` ); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.writeFile( this.settingsFilePath, this.settingsFileContent ); - } catch ( err ) { + } catch ( err: unknown ) { console.error( 'Error writing settings:', err ); throw err; } }; - startAstral = async () => { + startAstral = async (): Promise => { const { id, binary, args } = this; console.log( `Start astral run ${id}` ); this.running = true; - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.startAstral( { id, binaryName: binary.value, + // @ts-expect-error the args getter is typed for every binary; ASTRAL args are all strings args, } ); }; - start = async () => { + start = async (): Promise => { const { id, args, @@ -1376,9 +1398,10 @@ Results saved to: ${this.outputDir} return; } console.log( `Start run ${id} with args ${args}` ); - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; await rendererBridge.startRun( { id, + // @ts-expect-error args carry seed and thread numbers the payload type calls strings args, binaryName: binary.value, outputDir, @@ -1391,43 +1414,39 @@ Results saved to: ${this.outputDir} } ); }; - cancel = () => { + cancel = (): void => { this.startToken = null; - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; rendererBridge.cancelRun( this.id ); this.afterRun(); }; - afterRun = () => { + afterRun = (): void => { this.running = false; this.atomAfterRun.reportChanged(); }; - alignments = []; - astralTree = undefined; - code = undefined; + alignments: Alignment[] = []; + astralTree: AstralTree | null | undefined = undefined; + code: undefined = undefined; data = ''; - path = undefined; + path: string | undefined = undefined; stdout = ''; stderr = ''; useBackboneConstraint = false; useMultifurcatingConstraint = false; - get numSites() { - return this.alignments.reduce( ( sum, n ) => sum + n, 0 ); - } - - get needAlignment() { + get needAlignment(): boolean { return true; } - removeRun = () => { + removeRun = (): void => { this.parent.deleteRun( this ); }; - loadAlignmentFiles = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + loadAlignmentFiles = async (): Promise => { + const { rendererBridge } = window; const alignments = await rendererBridge.selectAlignment( this.id ); if ( !alignments ) { return; @@ -1435,8 +1454,8 @@ Results saved to: ${this.outputDir} this.addAlignments( alignments ); }; - loadAstralTree = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + loadAstralTree = async (): Promise => { + const { rendererBridge } = window; const file = await rendererBridge.selectAstralFile( this.id ); if ( !file ) { return; @@ -1444,12 +1463,12 @@ Results saved to: ${this.outputDir} this.addAstralFiles( file ); }; - haveAlignment = ( id ) => { + haveAlignment = ( id: string ): boolean => { // TODO: Input.js queries without id, doe it work as expected? Later queries with path instead of id return this.alignments.findIndex( ( alignment ) => alignment.id === id ) >= 0; }; - addAlignments = ( alignments ) => { + addAlignments = ( alignments: FilePathEntry[] ): void => { alignments.forEach( ( { path } ) => { if ( !this.haveAlignment( path ) ) { this.alignments.push( new Alignment( this, path ) ); @@ -1463,7 +1482,7 @@ Results saved to: ${this.outputDir} } ); }; - addAstralFiles = ( { path } ) => { + addAstralFiles = ( { path }: FilePathEntry ): void => { if ( !this.hasAstralTree ) { this.astralTree = new AstralTree( this, path ); this.setOutputName( this.astralTree.name ); @@ -1473,7 +1492,7 @@ Results saved to: ${this.outputDir} } }; - removeAlignment = ( alignment ) => { + removeAlignment = ( alignment: Alignment ): void => { const oldDataType = this.dataType; const index = this.alignments.indexOf( alignment ); if ( index >= 0 ) { @@ -1490,38 +1509,38 @@ Results saved to: ${this.outputDir} } }; - removeAstralTree = () => { + removeAstralTree = (): void => { this.astralTree = null; }; - get canLoadAlignment() { + get canLoadAlignment(): boolean { return ( ( this.binary.type === 'raxml' || this.binary.type === 'modeltest' ) && !this.havePartitionFile ); } - get canLoadAstralTree() { + get canLoadAstralTree(): boolean { return this.usesAstral && !this.hasAstralTree; } partitionFile = ''; partitionFileContent = ''; - get partitionFileName() { + get partitionFileName(): string { return basename( this.partitionFile ); } - get havePartitionFile() { + get havePartitionFile(): boolean { return this.partitionFile !== ''; } - get canLoadPartitionFile() { + get canLoadPartitionFile(): boolean { return this.alignments.length === 1 && !this.havePartitionFile; } - loadPartitionFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + loadPartitionFile = async (): Promise => { + const { rendererBridge } = window; const filePath = await rendererBridge.selectPartitionFile( this.id ); if ( !filePath ) { return; @@ -1529,12 +1548,12 @@ Results saved to: ${this.outputDir} await this.addPartitionFiles( [{ path: filePath }] ); }; - addPartitionFiles = async ( files ) => { + addPartitionFiles = async ( files: FilePathEntry[] ): Promise => { if ( !files.length ) { return; } const { path } = files[0]; - const { rendererBridge } = /** @type {any} */ ( window ); + const { rendererBridge } = window; const content = await rendererBridge.readFile( path ); runInAction( () => { this.partitionFile = path; @@ -1542,7 +1561,7 @@ Results saved to: ${this.outputDir} } ); }; - addTreeFiles = ( type, files ) => { + addTreeFiles = ( type: string, files: FilePathEntry[] ): void => { if ( !files.length ) { return; } @@ -1562,39 +1581,39 @@ Results saved to: ${this.outputDir} } }; - removePartitionFile = () => { + removePartitionFile = (): void => { this.partitionFile = ''; this.partitionFileContent = ''; }; - clearStdout = () => { + clearStdout = (): void => { this.stdout = ''; }; - clearStderr = () => { + clearStderr = (): void => { this.stderr = ''; }; - clearConsole = () => { + clearConsole = (): void => { this.clearStdout(); this.clearStderr(); }; - clearError = () => { + clearError = (): void => { this.error = null; }; - reset = () => { + reset = (): void => { this.outGroup.reset(); this.removePartitionFile(); }; - dispose = () => { + dispose = (): void => { this.cancel(); this.unlisten(); }; - listen = () => { + listen = (): void => { this.subscribe( runEvents.onRunStdout, this.onRunStdout ); this.subscribe( runEvents.onRunStderr, this.onRunStderr ); this.subscribe( runEvents.onRunFinished, this.onRunFinished ); @@ -1606,19 +1625,19 @@ Results saved to: ${this.outputDir} // Listeners // ----------------------------------------------------------- - onRunStdout = ( { id, content } ) => { + onRunStdout = ( { id, content }: RunOutputPayload ): void => { if ( id === this.id ) { this.stdout += content; } }; - onRunStderr = ( { id, content } ) => { + onRunStderr = ( { id, content }: RunOutputPayload ): void => { if ( id === this.id ) { this.stderr += content; } }; - onAstralSuccess = ( { id, exitCode } ) => { + onAstralSuccess = ( { id, exitCode }: AstralSuccessPayload ): void => { if ( id === this.id ) { console.log( `Process ${id} finished with exitCode '${exitCode}'` ); this.resultDir = this.outputDir; @@ -1629,7 +1648,7 @@ Results saved to: ${this.outputDir} } }; - onRunFinished = ( { id, resultDir, resultFilenames, exitCode } ) => { + onRunFinished = ( { id, resultDir, resultFilenames, exitCode }: RunFinishedPayload ): void => { if ( id === this.id ) { console.log( `Process ${id} finished with exitCode '${exitCode}' and result filenames ${resultFilenames} in dir ${resultDir}.`, @@ -1642,7 +1661,7 @@ Results saved to: ${this.outputDir} } }; - onRunError = ( { id, error } ) => { + onRunError = ( { id, error }: RunErrorPayload ): void => { if ( id === this.id ) { console.log( `Process ${id} finished with error:`, error ); this.error = error; @@ -1650,15 +1669,15 @@ Results saved to: ${this.outputDir} } }; - onBackboneConstraint = ( event, params ) => { + onBackboneConstraint = ( _event: unknown, _params: unknown ): void => { this.useBackboneConstraint = !this.useBackboneConstraint; }; - onMultifurcatingConstraint = ( event, params ) => { + onMultifurcatingConstraint = ( _event: unknown, _params: unknown ): void => { this.useMultifurcatingConstraint = !this.useMultifurcatingConstraint; }; - generateReport = ( { maxStdoutLength = 1000 } = {} ) => { + generateReport = ( { maxStdoutLength = 1000 }: { maxStdoutLength?: number } = {} ): { command: string; stdout: string; } => { const { command, stdout } = this; return { command, diff --git a/src/app/store/RunList.js b/src/app/store/RunList.ts similarity index 72% rename from src/app/store/RunList.js rename to src/app/store/RunList.ts index a5630c9a..8be3847a 100644 --- a/src/app/store/RunList.js +++ b/src/app/store/RunList.ts @@ -1,10 +1,11 @@ import { observable, computed, action, makeObservable } from 'mobx'; +import type { StateReport } from '../../main/getActiveState'; import Run from './Run'; import AppStore from './AppStore'; import { runEvents } from './StoreBase'; class RunList extends AppStore { - runs = []; + runs: Run[] = []; activeIndex = 0; constructor() { @@ -29,27 +30,27 @@ class RunList extends AppStore { this.listen(); } - error = null; - errorTitle = null; - clearError = () => { + error: unknown = null; + errorTitle: string | null = null; + clearError = (): void => { this.error = null; this.errorTitle = null; }; - get activeRun() { + get activeRun(): Run { return this.runs[this.activeIndex]; } - addRun = () => { + addRun = (): void => { let maxId = 0; - this.runs.forEach( ( run ) => ( maxId = Math.max( run.id, maxId ) ) ); + this.runs.forEach( ( run: Run ) => ( maxId = Math.max( run.id, maxId ) ) ); this.runs.push( new Run( this, maxId + 1 ) ); this.activeIndex = this.runs.length - 1; }; - deleteRun = ( run ) => { + deleteRun = ( run: Run ): void => { run.dispose(); - const runIndex = this.runs.findIndex( ( m ) => m.id === run.id ); + const runIndex = this.runs.findIndex( ( m: Run ) => m.id === run.id ); this.runs.splice( runIndex, 1 ); if ( this.runs.length === 0 ) { this.runs.push( new Run( this, 1 ) ); @@ -57,36 +58,36 @@ class RunList extends AppStore { this.activeIndex = Math.min( this.runs.length - 1, this.activeIndex ); }; - setActive = ( index ) => { + setActive = ( index: number ): void => { this.activeIndex = index; }; - deleteActive = () => { + deleteActive = (): void => { this.deleteRun( this.activeRun ); }; - onError = ( error ) => { + onError = ( error: unknown ): void => { this.errorTitle = null; this.error = error; }; - onUnhandledError = ( { title, error } ) => { + onUnhandledError = ( { title, error }: { title: string; error: unknown } ): void => { console.log( `Unhandled error:`, error ); this.errorTitle = title; this.error = error; }; - onBackboneConstraint = ( event, params ) => { + onBackboneConstraint = (): void => { this.activeRun.useBackboneConstraint = !this.activeRun.useBackboneConstraint; }; - onMultifurcatingConstraint = ( event, params ) => { + onMultifurcatingConstraint = (): void => { this.activeRun.useMultifurcatingConstraint = !this.activeRun.useMultifurcatingConstraint; }; - listen = () => { + listen = (): void => { this.subscribe( runEvents.onUnhandledError, this.onUnhandledError ); this.subscribe( runEvents.onAddRun, this.addRun ); this.subscribe( runEvents.onRemoveRun, this.deleteActive ); @@ -97,7 +98,7 @@ class RunList extends AppStore { ); }; - generateReport = ( { maxStdoutLength = 1000 } = {} ) => { + generateReport = ( { maxStdoutLength = 1000 } = {} ): StateReport => { return this.activeRun.generateReport( { maxStdoutLength } ); }; } diff --git a/src/app/store/RunOptions.js b/src/app/store/RunOptions.ts similarity index 72% rename from src/app/store/RunOptions.js rename to src/app/store/RunOptions.ts index bb7ca28f..091d55ff 100644 --- a/src/app/store/RunOptions.js +++ b/src/app/store/RunOptions.ts @@ -6,6 +6,45 @@ import { host } from './host'; import { basename, dir, name } from '../paths'; import * as raxmlSettings from '../../settings/raxml'; +/** What the option classes read from the run that owns them */ +interface RunOwner { + binary: { value: string }; + analysis: { value: string }; + analysisOption: { params: string[] }; + startingTree: { notAvailable: boolean; value: string }; + substitutionMatrix: { notGTR: boolean }; + substitutionI: { isSet: boolean }; + substitutionAscertainment: { isSet: boolean }; + finalAlignment: { hasInvariantSites: boolean }; + taxons: string[]; + haveAlignments: boolean; + dataType: string; + usesRaxmlNg: boolean; + usesModeltestNg: boolean; + useBackboneConstraint: boolean; + useMultifurcatingConstraint: boolean; +} + +interface BinaryInfo { + name: string; + multithreaded?: boolean; + version: string; + type: string; + initial?: boolean; +} + +export interface AnalysisChoice { + title: string; + value: string; + params: string[]; + needTree?: boolean; +} + +interface Choice { + value: Value; + title: string | number; +} + const raxmlMatrixOptions = raxmlSettings.matrixOptions; const raxmlRateOptions = raxmlSettings.rateOptions; const raxmlIOptions = raxmlSettings.iOptions; @@ -15,7 +54,7 @@ export const MAX_NUM_CPUS = navigator.hardwareConcurrency || 1; // On Windows 7 (= 6.1) use older versions of RAxML const [majorVersion, minorVersion] = host.release.split( '.' ); -const winBinaries = +const winBinaries: BinaryInfo[] = majorVersion === '6' && minorVersion === '1' ? [ // TODO: add raxml ng windows exe @@ -93,7 +132,7 @@ const winBinaries = const likelyARM = host.arch.includes( 'arm64' ) || host.cpuModel.includes( 'Apple' ); -const armBinaries = [ +const armBinaries: BinaryInfo[] = [ { name: 'modeltest-ng-ARM64', multithreaded: true, @@ -101,7 +140,7 @@ const armBinaries = [ type: 'modeltest', }, ]; -const x64Binaries = [ +const x64Binaries: BinaryInfo[] = [ { name: 'modeltest-ng', multithreaded: true, @@ -110,7 +149,7 @@ const x64Binaries = [ }, ]; -const allBinaries = host.windows +const allBinaries: BinaryInfo[] = host.windows ? winBinaries : [ ...( !likelyARM @@ -156,7 +195,7 @@ const allBinaries = host.windows // }, ]; -export const binaries = allBinaries.filter( ( { multithreaded } ) => +export const binaries: BinaryInfo[] = allBinaries.filter( ( { multithreaded } ) => MAX_NUM_CPUS === 1 ? !multithreaded : true, @@ -165,7 +204,7 @@ export const binaries = allBinaries.filter( ( { multithreaded } ) => const initialBinaryName = binaries.filter( ( { initial } ) => initial )[0].name; // Available parameters for different analysis -const params = { +const params: Record = { brL: 'brL', SHlike: 'SHlike', combinedOutput: 'combinedOutput', @@ -177,7 +216,7 @@ const params = { outGroup: 'outGroup', }; -export const analysisOptions = [ +export const analysisOptions: AnalysisChoice[] = [ { title: 'Fast tree search', value: 'FT', @@ -226,7 +265,7 @@ export const analysisOptions = [ }, ]; -export const raxmlNgAnalysisOptions = [ +export const raxmlNgAnalysisOptions: AnalysisChoice[] = [ { title: 'Sanity check', value: 'SC', @@ -260,79 +299,79 @@ export const raxmlNgAnalysisOptions = [ }, ]; -export class Binary extends Option { - constructor( run ) { +export class Binary extends Option { + constructor( run: RunOwner ) { super( run, initialBinaryName, 'Binary', 'Name of binary' ); makeObservable( this, { version: computed, type: computed, } ); } - options = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); - get version() { + options: Choice[] = binaries.map( ( { name } ) => ( { value: name, title: name } ) ); + get version(): string { return binaries.filter( ( b ) => b.name === this.value )[0].version; } - get type() { + get type(): string { return binaries.filter( ( b ) => b.name === this.value )[0].type; } } -export class NumThreads extends Option { - constructor( run ) { +export class NumThreads extends Option { + constructor( run: RunOwner ) { super( run, 2, 'Threads', 'Number of cpu threads' ); makeObservable( this, { notAvailable: computed, } ); } - options = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { + options: Choice[] = range( 1, MAX_NUM_CPUS + 1 ).map( ( value ) => ( { value, title: value, } ) ); - get notAvailable() { + get notAvailable(): boolean { return !( /PTHREADS/.test( this.run.binary.value ) || this.run.usesModeltestNg ); } } -export class Analysis extends Option { - constructor( run ) { +export class Analysis extends Option { + constructor( run: RunOwner ) { super( run, 'ML+rBS', 'Analysis', 'Type of analysis' ); } - options = analysisOptions.map( ( { value, title } ) => ( { value, title } ) ); + options: Choice[] = analysisOptions.map( ( { value, title } ) => ( { value, title } ) ); } -export class RaxmlNgAnalysis extends Option { - constructor( run ) { +export class RaxmlNgAnalysis extends Option { + constructor( run: RunOwner ) { super( run, 'ML+TBE+con', 'Analysis', 'Type of analysis' ); } - options = raxmlNgAnalysisOptions.map( ( { value, title } ) => ( { + options: Choice[] = raxmlNgAnalysisOptions.map( ( { value, title } ) => ( { value, title, } ) ); } -export class NumRuns extends Option { - constructor( run ) { +export class NumRuns extends Option { + constructor( run: RunOwner ) { super( run, 1, 'Runs', 'Number of runs' ); makeObservable( this, { notAvailable: computed, } ); } - options = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); - get notAvailable() { + options: Choice[] = [1, 10, 20, 50, 100, 500].map( ( value ) => ( { value, title: value } ) ); + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.runs ); } } -export class NumRepetitions extends Option { - constructor( run ) { +export class NumRepetitions extends Option { + constructor( run: RunOwner ) { super( run, 100, 'Reps.', 'Number of repetitions' ); makeObservable( this, { notAvailable: computed, } ); } - options = [ + options: Choice[] = [ 100, 200, 500, @@ -343,30 +382,30 @@ export class NumRepetitions extends Option { 'autoMRE_IGN', 'autoFC', ].map( ( value ) => ( { value, title: value } ) ); - get notAvailable() { + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.reps ); } } -export class NumRepetitionsNg extends Option { - constructor( run ) { +export class NumRepetitionsNg extends Option { + constructor( run: RunOwner ) { super( run, 100, 'Reps.', 'Number of repetitions' ); makeObservable( this, { notAvailable: computed, } ); } - options = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { + options: Choice[] = [100, 200, 500, 1000, 10000, 'autoMRE'].map( ( value ) => ( { value, title: value, } ) ); - get notAvailable() { + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.repsNg ); } } //TODO: Another branch lengths option for FT? ('compute brL' vs 'BS brL' for the rest) -export class BranchLength extends Option { - constructor( run ) { +export class BranchLength extends Option { + constructor( run: RunOwner ) { super( run, false, @@ -378,13 +417,13 @@ export class BranchLength extends Option { notAvailable: computed, } ); } - get notAvailable() { + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.brL ); } } -export class SHlike extends Option { - constructor( run ) { +export class SHlike extends Option { + constructor( run: RunOwner ) { super( run, false, @@ -396,45 +435,45 @@ export class SHlike extends Option { notAvailable: computed, } ); } - get notAvailable() { + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.SHlike ); } } -export class CombinedOutput extends Option { - constructor( run ) { +export class CombinedOutput extends Option { + constructor( run: RunOwner ) { super( run, false, 'Combined output', 'Concatenate output trees' ); makeObservable( this, { notAvailable: computed, isUsed: computed, } ); } - get notAvailable() { + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.combinedOutput ); } - get isUsed() { + get isUsed(): boolean { return this.value && !this.notAvailable; } } -export class StartingTree extends Option { - constructor( run ) { +export class StartingTree extends Option { + constructor( run: RunOwner ) { super( run, 'Maximum parsimony', 'Starting tree', '' ); makeObservable( this, { notAvailable: computed, } ); } - options = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { + options: Choice[] = ['Maximum parsimony', 'User defined'].map( ( value ) => ( { value, title: value, } ) ); - get notAvailable() { + get notAvailable(): boolean { return !this.run.analysisOption.params.includes( params.startingTree ); } } -export class OutGroup extends Option { - constructor( run ) { +export class OutGroup extends Option { + constructor( run: RunOwner ) { super( run, [''], 'Outgroup', '' ); makeObservable( this, { options: computed, @@ -444,40 +483,41 @@ export class OutGroup extends Option { } ); this.multiple = true; } - get options() { + multiple: boolean; + get options(): Choice[] { return ['', ...this.run.taxons].map( ( value ) => ( { value, title: value, } ) ); } - setValue( value ) { + setValue( value: string[] ): void { if ( this.value.includes( '' ) ) { - this.value = value.filter( ( v ) => v !== '' ); + this.value = value.filter( ( v: string ) => v !== '' ); return; } if ( !this.value.includes( '' ) && value.includes( '' ) ) { - this.value = value.filter( ( v ) => v === '' ); + this.value = value.filter( ( v: string ) => v === '' ); return; } this.value = value; } - get notAvailable() { + get notAvailable(): boolean { return ( !this.run.haveAlignments || !this.run.analysisOption.params.includes( params.outGroup ) ); } - get cmdValue() { + get cmdValue(): string { return this.value.includes( '' ) ? '' : this.value.join( ',' ); } } -export class SubstitutionMatrix extends Option { - constructor( run ) { +export class SubstitutionMatrix extends Option { + constructor( run: RunOwner ) { super( run, 'GTR', 'Substitution matrix' ); makeObservable( this, { options: computed, @@ -487,11 +527,11 @@ export class SubstitutionMatrix extends Option { notGTR: computed, } ); } - get options() { + get options(): Choice[] { if ( !this.run.haveAlignments ) { return []; } - const modelSettings = raxmlMatrixOptions[this.run.dataType]; + const modelSettings = ( raxmlMatrixOptions as Record )[this.run.dataType]; if ( !modelSettings ) { return []; } @@ -502,7 +542,7 @@ export class SubstitutionMatrix extends Option { : `${value} + GAMMA`, } ) ); } - get notAvailable() { + get notAvailable(): boolean { return ( !this.run.haveAlignments || this.run.dataType === 'binary' || @@ -511,7 +551,7 @@ export class SubstitutionMatrix extends Option { this.run.usesRaxmlNg ); } - get cmdValue() { + get cmdValue(): string { if ( this.run.dataType === 'binary' ) { return 'BIN'; } @@ -526,7 +566,7 @@ export class SubstitutionMatrix extends Option { } return this.value; } - get extraCmdValue() { + get extraCmdValue(): string { switch ( this.value ) { case 'JC': return '--JC69'; @@ -538,13 +578,13 @@ export class SubstitutionMatrix extends Option { return ''; } } - get notGTR() { + get notGTR(): boolean { return this.value !== 'GTR'; } } -export class SubstitutionRate extends Option { - constructor( run ) { +export class SubstitutionRate extends Option { + constructor( run: RunOwner ) { super( run, 'GAMMA', 'Substitution rates' ); makeObservable( this, { options: computed, @@ -553,7 +593,7 @@ export class SubstitutionRate extends Option { isCAT: computed, } ); } - get options() { + get options(): Choice[] { if ( !this.run.haveAlignments ) { return []; } @@ -563,7 +603,7 @@ export class SubstitutionRate extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - get notAvailable() { + get notAvailable(): boolean { return ( !this.run.haveAlignments || ( ( this.run.dataType === 'dna' || @@ -573,19 +613,19 @@ export class SubstitutionRate extends Option { this.run.usesRaxmlNg ); } - get cmdValue() { + get cmdValue(): string { if ( this.run.substitutionMatrix.notGTR ) { return 'GAMMA'; } return this.value; } - get isCAT() { + get isCAT(): boolean { return this.value === 'CAT'; } } -export class SubstitutionI extends Option { - constructor( run ) { +export class SubstitutionI extends Option { + constructor( run: RunOwner ) { super( run, 'none', 'Proportion of invariant sites' ); makeObservable( this, { options: computed, @@ -594,7 +634,7 @@ export class SubstitutionI extends Option { isSet: computed, } ); } - get options() { + get options(): Choice[] { if ( !this.run.haveAlignments ) { return []; } @@ -604,25 +644,25 @@ export class SubstitutionI extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - get notAvailable() { + get notAvailable(): boolean { return ( this.run.substitutionAscertainment.isSet || !this.run.haveAlignments || this.run.usesRaxmlNg ); } - get cmdValue() { + get cmdValue(): string { return this.value === 'none' ? '' : 'I'; } - get isSet() { + get isSet(): boolean { return this.value !== 'none'; } } -export class SubstitutionAscertainment extends Option { - constructor( run ) { +export class SubstitutionAscertainment extends Option { + constructor( run: RunOwner ) { super( run, 'none', 'Ascertainment bias correction' ); makeObservable( this, { options: computed, @@ -632,7 +672,7 @@ export class SubstitutionAscertainment extends Option { isSet: computed, } ); } - get options() { + get options(): Choice[] { if ( !this.run.haveAlignments ) { return []; } @@ -642,7 +682,7 @@ export class SubstitutionAscertainment extends Option { } return modelSettings.options.map( ( value ) => ( { value, title: value } ) ); } - get notAvailable() { + get notAvailable(): boolean { return ( !this.run.haveAlignments || this.run.usesRaxmlNg || @@ -651,12 +691,12 @@ export class SubstitutionAscertainment extends Option { this.run.substitutionI.isSet ); } - get cmdValue() { + get cmdValue(): string { return this.value === 'none' ? '' : 'ASC_'; } - get extraCmdValue() { + get extraCmdValue(): string { switch ( this.value ) { case "Lewis' method": return '--asc-corr=lewis'; @@ -668,13 +708,13 @@ export class SubstitutionAscertainment extends Option { return ''; } } - get isSet() { + get isSet(): boolean { return this.value !== 'none'; } } -export class AAMatrixName extends Option { - constructor( run ) { +export class AAMatrixName extends Option { + constructor( run: RunOwner ) { super( run, 'BLOSUM62', @@ -685,16 +725,16 @@ export class AAMatrixName extends Option { notAvailable: computed, } ); } - options = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( + options: Choice[] = raxmlSettings.aminoAcidSubstitutionMatrixOptions.options.map( ( value ) => ( { value, title: value } ), ); - get notAvailable() { + get notAvailable(): boolean { return this.run.dataType !== 'protein'; } } -export class EstimatedFrequencies extends Option { - constructor( run ) { +export class EstimatedFrequencies extends Option { + constructor( run: RunOwner ) { super( run, false, @@ -706,13 +746,13 @@ export class EstimatedFrequencies extends Option { notAvailable: computed, } ); } - get notAvailable() { + get notAvailable(): boolean { return this.run.dataType === 'protein' || this.run.usesRaxmlNg; } } -export class BaseFrequencies extends Option { - constructor( run ) { +export class BaseFrequencies extends Option { + constructor( run: RunOwner ) { super( run, 'default', @@ -723,33 +763,33 @@ export class BaseFrequencies extends Option { notAvailable: computed, } ); } - options = [ + options: Choice[] = [ { title: 'From model', value: 'default' }, { title: 'Empirical', value: 'F' }, { title: 'Estimated (ML)', value: 'X' }, ]; - get notAvailable() { + get notAvailable(): boolean { return this.run.dataType !== 'protein' || this.run.usesRaxmlNg; } } -export class MultistateModel extends Option { - constructor( run ) { +export class MultistateModel extends Option { + constructor( run: RunOwner ) { super( run, 'GTR', 'Multistate model' ); makeObservable( this, { notAvailable: computed, } ); } - options = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( + options: Choice[] = raxmlSettings.kMultistateSubstitutionModelOptions.options.map( ( value ) => ( { value, title: value } ), ); - get notAvailable() { + get notAvailable(): boolean { return this.run.dataType !== 'multistate' || this.run.usesRaxmlNg; } } -class TreeFile extends Option { - constructor( run ) { +class TreeFile extends Option { + constructor( run: RunOwner ) { super( run, '', 'Tree', '' ); makeObservable( this, { filePath: observable, @@ -764,42 +804,42 @@ class TreeFile extends Option { } ); } filePath = ''; - get haveFile() { + get haveFile(): boolean { return !!this.filePath; } - get filename() { + get filename(): string { return basename( this.filePath ); } - get name() { + get name(): string { return name( this.filePath ); } - get dir() { + get dir(): string { return dir( this.filePath ); } - setFilePath = ( filePath ) => { + setFilePath = ( filePath: string ): void => { this.filePath = filePath; }; - openFolder = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + openFolder = async (): Promise => { + const { rendererBridge } = window; await rendererBridge.showItemInFolder( this.filePath ); }; - openFile = async () => { - const { rendererBridge } = /** @type {any} */ ( window ); + openFile = async (): Promise => { + const { rendererBridge } = window; await rendererBridge.openPath( this.filePath ); }; - remove = () => { + remove = (): void => { this.setFilePath( '' ); }; } export class Tree extends TreeFile { - constructor( ...args ) { + constructor( ...args: ConstructorParameters ) { super( ...args ); makeObservable( this, { notAvailable: computed, } ); } - get notAvailable() { + get notAvailable(): boolean { return !( this.run.analysisOption.params.includes( params.tree ) || ( !this.run.startingTree.notAvailable && @@ -809,7 +849,7 @@ export class Tree extends TreeFile { } export class BackboneConstraintTree extends TreeFile { - constructor( ...args ) { + constructor( ...args: ConstructorParameters ) { super( ...args ); makeObservable( this, { isSet: computed, @@ -817,10 +857,10 @@ export class BackboneConstraintTree extends TreeFile { notAvailable: computed, } ); } - get isSet() { + get isSet(): boolean { return this.run.useBackboneConstraint && this.haveFile; } - get canConstraint() { + get canConstraint(): boolean { const analysisWithConstraint = [ 'ML', 'ML+rBS', @@ -835,13 +875,13 @@ export class BackboneConstraintTree extends TreeFile { ]; return analysisWithConstraint.includes( this.run.analysis.value ); } - get notAvailable() { + get notAvailable(): boolean { return !this.run.useBackboneConstraint || !this.canConstraint; } } export class MultifurcatingConstraintTree extends TreeFile { - constructor( ...args ) { + constructor( ...args: ConstructorParameters ) { super( ...args ); makeObservable( this, { isSet: computed, @@ -849,10 +889,10 @@ export class MultifurcatingConstraintTree extends TreeFile { notAvailable: computed, } ); } - get isSet() { + get isSet(): boolean { return this.run.useMultifurcatingConstraint && this.haveFile; } - get canConstraint() { + get canConstraint(): boolean { const analysisWithConstraint = [ 'ML', 'ML+rBS', @@ -867,7 +907,7 @@ export class MultifurcatingConstraintTree extends TreeFile { ]; return analysisWithConstraint.includes( this.run.analysis.value ); } - get notAvailable() { + get notAvailable(): boolean { return !this.run.useMultifurcatingConstraint || !this.canConstraint; } } diff --git a/src/app/store/StoreBase.js b/src/app/store/StoreBase.ts similarity index 64% rename from src/app/store/StoreBase.js rename to src/app/store/StoreBase.ts index 8efd2ac6..f3c9496f 100644 --- a/src/app/store/StoreBase.js +++ b/src/app/store/StoreBase.ts @@ -1,5 +1,7 @@ import { runInAction } from 'mobx'; +import type { RendererBridge } from '../../common/rendererBridge'; + export const runEvents = { onRunStdout: 'onRunStdout', onRunStderr: 'onRunStderr', @@ -15,33 +17,39 @@ export const runEvents = { onToggleBackboneConstraint: 'onToggleBackboneConstraint', onToggleMultifurcatingConstraint: 'onToggleMultifurcatingConstraint', onUnhandledError: 'onUnhandledError', -}; +} as const; export default class StoreBase { - eventStops = []; + eventStops: ( () => void )[] = []; + + version: string | undefined = undefined; constructor() { this._init(); } - subscribe = ( name, listener ) => { - const { rendererBridge } = /** @type {any} */ ( window ); - this.eventStops.push( rendererBridge[name]( listener ) ); + subscribe = ( + name: K, + listener: Parameters[0], + ): void => { + const { rendererBridge } = window; + const on = rendererBridge[name] as ( l: typeof listener ) => () => void; + this.eventStops.push( on( listener ) ); }; - unlisten = () => { + unlisten = (): void => { while ( this.eventStops.length ) { this.eventStops.pop()(); } }; // A method: a field here would clash with a subclass's dispose field. - dispose() { + dispose(): void { this.unlisten(); } - _init = () => { - const { rendererBridge } = /** @type {any} */ ( window ); + _init = (): void => { + const { rendererBridge } = window; rendererBridge.getVersion().then( ( version ) => { runInAction( () => { this.version = version; diff --git a/src/app/store/alignmentStore.test.js b/src/app/store/alignmentStore.test.js index bd97d9fa..0ae40f35 100644 --- a/src/app/store/alignmentStore.test.js +++ b/src/app/store/alignmentStore.test.js @@ -92,14 +92,11 @@ describe( 'Alignment observable fields update the page store', () => { stop(); } ); - it( 'length updates numSites and getSequenceCode padding', () => { + it( 'length drives getSequenceCode padding', () => { const { alignment } = setup(); - const { seen, stop } = track( () => alignment.numSites ); set( alignment, { sequences: parsed.sequences, length: 4 } ); - expect( seen ).toEqual( [0, 4] ); expect( alignment.getSequenceCode( 'Homo' ) ).toBe( 'ACGT' ); expect( alignment.getSequenceCode( 'Missing' ) ).toBe( '----' ); - stop(); } ); it( 'dataType updates partitionType, modelTestCanRun and modelExtra', () => { diff --git a/src/app/store/finalAlignment.test.js b/src/app/store/finalAlignment.test.js index 50e79769..7e16f813 100644 --- a/src/app/store/finalAlignment.test.js +++ b/src/app/store/finalAlignment.test.js @@ -75,14 +75,6 @@ describe( 'FinalAlignment computeds', () => { expect( f.partitionFileContent ).not.toBe( '' ); } ); - it( 'reports no model flag without alignments, else the first one', () => { - expect( makeRun( [] ).finalAlignment.modelFlagName ).toBe( 'none' ); - const run = makeRun( [A, B] ); - expect( run.finalAlignment.modelFlagName ).toBe( - run.alignments[0].modelFlagName, - ); - } ); - it( 'combines data types and invariant sites over alignments', () => { const run = makeRun( [A, B] ); expect( run.finalAlignment.dataType ).toBe( 'mixed' ); diff --git a/src/app/store/host.js b/src/app/store/host.ts similarity index 60% rename from src/app/store/host.js rename to src/app/store/host.ts index 64304ae6..5e810f23 100644 --- a/src/app/store/host.js +++ b/src/app/store/host.ts @@ -1,5 +1,5 @@ const { rendererBridge: { host }, -} = /** @type {any} */ ( window ); +} = window; export { host }; diff --git a/src/app/store/index.js b/src/app/store/index.ts similarity index 75% rename from src/app/store/index.js rename to src/app/store/index.ts index 8f3ad5b3..36f071f7 100644 --- a/src/app/store/index.js +++ b/src/app/store/index.ts @@ -3,6 +3,6 @@ import RunList from './RunList'; const store = new RunList(); window.store = store; -const { rendererBridge } = /** @type {any} */ ( window ); +const { rendererBridge } = window; rendererBridge.provideStateReport( () => store.generateReport() ); export default store; diff --git a/src/app/store/runInputActions.test.js b/src/app/store/runInputActions.test.js index cc1c27f6..8cf791fa 100644 --- a/src/app/store/runInputActions.test.js +++ b/src/app/store/runInputActions.test.js @@ -1,5 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. -import { autorun, runInAction } from 'mobx'; +import { autorun } from 'mobx'; import Run from './Run'; @@ -307,15 +307,3 @@ describe( 'tree files', () => { expect( run.multifurcatingConstraint.filePath ).toBe( '' ); } ); } ); - -describe( 'state set directly', () => { - it( 'setting the alignments inside runInAction moves numSites', () => { - const { seen, dispose } = watch( () => run.numSites ); - runInAction( () => { - run.alignments = [ 3, 4 ]; - } ); - dispose(); - - expect( seen ).toEqual( [ 0, 7 ] ); - } ); -} ); diff --git a/src/common/fastaParser.js b/src/common/fastaParser.ts similarity index 79% rename from src/common/fastaParser.js rename to src/common/fastaParser.ts index 4fbb8f35..98f88d47 100644 --- a/src/common/fastaParser.js +++ b/src/common/fastaParser.ts @@ -1,5 +1,18 @@ import UserFixError from './errors'; -export const isFasta = ( lines ) => { + +export interface FastaSequence { + taxon: string; + code: string; +} + +export interface FastaAlignment { + sequences: FastaSequence[]; + numSequences: number; + length: number; + fileFormat: 'FASTA'; +} + +export const isFasta = ( lines: string[] ): boolean => { for ( let i = 0; i < lines.length; ++i ) { const line = lines[0].trim(); if ( line.length === 0 || line[0] === '#' ) { @@ -11,12 +24,12 @@ export const isFasta = ( lines ) => { } return false; }; -export const parse = ( lines ) => { +export const parse = ( lines: string[] ): FastaAlignment => { if ( !isFasta( lines ) ) { throw new Error( `Could not parse the file as a FASTA file` ); } let lineIndex = 0; - const parseTaxon = ( line ) => { + const parseTaxon = ( line: string ): string => { if ( line[0] !== '>' ) { throw new Error( `Expected a '>' to start a taxon line` ); } @@ -26,16 +39,16 @@ export const parse = ( lines ) => { } return taxon; }; - const parseCode = ( line ) => { + const parseCode = ( line: string ): string => { const code = line.replace( /\s+/g, '' ); if ( !code ) { throw new Error( `Empty sequence at line ${lineIndex + 1}` ); } return code; }; - const sequences = []; + const sequences: FastaSequence[] = []; let taxon = ''; - let codeLines = []; + let codeLines: string[] = []; const addSequence = () => { const code = codeLines.join( '' ); sequences.push( { taxon, code } ); @@ -69,7 +82,7 @@ export const parse = ( lines ) => { } } // console.log('Sequences:', sequences); - const alignment = { + const alignment: FastaAlignment = { sequences, numSequences, length, diff --git a/src/common/io.ts b/src/common/io.ts index c814e120..6f3a0bde 100644 --- a/src/common/io.ts +++ b/src/common/io.ts @@ -13,6 +13,7 @@ interface AlignmentSequence { interface Alignment { sequences: AlignmentSequence[]; + length: number; } export const parseAlignment = async ( filePath: string ): Promise => { diff --git a/src/common/phylipParser.js b/src/common/phylipParser.ts similarity index 86% rename from src/common/phylipParser.js rename to src/common/phylipParser.ts index 79a34f29..fc4b0eea 100644 --- a/src/common/phylipParser.js +++ b/src/common/phylipParser.ts @@ -1,13 +1,29 @@ import UserFixError from './errors'; + +export interface PhylipSequence { + taxon: string; + code: string; +} + +export interface PhylipAlignment { + sequences: PhylipSequence[]; + numSequences: number; + length: number; + fileFormat: 'PHYLIP'; + interleaved: boolean; + relaxed: boolean; + numLinesPerTaxa: number; +} + const rePhylipHeader = /^\s*(\d+)\s+(\d+)(?:\s+([is]))?\s*$/; // 3 78 i (optional i/s for interleaved/sequential) -export const isPhylip = ( lines ) => { +export const isPhylip = ( lines: string[] ): boolean => { if ( lines.length === 0 ) { throw new Error( 'No lines' ); } return rePhylipHeader.test( lines[0] ); }; //TODO: Make PhylipParserError class -export const parse = ( lines ) => { +export const parse = ( lines: string[] ): PhylipAlignment => { if ( !isPhylip( lines ) ) { throw new Error( 'First line is not a phylip formatted header' ); } @@ -39,13 +55,13 @@ export const parse = ( lines ) => { console.log( 'firstSeqLineIndex:', firstSeqLineIndex, 'lastSeqLineIndex:', lastSeqLineIndex ); console.log( 'numSeqLines:', numSeqLines, 'oneLineSequences:', oneLineSequences ); let numLinesPerTaxa = 1; - const interleavedStartLineIndices = []; + const interleavedStartLineIndices: number[] = []; if ( !oneLineSequences ) { // Check if sequential or interleaved // Interleaved format must have empty lines between interleaved sections let lastEmpty = false; let currentSectionStartLineIndex = firstSeqLineIndex; - const assertCorrectNumberOfSeqLines = ( startIndex, endIndex ) => { + const assertCorrectNumberOfSeqLines = ( startIndex: number, endIndex: number ): void => { const numSeq = endIndex + 1 - startIndex; if ( numSeq !== numSequences ) { throw new UserFixError( `Interleaved section (lines ${startIndex + 1}-${endIndex + 1}) doesn't have specified ${numSequences} lines of sequences.` ); @@ -94,7 +110,7 @@ export const parse = ( lines ) => { ? 1 : numLinesPerTaxa; // Discern if strict or relaxed format, first some helper methods - const getLineIndex = ( seqIndex, subLineIndex = 0 ) => { + const getLineIndex = ( seqIndex: number, subLineIndex = 0 ): number => { const startLineIndex = firstSeqLineIndex + seqIndex * numConsequtiveLinesPerTaxa; if ( subLineIndex === 0 ) { return startLineIndex; @@ -104,17 +120,17 @@ export const parse = ( lines ) => { } return interleavedStartLineIndices[subLineIndex - 1]; }; - const getSeqLine = ( seqIndex, subLineIndex = 0 ) => { + const getSeqLine = ( seqIndex: number, subLineIndex = 0 ): string => { return lines[getLineIndex( seqIndex, subLineIndex )]; }; - const getSeqLines = ( seqIndex ) => { - const seqLines = []; + const getSeqLines = ( seqIndex: number ): string[] => { + const seqLines: string[] = []; for ( let i = 0; i < numLinesPerTaxa; ++i ) { seqLines.push( getSeqLine( seqIndex, i ) ); } return seqLines; }; - const parseSeqAssumingStrictName = ( seqIndex ) => { + const parseSeqAssumingStrictName = ( seqIndex: number ): PhylipSequence => { const line = getSeqLines( seqIndex ).join( '' ); const taxon = line.substring( 0, 10 ).trim(); let code = line.substring( 10 ); @@ -122,13 +138,13 @@ export const parse = ( lines ) => { code = code.replace( /(?<=\S)\s+/g, '' ); return { taxon, code }; }; - const parseSeqAssumingRelaxedName = ( seqIndex ) => { + const parseSeqAssumingRelaxedName = ( seqIndex: number ): PhylipSequence => { const line = getSeqLines( seqIndex ).join( '' ); const [taxon, ...codeChunks] = line.split( /\s+/ ); const code = codeChunks.join( '' ); return { taxon, code }; }; - const checkIsRelaxed = () => { + const checkIsRelaxed = (): boolean => { console.log( `Checking if strict or relaxed from first sequence...` ); // Check the length of the code part assuming strict and relaxe and see which matches const seqIfStrict = parseSeqAssumingStrictName( 0 ); @@ -145,7 +161,7 @@ export const parse = ( lines ) => { }; const isRelaxed = checkIsRelaxed(); // Parse sequences - const sequences = []; + const sequences: PhylipSequence[] = []; const parseSequence = isRelaxed ? parseSeqAssumingRelaxedName : parseSeqAssumingStrictName; @@ -157,7 +173,7 @@ export const parse = ( lines ) => { sequences.push( seq ); } // console.log('Sequences:', sequences); - const alignment = { + const alignment: PhylipAlignment = { sequences, numSequences, length, diff --git a/src/common/rendererBridge.ts b/src/common/rendererBridge.ts new file mode 100644 index 00000000..eeb25b38 --- /dev/null +++ b/src/common/rendererBridge.ts @@ -0,0 +1,79 @@ +// Declared, not derived from the preload: ipc invoke types every result as any. +import type { StateReport } from '../main/getActiveState'; +import type RunList from '../app/store/RunList'; +import type { ExampleFilesPayload } from '../main/api'; +import type { CheckOutputArgs, CheckOutputResult } from '../main/checkOutput'; +import type { + ModelSelectionPayload, + ModelSelectionSuccessPayload, + ModelSelectionFailurePayload, +} from '../main/modelSelection'; +import type { SelectedAlignment } from '../main/selectAlignment'; +import type { SelectedTree } from '../main/selectTree'; +import type { SelectedAstralFile } from '../main/selectAstralFile'; +import type { AstralPayload, AstralSuccessPayload } from '../main/astral'; +import type { RunOutputPayload } from '../main/processHelpers'; +import type { StartRunPayload, RunFinishedPayload, RunErrorPayload } from '../main/startRun'; +import type { AlignmentParseResult } from '../main/parseAlignment'; + +export interface HostInfo { + windows: boolean; + release: string; + arch: string; + cpuModel: string; +} + +// An event payload the page does not read yet; the leaf that reads it tightens it. +type Listener = ( payload: unknown ) => void; +type Unsubscribe = () => void; + +export interface RendererBridge { + host: HostInfo; + provideStateReport: ( fn: () => StateReport ) => void; + copyText: ( text: string ) => Promise; + getExampleFiles: () => Promise; + getVersion: () => Promise; + getDarkMode: () => Promise; + setDarkMode: ( value: boolean ) => Promise; + selectAlignment: ( runId: number ) => Promise; + parseAlignment: ( id: string, filePath: string ) => Promise; + selectAstralFile: ( runId: number ) => Promise; + selectOutputDir: ( runId: number ) => Promise; + checkOutput: ( args: CheckOutputArgs ) => Promise; + readFile: ( filePath: string ) => Promise; + writeFile: ( filePath: string, text: string ) => Promise; + reload: () => Promise; + debugInfo: () => Promise; + openExternal: ( url: string ) => Promise; + openPath: ( fullPath: string ) => Promise; + selectPartitionFile: ( runId: number ) => Promise; + selectTree: ( runId: number, type: string ) => Promise; + showItemInFolder: ( fullPath: string ) => Promise; + startRun: ( payload: StartRunPayload ) => Promise; + cancelRun: ( id: number ) => Promise; + onRunStdout: ( listener: ( payload: RunOutputPayload ) => void ) => Unsubscribe; + onRunStderr: ( listener: ( payload: RunOutputPayload ) => void ) => Unsubscribe; + onRunFinished: ( listener: ( payload: RunFinishedPayload ) => void ) => Unsubscribe; + onRunError: ( listener: ( payload: RunErrorPayload ) => void ) => Unsubscribe; + startAstral: ( payload: AstralPayload ) => Promise; + onAstralSuccess: ( listener: ( payload: AstralSuccessPayload ) => void ) => Unsubscribe; + startModelSelection: ( payload: ModelSelectionPayload ) => Promise; + cancelModelSelection: ( id: string ) => Promise; + onModelSelectionSuccess: ( listener: ( payload: ModelSelectionSuccessPayload ) => void ) => Unsubscribe; + onModelSelectionFailure: ( listener: ( payload: ModelSelectionFailurePayload ) => void ) => Unsubscribe; + onAddRun: ( listener: Listener ) => Unsubscribe; + onRemoveRun: ( listener: Listener ) => Unsubscribe; + onLightMode: ( listener: () => void ) => Unsubscribe; + onDarkMode: ( listener: () => void ) => Unsubscribe; + onToggleBackboneConstraint: ( listener: Listener ) => Unsubscribe; + onToggleMultifurcatingConstraint: ( listener: Listener ) => Unsubscribe; + onUnhandledError: ( listener: Listener ) => Unsubscribe; + getPathForFile: ( file: File ) => string; +} + +declare global { + interface Window { + rendererBridge: RendererBridge; + store: RunList; + } +} diff --git a/src/common/typecheckAlignment.js b/src/common/typecheckAlignment.ts similarity index 83% rename from src/common/typecheckAlignment.js rename to src/common/typecheckAlignment.ts index 593f04d4..cdf6d364 100644 --- a/src/common/typecheckAlignment.js +++ b/src/common/typecheckAlignment.ts @@ -1,5 +1,16 @@ import UserFixError from './errors'; -export const getFinalDataType = ( dataTypes ) => { + +export type DataType = 'protein' | 'nucleotide' | 'multistate' | 'binary' | 'mixed' | 'unknown' | 'invalid'; + +export interface TypecheckableAlignment { + sequences: { taxon: string; code: string; dataType?: DataType }[]; + length: number; + hasInvariantSites?: boolean; + dataType?: DataType; + typecheckingComplete?: boolean; +} + +export const getFinalDataType = ( dataTypes: ( DataType | undefined )[] ): DataType | undefined => { const notUndefinedTypes = dataTypes.filter( ( d ) => d !== undefined ); if ( notUndefinedTypes.length === 0 ) { return undefined; @@ -24,7 +35,7 @@ const reInvalidDNA = /[^ABCDGHKMRSTUVWYNOX?-]/gi; const reInvalidAA = /[^ARNDCQEGHILKMFPSTWYVBZX*?-]/gi; const reInvalidGeneric = /[^0123456789ABCDEFGHIJKLMNOPQRSTU?-]/gi; const reInvalidMixed = /[^0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*?-]/gi; -export function findInvalidCharacter( code, dataType ) { +export function findInvalidCharacter( code: string, dataType: DataType | undefined ): number { // Returns the index of the invalid character if found, else -1 switch ( dataType ) { case 'protein': @@ -51,9 +62,9 @@ export function findInvalidCharacter( code, dataType ) { : -1; } } -function hasInvariantSites( length, sequences ) { +function hasInvariantSites( length: number, sequences: TypecheckableAlignment['sequences'] ): boolean { for ( let i = 0; i < length; i++ ) { - const variantsAtPosition = []; + const variantsAtPosition: string[] = []; for ( const sequence of sequences ) { const site = sequence.code[i]; if ( !variantsAtPosition.includes( site ) ) { @@ -66,19 +77,19 @@ function hasInvariantSites( length, sequences ) { } return false; } -export default function typecheckAlignment( alignment ) { +export default function typecheckAlignment( alignment: T ): T { const acgMatch = /[ACGN?]/i; // Include 'N' and '?' as symbols for missing characters in DNA // const proteinMatch = /[RNDEQHILKMFPSWYVXBZJ]/i; const proteinMatch = /[EFJIJLOPQZX]/i; const binaryMatch = /[01]/; const multistateMatch = /2/; const unknownMatch = /^[N?]+$/i; - const sequenceDataTypes = []; - const dataTypes = new Set(); + const sequenceDataTypes: ( DataType | undefined )[] = []; + const dataTypes = new Set(); let numSequencesTypechecked = 0; - alignment.sequences.forEach( ( sequence, index ) => { + alignment.sequences.forEach( ( sequence ) => { const { code } = sequence; - let dataType = undefined; + let dataType: DataType | undefined; if ( proteinMatch.test( code ) ) { dataType = 'protein'; } else if ( acgMatch.test( code ) ) { diff --git a/src/main/api.ts b/src/main/api.ts index b77dc46e..9edc06d5 100644 --- a/src/main/api.ts +++ b/src/main/api.ts @@ -54,6 +54,12 @@ process.on( 'uncaughtException', ( error: Error ) => { process.on( 'unhandledRejection', ( error: unknown ) => { handleError( 'Unhandled Promise Rejection', error ); } ); +export interface ExampleFilesPayload { + fasta: string[]; + phylip: string[]; + dir: string; + outdir: string; +} const exec = util.promisify( childProcess.exec ); ipcMain.on( ipc.HOST, ( event: IpcMainEvent ) => { const cpu = os.cpus()[0]; @@ -165,12 +171,7 @@ ipcMain.handle( ipc.ALIGNMENT_SELECT, ( _event: IpcMainInvokeEvent, _runId: numb ipcMain.handle( ipc.ASTRAL_FILE_SELECT, ( _event: IpcMainInvokeEvent, _runId: number ) => { return selectAstralFile( ( options: OpenDialogOptions ) => dialog.showOpenDialog( options ) ); } ); -ipcMain.handle( ipc.EXAMPLE_FILES, async (): Promise<{ - fasta: string[]; - phylip: string[]; - dir: string; - outdir: string; -}> => { +ipcMain.handle( ipc.EXAMPLE_FILES, async (): Promise => { const staticDir = getStaticDir(); const dir = path.join( staticDir, 'example-files' ); const outdir = path.join( staticDir, 'test-results' ); diff --git a/src/main/astral.ts b/src/main/astral.ts index d5766310..093ca1eb 100644 --- a/src/main/astral.ts +++ b/src/main/astral.ts @@ -16,12 +16,17 @@ type ProcessExit = | NodeJS.Signals | null; -interface AstralPayload { +export interface AstralPayload { id: RunId; binaryName: string; args: string[][]; } +export interface AstralSuccessPayload { + id: RunId; + exitCode: ProcessExit; +} + export async function runAstral( event: IpcMainEvent, payload: AstralPayload, diff --git a/src/main/checkOutput.ts b/src/main/checkOutput.ts index e8f1d8c3..ac8fe1d1 100644 --- a/src/main/checkOutput.ts +++ b/src/main/checkOutput.ts @@ -3,12 +3,12 @@ import { serializeError } from 'serialize-error'; import type { ErrorObject } from 'serialize-error'; import * as ipc from '../constants/ipc'; -interface CheckOutputArgs { +export interface CheckOutputArgs { outputDir: string; outputName: string; } -interface CheckOutputResult { +export interface CheckOutputResult { outputDir: string; outputName: string; ok: boolean; diff --git a/src/main/getActiveState.ts b/src/main/getActiveState.ts index b646a881..1fb97b61 100644 --- a/src/main/getActiveState.ts +++ b/src/main/getActiveState.ts @@ -5,12 +5,17 @@ import { randomUUID } from 'node:crypto'; import { STATE_REPORT, STATE_REPORT_RESULT } from '../constants/ipc'; import { activeWindow } from './utils/utils'; +export interface StateReport { + command: string; + stdout: string; +} + interface StateReportPayload { id: string; - report: unknown; + report: StateReport | undefined; } -export function getActiveState(): Promise { +export function getActiveState(): Promise { const win = activeWindow(); if ( !win ) { return Promise.resolve( undefined ); diff --git a/src/main/modelSelection.ts b/src/main/modelSelection.ts index ccbd0134..133a02bf 100644 --- a/src/main/modelSelection.ts +++ b/src/main/modelSelection.ts @@ -22,7 +22,7 @@ type ProcessExit = | NodeJS.Signals | null; -interface ModelSelectionPayload { +export interface ModelSelectionPayload { id: string; filePath: string; outputDir: string; @@ -31,6 +31,22 @@ interface ModelSelectionPayload { binaryName: string; } +export interface ModelSelectionResult { + raxml: string; + extraFlag: string | undefined; + raxmlNG: string; +} + +export interface ModelSelectionSuccessPayload { + id: string; + result: ModelSelectionResult; +} + +export interface ModelSelectionFailurePayload { + id: string; + error: unknown; +} + export async function runModelSelection( event: IpcMainEvent, payload: ModelSelectionPayload, @@ -41,7 +57,7 @@ export async function runModelSelection( if ( !stillRunning( id, token ) ) { return; } - send( event, ipc.ALIGNMENT_MODEL_SELECTION_FAILURE, { id, error } ); + send( event, ipc.ALIGNMENT_MODEL_SELECTION_FAILURE, { id, error } satisfies ModelSelectionFailurePayload ); }; const { name } = parsePath( filePath ); const outputPath = path.join( outputDir, `RAxML_GUI_ModelTest_${name}` ); @@ -50,7 +66,7 @@ export async function runModelSelection( await fs.unlink( `${outputPath}.ckp` ); } catch ( _err: unknown ) { } - const args = []; + const args: string[] = []; if ( dataType === 'nucleotide' ) { args.push( '-d', 'nt' ); } @@ -64,7 +80,7 @@ export async function runModelSelection( // modeltest throws errors if the output file already exists args.push( '--force' ); // Number of processors - args.push( '-p', numThreads ); + args.push( '-p', String( numThreads ) ); console.log( `Alignment '${id}': Run modeltest with args ${args}...` ); const stdOuts: string[] = []; const onStdOut = ( content: string ): void => { @@ -109,7 +125,7 @@ export async function runModelSelection( extraFlag, raxmlNG: modelRaxmlNG, }, - } ); + } satisfies ModelSelectionSuccessPayload ); } catch ( err: unknown ) { console.error( `Couldn't parse best models from modeltest-ng output:`, err ); diff --git a/src/main/parseAlignment.ts b/src/main/parseAlignment.ts index 4e98398f..578dcc25 100644 --- a/src/main/parseAlignment.ts +++ b/src/main/parseAlignment.ts @@ -1,11 +1,21 @@ import path from 'path'; -interface AlignmentSequence { +import type { DataType } from '../common/typecheckAlignment'; + +export interface AlignmentSequence { taxon: string; + code: string; } -interface Alignment { +// Optional fields: the parsers and typecheck add them, io.parseAlignment does not declare them. +export interface Alignment { sequences: AlignmentSequence[]; + length: number; + numSequences?: number; + fileFormat?: string; + dataType?: DataType; + hasInvariantSites?: boolean; + typecheckingComplete?: boolean; } interface AlignmentParseTools { @@ -15,7 +25,7 @@ interface AlignmentParseTools { write: ( filePath: string, alignment: Alignment ) => Promise; } -interface AlignmentChange { +export interface AlignmentChange { newFilePath: string; format: string | undefined; converted: boolean | undefined; @@ -23,7 +33,7 @@ interface AlignmentChange { modificationMessages: string[]; } -interface AlignmentParseResult { +export interface AlignmentParseResult { alignment: Alignment; change: AlignmentChange | null; } diff --git a/src/main/processHelpers.ts b/src/main/processHelpers.ts index a47983d2..78c947c8 100644 --- a/src/main/processHelpers.ts +++ b/src/main/processHelpers.ts @@ -24,6 +24,11 @@ type ProcessExit = | NodeJS.Signals | null; +export interface RunOutputPayload { + id: TrackedId; + content: string; +} + interface RunProcessHooks { onStdOut?: ( content: string ) => void; onStdErr?: ( content: string ) => void; diff --git a/src/main/selectAlignment.ts b/src/main/selectAlignment.ts index 6f808914..a5b799ca 100644 --- a/src/main/selectAlignment.ts +++ b/src/main/selectAlignment.ts @@ -5,7 +5,7 @@ type ShowOpenDialog = ( options: OpenDialogOptions, ) => Promise; -interface SelectedAlignment { +export interface SelectedAlignment { path: string; name: string; } diff --git a/src/main/selectAstralFile.ts b/src/main/selectAstralFile.ts index 6778de50..2f600599 100644 --- a/src/main/selectAstralFile.ts +++ b/src/main/selectAstralFile.ts @@ -5,7 +5,7 @@ type ShowOpenDialog = ( options: OpenDialogOptions, ) => Promise; -interface SelectedAstralFile { +export interface SelectedAstralFile { path: string; name: string; } diff --git a/src/main/selectTree.ts b/src/main/selectTree.ts index 36e70da7..b7669684 100644 --- a/src/main/selectTree.ts +++ b/src/main/selectTree.ts @@ -5,7 +5,7 @@ type ShowOpenDialog = ( options: OpenDialogOptions, ) => Promise; -interface SelectedTree { +export interface SelectedTree { type: string; filePath: string; } diff --git a/src/main/startRun.ts b/src/main/startRun.ts index 968b6af4..ef5902b5 100644 --- a/src/main/startRun.ts +++ b/src/main/startRun.ts @@ -7,6 +7,7 @@ import type { IpcMainEvent } from 'electron'; import * as Sentry from '@sentry/electron/main'; import * as ipc from '../constants/ipc'; import { is } from '../common/utils'; +import type { ErrorObject } from 'serialize-error'; import UserFixError from '../common/errors'; import { beginRun, @@ -33,7 +34,7 @@ type ProcessExit = | NodeJS.Signals | null; -interface StartRunPayload { +export interface StartRunPayload { id: RunId; args: string[][]; binaryName: string; @@ -46,6 +47,19 @@ interface StartRunPayload { inputPath: string; } +export interface RunFinishedPayload { + id: RunId; + resultDir: string; + resultFilenames: string[]; + exitCode: ProcessExit; +} + +// `error` is the serialized plain object `send` puts on the wire. +export interface RunErrorPayload { + id: RunId; + error: ErrorObject; +} + async function combineOutput( outputDir: string, outputFilename: string ): Promise { // Use type command on windows, cat on Mac or Linux const command = is.windows diff --git a/src/pageNodeImports.test.js b/src/pageNodeImports.test.js index e6e2d4fc..c3930c98 100644 --- a/src/pageNodeImports.test.js +++ b/src/pageNodeImports.test.js @@ -39,11 +39,11 @@ it( 'the page does not import electron, electron-better-ipc, fs, or os', () => { } ); it( 'the page can still import the user-fix error type and the alignment typecheck', () => { - const alignment = fs.readFileSync( path.join( appRoot, 'store', 'Alignment.js' ), 'utf8' ); - const run = fs.readFileSync( path.join( appRoot, 'store', 'Run.js' ), 'utf8' ); + const alignment = fs.readFileSync( path.join( appRoot, 'store', 'Alignment.ts' ), 'utf8' ); + const run = fs.readFileSync( path.join( appRoot, 'store', 'Run.ts' ), 'utf8' ); expect( alignment ).toMatch( /from ['"]\.\.\/\.\.\/common\/typecheckAlignment['"]/ ); expect( alignment ).toMatch( /from ['"]\.\.\/\.\.\/common\/errors['"]/ ); expect( run ).toMatch( /from ['"]\.\.\/\.\.\/common\/errors['"]/ ); - expect( fs.readFileSync( path.join( __dirname, 'app', 'index.js' ), 'utf8' ) ) + expect( fs.readFileSync( path.join( __dirname, 'app', 'index.tsx' ), 'utf8' ) ) .not.toMatch( /from ['"]\.\.\/common\/utils['"]/ ); } ); diff --git a/src/parse-filepath.d.ts b/src/parse-filepath.d.ts new file mode 100644 index 00000000..bad6f4e5 --- /dev/null +++ b/src/parse-filepath.d.ts @@ -0,0 +1,10 @@ +declare module 'parse-filepath' { + interface ParsedPath { + name: string; + base: string; + dir: string; + ext: string; + path: string; + } + export default function parsePath( filePath: string ): ParsedPath; +} diff --git a/src/preload/index.js b/src/preload/index.ts similarity index 55% rename from src/preload/index.js rename to src/preload/index.ts index a141d313..4a7ea142 100644 --- a/src/preload/index.js +++ b/src/preload/index.ts @@ -42,31 +42,42 @@ import { UNHANDLED_ERROR, WRITE_FILE, } from '../constants/ipc'; +import type { RendererBridge, HostInfo } from '../common/rendererBridge'; +import type { CheckOutputArgs } from '../main/checkOutput'; +import type { StateReport } from '../main/getActiveState'; +import type { StartRunPayload, RunFinishedPayload, RunErrorPayload } from '../main/startRun'; +import type { AstralPayload, AstralSuccessPayload } from '../main/astral'; +import type { RunOutputPayload } from '../main/processHelpers'; +import type { + ModelSelectionPayload, + ModelSelectionSuccessPayload, + ModelSelectionFailurePayload, +} from '../main/modelSelection'; -function onEvent( channel, listener ) { - const wrapped = ( _event, payload ) => listener( payload ); +function onEvent( channel: string, listener: ( payload: T ) => void ): () => void { + const wrapped = ( _event: unknown, payload: T ): void => listener( payload ); ipcRenderer.on( channel, wrapped ); return () => ipcRenderer.removeListener( channel, wrapped ); } // Sandboxed preload cannot load Node's os. Main answers once; later reads stay local. -const host = ipcRenderer.sendSync( HOST ); +const host: HostInfo = ipcRenderer.sendSync( HOST ); -let stateReport = null; +let stateReport: ( () => StateReport ) | null = null; -ipcRenderer.on( STATE_REPORT, ( _event, id ) => { +ipcRenderer.on( STATE_REPORT, ( _event: unknown, id: string ): void => { const report = stateReport ? stateReport() : undefined; ipcRenderer.send( STATE_REPORT_RESULT, { id, report } ); } ); -contextBridge.exposeInMainWorld( 'rendererBridge', { +const rendererBridge = { host, - provideStateReport( fn ) { + provideStateReport( fn: () => StateReport ): void { stateReport = fn; }, - copyText( text ) { + copyText( text: string ) { return ipcRenderer.invoke( COPY_TEXT, text ); }, getExampleFiles() { @@ -78,28 +89,28 @@ contextBridge.exposeInMainWorld( 'rendererBridge', { getDarkMode() { return ipcRenderer.invoke( GET_DARK_MODE ); }, - setDarkMode( value ) { + setDarkMode( value: boolean ) { return ipcRenderer.invoke( SET_DARK_MODE, value ); }, - selectAlignment( runId ) { + selectAlignment( runId: number ) { return ipcRenderer.invoke( ALIGNMENT_SELECT, runId ); }, - parseAlignment( id, filePath ) { + parseAlignment( id: string, filePath: string ) { return ipcRenderer.invoke( ALIGNMENT_PARSE, id, filePath ); }, - selectAstralFile( runId ) { + selectAstralFile( runId: number ) { return ipcRenderer.invoke( ASTRAL_FILE_SELECT, runId ); }, - selectOutputDir( runId ) { + selectOutputDir( runId: number ) { return ipcRenderer.invoke( OUTPUT_DIR_SELECT, runId ); }, - checkOutput( { outputDir, outputName } ) { + checkOutput( { outputDir, outputName }: CheckOutputArgs ) { return ipcRenderer.invoke( OUTPUT_CHECK, { outputDir, outputName } ); }, - readFile( filePath ) { + readFile( filePath: string ) { return ipcRenderer.invoke( READ_FILE, filePath ); }, - writeFile( filePath, text ) { + writeFile( filePath: string, text: string ) { return ipcRenderer.invoke( WRITE_FILE, filePath, text ); }, reload() { @@ -108,79 +119,81 @@ contextBridge.exposeInMainWorld( 'rendererBridge', { debugInfo() { return ipcRenderer.invoke( DEBUG_INFO ); }, - openExternal( url ) { + openExternal( url: string ) { return ipcRenderer.invoke( OPEN_EXTERNAL, url ); }, - openPath( fullPath ) { + openPath( fullPath: string ) { return ipcRenderer.invoke( OPEN_PATH, fullPath ); }, - selectPartitionFile( runId ) { + selectPartitionFile( runId: number ) { return ipcRenderer.invoke( PARTITION_FILE_SELECT, runId ); }, - selectTree( runId, type ) { + selectTree( runId: number, type: string ) { return ipcRenderer.invoke( TREE_SELECT, runId, type ); }, - showItemInFolder( fullPath ) { + showItemInFolder( fullPath: string ) { return ipcRenderer.invoke( FILE_SHOW_IN_FOLDER, fullPath ); }, - startRun( payload ) { + startRun( payload: StartRunPayload ) { return ipcRenderer.invoke( RUN_START, payload ); }, - cancelRun( id ) { + cancelRun( id: number ) { return ipcRenderer.invoke( RUN_CANCEL, id ); }, - onRunStdout( listener ) { + onRunStdout( listener: ( payload: RunOutputPayload ) => void ) { return onEvent( RUN_STDOUT, listener ); }, - onRunStderr( listener ) { + onRunStderr( listener: ( payload: RunOutputPayload ) => void ) { return onEvent( RUN_STDERR, listener ); }, - onRunFinished( listener ) { + onRunFinished( listener: ( payload: RunFinishedPayload ) => void ) { return onEvent( RUN_FINISHED, listener ); }, - onRunError( listener ) { + onRunError( listener: ( payload: RunErrorPayload ) => void ) { return onEvent( RUN_ERROR, listener ); }, - startAstral( payload ) { + startAstral( payload: AstralPayload ) { return ipcRenderer.invoke( ASTRAL_REQUEST, payload ); }, - onAstralSuccess( listener ) { + onAstralSuccess( listener: ( payload: AstralSuccessPayload ) => void ) { return onEvent( ASTRAL_SUCCESS, listener ); }, - startModelSelection( payload ) { + startModelSelection( payload: ModelSelectionPayload ) { return ipcRenderer.invoke( ALIGNMENT_MODEL_SELECTION_REQUEST, payload ); }, - cancelModelSelection( id ) { + cancelModelSelection( id: string ) { return ipcRenderer.invoke( ALIGNMENT_MODEL_SELECTION_CANCEL, id ); }, - onModelSelectionSuccess( listener ) { + onModelSelectionSuccess( listener: ( payload: ModelSelectionSuccessPayload ) => void ) { return onEvent( ALIGNMENT_MODEL_SELECTION_SUCCESS, listener ); }, - onModelSelectionFailure( listener ) { + onModelSelectionFailure( listener: ( payload: ModelSelectionFailurePayload ) => void ) { return onEvent( ALIGNMENT_MODEL_SELECTION_FAILURE, listener ); }, - onAddRun( listener ) { + onAddRun( listener: ( payload: unknown ) => void ) { return onEvent( ADD_RUN, listener ); }, - onRemoveRun( listener ) { + onRemoveRun( listener: ( payload: unknown ) => void ) { return onEvent( REMOVE_RUN, listener ); }, - onLightMode( listener ) { + onLightMode( listener: ( payload: unknown ) => void ) { return onEvent( LIGHT_MODE, listener ); }, - onDarkMode( listener ) { + onDarkMode( listener: ( payload: unknown ) => void ) { return onEvent( DARK_MODE, listener ); }, - onToggleBackboneConstraint( listener ) { + onToggleBackboneConstraint( listener: ( payload: unknown ) => void ) { return onEvent( TOGGLE_BACKBONE_CONSTRAINT, listener ); }, - onToggleMultifurcatingConstraint( listener ) { + onToggleMultifurcatingConstraint( listener: ( payload: unknown ) => void ) { return onEvent( TOGGLE_MULTIFURCATING_CONSTRAINT, listener ); }, - onUnhandledError( listener ) { + onUnhandledError( listener: ( payload: unknown ) => void ) { return onEvent( UNHANDLED_ERROR, listener ); }, - getPathForFile( file ) { + getPathForFile( file: File ): string { return webUtils.getPathForFile( file ); }, -} ); +} satisfies RendererBridge; + +contextBridge.exposeInMainWorld( 'rendererBridge', rendererBridge ); diff --git a/src/typecheckBaseline.test.js b/src/typecheckBaseline.test.js index a9b2fe1f..d4ca830b 100644 --- a/src/typecheckBaseline.test.js +++ b/src/typecheckBaseline.test.js @@ -1,5 +1,5 @@ // @ts-nocheck — Jest globals. checkJs has no test runner types. -const { freshLines, unusedLines } = require( '../scripts/typecheck-baseline' ); +const { freshLines, unusedLines, typeScriptLines } = require( '../scripts/typecheck-baseline' ); it( 'reports a diagnostic line that the baseline does not list', () => { const known = ['src/a.js(1,1): error TS1: known']; @@ -38,3 +38,40 @@ it( 'does not let one file\'s continuation shelter another file\'s', () => { ]; expect( freshLines( actual, known ) ).toEqual( actual ); } ); + +it( 'keeps the noImplicitAny diagnostics of .ts and .tsx files and their continuations', () => { + expect( typeScriptLines( [ + 'src/a.js(1,1): error TS7006: Parameter implicitly has an any type.', + ' js continuation', + 'src/b.ts(2,1): error TS7016: Could not find a declaration file.', + ' ts continuation', + 'src/c.tsx(3,1): error TS7006: Parameter implicitly has an any type.', + ] ) ).toEqual( [ + 'src/b.ts(2,1): error TS7016: Could not find a declaration file.', + ' ts continuation', + 'src/c.tsx(3,1): error TS7006: Parameter implicitly has an any type.', + ] ); + expect( typeScriptLines( ['src/a.js(1,1): error TS7006: x'] ) ).toEqual( [] ); +} ); + +it( 'passes on an empty baseline when tsc reports nothing', () => { + expect( freshLines( [], [] ) ).toEqual( [] ); + expect( unusedLines( [], [] ) ).toEqual( [] ); +} ); + +it( 'exits non-zero when a .ts file has an implicit any, even if the first pass is clean', () => { + const fs = require( 'fs' ); + const path = require( 'path' ); + const { spawnSync } = require( 'child_process' ); + const file = path.join( __dirname, 'implicitAnyProbe.ts' ); + fs.writeFileSync( file, 'export function probe( x ) { return x; }\n' ); + try { + const result = spawnSync( process.execPath, [ + path.join( __dirname, '..', 'scripts', 'typecheck-baseline.js' ), + ], { encoding: 'utf8' } ); + expect( result.status ).toBe( 1 ); + expect( result.stderr ).toContain( 'src/implicitAnyProbe.ts' ); + } finally { + fs.unlinkSync( file ); + } +}, 60000 ); diff --git a/yarn.lock b/yarn.lock index 053bb5d3..c29dc019 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3234,6 +3234,11 @@ dependencies: "@babel/types" "^7.20.7" +"@types/d3-array@^3.2.2": + version "3.2.2" + resolved "https://registry.yarnpkg.com/@types/d3-array/-/d3-array-3.2.2.tgz#e02151464d02d4a1b44646d0fcdb93faf88fde8c" + integrity sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw== + "@types/debug@^4.1.6": version "4.1.12" resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.12.tgz#a155f21690871953410df4b6b6f53187f0500917" @@ -3292,6 +3297,11 @@ resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ== +"@types/lodash@^4.17.27": + version "4.17.27" + resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.17.27.tgz#15fb73275b64dbfe49e2ae8376bb469b352a47a7" + integrity sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew== + "@types/minimatch@*": version "5.1.2" resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-5.1.2.tgz#07508b45797cb81ec3f273011b054cd0755eddca"