Compare commits
14 Commits
pierremtb/
...
nightly-v2
Author | SHA1 | Date | |
---|---|---|---|
f321ecdff0 | |||
d114ab798c | |||
69fec37107 | |||
8ca8c49cc3 | |||
b25fc302fd | |||
648b37c1dd | |||
18e5da5ca4 | |||
46524cda10 | |||
4585671a5d | |||
e7203b9e7a | |||
ab375f4b92 | |||
04ed6f52ee | |||
2332338ca1 | |||
41b97de3d1 |
@ -4,8 +4,12 @@ excerpt: "Import a CAD file."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
**WARNING:** This function is deprecated.
|
||||
|
||||
Import a CAD file.
|
||||
|
||||
**DEPRECATED** Prefer to use import statements.
|
||||
|
||||
For formats lacking unit data (such as STL, OBJ, or PLY files), the default unit of measurement is millimeters. Alternatively you may specify the unit by passing your desired measurement unit in the options parameter. When importing a GLTF file, the bin file will be imported as well. Import paths are relative to the current project directory.
|
||||
|
||||
Note: The import command currently only works when using the native Modeling App.
|
||||
|
@ -51,7 +51,6 @@ layout: manual
|
||||
* [`helixRevolutions`](kcl/helixRevolutions)
|
||||
* [`hole`](kcl/hole)
|
||||
* [`hollow`](kcl/hollow)
|
||||
* [`import`](kcl/import)
|
||||
* [`inch`](kcl/inch)
|
||||
* [`lastSegX`](kcl/lastSegX)
|
||||
* [`lastSegY`](kcl/lastSegY)
|
||||
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -92765,7 +92765,7 @@
|
||||
{
|
||||
"name": "import",
|
||||
"summary": "Import a CAD file.",
|
||||
"description": "For formats lacking unit data (such as STL, OBJ, or PLY files), the default unit of measurement is millimeters. Alternatively you may specify the unit by passing your desired measurement unit in the options parameter. When importing a GLTF file, the bin file will be imported as well. Import paths are relative to the current project directory.\n\nNote: The import command currently only works when using the native Modeling App.\n\nFor importing KCL functions using the `import` statement, see the docs on [KCL modules](/docs/kcl/modules).",
|
||||
"description": "**DEPRECATED** Prefer to use import statements.\n\nFor formats lacking unit data (such as STL, OBJ, or PLY files), the default unit of measurement is millimeters. Alternatively you may specify the unit by passing your desired measurement unit in the options parameter. When importing a GLTF file, the bin file will be imported as well. Import paths are relative to the current project directory.\n\nNote: The import command currently only works when using the native Modeling App.\n\nFor importing KCL functions using the `import` statement, see the docs on [KCL modules](/docs/kcl/modules).",
|
||||
"tags": [],
|
||||
"keywordArguments": false,
|
||||
"args": [
|
||||
@ -93168,7 +93168,7 @@
|
||||
"labelRequired": true
|
||||
},
|
||||
"unpublished": false,
|
||||
"deprecated": false,
|
||||
"deprecated": true,
|
||||
"examples": [
|
||||
"model = import(\"tests/inputs/cube.obj\")",
|
||||
"model = import(\"tests/inputs/cube.obj\", { format = \"obj\", units = \"m\" })",
|
||||
|
@ -1,7 +1,8 @@
|
||||
import { test, expect } from './zoo-test'
|
||||
|
||||
import { getUtils } from './test-utils'
|
||||
import * as fsp from 'fs/promises'
|
||||
import { executorInputPath, getUtils } from './test-utils'
|
||||
import { KCL_DEFAULT_LENGTH } from 'lib/constants'
|
||||
import path from 'path'
|
||||
|
||||
test.describe('Command bar tests', () => {
|
||||
test('Extrude from command bar selects extrude line after', async ({
|
||||
@ -305,4 +306,132 @@ test.describe('Command bar tests', () => {
|
||||
await arcToolCommand.click()
|
||||
await expect(arcToolButton).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
test(`Reacts to query param to open "import from URL" command`, async ({
|
||||
page,
|
||||
cmdBar,
|
||||
editor,
|
||||
homePage,
|
||||
}) => {
|
||||
await test.step(`Prepare and navigate to home page with query params`, async () => {
|
||||
const targetURL = `?create-file&name=test&units=mm&code=ZXh0cnVzaW9uRGlzdGFuY2UgPSAxMg%3D%3D&ask-open-desktop`
|
||||
await homePage.expectState({
|
||||
projectCards: [],
|
||||
sortBy: 'last-modified-desc',
|
||||
})
|
||||
await page.goto(page.url() + targetURL)
|
||||
expect(page.url()).toContain(targetURL)
|
||||
})
|
||||
|
||||
await test.step(`Submit the command`, async () => {
|
||||
await cmdBar.expectState({
|
||||
stage: 'arguments',
|
||||
commandName: 'Import file from URL',
|
||||
currentArgKey: 'method',
|
||||
currentArgValue: '',
|
||||
headerArguments: {
|
||||
Method: '',
|
||||
Name: 'test',
|
||||
Code: '1 line',
|
||||
},
|
||||
highlightedHeaderArg: 'method',
|
||||
})
|
||||
await cmdBar.selectOption({ name: 'New Project' }).click()
|
||||
await cmdBar.expectState({
|
||||
stage: 'review',
|
||||
commandName: 'Import file from URL',
|
||||
headerArguments: {
|
||||
Method: 'New project',
|
||||
Name: 'test',
|
||||
Code: '1 line',
|
||||
},
|
||||
})
|
||||
await cmdBar.progressCmdBar()
|
||||
})
|
||||
|
||||
await test.step(`Ensure we created the project and are in the modeling scene`, async () => {
|
||||
await editor.expectEditor.toContain('extrusionDistance = 12')
|
||||
})
|
||||
})
|
||||
|
||||
test(`"import from URL" can add to existing project`, async ({
|
||||
page,
|
||||
cmdBar,
|
||||
editor,
|
||||
homePage,
|
||||
toolbar,
|
||||
context,
|
||||
}) => {
|
||||
await context.folderSetupFn(async (dir) => {
|
||||
const testProjectDir = path.join(dir, 'testProjectDir')
|
||||
await Promise.all([fsp.mkdir(testProjectDir, { recursive: true })])
|
||||
await Promise.all([
|
||||
fsp.copyFile(
|
||||
executorInputPath('cylinder.kcl'),
|
||||
path.join(testProjectDir, 'main.kcl')
|
||||
),
|
||||
])
|
||||
})
|
||||
await test.step(`Prepare and navigate to home page with query params`, async () => {
|
||||
const targetURL = `?create-file&name=test&units=mm&code=ZXh0cnVzaW9uRGlzdGFuY2UgPSAxMg%3D%3D&ask-open-desktop`
|
||||
await homePage.expectState({
|
||||
projectCards: [
|
||||
{
|
||||
fileCount: 1,
|
||||
title: 'testProjectDir',
|
||||
},
|
||||
],
|
||||
sortBy: 'last-modified-desc',
|
||||
})
|
||||
await page.goto(page.url() + targetURL)
|
||||
expect(page.url()).toContain(targetURL)
|
||||
})
|
||||
|
||||
await test.step(`Submit the command`, async () => {
|
||||
await cmdBar.expectState({
|
||||
stage: 'arguments',
|
||||
commandName: 'Import file from URL',
|
||||
currentArgKey: 'method',
|
||||
currentArgValue: '',
|
||||
headerArguments: {
|
||||
Method: '',
|
||||
Name: 'test',
|
||||
Code: '1 line',
|
||||
},
|
||||
highlightedHeaderArg: 'method',
|
||||
})
|
||||
await cmdBar.selectOption({ name: 'Existing Project' }).click()
|
||||
await cmdBar.expectState({
|
||||
stage: 'arguments',
|
||||
commandName: 'Import file from URL',
|
||||
currentArgKey: 'projectName',
|
||||
currentArgValue: '',
|
||||
headerArguments: {
|
||||
Method: 'Existing project',
|
||||
Name: 'test',
|
||||
ProjectName: '',
|
||||
Code: '1 line',
|
||||
},
|
||||
highlightedHeaderArg: 'projectName',
|
||||
})
|
||||
await cmdBar.selectOption({ name: 'testProjectDir' }).click()
|
||||
await cmdBar.expectState({
|
||||
stage: 'review',
|
||||
commandName: 'Import file from URL',
|
||||
headerArguments: {
|
||||
Method: 'Existing project',
|
||||
ProjectName: 'testProjectDir',
|
||||
Name: 'test',
|
||||
Code: '1 line',
|
||||
},
|
||||
})
|
||||
await cmdBar.progressCmdBar()
|
||||
})
|
||||
|
||||
await test.step(`Ensure we created the project and are in the modeling scene`, async () => {
|
||||
await editor.expectEditor.toContain('extrusionDistance = 12')
|
||||
await toolbar.openPane('files')
|
||||
await toolbar.expectFileTreeState(['main.kcl', 'test.kcl'])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
@ -151,4 +151,11 @@ export class CmdBarFixture {
|
||||
chooseCommand = async (commandName: string) => {
|
||||
await this.cmdOptions.getByText(commandName).click()
|
||||
}
|
||||
|
||||
/**
|
||||
* Select an option from the command bar
|
||||
*/
|
||||
selectOption = (options: Parameters<typeof this.page.getByRole>[1]) => {
|
||||
return this.page.getByRole('option', options)
|
||||
}
|
||||
}
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 74 KiB |
Binary file not shown.
Before Width: | Height: | Size: 145 KiB After Width: | Height: | Size: 145 KiB |
@ -683,9 +683,9 @@ vite-tsconfig-paths@^4.3.2:
|
||||
tsconfck "^3.0.3"
|
||||
|
||||
vite@^5.0.0:
|
||||
version "5.4.11"
|
||||
resolved "https://registry.yarnpkg.com/vite/-/vite-5.4.11.tgz#3b415cd4aed781a356c1de5a9ebafb837715f6e5"
|
||||
integrity sha512-c7jFQRklXua0mTzneGW9QVyxFjUgwcihC4bXEtujIo2ouWCe1Ajt/amn2PCxYnhYfd5k09JX3SB7OYWFKYqj8Q==
|
||||
version "5.4.14"
|
||||
resolved "https://registry.yarnpkg.com/vite/-/vite-5.4.14.tgz#ff8255edb02134df180dcfca1916c37a6abe8408"
|
||||
integrity sha512-EK5cY7Q1D8JNhSaPKVK4pwBFvaTmZxEnoKXLG/U9gmdDcihQGNzFlgIvaxezFR4glP1LsuiedwMBqCXH3wZccA==
|
||||
dependencies:
|
||||
esbuild "^0.21.3"
|
||||
postcss "^8.4.43"
|
||||
|
15
src/App.tsx
15
src/App.tsx
@ -22,13 +22,28 @@ import Gizmo from 'components/Gizmo'
|
||||
import { CoreDumpManager } from 'lib/coredump'
|
||||
import { UnitsMenu } from 'components/UnitsMenu'
|
||||
import { CameraProjectionToggle } from 'components/CameraProjectionToggle'
|
||||
import { useCreateFileLinkQuery } from 'hooks/useCreateFileLinkQueryWatcher'
|
||||
import { maybeWriteToDisk } from 'lib/telemetry'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
maybeWriteToDisk()
|
||||
.then(() => {})
|
||||
.catch(() => {})
|
||||
|
||||
export function App() {
|
||||
const { project, file } = useLoaderData() as IndexLoaderData
|
||||
|
||||
// Keep a lookout for a URL query string that invokes the 'import file from URL' command
|
||||
useCreateFileLinkQuery((argDefaultValues) => {
|
||||
commandBarActor.send({
|
||||
type: 'Find and select command',
|
||||
data: {
|
||||
groupId: 'projects',
|
||||
name: 'Import file from URL',
|
||||
argDefaultValues,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
useRefreshSettings(PATHS.FILE + 'SETTINGS')
|
||||
const navigate = useNavigate()
|
||||
const filePath = useAbsoluteFilePath()
|
||||
|
@ -34,7 +34,7 @@ import {
|
||||
import SettingsAuthProvider from 'components/SettingsAuthProvider'
|
||||
import LspProvider from 'components/LspProvider'
|
||||
import { KclContextProvider } from 'lang/KclProvider'
|
||||
import { BROWSER_PROJECT_NAME } from 'lib/constants'
|
||||
import { ASK_TO_OPEN_QUERY_PARAM, BROWSER_PROJECT_NAME } from 'lib/constants'
|
||||
import { CoreDumpManager } from 'lib/coredump'
|
||||
import { codeManager, engineCommandManager } from 'lib/singletons'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
@ -46,6 +46,7 @@ import { AppStateProvider } from 'AppState'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
import { RouteProvider } from 'components/RouteProvider'
|
||||
import { ProjectsContextProvider } from 'components/ProjectsContextProvider'
|
||||
import { OpenInDesktopAppHandler } from 'components/OpenInDesktopAppHandler'
|
||||
|
||||
const createRouter = isDesktop() ? createHashRouter : createBrowserRouter
|
||||
|
||||
@ -57,6 +58,7 @@ const router = createRouter([
|
||||
/* Make sure auth is the outermost provider or else we will have
|
||||
* inefficient re-renders, use the react profiler to see. */
|
||||
element: (
|
||||
<OpenInDesktopAppHandler>
|
||||
<RouteProvider>
|
||||
<SettingsAuthProvider>
|
||||
<LspProvider>
|
||||
@ -72,16 +74,26 @@ const router = createRouter([
|
||||
</LspProvider>
|
||||
</SettingsAuthProvider>
|
||||
</RouteProvider>
|
||||
</OpenInDesktopAppHandler>
|
||||
),
|
||||
errorElement: <ErrorPage />,
|
||||
children: [
|
||||
{
|
||||
path: PATHS.INDEX,
|
||||
loader: async () => {
|
||||
loader: async ({ request }) => {
|
||||
const onDesktop = isDesktop()
|
||||
return onDesktop
|
||||
? redirect(PATHS.HOME)
|
||||
: redirect(PATHS.FILE + '/%2F' + BROWSER_PROJECT_NAME)
|
||||
const url = new URL(request.url)
|
||||
if (onDesktop) {
|
||||
return redirect(PATHS.HOME + (url.search || ''))
|
||||
} else {
|
||||
const searchParams = new URLSearchParams(url.search)
|
||||
if (!searchParams.has(ASK_TO_OPEN_QUERY_PARAM)) {
|
||||
return redirect(
|
||||
PATHS.FILE + '/%2F' + BROWSER_PROJECT_NAME + (url.search || '')
|
||||
)
|
||||
}
|
||||
}
|
||||
return null
|
||||
},
|
||||
},
|
||||
{
|
||||
|
@ -69,7 +69,8 @@ import {
|
||||
codeManager,
|
||||
editorManager,
|
||||
} from 'lib/singletons'
|
||||
import { getNodeFromPath, getNodePathFromSourceRange } from 'lang/queryAst'
|
||||
import { getNodeFromPath } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { executeAst, ToolTip } from 'lang/langHelpers'
|
||||
import {
|
||||
createProfileStartHandle,
|
||||
|
@ -1,6 +1,7 @@
|
||||
import { useModelingContext } from 'hooks/useModelingContext'
|
||||
import { editorManager, engineCommandManager, kclManager } from 'lib/singletons'
|
||||
import { getNodeFromPath, getNodePathFromSourceRange } from 'lang/queryAst'
|
||||
import { getNodeFromPath } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { trap } from 'lib/trap'
|
||||
import { codeToIdSelections } from 'lib/selections'
|
||||
|
@ -129,6 +129,7 @@ function CommandArgOptionInput({
|
||||
<label
|
||||
htmlFor="option-input"
|
||||
className="capitalize px-2 py-1 rounded-l bg-chalkboard-100 dark:bg-chalkboard-80 text-chalkboard-10 border-b border-b-chalkboard-100 dark:border-b-chalkboard-80"
|
||||
data-testid="cmd-bar-arg-name"
|
||||
>
|
||||
{argName}
|
||||
</label>
|
||||
|
@ -75,6 +75,7 @@ function CommandComboBox({
|
||||
autoFocus
|
||||
/>
|
||||
</div>
|
||||
{filteredOptions?.length ? (
|
||||
<Combobox.Options
|
||||
static
|
||||
className="overflow-y-auto max-h-96 cursor-pointer"
|
||||
@ -103,6 +104,11 @@ function CommandComboBox({
|
||||
</Combobox.Option>
|
||||
))}
|
||||
</Combobox.Options>
|
||||
) : (
|
||||
<p className="px-4 pt-2 text-chalkboard-60 dark:text-chalkboard-50">
|
||||
No results found
|
||||
</p>
|
||||
)}
|
||||
</Combobox>
|
||||
)
|
||||
}
|
||||
|
@ -47,8 +47,9 @@ export const FileMachineProvider = ({
|
||||
children: React.ReactNode
|
||||
}) => {
|
||||
const navigate = useNavigate()
|
||||
const { settings } = useSettingsAuthContext()
|
||||
const { project, file } = useRouteLoaderData(PATHS.FILE) as IndexLoaderData
|
||||
const { settings, auth } = useSettingsAuthContext()
|
||||
const projectData = useRouteLoaderData(PATHS.FILE) as IndexLoaderData
|
||||
const { project, file } = projectData
|
||||
const [kclSamples, setKclSamples] = React.useState<KclSamplesManifestItem[]>(
|
||||
[]
|
||||
)
|
||||
@ -295,8 +296,14 @@ export const FileMachineProvider = ({
|
||||
|
||||
const kclCommandMemo = useMemo(
|
||||
() =>
|
||||
kclCommands(
|
||||
async (data) => {
|
||||
kclCommands({
|
||||
authToken: auth?.context?.token ?? '',
|
||||
projectData,
|
||||
settings: {
|
||||
defaultUnit: settings?.context?.modeling.defaultUnit.current ?? 'mm',
|
||||
},
|
||||
specialPropsForSampleCommand: {
|
||||
onSubmit: async (data) => {
|
||||
if (data.method === 'overwrite') {
|
||||
codeManager.updateCodeStateEditor(data.code)
|
||||
await kclManager.executeCode(true)
|
||||
@ -324,11 +331,12 @@ export const FileMachineProvider = ({
|
||||
})
|
||||
}
|
||||
},
|
||||
kclSamples.map((sample) => ({
|
||||
providedOptions: kclSamples.map((sample) => ({
|
||||
value: sample.pathFromProjectDirectoryToFirstFile,
|
||||
name: sample.title,
|
||||
}))
|
||||
).filter(
|
||||
})),
|
||||
},
|
||||
}).filter(
|
||||
(command) => kclSamples.length || command.name !== 'open-kcl-example'
|
||||
),
|
||||
[codeManager, kclManager, send, kclSamples]
|
||||
|
@ -68,11 +68,8 @@ import {
|
||||
startSketchOnDefault,
|
||||
} from 'lang/modifyAst'
|
||||
import { PathToNode, Program, parse, recast, resultIsOk } from 'lang/wasm'
|
||||
import {
|
||||
artifactIsPlaneWithPaths,
|
||||
getNodePathFromSourceRange,
|
||||
isSingleCursorInPipe,
|
||||
} from 'lang/queryAst'
|
||||
import { artifactIsPlaneWithPaths, isSingleCursorInPipe } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { exportFromEngine } from 'lib/exportFromEngine'
|
||||
import { Models } from '@kittycad/lib/dist/types/src'
|
||||
import toast from 'react-hot-toast'
|
||||
|
@ -297,7 +297,7 @@ function ModelingPaneButton({
|
||||
})
|
||||
|
||||
return (
|
||||
<div id={paneConfig.id + '-button-holder'}>
|
||||
<div id={paneConfig.id + '-button-holder'} className="relative">
|
||||
<button
|
||||
className="group pointer-events-auto flex items-center justify-center border-transparent dark:border-transparent disabled:!border-transparent p-0 m-0 rounded-sm !outline-0 focus-visible:border-primary"
|
||||
onClick={onClick}
|
||||
@ -339,7 +339,7 @@ function ModelingPaneButton({
|
||||
<p
|
||||
id={`${paneConfig.id}-badge`}
|
||||
className={
|
||||
'absolute m-0 p-0 top-1 right-0 w-3 h-3 flex items-center justify-center text-[10px] font-semibold text-white bg-primary hue-rotate-90 rounded-full border border-chalkboard-10 dark:border-chalkboard-80 z-50 hover:cursor-pointer hover:scale-[2] transition-transform duration-200'
|
||||
'absolute m-0 p-0 bottom-4 left-4 w-3 h-3 flex items-center justify-center text-[10px] font-semibold text-white bg-primary hue-rotate-90 rounded-full border border-chalkboard-10 dark:border-chalkboard-80 z-50 hover:cursor-pointer hover:scale-[2] transition-transform duration-200'
|
||||
}
|
||||
onClick={showBadge.onClick}
|
||||
title={`Click to view ${showBadge.value} notification${
|
||||
|
68
src/components/OpenInDesktopAppHandler.test.tsx
Normal file
68
src/components/OpenInDesktopAppHandler.test.tsx
Normal file
@ -0,0 +1,68 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { BrowserRouter, Route, Routes } from 'react-router-dom'
|
||||
import { OpenInDesktopAppHandler } from './OpenInDesktopAppHandler'
|
||||
|
||||
/**
|
||||
* The behavior under test requires a router,
|
||||
* so we wrap the component in a minimal router setup.
|
||||
*/
|
||||
function TestingMinimalRouterWrapper({
|
||||
children,
|
||||
location,
|
||||
}: {
|
||||
location?: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<Routes location={location}>
|
||||
<Route
|
||||
path="/"
|
||||
element={<OpenInDesktopAppHandler>{children}</OpenInDesktopAppHandler>}
|
||||
/>
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
|
||||
describe('OpenInDesktopAppHandler tests', () => {
|
||||
test(`does not render the modal if no query param is present`, () => {
|
||||
render(
|
||||
<BrowserRouter>
|
||||
<TestingMinimalRouterWrapper>
|
||||
<p>Dummy app contents</p>
|
||||
</TestingMinimalRouterWrapper>
|
||||
</BrowserRouter>
|
||||
)
|
||||
|
||||
const dummyAppContents = screen.getByText('Dummy app contents')
|
||||
const modalContents = screen.queryByText('Open in desktop app')
|
||||
|
||||
expect(dummyAppContents).toBeInTheDocument()
|
||||
expect(modalContents).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test(`renders the modal if the query param is present`, () => {
|
||||
render(
|
||||
<BrowserRouter>
|
||||
<TestingMinimalRouterWrapper location="/?ask-open-desktop">
|
||||
<p>Dummy app contents</p>
|
||||
</TestingMinimalRouterWrapper>
|
||||
</BrowserRouter>
|
||||
)
|
||||
|
||||
let dummyAppContents = screen.queryByText('Dummy app contents')
|
||||
let modalButton = screen.queryByText('Continue to web app')
|
||||
|
||||
// Starts as disconnected
|
||||
expect(dummyAppContents).not.toBeInTheDocument()
|
||||
expect(modalButton).not.toBeFalsy()
|
||||
expect(modalButton).toBeInTheDocument()
|
||||
fireEvent.click(modalButton as Element)
|
||||
|
||||
// I don't like that you have to re-query the screen here
|
||||
dummyAppContents = screen.queryByText('Dummy app contents')
|
||||
modalButton = screen.queryByText('Continue to web app')
|
||||
|
||||
expect(dummyAppContents).toBeInTheDocument()
|
||||
expect(modalButton).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
125
src/components/OpenInDesktopAppHandler.tsx
Normal file
125
src/components/OpenInDesktopAppHandler.tsx
Normal file
@ -0,0 +1,125 @@
|
||||
import { getSystemTheme, Themes } from 'lib/theme'
|
||||
import { ZOO_STUDIO_PROTOCOL } from 'lib/constants'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { ASK_TO_OPEN_QUERY_PARAM } from 'lib/constants'
|
||||
import { VITE_KC_SITE_BASE_URL } from 'env'
|
||||
import { ActionButton } from './ActionButton'
|
||||
import { Transition } from '@headlessui/react'
|
||||
|
||||
/**
|
||||
* This component is a handler that checks if a certain query parameter
|
||||
* is present, and if so, it will show a modal asking the user if they
|
||||
* want to open the current page in the desktop app.
|
||||
*/
|
||||
export const OpenInDesktopAppHandler = (props: React.PropsWithChildren) => {
|
||||
const theme = getSystemTheme()
|
||||
const buttonClasses =
|
||||
'bg-transparent flex-0 hover:bg-primary/10 dark:hover:bg-primary/10'
|
||||
const pathLogomarkSvg = `${isDesktop() ? '.' : ''}/zma-logomark${
|
||||
theme === Themes.Light ? '-dark' : ''
|
||||
}.svg`
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
// We also ignore this param on desktop, as it is redundant
|
||||
const hasAskToOpenParam =
|
||||
!isDesktop() && searchParams.has(ASK_TO_OPEN_QUERY_PARAM)
|
||||
|
||||
/**
|
||||
* This function removes the query param to ask to open in desktop app
|
||||
* and then navigates to the same route but with our custom protocol
|
||||
* `zoo-studio:` instead of `https://${BASE_URL}`, to trigger the user's
|
||||
* desktop app to open.
|
||||
*/
|
||||
function onOpenInDesktopApp() {
|
||||
const newSearchParams = new URLSearchParams(globalThis.location.search)
|
||||
newSearchParams.delete(ASK_TO_OPEN_QUERY_PARAM)
|
||||
const newURL = `${ZOO_STUDIO_PROTOCOL}${globalThis.location.pathname.replace(
|
||||
'/',
|
||||
''
|
||||
)}${searchParams.size > 0 ? `?${newSearchParams.toString()}` : ''}`
|
||||
globalThis.location.href = newURL
|
||||
}
|
||||
|
||||
/**
|
||||
* Just remove the query param to ask to open in desktop app
|
||||
* and continue to the web app.
|
||||
*/
|
||||
function continueToWebApp() {
|
||||
searchParams.delete(ASK_TO_OPEN_QUERY_PARAM)
|
||||
setSearchParams(searchParams)
|
||||
}
|
||||
|
||||
return hasAskToOpenParam ? (
|
||||
<Transition
|
||||
appear
|
||||
show={true}
|
||||
as="div"
|
||||
className={
|
||||
theme +
|
||||
` fixed inset-0 grid p-4 place-content-center ${
|
||||
theme === Themes.Dark ? '!bg-chalkboard-110 text-chalkboard-20' : ''
|
||||
}`
|
||||
}
|
||||
>
|
||||
<Transition.Child
|
||||
as="div"
|
||||
className={`max-w-3xl py-6 px-10 flex flex-col items-center gap-8
|
||||
mx-auto border rounded-lg shadow-lg dark:bg-chalkboard-100`}
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
style={{ zIndex: 10 }}
|
||||
>
|
||||
<div>
|
||||
<h1 className="text-2xl">
|
||||
Launching{' '}
|
||||
<img
|
||||
src={pathLogomarkSvg}
|
||||
className="w-48"
|
||||
alt="Zoo Modeling App"
|
||||
/>
|
||||
</h1>
|
||||
</div>
|
||||
<p className="text-primary flex items-center gap-2">
|
||||
Choose where to open this link...
|
||||
</p>
|
||||
<div className="flex flex-col md:flex-row items-start justify-between gap-4 xl:gap-8">
|
||||
<div className="flex flex-col gap-2">
|
||||
<ActionButton
|
||||
Element="button"
|
||||
className={buttonClasses + ' !text-base'}
|
||||
onClick={onOpenInDesktopApp}
|
||||
iconEnd={{ icon: 'arrowRight' }}
|
||||
>
|
||||
Open in desktop app
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
Element="externalLink"
|
||||
className={
|
||||
buttonClasses +
|
||||
' text-sm border-transparent justify-center dark:bg-transparent'
|
||||
}
|
||||
to={`${VITE_KC_SITE_BASE_URL}/modeling-app/download`}
|
||||
iconEnd={{ icon: 'link', bgClassName: '!bg-transparent' }}
|
||||
>
|
||||
Download desktop app
|
||||
</ActionButton>
|
||||
</div>
|
||||
<ActionButton
|
||||
Element="button"
|
||||
className={buttonClasses + ' -order-1 !text-base'}
|
||||
onClick={continueToWebApp}
|
||||
iconStart={{ icon: 'arrowLeft' }}
|
||||
>
|
||||
Continue to web app
|
||||
</ActionButton>
|
||||
</div>
|
||||
</Transition.Child>
|
||||
</Transition>
|
||||
) : (
|
||||
props.children
|
||||
)
|
||||
}
|
@ -9,7 +9,7 @@ import { Logo } from './Logo'
|
||||
import { APP_NAME } from 'lib/constants'
|
||||
import { CustomIcon } from './CustomIcon'
|
||||
import { useLspContext } from './LspProvider'
|
||||
import { engineCommandManager, kclManager } from 'lib/singletons'
|
||||
import { codeManager, engineCommandManager, kclManager } from 'lib/singletons'
|
||||
import { MachineManagerContext } from 'components/MachineManagerProvider'
|
||||
import usePlatform from 'hooks/usePlatform'
|
||||
import { useAbsoluteFilePath } from 'hooks/useAbsoluteFilePath'
|
||||
@ -17,6 +17,9 @@ import Tooltip from './Tooltip'
|
||||
import { SnapshotFrom } from 'xstate'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import { useSelector } from '@xstate/react'
|
||||
import { copyFileShareLink } from 'lib/links'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import { DEV } from 'env'
|
||||
|
||||
const ProjectSidebarMenu = ({
|
||||
project,
|
||||
@ -100,6 +103,7 @@ function ProjectMenuPopover({
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const filePath = useAbsoluteFilePath()
|
||||
const { settings, auth } = useSettingsAuthContext()
|
||||
const machineManager = useContext(MachineManagerContext)
|
||||
const commands = useSelector(commandBarActor, commandsSelector)
|
||||
|
||||
@ -158,7 +162,6 @@ function ProjectMenuPopover({
|
||||
data: exportCommandInfo,
|
||||
}),
|
||||
},
|
||||
'break',
|
||||
{
|
||||
id: 'make',
|
||||
Element: 'button',
|
||||
@ -184,6 +187,20 @@ function ProjectMenuPopover({
|
||||
})
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'share-link',
|
||||
Element: 'button',
|
||||
children: 'Share link to file',
|
||||
disabled: !DEV,
|
||||
onClick: async () => {
|
||||
await copyFileShareLink({
|
||||
token: auth?.context.token || '',
|
||||
code: codeManager.code,
|
||||
name: project?.name || '',
|
||||
units: settings.context.modeling.defaultUnit.current,
|
||||
})
|
||||
},
|
||||
},
|
||||
'break',
|
||||
{
|
||||
id: 'go-home',
|
||||
|
@ -2,11 +2,11 @@ import { useMachine } from '@xstate/react'
|
||||
import { useFileSystemWatcher } from 'hooks/useFileSystemWatcher'
|
||||
import { useProjectsLoader } from 'hooks/useProjectsLoader'
|
||||
import { projectsMachine } from 'machines/projectsMachine'
|
||||
import { createContext, useEffect, useState } from 'react'
|
||||
import { createContext, useCallback, useEffect, useState } from 'react'
|
||||
import { Actor, AnyStateMachine, fromPromise, Prop, StateFrom } from 'xstate'
|
||||
import { useLspContext } from './LspProvider'
|
||||
import toast from 'react-hot-toast'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
|
||||
import { PATHS } from 'lib/paths'
|
||||
import {
|
||||
createNewProjectDirectory,
|
||||
@ -18,12 +18,28 @@ import {
|
||||
interpolateProjectNameWithIndex,
|
||||
doesProjectNameNeedInterpolated,
|
||||
getUniqueProjectName,
|
||||
getNextFileName,
|
||||
} from 'lib/desktopFS'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import useStateMachineCommands from 'hooks/useStateMachineCommands'
|
||||
import { projectsCommandBarConfig } from 'lib/commandBarConfigs/projectsCommandConfig'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import {
|
||||
CREATE_FILE_URL_PARAM,
|
||||
FILE_EXT,
|
||||
PROJECT_ENTRYPOINT,
|
||||
} from 'lib/constants'
|
||||
import { DeepPartial } from 'lib/types'
|
||||
import { Configuration } from 'wasm-lib/kcl/bindings/Configuration'
|
||||
import { codeManager } from 'lib/singletons'
|
||||
import {
|
||||
loadAndValidateSettings,
|
||||
projectConfigurationToSettingsPayload,
|
||||
saveSettings,
|
||||
setSettingsAtLevel,
|
||||
} from 'lib/settings/settingsUtils'
|
||||
import { Project } from 'lib/project'
|
||||
|
||||
type MachineContext<T extends AnyStateMachine> = {
|
||||
state?: StateFrom<T>
|
||||
@ -53,12 +69,110 @@ export const ProjectsContextProvider = ({
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* We need some of the functionality of the ProjectsContextProvider in the web version
|
||||
* but we can't perform file system operations in the browser,
|
||||
* so most of the behavior of this machine is stubbed out.
|
||||
*/
|
||||
const ProjectsContextWeb = ({ children }: { children: React.ReactNode }) => {
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const clearImportSearchParams = useCallback(() => {
|
||||
// Clear the search parameters related to the "Import file from URL" command
|
||||
// or we'll never be able cancel or submit it.
|
||||
searchParams.delete(CREATE_FILE_URL_PARAM)
|
||||
searchParams.delete('code')
|
||||
searchParams.delete('name')
|
||||
searchParams.delete('units')
|
||||
setSearchParams(searchParams)
|
||||
}, [searchParams, setSearchParams])
|
||||
const {
|
||||
settings: { context: settings, send: settingsSend },
|
||||
} = useSettingsAuthContext()
|
||||
|
||||
const [state, send, actor] = useMachine(
|
||||
projectsMachine.provide({
|
||||
actions: {
|
||||
navigateToProject: () => {},
|
||||
navigateToProjectIfNeeded: () => {},
|
||||
navigateToFile: () => {},
|
||||
toastSuccess: ({ event }) =>
|
||||
toast.success(
|
||||
('data' in event && typeof event.data === 'string' && event.data) ||
|
||||
('output' in event &&
|
||||
'message' in event.output &&
|
||||
typeof event.output.message === 'string' &&
|
||||
event.output.message) ||
|
||||
''
|
||||
),
|
||||
toastError: ({ event }) =>
|
||||
toast.error(
|
||||
('data' in event && typeof event.data === 'string' && event.data) ||
|
||||
('output' in event &&
|
||||
typeof event.output === 'string' &&
|
||||
event.output) ||
|
||||
''
|
||||
),
|
||||
},
|
||||
actors: {
|
||||
readProjects: fromPromise(async () => [] as Project[]),
|
||||
createProject: fromPromise(async () => ({
|
||||
message: 'not implemented on web',
|
||||
})),
|
||||
renameProject: fromPromise(async () => ({
|
||||
message: 'not implemented on web',
|
||||
oldName: '',
|
||||
newName: '',
|
||||
})),
|
||||
deleteProject: fromPromise(async () => ({
|
||||
message: 'not implemented on web',
|
||||
name: '',
|
||||
})),
|
||||
createFile: fromPromise(async ({ input }) => {
|
||||
// Browser version doesn't navigate, just overwrites the current file
|
||||
clearImportSearchParams()
|
||||
codeManager.updateCodeStateEditor(input.code || '')
|
||||
await codeManager.writeToFile()
|
||||
|
||||
settingsSend({
|
||||
type: 'set.modeling.defaultUnit',
|
||||
data: {
|
||||
level: 'project',
|
||||
value: input.units,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
message: 'File and units overwritten successfully',
|
||||
fileName: input.name,
|
||||
projectName: '',
|
||||
}
|
||||
}),
|
||||
},
|
||||
}),
|
||||
{
|
||||
input: {
|
||||
projects: [],
|
||||
defaultProjectName: settings.projects.defaultProjectName.current,
|
||||
defaultDirectory: settings.app.projectDirectory.current,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// register all project-related command palette commands
|
||||
useStateMachineCommands({
|
||||
machineId: 'projects',
|
||||
send,
|
||||
state,
|
||||
commandBarConfig: projectsCommandBarConfig,
|
||||
actor,
|
||||
onCancel: clearImportSearchParams,
|
||||
})
|
||||
|
||||
return (
|
||||
<ProjectsMachineContext.Provider
|
||||
value={{
|
||||
state: undefined,
|
||||
send: () => {},
|
||||
state,
|
||||
send,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
@ -73,18 +187,21 @@ const ProjectsContextDesktop = ({
|
||||
}) => {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const clearImportSearchParams = useCallback(() => {
|
||||
// Clear the search parameters related to the "Import file from URL" command
|
||||
// or we'll never be able cancel or submit it.
|
||||
searchParams.delete(CREATE_FILE_URL_PARAM)
|
||||
searchParams.delete('code')
|
||||
searchParams.delete('name')
|
||||
searchParams.delete('units')
|
||||
setSearchParams(searchParams)
|
||||
}, [searchParams, setSearchParams])
|
||||
const { onProjectOpen } = useLspContext()
|
||||
const {
|
||||
settings: { context: settings },
|
||||
} = useSettingsAuthContext()
|
||||
|
||||
useEffect(() => {
|
||||
console.log(
|
||||
'project directory changed',
|
||||
settings.app.projectDirectory.current
|
||||
)
|
||||
}, [settings.app.projectDirectory.current])
|
||||
|
||||
const [projectsLoaderTrigger, setProjectsLoaderTrigger] = useState(0)
|
||||
const { projectPaths, projectsDir } = useProjectsLoader([
|
||||
projectsLoaderTrigger,
|
||||
@ -168,6 +285,31 @@ const ProjectsContextDesktop = ({
|
||||
}
|
||||
}
|
||||
},
|
||||
navigateToFile: ({ context, event }) => {
|
||||
if (event.type !== 'xstate.done.actor.create-file') return
|
||||
// For now, the browser version of create-file doesn't need to navigate
|
||||
// since it just overwrites the current file.
|
||||
if (!isDesktop()) return
|
||||
let projectPath = window.electron.join(
|
||||
context.defaultDirectory,
|
||||
event.output.projectName
|
||||
)
|
||||
let filePath = window.electron.join(
|
||||
projectPath,
|
||||
event.output.fileName
|
||||
)
|
||||
onProjectOpen(
|
||||
{
|
||||
name: event.output.projectName,
|
||||
path: projectPath,
|
||||
},
|
||||
null
|
||||
)
|
||||
const pathToNavigateTo = `${PATHS.FILE}/${encodeURIComponent(
|
||||
filePath
|
||||
)}`
|
||||
navigate(pathToNavigateTo)
|
||||
},
|
||||
toastSuccess: ({ event }) =>
|
||||
toast.success(
|
||||
('data' in event && typeof event.data === 'string' && event.data) ||
|
||||
@ -217,8 +359,6 @@ const ProjectsContextDesktop = ({
|
||||
name = interpolateProjectNameWithIndex(name, nextIndex)
|
||||
}
|
||||
|
||||
console.log('from Project')
|
||||
|
||||
await renameProjectDirectory(
|
||||
window.electron.path.join(defaultDirectory, oldName),
|
||||
name
|
||||
@ -241,14 +381,83 @@ const ProjectsContextDesktop = ({
|
||||
name: input.name,
|
||||
}
|
||||
}),
|
||||
createFile: fromPromise(async ({ input }) => {
|
||||
let projectName =
|
||||
(input.method === 'newProject' ? input.name : input.projectName) ||
|
||||
settings.projects.defaultProjectName.current
|
||||
let fileName =
|
||||
input.method === 'newProject'
|
||||
? PROJECT_ENTRYPOINT
|
||||
: input.name.endsWith(FILE_EXT)
|
||||
? input.name
|
||||
: input.name + FILE_EXT
|
||||
let message = 'File created successfully'
|
||||
const unitsConfiguration: DeepPartial<Configuration> = {
|
||||
settings: {
|
||||
project: {
|
||||
directory: settings.app.projectDirectory.current,
|
||||
},
|
||||
guards: {
|
||||
'Has at least 1 project': ({ event }) => {
|
||||
if (event.type !== 'xstate.done.actor.read-projects') return false
|
||||
console.log(`from has at least 1 project: ${event.output.length}`)
|
||||
return event.output.length ? event.output.length >= 1 : false
|
||||
modeling: {
|
||||
base_unit: input.units,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const needsInterpolated = doesProjectNameNeedInterpolated(projectName)
|
||||
if (needsInterpolated) {
|
||||
const nextIndex = getNextProjectIndex(projectName, input.projects)
|
||||
projectName = interpolateProjectNameWithIndex(
|
||||
projectName,
|
||||
nextIndex
|
||||
)
|
||||
}
|
||||
|
||||
// Create the project around the file if newProject
|
||||
if (input.method === 'newProject') {
|
||||
await createNewProjectDirectory(
|
||||
projectName,
|
||||
input.code,
|
||||
unitsConfiguration
|
||||
)
|
||||
message = `Project "${projectName}" created successfully with link contents`
|
||||
} else {
|
||||
let projectPath = window.electron.join(
|
||||
settings.app.projectDirectory.current,
|
||||
projectName
|
||||
)
|
||||
|
||||
message = `File "${fileName}" created successfully`
|
||||
const existingConfiguration = await loadAndValidateSettings(
|
||||
projectPath
|
||||
)
|
||||
const settingsToSave = setSettingsAtLevel(
|
||||
existingConfiguration.settings,
|
||||
'project',
|
||||
projectConfigurationToSettingsPayload(unitsConfiguration)
|
||||
)
|
||||
await saveSettings(settingsToSave, projectPath)
|
||||
}
|
||||
|
||||
// Create the file
|
||||
let baseDir = window.electron.join(
|
||||
settings.app.projectDirectory.current,
|
||||
projectName
|
||||
)
|
||||
const { name, path } = getNextFileName({
|
||||
entryName: fileName,
|
||||
baseDir,
|
||||
})
|
||||
|
||||
fileName = name
|
||||
await window.electron.writeFile(path, input.code || '')
|
||||
|
||||
return {
|
||||
message,
|
||||
fileName,
|
||||
projectName,
|
||||
}
|
||||
}),
|
||||
},
|
||||
}),
|
||||
{
|
||||
input: {
|
||||
@ -270,6 +479,7 @@ const ProjectsContextDesktop = ({
|
||||
state,
|
||||
commandBarConfig: projectsCommandBarConfig,
|
||||
actor,
|
||||
onCancel: clearImportSearchParams,
|
||||
})
|
||||
|
||||
return (
|
||||
|
@ -1,10 +1,8 @@
|
||||
import { toolTips } from 'lang/langHelpers'
|
||||
import { Selections } from 'lib/selections'
|
||||
import { Program, Expr, VariableDeclarator } from '../../lang/wasm'
|
||||
import {
|
||||
getNodePathFromSourceRange,
|
||||
getNodeFromPath,
|
||||
} from '../../lang/queryAst'
|
||||
import { getNodeFromPath } from '../../lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { isSketchVariablesLinked } from '../../lang/std/sketchConstraints'
|
||||
import {
|
||||
transformSecondarySketchLinesTagFirst,
|
||||
|
65
src/hooks/useCreateFileLinkQueryWatcher.ts
Normal file
65
src/hooks/useCreateFileLinkQueryWatcher.ts
Normal file
@ -0,0 +1,65 @@
|
||||
import { base64ToString } from 'lib/base64'
|
||||
import { CREATE_FILE_URL_PARAM, DEFAULT_FILE_NAME } from 'lib/constants'
|
||||
import { useEffect } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { useSettingsAuthContext } from './useSettingsAuthContext'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { FileLinkParams } from 'lib/links'
|
||||
import { ProjectsCommandSchema } from 'lib/commandBarConfigs/projectsCommandConfig'
|
||||
import { baseUnitsUnion } from 'lib/settings/settingsTypes'
|
||||
|
||||
// For initializing the command arguments, we actually want `method` to be undefined
|
||||
// so that we don't skip it in the command palette.
|
||||
export type CreateFileSchemaMethodOptional = Omit<
|
||||
ProjectsCommandSchema['Import file from URL'],
|
||||
'method'
|
||||
> & {
|
||||
method?: 'newProject' | 'existingProject'
|
||||
}
|
||||
|
||||
/**
|
||||
* companion to createFileLink. This hook runs an effect on mount that
|
||||
* checks the URL for the CREATE_FILE_URL_PARAM and triggers the "Create file"
|
||||
* command if it is present, loading the command's default values from the other
|
||||
* URL parameters.
|
||||
*/
|
||||
export function useCreateFileLinkQuery(
|
||||
callback: (args: CreateFileSchemaMethodOptional) => void
|
||||
) {
|
||||
const [searchParams] = useSearchParams()
|
||||
const { settings } = useSettingsAuthContext()
|
||||
|
||||
useEffect(() => {
|
||||
const createFileParam = searchParams.has(CREATE_FILE_URL_PARAM)
|
||||
|
||||
if (createFileParam) {
|
||||
const params: FileLinkParams = {
|
||||
code: base64ToString(
|
||||
decodeURIComponent(searchParams.get('code') ?? '')
|
||||
),
|
||||
|
||||
name: searchParams.get('name') ?? DEFAULT_FILE_NAME,
|
||||
|
||||
units:
|
||||
(baseUnitsUnion.find((unit) => searchParams.get('units') === unit) ||
|
||||
settings.context.modeling.defaultUnit.default) ??
|
||||
settings.context.modeling.defaultUnit.current,
|
||||
}
|
||||
|
||||
const argDefaultValues: CreateFileSchemaMethodOptional = {
|
||||
name: params.name
|
||||
? isDesktop()
|
||||
? params.name.replace('.kcl', '')
|
||||
: params.name
|
||||
: isDesktop()
|
||||
? settings.context.projects.defaultProjectName.current
|
||||
: DEFAULT_FILE_NAME,
|
||||
code: params.code || '',
|
||||
units: params.units,
|
||||
method: isDesktop() ? undefined : 'existingProject',
|
||||
}
|
||||
|
||||
callback(argDefaultValues)
|
||||
}
|
||||
}, [searchParams])
|
||||
}
|
@ -17,7 +17,8 @@ import {
|
||||
} from 'lang/std/artifactGraph'
|
||||
import { err, reportRejection } from 'lib/trap'
|
||||
import { DefaultPlaneStr, getFaceDetails } from 'clientSideScene/sceneEntities'
|
||||
import { getNodeFromPath, getNodePathFromSourceRange } from 'lang/queryAst'
|
||||
import { getNodeFromPath } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { CallExpression, defaultSourceRange } from 'lang/wasm'
|
||||
import { EdgeCutInfo, ExtrudeFacePlane } from 'machines/modelingMachine'
|
||||
|
||||
|
@ -14,7 +14,7 @@ export const useProjectsLoader = (deps?: [number]) => {
|
||||
|
||||
useEffect(() => {
|
||||
// Useless on web, until we get fake filesystems over there.
|
||||
if (!isDesktop) return
|
||||
if (!isDesktop()) return
|
||||
|
||||
if (deps && deps[0] === lastTs) return
|
||||
|
||||
|
@ -322,6 +322,7 @@ export class KclManager {
|
||||
await this.ensureWasmInit()
|
||||
const { logs, errors, execState, isInterrupted } = await executeAst({
|
||||
ast,
|
||||
path: codeManager.currentFilePath || undefined,
|
||||
engineCommandManager: this.engineCommandManager,
|
||||
})
|
||||
|
||||
|
@ -80,6 +80,10 @@ export default class CodeManager {
|
||||
}))
|
||||
}
|
||||
|
||||
get currentFilePath(): string | null {
|
||||
return this._currentFilePath
|
||||
}
|
||||
|
||||
updateCurrentFilePath(path: string) {
|
||||
this._currentFilePath = path
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
import { getNodePathFromSourceRange, getNodeFromPath } from './queryAst'
|
||||
import { getNodeFromPath } from './queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import {
|
||||
Identifier,
|
||||
assertParse,
|
||||
|
@ -52,27 +52,22 @@ afterAll(async () => {
|
||||
} catch (e) {}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir('..')
|
||||
})
|
||||
|
||||
// The tests have to be sequential because we need to change directories
|
||||
// to support `import` working properly.
|
||||
// @ts-expect-error
|
||||
describe.sequential('Test KCL Samples from public Github repository', () => {
|
||||
// @ts-expect-error
|
||||
describe.sequential('when performing enginelessExecutor', () => {
|
||||
describe('Test KCL Samples from public Github repository', () => {
|
||||
describe('when performing enginelessExecutor', () => {
|
||||
manifest.forEach((file: KclSampleFile) => {
|
||||
// @ts-expect-error
|
||||
it.sequential(
|
||||
it(
|
||||
`should execute ${file.title} (${file.file}) successfully`,
|
||||
async () => {
|
||||
const [dirProject, fileKcl] =
|
||||
file.pathFromProjectDirectoryToFirstFile.split('/')
|
||||
process.chdir(dirProject)
|
||||
const code = await fs.readFile(fileKcl, 'utf-8')
|
||||
const code = await fs.readFile(
|
||||
file.pathFromProjectDirectoryToFirstFile,
|
||||
'utf-8'
|
||||
)
|
||||
const ast = assertParse(code)
|
||||
await enginelessExecutor(ast, programMemoryInit())
|
||||
await enginelessExecutor(
|
||||
ast,
|
||||
programMemoryInit(),
|
||||
file.pathFromProjectDirectoryToFirstFile
|
||||
)
|
||||
},
|
||||
files.length * 1000
|
||||
)
|
||||
|
@ -46,12 +46,14 @@ export const toolTips: Array<ToolTip> = [
|
||||
|
||||
export async function executeAst({
|
||||
ast,
|
||||
path,
|
||||
engineCommandManager,
|
||||
// If you set programMemoryOverride we assume you mean mock mode. Since that
|
||||
// is the only way to go about it.
|
||||
programMemoryOverride,
|
||||
}: {
|
||||
ast: Node<Program>
|
||||
path?: string
|
||||
engineCommandManager: EngineCommandManager
|
||||
programMemoryOverride?: ProgramMemory
|
||||
isInterrupted?: boolean
|
||||
@ -63,8 +65,8 @@ export async function executeAst({
|
||||
}> {
|
||||
try {
|
||||
const execState = await (programMemoryOverride
|
||||
? enginelessExecutor(ast, programMemoryOverride)
|
||||
: executor(ast, engineCommandManager))
|
||||
? enginelessExecutor(ast, programMemoryOverride, path)
|
||||
: executor(ast, engineCommandManager, path))
|
||||
|
||||
await engineCommandManager.waitForAllCommands()
|
||||
|
||||
|
@ -25,7 +25,8 @@ import {
|
||||
deleteFromSelection,
|
||||
} from './modifyAst'
|
||||
import { enginelessExecutor } from '../lib/testHelpers'
|
||||
import { findUsesOfTagInPipe, getNodePathFromSourceRange } from './queryAst'
|
||||
import { findUsesOfTagInPipe } from './queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { err } from 'lib/trap'
|
||||
import { SimplifiedArgDetails } from './std/stdTypes'
|
||||
import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
|
@ -26,10 +26,10 @@ import {
|
||||
findAllPreviousVariables,
|
||||
findAllPreviousVariablesPath,
|
||||
getNodeFromPath,
|
||||
getNodePathFromSourceRange,
|
||||
isNodeSafeToReplace,
|
||||
traverse,
|
||||
} from './queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { addTagForSketchOnFace, getConstraintInfo } from './std/sketch'
|
||||
import {
|
||||
PathToNodeMap,
|
||||
|
@ -21,7 +21,8 @@ import {
|
||||
ChamferParameters,
|
||||
EdgeTreatmentParameters,
|
||||
} from './addEdgeTreatment'
|
||||
import { getNodeFromPath, getNodePathFromSourceRange } from '../queryAst'
|
||||
import { getNodeFromPath } from '../queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { createLiteral } from 'lang/modifyAst'
|
||||
import { err } from 'lib/trap'
|
||||
import { Selection, Selections } from 'lib/selections'
|
||||
|
@ -20,10 +20,10 @@ import {
|
||||
} from '../modifyAst'
|
||||
import {
|
||||
getNodeFromPath,
|
||||
getNodePathFromSourceRange,
|
||||
hasSketchPipeBeenExtruded,
|
||||
traverse,
|
||||
} from '../queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import {
|
||||
addTagForSketchOnFace,
|
||||
getTagFromCallExpression,
|
||||
|
@ -19,7 +19,8 @@ import {
|
||||
findUniqueName,
|
||||
createVariableDeclaration,
|
||||
} from 'lang/modifyAst'
|
||||
import { getNodeFromPath, getNodePathFromSourceRange } from 'lang/queryAst'
|
||||
import { getNodeFromPath } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import {
|
||||
mutateAstWithTagForSketchSegment,
|
||||
getEdgeTagCall,
|
||||
|
@ -10,7 +10,6 @@ import {
|
||||
findAllPreviousVariables,
|
||||
isNodeSafeToReplace,
|
||||
isTypeInValue,
|
||||
getNodePathFromSourceRange,
|
||||
hasExtrudeSketch,
|
||||
findUsesOfTagInPipe,
|
||||
hasSketchPipeBeenExtruded,
|
||||
@ -19,6 +18,7 @@ import {
|
||||
getNodeFromPath,
|
||||
doesSceneHaveExtrudedSketch,
|
||||
} from './queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { enginelessExecutor } from '../lib/testHelpers'
|
||||
import {
|
||||
createArrayExpression,
|
||||
|
@ -22,6 +22,7 @@ import {
|
||||
VariableDeclaration,
|
||||
VariableDeclarator,
|
||||
} from './wasm'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { createIdentifier, splitPathAtLastIndex } from './modifyAst'
|
||||
import { getSketchSegmentFromSourceRange } from './std/sketchConstraints'
|
||||
import { getAngle } from '../lib/utils'
|
||||
@ -125,311 +126,6 @@ export function getNodeFromPathCurry(
|
||||
}
|
||||
}
|
||||
|
||||
function moreNodePathFromSourceRange(
|
||||
node: Node<
|
||||
| Expr
|
||||
| ImportStatement
|
||||
| ExpressionStatement
|
||||
| VariableDeclaration
|
||||
| ReturnStatement
|
||||
>,
|
||||
sourceRange: SourceRange,
|
||||
previousPath: PathToNode = [['body', '']]
|
||||
): PathToNode {
|
||||
const [start, end] = sourceRange
|
||||
let path: PathToNode = [...previousPath]
|
||||
const _node = { ...node }
|
||||
|
||||
if (start < _node.start || end > _node.end) return path
|
||||
|
||||
const isInRange = _node.start <= start && _node.end >= end
|
||||
|
||||
if (
|
||||
(_node.type === 'Identifier' ||
|
||||
_node.type === 'Literal' ||
|
||||
_node.type === 'TagDeclarator') &&
|
||||
isInRange
|
||||
) {
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'CallExpression' && isInRange) {
|
||||
const { callee, arguments: args } = _node
|
||||
if (
|
||||
callee.type === 'Identifier' &&
|
||||
callee.start <= start &&
|
||||
callee.end >= end
|
||||
) {
|
||||
path.push(['callee', 'CallExpression'])
|
||||
return path
|
||||
}
|
||||
if (args.length > 0) {
|
||||
for (let argIndex = 0; argIndex < args.length; argIndex++) {
|
||||
const arg = args[argIndex]
|
||||
if (arg.start <= start && arg.end >= end) {
|
||||
path.push(['arguments', 'CallExpression'])
|
||||
path.push([argIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(arg, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'CallExpressionKw' && isInRange) {
|
||||
const { callee, arguments: args } = _node
|
||||
if (
|
||||
callee.type === 'Identifier' &&
|
||||
callee.start <= start &&
|
||||
callee.end >= end
|
||||
) {
|
||||
path.push(['callee', 'CallExpressionKw'])
|
||||
return path
|
||||
}
|
||||
if (args.length > 0) {
|
||||
for (let argIndex = 0; argIndex < args.length; argIndex++) {
|
||||
const arg = args[argIndex].arg
|
||||
if (arg.start <= start && arg.end >= end) {
|
||||
path.push(['arguments', 'CallExpressionKw'])
|
||||
path.push([argIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(arg, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'BinaryExpression' && isInRange) {
|
||||
const { left, right } = _node
|
||||
if (left.start <= start && left.end >= end) {
|
||||
path.push(['left', 'BinaryExpression'])
|
||||
return moreNodePathFromSourceRange(left, sourceRange, path)
|
||||
}
|
||||
if (right.start <= start && right.end >= end) {
|
||||
path.push(['right', 'BinaryExpression'])
|
||||
return moreNodePathFromSourceRange(right, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'PipeExpression' && isInRange) {
|
||||
const { body } = _node
|
||||
for (let i = 0; i < body.length; i++) {
|
||||
const pipe = body[i]
|
||||
if (pipe.start <= start && pipe.end >= end) {
|
||||
path.push(['body', 'PipeExpression'])
|
||||
path.push([i, 'index'])
|
||||
return moreNodePathFromSourceRange(pipe, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ArrayExpression' && isInRange) {
|
||||
const { elements } = _node
|
||||
for (let elIndex = 0; elIndex < elements.length; elIndex++) {
|
||||
const element = elements[elIndex]
|
||||
if (element.start <= start && element.end >= end) {
|
||||
path.push(['elements', 'ArrayExpression'])
|
||||
path.push([elIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(element, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ObjectExpression' && isInRange) {
|
||||
const { properties } = _node
|
||||
for (let propIndex = 0; propIndex < properties.length; propIndex++) {
|
||||
const property = properties[propIndex]
|
||||
if (property.start <= start && property.end >= end) {
|
||||
path.push(['properties', 'ObjectExpression'])
|
||||
path.push([propIndex, 'index'])
|
||||
if (property.key.start <= start && property.key.end >= end) {
|
||||
path.push(['key', 'Property'])
|
||||
return moreNodePathFromSourceRange(property.key, sourceRange, path)
|
||||
}
|
||||
if (property.value.start <= start && property.value.end >= end) {
|
||||
path.push(['value', 'Property'])
|
||||
return moreNodePathFromSourceRange(property.value, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ExpressionStatement' && isInRange) {
|
||||
const { expression } = _node
|
||||
path.push(['expression', 'ExpressionStatement'])
|
||||
return moreNodePathFromSourceRange(expression, sourceRange, path)
|
||||
}
|
||||
if (_node.type === 'VariableDeclaration' && isInRange) {
|
||||
const declaration = _node.declaration
|
||||
|
||||
if (declaration.start <= start && declaration.end >= end) {
|
||||
path.push(['declaration', 'VariableDeclaration'])
|
||||
const init = declaration.init
|
||||
if (init.start <= start && init.end >= end) {
|
||||
path.push(['init', ''])
|
||||
return moreNodePathFromSourceRange(init, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_node.type === 'VariableDeclaration' && isInRange) {
|
||||
const declaration = _node.declaration
|
||||
|
||||
if (declaration.start <= start && declaration.end >= end) {
|
||||
const init = declaration.init
|
||||
if (init.start <= start && init.end >= end) {
|
||||
path.push(['declaration', 'VariableDeclaration'])
|
||||
path.push(['init', ''])
|
||||
return moreNodePathFromSourceRange(init, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'UnaryExpression' && isInRange) {
|
||||
const { argument } = _node
|
||||
if (argument.start <= start && argument.end >= end) {
|
||||
path.push(['argument', 'UnaryExpression'])
|
||||
return moreNodePathFromSourceRange(argument, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'FunctionExpression' && isInRange) {
|
||||
for (let i = 0; i < _node.params.length; i++) {
|
||||
const param = _node.params[i]
|
||||
if (param.identifier.start <= start && param.identifier.end >= end) {
|
||||
path.push(['params', 'FunctionExpression'])
|
||||
path.push([i, 'index'])
|
||||
return moreNodePathFromSourceRange(param.identifier, sourceRange, path)
|
||||
}
|
||||
}
|
||||
if (_node.body.start <= start && _node.body.end >= end) {
|
||||
path.push(['body', 'FunctionExpression'])
|
||||
const fnBody = _node.body.body
|
||||
for (let i = 0; i < fnBody.length; i++) {
|
||||
const statement = fnBody[i]
|
||||
if (statement.start <= start && statement.end >= end) {
|
||||
path.push(['body', 'FunctionExpression'])
|
||||
path.push([i, 'index'])
|
||||
return moreNodePathFromSourceRange(statement, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ReturnStatement' && isInRange) {
|
||||
const { argument } = _node
|
||||
if (argument.start <= start && argument.end >= end) {
|
||||
path.push(['argument', 'ReturnStatement'])
|
||||
return moreNodePathFromSourceRange(argument, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'MemberExpression' && isInRange) {
|
||||
const { object, property } = _node
|
||||
if (object.start <= start && object.end >= end) {
|
||||
path.push(['object', 'MemberExpression'])
|
||||
return moreNodePathFromSourceRange(object, sourceRange, path)
|
||||
}
|
||||
if (property.start <= start && property.end >= end) {
|
||||
path.push(['property', 'MemberExpression'])
|
||||
return moreNodePathFromSourceRange(property, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'PipeSubstitution' && isInRange) return path
|
||||
|
||||
if (_node.type === 'IfExpression' && isInRange) {
|
||||
const { cond, then_val, else_ifs, final_else } = _node
|
||||
if (cond.start <= start && cond.end >= end) {
|
||||
path.push(['cond', 'IfExpression'])
|
||||
return moreNodePathFromSourceRange(cond, sourceRange, path)
|
||||
}
|
||||
if (then_val.start <= start && then_val.end >= end) {
|
||||
path.push(['then_val', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(then_val, sourceRange, path)
|
||||
}
|
||||
for (let i = 0; i < else_ifs.length; i++) {
|
||||
const else_if = else_ifs[i]
|
||||
if (else_if.start <= start && else_if.end >= end) {
|
||||
path.push(['else_ifs', 'IfExpression'])
|
||||
path.push([i, 'index'])
|
||||
const { cond, then_val } = else_if
|
||||
if (cond.start <= start && cond.end >= end) {
|
||||
path.push(['cond', 'IfExpression'])
|
||||
return moreNodePathFromSourceRange(cond, sourceRange, path)
|
||||
}
|
||||
path.push(['then_val', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(then_val, sourceRange, path)
|
||||
}
|
||||
}
|
||||
if (final_else.start <= start && final_else.end >= end) {
|
||||
path.push(['final_else', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(final_else, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'ImportStatement' && isInRange) {
|
||||
if (_node.selector && _node.selector.type === 'List') {
|
||||
path.push(['selector', 'ImportStatement'])
|
||||
const { items } = _node.selector
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
if (item.start <= start && item.end >= end) {
|
||||
path.push(['items', 'ImportSelector'])
|
||||
path.push([i, 'index'])
|
||||
if (item.name.start <= start && item.name.end >= end) {
|
||||
path.push(['name', 'ImportItem'])
|
||||
return path
|
||||
}
|
||||
if (
|
||||
item.alias &&
|
||||
item.alias.start <= start &&
|
||||
item.alias.end >= end
|
||||
) {
|
||||
path.push(['alias', 'ImportItem'])
|
||||
return path
|
||||
}
|
||||
return path
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
console.error('not implemented: ' + node.type)
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
export function getNodePathFromSourceRange(
|
||||
node: Program,
|
||||
sourceRange: SourceRange,
|
||||
previousPath: PathToNode = [['body', '']]
|
||||
): PathToNode {
|
||||
const [start, end] = sourceRange || []
|
||||
let path: PathToNode = [...previousPath]
|
||||
const _node = { ...node }
|
||||
|
||||
// loop over each statement in body getting the index with a for loop
|
||||
for (
|
||||
let statementIndex = 0;
|
||||
statementIndex < _node.body.length;
|
||||
statementIndex++
|
||||
) {
|
||||
const statement = _node.body[statementIndex]
|
||||
if (statement.start <= start && statement.end >= end) {
|
||||
path.push([statementIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(statement, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
type KCLNode = Node<
|
||||
| Expr
|
||||
| ExpressionStatement
|
||||
|
316
src/lang/queryAstNodePathUtils.ts
Normal file
316
src/lang/queryAstNodePathUtils.ts
Normal file
@ -0,0 +1,316 @@
|
||||
import {
|
||||
Expr,
|
||||
ExpressionStatement,
|
||||
VariableDeclaration,
|
||||
ReturnStatement,
|
||||
SourceRange,
|
||||
PathToNode,
|
||||
Program,
|
||||
} from './wasm'
|
||||
import { ImportStatement } from 'wasm-lib/kcl/bindings/ImportStatement'
|
||||
import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
|
||||
function moreNodePathFromSourceRange(
|
||||
node: Node<
|
||||
| Expr
|
||||
| ImportStatement
|
||||
| ExpressionStatement
|
||||
| VariableDeclaration
|
||||
| ReturnStatement
|
||||
>,
|
||||
sourceRange: SourceRange,
|
||||
previousPath: PathToNode = [['body', '']]
|
||||
): PathToNode {
|
||||
const [start, end] = sourceRange
|
||||
let path: PathToNode = [...previousPath]
|
||||
const _node = { ...node }
|
||||
|
||||
if (start < _node.start || end > _node.end) return path
|
||||
|
||||
const isInRange = _node.start <= start && _node.end >= end
|
||||
|
||||
if (
|
||||
(_node.type === 'Identifier' ||
|
||||
_node.type === 'Literal' ||
|
||||
_node.type === 'TagDeclarator') &&
|
||||
isInRange
|
||||
) {
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'CallExpression' && isInRange) {
|
||||
const { callee, arguments: args } = _node
|
||||
if (
|
||||
callee.type === 'Identifier' &&
|
||||
callee.start <= start &&
|
||||
callee.end >= end
|
||||
) {
|
||||
path.push(['callee', 'CallExpression'])
|
||||
return path
|
||||
}
|
||||
if (args.length > 0) {
|
||||
for (let argIndex = 0; argIndex < args.length; argIndex++) {
|
||||
const arg = args[argIndex]
|
||||
if (arg.start <= start && arg.end >= end) {
|
||||
path.push(['arguments', 'CallExpression'])
|
||||
path.push([argIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(arg, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'CallExpressionKw' && isInRange) {
|
||||
const { callee, arguments: args } = _node
|
||||
if (
|
||||
callee.type === 'Identifier' &&
|
||||
callee.start <= start &&
|
||||
callee.end >= end
|
||||
) {
|
||||
path.push(['callee', 'CallExpressionKw'])
|
||||
return path
|
||||
}
|
||||
if (args.length > 0) {
|
||||
for (let argIndex = 0; argIndex < args.length; argIndex++) {
|
||||
const arg = args[argIndex].arg
|
||||
if (arg.start <= start && arg.end >= end) {
|
||||
path.push(['arguments', 'CallExpressionKw'])
|
||||
path.push([argIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(arg, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'BinaryExpression' && isInRange) {
|
||||
const { left, right } = _node
|
||||
if (left.start <= start && left.end >= end) {
|
||||
path.push(['left', 'BinaryExpression'])
|
||||
return moreNodePathFromSourceRange(left, sourceRange, path)
|
||||
}
|
||||
if (right.start <= start && right.end >= end) {
|
||||
path.push(['right', 'BinaryExpression'])
|
||||
return moreNodePathFromSourceRange(right, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'PipeExpression' && isInRange) {
|
||||
const { body } = _node
|
||||
for (let i = 0; i < body.length; i++) {
|
||||
const pipe = body[i]
|
||||
if (pipe.start <= start && pipe.end >= end) {
|
||||
path.push(['body', 'PipeExpression'])
|
||||
path.push([i, 'index'])
|
||||
return moreNodePathFromSourceRange(pipe, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ArrayExpression' && isInRange) {
|
||||
const { elements } = _node
|
||||
for (let elIndex = 0; elIndex < elements.length; elIndex++) {
|
||||
const element = elements[elIndex]
|
||||
if (element.start <= start && element.end >= end) {
|
||||
path.push(['elements', 'ArrayExpression'])
|
||||
path.push([elIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(element, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ObjectExpression' && isInRange) {
|
||||
const { properties } = _node
|
||||
for (let propIndex = 0; propIndex < properties.length; propIndex++) {
|
||||
const property = properties[propIndex]
|
||||
if (property.start <= start && property.end >= end) {
|
||||
path.push(['properties', 'ObjectExpression'])
|
||||
path.push([propIndex, 'index'])
|
||||
if (property.key.start <= start && property.key.end >= end) {
|
||||
path.push(['key', 'Property'])
|
||||
return moreNodePathFromSourceRange(property.key, sourceRange, path)
|
||||
}
|
||||
if (property.value.start <= start && property.value.end >= end) {
|
||||
path.push(['value', 'Property'])
|
||||
return moreNodePathFromSourceRange(property.value, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ExpressionStatement' && isInRange) {
|
||||
const { expression } = _node
|
||||
path.push(['expression', 'ExpressionStatement'])
|
||||
return moreNodePathFromSourceRange(expression, sourceRange, path)
|
||||
}
|
||||
if (_node.type === 'VariableDeclaration' && isInRange) {
|
||||
const declaration = _node.declaration
|
||||
|
||||
if (declaration.start <= start && declaration.end >= end) {
|
||||
path.push(['declaration', 'VariableDeclaration'])
|
||||
const init = declaration.init
|
||||
if (init.start <= start && init.end >= end) {
|
||||
path.push(['init', ''])
|
||||
return moreNodePathFromSourceRange(init, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (_node.type === 'VariableDeclaration' && isInRange) {
|
||||
const declaration = _node.declaration
|
||||
|
||||
if (declaration.start <= start && declaration.end >= end) {
|
||||
const init = declaration.init
|
||||
if (init.start <= start && init.end >= end) {
|
||||
path.push(['declaration', 'VariableDeclaration'])
|
||||
path.push(['init', ''])
|
||||
return moreNodePathFromSourceRange(init, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'UnaryExpression' && isInRange) {
|
||||
const { argument } = _node
|
||||
if (argument.start <= start && argument.end >= end) {
|
||||
path.push(['argument', 'UnaryExpression'])
|
||||
return moreNodePathFromSourceRange(argument, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'FunctionExpression' && isInRange) {
|
||||
for (let i = 0; i < _node.params.length; i++) {
|
||||
const param = _node.params[i]
|
||||
if (param.identifier.start <= start && param.identifier.end >= end) {
|
||||
path.push(['params', 'FunctionExpression'])
|
||||
path.push([i, 'index'])
|
||||
return moreNodePathFromSourceRange(param.identifier, sourceRange, path)
|
||||
}
|
||||
}
|
||||
if (_node.body.start <= start && _node.body.end >= end) {
|
||||
path.push(['body', 'FunctionExpression'])
|
||||
const fnBody = _node.body.body
|
||||
for (let i = 0; i < fnBody.length; i++) {
|
||||
const statement = fnBody[i]
|
||||
if (statement.start <= start && statement.end >= end) {
|
||||
path.push(['body', 'FunctionExpression'])
|
||||
path.push([i, 'index'])
|
||||
return moreNodePathFromSourceRange(statement, sourceRange, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'ReturnStatement' && isInRange) {
|
||||
const { argument } = _node
|
||||
if (argument.start <= start && argument.end >= end) {
|
||||
path.push(['argument', 'ReturnStatement'])
|
||||
return moreNodePathFromSourceRange(argument, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
if (_node.type === 'MemberExpression' && isInRange) {
|
||||
const { object, property } = _node
|
||||
if (object.start <= start && object.end >= end) {
|
||||
path.push(['object', 'MemberExpression'])
|
||||
return moreNodePathFromSourceRange(object, sourceRange, path)
|
||||
}
|
||||
if (property.start <= start && property.end >= end) {
|
||||
path.push(['property', 'MemberExpression'])
|
||||
return moreNodePathFromSourceRange(property, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'PipeSubstitution' && isInRange) return path
|
||||
|
||||
if (_node.type === 'IfExpression' && isInRange) {
|
||||
const { cond, then_val, else_ifs, final_else } = _node
|
||||
if (cond.start <= start && cond.end >= end) {
|
||||
path.push(['cond', 'IfExpression'])
|
||||
return moreNodePathFromSourceRange(cond, sourceRange, path)
|
||||
}
|
||||
if (then_val.start <= start && then_val.end >= end) {
|
||||
path.push(['then_val', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(then_val, sourceRange, path)
|
||||
}
|
||||
for (let i = 0; i < else_ifs.length; i++) {
|
||||
const else_if = else_ifs[i]
|
||||
if (else_if.start <= start && else_if.end >= end) {
|
||||
path.push(['else_ifs', 'IfExpression'])
|
||||
path.push([i, 'index'])
|
||||
const { cond, then_val } = else_if
|
||||
if (cond.start <= start && cond.end >= end) {
|
||||
path.push(['cond', 'IfExpression'])
|
||||
return moreNodePathFromSourceRange(cond, sourceRange, path)
|
||||
}
|
||||
path.push(['then_val', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(then_val, sourceRange, path)
|
||||
}
|
||||
}
|
||||
if (final_else.start <= start && final_else.end >= end) {
|
||||
path.push(['final_else', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(final_else, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'ImportStatement' && isInRange) {
|
||||
if (_node.selector && _node.selector.type === 'List') {
|
||||
path.push(['selector', 'ImportStatement'])
|
||||
const { items } = _node.selector
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
if (item.start <= start && item.end >= end) {
|
||||
path.push(['items', 'ImportSelector'])
|
||||
path.push([i, 'index'])
|
||||
if (item.name.start <= start && item.name.end >= end) {
|
||||
path.push(['name', 'ImportItem'])
|
||||
return path
|
||||
}
|
||||
if (
|
||||
item.alias &&
|
||||
item.alias.start <= start &&
|
||||
item.alias.end >= end
|
||||
) {
|
||||
path.push(['alias', 'ImportItem'])
|
||||
return path
|
||||
}
|
||||
return path
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
console.error('not implemented: ' + node.type)
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
export function getNodePathFromSourceRange(
|
||||
node: Program,
|
||||
sourceRange: SourceRange,
|
||||
previousPath: PathToNode = [['body', '']]
|
||||
): PathToNode {
|
||||
const [start, end] = sourceRange || []
|
||||
let path: PathToNode = [...previousPath]
|
||||
const _node = { ...node }
|
||||
|
||||
// loop over each statement in body getting the index with a for loop
|
||||
for (
|
||||
let statementIndex = 0;
|
||||
statementIndex < _node.body.length;
|
||||
statementIndex++
|
||||
) {
|
||||
const statement = _node.body[statementIndex]
|
||||
if (statement.start <= start && statement.end >= end) {
|
||||
path.push([statementIndex, 'index'])
|
||||
return moreNodePathFromSourceRange(statement, sourceRange, path)
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
@ -16,7 +16,7 @@ import {
|
||||
EdgeCut,
|
||||
} from 'lang/wasm'
|
||||
import { Models } from '@kittycad/lib'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { err } from 'lib/trap'
|
||||
|
||||
export type { Artifact, ArtifactId, SegmentArtifact } from 'lang/wasm'
|
||||
|
@ -31,6 +31,9 @@ class FileSystemManager {
|
||||
}
|
||||
|
||||
async join(dir: string, path: string): Promise<string> {
|
||||
if (path.startsWith(dir)) {
|
||||
path = path.slice(dir.length)
|
||||
}
|
||||
return Promise.resolve(window.electron.path.join(dir, path))
|
||||
}
|
||||
|
||||
|
@ -14,7 +14,8 @@ import {
|
||||
CallExpression,
|
||||
topLevelRange,
|
||||
} from '../wasm'
|
||||
import { getNodeFromPath, getNodePathFromSourceRange } from '../queryAst'
|
||||
import { getNodeFromPath } from '../queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { enginelessExecutor } from '../../lib/testHelpers'
|
||||
import { err } from 'lib/trap'
|
||||
import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
|
@ -17,9 +17,9 @@ import {
|
||||
import {
|
||||
getNodeFromPath,
|
||||
getNodeFromPathCurry,
|
||||
getNodePathFromSourceRange,
|
||||
getObjExprProperty,
|
||||
} from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import {
|
||||
isLiteralArrayOrStatic,
|
||||
isNotLiteralArrayOrStatic,
|
||||
|
@ -22,11 +22,8 @@ import {
|
||||
SourceRange,
|
||||
LiteralValue,
|
||||
} from '../wasm'
|
||||
import {
|
||||
getNodeFromPath,
|
||||
getNodeFromPathCurry,
|
||||
getNodePathFromSourceRange,
|
||||
} from '../queryAst'
|
||||
import { getNodeFromPath, getNodeFromPathCurry } from '../queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import {
|
||||
createArrayExpression,
|
||||
createBinaryExpression,
|
||||
|
@ -53,7 +53,7 @@ import { ArtifactId } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
import { ArtifactCommand } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
import { ArtifactGraph as RustArtifactGraph } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
import { Artifact } from './std/artifactGraph'
|
||||
import { getNodePathFromSourceRange } from './queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
|
||||
export type { Artifact } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
export type { ArtifactCommand } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
@ -566,9 +566,19 @@ export function sketchFromKclValue(
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a KCL program.
|
||||
* @param node The AST of the program to execute.
|
||||
* @param path The full path of the file being executed. Use `null` for
|
||||
* expressions that don't have a file, like expressions in the command bar.
|
||||
* @param programMemoryOverride If this is not `null`, this will be used as the
|
||||
* initial program memory, and the execution will be engineless (AKA mock
|
||||
* execution).
|
||||
*/
|
||||
export const executor = async (
|
||||
node: Node<Program>,
|
||||
engineCommandManager: EngineCommandManager,
|
||||
path?: string,
|
||||
programMemoryOverride: ProgramMemory | Error | null = null
|
||||
): Promise<ExecState> => {
|
||||
if (programMemoryOverride !== null && err(programMemoryOverride))
|
||||
@ -590,6 +600,7 @@ export const executor = async (
|
||||
}
|
||||
const execOutcome: RustExecOutcome = await execute(
|
||||
JSON.stringify(node),
|
||||
path,
|
||||
JSON.stringify(programMemoryOverride?.toRaw() || null),
|
||||
JSON.stringify({ settings: jsAppSettings }),
|
||||
engineCommandManager,
|
||||
|
40
src/lib/base64.test.ts
Normal file
40
src/lib/base64.test.ts
Normal file
@ -0,0 +1,40 @@
|
||||
import { expect } from 'vitest'
|
||||
import { base64ToString, stringToBase64 } from './base64'
|
||||
|
||||
describe('base64 encoding', () => {
|
||||
test('to base64, simple code', async () => {
|
||||
const code = `extrusionDistance = 12`
|
||||
// Generated by online tool
|
||||
const expectedBase64 = `ZXh0cnVzaW9uRGlzdGFuY2UgPSAxMg==`
|
||||
|
||||
const base64 = stringToBase64(code)
|
||||
expect(base64).toBe(expectedBase64)
|
||||
})
|
||||
|
||||
test(`to base64, code with UTF-8 characters`, async () => {
|
||||
// example adapted from MDN docs: https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
|
||||
const code = `a = 5; Ā = 12.in(); 𐀀 = Ā; 文 = 12.0; 🦄 = -5;`
|
||||
// Generated by online tool
|
||||
const expectedBase64 = `YSA9IDU7IMSAID0gMTIuaW4oKTsg8JCAgCA9IMSAOyDmlocgPSAxMi4wOyDwn6aEID0gLTU7`
|
||||
|
||||
const base64 = stringToBase64(code)
|
||||
expect(base64).toBe(expectedBase64)
|
||||
})
|
||||
|
||||
// The following are simply the reverse of the above tests
|
||||
test('from base64, simple code', async () => {
|
||||
const base64 = `ZXh0cnVzaW9uRGlzdGFuY2UgPSAxMg==`
|
||||
const expectedCode = `extrusionDistance = 12`
|
||||
|
||||
const code = base64ToString(base64)
|
||||
expect(code).toBe(expectedCode)
|
||||
})
|
||||
|
||||
test(`from base64, code with UTF-8 characters`, async () => {
|
||||
const base64 = `YSA9IDU7IMSAID0gMTIuaW4oKTsg8JCAgCA9IMSAOyDmlocgPSAxMi4wOyDwn6aEID0gLTU7`
|
||||
const expectedCode = `a = 5; Ā = 12.in(); 𐀀 = Ā; 文 = 12.0; 🦄 = -5;`
|
||||
|
||||
const code = base64ToString(base64)
|
||||
expect(code).toBe(expectedCode)
|
||||
})
|
||||
})
|
29
src/lib/base64.ts
Normal file
29
src/lib/base64.ts
Normal file
@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Converts a string to a base64 string, preserving the UTF-8 encoding
|
||||
*/
|
||||
export function stringToBase64(str: string) {
|
||||
return bytesToBase64(new TextEncoder().encode(str))
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a base64 string to a string, preserving the UTF-8 encoding
|
||||
*/
|
||||
export function base64ToString(base64: string) {
|
||||
return new TextDecoder().decode(base64ToBytes(base64))
|
||||
}
|
||||
|
||||
/**
|
||||
* From the MDN Web Docs
|
||||
* https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
|
||||
*/
|
||||
function base64ToBytes(base64: string) {
|
||||
const binString = atob(base64)
|
||||
return Uint8Array.from(binString, (m) => m.codePointAt(0)!)
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes: Uint8Array) {
|
||||
const binString = Array.from(bytes, (byte) =>
|
||||
String.fromCodePoint(byte)
|
||||
).join('')
|
||||
return btoa(binString)
|
||||
}
|
@ -1,5 +1,8 @@
|
||||
import { UnitLength_type } from '@kittycad/lib/dist/types/src/models'
|
||||
import { CommandBarOverwriteWarning } from 'components/CommandBarOverwriteWarning'
|
||||
import { StateMachineCommandSetConfig } from 'lib/commandTypes'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { baseUnitLabels, baseUnitsUnion } from 'lib/settings/settingsTypes'
|
||||
import { projectsMachine } from 'machines/projectsMachine'
|
||||
|
||||
export type ProjectsCommandSchema = {
|
||||
@ -17,6 +20,13 @@ export type ProjectsCommandSchema = {
|
||||
oldName: string
|
||||
newName: string
|
||||
}
|
||||
'Import file from URL': {
|
||||
name: string
|
||||
code?: string
|
||||
units: UnitLength_type
|
||||
method: 'newProject' | 'existingProject'
|
||||
projectName?: string
|
||||
}
|
||||
}
|
||||
|
||||
export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
@ -26,6 +36,7 @@ export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
'Open project': {
|
||||
icon: 'arrowRight',
|
||||
description: 'Open a project',
|
||||
status: isDesktop() ? 'active' : 'inactive',
|
||||
args: {
|
||||
name: {
|
||||
inputType: 'options',
|
||||
@ -42,6 +53,7 @@ export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
'Create project': {
|
||||
icon: 'folderPlus',
|
||||
description: 'Create a project',
|
||||
status: isDesktop() ? 'active' : 'inactive',
|
||||
args: {
|
||||
name: {
|
||||
inputType: 'string',
|
||||
@ -53,6 +65,7 @@ export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
'Delete project': {
|
||||
icon: 'close',
|
||||
description: 'Delete a project',
|
||||
status: isDesktop() ? 'active' : 'inactive',
|
||||
needsReview: true,
|
||||
reviewMessage: ({ argumentsToSubmit }) =>
|
||||
CommandBarOverwriteWarning({
|
||||
@ -75,6 +88,7 @@ export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
icon: 'folder',
|
||||
description: 'Rename a project',
|
||||
needsReview: true,
|
||||
status: isDesktop() ? 'active' : 'inactive',
|
||||
args: {
|
||||
oldName: {
|
||||
inputType: 'options',
|
||||
@ -92,4 +106,80 @@ export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
},
|
||||
},
|
||||
},
|
||||
'Import file from URL': {
|
||||
icon: 'file',
|
||||
description: 'Create a file',
|
||||
needsReview: true,
|
||||
status: 'active',
|
||||
args: {
|
||||
method: {
|
||||
inputType: 'options',
|
||||
required: true,
|
||||
skip: true,
|
||||
options: isDesktop()
|
||||
? [
|
||||
{ name: 'New project', value: 'newProject' },
|
||||
{ name: 'Existing project', value: 'existingProject' },
|
||||
]
|
||||
: [{ name: 'Overwrite', value: 'existingProject' }],
|
||||
valueSummary(value) {
|
||||
return isDesktop()
|
||||
? value === 'newProject'
|
||||
? 'New project'
|
||||
: 'Existing project'
|
||||
: 'Overwrite'
|
||||
},
|
||||
},
|
||||
// TODO: We can't get the currently-opened project to auto-populate here because
|
||||
// it's not available on projectMachine, but lower in fileMachine. Unify these.
|
||||
projectName: {
|
||||
inputType: 'options',
|
||||
required: (commandsContext) =>
|
||||
isDesktop() &&
|
||||
commandsContext.argumentsToSubmit.method === 'existingProject',
|
||||
skip: true,
|
||||
options: (_, context) =>
|
||||
context?.projects.map((p) => ({
|
||||
name: p.name!,
|
||||
value: p.name!,
|
||||
})) || [],
|
||||
},
|
||||
name: {
|
||||
inputType: 'string',
|
||||
required: isDesktop(),
|
||||
skip: true,
|
||||
},
|
||||
code: {
|
||||
inputType: 'text',
|
||||
required: true,
|
||||
skip: true,
|
||||
valueSummary(value) {
|
||||
const lineCount = value?.trim().split('\n').length
|
||||
return `${lineCount} line${lineCount === 1 ? '' : 's'}`
|
||||
},
|
||||
},
|
||||
units: {
|
||||
inputType: 'options',
|
||||
required: false,
|
||||
skip: true,
|
||||
options: baseUnitsUnion.map((unit) => ({
|
||||
name: baseUnitLabels[unit],
|
||||
value: unit,
|
||||
})),
|
||||
},
|
||||
},
|
||||
reviewMessage(commandBarContext) {
|
||||
return isDesktop()
|
||||
? `Will add the contents from URL to a new ${
|
||||
commandBarContext.argumentsToSubmit.method === 'newProject'
|
||||
? 'project with file main.kcl'
|
||||
: `file within the project "${commandBarContext.argumentsToSubmit.projectName}"`
|
||||
} named "${
|
||||
commandBarContext.argumentsToSubmit.name
|
||||
}", and set default units to "${
|
||||
commandBarContext.argumentsToSubmit.units
|
||||
}".`
|
||||
: `Will overwrite the contents of the current file with the contents from the URL.`
|
||||
},
|
||||
},
|
||||
}
|
||||
|
@ -69,6 +69,7 @@ export const KCL_DEFAULT_DEGREE = `360`
|
||||
export const TEST_SETTINGS_FILE_KEY = 'playwright-test-settings'
|
||||
|
||||
export const DEFAULT_HOST = 'https://api.zoo.dev'
|
||||
export const PROD_APP_URL = 'https://app.zoo.dev'
|
||||
export const SETTINGS_FILE_NAME = 'settings.toml'
|
||||
export const TOKEN_FILE_NAME = 'token.txt'
|
||||
export const PROJECT_SETTINGS_FILE_NAME = 'project.toml'
|
||||
@ -110,6 +111,9 @@ export const KCL_SAMPLES_MANIFEST_URLS = {
|
||||
localFallback: '/kcl-samples-manifest-fallback.json',
|
||||
} as const
|
||||
|
||||
/** URL parameter to create a file */
|
||||
export const CREATE_FILE_URL_PARAM = 'create-file'
|
||||
|
||||
/** Toast id for the app auto-updater toast */
|
||||
export const AUTO_UPDATER_TOAST_ID = 'auto-updater-toast'
|
||||
|
||||
@ -139,3 +143,12 @@ export const VIEW_NAMES_SEMANTIC = {
|
||||
} as const
|
||||
/** The modeling sidebar buttons' IDs get a suffix to prevent collisions */
|
||||
export const SIDEBAR_BUTTON_SUFFIX = '-pane-button'
|
||||
|
||||
/** Custom URL protocol our desktop registers */
|
||||
export const ZOO_STUDIO_PROTOCOL = 'zoo-studio:'
|
||||
|
||||
/**
|
||||
* A query parameter that triggers a modal
|
||||
* to "open in desktop app" when present in the URL
|
||||
*/
|
||||
export const ASK_TO_OPEN_QUERY_PARAM = 'ask-open-desktop'
|
||||
|
@ -1,12 +1,14 @@
|
||||
import { CommandBarOverwriteWarning } from 'components/CommandBarOverwriteWarning'
|
||||
import { Command, CommandArgumentOption } from './commandTypes'
|
||||
import { kclManager } from './singletons'
|
||||
import { codeManager, kclManager } from './singletons'
|
||||
import { isDesktop } from './isDesktop'
|
||||
import { FILE_EXT, PROJECT_SETTINGS_FILE_NAME } from './constants'
|
||||
import { UnitLength_type } from '@kittycad/lib/dist/types/src/models'
|
||||
import { parseProjectSettings } from 'lang/wasm'
|
||||
import { err, reportRejection } from './trap'
|
||||
import { projectConfigurationToSettingsPayload } from './settings/settingsUtils'
|
||||
import { copyFileShareLink } from './links'
|
||||
import { IndexLoaderData } from './types'
|
||||
|
||||
interface OnSubmitProps {
|
||||
sampleName: string
|
||||
@ -15,10 +17,21 @@ interface OnSubmitProps {
|
||||
method: 'overwrite' | 'newFile'
|
||||
}
|
||||
|
||||
export function kclCommands(
|
||||
onSubmit: (p: OnSubmitProps) => Promise<void>,
|
||||
interface KclCommandConfig {
|
||||
// TODO: find a different approach that doesn't require
|
||||
// special props for a single command
|
||||
specialPropsForSampleCommand: {
|
||||
onSubmit: (p: OnSubmitProps) => Promise<void>
|
||||
providedOptions: CommandArgumentOption<string>[]
|
||||
): Command[] {
|
||||
}
|
||||
projectData: IndexLoaderData
|
||||
authToken: string
|
||||
settings: {
|
||||
defaultUnit: UnitLength_type
|
||||
}
|
||||
}
|
||||
|
||||
export function kclCommands(commandProps: KclCommandConfig): Command[] {
|
||||
return [
|
||||
{
|
||||
name: 'format-code',
|
||||
@ -107,7 +120,9 @@ export function kclCommands(
|
||||
)
|
||||
.then((props) => {
|
||||
if (props?.code) {
|
||||
onSubmit(props).catch(reportError)
|
||||
commandProps.specialPropsForSampleCommand
|
||||
.onSubmit(props)
|
||||
.catch(reportError)
|
||||
}
|
||||
})
|
||||
.catch(reportError)
|
||||
@ -149,9 +164,25 @@ export function kclCommands(
|
||||
}
|
||||
return value
|
||||
},
|
||||
options: providedOptions,
|
||||
options: commandProps.specialPropsForSampleCommand.providedOptions,
|
||||
},
|
||||
},
|
||||
},
|
||||
// {
|
||||
// name: 'share-file-link',
|
||||
// displayName: 'Share file',
|
||||
// description: 'Create a link that contains a copy of the current file.',
|
||||
// groupId: 'code',
|
||||
// needsReview: false,
|
||||
// icon: 'link',
|
||||
// onSubmit: () => {
|
||||
// copyFileShareLink({
|
||||
// token: commandProps.authToken,
|
||||
// code: codeManager.code,
|
||||
// name: commandProps.projectData.project?.name || '',
|
||||
// units: commandProps.settings.defaultUnit,
|
||||
// }).catch(reportRejection)
|
||||
// },
|
||||
// },
|
||||
]
|
||||
}
|
||||
|
16
src/lib/links.test.ts
Normal file
16
src/lib/links.test.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { createCreateFileUrl } from './links'
|
||||
|
||||
describe(`link creation tests`, () => {
|
||||
test(`createCreateFileUrl happy path`, async () => {
|
||||
const code = `extrusionDistance = 12`
|
||||
const name = `test`
|
||||
const units = `mm`
|
||||
|
||||
// Converted with external online tools
|
||||
const expectedEncodedCode = `ZXh0cnVzaW9uRGlzdGFuY2UgPSAxMg%3D%3D`
|
||||
const expectedLink = `http://localhost:3000/?create-file=true&name=test&units=mm&code=${expectedEncodedCode}&ask-open-desktop=true`
|
||||
|
||||
const result = createCreateFileUrl({ code, name, units })
|
||||
expect(result.toString()).toBe(expectedLink)
|
||||
})
|
||||
})
|
100
src/lib/links.ts
Normal file
100
src/lib/links.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { UnitLength_type } from '@kittycad/lib/dist/types/src/models'
|
||||
import {
|
||||
ASK_TO_OPEN_QUERY_PARAM,
|
||||
CREATE_FILE_URL_PARAM,
|
||||
PROD_APP_URL,
|
||||
} from './constants'
|
||||
import { stringToBase64 } from './base64'
|
||||
import { DEV, VITE_KC_API_BASE_URL } from 'env'
|
||||
import toast from 'react-hot-toast'
|
||||
import { err } from './trap'
|
||||
export interface FileLinkParams {
|
||||
code: string
|
||||
name: string
|
||||
units: UnitLength_type
|
||||
}
|
||||
|
||||
export async function copyFileShareLink(
|
||||
args: FileLinkParams & { token: string }
|
||||
) {
|
||||
const token = args.token
|
||||
if (!token) {
|
||||
toast.error('You need to be signed in to share a file.', {
|
||||
duration: 5000,
|
||||
})
|
||||
return
|
||||
}
|
||||
const shareUrl = createCreateFileUrl(args)
|
||||
const shortlink = await createShortlink(token, shareUrl.toString())
|
||||
|
||||
if (err(shortlink)) {
|
||||
toast.error(shortlink.message, {
|
||||
duration: 5000,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await globalThis.navigator.clipboard.writeText(shortlink.url)
|
||||
toast.success(
|
||||
'Link copied to clipboard. Anyone who clicks this link will get a copy of this file. Share carefully!',
|
||||
{
|
||||
duration: 5000,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a URL with the necessary query parameters to trigger
|
||||
* the "Import file from URL" command in the app.
|
||||
*
|
||||
* With the additional step of asking the user if they want to
|
||||
* open the URL in the desktop app.
|
||||
*/
|
||||
export function createCreateFileUrl({ code, name, units }: FileLinkParams) {
|
||||
// Use the dev server if we are in development mode
|
||||
let origin = DEV ? 'http://localhost:3000' : PROD_APP_URL
|
||||
const searchParams = new URLSearchParams({
|
||||
[CREATE_FILE_URL_PARAM]: String(true),
|
||||
name,
|
||||
units,
|
||||
code: stringToBase64(code),
|
||||
[ASK_TO_OPEN_QUERY_PARAM]: String(true),
|
||||
})
|
||||
const createFileUrl = new URL(`?${searchParams.toString()}`, origin)
|
||||
|
||||
return createFileUrl
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a file's code, name, and units, creates shareable link to the
|
||||
* web app with a query parameter that triggers a modal to "open in desktop app".
|
||||
* That modal is defined in the `OpenInDesktopAppHandler` component.
|
||||
* TODO: update the return type to use TS library after its updated
|
||||
*/
|
||||
export async function createShortlink(
|
||||
token: string,
|
||||
url: string
|
||||
): Promise<Error | { key: string; url: string }> {
|
||||
/**
|
||||
* We don't use our `withBaseURL` function here because
|
||||
* there is no URL shortener service in the dev API.
|
||||
*/
|
||||
const response = await fetch(`${VITE_KC_API_BASE_URL}/user/shortlinks`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-type': 'application/json',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
url,
|
||||
// In future we can support org-scoped and password-protected shortlinks here
|
||||
// https://zoo.dev/docs/api/shortlinks/create-a-shortlink-for-a-user?lang=typescript
|
||||
}),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const error = await response.json()
|
||||
return new Error(`Failed to create shortlink: ${error.message}`)
|
||||
} else {
|
||||
return response.json()
|
||||
}
|
||||
}
|
@ -114,7 +114,7 @@ export const fileLoader: LoaderFunction = async (
|
||||
return redirect(
|
||||
`${PATHS.FILE}/${encodeURIComponent(
|
||||
isDesktop() ? fallbackFile : params.id + '/' + PROJECT_ENTRYPOINT
|
||||
)}`
|
||||
)}${new URL(routerData.request.url).search || ''}`
|
||||
)
|
||||
}
|
||||
|
||||
@ -188,11 +188,14 @@ export const fileLoader: LoaderFunction = async (
|
||||
|
||||
// Loads the settings and by extension the projects in the default directory
|
||||
// and returns them to the Home route, along with any errors that occurred
|
||||
export const homeLoader: LoaderFunction = async (): Promise<
|
||||
HomeLoaderData | Response
|
||||
> => {
|
||||
export const homeLoader: LoaderFunction = async ({
|
||||
request,
|
||||
}): Promise<HomeLoaderData | Response> => {
|
||||
const url = new URL(request.url)
|
||||
if (!isDesktop()) {
|
||||
return redirect(PATHS.FILE + '/%2F' + BROWSER_PROJECT_NAME)
|
||||
return redirect(
|
||||
PATHS.FILE + '/%2F' + BROWSER_PROJECT_NAME + (url.search || '')
|
||||
)
|
||||
}
|
||||
return {}
|
||||
}
|
||||
|
@ -18,11 +18,8 @@ import { EditorSelection, SelectionRange } from '@codemirror/state'
|
||||
import { getNormalisedCoordinates, isOverlap } from 'lib/utils'
|
||||
import { isCursorInSketchCommandRange } from 'lang/util'
|
||||
import { Program } from 'lang/wasm'
|
||||
import {
|
||||
getNodeFromPath,
|
||||
getNodePathFromSourceRange,
|
||||
isSingleCursorInPipe,
|
||||
} from 'lang/queryAst'
|
||||
import { getNodeFromPath, isSingleCursorInPipe } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { CommandArgument } from './commandTypes'
|
||||
import {
|
||||
DefaultPlaneStr,
|
||||
|
@ -80,7 +80,8 @@ class MockEngineCommandManager {
|
||||
|
||||
export async function enginelessExecutor(
|
||||
ast: Node<Program>,
|
||||
pmo: ProgramMemory | Error = ProgramMemory.empty()
|
||||
pmo: ProgramMemory | Error = ProgramMemory.empty(),
|
||||
path?: string
|
||||
): Promise<ExecState> {
|
||||
if (pmo !== null && err(pmo)) return Promise.reject(pmo)
|
||||
|
||||
@ -90,7 +91,7 @@ export async function enginelessExecutor(
|
||||
}) as any as EngineCommandManager
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
mockEngineCommandManager.startNewSession()
|
||||
const execState = await executor(ast, mockEngineCommandManager, pmo)
|
||||
const execState = await executor(ast, mockEngineCommandManager, path, pmo)
|
||||
await mockEngineCommandManager.waitForAllCommands()
|
||||
return execState
|
||||
}
|
||||
|
@ -16,10 +16,8 @@ import {
|
||||
} from 'lib/selections'
|
||||
import { assign, fromPromise, fromCallback, setup } from 'xstate'
|
||||
import { SidebarType } from 'components/ModelingSidebar/ModelingPanes'
|
||||
import {
|
||||
isNodeSafeToReplacePath,
|
||||
getNodePathFromSourceRange,
|
||||
} from 'lang/queryAst'
|
||||
import { isNodeSafeToReplacePath } from 'lang/queryAst'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import {
|
||||
kclManager,
|
||||
sceneInfra,
|
||||
|
@ -25,6 +25,10 @@ export const projectsMachine = setup({
|
||||
type: 'Delete project'
|
||||
data: ProjectsCommandSchema['Delete project']
|
||||
}
|
||||
| {
|
||||
type: 'Import file from URL'
|
||||
data: ProjectsCommandSchema['Import file from URL']
|
||||
}
|
||||
| { type: 'navigate'; data: { name: string } }
|
||||
| {
|
||||
type: 'xstate.done.actor.read-projects'
|
||||
@ -42,6 +46,10 @@ export const projectsMachine = setup({
|
||||
type: 'xstate.done.actor.rename-project'
|
||||
output: { message: string; oldName: string; newName: string }
|
||||
}
|
||||
| {
|
||||
type: 'xstate.done.actor.create-file'
|
||||
output: { message: string; projectName: string; fileName: string }
|
||||
}
|
||||
| { type: 'assign'; data: { [key: string]: any } },
|
||||
input: {} as {
|
||||
projects: Project[]
|
||||
@ -60,6 +68,7 @@ export const projectsMachine = setup({
|
||||
toastError: () => {},
|
||||
navigateToProject: () => {},
|
||||
navigateToProjectIfNeeded: () => {},
|
||||
navigateToFile: () => {},
|
||||
},
|
||||
actors: {
|
||||
readProjects: fromPromise(() => Promise.resolve([] as Project[])),
|
||||
@ -90,12 +99,22 @@ export const projectsMachine = setup({
|
||||
name: '',
|
||||
})
|
||||
),
|
||||
createFile: fromPromise(
|
||||
(_: {
|
||||
input: ProjectsCommandSchema['Import file from URL'] & {
|
||||
projects: Project[]
|
||||
}
|
||||
}) => Promise.resolve({ message: '', projectName: '', fileName: '' })
|
||||
),
|
||||
},
|
||||
guards: {
|
||||
'Has at least 1 project': () => false,
|
||||
'Has at least 1 project': ({ event }) => {
|
||||
if (event.type !== 'xstate.done.actor.read-projects') return false
|
||||
return event.output.length ? event.output.length >= 1 : false
|
||||
},
|
||||
},
|
||||
}).createMachine({
|
||||
/** @xstate-layout N4IgpgJg5mDOIC5QAkD2BbMACdBDAxgBYCWAdmAMS6yzFSkDaADALqKgAOqtALsaqXYgAHogAsAJgA0IAJ6IAjBIkA2AHQAOCUw0qNkjQE4xYjQF8zMtJhwES5NcmpZSqLBwBOqAFZh8PWAoAJTBcCHcvX39YZjYkEC5efkF40QQFFQBmAHY1Qwz9QwBWU0NMrRl5BGyxBTUVJlVM01rtBXNLEGtsPCIyMEdnVwifPwCKAGEPUJ5sT1H-WKFE4j4BITSMzMzNIsyJDSZMhSYmFWzKxAkTNSYxIuU9zOKT7IsrDB67fsHYEajxiEwv8xjFWMtuKtkhsrpJboZsioincFMdTIjLggVGJ1GImMVMg0JISjEV3l1PrY+g4nH95gDAiFSLgbPSxkt4is1ilQGlrhJ4YjkbU0RoMXJEIYkWoikV8hJinjdOdyd0qfYBrSQdFJtNcLNtTwOZxIdyYQh+YKkSjReKqqYBQoEQpsgiSi9MqrKb0Nb9DYEACJgAA2YANbMW4M5puhqVhAvxQptCnRKkxCleuw0Gm2+2aRVRXpsPp+Woj4wA8hwwKRDcaEjH1nGLXDE9aRSmxWmJVipWocmdsbL8kxC501SWHFMZmQoIaKBABAMyAA3VAAawG+D1swAtOX61zY7zENlEWoMkoatcdPoipjCWIZRIirozsPiYYi19qQNp-rZ3nMAPC8Dw1A4YN9QAM1QDx0DUbcZjAfdInZKMTSSJsT2qc9Lwka8lTvTFTB2WUMiyQwc3yPRv3VH4mRZQDywXJc1FXDcBmmZlMBQhYjXQhtMJ5ERT1wlQr0kQj7kxKiZTxM5s2zbQEVoycBgY9AmNQ-wKGA0DwMgngYLgtQuJZZCDwEo8sJEnD1Dwgjb2kntig0GUkWVfZDEMfFVO+Bwg1DPhSDnZjFwcdjNzUCAQzDCztP4uIMKhGy0jPezxPwySnPvHsTjlPIhyOHRsnwlM-N-NRArDLS+N0kDYIM6DYPgmKgvivjD0bYS+VbBF21RTs7UUUcimfRpXyYRF8LFCrfSBCBaoZFiItINcor1CBeIZLqhPNdKL0yxzs2cqoNDqdpSo0EoSoLOb6NCRaQv9FblzWjjTMe7bQQYBQksElKesUMRjFubRMllCHsm2a5MVldRDBfFpmj0IpxPuhwFqW0F6v0iDmpMzbvuiXbAfNFNQcaI5IaKaH9jETFsUMNRVDxOU5TxBULE6VwYvgeIJ38sAIT25td27KpdzG7yZeho5slHVmMc1IY3HLfnkrNZt2hOW5smRCQM2uhQHkZ6VtkRBFnmu0qFGVv11ZFsnm0kdN8QFJVjlUPZ9co+3-2C0KEqdrXsJMJ8ryc86iUyYiCvxFNzldb3jHtjTsf8EPj1ssQchZlR8jR5EmDRrIGZcuF7maF1aZtslx29IWqtiwPDSz1LxDxepnlOfYDghp03eyOpngzXuYdHNPHozgJ26B9IXR2cTvP0BVkSRXKqgLtyq8OfQcXOwlubMIA */
|
||||
/** @xstate-layout N4IgpgJg5mDOIC5QAkD2BbMACdBDAxgBYCWAdmAMS6yzFSkDaADALqKgAOqtALsaqXYgAHogAsAJgA0IAJ6IAjAHYAbADoArBJVMFTCQA4mTAMwmxAXwsy0mHARLkKASXRcATjywAzYgBtsb3cMLABVACUAGWY2JBAuXn5BONEESRl5BAUFFQM1HQUxJSYATmyFAyUTKxsMbDwiMjA1ZGosUlQsDmCAKzB8HlgKcLBcCC7e-sGYoQTiPgEhVIUy9SKSiQ0NEwkclRyMxGKJNRKlMRVDU23zpRqQW3qHJpa2jonUPoGhgGF3UZ42G6nymMzicwWyVAyzKJzECg0OiYGjERhK+kOWUMSlOGiUlTEJlMxRKBnuj3sjXIr1gHy+g2Go3GwPpsDBnG48ySS0QGj0+Q0JTOGkqBg2JhKmNRJy2OyUEn0Kml5LqlMczVatJZUyGI1IuDs2oG7PinMhPIQfKYAqFShF+PFkrkRwkYjU8OUShKKhMKg0pUs1geqoa6ppdJ1FD+AKBk2NrFmZu5KV5-L9tvtYokEsxelRagUCoMiMumyUdpVdlDL01Ee+FAAImAAoC6zwTRDk9DU9b08LRY7MWd1AZcoS-aoLiYFJWnlSNW0jQyAPIcMCkNsdpOLFOWtOC-sO7NOzLbGWFbY6acmFESWdql7R3B8UhQNsUCACZpkABuqAA1s0+D-M+YAALRLluiQ7t2WRMGIbryjeBgGBIEglNsCi5sY6hMOchQqEoCLFCh97VtST4vm+S4UGA7jBO4agcH4z7eKg7joGowExhBcbtgm4LblCIiKPBiHZiKqHoZhuaFhoBbGMYBhiPBCgStUQYUuRzR6gaZDUXxH5fmov4Ac0-z6pgvEgvGsQctBwnLGJahIZJaEYdOmKEfJuQSoRRKSRcZHPNSunoPp750QxTEsTwbEcWoFkGuBkECfZXIwSJcEIS5Ekoe5MnOggXqIaUqFiiUhIInemkhiFzRNi2EU0Z+1KmYBagQM2YCAtZ9JQRljmiTlrn5dJnlFShOLwcpZjKBs+KBrUVb1WojU9c1hlRexMWsexnFdS2KV8QN5q7laNqHlmOaTcpmjoWc8L6HoYrBfOagjGMm02QyrXfqQf4dSBEB9Tqp1dllebichUkeVhRXTiU+QecUKhCps4pvWGn0QN9rJGW1ANmYlTKg98DAKHZpoORanoyqh8oImU3pKJifJ5Ohdr7CYqjIvKWMvDjeORttjHMXtCXA2T0xpdTg20+W9MSIzgorIRXlpr6ORbPs+jwQLFEgVRPj+JQf0mUTHXcaBYG+AE4OZcsxbuts5hbCK+zFmImJgSc5zPV6BQVD6RQG80lERXblCi7tcX7VxRvgVHDtDQgaE4vK2gXKiTA6ItubmJo8IoqOylERUVhBh0XXwHEWn1YmNO7mBKg+2KpzK2IpIBUwBhqUtwYre9tbvEutfpWdsFFnkPpVJnQqz15Ozur36FoypREbGH4Zj438u7tO1qIu5qK5PBGyYjebpEkS44e9oVTbxHr5tnvk9ZeXajTuW+zaHNuzYRUmoeCEp-RKlUHJbeYVhYDDfhDVIxR5IGGnISQk6E+6EkxMUBQX9c66EMMg3Q5Zt7rWNkuOBjsjilDUAqQsZQzzgOkJNUk7o7SmF-tiXOUCmQwMGBQ1OF4TgVGzFUG8yIxQGDZiYPI4oqh+mPsrDSy05xhmfm+KO-CLT+iRucEUuwFQqWzMWXM2YTAuTtL6ZBylkRcMrkAA */
|
||||
id: 'Home machine',
|
||||
|
||||
initial: 'Reading projects',
|
||||
@ -111,6 +130,8 @@ export const projectsMachine = setup({
|
||||
})),
|
||||
target: '.Reading projects',
|
||||
},
|
||||
|
||||
'Import file from URL': '.Creating file',
|
||||
},
|
||||
states: {
|
||||
'Has no projects': {
|
||||
@ -155,7 +176,10 @@ export const projectsMachine = setup({
|
||||
id: 'create-project',
|
||||
src: 'createProject',
|
||||
input: ({ event, context }) => {
|
||||
if (event.type !== 'Create project') {
|
||||
if (
|
||||
event.type !== 'Create project' &&
|
||||
event.type !== 'Import file from URL'
|
||||
) {
|
||||
return {
|
||||
name: '',
|
||||
projects: context.projects,
|
||||
@ -272,5 +296,39 @@ export const projectsMachine = setup({
|
||||
],
|
||||
},
|
||||
},
|
||||
|
||||
'Creating file': {
|
||||
invoke: {
|
||||
id: 'create-file',
|
||||
src: 'createFile',
|
||||
input: ({ event, context }) => {
|
||||
if (event.type !== 'Import file from URL') {
|
||||
return {
|
||||
code: '',
|
||||
name: '',
|
||||
units: 'mm',
|
||||
method: 'existingProject',
|
||||
projects: context.projects,
|
||||
}
|
||||
}
|
||||
return {
|
||||
code: event.data.code || '',
|
||||
name: event.data.name,
|
||||
units: event.data.units,
|
||||
method: event.data.method,
|
||||
projectName: event.data.projectName,
|
||||
projects: context.projects,
|
||||
}
|
||||
},
|
||||
onDone: {
|
||||
target: 'Reading projects',
|
||||
actions: ['navigateToFile', 'toastSuccess'],
|
||||
},
|
||||
onError: {
|
||||
target: 'Reading projects',
|
||||
actions: 'toastError',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
37
src/main.ts
37
src/main.ts
@ -21,6 +21,7 @@ import minimist from 'minimist'
|
||||
import getCurrentProjectFile from 'lib/getCurrentProjectFile'
|
||||
import os from 'node:os'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
import { ZOO_STUDIO_PROTOCOL } from 'lib/constants'
|
||||
import argvFromYargs from './commandLineArgs'
|
||||
|
||||
import * as packageJSON from '../package.json'
|
||||
@ -48,9 +49,7 @@ process.env.VITE_KC_SITE_BASE_URL ??= 'https://zoo.dev'
|
||||
process.env.VITE_KC_SKIP_AUTH ??= 'false'
|
||||
process.env.VITE_KC_CONNECTION_TIMEOUT_MS ??= '15000'
|
||||
|
||||
const ZOO_STUDIO_PROTOCOL = 'zoo-studio'
|
||||
|
||||
/// Register our application to handle all "electron-fiddle://" protocols.
|
||||
/// Register our application to handle all "zoo-studio:" protocols.
|
||||
if (process.defaultApp) {
|
||||
if (process.argv.length >= 2) {
|
||||
app.setAsDefaultProtocolClient(ZOO_STUDIO_PROTOCOL, process.execPath, [
|
||||
@ -65,7 +64,7 @@ if (process.defaultApp) {
|
||||
// Must be done before ready event.
|
||||
registerStartupListeners()
|
||||
|
||||
const createWindow = (filePath?: string, reuse?: boolean): BrowserWindow => {
|
||||
const createWindow = (pathToOpen?: string, reuse?: boolean): BrowserWindow => {
|
||||
let newWindow
|
||||
|
||||
if (reuse) {
|
||||
@ -90,11 +89,34 @@ const createWindow = (filePath?: string, reuse?: boolean): BrowserWindow => {
|
||||
})
|
||||
}
|
||||
|
||||
const pathIsCustomProtocolLink =
|
||||
pathToOpen?.startsWith(ZOO_STUDIO_PROTOCOL) ?? false
|
||||
|
||||
// and load the index.html of the app.
|
||||
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
|
||||
newWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL).catch(reportRejection)
|
||||
const filteredPath = pathToOpen
|
||||
? decodeURI(pathToOpen.replace(ZOO_STUDIO_PROTOCOL, ''))
|
||||
: ''
|
||||
const fullHashBasedUrl = `${MAIN_WINDOW_VITE_DEV_SERVER_URL}/#/${filteredPath}`
|
||||
newWindow.loadURL(fullHashBasedUrl).catch(reportRejection)
|
||||
} else {
|
||||
getProjectPathAtStartup(filePath)
|
||||
if (pathIsCustomProtocolLink && pathToOpen) {
|
||||
// We're trying to open a custom protocol link
|
||||
const filteredPath = pathToOpen
|
||||
? decodeURI(pathToOpen.replace(ZOO_STUDIO_PROTOCOL, ''))
|
||||
: ''
|
||||
const startIndex = path.join(
|
||||
__dirname,
|
||||
`../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`
|
||||
)
|
||||
newWindow
|
||||
.loadFile(startIndex, {
|
||||
hash: filteredPath,
|
||||
})
|
||||
.catch(reportRejection)
|
||||
} else {
|
||||
// otherwise we're trying to open a local file from the command line
|
||||
getProjectPathAtStartup(pathToOpen)
|
||||
.then(async (projectPath) => {
|
||||
const startIndex = path.join(
|
||||
__dirname,
|
||||
@ -106,8 +128,6 @@ const createWindow = (filePath?: string, reuse?: boolean): BrowserWindow => {
|
||||
return
|
||||
}
|
||||
|
||||
console.log('Loading file', projectPath)
|
||||
|
||||
const fullUrl = `/file/${encodeURIComponent(projectPath)}`
|
||||
console.log('Full URL', fullUrl)
|
||||
|
||||
@ -117,6 +137,7 @@ const createWindow = (filePath?: string, reuse?: boolean): BrowserWindow => {
|
||||
})
|
||||
.catch(reportRejection)
|
||||
}
|
||||
}
|
||||
|
||||
// Open the DevTools.
|
||||
// mainWindow.webContents.openDevTools()
|
||||
|
@ -25,6 +25,7 @@ import { useFileSystemWatcher } from 'hooks/useFileSystemWatcher'
|
||||
import { useProjectsLoader } from 'hooks/useProjectsLoader'
|
||||
import { useProjectsContext } from 'hooks/useProjectsContext'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import { useCreateFileLinkQuery } from 'hooks/useCreateFileLinkQueryWatcher'
|
||||
|
||||
// This route only opens in the desktop context for now,
|
||||
// as defined in Router.tsx, so we can use the desktop APIs and types.
|
||||
@ -33,6 +34,18 @@ const Home = () => {
|
||||
const [projectsLoaderTrigger, setProjectsLoaderTrigger] = useState(0)
|
||||
const { projectsDir } = useProjectsLoader([projectsLoaderTrigger])
|
||||
|
||||
// Keep a lookout for a URL query string that invokes the 'import file from URL' command
|
||||
useCreateFileLinkQuery((argDefaultValues) => {
|
||||
commandBarActor.send({
|
||||
type: 'Find and select command',
|
||||
data: {
|
||||
groupId: 'projects',
|
||||
name: 'Import file from URL',
|
||||
argDefaultValues,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
useRefreshSettings(PATHS.HOME + 'SETTINGS')
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
|
30
src/wasm-lib/Cargo.lock
generated
30
src/wasm-lib/Cargo.lock
generated
@ -443,9 +443,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.23"
|
||||
version = "4.5.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3135e7ec2ef7b10c6ed8950f0f792ed96ee093fa088608f1c76e569722700c84"
|
||||
checksum = "769b0145982b4b48713e01ec42d61614425f27b7058bda7180a3a41f30104796"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
@ -453,9 +453,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.5.23"
|
||||
version = "4.5.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "30582fc632330df2bd26877bde0c1f4470d57c582bbc070376afcd04d8cb4838"
|
||||
checksum = "1b26884eb4b57140e4d2d93652abfa49498b938b3c9179f9fc487b0acc3edad7"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@ -467,9 +467,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.5.18"
|
||||
version = "4.5.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab"
|
||||
checksum = "54b755194d6389280185988721fffba69495eed5ee9feeee9a599b53db80318c"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@ -708,9 +708,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.6.0"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2"
|
||||
checksum = "0e60eed09d8c01d3cee5b7d30acb059b76614c918fa0f992e0dd6eeb10daad6f"
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
@ -1710,7 +1710,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kcl-lib"
|
||||
version = "0.2.30"
|
||||
version = "0.2.31"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"approx 0.5.1",
|
||||
@ -1844,9 +1844,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kittycad-modeling-cmds"
|
||||
version = "0.2.89"
|
||||
version = "0.2.93"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce9e58b34645facea36bc9f4868877bbe6fcac01b92896825e8d4f2f7c71dbd6"
|
||||
checksum = "67a993046541732e3c3ddd8a0364b55b7b138a9258beff353b6e7a043a41dce3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
@ -3266,9 +3266,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.135"
|
||||
version = "1.0.137"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b0d7ba2887406110130a978386c4e1befb98c674b4fba677954e4db976630d9"
|
||||
checksum = "930cfb6e6abf99298aaad7d29abbef7a9999a9a8806a40088f55f0dcec03146b"
|
||||
dependencies = [
|
||||
"indexmap 2.7.0",
|
||||
"itoa",
|
||||
@ -4184,9 +4184,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "1.11.1"
|
||||
version = "1.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b913a3b5fe84142e269d63cc62b64319ccaf89b748fc31fe025177f767a756c4"
|
||||
checksum = "b3758f5e68192bb96cc8f9b7e2c2cfdabb435499a28499a42f8f984092adad4b"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"serde",
|
||||
|
@ -76,7 +76,7 @@ members = [
|
||||
[workspace.dependencies]
|
||||
http = "1"
|
||||
kittycad = { version = "0.3.28", default-features = false, features = ["js", "requests"] }
|
||||
kittycad-modeling-cmds = { version = "0.2.89", features = [
|
||||
kittycad-modeling-cmds = { version = "0.2.93", features = [
|
||||
"ts-rs",
|
||||
"websocket",
|
||||
] }
|
||||
|
@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "kcl-lib"
|
||||
description = "KittyCAD Language implementation and tools"
|
||||
version = "0.2.30"
|
||||
version = "0.2.31"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/KittyCAD/modeling-app"
|
||||
@ -16,7 +16,7 @@ async-recursion = "1.1.1"
|
||||
async-trait = "0.1.85"
|
||||
base64 = "0.22.1"
|
||||
chrono = "0.4.38"
|
||||
clap = { version = "4.5.23", default-features = false, optional = true, features = [
|
||||
clap = { version = "4.5.27", default-features = false, optional = true, features = [
|
||||
"std",
|
||||
"derive",
|
||||
] }
|
||||
|
294
src/wasm-lib/kcl/src/execution/import.rs
Normal file
294
src/wasm-lib/kcl/src/execution/import.rs
Normal file
@ -0,0 +1,294 @@
|
||||
use std::{ffi::OsStr, path::Path, str::FromStr};
|
||||
|
||||
use anyhow::Result;
|
||||
use kcmc::{
|
||||
coord::{Axis, AxisDirectionPair, Direction, System},
|
||||
each_cmd as mcmd,
|
||||
format::InputFormat,
|
||||
ok_response::OkModelingCmdResponse,
|
||||
shared::FileImportFormat,
|
||||
units::UnitLength,
|
||||
websocket::OkWebSocketResponseData,
|
||||
ImportFile, ModelingCmd,
|
||||
};
|
||||
use kittycad_modeling_cmds as kcmc;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
errors::{KclError, KclErrorDetails},
|
||||
execution::{ExecState, ImportedGeometry},
|
||||
fs::FileSystem,
|
||||
source_range::SourceRange,
|
||||
};
|
||||
|
||||
use super::ExecutorContext;
|
||||
|
||||
// Zoo co-ordinate system.
|
||||
//
|
||||
// * Forward: -Y
|
||||
// * Up: +Z
|
||||
// * Handedness: Right
|
||||
pub const ZOO_COORD_SYSTEM: System = System {
|
||||
forward: AxisDirectionPair {
|
||||
axis: Axis::Y,
|
||||
direction: Direction::Negative,
|
||||
},
|
||||
up: AxisDirectionPair {
|
||||
axis: Axis::Z,
|
||||
direction: Direction::Positive,
|
||||
},
|
||||
};
|
||||
|
||||
pub async fn import_foreign(
|
||||
file_path: &Path,
|
||||
format: Option<InputFormat>,
|
||||
exec_state: &mut ExecState,
|
||||
ctxt: &ExecutorContext,
|
||||
source_range: SourceRange,
|
||||
) -> Result<PreImportedGeometry, KclError> {
|
||||
// Make sure the file exists.
|
||||
if !ctxt.fs.exists(file_path, source_range).await? {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!("File `{}` does not exist.", file_path.display()),
|
||||
source_ranges: vec![source_range],
|
||||
}));
|
||||
}
|
||||
|
||||
let ext_format = get_import_format_from_extension(file_path.extension().ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!("No file extension found for `{}`", file_path.display()),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?)
|
||||
.map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Get the format type from the extension of the file.
|
||||
let format = if let Some(format) = format {
|
||||
// Validate the given format with the extension format.
|
||||
validate_extension_format(ext_format, format.clone()).map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
format
|
||||
} else {
|
||||
ext_format
|
||||
};
|
||||
|
||||
// Get the file contents for each file path.
|
||||
let file_contents = ctxt.fs.read(file_path, source_range).await.map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// We want the file_path to be without the parent.
|
||||
let file_name = std::path::Path::new(&file_path)
|
||||
.file_name()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!("Could not get the file name from the path `{}`", file_path.display()),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
let mut import_files = vec![kcmc::ImportFile {
|
||||
path: file_name.to_string(),
|
||||
data: file_contents.clone(),
|
||||
}];
|
||||
|
||||
// In the case of a gltf importing a bin file we need to handle that! and figure out where the
|
||||
// file is relative to our current file.
|
||||
if let InputFormat::Gltf(..) = format {
|
||||
// Check if the file is a binary gltf file, in that case we don't need to import the bin
|
||||
// file.
|
||||
if !file_contents.starts_with(b"glTF") {
|
||||
let json = gltf_json::Root::from_slice(&file_contents).map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Read the gltf file and check if there is a bin file.
|
||||
for buffer in json.buffers.iter() {
|
||||
if let Some(uri) = &buffer.uri {
|
||||
if !uri.starts_with("data:") {
|
||||
// We want this path relative to the file_path given.
|
||||
let bin_path = std::path::Path::new(&file_path)
|
||||
.parent()
|
||||
.map(|p| p.join(uri))
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"Could not get the parent path of the file `{}`",
|
||||
file_path.display()
|
||||
),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
let bin_contents = ctxt.fs.read(&bin_path, source_range).await.map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
import_files.push(ImportFile {
|
||||
path: uri.to_string(),
|
||||
data: bin_contents,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(PreImportedGeometry {
|
||||
id: exec_state.next_uuid(),
|
||||
source_range,
|
||||
command: mcmd::ImportFiles {
|
||||
files: import_files.clone(),
|
||||
format,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub struct PreImportedGeometry {
|
||||
id: Uuid,
|
||||
command: mcmd::ImportFiles,
|
||||
source_range: SourceRange,
|
||||
}
|
||||
|
||||
pub async fn send_to_engine(pre: PreImportedGeometry, ctxt: &ExecutorContext) -> Result<ImportedGeometry, KclError> {
|
||||
if ctxt.is_mock() {
|
||||
return Ok(ImportedGeometry {
|
||||
id: pre.id,
|
||||
value: pre.command.files.iter().map(|f| f.path.to_string()).collect(),
|
||||
meta: vec![pre.source_range.into()],
|
||||
});
|
||||
}
|
||||
|
||||
let resp = ctxt
|
||||
.engine
|
||||
.send_modeling_cmd(pre.id, pre.source_range, &ModelingCmd::from(pre.command.clone()))
|
||||
.await?;
|
||||
|
||||
let OkWebSocketResponseData::Modeling {
|
||||
modeling_response: OkModelingCmdResponse::ImportFiles(imported_files),
|
||||
} = &resp
|
||||
else {
|
||||
return Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("ImportFiles response was not as expected: {:?}", resp),
|
||||
source_ranges: vec![pre.source_range],
|
||||
}));
|
||||
};
|
||||
|
||||
Ok(ImportedGeometry {
|
||||
id: imported_files.object_id,
|
||||
value: pre.command.files.iter().map(|f| f.path.to_string()).collect(),
|
||||
meta: vec![pre.source_range.into()],
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the source format from the extension.
|
||||
fn get_import_format_from_extension(ext: &OsStr) -> Result<InputFormat> {
|
||||
let ext = ext
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid file extension: `{ext:?}`"))?;
|
||||
let format = match FileImportFormat::from_str(ext) {
|
||||
Ok(format) => format,
|
||||
Err(_) => {
|
||||
if ext == "stp" {
|
||||
FileImportFormat::Step
|
||||
} else if ext == "glb" {
|
||||
FileImportFormat::Gltf
|
||||
} else {
|
||||
anyhow::bail!("unknown source format for file extension: {ext}. Try setting the `--src-format` flag explicitly or use a valid format.")
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Make the default units millimeters.
|
||||
let ul = UnitLength::Millimeters;
|
||||
|
||||
// Zoo co-ordinate system.
|
||||
//
|
||||
// * Forward: -Y
|
||||
// * Up: +Z
|
||||
// * Handedness: Right
|
||||
match format {
|
||||
FileImportFormat::Step => Ok(InputFormat::Step(kcmc::format::step::import::Options {
|
||||
split_closed_faces: false,
|
||||
})),
|
||||
FileImportFormat::Stl => Ok(InputFormat::Stl(kcmc::format::stl::import::Options {
|
||||
coords: ZOO_COORD_SYSTEM,
|
||||
units: ul,
|
||||
})),
|
||||
FileImportFormat::Obj => Ok(InputFormat::Obj(kcmc::format::obj::import::Options {
|
||||
coords: ZOO_COORD_SYSTEM,
|
||||
units: ul,
|
||||
})),
|
||||
FileImportFormat::Gltf => Ok(InputFormat::Gltf(kcmc::format::gltf::import::Options {})),
|
||||
FileImportFormat::Ply => Ok(InputFormat::Ply(kcmc::format::ply::import::Options {
|
||||
coords: ZOO_COORD_SYSTEM,
|
||||
units: ul,
|
||||
})),
|
||||
FileImportFormat::Fbx => Ok(InputFormat::Fbx(kcmc::format::fbx::import::Options {})),
|
||||
FileImportFormat::Sldprt => Ok(InputFormat::Sldprt(kcmc::format::sldprt::import::Options {
|
||||
split_closed_faces: false,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_extension_format(ext: InputFormat, given: InputFormat) -> Result<()> {
|
||||
if let InputFormat::Stl(_) = ext {
|
||||
if let InputFormat::Stl(_) = given {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if let InputFormat::Obj(_) = ext {
|
||||
if let InputFormat::Obj(_) = given {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if let InputFormat::Ply(_) = ext {
|
||||
if let InputFormat::Ply(_) = given {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if ext == given {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"The given format does not match the file extension. Expected: `{}`, Given: `{}`",
|
||||
get_name_of_format(ext),
|
||||
get_name_of_format(given)
|
||||
)
|
||||
}
|
||||
|
||||
fn get_name_of_format(type_: InputFormat) -> &'static str {
|
||||
match type_ {
|
||||
InputFormat::Fbx(_) => "fbx",
|
||||
InputFormat::Gltf(_) => "gltf",
|
||||
InputFormat::Obj(_) => "obj",
|
||||
InputFormat::Ply(_) => "ply",
|
||||
InputFormat::Sldprt(_) => "sldprt",
|
||||
InputFormat::Step(_) => "step",
|
||||
InputFormat::Stl(_) => "stl",
|
||||
}
|
||||
}
|
@ -23,6 +23,7 @@ type Point2D = kcmc::shared::Point2d<f64>;
|
||||
type Point3D = kcmc::shared::Point3d<f64>;
|
||||
|
||||
pub use function_param::FunctionParam;
|
||||
pub(crate) use import::{import_foreign, send_to_engine as send_import_to_engine, ZOO_COORD_SYSTEM};
|
||||
pub use kcl_value::{KclObjectFields, KclValue, UnitAngle, UnitLen};
|
||||
use uuid::Uuid;
|
||||
|
||||
@ -32,6 +33,7 @@ pub(crate) mod cache;
|
||||
mod cad_op;
|
||||
mod exec_ast;
|
||||
mod function_param;
|
||||
mod import;
|
||||
mod kcl_value;
|
||||
|
||||
use crate::{
|
||||
@ -40,7 +42,7 @@ use crate::{
|
||||
execution::cache::{CacheInformation, CacheResult},
|
||||
fs::{FileManager, FileSystem},
|
||||
parsing::ast::types::{
|
||||
BodyItem, Expr, FunctionExpression, ImportSelector, ItemVisibility, Node, NodeRef, NonCodeValue,
|
||||
BodyItem, Expr, FunctionExpression, ImportPath, ImportSelector, ItemVisibility, Node, NodeRef, NonCodeValue,
|
||||
Program as AstProgram, TagDeclarator, TagNode,
|
||||
},
|
||||
settings::types::UnitLength,
|
||||
@ -129,7 +131,7 @@ pub struct ExecOutcome {
|
||||
impl ExecState {
|
||||
pub fn new(exec_settings: &ExecutorSettings) -> Self {
|
||||
ExecState {
|
||||
global: GlobalState::new(),
|
||||
global: GlobalState::new(exec_settings),
|
||||
mod_local: ModuleState::new(exec_settings),
|
||||
}
|
||||
}
|
||||
@ -140,7 +142,7 @@ impl ExecState {
|
||||
// This is for the front end to keep track of the ids.
|
||||
id_generator.next_id = 0;
|
||||
|
||||
let mut global = GlobalState::new();
|
||||
let mut global = GlobalState::new(exec_settings);
|
||||
global.id_generator = id_generator;
|
||||
|
||||
*self = ExecState {
|
||||
@ -181,34 +183,15 @@ impl ExecState {
|
||||
self.global.artifacts.insert(id, artifact);
|
||||
}
|
||||
|
||||
async fn add_module(
|
||||
&mut self,
|
||||
path: std::path::PathBuf,
|
||||
ctxt: &ExecutorContext,
|
||||
source_range: SourceRange,
|
||||
) -> Result<ModuleId, KclError> {
|
||||
// Need to avoid borrowing self in the closure.
|
||||
let new_module_id = ModuleId::from_usize(self.global.path_to_source_id.len());
|
||||
let mut is_new = false;
|
||||
let id = *self.global.path_to_source_id.entry(path.clone()).or_insert_with(|| {
|
||||
is_new = true;
|
||||
new_module_id
|
||||
});
|
||||
fn add_module(&mut self, id: ModuleId, path: std::path::PathBuf, repr: ModuleRepr) -> ModuleId {
|
||||
debug_assert!(!self.global.path_to_source_id.contains_key(&path));
|
||||
|
||||
if is_new {
|
||||
let source = ctxt.fs.read_to_string(&path, source_range).await?;
|
||||
// TODO handle parsing errors properly
|
||||
let parsed = crate::parsing::parse_str(&source, id).parse_errs_as_err()?;
|
||||
self.global.path_to_source_id.insert(path.clone(), id);
|
||||
|
||||
let module_info = ModuleInfo {
|
||||
id,
|
||||
path,
|
||||
parsed: Some(parsed),
|
||||
};
|
||||
let module_info = ModuleInfo { id, repr, path };
|
||||
self.global.module_infos.insert(id, module_info);
|
||||
}
|
||||
|
||||
Ok(id)
|
||||
id
|
||||
}
|
||||
|
||||
pub fn length_unit(&self) -> UnitLen {
|
||||
@ -221,7 +204,7 @@ impl ExecState {
|
||||
}
|
||||
|
||||
impl GlobalState {
|
||||
fn new() -> Self {
|
||||
fn new(settings: &ExecutorSettings) -> Self {
|
||||
let mut global = GlobalState {
|
||||
id_generator: Default::default(),
|
||||
path_to_source_id: Default::default(),
|
||||
@ -232,15 +215,14 @@ impl GlobalState {
|
||||
artifact_graph: Default::default(),
|
||||
};
|
||||
|
||||
// TODO(#4434): Use the top-level file's path.
|
||||
let root_path = PathBuf::new();
|
||||
let root_id = ModuleId::default();
|
||||
let root_path = settings.current_file.clone().unwrap_or_default();
|
||||
global.module_infos.insert(
|
||||
root_id,
|
||||
ModuleInfo {
|
||||
id: root_id,
|
||||
path: root_path.clone(),
|
||||
parsed: None,
|
||||
repr: ModuleRepr::Root,
|
||||
},
|
||||
);
|
||||
global.path_to_source_id.insert(root_path, root_id);
|
||||
@ -1253,7 +1235,15 @@ pub struct ModuleInfo {
|
||||
id: ModuleId,
|
||||
/// Absolute path of the module's source file.
|
||||
path: std::path::PathBuf,
|
||||
parsed: Option<Node<AstProgram>>,
|
||||
repr: ModuleRepr,
|
||||
}
|
||||
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
pub enum ModuleRepr {
|
||||
Root,
|
||||
Kcl(Node<AstProgram>),
|
||||
Foreign(import::PreImportedGeometry),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, ts_rs::TS, JsonSchema)]
|
||||
@ -1761,6 +1751,9 @@ pub struct ExecutorSettings {
|
||||
/// The directory of the current project. This is used for resolving import
|
||||
/// paths. If None is given, the current working directory is used.
|
||||
pub project_directory: Option<PathBuf>,
|
||||
/// This is the path to the current file being executed.
|
||||
/// We use this for preventing cyclic imports.
|
||||
pub current_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for ExecutorSettings {
|
||||
@ -1772,6 +1765,7 @@ impl Default for ExecutorSettings {
|
||||
show_grid: false,
|
||||
replay: None,
|
||||
project_directory: None,
|
||||
current_file: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1785,6 +1779,7 @@ impl From<crate::settings::types::Configuration> for ExecutorSettings {
|
||||
show_grid: config.settings.modeling.show_scale_grid,
|
||||
replay: None,
|
||||
project_directory: None,
|
||||
current_file: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1798,6 +1793,7 @@ impl From<crate::settings::types::project::ProjectConfiguration> for ExecutorSet
|
||||
show_grid: config.settings.modeling.show_scale_grid,
|
||||
replay: None,
|
||||
project_directory: None,
|
||||
current_file: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1811,6 +1807,25 @@ impl From<crate::settings::types::ModelingSettings> for ExecutorSettings {
|
||||
show_grid: modeling.show_scale_grid,
|
||||
replay: None,
|
||||
project_directory: None,
|
||||
current_file: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExecutorSettings {
|
||||
/// Add the current file path to the executor settings.
|
||||
pub fn with_current_file(&mut self, current_file: PathBuf) {
|
||||
// We want the parent directory of the file.
|
||||
if current_file.extension() == Some(std::ffi::OsStr::new("kcl")) {
|
||||
self.current_file = Some(current_file.clone());
|
||||
// Get the parent directory.
|
||||
if let Some(parent) = current_file.parent() {
|
||||
self.project_directory = Some(parent.to_path_buf());
|
||||
} else {
|
||||
self.project_directory = Some(std::path::PathBuf::from(""));
|
||||
}
|
||||
} else {
|
||||
self.project_directory = Some(current_file.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2028,6 +2043,7 @@ impl ExecutorContext {
|
||||
show_grid: false,
|
||||
replay: None,
|
||||
project_directory: None,
|
||||
current_file: None,
|
||||
},
|
||||
None,
|
||||
engine_addr,
|
||||
@ -2511,14 +2527,16 @@ impl ExecutorContext {
|
||||
|
||||
async fn open_module(
|
||||
&self,
|
||||
path: &str,
|
||||
path: &ImportPath,
|
||||
exec_state: &mut ExecState,
|
||||
source_range: SourceRange,
|
||||
) -> Result<ModuleId, KclError> {
|
||||
match path {
|
||||
ImportPath::Kcl { filename } => {
|
||||
let resolved_path = if let Some(project_dir) = &self.settings.project_directory {
|
||||
project_dir.join(path)
|
||||
project_dir.join(filename)
|
||||
} else {
|
||||
std::path::PathBuf::from(&path)
|
||||
std::path::PathBuf::from(filename)
|
||||
};
|
||||
|
||||
if exec_state.mod_local.import_stack.contains(&resolved_path) {
|
||||
@ -2537,7 +2555,40 @@ impl ExecutorContext {
|
||||
source_ranges: vec![source_range],
|
||||
}));
|
||||
}
|
||||
exec_state.add_module(resolved_path.clone(), self, source_range).await
|
||||
|
||||
if let Some(id) = exec_state.global.path_to_source_id.get(&resolved_path) {
|
||||
return Ok(*id);
|
||||
}
|
||||
|
||||
let source = self.fs.read_to_string(&resolved_path, source_range).await?;
|
||||
let id = ModuleId::from_usize(exec_state.global.path_to_source_id.len());
|
||||
// TODO handle parsing errors properly
|
||||
let parsed = crate::parsing::parse_str(&source, id).parse_errs_as_err()?;
|
||||
let repr = ModuleRepr::Kcl(parsed);
|
||||
|
||||
Ok(exec_state.add_module(id, resolved_path, repr))
|
||||
}
|
||||
ImportPath::Foreign { path } => {
|
||||
let resolved_path = if let Some(project_dir) = &self.settings.project_directory {
|
||||
project_dir.join(path)
|
||||
} else {
|
||||
std::path::PathBuf::from(path)
|
||||
};
|
||||
|
||||
if let Some(id) = exec_state.global.path_to_source_id.get(&resolved_path) {
|
||||
return Ok(*id);
|
||||
}
|
||||
|
||||
let geom = import::import_foreign(&resolved_path, None, exec_state, self, source_range).await?;
|
||||
let repr = ModuleRepr::Foreign(geom);
|
||||
let id = ModuleId::from_usize(exec_state.global.path_to_source_id.len());
|
||||
Ok(exec_state.add_module(id, resolved_path, repr))
|
||||
}
|
||||
i => Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!("Unsupported import: `{i}`"),
|
||||
source_ranges: vec![source_range],
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async fn exec_module(
|
||||
@ -2551,6 +2602,22 @@ impl ExecutorContext {
|
||||
// TODO It sucks that we have to clone the whole module AST here
|
||||
let info = exec_state.global.module_infos[&module_id].clone();
|
||||
|
||||
match &info.repr {
|
||||
ModuleRepr::Root => Err(KclError::ImportCycle(KclErrorDetails {
|
||||
message: format!(
|
||||
"circular import of modules is not allowed: {} -> {}",
|
||||
exec_state
|
||||
.mod_local
|
||||
.import_stack
|
||||
.iter()
|
||||
.map(|p| p.as_path().to_string_lossy())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" -> "),
|
||||
info.path.display()
|
||||
),
|
||||
source_ranges: vec![source_range],
|
||||
})),
|
||||
ModuleRepr::Kcl(program) => {
|
||||
let mut local_state = ModuleState {
|
||||
import_stack: exec_state.mod_local.import_stack.clone(),
|
||||
..ModuleState::new(&self.settings)
|
||||
@ -2559,9 +2626,8 @@ impl ExecutorContext {
|
||||
std::mem::swap(&mut exec_state.mod_local, &mut local_state);
|
||||
let original_execution = self.engine.replace_execution_kind(exec_kind);
|
||||
|
||||
// The unwrap here is safe since we only elide the AST for the top module.
|
||||
let result = self
|
||||
.inner_execute(&info.parsed.unwrap(), exec_state, crate::execution::BodyType::Root)
|
||||
.inner_execute(program, exec_state, crate::execution::BodyType::Root)
|
||||
.await;
|
||||
|
||||
let new_units = exec_state.length_unit();
|
||||
@ -2589,6 +2655,12 @@ impl ExecutorContext {
|
||||
|
||||
Ok((result, local_state.memory, local_state.module_exports))
|
||||
}
|
||||
ModuleRepr::Foreign(geom) => {
|
||||
let geom = send_import_to_engine(geom.clone(), self).await?;
|
||||
Ok((Some(KclValue::ImportedGeometry(geom)), ProgramMemory::new(), Vec::new()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_recursion]
|
||||
pub async fn execute_expr<'a: 'async_recursion>(
|
||||
@ -2608,15 +2680,20 @@ impl ExecutorContext {
|
||||
let (result, _, _) = self
|
||||
.exec_module(module_id, exec_state, ExecutionKind::Normal, metadata.source_range)
|
||||
.await?;
|
||||
result.ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"Evaluating module `{}` as part of an assembly did not produce a result",
|
||||
identifier.name
|
||||
),
|
||||
source_ranges: vec![metadata.source_range, meta[0].source_range],
|
||||
result.unwrap_or_else(|| {
|
||||
// The module didn't have a return value. Currently,
|
||||
// the only way to have a return value is with the final
|
||||
// statement being an expression statement.
|
||||
//
|
||||
// TODO: Make a warning when we support them in the
|
||||
// execution phase.
|
||||
let mut new_meta = vec![metadata.to_owned()];
|
||||
new_meta.extend(meta);
|
||||
KclValue::KclNone {
|
||||
value: Default::default(),
|
||||
meta: new_meta,
|
||||
}
|
||||
})
|
||||
})?
|
||||
} else {
|
||||
value
|
||||
}
|
||||
@ -3421,6 +3498,16 @@ const inInches = 1.0 * inch()"#;
|
||||
assert_eq!(1.0, mem_get_json(exec_state.memory(), "inInches").as_f64().unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_unit_overriden_in() {
|
||||
let ast = r#"@settings(defaultLengthUnit = in)
|
||||
const inMm = 25.4 * mm()
|
||||
const inInches = 2.0 * inch()"#;
|
||||
let (_, _, exec_state) = parse_execute(ast).await.unwrap();
|
||||
assert_eq!(1.0, mem_get_json(exec_state.memory(), "inMm").as_f64().unwrap().round());
|
||||
assert_eq!(2.0, mem_get_json(exec_state.memory(), "inInches").as_f64().unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn test_zero_param_fn() {
|
||||
let ast = r#"const sigmaAllow = 35000 // psi
|
||||
|
@ -75,7 +75,7 @@ pub mod std;
|
||||
pub mod test_server;
|
||||
mod thread;
|
||||
mod unparser;
|
||||
mod walk;
|
||||
pub mod walk;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod wasm;
|
||||
|
||||
|
@ -66,7 +66,8 @@ impl ImportStatement {
|
||||
}
|
||||
}
|
||||
hasher.update(slf.visibility.digestable_id());
|
||||
let path = slf.path.as_bytes();
|
||||
let path = slf.path.to_string();
|
||||
let path = path.as_bytes();
|
||||
hasher.update(path.len().to_ne_bytes());
|
||||
hasher.update(path);
|
||||
});
|
||||
|
@ -1256,6 +1256,32 @@ impl ImportSelector {
|
||||
ImportSelector::None { alias: Some(alias) } => alias.rename(old_name, new_name),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn exposes_imported_name(&self) -> bool {
|
||||
matches!(self, ImportSelector::None { alias: None })
|
||||
}
|
||||
|
||||
pub fn imports_items(&self) -> bool {
|
||||
!matches!(self, ImportSelector::None { .. })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Eq, PartialEq, Debug, Deserialize, Serialize, ts_rs::TS, JsonSchema)]
|
||||
#[ts(export)]
|
||||
#[serde(tag = "type")]
|
||||
pub enum ImportPath {
|
||||
Kcl { filename: String },
|
||||
Foreign { path: String },
|
||||
Std,
|
||||
}
|
||||
|
||||
impl fmt::Display for ImportPath {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
ImportPath::Kcl { filename: s } | ImportPath::Foreign { path: s } => write!(f, "{s}"),
|
||||
ImportPath::Std => write!(f, "std"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema)]
|
||||
@ -1263,7 +1289,7 @@ impl ImportSelector {
|
||||
#[serde(tag = "type")]
|
||||
pub struct ImportStatement {
|
||||
pub selector: ImportSelector,
|
||||
pub path: String,
|
||||
pub path: ImportPath,
|
||||
#[serde(default, skip_serializing_if = "ItemVisibility::is_default")]
|
||||
pub visibility: ItemVisibility,
|
||||
|
||||
@ -1312,12 +1338,15 @@ impl ImportStatement {
|
||||
return Some(alias.name.clone());
|
||||
}
|
||||
|
||||
let mut parts = self.path.split('.');
|
||||
let mut parts = match &self.path {
|
||||
ImportPath::Kcl { filename: s } | ImportPath::Foreign { path: s } => s.split('.'),
|
||||
_ => return None,
|
||||
};
|
||||
let name = parts.next()?;
|
||||
let ext = parts.next()?;
|
||||
let _ext = parts.next()?;
|
||||
let rest = parts.next();
|
||||
|
||||
if rest.is_some() || ext != "kcl" {
|
||||
if rest.is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
|
@ -12,7 +12,10 @@ use winnow::{
|
||||
token::{any, one_of, take_till},
|
||||
};
|
||||
|
||||
use super::{ast::types::LabelledExpression, token::NumericSuffix};
|
||||
use super::{
|
||||
ast::types::{ImportPath, LabelledExpression},
|
||||
token::NumericSuffix,
|
||||
};
|
||||
use crate::{
|
||||
docs::StdLibFn,
|
||||
errors::{CompilationError, Severity, Tag},
|
||||
@ -1545,33 +1548,11 @@ fn import_stmt(i: &mut TokenSlice) -> PResult<BoxNode<ImportStatement>> {
|
||||
};
|
||||
|
||||
let mut end: usize = path.end;
|
||||
let path_string = match path.inner.value {
|
||||
LiteralValue::String(s) => s,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if path_string.is_empty() {
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(
|
||||
SourceRange::new(path.start, path.end, path.module_id),
|
||||
"import path cannot be empty",
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if path_string
|
||||
.chars()
|
||||
.any(|c| !c.is_ascii_alphanumeric() && c != '_' && c != '-' && c != '.')
|
||||
{
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(
|
||||
SourceRange::new(path.start, path.end, path.module_id),
|
||||
"import path may only contain alphanumeric characters, underscore, hyphen, and period. Files in other directories are not yet supported.",
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
if let ImportSelector::None { alias: ref mut a } = selector {
|
||||
if let ImportSelector::None {
|
||||
alias: ref mut selector_alias,
|
||||
} = selector
|
||||
{
|
||||
if let Some(alias) = opt(preceded(
|
||||
(whitespace, import_as_keyword, whitespace),
|
||||
identifier.context(expected("an identifier to alias the import")),
|
||||
@ -1579,35 +1560,40 @@ fn import_stmt(i: &mut TokenSlice) -> PResult<BoxNode<ImportStatement>> {
|
||||
.parse_next(i)?
|
||||
{
|
||||
end = alias.end;
|
||||
*a = Some(alias);
|
||||
*selector_alias = Some(alias);
|
||||
}
|
||||
|
||||
ParseContext::warn(CompilationError::err(
|
||||
SourceRange::new(start, path.end, path.module_id),
|
||||
"Importing a whole module is experimental, likely to be buggy, and likely to change",
|
||||
));
|
||||
}
|
||||
|
||||
if a.is_none()
|
||||
&& (!path_string.ends_with(".kcl")
|
||||
|| path_string.starts_with("_")
|
||||
|| path_string.contains('-')
|
||||
|| path_string[0..path_string.len() - 4].contains('.'))
|
||||
{
|
||||
let path_string = match path.inner.value {
|
||||
LiteralValue::String(s) => s,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let path = validate_path_string(
|
||||
path_string,
|
||||
selector.exposes_imported_name(),
|
||||
SourceRange::new(path.start, path.end, path.module_id),
|
||||
)?;
|
||||
|
||||
if matches!(path, ImportPath::Foreign { .. }) && selector.imports_items() {
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(
|
||||
SourceRange::new(path.start, path.end, path.module_id),
|
||||
"import path is not a valid identifier and must be aliased.".to_owned(),
|
||||
SourceRange::new(start, end, module_id),
|
||||
"individual items can only be imported from KCL files",
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Node::boxed(
|
||||
ImportStatement {
|
||||
selector,
|
||||
visibility,
|
||||
path: path_string,
|
||||
path,
|
||||
digest: None,
|
||||
},
|
||||
start,
|
||||
@ -1616,6 +1602,72 @@ fn import_stmt(i: &mut TokenSlice) -> PResult<BoxNode<ImportStatement>> {
|
||||
))
|
||||
}
|
||||
|
||||
const FOREIGN_IMPORT_EXTENSIONS: [&str; 8] = ["fbx", "gltf", "glb", "obj", "ply", "sldprt", "step", "stl"];
|
||||
|
||||
/// Validates the path string in an `import` statement.
|
||||
///
|
||||
/// `var_name` is `true` if the path will be used as a variable name.
|
||||
fn validate_path_string(path_string: String, var_name: bool, path_range: SourceRange) -> PResult<ImportPath> {
|
||||
if path_string.is_empty() {
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(path_range, "import path cannot be empty").into(),
|
||||
));
|
||||
}
|
||||
|
||||
if var_name
|
||||
&& (path_string.starts_with("_")
|
||||
|| path_string.contains('-')
|
||||
|| path_string.chars().filter(|c| *c == '.').count() > 1)
|
||||
{
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(path_range, "import path is not a valid identifier and must be aliased.").into(),
|
||||
));
|
||||
}
|
||||
|
||||
let path = if path_string.ends_with(".kcl") {
|
||||
if path_string
|
||||
.chars()
|
||||
.any(|c| !c.is_ascii_alphanumeric() && c != '_' && c != '-' && c != '.')
|
||||
{
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(
|
||||
path_range,
|
||||
"import path may only contain alphanumeric characters, underscore, hyphen, and period. KCL files in other directories are not yet supported.",
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
ImportPath::Kcl { filename: path_string }
|
||||
} else if path_string.starts_with("std") {
|
||||
ParseContext::warn(CompilationError::err(
|
||||
path_range,
|
||||
"explicit imports from the standard library are experimental, likely to be buggy, and likely to change.",
|
||||
));
|
||||
|
||||
ImportPath::Std
|
||||
} else if path_string.contains('.') {
|
||||
let extn = &path_string[path_string.rfind('.').unwrap() + 1..];
|
||||
if !FOREIGN_IMPORT_EXTENSIONS.contains(&extn) {
|
||||
ParseContext::warn(CompilationError::err(
|
||||
path_range,
|
||||
format!("unsupported import path format. KCL files can be imported from the current project, CAD files with the following formats are supported: {}", FOREIGN_IMPORT_EXTENSIONS.join(", ")),
|
||||
))
|
||||
}
|
||||
ImportPath::Foreign { path: path_string }
|
||||
} else {
|
||||
return Err(ErrMode::Cut(
|
||||
CompilationError::fatal(
|
||||
path_range,
|
||||
format!("unsupported import path format. KCL files can be imported from the current project, CAD files with the following formats are supported: {}", FOREIGN_IMPORT_EXTENSIONS.join(", ")),
|
||||
)
|
||||
.into(),
|
||||
));
|
||||
};
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
fn import_item(i: &mut TokenSlice) -> PResult<Node<ImportItem>> {
|
||||
let name = nameable_identifier
|
||||
.context(expected("an identifier to import"))
|
||||
@ -3611,7 +3663,11 @@ mySk1 = startSketchAt([0, 0])"#;
|
||||
fn assert_err(p: &str, msg: &str, src_expected: [usize; 2]) {
|
||||
let result = crate::parsing::top_level_parse(p);
|
||||
let err = result.unwrap_errs().next().unwrap();
|
||||
assert_eq!(err.message, msg);
|
||||
assert!(
|
||||
err.message.starts_with(msg),
|
||||
"Found `{}`, expected `{msg}`",
|
||||
err.message
|
||||
);
|
||||
let src_actual = [err.source_range.start(), err.source_range.end()];
|
||||
assert_eq!(
|
||||
src_expected,
|
||||
@ -3977,7 +4033,7 @@ e
|
||||
fn bad_imports() {
|
||||
assert_err(
|
||||
r#"import cube from "../cube.kcl""#,
|
||||
"import path may only contain alphanumeric characters, underscore, hyphen, and period. Files in other directories are not yet supported.",
|
||||
"import path may only contain alphanumeric characters, underscore, hyphen, and period. KCL files in other directories are not yet supported.",
|
||||
[17, 30],
|
||||
);
|
||||
assert_err(
|
||||
@ -3985,17 +4041,21 @@ e
|
||||
"as is not the 'from' keyword",
|
||||
[9, 11],
|
||||
);
|
||||
assert_err(r#"import a from "dsfs" as b"#, "Unexpected token: as", [21, 23]);
|
||||
assert_err(r#"import * from "dsfs" as b"#, "Unexpected token: as", [21, 23]);
|
||||
assert_err(
|
||||
r#"import a from "dsfs" as b"#,
|
||||
"unsupported import path format",
|
||||
[14, 20],
|
||||
);
|
||||
assert_err(
|
||||
r#"import * from "dsfs" as b"#,
|
||||
"unsupported import path format",
|
||||
[14, 20],
|
||||
);
|
||||
assert_err(r#"import a from b"#, "invalid string literal", [14, 15]);
|
||||
assert_err(r#"import * "dsfs""#, "\"dsfs\" is not the 'from' keyword", [9, 15]);
|
||||
assert_err(r#"import from "dsfs""#, "\"dsfs\" is not the 'from' keyword", [12, 18]);
|
||||
assert_err(r#"import "dsfs.kcl" as *"#, "Unexpected token: as", [18, 20]);
|
||||
assert_err(
|
||||
r#"import "dsfs""#,
|
||||
"import path is not a valid identifier and must be aliased.",
|
||||
[7, 13],
|
||||
);
|
||||
assert_err(r#"import "dsfs""#, "unsupported import path format", [7, 13]);
|
||||
assert_err(
|
||||
r#"import "foo.bar.kcl""#,
|
||||
"import path is not a valid identifier and must be aliased.",
|
||||
@ -4017,7 +4077,19 @@ e
|
||||
fn warn_import() {
|
||||
let some_program_string = r#"import "foo.kcl""#;
|
||||
let (_, errs) = assert_no_err(some_program_string);
|
||||
assert_eq!(errs.len(), 1);
|
||||
assert_eq!(errs.len(), 1, "{errs:#?}");
|
||||
|
||||
let some_program_string = r#"import "foo.obj""#;
|
||||
let (_, errs) = assert_no_err(some_program_string);
|
||||
assert_eq!(errs.len(), 1, "{errs:#?}");
|
||||
|
||||
let some_program_string = r#"import "foo.sldprt""#;
|
||||
let (_, errs) = assert_no_err(some_program_string);
|
||||
assert_eq!(errs.len(), 1, "{errs:#?}");
|
||||
|
||||
let some_program_string = r#"import "foo.bad""#;
|
||||
let (_, errs) = assert_no_err(some_program_string);
|
||||
assert_eq!(errs.len(), 2, "{errs:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -62,14 +62,14 @@ impl FromStr for NumericSuffix {
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"_" => Ok(NumericSuffix::Count),
|
||||
"mm" => Ok(NumericSuffix::Mm),
|
||||
"cm" => Ok(NumericSuffix::Cm),
|
||||
"m" => Ok(NumericSuffix::M),
|
||||
"mm" | "millimeters" => Ok(NumericSuffix::Mm),
|
||||
"cm" | "centimeters" => Ok(NumericSuffix::Cm),
|
||||
"m" | "meters" => Ok(NumericSuffix::M),
|
||||
"inch" | "in" => Ok(NumericSuffix::Inch),
|
||||
"ft" => Ok(NumericSuffix::Ft),
|
||||
"yd" => Ok(NumericSuffix::Yd),
|
||||
"deg" => Ok(NumericSuffix::Deg),
|
||||
"rad" => Ok(NumericSuffix::Rad),
|
||||
"ft" | "feet" => Ok(NumericSuffix::Ft),
|
||||
"yd" | "yards" => Ok(NumericSuffix::Yd),
|
||||
"deg" | "degrees" => Ok(NumericSuffix::Deg),
|
||||
"rad" | "radians" => Ok(NumericSuffix::Rad),
|
||||
_ => Err(CompilationError::err(SourceRange::default(), "invalid unit of measure")),
|
||||
}
|
||||
}
|
||||
|
@ -87,7 +87,7 @@ async fn execute(test_name: &str, render_to_png: bool) {
|
||||
let exec_res = crate::test_server::execute_and_snapshot_ast(
|
||||
ast.into(),
|
||||
crate::settings::types::UnitLength::Mm,
|
||||
Some(Path::new("tests").join(test_name)),
|
||||
Some(Path::new("tests").join(test_name).join("input.kcl").to_owned()),
|
||||
)
|
||||
.await;
|
||||
match exec_res {
|
||||
@ -872,6 +872,27 @@ mod import_side_effect {
|
||||
super::execute(TEST_NAME, false).await
|
||||
}
|
||||
}
|
||||
mod import_foreign {
|
||||
const TEST_NAME: &str = "import_foreign";
|
||||
|
||||
/// Test parsing KCL.
|
||||
#[test]
|
||||
fn parse() {
|
||||
super::parse(TEST_NAME)
|
||||
}
|
||||
|
||||
/// Test that parsing and unparsing KCL produces the original KCL input.
|
||||
#[test]
|
||||
fn unparse() {
|
||||
super::unparse(TEST_NAME)
|
||||
}
|
||||
|
||||
/// Test that KCL is executed correctly.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn kcl_test_execute() {
|
||||
super::execute(TEST_NAME, false).await
|
||||
}
|
||||
}
|
||||
mod array_elem_push_fail {
|
||||
const TEST_NAME: &str = "array_elem_push_fail";
|
||||
|
||||
|
@ -143,10 +143,8 @@ async fn inner_chamfer(
|
||||
radius: LengthUnit(data.length),
|
||||
tolerance: LengthUnit(DEFAULT_TOLERANCE), // We can let the user set this in the future.
|
||||
cut_type: CutType::Chamfer,
|
||||
// We pass in the command id as the face id.
|
||||
// So the resulting face of the fillet will be the same.
|
||||
// This is because that's how most other endpoints work.
|
||||
face_id: Some(id),
|
||||
// We make this a none so that we can remove it in the future.
|
||||
face_id: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
@ -152,10 +152,8 @@ async fn inner_fillet(
|
||||
radius: LengthUnit(data.radius),
|
||||
tolerance: LengthUnit(data.tolerance.unwrap_or(default_tolerance(&args.ctx.settings.units))),
|
||||
cut_type: CutType::Fillet,
|
||||
// We pass in the command id as the face id.
|
||||
// So the resulting face of the fillet will be the same.
|
||||
// This is because that's how most other endpoints work.
|
||||
face_id: Some(id),
|
||||
// We make this a none so that we can remove it in the future.
|
||||
face_id: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
@ -140,7 +140,7 @@ async fn inner_helix(data: HelixData, exec_state: &mut ExecState, args: Args) ->
|
||||
args.batch_modeling_cmd(
|
||||
id,
|
||||
ModelingCmd::from(mcmd::EntityMakeHelixFromParams {
|
||||
radius: data.radius,
|
||||
radius: LengthUnit(data.radius),
|
||||
is_clockwise: !data.ccw,
|
||||
length: LengthUnit(length),
|
||||
revolutions: data.revolutions,
|
||||
@ -157,7 +157,7 @@ async fn inner_helix(data: HelixData, exec_state: &mut ExecState, args: Args) ->
|
||||
args.batch_modeling_cmd(
|
||||
id,
|
||||
ModelingCmd::from(mcmd::EntityMakeHelixFromEdge {
|
||||
radius: data.radius,
|
||||
radius: LengthUnit(data.radius),
|
||||
is_clockwise: !data.ccw,
|
||||
length: data.length.map(LengthUnit),
|
||||
revolutions: data.revolutions,
|
||||
|
@ -1,44 +1,16 @@
|
||||
//! Standard library functions involved in importing files.
|
||||
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::Result;
|
||||
use derive_docs::stdlib;
|
||||
use kcmc::{
|
||||
coord::{Axis, AxisDirectionPair, Direction, System},
|
||||
each_cmd as mcmd,
|
||||
format::InputFormat,
|
||||
ok_response::OkModelingCmdResponse,
|
||||
shared::FileImportFormat,
|
||||
units::UnitLength,
|
||||
websocket::OkWebSocketResponseData,
|
||||
ImportFile, ModelingCmd,
|
||||
};
|
||||
use kcmc::{coord::System, format::InputFormat, units::UnitLength};
|
||||
use kittycad_modeling_cmds as kcmc;
|
||||
|
||||
use crate::{
|
||||
errors::{KclError, KclErrorDetails},
|
||||
execution::{ExecState, ImportedGeometry, KclValue},
|
||||
fs::FileSystem,
|
||||
execution::{import_foreign, send_import_to_engine, ExecState, ImportedGeometry, KclValue, ZOO_COORD_SYSTEM},
|
||||
std::Args,
|
||||
};
|
||||
|
||||
// Zoo co-ordinate system.
|
||||
//
|
||||
// * Forward: -Y
|
||||
// * Up: +Z
|
||||
// * Handedness: Right
|
||||
const ZOO_COORD_SYSTEM: System = System {
|
||||
forward: AxisDirectionPair {
|
||||
axis: Axis::Y,
|
||||
direction: Direction::Negative,
|
||||
},
|
||||
up: AxisDirectionPair {
|
||||
axis: Axis::Z,
|
||||
direction: Direction::Positive,
|
||||
},
|
||||
};
|
||||
|
||||
/// Import format specifier
|
||||
#[derive(serde :: Serialize, serde :: Deserialize, PartialEq, Debug, Clone, schemars :: JsonSchema)]
|
||||
#[cfg_attr(feature = "tabled", derive(tabled::Tabled))]
|
||||
@ -135,6 +107,8 @@ pub async fn import(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
|
||||
|
||||
/// Import a CAD file.
|
||||
///
|
||||
/// **DEPRECATED** Prefer to use import statements.
|
||||
///
|
||||
/// For formats lacking unit data (such as STL, OBJ, or PLY files), the default
|
||||
/// unit of measurement is millimeters. Alternatively you may specify the unit
|
||||
/// by passing your desired measurement unit in the options parameter. When
|
||||
@ -178,6 +152,7 @@ pub async fn import(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
|
||||
#[stdlib {
|
||||
name = "import",
|
||||
feature_tree_operation = true,
|
||||
deprecated = true,
|
||||
tags = [],
|
||||
}]
|
||||
async fn inner_import(
|
||||
@ -193,232 +168,17 @@ async fn inner_import(
|
||||
}));
|
||||
}
|
||||
|
||||
// Make sure the file exists.
|
||||
if !args.ctx.fs.exists(&file_path, args.source_range).await? {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!("File `{}` does not exist.", file_path),
|
||||
source_ranges: vec![args.source_range],
|
||||
}));
|
||||
}
|
||||
|
||||
let ext_format = get_import_format_from_extension(file_path.split('.').last().ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!("No file extension found for `{}`", file_path),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?)
|
||||
.map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Get the format type from the extension of the file.
|
||||
let format = if let Some(options) = options {
|
||||
// Validate the given format with the extension format.
|
||||
let format: InputFormat = options.into();
|
||||
validate_extension_format(ext_format, format.clone()).map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
format
|
||||
} else {
|
||||
ext_format
|
||||
};
|
||||
|
||||
// Get the file contents for each file path.
|
||||
let file_contents = args.ctx.fs.read(&file_path, args.source_range).await.map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// We want the file_path to be without the parent.
|
||||
let file_name = std::path::Path::new(&file_path)
|
||||
.file_name()
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!("Could not get the file name from the path `{}`", file_path),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
let mut import_files = vec![kcmc::ImportFile {
|
||||
path: file_name.to_string(),
|
||||
data: file_contents.clone(),
|
||||
}];
|
||||
|
||||
// In the case of a gltf importing a bin file we need to handle that! and figure out where the
|
||||
// file is relative to our current file.
|
||||
if let InputFormat::Gltf(..) = format {
|
||||
// Check if the file is a binary gltf file, in that case we don't need to import the bin
|
||||
// file.
|
||||
if !file_contents.starts_with(b"glTF") {
|
||||
let json = gltf_json::Root::from_slice(&file_contents).map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
// Read the gltf file and check if there is a bin file.
|
||||
for buffer in json.buffers.iter() {
|
||||
if let Some(uri) = &buffer.uri {
|
||||
if !uri.starts_with("data:") {
|
||||
// We want this path relative to the file_path given.
|
||||
let bin_path = std::path::Path::new(&file_path)
|
||||
.parent()
|
||||
.map(|p| p.join(uri))
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
.ok_or_else(|| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: format!("Could not get the parent path of the file `{}`", file_path),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
let bin_contents = args.ctx.fs.read(&bin_path, args.source_range).await.map_err(|e| {
|
||||
KclError::Semantic(KclErrorDetails {
|
||||
message: e.to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?;
|
||||
|
||||
import_files.push(ImportFile {
|
||||
path: uri.to_string(),
|
||||
data: bin_contents,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if args.ctx.is_mock() {
|
||||
return Ok(ImportedGeometry {
|
||||
id: exec_state.next_uuid(),
|
||||
value: import_files.iter().map(|f| f.path.to_string()).collect(),
|
||||
meta: vec![args.source_range.into()],
|
||||
});
|
||||
}
|
||||
|
||||
let id = exec_state.next_uuid();
|
||||
let resp = args
|
||||
.send_modeling_cmd(
|
||||
id,
|
||||
ModelingCmd::from(mcmd::ImportFiles {
|
||||
files: import_files.clone(),
|
||||
let format = options.map(InputFormat::from);
|
||||
send_import_to_engine(
|
||||
import_foreign(
|
||||
std::path::Path::new(&file_path),
|
||||
format,
|
||||
}),
|
||||
exec_state,
|
||||
&args.ctx,
|
||||
args.source_range,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let OkWebSocketResponseData::Modeling {
|
||||
modeling_response: OkModelingCmdResponse::ImportFiles(imported_files),
|
||||
} = &resp
|
||||
else {
|
||||
return Err(KclError::Engine(KclErrorDetails {
|
||||
message: format!("ImportFiles response was not as expected: {:?}", resp),
|
||||
source_ranges: vec![args.source_range],
|
||||
}));
|
||||
};
|
||||
|
||||
Ok(ImportedGeometry {
|
||||
id: imported_files.object_id,
|
||||
value: import_files.iter().map(|f| f.path.to_string()).collect(),
|
||||
meta: vec![args.source_range.into()],
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the source format from the extension.
|
||||
fn get_import_format_from_extension(ext: &str) -> Result<InputFormat> {
|
||||
let format = match FileImportFormat::from_str(ext) {
|
||||
Ok(format) => format,
|
||||
Err(_) => {
|
||||
if ext == "stp" {
|
||||
FileImportFormat::Step
|
||||
} else if ext == "glb" {
|
||||
FileImportFormat::Gltf
|
||||
} else {
|
||||
anyhow::bail!("unknown source format for file extension: {}. Try setting the `--src-format` flag explicitly or use a valid format.", ext)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Make the default units millimeters.
|
||||
let ul = UnitLength::Millimeters;
|
||||
|
||||
// Zoo co-ordinate system.
|
||||
//
|
||||
// * Forward: -Y
|
||||
// * Up: +Z
|
||||
// * Handedness: Right
|
||||
match format {
|
||||
FileImportFormat::Step => Ok(InputFormat::Step(kcmc::format::step::import::Options {
|
||||
split_closed_faces: false,
|
||||
})),
|
||||
FileImportFormat::Stl => Ok(InputFormat::Stl(kcmc::format::stl::import::Options {
|
||||
coords: ZOO_COORD_SYSTEM,
|
||||
units: ul,
|
||||
})),
|
||||
FileImportFormat::Obj => Ok(InputFormat::Obj(kcmc::format::obj::import::Options {
|
||||
coords: ZOO_COORD_SYSTEM,
|
||||
units: ul,
|
||||
})),
|
||||
FileImportFormat::Gltf => Ok(InputFormat::Gltf(kcmc::format::gltf::import::Options {})),
|
||||
FileImportFormat::Ply => Ok(InputFormat::Ply(kcmc::format::ply::import::Options {
|
||||
coords: ZOO_COORD_SYSTEM,
|
||||
units: ul,
|
||||
})),
|
||||
FileImportFormat::Fbx => Ok(InputFormat::Fbx(kcmc::format::fbx::import::Options {})),
|
||||
FileImportFormat::Sldprt => Ok(InputFormat::Sldprt(kcmc::format::sldprt::import::Options {
|
||||
split_closed_faces: false,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_extension_format(ext: InputFormat, given: InputFormat) -> Result<()> {
|
||||
if let InputFormat::Stl(_) = ext {
|
||||
if let InputFormat::Stl(_) = given {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if let InputFormat::Obj(_) = ext {
|
||||
if let InputFormat::Obj(_) = given {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if let InputFormat::Ply(_) = ext {
|
||||
if let InputFormat::Ply(_) = given {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
if ext == given {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
anyhow::bail!(
|
||||
"The given format does not match the file extension. Expected: `{}`, Given: `{}`",
|
||||
get_name_of_format(ext),
|
||||
get_name_of_format(given)
|
||||
.await?,
|
||||
&args.ctx,
|
||||
)
|
||||
}
|
||||
|
||||
fn get_name_of_format(type_: InputFormat) -> &'static str {
|
||||
match type_ {
|
||||
InputFormat::Fbx(_) => "fbx",
|
||||
InputFormat::Gltf(_) => "gltf",
|
||||
InputFormat::Obj(_) => "obj",
|
||||
InputFormat::Ply(_) => "ply",
|
||||
InputFormat::Sldprt(_) => "sldprt",
|
||||
InputFormat::Step(_) => "step",
|
||||
InputFormat::Stl(_) => "stl",
|
||||
}
|
||||
.await
|
||||
}
|
||||
|
@ -21,9 +21,9 @@ pub struct RequestBody {
|
||||
pub async fn execute_and_snapshot(
|
||||
code: &str,
|
||||
units: UnitLength,
|
||||
project_directory: Option<PathBuf>,
|
||||
current_file: Option<PathBuf>,
|
||||
) -> Result<image::DynamicImage, ExecError> {
|
||||
let ctx = new_context(units, true, project_directory).await?;
|
||||
let ctx = new_context(units, true, current_file).await?;
|
||||
let program = Program::parse_no_errs(code).map_err(KclErrorWithOutputs::no_outputs)?;
|
||||
let res = do_execute_and_snapshot(&ctx, program)
|
||||
.await
|
||||
@ -38,9 +38,9 @@ pub async fn execute_and_snapshot(
|
||||
pub async fn execute_and_snapshot_ast(
|
||||
ast: Program,
|
||||
units: UnitLength,
|
||||
project_directory: Option<PathBuf>,
|
||||
current_file: Option<PathBuf>,
|
||||
) -> Result<(ExecState, image::DynamicImage), ExecErrorWithState> {
|
||||
let ctx = new_context(units, true, project_directory).await?;
|
||||
let ctx = new_context(units, true, current_file).await?;
|
||||
let res = do_execute_and_snapshot(&ctx, ast).await;
|
||||
ctx.close().await;
|
||||
res
|
||||
@ -49,9 +49,9 @@ pub async fn execute_and_snapshot_ast(
|
||||
pub async fn execute_and_snapshot_no_auth(
|
||||
code: &str,
|
||||
units: UnitLength,
|
||||
project_directory: Option<PathBuf>,
|
||||
current_file: Option<PathBuf>,
|
||||
) -> Result<image::DynamicImage, ExecError> {
|
||||
let ctx = new_context(units, false, project_directory).await?;
|
||||
let ctx = new_context(units, false, current_file).await?;
|
||||
let program = Program::parse_no_errs(code).map_err(KclErrorWithOutputs::no_outputs)?;
|
||||
let res = do_execute_and_snapshot(&ctx, program)
|
||||
.await
|
||||
@ -88,7 +88,7 @@ async fn do_execute_and_snapshot(
|
||||
pub async fn new_context(
|
||||
units: UnitLength,
|
||||
with_auth: bool,
|
||||
project_directory: Option<PathBuf>,
|
||||
current_file: Option<PathBuf>,
|
||||
) -> Result<ExecutorContext, ConnectionError> {
|
||||
let mut client = new_zoo_client(if with_auth { None } else { Some("bad_token".to_string()) }, None)
|
||||
.map_err(ConnectionError::CouldNotMakeClient)?;
|
||||
@ -99,17 +99,19 @@ pub async fn new_context(
|
||||
client.set_base_url("https://api.zoo.dev".to_string());
|
||||
}
|
||||
|
||||
let ctx = ExecutorContext::new(
|
||||
&client,
|
||||
ExecutorSettings {
|
||||
let mut settings = ExecutorSettings {
|
||||
units,
|
||||
highlight_edges: true,
|
||||
enable_ssao: false,
|
||||
show_grid: false,
|
||||
replay: None,
|
||||
project_directory,
|
||||
},
|
||||
)
|
||||
project_directory: None,
|
||||
current_file: None,
|
||||
};
|
||||
if let Some(current_file) = current_file {
|
||||
settings.with_current_file(current_file);
|
||||
}
|
||||
let ctx = ExecutorContext::new(&client, settings)
|
||||
.await
|
||||
.map_err(ConnectionError::Establishing)?;
|
||||
Ok(ctx)
|
||||
|
@ -76,6 +76,48 @@ impl Node<'_> {
|
||||
Node::LabelledExpression(n) => n.digest,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check to see if this [Node] points to the same underlying specific
|
||||
/// borrowed object as another [Node]. This is not the same as `Eq` or
|
||||
/// even `PartialEq` -- anything that is `true` here is absolutely `Eq`,
|
||||
/// but it's possible this node is `Eq` to another with this being `false`.
|
||||
///
|
||||
/// This merely indicates that this [Node] specifically is the exact same
|
||||
/// borrowed object as [Node].
|
||||
pub fn ptr_eq(&self, other: Node) -> bool {
|
||||
unsafe { std::ptr::eq(self.ptr(), other.ptr()) }
|
||||
}
|
||||
|
||||
unsafe fn ptr(&self) -> *const () {
|
||||
match self {
|
||||
Node::Program(n) => *n as *const _ as *const (),
|
||||
Node::ImportStatement(n) => *n as *const _ as *const (),
|
||||
Node::ExpressionStatement(n) => *n as *const _ as *const (),
|
||||
Node::VariableDeclaration(n) => *n as *const _ as *const (),
|
||||
Node::ReturnStatement(n) => *n as *const _ as *const (),
|
||||
Node::VariableDeclarator(n) => *n as *const _ as *const (),
|
||||
Node::Literal(n) => *n as *const _ as *const (),
|
||||
Node::TagDeclarator(n) => *n as *const _ as *const (),
|
||||
Node::Identifier(n) => *n as *const _ as *const (),
|
||||
Node::BinaryExpression(n) => *n as *const _ as *const (),
|
||||
Node::FunctionExpression(n) => *n as *const _ as *const (),
|
||||
Node::CallExpression(n) => *n as *const _ as *const (),
|
||||
Node::CallExpressionKw(n) => *n as *const _ as *const (),
|
||||
Node::PipeExpression(n) => *n as *const _ as *const (),
|
||||
Node::PipeSubstitution(n) => *n as *const _ as *const (),
|
||||
Node::ArrayExpression(n) => *n as *const _ as *const (),
|
||||
Node::ArrayRangeExpression(n) => *n as *const _ as *const (),
|
||||
Node::ObjectExpression(n) => *n as *const _ as *const (),
|
||||
Node::MemberExpression(n) => *n as *const _ as *const (),
|
||||
Node::UnaryExpression(n) => *n as *const _ as *const (),
|
||||
Node::Parameter(p) => *p as *const _ as *const (),
|
||||
Node::ObjectProperty(n) => *n as *const _ as *const (),
|
||||
Node::IfExpression(n) => *n as *const _ as *const (),
|
||||
Node::ElseIf(n) => *n as *const _ as *const (),
|
||||
Node::KclNone(n) => *n as *const _ as *const (),
|
||||
Node::LabelledExpression(n) => *n as *const _ as *const (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returned during source_range conversion.
|
||||
@ -239,3 +281,33 @@ impl_from!(Node, IfExpression);
|
||||
impl_from!(Node, ElseIf);
|
||||
impl_from!(Node, LabelledExpression);
|
||||
impl_from!(Node, KclNone);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
macro_rules! kcl {
|
||||
( $kcl:expr ) => {{
|
||||
$crate::parsing::top_level_parse($kcl).unwrap()
|
||||
}};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_ptr_eq() {
|
||||
let program = kcl!(
|
||||
"
|
||||
const foo = 1
|
||||
const bar = foo + 1
|
||||
|
||||
fn myfn = () => {
|
||||
const foo = 2
|
||||
sin(foo)
|
||||
}
|
||||
"
|
||||
);
|
||||
|
||||
let foo: Node = (&program.body[0]).into();
|
||||
assert!(foo.ptr_eq((&program.body[0]).into()));
|
||||
assert!(!foo.ptr_eq((&program.body[1]).into()));
|
||||
}
|
||||
}
|
||||
|
@ -3,4 +3,5 @@ mod ast_visitor;
|
||||
mod ast_walk;
|
||||
|
||||
pub use ast_node::Node;
|
||||
pub use ast_visitor::{Visitable, Visitor};
|
||||
pub use ast_walk::walk;
|
||||
|
@ -661,8 +661,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 5.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
@ -654,8 +654,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -671,8 +670,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
@ -654,8 +654,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -671,8 +670,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
@ -654,8 +654,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
@ -654,8 +654,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
@ -640,8 +640,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -657,8 +656,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 2.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
@ -2487,8 +2487,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 1.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -2504,8 +2503,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 1.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -2521,8 +2519,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 1.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
@ -2538,8 +2535,7 @@ snapshot_kind: text
|
||||
"edge_id": "[uuid]",
|
||||
"radius": 1.0,
|
||||
"tolerance": 0.0000001,
|
||||
"cut_type": "fillet",
|
||||
"face_id": "[uuid]"
|
||||
"cut_type": "fillet"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
@ -7,7 +7,10 @@ description: Result of parsing import_constant.kcl
|
||||
"body": [
|
||||
{
|
||||
"end": 39,
|
||||
"path": "export_constant.kcl",
|
||||
"path": {
|
||||
"type": "Kcl",
|
||||
"filename": "export_constant.kcl"
|
||||
},
|
||||
"selector": {
|
||||
"type": "List",
|
||||
"items": [
|
||||
|
@ -7,7 +7,10 @@ description: Result of parsing import_cycle1.kcl
|
||||
"body": [
|
||||
{
|
||||
"end": 35,
|
||||
"path": "import_cycle2.kcl",
|
||||
"path": {
|
||||
"type": "Kcl",
|
||||
"filename": "import_cycle2.kcl"
|
||||
},
|
||||
"selector": {
|
||||
"type": "List",
|
||||
"items": [
|
||||
|
@ -1,12 +1,13 @@
|
||||
---
|
||||
source: kcl/src/simulation_tests.rs
|
||||
description: Error from executing import_cycle1.kcl
|
||||
snapshot_kind: text
|
||||
---
|
||||
KCL ImportCycle error
|
||||
|
||||
× import cycle: circular import of modules is not allowed: tests/
|
||||
│ import_cycle1/import_cycle2.kcl -> tests/import_cycle1/import_cycle3.kcl
|
||||
│ -> tests/import_cycle1/input.kcl -> tests/import_cycle1/import_cycle2.kcl
|
||||
│ -> tests/import_cycle1/input.kcl
|
||||
╭─[1:1]
|
||||
1 │ import two from "import_cycle2.kcl"
|
||||
· ───────────────────────────────────
|
||||
|
@ -7,7 +7,10 @@ description: Result of parsing import_export.kcl
|
||||
"body": [
|
||||
{
|
||||
"end": 32,
|
||||
"path": "export_1.kcl",
|
||||
"path": {
|
||||
"type": "Kcl",
|
||||
"filename": "export_1.kcl"
|
||||
},
|
||||
"selector": {
|
||||
"type": "List",
|
||||
"items": [
|
||||
|
3281
src/wasm-lib/kcl/tests/import_foreign/artifact_commands.snap
Normal file
3281
src/wasm-lib/kcl/tests/import_foreign/artifact_commands.snap
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,6 @@
|
||||
---
|
||||
source: kcl/src/simulation_tests.rs
|
||||
description: Artifact graph flowchart import_glob.kcl
|
||||
extension: md
|
||||
snapshot_kind: binary
|
||||
---
|
@ -0,0 +1,3 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
```
|
@ -0,0 +1,6 @@
|
||||
---
|
||||
source: kcl/src/simulation_tests.rs
|
||||
description: Artifact graph mind map import_glob.kcl
|
||||
extension: md
|
||||
snapshot_kind: binary
|
||||
---
|
@ -0,0 +1,4 @@
|
||||
```mermaid
|
||||
mindmap
|
||||
root
|
||||
```
|
71
src/wasm-lib/kcl/tests/import_foreign/ast.snap
Normal file
71
src/wasm-lib/kcl/tests/import_foreign/ast.snap
Normal file
@ -0,0 +1,71 @@
|
||||
---
|
||||
source: kcl/src/simulation_tests.rs
|
||||
description: Result of parsing import_foreign.kcl
|
||||
---
|
||||
{
|
||||
"Ok": {
|
||||
"body": [
|
||||
{
|
||||
"end": 36,
|
||||
"path": {
|
||||
"type": "Foreign",
|
||||
"path": "../inputs/cube.gltf"
|
||||
},
|
||||
"selector": {
|
||||
"type": "None",
|
||||
"alias": {
|
||||
"end": 36,
|
||||
"name": "cube",
|
||||
"start": 32,
|
||||
"type": "Identifier"
|
||||
}
|
||||
},
|
||||
"start": 0,
|
||||
"type": "ImportStatement",
|
||||
"type": "ImportStatement"
|
||||
},
|
||||
{
|
||||
"declaration": {
|
||||
"end": 50,
|
||||
"id": {
|
||||
"end": 43,
|
||||
"name": "model",
|
||||
"start": 38,
|
||||
"type": "Identifier"
|
||||
},
|
||||
"init": {
|
||||
"end": 50,
|
||||
"name": "cube",
|
||||
"start": 46,
|
||||
"type": "Identifier",
|
||||
"type": "Identifier"
|
||||
},
|
||||
"start": 38,
|
||||
"type": "VariableDeclarator"
|
||||
},
|
||||
"end": 50,
|
||||
"kind": "const",
|
||||
"start": 38,
|
||||
"type": "VariableDeclaration",
|
||||
"type": "VariableDeclaration"
|
||||
}
|
||||
],
|
||||
"end": 51,
|
||||
"nonCodeMeta": {
|
||||
"nonCodeNodes": {
|
||||
"0": [
|
||||
{
|
||||
"end": 38,
|
||||
"start": 36,
|
||||
"type": "NonCodeNode",
|
||||
"value": {
|
||||
"type": "newLine"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"startNodes": []
|
||||
},
|
||||
"start": 0
|
||||
}
|
||||
}
|
3
src/wasm-lib/kcl/tests/import_foreign/input.kcl
Normal file
3
src/wasm-lib/kcl/tests/import_foreign/input.kcl
Normal file
@ -0,0 +1,3 @@
|
||||
import "../inputs/cube.gltf" as cube
|
||||
|
||||
model = cube
|
6
src/wasm-lib/kcl/tests/import_foreign/ops.snap
Normal file
6
src/wasm-lib/kcl/tests/import_foreign/ops.snap
Normal file
@ -0,0 +1,6 @@
|
||||
---
|
||||
source: kcl/src/simulation_tests.rs
|
||||
description: Operations executed import_glob.kcl
|
||||
snapshot_kind: text
|
||||
---
|
||||
[]
|
64
src/wasm-lib/kcl/tests/import_foreign/program_memory.snap
Normal file
64
src/wasm-lib/kcl/tests/import_foreign/program_memory.snap
Normal file
@ -0,0 +1,64 @@
|
||||
---
|
||||
source: kcl/src/simulation_tests.rs
|
||||
description: Program memory after executing import_foreign.kcl
|
||||
---
|
||||
{
|
||||
"environments": [
|
||||
{
|
||||
"bindings": {
|
||||
"HALF_TURN": {
|
||||
"type": "Number",
|
||||
"value": 180.0,
|
||||
"__meta": []
|
||||
},
|
||||
"QUARTER_TURN": {
|
||||
"type": "Number",
|
||||
"value": 90.0,
|
||||
"__meta": []
|
||||
},
|
||||
"THREE_QUARTER_TURN": {
|
||||
"type": "Number",
|
||||
"value": 270.0,
|
||||
"__meta": []
|
||||
},
|
||||
"ZERO": {
|
||||
"type": "Number",
|
||||
"value": 0.0,
|
||||
"__meta": []
|
||||
},
|
||||
"cube": {
|
||||
"type": "Module",
|
||||
"value": 1,
|
||||
"__meta": [
|
||||
{
|
||||
"sourceRange": [
|
||||
0,
|
||||
36,
|
||||
0
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"model": {
|
||||
"type": "ImportedGeometry",
|
||||
"id": "[uuid]",
|
||||
"value": [
|
||||
"cube.gltf"
|
||||
],
|
||||
"__meta": [
|
||||
{
|
||||
"sourceRange": [
|
||||
0,
|
||||
36,
|
||||
0
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"parent": null
|
||||
}
|
||||
],
|
||||
"currentEnv": 0,
|
||||
"return": null
|
||||
}
|
@ -7,7 +7,10 @@ description: Result of parsing import_glob.kcl
|
||||
"body": [
|
||||
{
|
||||
"end": 35,
|
||||
"path": "export_constant.kcl",
|
||||
"path": {
|
||||
"type": "Kcl",
|
||||
"filename": "export_constant.kcl"
|
||||
},
|
||||
"selector": {
|
||||
"end": 8,
|
||||
"start": 7,
|
||||
|
@ -7,7 +7,10 @@ description: Result of parsing import_side_effect.kcl
|
||||
"body": [
|
||||
{
|
||||
"end": 40,
|
||||
"path": "export_side_effect.kcl",
|
||||
"path": {
|
||||
"type": "Kcl",
|
||||
"filename": "export_side_effect.kcl"
|
||||
},
|
||||
"selector": {
|
||||
"type": "List",
|
||||
"items": [
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user