A local-first personal finance app
Port App and FatalError components to TS and functional components (#1535)
Joel Jeremy Marquez79f4d023506f
diff --git a/packages/desktop-client/package.json b/packages/desktop-client/package.jsonindex 93eec39806..4221044e30 100644--- a/packages/desktop-client/package.json+++ b/packages/desktop-client/package.json@@ -43,6 +43,7 @@"react-dnd": "^16.0.1","react-dnd-html5-backend": "^16.0.1","react-dom": "18.2.0",+ "react-error-boundary": "^4.0.11","react-merge-refs": "^1.1.0","react-modal": "3.16.1","react-redux": "7.2.1",diff --git a/packages/desktop-client/src/components/App.js b/packages/desktop-client/src/components/App.jsdeleted file mode 100644index 4befb0ffeb..0000000000--- a/packages/desktop-client/src/components/App.js+++ /dev/null@@ -1,162 +0,0 @@-import React, { Component } from 'react';-import { useSelector } from 'react-redux';--import { css } from 'glamor';--import {- init as initConnection,- send,-} from 'loot-core/src/platform/client/fetch';--import { useActions } from '../hooks/useActions';-import installPolyfills from '../polyfills';-import { ResponsiveProvider } from '../ResponsiveProvider';-import { styles, hasHiddenScrollbars, ThemeStyle } from '../style';--import AppBackground from './AppBackground';-import DevelopmentTopBar from './DevelopmentTopBar';-import FatalError from './FatalError';-import FinancesApp from './FinancesApp';-import ManagementApp from './manager/ManagementApp';-import MobileWebMessage from './MobileWebMessage';-import UpdateNotification from './UpdateNotification';--class App extends Component {- state = {- fatalError: null,- initializing: true,- hiddenScrollbars: hasHiddenScrollbars(),- };-- async init() {- const socketName = await global.Actual.getServerSocket();-- try {- await initConnection(socketName);- } catch (e) {- if (e.type === 'app-init-failure') {- this.setState({ initializing: false, fatalError: e });- return;- } else {- throw e;- }- }-- // Load any global prefs- await this.props.loadGlobalPrefs();-- // Open the last opened budget, if any- const budgetId = await send('get-last-opened-backup');- if (budgetId) {- await this.props.loadBudget(budgetId);-- // Check to see if this file has been remotely deleted (but- // don't block on this in case they are offline or something)- send('get-remote-files').then(files => {- if (files) {- let remoteFile = files.find(f => f.fileId === this.props.cloudFileId);- if (remoteFile && remoteFile.deleted) {- this.props.closeBudget();- }- }- });- }- }-- async componentDidMount() {- await Promise.all([installPolyfills(), this.init()]);-- this.setState({ initializing: false });-- let checkScrollbars = () => {- if (this.state.hiddenScrollbars !== hasHiddenScrollbars()) {- this.setState({ hiddenScrollbars: hasHiddenScrollbars() });- }- };- window.addEventListener('focus', checkScrollbars);- this.cleanup = () => window.removeEventListener('focus', checkScrollbars);- }-- componentDidCatch(error) {- this.setState({ fatalError: error });- }-- componentDidUpdate(prevProps) {- if (this.props.budgetId !== prevProps.budgetId) {- global.Actual.updateAppMenu(!!this.props.budgetId);- }- }-- render() {- const { budgetId, loadingText } = this.props;- const { fatalError, initializing, hiddenScrollbars } = this.state;-- return (- <ResponsiveProvider>- <div- style={{ height: '100%', display: 'flex', flexDirection: 'column' }}- >- {process.env.REACT_APP_REVIEW_ID && <DevelopmentTopBar />}- <div- key={hiddenScrollbars ? 'hidden-scrollbars' : 'scrollbars'}- {...css([- {- flexGrow: 1,- overflow: 'hidden',- },- styles.lightScrollbar,- ])}- >- {fatalError ? (- <>- <AppBackground />- <FatalError error={fatalError} buttonText="Restart app" />- </>- ) : initializing ? (- <AppBackground- initializing={initializing}- loadingText={loadingText}- />- ) : budgetId ? (- <FinancesApp />- ) : (- <>- <AppBackground- initializing={initializing}- loadingText={loadingText}- />- <ManagementApp isLoading={loadingText != null} />- </>- )}-- <UpdateNotification />- <MobileWebMessage />- </div>- </div>- <ThemeStyle />- </ResponsiveProvider>- );- }-}--export default function AppWrapper() {- let budgetId = useSelector(- state => state.prefs.local && state.prefs.local.id,- );- let cloudFileId = useSelector(- state => state.prefs.local && state.prefs.local.cloudFileId,- );- let loadingText = useSelector(state => state.app.loadingText);- let { loadBudget, closeBudget, loadGlobalPrefs } = useActions();-- return (- <App- budgetId={budgetId}- cloudFileId={cloudFileId}- loadingText={loadingText}- loadBudget={loadBudget}- closeBudget={closeBudget}- loadGlobalPrefs={loadGlobalPrefs}- />- );-}diff --git a/packages/desktop-client/src/components/App.tsx b/packages/desktop-client/src/components/App.tsxnew file mode 100644index 0000000000..ea0762201d--- /dev/null+++ b/packages/desktop-client/src/components/App.tsx@@ -0,0 +1,179 @@+import React, { useEffect, useState } from 'react';+import {+ ErrorBoundary,+ useErrorBoundary,+ type FallbackProps,+} from 'react-error-boundary';+import { useSelector } from 'react-redux';++import {+ init as initConnection,+ send,+} from 'loot-core/src/platform/client/fetch';+import { type GlobalPrefs } from 'loot-core/src/types/prefs';++import { useActions } from '../hooks/useActions';+import installPolyfills from '../polyfills';+import { ResponsiveProvider } from '../ResponsiveProvider';+import { styles, hasHiddenScrollbars, ThemeStyle } from '../style';++import AppBackground from './AppBackground';+import View from './common/View';+import DevelopmentTopBar from './DevelopmentTopBar';+import FatalError from './FatalError';+import FinancesApp from './FinancesApp';+import ManagementApp from './manager/ManagementApp';+import MobileWebMessage from './MobileWebMessage';+import UpdateNotification from './UpdateNotification';++type AppProps = {+ budgetId: string;+ cloudFileId: string;+ loadingText: string;+ loadBudget: (+ id: string,+ loadingText?: string,+ options?: object,+ ) => Promise<void>;+ closeBudget: () => Promise<void>;+ loadGlobalPrefs: () => Promise<GlobalPrefs>;+};++function App({+ budgetId,+ cloudFileId,+ loadingText,+ loadBudget,+ closeBudget,+ loadGlobalPrefs,+}: AppProps) {+ const [initializing, setInitializing] = useState(true);+ const { showBoundary: showErrorBoundary } = useErrorBoundary();++ async function init() {+ const socketName = await global.Actual.getServerSocket();++ await initConnection(socketName);++ // Load any global prefs+ await loadGlobalPrefs();++ // Open the last opened budget, if any+ const budgetId = await send('get-last-opened-backup');+ if (budgetId) {+ await loadBudget(budgetId);++ // Check to see if this file has been remotely deleted (but+ // don't block on this in case they are offline or something)+ send('get-remote-files').then(files => {+ if (files) {+ let remoteFile = files.find(f => f.fileId === cloudFileId);+ if (remoteFile && remoteFile.deleted) {+ closeBudget();+ }+ }+ });+ }+ }++ useEffect(() => {+ async function initAll() {+ await Promise.all([installPolyfills(), init()]);+ setInitializing(false);+ }++ initAll().catch(showErrorBoundary);+ }, []);++ useEffect(() => {+ global.Actual.updateAppMenu(!!budgetId);+ }, [budgetId]);++ return (+ <>+ {initializing ? (+ <AppBackground initializing={initializing} loadingText={loadingText} />+ ) : budgetId ? (+ <FinancesApp />+ ) : (+ <>+ <AppBackground+ initializing={initializing}+ loadingText={loadingText}+ />+ <ManagementApp isLoading={loadingText != null} />+ </>+ )}++ <UpdateNotification />+ <MobileWebMessage />+ </>+ );+}++function ErrorFallback({ error }: FallbackProps) {+ return (+ <>+ <AppBackground />+ <FatalError error={error} buttonText="Restart app" />+ </>+ );+}++function AppWrapper() {+ let budgetId = useSelector(+ state => state.prefs.local && state.prefs.local.id,+ );+ let cloudFileId = useSelector(+ state => state.prefs.local && state.prefs.local.cloudFileId,+ );+ let loadingText = useSelector(state => state.app.loadingText);+ let { loadBudget, closeBudget, loadGlobalPrefs } = useActions();+ const [hiddenScrollbars, setHiddenScrollbars] = useState(+ hasHiddenScrollbars(),+ );++ useEffect(() => {+ function checkScrollbars() {+ if (hiddenScrollbars !== hasHiddenScrollbars()) {+ setHiddenScrollbars(hasHiddenScrollbars());+ }+ }++ window.addEventListener('focus', checkScrollbars);++ return () => window.removeEventListener('focus', checkScrollbars);+ }, []);++ return (+ <ResponsiveProvider>+ <View+ style={{ height: '100%', display: 'flex', flexDirection: 'column' }}+ >+ <View+ key={hiddenScrollbars ? 'hidden-scrollbars' : 'scrollbars'}+ style={{+ flexGrow: 1,+ overflow: 'hidden',+ ...styles.lightScrollbar,+ }}+ >+ <ErrorBoundary FallbackComponent={ErrorFallback}>+ {process.env.REACT_APP_REVIEW_ID && <DevelopmentTopBar />}+ <App+ budgetId={budgetId}+ cloudFileId={cloudFileId}+ loadingText={loadingText}+ loadBudget={loadBudget}+ closeBudget={closeBudget}+ loadGlobalPrefs={loadGlobalPrefs}+ />+ </ErrorBoundary>+ <ThemeStyle />+ </View>+ </View>+ </ResponsiveProvider>+ );+}++export default AppWrapper;diff --git a/packages/desktop-client/src/components/AppBackground.js b/packages/desktop-client/src/components/AppBackground.tsxsimilarity index 84%rename from packages/desktop-client/src/components/AppBackground.jsrename to packages/desktop-client/src/components/AppBackground.tsxindex 697e20f02d..1af44ea58b 100644--- a/packages/desktop-client/src/components/AppBackground.js+++ b/packages/desktop-client/src/components/AppBackground.tsx@@ -9,7 +9,12 @@ import Background from './Background';import Block from './common/Block';import View from './common/View';-function AppBackground({ initializing, loadingText }) {+type AppBackgroundProps = {+ initializing?: boolean;+ loadingText?: string;+};++function AppBackground({ initializing, loadingText }: AppBackgroundProps) {return (<><Background />diff --git a/packages/desktop-client/src/components/FatalError.js b/packages/desktop-client/src/components/FatalError.jsdeleted file mode 100644index 23c2346e42..0000000000--- a/packages/desktop-client/src/components/FatalError.js+++ /dev/null@@ -1,186 +0,0 @@-import React, { Component, useState } from 'react';--import { theme } from '../style';--import Block from './common/Block';-import Button from './common/Button';-import ExternalLink from './common/ExternalLink';-import LinkButton from './common/LinkButton';-import Modal from './common/Modal';-import Paragraph from './common/Paragraph';-import Stack from './common/Stack';-import Text from './common/Text';-import View from './common/View';-import { Checkbox } from './forms';--class FatalError extends Component {- state = { showError: false };-- renderSimple(error) {- let msg;- if (error.IDBFailure) {- // IndexedDB wasn't able to open the database- msg = (- <Text>- Your browser doesn’t support IndexedDB in this environment, a feature- that Actual requires to run. This might happen if you are in private- browsing mode. Please try a different browser or turn off private- browsing.- </Text>- );- } else if (error.SharedArrayBufferMissing) {- // SharedArrayBuffer isn't available- msg = (- <Text>- Actual requires access to <code>SharedArrayBuffer</code> in order to- function properly. If you’re seeing this error, either your browser- does not support <code>SharedArrayBuffer</code>, or your server is not- sending the appropriate headers, or you are not using HTTPS. See{' '}- <ExternalLink- linkColor="muted"- to="https://actualbudget.org/docs/troubleshooting/shared-array-buffer"- >- our troubleshooting documentation- </ExternalLink>{' '}- to learn more. <SharedArrayBufferOverride />- </Text>- );- } else {- // This indicates the backend failed to initialize. Show the- // user something at least so they aren't looking at a blank- // screen- msg = (- <Text>- There was a problem loading the app in this browser version. If this- continues to be a problem, you can{' '}- <ExternalLink- linkColor="muted"- to="https://github.com/actualbudget/releases"- >- download the desktop app- </ExternalLink>- .- </Text>- );- }-- return (- <View- style={{- alignItems: 'center',- justifyContent: 'center',- height: '100%',- }}- >- <Stack- style={{- paddingBottom: 100,- maxWidth: 500,- color: theme.errorText,- backgroundColor: theme.errorBackground,- lineHeight: '1.5em',- fontSize: 15,- }}- >- <Text>{msg}</Text>- <Text>- Please get{' '}- <ExternalLink- linkColor="muted"- to="https://actualbudget.org/contact"- >- in touch- </ExternalLink>{' '}- for support- </Text>- </Stack>- </View>- );- }-- render() {- const { buttonText, error } = this.props;- const { showError } = this.state;-- if (error.type === 'app-init-failure') {- return this.renderSimple(error);- }-- return (- <Modal isCurrent={true} showClose={false} title="Fatal Error">- {() => (- <View style={{ maxWidth: 500 }}>- <Paragraph>- There was an unrecoverable error in the UI. Sorry!- </Paragraph>- <Paragraph>- If this error persists, please get{' '}- <ExternalLink to="https://actualbudget.org/contact">- in touch- </ExternalLink>{' '}- so it can be investigated.- </Paragraph>- <Paragraph>- <Button onClick={() => window.Actual.relaunch()}>- {buttonText}- </Button>- </Paragraph>- <Paragraph isLast={true} style={{ fontSize: 11 }}>- <LinkButton onClick={() => this.setState({ showError: true })}>- Show Error- </LinkButton>- {showError && (- <Block- style={{- marginTop: 5,- height: 100,- overflow: 'auto',- }}- >- {error.stack}- </Block>- )}- </Paragraph>- </View>- )}- </Modal>- );- }-}-export default FatalError;--function SharedArrayBufferOverride() {- let [expanded, setExpanded] = useState(false);- let [understand, setUnderstand] = useState(false);-- return expanded ? (- <>- <Paragraph style={{ marginTop: 10 }}>- Actual uses <code>SharedArrayBuffer</code> to allow usage from multiple- tabs at once and to ensure correct behavior when switching files. While- it can run without access to <code>SharedArrayBuffer</code>, you may- encounter data loss or notice multiple budget files being merged with- each other.- </Paragraph>- <label- style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}- >- <Checkbox checked={understand} onChange={setUnderstand} /> I understand- the risks, run Actual in the unsupported fallback mode- </label>- <Button- disabled={!understand}- onClick={() => {- window.localStorage.setItem('SharedArrayBufferOverride', 'true');- window.location.reload();- }}- >- Open Actual- </Button>- </>- ) : (- <LinkButton onClick={() => setExpanded(true)} style={{ marginLeft: 5 }}>- Advanced options- </LinkButton>- );-}diff --git a/packages/desktop-client/src/components/FatalError.tsx b/packages/desktop-client/src/components/FatalError.tsxnew file mode 100644index 0000000000..c5ee769bc3--- /dev/null+++ b/packages/desktop-client/src/components/FatalError.tsx@@ -0,0 +1,196 @@+import React, { useState } from 'react';++import { theme } from '../style';++import Block from './common/Block';+import Button from './common/Button';+import ExternalLink from './common/ExternalLink';+import LinkButton from './common/LinkButton';+import Modal from './common/Modal';+import Paragraph from './common/Paragraph';+import Stack from './common/Stack';+import Text from './common/Text';+import View from './common/View';+import { Checkbox } from './forms';++type AppError = Error & {+ type?: string;+ IDBFailure?: boolean;+ SharedArrayBufferMissing?: boolean;+};++type FatalErrorProps = {+ buttonText: string;+ error: Error | AppError;+};++function renderSimple(error: FatalErrorProps['error']) {+ let msg;+ if ('IDBFailure' in error && error.IDBFailure) {+ // IndexedDB wasn't able to open the database+ msg = (+ <Text>+ Your browser doesn’t support IndexedDB in this environment, a feature+ that Actual requires to run. This might happen if you are in private+ browsing mode. Please try a different browser or turn off private+ browsing.+ </Text>+ );+ } else if (+ 'SharedArrayBufferMissing' in error &&+ error.SharedArrayBufferMissing+ ) {+ // SharedArrayBuffer isn't available+ msg = (+ <Text>+ Actual requires access to <code>SharedArrayBuffer</code> in order to+ function properly. If you’re seeing this error, either your browser does+ not support <code>SharedArrayBuffer</code>, or your server is not+ sending the appropriate headers, or you are not using HTTPS. See{' '}+ <ExternalLink+ linkColor="muted"+ to="https://actualbudget.org/docs/troubleshooting/shared-array-buffer"+ >+ our troubleshooting documentation+ </ExternalLink>{' '}+ to learn more. <SharedArrayBufferOverride />+ </Text>+ );+ } else {+ // This indicates the backend failed to initialize. Show the+ // user something at least so they aren't looking at a blank+ // screen+ msg = (+ <Text>+ There was a problem loading the app in this browser version. If this+ continues to be a problem, you can{' '}+ <ExternalLink+ linkColor="muted"+ to="https://github.com/actualbudget/releases"+ >+ download the desktop app+ </ExternalLink>+ .+ </Text>+ );+ }++ return (+ <View+ style={{+ alignItems: 'center',+ justifyContent: 'center',+ height: '100%',+ }}+ >+ <Stack+ style={{+ paddingBottom: 100,+ maxWidth: 500,+ color: theme.errorText,+ backgroundColor: theme.errorBackground,+ lineHeight: '1.5em',+ fontSize: 15,+ }}+ >+ <Text>{msg}</Text>+ <Text>+ Please get{' '}+ <ExternalLink linkColor="muted" to="https://actualbudget.org/contact">+ in touch+ </ExternalLink>{' '}+ for support+ </Text>+ </Stack>+ </View>+ );+}++function SharedArrayBufferOverride() {+ let [expanded, setExpanded] = useState(false);+ let [understand, setUnderstand] = useState(false);++ return expanded ? (+ <>+ <Paragraph style={{ marginTop: 10 }}>+ Actual uses <code>SharedArrayBuffer</code> to allow usage from multiple+ tabs at once and to ensure correct behavior when switching files. While+ it can run without access to <code>SharedArrayBuffer</code>, you may+ encounter data loss or notice multiple budget files being merged with+ each other.+ </Paragraph>+ <label+ style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}+ >+ <Checkbox+ checked={understand}+ onChange={_ => setUnderstand(!understand)}+ />{' '}+ I understand the risks, run Actual in the unsupported fallback mode+ </label>+ <Button+ disabled={!understand}+ onClick={() => {+ window.localStorage.setItem('SharedArrayBufferOverride', 'true');+ window.location.reload();+ }}+ >+ Open Actual+ </Button>+ </>+ ) : (+ <LinkButton onClick={() => setExpanded(true)} style={{ marginLeft: 5 }}>+ Advanced options+ </LinkButton>+ );+}++function FatalError({ buttonText, error }: FatalErrorProps) {+ let [showError, setShowError] = useState(false);++ if ('type' in error && error.type === 'app-init-failure') {+ return renderSimple(error);+ }++ return (+ <Modal isCurrent={true} showClose={false} title="Fatal Error">+ {() => (+ <View style={{ maxWidth: 500 }}>+ <Paragraph>+ There was an unrecoverable error in the UI. Sorry!+ </Paragraph>+ <Paragraph>+ If this error persists, please get{' '}+ <ExternalLink to="https://actualbudget.org/contact">+ in touch+ </ExternalLink>{' '}+ so it can be investigated.+ </Paragraph>+ <Paragraph>+ <Button onClick={() => window.Actual.relaunch()}>+ {buttonText}+ </Button>+ </Paragraph>+ <Paragraph isLast={true} style={{ fontSize: 11 }}>+ <LinkButton onClick={() => setShowError(true)}>+ Show Error+ </LinkButton>+ {showError && (+ <Block+ style={{+ marginTop: 5,+ height: 100,+ overflow: 'auto',+ }}+ >+ {error.stack}+ </Block>+ )}+ </Paragraph>+ </View>+ )}+ </Modal>+ );+}++export default FatalError;diff --git a/upcoming-release-notes/1535.md b/upcoming-release-notes/1535.mdnew file mode 100644index 0000000000..78d3a1a5a2--- /dev/null+++ b/upcoming-release-notes/1535.md@@ -0,0 +1,6 @@+---+category: Maintenance+authors: [joel-jeremy]+---++Port App to functional componentdiff --git a/yarn.lock b/yarn.lockindex 8ab7e5539a..d4250ebcbd 100644--- a/yarn.lock+++ b/yarn.lock@@ -81,6 +81,7 @@ __metadata:react-dnd: ^16.0.1react-dnd-html5-backend: ^16.0.1react-dom: 18.2.0+ react-error-boundary: ^4.0.11react-merge-refs: ^1.1.0react-modal: 3.16.1react-redux: 7.2.1@@ -15466,6 +15467,17 @@ __metadata:languageName: nodelinkType: hard+"react-error-boundary@npm:^4.0.11":+ version: 4.0.11+ resolution: "react-error-boundary@npm:4.0.11"+ dependencies:+ "@babel/runtime": ^7.12.5+ peerDependencies:+ react: ">=16.13.1"+ checksum: b3c157fea4e8f78411e9aa0fbf5241f6907b66ede1cd8b7bb22faaeb0339ebeb3dc8e63bf90ef3f740bfa8fd994ca6edf975089cd371b664ad6c2735e7512d38+ languageName: node+ linkType: hard+"react-error-overlay@npm:6.0.9":version: 6.0.9resolution: "react-error-overlay@npm:6.0.9"