Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Reduce application bundle size #425

Merged
merged 10 commits into from
Oct 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
"@xterm/addon-image": "^0.7.0-beta.1",
"@xterm/addon-webgl": "^0.17.0-beta.1",
"@xterm/xterm": "^5.4.0-beta.1",
"axios": "^1.7.4",
"clsx": "^1.1.1",
"comlink": "^4.4.1",
"connected-react-router": "^6.9.2",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import React, { type PropsWithChildren, Suspense } from 'react'
import { type IStackStyles, mergeStyleSets, Spinner, Stack, useTheme } from '@fluentui/react'
import { Poster } from '../Poster'

type ContainerProps = PropsWithChildren<{
styles?: IStackStyles
}>

const SuspenseContainer: React.FC<ContainerProps> = ({ children, styles }) => {
const theme = useTheme()
const stackStyles: IStackStyles = mergeStyleSets(
{
root: {
background: theme.semanticColors.bodyBackground,
},
},
styles,
)

return (
<Stack grow verticalFill horizontalAlign="center" verticalAlign="center" styles={stackStyles}>
{children}
</Stack>
)
}

interface ErrorProps extends ContainerProps {
errorLabel?: string
error?: Error
}

const SuspenseErrorBoundary: React.FC<ErrorProps> = ({ styles, children, error, errorLabel }) => {
return error ? (
<SuspenseContainer styles={styles}>
<Poster label={errorLabel ?? 'Error'} type="error" message={error.toString()} />
</SuspenseContainer>
) : (
<>{children}</>
)
}

interface PreloaderProps {
preloaderText?: string
styles?: IStackStyles
}

const SuspensePreloader: React.FC<PreloaderProps> = ({ preloaderText }) => {
return (
<SuspenseContainer>
<Spinner key="spinner" label={preloaderText ?? 'Loading...'} labelPosition="right" />
</SuspenseContainer>
)
}

export interface SuspenseProps extends PreloaderProps {
errorLabel?: string
}

interface State {
error?: Error
}

export class SuspenseBoundary extends React.Component<PropsWithChildren<SuspenseProps>, State> {
state: State = {}

componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('failed to render a component', error, errorInfo)
this.setState({ error })
}

render() {
return (
<SuspenseErrorBoundary errorLabel={this.props.errorLabel} error={this.state.error}>
<Suspense fallback={<SuspensePreloader preloaderText={this.props.preloaderText} />}>
{this.props.children}
</Suspense>
</SuspenseErrorBoundary>
)
}

static getDerivedStateFromError(err: Error) {
return {
error: err,
}
}
}
1 change: 1 addition & 0 deletions web/src/components/elements/misc/SuspenseBoundary/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './SuspenseBoundary.tsx'
2 changes: 1 addition & 1 deletion web/src/components/elements/tabs/TabLabel/TabLabel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
type IStackStyles,
type IButtonStyles,
} from '@fluentui/react'
import type { TabIconStyles } from '../types.ts'
import type { TabIconStyles } from '../types'

const BUTTON_PRIMARY = 0
const BUTTON_WHEEL = 1
Expand Down
2 changes: 1 addition & 1 deletion web/src/components/elements/tabs/TabView/TabView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { TabHeader } from '../TabHeader'
import type { TabBarAction, TabInfo, TabIconStyles } from '../types'

import { containerStyles, tabHeaderStyles, getTabContentStyles } from './styles'
import { debounce } from './debounce.ts'
import { debounce } from './debounce'

