This commit is contained in:
49lf
2024-07-31 15:31:55 -04:00
parent 53467ee954
commit 638217311b
17 changed files with 298 additions and 218 deletions

View File

@ -49,7 +49,9 @@ export const FileMachineProvider = ({
commandBarSend({ type: 'Close' })
navigate(
`${paths.FILE}/${encodeURIComponent(
context.selectedDirectory + window.electron.path.sep + event.data.name
context.selectedDirectory +
window.electron.path.sep +
event.data.name
)}`
)
} else if (
@ -97,7 +99,10 @@ export const FileMachineProvider = ({
let createdPath: string
if (event.data.makeDir) {
createdPath = window.electron.path.join(context.selectedDirectory.path, createdName)
createdPath = window.electron.path.join(
context.selectedDirectory.path,
createdName
)
await window.electron.mkdir(createdPath)
} else {
createdPath =
@ -119,8 +124,14 @@ export const FileMachineProvider = ({
) => {
const { oldName, newName, isDir } = event.data
const name = newName ? newName : DEFAULT_FILE_NAME
const oldPath = window.electron.path.join(context.selectedDirectory.path, oldName)
const newDirPath = window.electron.path.join(context.selectedDirectory.path, name)
const oldPath = window.electron.path.join(
context.selectedDirectory.path,
oldName
)
const newDirPath = window.electron.path.join(
context.selectedDirectory.path,
name
)
const newPath =
newDirPath + (name.endsWith(FILE_EXT) || isDir ? '' : FILE_EXT)
@ -152,13 +163,15 @@ export const FileMachineProvider = ({
const isDir = !!event.data.children
if (isDir) {
await window.electron.rm(event.data.path, {
await window.electron
.rm(event.data.path, {
recursive: true,
}).catch((e) => console.error('Error deleting directory', e))
})
.catch((e) => console.error('Error deleting directory', e))
} else {
await window.electron.rm(event.data.path).catch((e) =>
console.error('Error deleting file', e)
)
await window.electron
.rm(event.data.path)
.catch((e) => console.error('Error deleting file', e))
}
// If we just deleted the current file or one of its parent directories,

View File

@ -207,7 +207,9 @@ function ProjectMenuPopover({
<div className="flex flex-col items-start py-0.5">
<span className="hidden text-sm text-chalkboard-110 dark:text-chalkboard-20 whitespace-nowrap lg:block">
{isDesktop() && file?.name
? file.name.slice(file.name.lastIndexOf(window.electron.path.sep) + 1)
? file.name.slice(
file.name.lastIndexOf(window.electron.path.sep) + 1
)
: APP_NAME}
</span>
{isDesktop() && project?.name && (

View File

@ -46,7 +46,12 @@ export const AllSettingsFields = forwardRef(
location.pathname
.replace(paths.FILE + '/', '')
.replace(paths.SETTINGS, '')
.slice(0, decodeURI(location.pathname).lastIndexOf(window.electron.path.sep))
.slice(
0,
decodeURI(location.pathname).lastIndexOf(
window.electron.path.sep
)
)
)
: undefined

View File

@ -119,7 +119,9 @@ export default class CodeManager {
// Wait one event loop to give a chance for params to be set
// Save the file to disk
this._currentFilePath &&
window.electron.writeFile(this._currentFilePath, this.code ?? '').catch((err) => {
window.electron
.writeFile(this._currentFilePath, this.code ?? '')
.catch((err) => {
// TODO: add tracing per GH issue #254 (https://github.com/KittyCAD/modeling-app/issues/254)
console.error('error saving file', err)
toast.error('Error saving file, please check file permissions')

View File

@ -52,8 +52,9 @@ class FileSystemManager {
return Promise.reject(new Error(`Error checking file exists: ${error}`))
})
.then(async (file) => {
try { await window.electron.stat(file) }
catch (e) {
try {
await window.electron.stat(file)
} catch (e) {
if (e === 'ENOENT') {
return false
}
@ -77,7 +78,8 @@ class FileSystemManager {
return Promise.reject(new Error(`Error joining dir: ${error}`))
})
.then((filepath) => {
return window.electron.readdir(filepath)
return window.electron
.readdir(filepath)
.catch((error) => {
return Promise.reject(new Error(`Error reading dir: ${error}`))
})

View File

@ -13,15 +13,13 @@ import {
parseAppSettings,
parseProjectSettings,
} from 'lang/wasm'
export {
parseProjectRoute,
} from 'lang/wasm'
export { parseProjectRoute } from 'lang/wasm'
const DEFAULT_HOST = 'https://api.zoo.dev'
const SETTINGS_FILE_NAME = 'settings.toml'
const PROJECT_SETTINGS_FILE_NAME = 'project.toml'
const PROJECT_FOLDER = 'zoo-modeling-app-projects'
const DEFAULT_PROJECT_KCL_FILE = "main.kcl"
const DEFAULT_PROJECT_KCL_FILE = 'main.kcl'
// List machines on the local network.
export async function listMachines(): Promise<{
@ -44,20 +42,28 @@ export async function renameProjectDirectory(
return Promise.reject(new Error(`New name for project cannot be empty`))
}
try { await window.electron.stat(projectPath) }
catch (e) {
try {
await window.electron.stat(projectPath)
} catch (e) {
if (e === 'ENOENT') {
return Promise.reject(new Error(`Path ${projectPath} is not a directory`))
}
}
// Make sure the new name does not exist.
const newPath = window.electron.path.join(projectPath.split('/').slice(0, -1).join('/'), newName)
const newPath = window.electron.path.join(
projectPath.split('/').slice(0, -1).join('/'),
newName
)
try {
await window.electron.stat(newPath)
// If we get here it means the stat succeeded and there's a file already
// with the same name...
return Promise.reject(new Error(`Path ${newPath} already exists, cannot rename to an existing path`))
return Promise.reject(
new Error(
`Path ${newPath} already exists, cannot rename to an existing path`
)
)
} catch (e) {
// Otherwise if it failed and the failure is "it doesnt exist" then rename it!
if (e === 'ENOENT') {
@ -143,11 +149,15 @@ export async function listProjects(
const projectPath = window.electron.path.join(projectDir, entry)
// if it's not a directory ignore.
const isDirectory = await window.electron.statIsDirectory(projectPath)
if (!isDirectory) { continue }
if (!isDirectory) {
continue
}
const project = await getProjectInfo(projectPath)
// Needs at least one file to be added to the projects list
if (project.kcl_file_count === 0) { continue }
if (project.kcl_file_count === 0) {
continue
}
projects.push(project)
}
return projects
@ -155,16 +165,20 @@ export async function listProjects(
const IMPORT_FILE_EXTENSIONS = [
// TODO Use ImportFormat enum
"stp", "glb", "fbxb", "kcl"
'stp',
'glb',
'fbxb',
'kcl',
]
const isRelevantFile = (filename: string): boolean => IMPORT_FILE_EXTENSIONS.some(
(ext) => filename.endsWith('.' + ext))
const isRelevantFile = (filename: string): boolean =>
IMPORT_FILE_EXTENSIONS.some((ext) => filename.endsWith('.' + ext))
const collectAllFilesRecursiveFrom = async (path: string) => {
// Make sure the filesystem object exists.
try { await window.electron.stat(path) }
catch (e) {
try {
await window.electron.stat(path)
} catch (e) {
if (e === 'ENOENT') {
return Promise.reject(new Error(`Directory ${path} does not exist`))
}
@ -189,7 +203,9 @@ const collectAllFilesRecursiveFrom = async (path: string) => {
for (let e of entries) {
// ignore hidden files and directories (starting with a dot)
if (e.indexOf('.') === 0) { continue }
if (e.indexOf('.') === 0) {
continue
}
const ePath = window.electron.path.join(path, e)
const isEDir = await window.electron.statIsDirectory(ePath)
@ -198,12 +214,16 @@ const collectAllFilesRecursiveFrom = async (path: string) => {
const subChildren = await collectAllFilesRecursiveFrom(ePath)
children.push(subChildren)
} else {
if (!isRelevantFile(ePath)) { continue }
children.push(/* FileEntry */ {
if (!isRelevantFile(ePath)) {
continue
}
children.push(
/* FileEntry */ {
name: e,
path: ePath,
children: undefined,
})
}
)
}
}
@ -220,14 +240,18 @@ const getDefaultKclFileForDir = async (projectDir, file) => {
return Promise.reject(new Error(`Path ${projectDir} is not a directory`))
}
let defaultFilePath = window.electron.path.join(projectDir, DEFAULT_PROJECT_KCL_FILE)
try { await window.electron.stat(defaultFilePath) }
catch (e) {
let defaultFilePath = window.electron.path.join(
projectDir,
DEFAULT_PROJECT_KCL_FILE
)
try {
await window.electron.stat(defaultFilePath)
} catch (e) {
if (e === 'ENOENT') {
// Find a kcl file in the directory.
if (file.children) {
for (let entry of file.children) {
if (entry.name.endsWith(".kcl")) {
if (entry.name.endsWith('.kcl')) {
return window.electron.path.join(projectDir, entry.name)
} else if (entry.children.length > 0) {
// Recursively find a kcl file in the directory.
@ -252,7 +276,7 @@ const kclFileCount = (file /* fileEntry */) => {
let count = 0
if (file.children) {
for (let entry of file.children) {
if (entry.name.endsWith(".kcl")) {
if (entry.name.endsWith('.kcl')) {
count += 1
} else {
count += kclFileCount(entry)
@ -276,22 +300,24 @@ const directoryCount = (file /* FileEntry */) => {
return count
}
export async function getProjectInfo(
projectPath: string,
): Promise<Project> {
export async function getProjectInfo(projectPath: string): Promise<Project> {
// Check the directory.
try { await window.electron.stat(projectPath) }
catch (e) {
try {
await window.electron.stat(projectPath)
} catch (e) {
if (e === 'ENOENT') {
return Promise.reject(new Error(`Project directory does not exist: ${project_path}`))
return Promise.reject(
new Error(`Project directory does not exist: ${project_path}`)
)
}
}
// Make sure it is a directory.
const projectPathIsDir = await window.electron.statIsDirectory(projectPath)
if (!projectPathIsDir) {
return Promise.reject(new Error(`Project path is not a directory: ${project_path}`))
return Promise.reject(
new Error(`Project path is not a directory: ${project_path}`)
)
}
let walked = await collectAllFilesRecursiveFrom(projectPath)
@ -361,19 +387,21 @@ export const getInitialDefaultDir = async () => {
return window.electron.path.join(dir, PROJECT_FOLDER)
}
export const readProjectSettingsFile = async (projectPath: string): ProjectConfiguration => {
export const readProjectSettingsFile = async (
projectPath: string
): ProjectConfiguration => {
let settingsPath = await getProjectSettingsFilePath(projectPath)
// Check if this file exists.
try { await window.electron.stat(settingsPath) }
catch (e) {
try {
await window.electron.stat(settingsPath)
} catch (e) {
if (e === 'ENOENT') {
// Return the default configuration.
return {}
}
}
const configToml = await window.electron.readFile(settingsPath)
const configObj = parseProjectSettings(configToml)
return configObj
@ -444,4 +472,3 @@ export const getUser = async (
})
return user
}

View File

@ -63,7 +63,10 @@ function interpolateProjectName(projectName: string) {
}
// Returns the next available index for a project name
export function getNextProjectIndex(projectName: string, projects: FileEntry[]) {
export function getNextProjectIndex(
projectName: string,
projects: FileEntry[]
) {
const regex = interpolateProjectName(projectName)
const matches = projects.map((project) => project.name?.match(regex))
const indices = matches

View File

@ -6,7 +6,8 @@ import packageJson from '../../package.json'
const open = (args: any) => ipcRenderer.invoke('dialog.showOpenDialog', args)
const save = (args: any) => ipcRenderer.invoke('dialog.showSaveDialog', args)
const openExternal = (url: any) => ipcRenderer.invoke('shell.openExternal', url)
const showInFolder = (path: string) => ipcRenderer.invoke('shell.showItemInFolder', path)
const showInFolder = (path: string) =>
ipcRenderer.invoke('shell.showItemInFolder', path)
const login = (host: string) => ipcRenderer.invoke('login', host)
const readFile = (path: string) => fs.readFile(path, 'utf-8')
@ -14,10 +15,12 @@ const rename = (prev: string, next: string) => fs.rename(prev, next)
const writeFile = (path: string, data: string) =>
fs.writeFile(path, data, 'utf-8')
const readdir = (path: string) => fs.readdir(path, 'utf-8')
const stat = (path: string) => fs.stat(path).catch((e) => Promise.reject(e.code))
const stat = (path: string) =>
fs.stat(path).catch((e) => Promise.reject(e.code))
// Electron has behavior where it doesn't clone the prototype chain over.
// So we need to call stat.isDirectory on this side.
const statIsDirectory = (path: string) => stat(path).then((res) => res.isDirectory())
const statIsDirectory = (path: string) =>
stat(path).then((res) => res.isDirectory())
const getPath = async (name: string) => ipcRenderer.invoke('app.getPath', name)
const exposeProcessEnv = (varName: string) => {

View File

@ -30,7 +30,10 @@ const save_ = async (file: ModelingAppFile) => {
if (filePathMeta.canceled) return
// Write the file.
await window.electron.writeFile(filePathMeta.filePath, new Uint8Array(file.contents))
await window.electron.writeFile(
filePathMeta.filePath,
new Uint8Array(file.contents)
)
} else {
// Download the file to the user's computer.
// Now we need to download the files to the user's downloads folder.

View File

@ -1,13 +1,14 @@
import { isDesktop } from 'lib/isDesktop'
export const openExternalBrowserIfDesktop = (to) => function(e) {
export const openExternalBrowserIfDesktop = (to) =>
function (e) {
if (isDesktop()) {
window.electron.openExternal(to || e.currentTarget.href)
e.preventDefault()
e.stopPropagation()
return false
}
}
}
// Open a new browser window desktop style or browser style.
export default async function openWindow(url: string) {

View File

@ -70,7 +70,9 @@ export const onboardingRedirectLoader: ActionFunction = async (args) => {
return settingsLoader(args)
}
export const fileLoader: LoaderFunction = async (routerData): Promise<FileLoaderData | Response> => {
export const fileLoader: LoaderFunction = async (
routerData
): Promise<FileLoaderData | Response> => {
const { params } = routerData
let { configuration } = await loadAndValidateSettings()
@ -93,7 +95,9 @@ export const fileLoader: LoaderFunction = async (routerData): Promise<FileLoader
if (!current_file_name || !current_file_path || !project_name) {
return redirect(
`${paths.FILE}/${encodeURIComponent(
`${params.id}${isDesktop() ? window.electron.path.sep : '/'}${PROJECT_ENTRYPOINT}`
`${params.id}${
isDesktop() ? window.electron.path.sep : '/'
}${PROJECT_ENTRYPOINT}`
)}`
)
}

View File

@ -209,14 +209,15 @@ export function createSettings() {
// In desktop end-to-end tests we can't control the file picker,
// so we seed the new directory value in the element's dataset
const inputRefVal = inputRef.current?.dataset.testValue
if (inputRef.current && inputRefVal && !Array.isArray(inputRefVal)) {
if (
inputRef.current &&
inputRefVal &&
!Array.isArray(inputRefVal)
) {
updateValue(inputRefVal)
} else {
const newPath = await window.electron.open({
properties: [
'openDirectory',
'createDirectory',
],
properties: ['openDirectory', 'createDirectory'],
defaultPath: value,
title: 'Choose a new project directory',
})

View File

@ -237,7 +237,10 @@ export async function saveSettings(
// Write the project settings.
if (onDesktop) {
await writeProjectSettingsFile({ projectPath, configuration: { settings: projectSettings }})
await writeProjectSettingsFile({
projectPath,
configuration: { settings: projectSettings },
})
} else {
localStorage.setItem(localStorageProjectSettingsPath(), tomlStr)
}

View File

@ -1,4 +1,7 @@
import { getNextProjectIndex, interpolateProjectNameWithIndex } from './desktopFS'
import {
getNextProjectIndex,
interpolateProjectNameWithIndex,
} from './desktopFS'
import { MAX_PADDING } from './constants'
describe('Test project name utility functions', () => {

View File

@ -146,7 +146,7 @@ async function getUser(context: UserContext) {
})
.then((res) => res.json())
.catch((err) => console.error('error from Browser getUser', err))
: getUserDesktop(context.token, VITE_KC_API_BASE_URL )
: getUserDesktop(context.token, VITE_KC_API_BASE_URL)
const user = await userPromise

View File

@ -81,7 +81,7 @@ ipcMain.handle('login', async (event, host) => {
// We can hardcode the client ID.
// This value is safe to be embedded in version control.
// This is the client ID of the KittyCAD app.
client_id: "2af127fb-e14e-400a-9c57-a9ed08d1a5b7",
client_id: '2af127fb-e14e-400a-9c57-a9ed08d1a5b7',
token_endpoint_auth_method: 'none',
})
@ -95,13 +95,15 @@ ipcMain.handle('login', async (event, host) => {
// and bypass the shell::open call as it fails on GitHub Actions.
const e2e_tauri_enabled = process.env.E2E_TAURI_ENABLED
if (e2e_tauri_enabled) {
console.warn(`E2E_TAURI_ENABLED is set, won't open ${handle.verification_uri_complete} externally`)
console.warn(
`E2E_TAURI_ENABLED is set, won't open ${handle.verification_uri_complete} externally`
)
let temp = '/tmp'
// Overwrite with Windows variable
if (process.env.TEMP) {
temp = process.env.TEMP
}
let path = path.join(temp, "kittycad_user_code")
let path = path.join(temp, 'kittycad_user_code')
console.log(`Writing to ${path}`)
await fs.writeFile(path, handle.user_code)
} else {

View File

@ -80,7 +80,10 @@ const Home = () => {
event: EventFrom<typeof homeMachine>
) => {
if (event.data && 'name' in event.data) {
let projectPath = context.defaultDirectory + window.electron.path.sep + event.data.name
let projectPath =
context.defaultDirectory +
window.electron.path.sep +
event.data.name
onProjectOpen(
{
name: event.data.name,
@ -138,9 +141,12 @@ const Home = () => {
context: ContextFrom<typeof homeMachine>,
event: EventFrom<typeof homeMachine, 'Delete project'>
) => {
await window.electron.rm(window.electron.path.join(context.defaultDirectory, event.data.name), {
await window.electron.rm(
window.electron.path.join(context.defaultDirectory, event.data.name),
{
recursive: true,
})
}
)
return `Successfully deleted "${event.data.name}"`
},
},