Skip to content

Fix electron type to reflect that it could be undefined #8019

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

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion e2e/playwright/fixtures/fixtureSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,10 @@ export class ElectronZoo {
}, dims)

return this.evaluate(async (dims: { width: number; height: number }) => {
await window.electron.resizeWindow(dims.width, dims.height)
if (!window.electron) {
throw new Error('Electron not defined')
}
await window.electron?.resizeWindow(dims.width, dims.height)
window.document.body.style.width = dims.width + 'px'
window.document.body.style.height = dims.height + 'px'
window.document.documentElement.style.width = dims.width + 'px'
Expand Down
16 changes: 9 additions & 7 deletions interface.d.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { MachinesListing } from 'components/MachineManagerProvider'
import type { MachinesListing } from 'components/MachineManagerProvider'
import 'electron'
import fs from 'node:fs/promises'
import path from 'path'
import { dialog, shell } from 'electron'
import type fs from 'node:fs/promises'
import type path from 'path'
import type { dialog, shell } from 'electron'
import type { WebContentSendPayload } from 'menu/channels'
import { ZooLabel } from 'menu/roles'
import type { ZooLabel } from 'menu/roles'

// Extend the interface with additional custom properties
declare module 'electron' {
Expand Down Expand Up @@ -108,7 +108,9 @@ export interface IElectronAPI {

declare global {
interface Window {
electron: IElectronAPI
openExternalLink: (e: React.MouseEvent<HTMLAnchorElement>) => void
electron: IElectronAPI | undefined
openExternalLink:
| ((e: React.MouseEvent<HTMLAnchorElement>) => void)
| undefined
}
}
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"rust/kcl-language-server"
],
"dependencies": {
"@chainner/node-path": "^0.1.1",
"@codemirror/autocomplete": "^6.18.6",
"@codemirror/commands": "^6.8.1",
"@codemirror/language": "^6.11.0",
Expand Down
3 changes: 0 additions & 3 deletions rust/kcl-lib/src/fs/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ extern "C" {
#[derive(Debug, Clone)]
pub type FileSystemManager;

#[wasm_bindgen(constructor)]
pub fn new() -> FileSystemManager;

#[wasm_bindgen(method, js_name = readFile, catch)]
fn read_file(this: &FileSystemManager, path: String) -> Result<js_sys::Promise, js_sys::Error>;

Expand Down
10 changes: 6 additions & 4 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,11 @@ import env from '@src/env'
// CYCLIC REF
sceneInfra.camControls.engineStreamActor = engineStreamActor

maybeWriteToDisk()
.then(() => {})
.catch(() => {})
if (window.electron) {
maybeWriteToDisk(window.electron)
.then(() => {})
.catch(reportRejection)
}

export function App() {
const { state: modelingState } = useModelingContext()
Expand Down Expand Up @@ -241,7 +243,7 @@ export function App() {

// Only create the native file menus on desktop
useEffect(() => {
if (isDesktop()) {
if (window.electron) {
window.electron
.createModelingPageMenu()
.then(() => {
Expand Down
5 changes: 4 additions & 1 deletion src/components/CommandBar/CommandBarPathInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ function CommandBarPathInput({
configuration.filters = arg.filters
}

if (!window.electron) {
return new Error("Can't open file picker without electron")
}
const newPath = await window.electron.open(configuration)
if (newPath.canceled) return
inputRef.current.value = newPath.filePaths[0]
Expand All @@ -75,7 +78,7 @@ function CommandBarPathInput({

// Fire on component mount, if outside of e2e test context
useEffect(() => {
window.electron.process.env.NODE_ENV !== 'test' &&
window.electron?.process.env.NODE_ENV !== 'test' &&
toSync(pickFileThroughNativeDialog, reportRejection)()
// eslint-disable-next-line react-hooks/exhaustive-deps -- TODO: blanket-ignored fix me!
}, [])
Expand Down
11 changes: 7 additions & 4 deletions src/components/Explorer/ProjectExplorer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ export const ProjectExplorer = ({
}
},
onOpenInNewWindow: () => {
window.electron.openInNewWindow(row.path)
window.electron?.openInNewWindow(row.path)
},
onRenameStart: () => {
if (readOnly) {
Expand Down Expand Up @@ -375,16 +375,19 @@ export const ProjectExplorer = ({
const absolutePathToParentDirectory = getParentAbsolutePath(
row.path
)
const oldPath = window.electron.path.join(
const oldPath = window.electron?.path.join(
absolutePathToParentDirectory,
name
)
const newPath = window.electron.path.join(
const newPath = window.electron?.path.join(
absolutePathToParentDirectory,
requestedName
)
const shouldWeNavigate =
file?.path?.startsWith(oldPath) && canNavigate
oldPath !== undefined &&
newPath !== undefined &&
file?.path?.startsWith(oldPath) &&
canNavigate

if (shouldWeNavigate && file && file.path) {
const requestedFileNameWithExtension =
Expand Down
34 changes: 25 additions & 9 deletions src/components/FileMachineProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
} from '@src/lib/constants'
import { getProjectInfo } from '@src/lib/desktop'
import { getNextDirName, getNextFileName } from '@src/lib/desktopFS'
import { isDesktop } from '@src/lib/isDesktop'
import { kclCommands } from '@src/lib/kclCommands'
import { BROWSER_PATH, PATHS } from '@src/lib/paths'
import { markOnce } from '@src/lib/performance'
Expand All @@ -35,6 +34,7 @@ import { useSettings, useToken } from '@src/lib/singletons'
import { commandBarActor } from '@src/lib/singletons'
import { fileMachine } from '@src/machines/fileMachine'
import { modelingMenuCallbackMostActions } from '@src/menu/register'
import { fsManager } from '@src/lang/std/fileSystemManager'

type MachineContext<T extends AnyStateMachine> = {
state: StateFrom<T>
Expand Down Expand Up @@ -127,7 +127,7 @@ export const FileMachineProvider = ({
// TODO: Should this be context.selectedDirectory.path?
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
context.selectedDirectory +
window.electron.path.sep +
fsManager.path.sep +
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
event.output.name
)}`
Expand All @@ -147,20 +147,24 @@ export const FileMachineProvider = ({
}

commandBarActor.send({ type: 'Close' })
window.electron.openInNewWindow(event.data.name)
window.electron?.openInNewWindow(event.data.name)
},
},
actors: {
readFiles: fromPromise(async ({ input }) => {
const newFiles =
(isDesktop() ? (await getProjectInfo(input.path)).children : []) ??
[]
(window.electron
? (await getProjectInfo(window.electron, input.path)).children
: []) ?? []
return {
...input,
children: newFiles,
}
}),
createAndOpenFile: fromPromise(async ({ input }) => {
if (!window.electron) {
return Promise.reject(new Error('No file system present'))
}
let createdName = input.name.trim() || DEFAULT_FILE_NAME
let createdPath: string

Expand All @@ -172,6 +176,7 @@ export const FileMachineProvider = ({
input.makeDir
) {
let { name, path } = getNextDirName({
electron: window.electron,
entryName: input.targetPathToClone
? window.electron.path.basename(input.targetPathToClone)
: createdName,
Expand All @@ -187,7 +192,8 @@ export const FileMachineProvider = ({
input.targetPathToClone &&
input.selectedDirectory.path.indexOf(input.targetPathToClone) > -1
if (isTargetPathToCloneASubPath) {
const { name, path } = getNextFileName({
const { name, path } = await getNextFileName({
electron: window.electron,
entryName: input.targetPathToClone
? window.electron.path.basename(input.targetPathToClone)
: createdName,
Expand All @@ -198,7 +204,8 @@ export const FileMachineProvider = ({
createdName = name
createdPath = path
} else {
const { name, path } = getNextFileName({
const { name, path } = await getNextFileName({
electron: window.electron,
entryName: input.targetPathToClone
? window.electron.path.basename(input.targetPathToClone)
: createdName,
Expand Down Expand Up @@ -229,19 +236,24 @@ export const FileMachineProvider = ({
}
}),
createFile: fromPromise(async ({ input }) => {
if (!window.electron) {
return Promise.reject(new Error('No file system present'))
}
let createdName = input.name.trim() || DEFAULT_FILE_NAME
let createdPath: string

if (input.makeDir) {
let { name, path } = getNextDirName({
electron: window.electron,
entryName: createdName,
baseDir: input.selectedDirectory.path,
})
createdName = name
createdPath = path
await window.electron.mkdir(createdPath)
} else {
const { name, path } = getNextFileName({
const { name, path } = await getNextFileName({
electron: window.electron,
entryName: createdName,
baseDir: input.selectedDirectory.path,
})
Expand All @@ -260,6 +272,9 @@ export const FileMachineProvider = ({
}
}),
renameFile: fromPromise(async ({ input }) => {
if (!window.electron) {
return Promise.reject(new Error('No file system present'))
}
const { oldName, newName, isDir } = input
const name = newName
? newName.endsWith(FILE_EXT) || isDir
Expand Down Expand Up @@ -319,6 +334,7 @@ export const FileMachineProvider = ({
}
}),
deleteFile: fromPromise(async ({ input }) => {
if (!window.electron) return
const isDir = !!input.children

if (isDir) {
Expand Down Expand Up @@ -444,7 +460,7 @@ export const FileMachineProvider = ({

const kclCommandMemo = useMemo(() => {
const providedOptions = []
if (isDesktop() && project?.children && file?.path) {
if (window.electron && project?.children && file?.path) {
const projectPath = project.path
const filePath = file.path
let children = project.children
Expand Down
2 changes: 1 addition & 1 deletion src/components/HelpMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,17 @@
>
Release notes
</HelpMenuItem>
{isDesktop() && (
<HelpMenuItem
as="button"
onClick={() => {
close()
window.electron.appCheckForUpdates().catch(reportRejection)
window.electron?.appCheckForUpdates().catch(reportRejection)
}}
>
Check for updates
</HelpMenuItem>
)}

Check warning on line 126 in src/components/HelpMenu.tsx

View workflow job for this annotation

GitHub Actions / semgrep-oss/scan

jsx-not-internationalized

JSX element not internationalized Check for updates . You should support different languages in your website or app with internationalization. Instead use packages such as i18next in order to internationalize your elements.
<HelpMenuItem
as="button"
onClick={() => {
Expand Down
8 changes: 4 additions & 4 deletions src/components/MachineManagerProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { createContext, useEffect, useState } from 'react'

import { isDesktop } from '@src/lib/isDesktop'
import type { components } from '@src/lib/machine-api'
import { engineCommandManager } from '@src/lib/singletons'
import { reportRejection } from '@src/lib/trap'
Expand Down Expand Up @@ -56,15 +55,16 @@ export const MachineManagerProvider = ({
}

useEffect(() => {
if (!isDesktop()) return
if (!window.electron) return
const electron = window.electron

const update = async () => {
const _machineApiIp = await window.electron.getMachineApiIp()
const _machineApiIp = await electron.getMachineApiIp()
if (_machineApiIp === null) return

setMachineApiIp(_machineApiIp)

const _machines = await window.electron.listMachines(_machineApiIp)
const _machines = await electron.listMachines(_machineApiIp)
setMachines(_machines)
}

Expand Down
12 changes: 6 additions & 6 deletions src/components/ModelingMachineProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ import {
} from '@src/lib/constants'
import { exportMake } from '@src/lib/exportMake'
import { exportSave } from '@src/lib/exportSave'
import { isDesktop } from '@src/lib/isDesktop'
import type { FileEntry, Project } from '@src/lib/project'
import type { WebContentSendPayload } from '@src/menu/channels'
import {
Expand Down Expand Up @@ -1202,7 +1201,8 @@ export const ModelingMachineProvider = ({
}
)
let basePath = ''
if (isDesktop() && theProject?.current?.children) {
if (window.electron && theProject?.current?.children) {
const electron = window.electron
// Use the entire project directory as the basePath for prompt to edit, do not use relative subdir paths
basePath = theProject?.current?.path
const filePromises: Promise<FileMeta | null>[] = []
Expand All @@ -1218,17 +1218,17 @@ export const ModelingMachineProvider = ({
}

const absolutePathToFileNameWithExtension = file.path
const fileNameWithExtension = window.electron.path.relative(
const fileNameWithExtension = electron.path.relative(
basePath,
absolutePathToFileNameWithExtension
)

const filePromise = window.electron
const filePromise = electron
.readFile(absolutePathToFileNameWithExtension)
.then((file): FileMeta => {
uploadSize += file.byteLength
const decoder = new TextDecoder('utf-8')
const fileType = window.electron.path.extname(
const fileType = electron.path.extname(
absolutePathToFileNameWithExtension
)
if (fileType === FILE_EXT) {
Expand Down Expand Up @@ -1274,7 +1274,7 @@ export const ModelingMachineProvider = ({
// route to main.kcl by default for web and desktop
let filePath: string = PROJECT_ENTRYPOINT
const possibleFileName = file?.path
if (possibleFileName && isDesktop()) {
if (possibleFileName && window.electron) {
// When prompt to edit finishes, try to route to the file they were in otherwise go to main.kcl
filePath = window.electron.path.relative(basePath, possibleFileName)
}
Expand Down
3 changes: 1 addition & 2 deletions src/components/ModelingPageProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { useMenuListener } from '@src/hooks/useMenu'
import { createNamedViewsCommand } from '@src/lib/commandBarConfigs/namedViewsConfig'
import { createRouteCommands } from '@src/lib/commandBarConfigs/routeCommandConfig'
import { DEFAULT_DEFAULT_LENGTH_UNIT } from '@src/lib/constants'
import { isDesktop } from '@src/lib/isDesktop'
import { kclCommands } from '@src/lib/kclCommands'
import { BROWSER_PATH, PATHS } from '@src/lib/paths'
import { markOnce } from '@src/lib/performance'
Expand Down Expand Up @@ -118,7 +117,7 @@ export const ModelingPageProvider = ({

const kclCommandMemo = useMemo(() => {
const providedOptions = []
if (isDesktop() && project?.children && file?.path) {
if (window.electron && project?.children && file?.path) {
const projectPath = project.path
const filePath = file.path
let children = project.children
Expand Down
Loading
Loading