interface Props {
actions?: TabBarAction[]
Expand Down
81 changes: 46 additions & 35 deletions web/src/components/features/workspace/CodeEditor/CodeEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,68 +12,57 @@ import {
newMonacoParamsChangeDispatcher,
runFileDispatcher,
type StateDispatch,
type State,
} from '~/store'
import { type WorkspaceState, dispatchFormatFile, dispatchResetWorkspace, dispatchUpdateFile } from '~/store/workspace'
import { getTimeNowUsageMarkers, asyncDebounce, debounce } from './utils'
import { attachCustomCommands } from './commands'
import { LANGUAGE_GOLANG, stateToOptions } from './props'
import { configureMonacoLoader } from './loader'
import { DocumentMetadataCache, registerGoLanguageProviders } from './autocomplete'
import type { VimState } from '~/store/vim/state'
import { spawnLanguageWorker } from '~/workers/language'
import { getTimeNowUsageMarkers, asyncDebounce, debounce } from './utils/utils'
import { attachCustomCommands } from './utils/commands'
import { languageFromFilename, stateToOptions } from './utils/props'
import { configureMonacoLoader } from './utils/loader'
import { DocumentMetadataCache, registerGoLanguageProviders } from './autocomplete'
import classes from './CodeEditor.module.css'

const ANALYZE_DEBOUNCE_TIME = 500

// ask monaco-editor/react to use our own Monaco instance.
configureMonacoLoader()

const mapWorkspaceProps = ({ files, selectedFile, snippet }: WorkspaceState) => {
const projectId = snippet?.id ?? ''
if (!selectedFile) {
return {
projectId,
code: '',
fileName: '',
}
}

return {
projectId,
code: files?.[selectedFile],
fileName: selectedFile,
}
}

interface CodeEditorState {
export interface CodeEditorState {
code?: string
loading?: boolean
fileName: string
projectId: string
}

interface Props extends CodeEditorState {
darkMode: boolean
vimModeEnabled: boolean
isServerEnvironment: boolean
options: MonacoSettings
vim?: VimState | null
}

export interface Props extends CodeEditorState {
dispatch: StateDispatch
}

class CodeEditor extends React.Component<Props> {
class CodeEditorView extends React.Component<Props> {
private analyzer?: Analyzer
private editorInstance?: monaco.editor.IStandaloneCodeEditor
private vimAdapter?: VimModeKeymap
private vimCommandAdapter?: StatusBarAdapter
private monaco?: Monaco
private disposables?: monaco.IDisposable[]
private saveTimeoutId?: ReturnType<typeof setTimeout>
private readonly disposables: monaco.IDisposable[] = []
private readonly metadataCache = new DocumentMetadataCache()

private readonly debouncedAnalyzeFunc = asyncDebounce(async (fileName: string, code: string) => {
return await this.doAnalyze(fileName, code)
}, ANALYZE_DEBOUNCE_TIME)

private addDisposer(...disposers: monaco.IDisposable[]) {
this.disposables.push(...disposers)
}

private readonly persistFontSize = debounce((fontSize: number) => {
this.props.dispatch(
newMonacoParamsChangeDispatcher({
Expand All @@ -83,7 +72,10 @@ class CodeEditor extends React.Component<Props> {
}, 1000)

editorDidMount(editorInstance: monaco.editor.IStandaloneCodeEditor, monacoInstance: Monaco) {
this.disposables = registerGoLanguageProviders(this.props.dispatch, this.metadataCache)
const [langWorker, workerDisposer] = spawnLanguageWorker()

this.addDisposer(workerDisposer)
this.addDisposer(...registerGoLanguageProviders(this.props.dispatch, this.metadataCache, langWorker))
this.editorInstance = editorInstance
this.monaco = monacoInstance

Expand Down Expand Up @@ -142,7 +134,7 @@ class CodeEditor extends React.Component<Props> {
]

// Persist font size on zoom
this.disposables.push(
this.addDisposer(
editorInstance.onDidChangeConfiguration((e) => {
if (e.hasChanged(monaco.editor.EditorOption.fontSize)) {
const newFontSize = editorInstance.getOption(monaco.editor.EditorOption.fontSize)
Expand All @@ -160,13 +152,13 @@ class CodeEditor extends React.Component<Props> {
void this.debouncedAnalyzeFunc(fileName, code)
}

private isFileOrEnvironmentChanged(prevProps) {
private isFileOrEnvironmentChanged(prevProps: Props) {
return (
prevProps.isServerEnvironment !== this.props.isServerEnvironment || prevProps.fileName !== this.props.fileName
)
}

private applyVimModeChanges(prevProps) {
private applyVimModeChanges(prevProps: Props) {
if (prevProps?.vimModeEnabled === this.props.vimModeEnabled) {
return
}
Expand Down Expand Up @@ -281,7 +273,7 @@ class CodeEditor extends React.Component<Props> {
return (
<MonacoEditor
className={classes.CodeEditor}
language={LANGUAGE_GOLANG}
language={languageFromFilename(this.props.fileName)}
theme={this.props.darkMode ? 'vs-dark' : 'vs-light'}
value={this.props.code}
defaultValue={this.props.code}
Expand All @@ -295,12 +287,31 @@ class CodeEditor extends React.Component<Props> {
}
}

export const ConnectedCodeEditor = connect<CodeEditorState, {}>(({ workspace, ...s }) => ({
const mapStateToProps = ({ workspace, ...s }: State): CodeEditorState => ({
...mapWorkspaceProps(workspace),
darkMode: s.settings.darkMode,
vimModeEnabled: s.settings.enableVimMode,
isServerEnvironment: s.runTarget.target === TargetType.Server,
loading: s.status?.loading,
options: s.monaco,
vim: s.vim,
}))(CodeEditor)
})

const mapWorkspaceProps = ({ files, selectedFile, snippet }: WorkspaceState) => {
const projectId = snippet?.id ?? ''
if (!selectedFile) {
return {
projectId,
code: '',
fileName: '',
}
}

return {
projectId,
code: files?.[selectedFile],
fileName: selectedFile,
}
}

export const CodeEditor = connect<CodeEditorState, {}>(mapStateToProps)(CodeEditorView)
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,27 @@ import { GoImportsCompletionProvider } from './imports'
import { GoHoverProvider } from './hover'
import type { StateDispatch } from '~/store'
import type { DocumentMetadataCache } from './cache'
import { getLanguageWorker } from '~/workers/language'
import type { LanguageWorker } from '~/workers/language'

const LANG_GO = 'go'

/**
* Registers all Go autocomplete providers for Monaco editor.
*/
export const registerGoLanguageProviders = (dispatcher: StateDispatch, cache: DocumentMetadataCache) => {
const worker = getLanguageWorker()
export const registerGoLanguageProviders = (
dispatcher: StateDispatch,
cache: DocumentMetadataCache,
langWorker: LanguageWorker,
) => {
return [
monaco.languages.registerCompletionItemProvider(
'go',
new GoSymbolsCompletionItemProvider(dispatcher, cache, worker),
LANG_GO,
new GoSymbolsCompletionItemProvider(dispatcher, cache, langWorker),
),
monaco.languages.registerCompletionItemProvider(
LANG_GO,
new GoImportsCompletionProvider(dispatcher, cache, langWorker),
),
monaco.languages.registerCompletionItemProvider('go', new GoImportsCompletionProvider(dispatcher, cache, worker)),
monaco.languages.registerHoverProvider('go', new GoHoverProvider(worker, cache)),
monaco.languages.registerHoverProvider(LANG_GO, new GoHoverProvider(langWorker, cache)),
]
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type * as monaco from 'monaco-editor'
import type { SuggestionContext, SuggestionQuery } from '~/workers/language'
import { asyncDebounce } from '../../utils'
import { asyncDebounce } from '../../utils/utils'
import snippets from './snippets'
import { parseExpression } from './parse'
import { CacheBasedCompletionProvider } from '../base'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,7 @@ import type * as monaco from 'monaco-editor'
import { type MonacoSettings } from '~/services/config'
import { getFontFamily, getDefaultFontFamily } from '~/services/fonts'

export const LANGUAGE_GOLANG = 'go'

export const DEMO_CODE = [
'package main\n',
'import (',
'\t"fmt"',
')\n',
'func main() {',
'\tfmt.Println("Hello World")',
'}\n',
].join('\n')
export const languageFromFilename = (fname: string) => (fname.endsWith('.mod') ? 'gomod' : 'go')

// stateToOptions converts MonacoState to IEditorOptions
export const stateToOptions = (state: MonacoSettings): monaco.editor.IEditorOptions => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import React, { lazy } from 'react'
import { SuspenseBoundary } from '~/components/elements/misc/SuspenseBoundary'

const LazyWorkspace = lazy(async () => await import('./Workspace.tsx'))

export const LazyLoadedWorkspace: React.FC = () => (
<SuspenseBoundary errorLabel="Failed to load workspace" preloaderText="Loading workspace...">
<LazyWorkspace />
</SuspenseBoundary>
)
Loading