Compare commits
30 Commits
v0.38.0
...
jtran/offs
Author | SHA1 | Date | |
---|---|---|---|
4391a286ce | |||
a44516bc7e | |||
ce62fe67cf | |||
763a1b6628 | |||
3281e62e6b | |||
f1a458f124 | |||
229433126d | |||
b962b5fcb3 | |||
428d125139 | |||
cffeb52b4b | |||
e0ef10e7bb | |||
7095ce2377 | |||
5b207d7d1a | |||
2fac213c58 | |||
2f72a8ef14 | |||
27ce9f8aa4 | |||
b0426e3f94 | |||
d707c66e53 | |||
f8f44743fa | |||
f262eda12a | |||
9e1136195a | |||
4ff07ddaee | |||
1e565379a7 | |||
76e34ac4da | |||
4cd427bf91 | |||
f321ecdff0 | |||
d114ab798c | |||
69fec37107 | |||
8ca8c49cc3 | |||
b25fc302fd |
@ -2,8 +2,8 @@ NODE_ENV=development
|
||||
DEV=true
|
||||
VITE_KC_API_WS_MODELING_URL=wss://api.dev.zoo.dev/ws/modeling/commands
|
||||
VITE_KC_API_BASE_URL=https://api.dev.zoo.dev
|
||||
BASE_URL=https://api.dev.zoo.dev
|
||||
VITE_KC_SITE_BASE_URL=https://dev.zoo.dev
|
||||
VITE_KC_SITE_APP_URL=https://app.dev.zoo.dev
|
||||
VITE_KC_SKIP_AUTH=false
|
||||
VITE_KC_CONNECTION_TIMEOUT_MS=5000
|
||||
# ONLY add your token in .env.development.local if you want to skip auth, otherwise this token takes precedence!
|
||||
|
@ -1,5 +1,8 @@
|
||||
NODE_ENV=production
|
||||
DEV=false
|
||||
VITE_KC_API_WS_MODELING_URL=wss://api.zoo.dev/ws/modeling/commands
|
||||
VITE_KC_API_BASE_URL=https://api.zoo.dev
|
||||
VITE_KC_SITE_BASE_URL=https://zoo.dev
|
||||
VITE_KC_SITE_APP_URL=https://app.zoo.dev
|
||||
VITE_KC_SKIP_AUTH=false
|
||||
VITE_KC_CONNECTION_TIMEOUT_MS=15000
|
||||
|
16
.github/workflows/build-apps.yml
vendored
@ -134,8 +134,6 @@ jobs:
|
||||
max_attempts: 3
|
||||
command: yarn install
|
||||
|
||||
- run: yarn tronb:vite
|
||||
|
||||
- name: Prepare certificate and variables (Windows only)
|
||||
if: ${{ (env.IS_RELEASE == 'true' || env.IS_NIGHTLY == 'true') && matrix.os == 'windows-2022' }}
|
||||
run: |
|
||||
@ -165,8 +163,8 @@ jobs:
|
||||
- name: Build the app (debug)
|
||||
if: ${{ env.IS_RELEASE == 'false' && env.IS_NIGHTLY == 'false' }}
|
||||
# electron-builder doesn't have a concept of release vs debug,
|
||||
# this is just not doing any codesign or release yml generation
|
||||
run: yarn electron-builder --config
|
||||
# this is just not doing any codesign or release yml generation, and points to dev infra
|
||||
run: yarn tronb:package:dev
|
||||
|
||||
- name: Build the app (release)
|
||||
if: ${{ env.IS_RELEASE == 'true' || env.IS_NIGHTLY == 'true' }}
|
||||
@ -185,7 +183,7 @@ jobs:
|
||||
with:
|
||||
timeout_minutes: 10
|
||||
max_attempts: 3
|
||||
command: yarn electron-builder --config --publish always
|
||||
command: yarn tronb:package:prod
|
||||
|
||||
- name: List artifacts in out/
|
||||
run: ls -R out
|
||||
@ -246,7 +244,7 @@ jobs:
|
||||
with:
|
||||
timeout_minutes: 10
|
||||
max_attempts: 3
|
||||
command: yarn electron-builder --config --publish always
|
||||
command: yarn tronb:package:prod
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ env.IS_RELEASE == 'true' }}
|
||||
@ -390,19 +388,19 @@ jobs:
|
||||
|
||||
- name: Authenticate to Google Cloud
|
||||
if: ${{ env.IS_NIGHTLY == 'true' }}
|
||||
uses: 'google-github-actions/auth@v2.1.7'
|
||||
uses: 'google-github-actions/auth@v2.1.8'
|
||||
with:
|
||||
credentials_json: '${{ secrets.GOOGLE_CLOUD_DL_SA }}'
|
||||
|
||||
- name: Set up Google Cloud SDK
|
||||
if: ${{ env.IS_NIGHTLY == 'true' }}
|
||||
uses: google-github-actions/setup-gcloud@v2.1.2
|
||||
uses: google-github-actions/setup-gcloud@v2.1.4
|
||||
with:
|
||||
project_id: ${{ env.GOOGLE_CLOUD_PROJECT_ID }}
|
||||
|
||||
- name: Upload nightly files to public bucket
|
||||
if: ${{ env.IS_NIGHTLY == 'true' }}
|
||||
uses: google-github-actions/upload-cloud-storage@v2.2.1
|
||||
uses: google-github-actions/upload-cloud-storage@v2.2.2
|
||||
with:
|
||||
path: out
|
||||
glob: '*'
|
||||
|
60
.github/workflows/e2e-tests.yml
vendored
@ -123,23 +123,23 @@ jobs:
|
||||
if: steps.download-wasm.outcome == 'failure'
|
||||
shell: bash
|
||||
run: yarn build:wasm
|
||||
- name: build electron
|
||||
- name: build web
|
||||
shell: bash
|
||||
run: yarn tron:package
|
||||
- name: Run ubuntu/chrome snapshots
|
||||
if: ${{ matrix.os == 'namespace-profile-ubuntu-8-cores' && matrix.shardIndex == 1 }}
|
||||
shell: bash
|
||||
# TODO: break this in its own job, for now it's not slowing down the overall execution as ubuntu is the quickest,
|
||||
# but we could do better. This forces a large 1/1 shard of all 20 snapshot tests that runs in about 3 minutes.
|
||||
run: |
|
||||
PLATFORM=web yarn playwright test --config=playwright.config.ts --retries="3" --update-snapshots --grep=@snapshot --shard=1/1
|
||||
env:
|
||||
CI: true
|
||||
NODE_ENV: development
|
||||
VITE_KC_DEV_TOKEN: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
|
||||
VITE_KC_SKIP_AUTH: true
|
||||
token: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
|
||||
snapshottoken: ${{ secrets.KITTYCAD_API_TOKEN }}
|
||||
run: yarn tronb:vite:dev
|
||||
# - name: Run ubuntu/chrome snapshots
|
||||
# if: ${{ matrix.os == 'namespace-profile-ubuntu-8-cores' && matrix.shardIndex == 1 }}
|
||||
# shell: bash
|
||||
# # TODO: break this in its own job, for now it's not slowing down the overall execution as ubuntu is the quickest,
|
||||
# # but we could do better. This forces a large 1/1 shard of all 20 snapshot tests that runs in about 3 minutes.
|
||||
# run: |
|
||||
# PLATFORM=web yarn playwright test --config=playwright.config.ts --retries="3" --update-snapshots --grep=@snapshot --shard=1/1
|
||||
# env:
|
||||
# CI: true
|
||||
# NODE_ENV: development
|
||||
# VITE_KC_DEV_TOKEN: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
|
||||
# VITE_KC_SKIP_AUTH: true
|
||||
# token: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
|
||||
# snapshottoken: ${{ secrets.KITTYCAD_API_TOKEN }}
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: ${{ !cancelled() && (success() || failure()) }}
|
||||
with:
|
||||
@ -162,20 +162,20 @@ jobs:
|
||||
then echo "modified=true" >> $GITHUB_OUTPUT
|
||||
else echo "modified=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
- name: Commit changes, if any
|
||||
if: steps.git-check.outputs.modified == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
git add .
|
||||
git config --local user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git config --local user.name "github-actions[bot]"
|
||||
git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git
|
||||
git fetch origin
|
||||
echo ${{ github.head_ref }}
|
||||
git checkout ${{ github.head_ref }}
|
||||
git commit -am "A snapshot a day keeps the bugs away! 📷🐛 (OS: ${{matrix.os}})" || true
|
||||
git push
|
||||
git push origin ${{ github.head_ref }}
|
||||
# - name: Commit changes, if any
|
||||
# if: steps.git-check.outputs.modified == 'true'
|
||||
# shell: bash
|
||||
# run: |
|
||||
# git add .
|
||||
# git config --local user.email "github-actions[bot]@users.noreply.github.com"
|
||||
# git config --local user.name "github-actions[bot]"
|
||||
# git remote set-url origin https://${{ github.actor }}:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git
|
||||
# git fetch origin
|
||||
# echo ${{ github.head_ref }}
|
||||
# git checkout ${{ github.head_ref }}
|
||||
# git commit -am "A snapshot a day keeps the bugs away! 📷🐛 (OS: ${{matrix.os}})" || true
|
||||
# git push
|
||||
# git push origin ${{ github.head_ref }}
|
||||
# only upload artifacts if there's actually changes
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: steps.git-check.outputs.modified == 'true'
|
||||
|
6
.github/workflows/publish-apps-release.yml
vendored
@ -108,17 +108,17 @@ jobs:
|
||||
run: yarn files:set-notes
|
||||
|
||||
- name: Authenticate to Google Cloud
|
||||
uses: 'google-github-actions/auth@v2.1.7'
|
||||
uses: 'google-github-actions/auth@v2.1.8'
|
||||
with:
|
||||
credentials_json: '${{ secrets.GOOGLE_CLOUD_DL_SA }}'
|
||||
|
||||
- name: Set up Google Cloud SDK
|
||||
uses: google-github-actions/setup-gcloud@v2.1.2
|
||||
uses: google-github-actions/setup-gcloud@v2.1.4
|
||||
with:
|
||||
project_id: ${{ env.GOOGLE_CLOUD_PROJECT_ID }}
|
||||
|
||||
- name: Upload release files to public bucket
|
||||
uses: google-github-actions/upload-cloud-storage@v2.2.1
|
||||
uses: google-github-actions/upload-cloud-storage@v2.2.2
|
||||
with:
|
||||
path: out
|
||||
glob: '*'
|
||||
|
2
.gitignore
vendored
@ -44,7 +44,7 @@ e2e/playwright/temp3.png
|
||||
e2e/playwright/export-snapshots/*
|
||||
!e2e/playwright/export-snapshots/*.png
|
||||
|
||||
|
||||
/kcl-samples
|
||||
/test-results/
|
||||
/playwright-report/
|
||||
/blob-report/
|
||||
|
@ -101,7 +101,7 @@ This will start the application and hot-reload on changes.
|
||||
|
||||
Devtools can be opened with the usual Cmd-Opt-I (Mac) or Ctrl-Shift-I (Linux and Windows).
|
||||
|
||||
To build, run `yarn tron:package`.
|
||||
To build with electron-builder, run `yarn tronb:package:dev` (or `yarn tronb:package:prod` to point to the .env.production variables)
|
||||
|
||||
## Checking out commits / Bisecting
|
||||
|
||||
|
@ -4,14 +4,16 @@ 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.
|
||||
|
||||
For importing KCL functions using the `import` statement, see the docs on [KCL modules](/docs/kcl/modules).
|
||||
|
||||
```js
|
||||
import(file_path: String, options?: ImportFormat) -> ImportedGeometry
|
||||
```
|
||||
|
@ -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)
|
||||
|
@ -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.",
|
||||
"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\" })",
|
||||
|
@ -4,7 +4,6 @@ import { expect } from '@playwright/test'
|
||||
type CmdBarSerialised =
|
||||
| {
|
||||
stage: 'commandBarClosed'
|
||||
// TODO no more properties needed but needs to be implemented in _serialiseCmdBar
|
||||
}
|
||||
| {
|
||||
stage: 'pickCommand'
|
||||
@ -37,6 +36,9 @@ export class CmdBarFixture {
|
||||
}
|
||||
|
||||
private _serialiseCmdBar = async (): Promise<CmdBarSerialised> => {
|
||||
if (!(await this.page.getByTestId('command-bar-wrapper').isVisible())) {
|
||||
return { stage: 'commandBarClosed' }
|
||||
}
|
||||
const reviewForm = this.page.locator('#review-form')
|
||||
const getHeaderArgs = async () => {
|
||||
const inputs = await this.page.getByTestId('cmd-bar-input-tab').all()
|
||||
|
@ -18,6 +18,7 @@ export class ToolbarFixture {
|
||||
filletButton!: Locator
|
||||
chamferButton!: Locator
|
||||
shellButton!: Locator
|
||||
revolveButton!: Locator
|
||||
offsetPlaneButton!: Locator
|
||||
startSketchBtn!: Locator
|
||||
lineBtn!: Locator
|
||||
@ -47,6 +48,7 @@ export class ToolbarFixture {
|
||||
this.filletButton = page.getByTestId('fillet3d')
|
||||
this.chamferButton = page.getByTestId('chamfer3d')
|
||||
this.shellButton = page.getByTestId('shell')
|
||||
this.revolveButton = page.getByTestId('revolve')
|
||||
this.offsetPlaneButton = page.getByTestId('plane-offset')
|
||||
this.startSketchBtn = page.getByTestId('sketch')
|
||||
this.lineBtn = page.getByTestId('line')
|
||||
|
@ -1078,7 +1078,7 @@ sketch002 = startSketchOn('XZ')
|
||||
await page.waitForTimeout(500)
|
||||
await cmdBar.progressCmdBar()
|
||||
await expect(
|
||||
page.getByText('Unable to sweep with the provided selection')
|
||||
page.getByText('Unable to sweep with the current selection. Reason:')
|
||||
).toBeVisible()
|
||||
})
|
||||
})
|
||||
@ -1183,7 +1183,7 @@ extrude001 = extrude(-12, sketch001)
|
||||
currentArgKey: 'radius',
|
||||
currentArgValue: '5',
|
||||
headerArguments: {
|
||||
Selection: '1 face',
|
||||
Selection: '1 segment',
|
||||
Radius: '',
|
||||
},
|
||||
stage: 'arguments',
|
||||
@ -1192,7 +1192,7 @@ extrude001 = extrude(-12, sketch001)
|
||||
await cmdBar.expectState({
|
||||
commandName: 'Fillet',
|
||||
headerArguments: {
|
||||
Selection: '1 face',
|
||||
Selection: '1 segment',
|
||||
Radius: '5',
|
||||
},
|
||||
stage: 'review',
|
||||
@ -1398,7 +1398,7 @@ extrude001 = extrude(-12, sketch001)
|
||||
currentArgKey: 'length',
|
||||
currentArgValue: '5',
|
||||
headerArguments: {
|
||||
Selection: '1 face',
|
||||
Selection: '1 segment',
|
||||
Length: '',
|
||||
},
|
||||
stage: 'arguments',
|
||||
@ -1407,7 +1407,7 @@ extrude001 = extrude(-12, sketch001)
|
||||
await cmdBar.expectState({
|
||||
commandName: 'Chamfer',
|
||||
headerArguments: {
|
||||
Selection: '1 face',
|
||||
Selection: '1 segment',
|
||||
Length: '5',
|
||||
},
|
||||
stage: 'review',
|
||||
@ -1846,8 +1846,176 @@ sweep001 = sweep({ path = sketch002 }, sketch001)
|
||||
await page.waitForTimeout(500)
|
||||
await cmdBar.progressCmdBar()
|
||||
await expect(
|
||||
page.getByText('Unable to shell with the provided selection')
|
||||
page.getByText('Unable to shell with the current selection. Reason:')
|
||||
).toBeVisible()
|
||||
await page.waitForTimeout(1000)
|
||||
})
|
||||
})
|
||||
|
||||
test.describe('Revolve point and click workflows', () => {
|
||||
test('Base case workflow, auto spam continue in command bar', async ({
|
||||
context,
|
||||
page,
|
||||
homePage,
|
||||
scene,
|
||||
editor,
|
||||
toolbar,
|
||||
cmdBar,
|
||||
}) => {
|
||||
const initialCode = `
|
||||
sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([-100.0, 100.0], %)
|
||||
|> angledLine([0, 200.0], %, $rectangleSegmentA001)
|
||||
|> angledLine([segAng(rectangleSegmentA001) - 90, 200], %, $rectangleSegmentB001)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA001),
|
||||
-segLen(rectangleSegmentA001)
|
||||
], %, $rectangleSegmentC001)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
extrude001 = extrude(200, sketch001)
|
||||
sketch002 = startSketchOn(extrude001, rectangleSegmentA001)
|
||||
|> startProfileAt([-66.77, 84.81], %)
|
||||
|> angledLine([180, 27.08], %, $rectangleSegmentA002)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA002) - 90,
|
||||
27.8
|
||||
], %, $rectangleSegmentB002)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA002),
|
||||
-segLen(rectangleSegmentA002)
|
||||
], %, $rectangleSegmentC002)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
`
|
||||
|
||||
await context.addInitScript((initialCode) => {
|
||||
localStorage.setItem('persistCode', initialCode)
|
||||
}, initialCode)
|
||||
await page.setBodyDimensions({ width: 1000, height: 500 })
|
||||
await homePage.goToModelingScene()
|
||||
await scene.waitForExecutionDone()
|
||||
|
||||
// select line of code
|
||||
const codeToSelecton = `segAng(rectangleSegmentA002) - 90,`
|
||||
// revolve
|
||||
await page.getByText(codeToSelecton).click()
|
||||
await toolbar.revolveButton.click()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
|
||||
const newCodeToFind = `revolve001 = revolve({ angle = 360, axis = 'X' }, sketch002)`
|
||||
expect(editor.expectEditor.toContain(newCodeToFind)).toBeTruthy()
|
||||
})
|
||||
test('revolve surface around edge from an extruded solid2d', async ({
|
||||
context,
|
||||
page,
|
||||
homePage,
|
||||
scene,
|
||||
editor,
|
||||
toolbar,
|
||||
cmdBar,
|
||||
}) => {
|
||||
const initialCode = `
|
||||
sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([-102.57, 101.72], %)
|
||||
|> angledLine([0, 202.6], %, $rectangleSegmentA001)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA001) - 90,
|
||||
202.6
|
||||
], %, $rectangleSegmentB001)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA001),
|
||||
-segLen(rectangleSegmentA001)
|
||||
], %, $rectangleSegmentC001)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
extrude001 = extrude(50, sketch001)
|
||||
sketch002 = startSketchOn(extrude001, rectangleSegmentA001)
|
||||
|> circle({
|
||||
center = [-11.34, 10.0],
|
||||
radius = 8.69
|
||||
}, %)
|
||||
`
|
||||
await context.addInitScript((initialCode) => {
|
||||
localStorage.setItem('persistCode', initialCode)
|
||||
}, initialCode)
|
||||
await page.setBodyDimensions({ width: 1000, height: 500 })
|
||||
await homePage.goToModelingScene()
|
||||
await scene.waitForExecutionDone()
|
||||
|
||||
// select line of code
|
||||
const codeToSelecton = `center = [-11.34, 10.0]`
|
||||
// revolve
|
||||
await page.getByText(codeToSelecton).click()
|
||||
await toolbar.revolveButton.click()
|
||||
await page.getByText('Edge', { exact: true }).click()
|
||||
const lineCodeToSelection = `|> angledLine([0, 202.6], %, $rectangleSegmentA001)`
|
||||
await page.getByText(lineCodeToSelection).click()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
|
||||
const newCodeToFind = `revolve001 = revolve({angle = 360, axis = getOppositeEdge(rectangleSegmentA001)}, sketch002) `
|
||||
expect(editor.expectEditor.toContain(newCodeToFind)).toBeTruthy()
|
||||
})
|
||||
test('revolve sketch circle around line segment from startProfileAt sketch', async ({
|
||||
context,
|
||||
page,
|
||||
homePage,
|
||||
scene,
|
||||
editor,
|
||||
toolbar,
|
||||
cmdBar,
|
||||
}) => {
|
||||
const initialCode = `
|
||||
sketch002 = startSketchOn('XY')
|
||||
|> startProfileAt([-2.02, 1.79], %)
|
||||
|> xLine(2.6, %)
|
||||
sketch001 = startSketchOn('-XY')
|
||||
|> startProfileAt([-0.48, 1.25], %)
|
||||
|> angledLine([0, 2.38], %, $rectangleSegmentA001)
|
||||
|> angledLine([segAng(rectangleSegmentA001) - 90, 2.4], %, $rectangleSegmentB001)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA001),
|
||||
-segLen(rectangleSegmentA001)
|
||||
], %, $rectangleSegmentC001)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
extrude001 = extrude(5, sketch001)
|
||||
sketch003 = startSketchOn(extrude001, 'START')
|
||||
|> circle({
|
||||
center = [-0.69, 0.56],
|
||||
radius = 0.28
|
||||
}, %)
|
||||
`
|
||||
|
||||
await context.addInitScript((initialCode) => {
|
||||
localStorage.setItem('persistCode', initialCode)
|
||||
}, initialCode)
|
||||
await page.setBodyDimensions({ width: 1000, height: 500 })
|
||||
await homePage.goToModelingScene()
|
||||
await scene.waitForExecutionDone()
|
||||
|
||||
// select line of code
|
||||
const codeToSelecton = `center = [-0.69, 0.56]`
|
||||
// revolve
|
||||
await page.getByText(codeToSelecton).click()
|
||||
await toolbar.revolveButton.click()
|
||||
await page.getByText('Edge', { exact: true }).click()
|
||||
const lineCodeToSelection = `|> xLine(2.6, %)`
|
||||
await page.getByText(lineCodeToSelection).click()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.progressCmdBar()
|
||||
|
||||
const newCodeToFind = `revolve001 = revolve({ angle = 360, axis = seg01 }, sketch003)`
|
||||
expect(editor.expectEditor.toContain(newCodeToFind)).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
@ -572,7 +572,7 @@ test(
|
||||
fs.utimesSync(`${dir}/lego/main.kcl`, _1995, _1995)
|
||||
})
|
||||
|
||||
await page.setBodyDimensions({ width: 1200, height: 500 })
|
||||
await page.setBodyDimensions({ width: 1200, height: 600 })
|
||||
|
||||
page.on('console', console.log)
|
||||
|
||||
@ -1525,7 +1525,7 @@ extrude001 = extrude(200, sketch001)`)
|
||||
test(
|
||||
'Opening a project should successfully load the stream, (regression test that this also works when switching between projects)',
|
||||
{ tag: '@electron' },
|
||||
async ({ context, page }, testInfo) => {
|
||||
async ({ context, page, cmdBar, homePage }, testInfo) => {
|
||||
await context.folderSetupFn(async (dir) => {
|
||||
await Promise.all([
|
||||
fsp.mkdir(path.join(dir, 'router-template-slate'), { recursive: true }),
|
||||
@ -1563,11 +1563,38 @@ test(
|
||||
|
||||
const pointOnModel = { x: 630, y: 280 }
|
||||
|
||||
await test.step('Opening the bracket project should load the stream', async () => {
|
||||
// expect to see the text bracket
|
||||
await expect(page.getByText('bracket')).toBeVisible()
|
||||
await test.step('Opening the bracket project via command palette should load the stream', async () => {
|
||||
await homePage.expectState({
|
||||
projectCards: [
|
||||
{
|
||||
title: 'bracket',
|
||||
fileCount: 1,
|
||||
},
|
||||
{
|
||||
title: 'router-template-slate',
|
||||
fileCount: 1,
|
||||
},
|
||||
],
|
||||
sortBy: 'last-modified-desc',
|
||||
})
|
||||
|
||||
await page.getByText('bracket').click()
|
||||
await cmdBar.openCmdBar()
|
||||
await cmdBar.chooseCommand('open project')
|
||||
await cmdBar.expectState({
|
||||
stage: 'arguments',
|
||||
commandName: 'Open project',
|
||||
currentArgKey: 'name',
|
||||
currentArgValue: '',
|
||||
headerArguments: {
|
||||
Name: '',
|
||||
},
|
||||
highlightedHeaderArg: 'name',
|
||||
})
|
||||
await cmdBar.argumentInput.fill('brac')
|
||||
await cmdBar.progressCmdBar()
|
||||
await cmdBar.expectState({
|
||||
stage: 'commandBarClosed',
|
||||
})
|
||||
|
||||
await u.waitForPageLoad()
|
||||
|
||||
@ -1588,7 +1615,7 @@ test(
|
||||
await expect(page.getByText('Create project')).toBeVisible()
|
||||
})
|
||||
|
||||
await test.step('Opening the router-template project should load the stream', async () => {
|
||||
await test.step('Opening the router-template project via link should load the stream', async () => {
|
||||
// expect to see the text bracket
|
||||
await expect(page.getByText('router-template-slate')).toBeVisible()
|
||||
|
||||
@ -1605,16 +1632,26 @@ test(
|
||||
.toBeLessThan(15)
|
||||
})
|
||||
|
||||
await test.step('Opening the router-template project should load the stream', async () => {
|
||||
await test.step('The projects on the home page should still be normal', async () => {
|
||||
await page.getByTestId('project-sidebar-toggle').click()
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Go to Home' })
|
||||
).toBeVisible()
|
||||
await page.getByRole('button', { name: 'Go to Home' }).click()
|
||||
|
||||
await expect(page.getByRole('link', { name: 'bracket' })).toBeVisible()
|
||||
await expect(page.getByText('router-template-slate')).toBeVisible()
|
||||
await expect(page.getByText('Create project')).toBeVisible()
|
||||
await homePage.expectState({
|
||||
projectCards: [
|
||||
{
|
||||
title: 'bracket',
|
||||
fileCount: 1,
|
||||
},
|
||||
{
|
||||
title: 'router-template-slate',
|
||||
fileCount: 1,
|
||||
},
|
||||
],
|
||||
sortBy: 'last-modified-desc',
|
||||
})
|
||||
})
|
||||
}
|
||||
)
|
||||
|
@ -34,7 +34,7 @@ test.describe('Sketch tests', () => {
|
||||
screwRadius = 3
|
||||
wireRadius = 2
|
||||
wireOffset = 0.5
|
||||
|
||||
|
||||
screwHole = startSketchOn('XY')
|
||||
${startProfileAt1}
|
||||
|> arc({
|
||||
@ -42,7 +42,7 @@ test.describe('Sketch tests', () => {
|
||||
angleStart = 0,
|
||||
angleEnd = 360
|
||||
}, %)
|
||||
|
||||
|
||||
part001 = startSketchOn('XY')
|
||||
${startProfileAt2}
|
||||
|> xLine(width * .5, %)
|
||||
@ -51,7 +51,7 @@ test.describe('Sketch tests', () => {
|
||||
|> close(%)
|
||||
|> hole(screwHole, %)
|
||||
|> extrude(thickness, %)
|
||||
|
||||
|
||||
part002 = startSketchOn('-XZ')
|
||||
${startProfileAt3}
|
||||
|> xLine(width / 4, %)
|
||||
@ -99,6 +99,7 @@ test.describe('Sketch tests', () => {
|
||||
test('Can delete most of a sketch and the line tool will still work', async ({
|
||||
page,
|
||||
homePage,
|
||||
scene,
|
||||
}) => {
|
||||
const u = await getUtils(page)
|
||||
await page.addInitScript(async () => {
|
||||
@ -112,12 +113,13 @@ test.describe('Sketch tests', () => {
|
||||
})
|
||||
|
||||
await homePage.goToModelingScene()
|
||||
await scene.waitForExecutionDone()
|
||||
|
||||
await expect(async () => {
|
||||
await page.getByText('tangentialArcTo([24.95, -5.38], %)').click()
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Edit Sketch' })
|
||||
).toBeEnabled({ timeout: 1000 })
|
||||
).toBeEnabled({ timeout: 2000 })
|
||||
await page.getByRole('button', { name: 'Edit Sketch' }).click()
|
||||
}).toPass({ timeout: 40_000, intervals: [1_000] })
|
||||
|
||||
@ -884,7 +886,7 @@ test.describe('Sketch tests', () => {
|
||||
// sketch selection should already have been made. "Selection: 1 face" only show up when the selection has been made already
|
||||
// otherwise the cmdbar would be waiting for a selection.
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'selection : 1 face', exact: false })
|
||||
page.getByRole('button', { name: 'selection : 1 segment', exact: false })
|
||||
).toBeVisible({
|
||||
timeout: 10_000,
|
||||
})
|
||||
@ -1063,7 +1065,7 @@ test.describe('Sketch tests', () => {
|
||||
`lugHeadLength = 0.25
|
||||
lugDiameter = 0.5
|
||||
lugLength = 2
|
||||
|
||||
|
||||
fn lug = (origin, length, diameter, plane) => {
|
||||
lugSketch = startSketchOn(plane)
|
||||
|> startProfileAt([origin[0] + lugDiameter / 2, origin[1]], %)
|
||||
@ -1072,10 +1074,10 @@ test.describe('Sketch tests', () => {
|
||||
|> yLineTo(0, %)
|
||||
|> close(%)
|
||||
|> revolve({ axis = "Y" }, %)
|
||||
|
||||
|
||||
return lugSketch
|
||||
}
|
||||
|
||||
|
||||
lug([0, 0], 10, .5, "XY")`
|
||||
)
|
||||
})
|
||||
@ -1127,14 +1129,14 @@ test.describe('Sketch tests', () => {
|
||||
`fn in2mm = (inches) => {
|
||||
return inches * 25.4
|
||||
}
|
||||
|
||||
|
||||
const railTop = in2mm(.748)
|
||||
const railSide = in2mm(.024)
|
||||
const railBaseWidth = in2mm(.612)
|
||||
const railWideWidth = in2mm(.835)
|
||||
const railBaseLength = in2mm(.200)
|
||||
const railClampable = in2mm(.200)
|
||||
|
||||
|
||||
const rail = startSketchOn('XZ')
|
||||
|> startProfileAt([
|
||||
-railTop / 2,
|
||||
@ -1405,3 +1407,46 @@ test.describe(`Click based selection don't brick the app when clicked out of ran
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// Regression test for https://github.com/KittyCAD/modeling-app/issues/4372
|
||||
test.describe('Redirecting to home page and back to the original file should clear sketch DOM elements', () => {
|
||||
test('Can redirect to home page and back to original file and have a cleared DOM', async ({
|
||||
context,
|
||||
page,
|
||||
scene,
|
||||
toolbar,
|
||||
editor,
|
||||
homePage,
|
||||
}) => {
|
||||
// We seed the scene with a single offset plane
|
||||
await context.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
'persistCode',
|
||||
` sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([256.85, 14.41], %)
|
||||
|> lineTo([0, 211.07], %)
|
||||
`
|
||||
)
|
||||
})
|
||||
await homePage.goToModelingScene()
|
||||
await scene.waitForExecutionDone()
|
||||
|
||||
const [objClick] = scene.makeMouseHelpers(634, 274)
|
||||
await objClick()
|
||||
|
||||
// Enter sketch mode
|
||||
await toolbar.editSketch()
|
||||
|
||||
await expect(page.getByText('323.49')).toBeVisible()
|
||||
|
||||
// Open navigation side bar
|
||||
await page.getByTestId('project-sidebar-toggle').click()
|
||||
const goToHome = page.getByRole('button', {
|
||||
name: 'Go to Home',
|
||||
})
|
||||
|
||||
await goToHome.click()
|
||||
await homePage.openProject('testDefault')
|
||||
await expect(page.getByText('323.49')).not.toBeVisible()
|
||||
})
|
||||
})
|
||||
|
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 74 KiB After Width: | Height: | Size: 74 KiB |
Before Width: | Height: | Size: 66 KiB After Width: | Height: | Size: 66 KiB |
Before Width: | Height: | Size: 145 KiB After Width: | Height: | Size: 145 KiB |
Before Width: | Height: | Size: 129 KiB After Width: | Height: | Size: 129 KiB |
Before Width: | Height: | Size: 54 KiB After Width: | Height: | Size: 54 KiB |
Before Width: | Height: | Size: 48 KiB After Width: | Height: | Size: 48 KiB |
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 47 KiB |
@ -69,7 +69,6 @@ test.describe('Testing in-app sample loading', () => {
|
||||
await confirmButton.click()
|
||||
|
||||
await editor.expectEditor.toContain('// ' + newSample.title)
|
||||
await expect(unitsToast('in')).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
||||
@ -158,7 +157,6 @@ test.describe('Testing in-app sample loading', () => {
|
||||
await editor.expectEditor.toContain('// ' + sampleOne.title)
|
||||
await expect(newlyCreatedFile(sampleOne.file)).toBeVisible()
|
||||
await expect(projectMenuButton).toContainText(sampleOne.file)
|
||||
await expect(unitsToast('in')).toBeVisible()
|
||||
})
|
||||
|
||||
await test.step(`Now overwrite the current file`, async () => {
|
||||
@ -188,7 +186,6 @@ test.describe('Testing in-app sample loading', () => {
|
||||
await expect(newlyCreatedFile(sampleOne.file)).toBeVisible()
|
||||
await expect(newlyCreatedFile(sampleTwo.file)).not.toBeVisible()
|
||||
await expect(projectMenuButton).toContainText(sampleOne.file)
|
||||
await expect(unitsToast('mm')).toBeVisible()
|
||||
})
|
||||
}
|
||||
)
|
||||
|
@ -75,3 +75,6 @@ publish:
|
||||
channel: latest
|
||||
releaseInfo:
|
||||
releaseNotesFile: release-notes.md
|
||||
protocols:
|
||||
- name: Zoo Studio
|
||||
schemes: ['zoo-studio']
|
||||
|
@ -9,23 +9,8 @@ const rootDir = process.cwd()
|
||||
const config: ForgeConfig = {
|
||||
packagerConfig: {
|
||||
asar: true,
|
||||
osxSign: (process.env.BUILD_RELEASE === 'true' && {}) || undefined,
|
||||
osxNotarize:
|
||||
(process.env.BUILD_RELEASE === 'true' && {
|
||||
appleId: process.env.APPLE_ID || '',
|
||||
appleIdPassword: process.env.APPLE_PASSWORD || '',
|
||||
teamId: process.env.APPLE_TEAM_ID || '',
|
||||
}) ||
|
||||
undefined,
|
||||
executableName: 'zoo-modeling-app',
|
||||
icon: path.resolve(rootDir, 'assets', 'icon'),
|
||||
protocols: [
|
||||
{
|
||||
name: 'Zoo Studio',
|
||||
schemes: ['zoo-studio'],
|
||||
},
|
||||
],
|
||||
extendInfo: 'Info.plist', // Information for file associations.
|
||||
},
|
||||
rebuildConfig: {},
|
||||
makers: [],
|
||||
|
1
interface.d.ts
vendored
@ -65,6 +65,7 @@ export interface IElectronAPI {
|
||||
VITE_KC_API_WS_MODELING_URL: string
|
||||
VITE_KC_API_BASE_URL: string
|
||||
VITE_KC_SITE_BASE_URL: string
|
||||
VITE_KC_SITE_APP_URL: string
|
||||
VITE_KC_SKIP_AUTH: string
|
||||
VITE_KC_CONNECTION_TIMEOUT_MS: string
|
||||
VITE_KC_DEV_TOKEN: string
|
||||
|
16
package.json
@ -103,11 +103,11 @@
|
||||
"make:dev": "make dev",
|
||||
"generate:machine-api": "npx openapi-typescript ./openapi/machine-api.json -o src/lib/machine-api.d.ts",
|
||||
"tron:start": "electron-forge start",
|
||||
"tron:package": "electron-forge package",
|
||||
"chrome:test": "PLATFORM=web NODE_ENV=development yarn playwright test --config=playwright.config.ts --project='Google Chrome' --grep-invert='@snapshot'",
|
||||
"tron:test": "NODE_ENV=development yarn playwright test --config=playwright.electron.config.ts --grep-invert='@snapshot'",
|
||||
"tronb:vite": "vite build -c vite.main.config.ts && vite build -c vite.preload.config.ts && vite build -c vite.renderer.config.ts",
|
||||
"tronb:package": "electron-builder --config electron-builder.yml",
|
||||
"tronb:vite:dev": "vite build -c vite.main.config.ts -m development && vite build -c vite.preload.config.ts -m development && vite build -c vite.renderer.config.ts -m development",
|
||||
"tronb:vite:prod": "vite build -c vite.main.config.ts && vite build -c vite.preload.config.ts && vite build -c vite.renderer.config.ts",
|
||||
"tronb:package:dev": "yarn tronb:vite:dev && electron-builder --config electron-builder.yml",
|
||||
"tronb:package:prod": "yarn tronb:vite:prod && electron-builder --config electron-builder.yml --publish always",
|
||||
"test-setup": "yarn install && yarn build:wasm",
|
||||
"test": "vitest --mode development",
|
||||
"test:unit": "vitest run --mode development --exclude **/kclSamples.test.ts",
|
||||
@ -116,10 +116,10 @@
|
||||
"test:playwright:electron:windows": "playwright test --config=playwright.electron.config.ts --grep-invert=\"@skipWin|@snapshot\" --quiet",
|
||||
"test:playwright:electron:macos": "playwright test --config=playwright.electron.config.ts --grep-invert='@skipMacos|@snapshot' --quiet",
|
||||
"test:playwright:electron:ubuntu": "playwright test --config=playwright.electron.config.ts --grep-invert='@skipLinux|@snapshot' --quiet",
|
||||
"test:playwright:electron:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@snapshot'",
|
||||
"test:playwright:electron:windows:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert=\"@skipWin|@snapshot\"",
|
||||
"test:playwright:electron:macos:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipMacos|@snapshot'",
|
||||
"test:playwright:electron:ubuntu:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipLinux|@snapshot'",
|
||||
"test:playwright:electron:local": "yarn tronb:package:dev && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@snapshot'",
|
||||
"test:playwright:electron:windows:local": "yarn tronb:package:dev && set NODE_ENV='development' && playwright test --config=playwright.electron.config.ts --grep-invert=\"@skipWin|@snapshot\"",
|
||||
"test:playwright:electron:macos:local": "yarn tronb:package:dev && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipMacos|@snapshot'",
|
||||
"test:playwright:electron:ubuntu:local": "yarn tronb:package:dev && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipLinux|@snapshot'",
|
||||
"test:unit:local": "yarn simpleserver:bg && yarn test:unit; kill-port 3000",
|
||||
"test:unit:kcl-samples:local": "yarn simpleserver:bg && yarn test:unit:kcl-samples; kill-port 3000"
|
||||
},
|
||||
|
39
src/App.tsx
@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useHotKeyListener } from './hooks/useHotKeyListener'
|
||||
import { Stream } from './components/Stream'
|
||||
import { AppHeader } from './components/AppHeader'
|
||||
@ -24,7 +24,12 @@ import { UnitsMenu } from 'components/UnitsMenu'
|
||||
import { CameraProjectionToggle } from 'components/CameraProjectionToggle'
|
||||
import { useCreateFileLinkQuery } from 'hooks/useCreateFileLinkQueryWatcher'
|
||||
import { maybeWriteToDisk } from 'lib/telemetry'
|
||||
import { takeScreenshotOfVideoStreamCanvas } from 'lib/screenshot'
|
||||
import { writeProjectThumbnailFile } from 'lib/desktop'
|
||||
import { useRouteLoaderData } from 'react-router-dom'
|
||||
import { useEngineCommands } from 'components/EngineCommands'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
maybeWriteToDisk()
|
||||
.then(() => {})
|
||||
.catch(() => {})
|
||||
@ -54,14 +59,20 @@ export function App() {
|
||||
|
||||
const projectName = project?.name || null
|
||||
const projectPath = project?.path || null
|
||||
|
||||
const [commands] = useEngineCommands()
|
||||
const [capturedCanvas, setCapturedCanvas] = useState(false)
|
||||
const loaderData = useRouteLoaderData(PATHS.FILE) as IndexLoaderData
|
||||
const lastCommandType = commands[commands.length - 1]?.type
|
||||
|
||||
useEffect(() => {
|
||||
onProjectOpen({ name: projectName, path: projectPath }, file || null)
|
||||
}, [projectName, projectPath])
|
||||
|
||||
useHotKeyListener()
|
||||
|
||||
const { auth, settings } = useSettingsAuthContext()
|
||||
const token = auth?.context?.token
|
||||
const { settings } = useSettingsAuthContext()
|
||||
const token = useToken()
|
||||
|
||||
const coreDumpManager = useMemo(
|
||||
() => new CoreDumpManager(engineCommandManager, codeManager, token),
|
||||
@ -91,6 +102,28 @@ export function App() {
|
||||
|
||||
useEngineConnectionSubscriptions()
|
||||
|
||||
// Generate thumbnail.png when loading the app
|
||||
useEffect(() => {
|
||||
if (!capturedCanvas && lastCommandType === 'execution-done') {
|
||||
setTimeout(() => {
|
||||
const projectDirectoryWithoutEndingSlash = loaderData?.project?.path
|
||||
if (!projectDirectoryWithoutEndingSlash) {
|
||||
return
|
||||
}
|
||||
const dataUrl: string = takeScreenshotOfVideoStreamCanvas()
|
||||
// zoom to fit command does not wait, wait 500ms to see if zoom to fit finishes
|
||||
writeProjectThumbnailFile(dataUrl, projectDirectoryWithoutEndingSlash)
|
||||
.then(() => {})
|
||||
.catch((e) => {
|
||||
console.error(
|
||||
`Failed to generate thumbnail for ${projectDirectoryWithoutEndingSlash}`
|
||||
)
|
||||
console.error(e)
|
||||
})
|
||||
}, 500)
|
||||
}
|
||||
}, [lastCommandType])
|
||||
|
||||
return (
|
||||
<div className="relative h-full flex flex-col" ref={ref}>
|
||||
<AppHeader
|
||||
|
@ -1,10 +1,10 @@
|
||||
import { useAuthState } from 'machines/appMachine'
|
||||
import Loading from './components/Loading'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
|
||||
// Wrapper around protected routes, used in src/Router.tsx
|
||||
export const Auth = ({ children }: React.PropsWithChildren) => {
|
||||
const { auth } = useSettingsAuthContext()
|
||||
const isLoggingIn = auth?.state.matches('checkIfLoggedIn')
|
||||
const authState = useAuthState()
|
||||
const isLoggingIn = authState.matches('checkIfLoggedIn')
|
||||
|
||||
return isLoggingIn ? (
|
||||
<Loading>
|
||||
|
@ -37,7 +37,6 @@ import { KclContextProvider } from 'lang/KclProvider'
|
||||
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'
|
||||
import useHotkeyWrapper from 'lib/hotkeyWrapper'
|
||||
import toast from 'react-hot-toast'
|
||||
import { coreDump } from 'lang/wasm'
|
||||
@ -47,6 +46,7 @@ import { reportRejection } from 'lib/trap'
|
||||
import { RouteProvider } from 'components/RouteProvider'
|
||||
import { ProjectsContextProvider } from 'components/ProjectsContextProvider'
|
||||
import { OpenInDesktopAppHandler } from 'components/OpenInDesktopAppHandler'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
|
||||
const createRouter = isDesktop() ? createHashRouter : createBrowserRouter
|
||||
|
||||
@ -203,8 +203,7 @@ export const Router = () => {
|
||||
}
|
||||
|
||||
function CoreDump() {
|
||||
const { auth } = useSettingsAuthContext()
|
||||
const token = auth?.context?.token
|
||||
const token = useToken()
|
||||
const coreDumpManager = useMemo(
|
||||
() => new CoreDumpManager(engineCommandManager, codeManager, token),
|
||||
[]
|
||||
|
@ -29,6 +29,7 @@ import * as TWEEN from '@tweenjs/tween.js'
|
||||
import { isQuaternionVertical } from './helpers'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
import { CameraProjectionType } from 'wasm-lib/kcl/bindings/CameraProjectionType'
|
||||
import { CameraDragInteractionType_type } from '@kittycad/lib/dist/types/src/models'
|
||||
|
||||
const ORTHOGRAPHIC_CAMERA_SIZE = 20
|
||||
const FRAMES_TO_ANIMATE_IN = 30
|
||||
@ -406,7 +407,7 @@ export class CameraControls {
|
||||
.sub(this.mouseDownPosition)
|
||||
this.mouseDownPosition.copy(this.mouseNewPosition)
|
||||
|
||||
const interaction = this.getInteractionType(event)
|
||||
let interaction = this.getInteractionType(event)
|
||||
if (interaction === 'none') return
|
||||
|
||||
// If there's a valid interaction and the mouse is moving,
|
||||
@ -753,8 +754,6 @@ export class CameraControls {
|
||||
didChange = true
|
||||
}
|
||||
|
||||
this.safeLookAtTarget(this.camera.up)
|
||||
|
||||
// Update the camera's matrices
|
||||
this.camera.updateMatrixWorld()
|
||||
if (didChange || forceUpdate) {
|
||||
@ -1189,14 +1188,24 @@ export class CameraControls {
|
||||
this.deferReactUpdate(this.reactCameraProperties)
|
||||
Object.values(this._camChangeCallbacks).forEach((cb) => cb())
|
||||
}
|
||||
getInteractionType = (event: MouseEvent) =>
|
||||
_getInteractionType(
|
||||
getInteractionType = (
|
||||
event: MouseEvent
|
||||
): CameraDragInteractionType_type | 'none' => {
|
||||
const initialInteractionType = _getInteractionType(
|
||||
this.interactionGuards,
|
||||
event,
|
||||
this.enablePan,
|
||||
this.enableRotate,
|
||||
this.enableZoom
|
||||
)
|
||||
if (
|
||||
initialInteractionType === 'rotate' &&
|
||||
this.engineCommandManager.settings.cameraOrbit === 'trackball'
|
||||
) {
|
||||
return 'rotatetrackball'
|
||||
}
|
||||
return initialInteractionType
|
||||
}
|
||||
}
|
||||
|
||||
// Pure function helpers
|
||||
|
@ -124,6 +124,14 @@ export const ClientSideScene = ({
|
||||
'mouseup',
|
||||
toSync(sceneInfra.onMouseUp, reportRejection)
|
||||
)
|
||||
sceneEntitiesManager
|
||||
.tearDownSketch()
|
||||
.then(() => {
|
||||
// no op
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
|
||||
|
@ -2,11 +2,11 @@ import { Toolbar } from '../Toolbar'
|
||||
import UserSidebarMenu from 'components/UserSidebarMenu'
|
||||
import { type IndexLoaderData } from 'lib/types'
|
||||
import ProjectSidebarMenu from './ProjectSidebarMenu'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import styles from './AppHeader.module.css'
|
||||
import { RefreshButton } from 'components/RefreshButton'
|
||||
import { CommandBarOpenButton } from './CommandBarOpenButton'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { useUser } from 'machines/appMachine'
|
||||
|
||||
interface AppHeaderProps extends React.PropsWithChildren {
|
||||
showToolbar?: boolean
|
||||
@ -24,8 +24,7 @@ export const AppHeader = ({
|
||||
style,
|
||||
enableMenu = false,
|
||||
}: AppHeaderProps) => {
|
||||
const { auth } = useSettingsAuthContext()
|
||||
const user = auth?.context?.user
|
||||
const user = useUser()
|
||||
|
||||
return (
|
||||
<header
|
||||
|
@ -98,6 +98,7 @@ export const CommandBar = () => {
|
||||
'fixed inset-0 z-50 overflow-y-auto pb-4 pt-1 ' +
|
||||
(isSelectionArgument ? 'pointer-events-none' : '')
|
||||
}
|
||||
data-testid="command-bar-wrapper"
|
||||
>
|
||||
<Transition.Child
|
||||
enter="duration-100 ease-out"
|
||||
|
@ -30,6 +30,7 @@ import {
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import { markOnce } from 'lib/performance'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
|
||||
type MachineContext<T extends AnyStateMachine> = {
|
||||
state: StateFrom<T>
|
||||
@ -47,7 +48,8 @@ export const FileMachineProvider = ({
|
||||
children: React.ReactNode
|
||||
}) => {
|
||||
const navigate = useNavigate()
|
||||
const { settings, auth } = useSettingsAuthContext()
|
||||
const { settings } = useSettingsAuthContext()
|
||||
const token = useToken()
|
||||
const projectData = useRouteLoaderData(PATHS.FILE) as IndexLoaderData
|
||||
const { project, file } = projectData
|
||||
const [kclSamples, setKclSamples] = React.useState<KclSamplesManifestItem[]>(
|
||||
@ -297,7 +299,7 @@ export const FileMachineProvider = ({
|
||||
const kclCommandMemo = useMemo(
|
||||
() =>
|
||||
kclCommands({
|
||||
authToken: auth?.context?.token ?? '',
|
||||
authToken: token ?? '',
|
||||
projectData,
|
||||
settings: {
|
||||
defaultUnit: settings?.context?.modeling.defaultUnit.current ?? 'mm',
|
||||
|
@ -27,6 +27,7 @@ import { PROJECT_ENTRYPOINT } from 'lib/constants'
|
||||
import { err } from 'lib/trap'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { codeManager } from 'lib/singletons'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
|
||||
function getWorkspaceFolders(): LSP.WorkspaceFolder[] {
|
||||
return []
|
||||
@ -69,8 +70,7 @@ export const LspProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const [isKclLspReady, setIsKclLspReady] = useState(false)
|
||||
const [isCopilotLspReady, setIsCopilotLspReady] = useState(false)
|
||||
|
||||
const { auth } = useSettingsAuthContext()
|
||||
const token = auth?.context.token
|
||||
const token = useToken()
|
||||
const navigate = useNavigate()
|
||||
|
||||
// So this is a bit weird, we need to initialize the lsp server and client.
|
||||
|
@ -1,10 +1,8 @@
|
||||
import { useEngineCommands } from './EngineCommands'
|
||||
import { Spinner } from './Spinner'
|
||||
import { CustomIcon } from './CustomIcon'
|
||||
|
||||
export const ModelStateIndicator = () => {
|
||||
const [commands] = useEngineCommands()
|
||||
|
||||
const lastCommandType = commands[commands.length - 1]?.type
|
||||
|
||||
let className = 'w-6 h-6 '
|
||||
|
@ -89,6 +89,7 @@ import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
import { promptToEditFlow } from 'lib/promptToEdit'
|
||||
import { kclEditorActor } from 'machines/kclEditorMachine'
|
||||
import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
|
||||
type MachineContext<T extends AnyStateMachine> = {
|
||||
state: StateFrom<T>
|
||||
@ -110,7 +111,6 @@ export const ModelingMachineProvider = ({
|
||||
children: React.ReactNode
|
||||
}) => {
|
||||
const {
|
||||
auth,
|
||||
settings: {
|
||||
context: {
|
||||
app: { theme, enableSSAO, allowOrbitInSketchMode },
|
||||
@ -119,6 +119,7 @@ export const ModelingMachineProvider = ({
|
||||
cameraProjection,
|
||||
highlightEdges,
|
||||
showScaleGrid,
|
||||
cameraOrbit,
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -127,7 +128,7 @@ export const ModelingMachineProvider = ({
|
||||
const navigate = useNavigate()
|
||||
const { context, send: fileMachineSend } = useFileContext()
|
||||
const { file } = useLoaderData() as IndexLoaderData
|
||||
const token = auth?.context?.token
|
||||
const token = useToken()
|
||||
const streamRef = useRef<HTMLDivElement>(null)
|
||||
const persistedContext = useMemo(() => getPersistedContext(), [])
|
||||
|
||||
@ -1154,6 +1155,7 @@ export const ModelingMachineProvider = ({
|
||||
enableSSAO: enableSSAO.current,
|
||||
showScaleGrid: showScaleGrid.current,
|
||||
cameraProjection: cameraProjection.current,
|
||||
cameraOrbit: cameraOrbit.current,
|
||||
},
|
||||
token
|
||||
)
|
||||
@ -1183,6 +1185,13 @@ export const ModelingMachineProvider = ({
|
||||
editorManager.selectionRanges = modelingState.context.selectionRanges
|
||||
}, [modelingState.context.selectionRanges])
|
||||
|
||||
// When changing camera modes reset the camera to the default orientation to correct
|
||||
// the up vector otherwise the conconical orientation for the camera modes will be
|
||||
// wrong
|
||||
useEffect(() => {
|
||||
sceneInfra.camControls.resetCameraPosition().catch(reportRejection)
|
||||
}, [cameraOrbit.current])
|
||||
|
||||
useEffect(() => {
|
||||
const onConnectionStateChanged = ({ detail }: CustomEvent) => {
|
||||
// If we are in sketch mode we need to exit it.
|
||||
|
@ -33,7 +33,7 @@ export const OpenInDesktopAppHandler = (props: React.PropsWithChildren) => {
|
||||
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(
|
||||
const newURL = `${ZOO_STUDIO_PROTOCOL}://${globalThis.location.pathname.replace(
|
||||
'/',
|
||||
''
|
||||
)}${searchParams.size > 0 ? `?${newSearchParams.toString()}` : ''}`
|
||||
|
@ -2,7 +2,7 @@ import { FormEvent, useEffect, useRef, useState } from 'react'
|
||||
import { PATHS } from 'lib/paths'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { ActionButton } from '../ActionButton'
|
||||
import { FILE_EXT } from 'lib/constants'
|
||||
import { FILE_EXT, PROJECT_IMAGE_NAME } from 'lib/constants'
|
||||
import { useHotkeys } from 'react-hotkeys-hook'
|
||||
import Tooltip from '../Tooltip'
|
||||
import { DeleteConfirmationDialog } from './DeleteProjectDialog'
|
||||
@ -29,7 +29,7 @@ function ProjectCard({
|
||||
const [isConfirmingDelete, setIsConfirmingDelete] = useState(false)
|
||||
const [numberOfFiles, setNumberOfFiles] = useState(1)
|
||||
const [numberOfFolders, setNumberOfFolders] = useState(0)
|
||||
// const [imageUrl, setImageUrl] = useState('')
|
||||
const [imageUrl, setImageUrl] = useState('')
|
||||
|
||||
let inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
@ -53,18 +53,21 @@ function ProjectCard({
|
||||
setNumberOfFolders(project.directory_count)
|
||||
}
|
||||
|
||||
// async function setupImageUrl() {
|
||||
// const projectImagePath = await join(project.file.path, PROJECT_IMAGE_NAME)
|
||||
// if (await exists(projectImagePath)) {
|
||||
// const imageData = await readFile(projectImagePath)
|
||||
// const blob = new Blob([imageData], { type: 'image/jpg' })
|
||||
// const imageUrl = URL.createObjectURL(blob)
|
||||
// setImageUrl(imageUrl)
|
||||
// }
|
||||
// }
|
||||
async function setupImageUrl() {
|
||||
const projectImagePath = window.electron.path.join(
|
||||
project.path,
|
||||
PROJECT_IMAGE_NAME
|
||||
)
|
||||
if (await window.electron.exists(projectImagePath)) {
|
||||
const imageData = await window.electron.readFile(projectImagePath)
|
||||
const blob = new Blob([imageData], { type: 'image/png' })
|
||||
const imageUrl = URL.createObjectURL(blob)
|
||||
setImageUrl(imageUrl)
|
||||
}
|
||||
}
|
||||
|
||||
void getNumberOfFiles()
|
||||
// void setupImageUrl()
|
||||
void setupImageUrl()
|
||||
}, [project.kcl_file_count, project.directory_count])
|
||||
|
||||
useEffect(() => {
|
||||
@ -84,7 +87,7 @@ function ProjectCard({
|
||||
to={`${PATHS.FILE}/${encodeURIComponent(project.default_file)}`}
|
||||
className="flex flex-col flex-1 !no-underline !text-chalkboard-110 dark:!text-chalkboard-10 group-hover:!hue-rotate-0 min-h-[5em] divide-y divide-primary/40 dark:divide-chalkboard-80 group-hover:!divide-primary"
|
||||
>
|
||||
{/* <div className="h-36 relative overflow-hidden bg-gradient-to-b from-transparent to-primary/10 rounded-t-sm">
|
||||
<div className="h-36 relative overflow-hidden bg-gradient-to-b from-transparent to-primary/10 rounded-t-sm">
|
||||
{imageUrl && (
|
||||
<img
|
||||
src={imageUrl}
|
||||
@ -92,7 +95,7 @@ function ProjectCard({
|
||||
className="h-full w-full transition-transform group-hover:scale-105 object-cover"
|
||||
/>
|
||||
)}
|
||||
</div> */}
|
||||
</div>
|
||||
<div className="pb-2 flex flex-col flex-grow flex-auto gap-2 rounded-b-sm">
|
||||
{isEditing ? (
|
||||
<ProjectCardRenameForm
|
||||
|
@ -19,7 +19,8 @@ import { commandBarActor } from 'machines/commandBarMachine'
|
||||
import { useSelector } from '@xstate/react'
|
||||
import { copyFileShareLink } from 'lib/links'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import { DEV } from 'env'
|
||||
import { IS_NIGHTLY_OR_DEBUG } from 'routes/Settings'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
|
||||
const ProjectSidebarMenu = ({
|
||||
project,
|
||||
@ -103,13 +104,15 @@ function ProjectMenuPopover({
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const filePath = useAbsoluteFilePath()
|
||||
const { settings, auth } = useSettingsAuthContext()
|
||||
const { settings } = useSettingsAuthContext()
|
||||
const token = useToken()
|
||||
const machineManager = useContext(MachineManagerContext)
|
||||
const commands = useSelector(commandBarActor, commandsSelector)
|
||||
|
||||
const { onProjectClose } = useLspContext()
|
||||
const exportCommandInfo = { name: 'Export', groupId: 'modeling' }
|
||||
const makeCommandInfo = { name: 'Make', groupId: 'modeling' }
|
||||
const shareCommandInfo = { name: 'share-file-link', groupId: 'code' }
|
||||
const findCommand = (obj: { name: string; groupId: string }) =>
|
||||
Boolean(
|
||||
commands.find((c) => c.name === obj.name && c.groupId === obj.groupId)
|
||||
@ -191,10 +194,10 @@ function ProjectMenuPopover({
|
||||
id: 'share-link',
|
||||
Element: 'button',
|
||||
children: 'Share link to file',
|
||||
disabled: !DEV,
|
||||
disabled: IS_NIGHTLY_OR_DEBUG || !findCommand(shareCommandInfo),
|
||||
onClick: async () => {
|
||||
await copyFileShareLink({
|
||||
token: auth?.context.token || '',
|
||||
token: token ?? '',
|
||||
code: codeManager.code,
|
||||
name: project?.name || '',
|
||||
units: settings.context.modeling.defaultUnit.current,
|
||||
|
@ -8,10 +8,10 @@ import Tooltip from './Tooltip'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
import { toSync } from 'lib/utils'
|
||||
import { useToken } from 'machines/appMachine'
|
||||
|
||||
export const RefreshButton = ({ children }: React.PropsWithChildren) => {
|
||||
const { auth } = useSettingsAuthContext()
|
||||
const token = auth?.context?.token
|
||||
const token = useToken()
|
||||
const coreDumpManager = useMemo(
|
||||
() => new CoreDumpManager(engineCommandManager, codeManager, token),
|
||||
[]
|
||||
|
@ -2,13 +2,16 @@ import { useEffect, useState, createContext, ReactNode } from 'react'
|
||||
import { useNavigation, useLocation } from 'react-router-dom'
|
||||
import { PATHS } from 'lib/paths'
|
||||
import { markOnce } from 'lib/performance'
|
||||
import { useAuthNavigation } from 'hooks/useAuthNavigation'
|
||||
|
||||
export const RouteProviderContext = createContext({})
|
||||
|
||||
export function RouteProvider({ children }: { children: ReactNode }) {
|
||||
useAuthNavigation()
|
||||
const [first, setFirstState] = useState(true)
|
||||
const navigation = useNavigation()
|
||||
const location = useLocation()
|
||||
|
||||
useEffect(() => {
|
||||
// On initialization, the react-router-dom does not send a 'loading' state event.
|
||||
// it sends an idle event first.
|
||||
|
@ -2,10 +2,7 @@ import { trap } from 'lib/trap'
|
||||
import { useMachine, useSelector } from '@xstate/react'
|
||||
import { useNavigate, useRouteLoaderData, useLocation } from 'react-router-dom'
|
||||
import { PATHS, BROWSER_PATH } from 'lib/paths'
|
||||
import { authMachine, TOKEN_PERSIST_KEY } from '../machines/authMachine'
|
||||
import withBaseUrl from '../lib/withBaseURL'
|
||||
import React, { createContext, useEffect, useState } from 'react'
|
||||
import useStateMachineCommands from '../hooks/useStateMachineCommands'
|
||||
import { settingsMachine } from 'machines/settingsMachine'
|
||||
import { toast } from 'react-hot-toast'
|
||||
import {
|
||||
@ -16,7 +13,6 @@ import {
|
||||
} from 'lib/theme'
|
||||
import decamelize from 'decamelize'
|
||||
import { Actor, AnyStateMachine, ContextFrom, Prop, StateFrom } from 'xstate'
|
||||
import { authCommandBarConfig } from 'lib/commandBarConfigs/authCommandConfig'
|
||||
import {
|
||||
kclManager,
|
||||
sceneInfra,
|
||||
@ -50,7 +46,6 @@ type MachineContext<T extends AnyStateMachine> = {
|
||||
}
|
||||
|
||||
type SettingsAuthContextType = {
|
||||
auth: MachineContext<typeof authMachine>
|
||||
settings: MachineContext<typeof settingsMachine>
|
||||
}
|
||||
|
||||
@ -370,40 +365,9 @@ export const SettingsAuthProviderBase = ({
|
||||
)
|
||||
}, [settingsState.context.textEditor.blinkingCursor.current])
|
||||
|
||||
// Auth machine setup
|
||||
const [authState, authSend, authActor] = useMachine(
|
||||
authMachine.provide({
|
||||
actions: {
|
||||
goToSignInPage: () => {
|
||||
navigate(PATHS.SIGN_IN)
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
logout()
|
||||
},
|
||||
goToIndexPage: () => {
|
||||
if (location.pathname.includes(PATHS.SIGN_IN)) {
|
||||
navigate(PATHS.INDEX)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
useStateMachineCommands({
|
||||
machineId: 'auth',
|
||||
state: authState,
|
||||
send: authSend,
|
||||
commandBarConfig: authCommandBarConfig,
|
||||
actor: authActor,
|
||||
})
|
||||
|
||||
return (
|
||||
<SettingsAuthContext.Provider
|
||||
value={{
|
||||
auth: {
|
||||
state: authState,
|
||||
context: authState.context,
|
||||
send: authSend,
|
||||
},
|
||||
settings: {
|
||||
state: settingsState,
|
||||
context: settingsState.context,
|
||||
@ -417,12 +381,3 @@ export const SettingsAuthProviderBase = ({
|
||||
}
|
||||
|
||||
export default SettingsAuthProvider
|
||||
|
||||
export async function logout() {
|
||||
localStorage.removeItem(TOKEN_PERSIST_KEY)
|
||||
if (isDesktop()) return Promise.resolve(null)
|
||||
return fetch(withBaseUrl('/logout'), {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
})
|
||||
}
|
||||
|
@ -4,12 +4,12 @@ import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { Fragment, useMemo, useState } from 'react'
|
||||
import { PATHS } from 'lib/paths'
|
||||
import { Models } from '@kittycad/lib'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import { useAbsoluteFilePath } from 'hooks/useAbsoluteFilePath'
|
||||
import Tooltip from './Tooltip'
|
||||
import usePlatform from 'hooks/usePlatform'
|
||||
import { isDesktop } from 'lib/isDesktop'
|
||||
import { CustomIcon } from './CustomIcon'
|
||||
import { authActor } from 'machines/appMachine'
|
||||
|
||||
type User = Models['User_type']
|
||||
|
||||
@ -20,7 +20,7 @@ const UserSidebarMenu = ({ user }: { user?: User }) => {
|
||||
const displayedName = getDisplayName(user)
|
||||
const [imageLoadFailed, setImageLoadFailed] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
const send = useSettingsAuthContext()?.auth?.send
|
||||
const send = authActor.send
|
||||
|
||||
// We filter this memoized list so that no orphan "break" elements are rendered.
|
||||
const userMenuItems = useMemo<(ActionButtonProps | 'break')[]>(
|
||||
|
@ -10,6 +10,7 @@ export const VITE_KC_API_WS_MODELING_URL = env.VITE_KC_API_WS_MODELING_URL as
|
||||
| undefined
|
||||
export const VITE_KC_API_BASE_URL = env.VITE_KC_API_BASE_URL as string
|
||||
export const VITE_KC_SITE_BASE_URL = env.VITE_KC_SITE_BASE_URL as string
|
||||
export const VITE_KC_SITE_APP_URL = env.VITE_KC_SITE_APP_URL as string
|
||||
export const VITE_KC_SKIP_AUTH = env.VITE_KC_SKIP_AUTH as string | undefined
|
||||
export const VITE_KC_CONNECTION_TIMEOUT_MS =
|
||||
env.VITE_KC_CONNECTION_TIMEOUT_MS as string | undefined
|
||||
|
29
src/hooks/useAuthNavigation.tsx
Normal file
@ -0,0 +1,29 @@
|
||||
import { PATHS } from 'lib/paths'
|
||||
import { useAuthState } from 'machines/appMachine'
|
||||
import { useEffect } from 'react'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
|
||||
/**
|
||||
* A simple hook that listens to the auth state of the app and navigates
|
||||
* accordingly.
|
||||
*/
|
||||
export function useAuthNavigation() {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const authState = useAuthState()
|
||||
|
||||
// Subscribe to the auth state of the app and navigate accordingly.
|
||||
useEffect(() => {
|
||||
if (
|
||||
authState.matches('loggedIn') &&
|
||||
location.pathname.includes(PATHS.SIGN_IN)
|
||||
) {
|
||||
navigate(PATHS.INDEX)
|
||||
} else if (
|
||||
authState.matches('loggedOut') &&
|
||||
!location.pathname.includes(PATHS.SIGN_IN)
|
||||
) {
|
||||
navigate(PATHS.SIGN_IN)
|
||||
}
|
||||
}, [authState])
|
||||
}
|
@ -16,14 +16,15 @@ export function useSetupEngineManager(
|
||||
streamRef: React.RefObject<HTMLDivElement>,
|
||||
modelingSend: ReturnType<typeof useModelingContext>['send'],
|
||||
modelingContext: ReturnType<typeof useModelingContext>['context'],
|
||||
settings = {
|
||||
settings: SettingsViaQueryString = {
|
||||
pool: null,
|
||||
theme: Themes.System,
|
||||
highlightEdges: true,
|
||||
enableSSAO: true,
|
||||
showScaleGrid: false,
|
||||
cameraProjection: 'perspective',
|
||||
} as SettingsViaQueryString,
|
||||
cameraOrbit: 'spherical',
|
||||
},
|
||||
token?: string
|
||||
) {
|
||||
const networkContext = useNetworkContext()
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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()
|
||||
|
||||
|
@ -5,6 +5,8 @@ import {
|
||||
Identifier,
|
||||
SourceRange,
|
||||
topLevelRange,
|
||||
LiteralValue,
|
||||
Literal,
|
||||
} from './wasm'
|
||||
import {
|
||||
createLiteral,
|
||||
@ -37,10 +39,26 @@ beforeAll(async () => {
|
||||
})
|
||||
|
||||
describe('Testing createLiteral', () => {
|
||||
it('should create a literal', () => {
|
||||
it('should create a literal number without units', () => {
|
||||
const result = createLiteral(5)
|
||||
expect(result.type).toBe('Literal')
|
||||
expect((result as any).value.value).toBe(5)
|
||||
expect((result as any).value.suffix).toBe('None')
|
||||
expect((result as Literal).raw).toBe('5')
|
||||
})
|
||||
it('should create a literal number with units', () => {
|
||||
const lit: LiteralValue = { value: 5, suffix: 'Mm' }
|
||||
const result = createLiteral(lit)
|
||||
expect(result.type).toBe('Literal')
|
||||
expect((result as any).value.value).toBe(5)
|
||||
expect((result as any).value.suffix).toBe('Mm')
|
||||
expect((result as Literal).raw).toBe('5mm')
|
||||
})
|
||||
it('should create a literal boolean', () => {
|
||||
const result = createLiteral(false)
|
||||
expect(result.type).toBe('Literal')
|
||||
expect((result as Literal).value).toBe(false)
|
||||
expect((result as Literal).raw).toBe('false')
|
||||
})
|
||||
})
|
||||
describe('Testing createIdentifier', () => {
|
||||
|
@ -20,6 +20,7 @@ import {
|
||||
SourceRange,
|
||||
sketchFromKclValue,
|
||||
isPathToNodeNumber,
|
||||
formatNumber,
|
||||
} from './wasm'
|
||||
import {
|
||||
isNodeSafeToReplacePath,
|
||||
@ -743,11 +744,26 @@ export function splitPathAtPipeExpression(pathToNode: PathToNode): {
|
||||
return splitPathAtPipeExpression(pathToNode.slice(0, -1))
|
||||
}
|
||||
|
||||
/**
|
||||
* Note: This depends on WASM, but it's not async. Callers are responsible for
|
||||
* awaiting init of the WASM module.
|
||||
*/
|
||||
export function createLiteral(value: LiteralValue | number): Node<Literal> {
|
||||
const raw = `${value}`
|
||||
if (typeof value === 'number') {
|
||||
value = { value, suffix: 'None' }
|
||||
}
|
||||
let raw: string
|
||||
if (typeof value === 'string') {
|
||||
// TODO: Should we handle escape sequences?
|
||||
raw = `${value}`
|
||||
} else if (typeof value === 'boolean') {
|
||||
raw = `${value}`
|
||||
} else if (typeof value.value === 'number' && value.suffix === 'None') {
|
||||
// Fast path for numbers when there are no units.
|
||||
raw = `${value.value}`
|
||||
} else {
|
||||
raw = formatNumber(value.value, value.suffix)
|
||||
}
|
||||
return {
|
||||
type: 'Literal',
|
||||
start: 0,
|
||||
|
@ -5,7 +5,11 @@ import {
|
||||
PathToNode,
|
||||
Identifier,
|
||||
topLevelRange,
|
||||
PipeExpression,
|
||||
CallExpression,
|
||||
VariableDeclarator,
|
||||
} from './wasm'
|
||||
import { ProgramMemory } from 'lang/wasm'
|
||||
import {
|
||||
findAllPreviousVariables,
|
||||
isNodeSafeToReplace,
|
||||
@ -25,9 +29,11 @@ import {
|
||||
createCallExpression,
|
||||
createLiteral,
|
||||
createPipeSubstitution,
|
||||
createCallExpressionStdLib,
|
||||
} from './modifyAst'
|
||||
import { err } from 'lib/trap'
|
||||
import { codeRefFromRange } from './std/artifactGraph'
|
||||
import { addCallExpressionsToPipe, addCloseToPipe } from 'lang/std/sketch'
|
||||
|
||||
beforeAll(async () => {
|
||||
await initPromise
|
||||
@ -680,3 +686,115 @@ myNestedVar = [
|
||||
expect(pathToNode).toEqual(pathToNode2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Testing specific sketch getNodeFromPath workflow', () => {
|
||||
it('should parse the code', () => {
|
||||
const openSketch = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([0.02, 0.22], %)
|
||||
|> xLine(0.39, %)
|
||||
|> line([0.02, -0.17], %)
|
||||
|> yLine(-0.15, %)
|
||||
|> line([-0.21, -0.02], %)
|
||||
|> xLine(-0.15, %)
|
||||
|> line([-0.02, 0.21], %)
|
||||
|> line([-0.08, 0.05], %)`
|
||||
const ast = assertParse(openSketch)
|
||||
expect(ast.start).toEqual(0)
|
||||
expect(ast.end).toEqual(227)
|
||||
})
|
||||
it('should find the location to add new lineTo', () => {
|
||||
const openSketch = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([0.02, 0.22], %)
|
||||
|> xLine(0.39, %)
|
||||
|> line([0.02, -0.17], %)
|
||||
|> yLine(-0.15, %)
|
||||
|> line([-0.21, -0.02], %)
|
||||
|> xLine(-0.15, %)
|
||||
|> line([-0.02, 0.21], %)
|
||||
|> line([-0.08, 0.05], %)`
|
||||
const ast = assertParse(openSketch)
|
||||
|
||||
const sketchSnippet = `startProfileAt([0.02, 0.22], %)`
|
||||
const sketchRange = topLevelRange(
|
||||
openSketch.indexOf(sketchSnippet),
|
||||
openSketch.indexOf(sketchSnippet) + sketchSnippet.length
|
||||
)
|
||||
const sketchPathToNode = getNodePathFromSourceRange(ast, sketchRange)
|
||||
const modifiedAst = addCallExpressionsToPipe({
|
||||
node: ast,
|
||||
programMemory: ProgramMemory.empty(),
|
||||
pathToNode: sketchPathToNode,
|
||||
expressions: [
|
||||
createCallExpressionStdLib(
|
||||
'lineTo', // We are forcing lineTo!
|
||||
[
|
||||
createArrayExpression([
|
||||
createCallExpressionStdLib('profileStartX', [
|
||||
createPipeSubstitution(),
|
||||
]),
|
||||
createCallExpressionStdLib('profileStartY', [
|
||||
createPipeSubstitution(),
|
||||
]),
|
||||
]),
|
||||
createPipeSubstitution(),
|
||||
]
|
||||
),
|
||||
],
|
||||
})
|
||||
if (err(modifiedAst)) throw modifiedAst
|
||||
const recasted = recast(modifiedAst)
|
||||
const expectedCode = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([0.02, 0.22], %)
|
||||
|> xLine(0.39, %)
|
||||
|> line([0.02, -0.17], %)
|
||||
|> yLine(-0.15, %)
|
||||
|> line([-0.21, -0.02], %)
|
||||
|> xLine(-0.15, %)
|
||||
|> line([-0.02, 0.21], %)
|
||||
|> line([-0.08, 0.05], %)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
`
|
||||
expect(recasted).toEqual(expectedCode)
|
||||
})
|
||||
it('it should find the location to add close', () => {
|
||||
const openSketch = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([0.02, 0.22], %)
|
||||
|> xLine(0.39, %)
|
||||
|> line([0.02, -0.17], %)
|
||||
|> yLine(-0.15, %)
|
||||
|> line([-0.21, -0.02], %)
|
||||
|> xLine(-0.15, %)
|
||||
|> line([-0.02, 0.21], %)
|
||||
|> line([-0.08, 0.05], %)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
`
|
||||
const ast = assertParse(openSketch)
|
||||
const sketchSnippet = `startProfileAt([0.02, 0.22], %)`
|
||||
const sketchRange = topLevelRange(
|
||||
openSketch.indexOf(sketchSnippet),
|
||||
openSketch.indexOf(sketchSnippet) + sketchSnippet.length
|
||||
)
|
||||
const sketchPathToNode = getNodePathFromSourceRange(ast, sketchRange)
|
||||
const modifiedAst = addCloseToPipe({
|
||||
node: ast,
|
||||
programMemory: ProgramMemory.empty(),
|
||||
pathToNode: sketchPathToNode,
|
||||
})
|
||||
|
||||
if (err(modifiedAst)) throw modifiedAst
|
||||
const recasted = recast(modifiedAst)
|
||||
const expectedCode = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([0.02, 0.22], %)
|
||||
|> xLine(0.39, %)
|
||||
|> line([0.02, -0.17], %)
|
||||
|> yLine(-0.15, %)
|
||||
|> line([-0.21, -0.02], %)
|
||||
|> xLine(-0.15, %)
|
||||
|> line([-0.02, 0.21], %)
|
||||
|> line([-0.08, 0.05], %)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
`
|
||||
expect(recasted).toEqual(expectedCode)
|
||||
})
|
||||
})
|
||||
|
@ -21,6 +21,7 @@ import {
|
||||
topLevelRange,
|
||||
VariableDeclaration,
|
||||
VariableDeclarator,
|
||||
recast,
|
||||
} from './wasm'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { createIdentifier, splitPathAtLastIndex } from './modifyAst'
|
||||
@ -68,7 +69,28 @@ export function getNodeFromPath<T>(
|
||||
deepPath: successfulPaths,
|
||||
}
|
||||
}
|
||||
return new Error('not an object')
|
||||
const stackTraceError = new Error()
|
||||
const sourceCode = recast(node)
|
||||
const levels = stackTraceError.stack?.split('\n')
|
||||
const aFewFunctionNames: string[] = []
|
||||
let tree = ''
|
||||
levels?.forEach((val, index) => {
|
||||
const fnName = val.trim().split(' ')[1]
|
||||
const ending = index === levels.length - 1 ? ' ' : ' > '
|
||||
tree += fnName + ending
|
||||
if (index < 3) {
|
||||
aFewFunctionNames.push(fnName)
|
||||
}
|
||||
})
|
||||
const error = new Error(
|
||||
`Failed to stopAt ${stopAt}, ${aFewFunctionNames
|
||||
.filter((a) => a)
|
||||
.join(' > ')}`
|
||||
)
|
||||
console.error(tree)
|
||||
console.error(sourceCode)
|
||||
console.error(error.stack)
|
||||
return error
|
||||
}
|
||||
currentNode = currentNode?.[pathItem[0]]
|
||||
successfulPaths.push(pathItem)
|
||||
|
@ -1389,6 +1389,7 @@ export class EngineCommandManager extends EventTarget {
|
||||
enableSSAO: true,
|
||||
showScaleGrid: false,
|
||||
cameraProjection: 'perspective',
|
||||
cameraOrbit: 'spherical',
|
||||
}
|
||||
}
|
||||
|
||||
@ -1437,6 +1438,7 @@ export class EngineCommandManager extends EventTarget {
|
||||
enableSSAO: true,
|
||||
showScaleGrid: false,
|
||||
cameraProjection: 'orthographic',
|
||||
cameraOrbit: 'spherical',
|
||||
},
|
||||
// When passed, use a completely separate connecting code path that simply
|
||||
// opens a websocket and this is a function that is called when connected.
|
||||
@ -1999,7 +2001,7 @@ export class EngineCommandManager extends EventTarget {
|
||||
.catch((e) => {
|
||||
// TODO: Previously was never caught, we are not rejecting these pendingCommands but this needs to be handled at some point.
|
||||
/*noop*/
|
||||
return null
|
||||
return e
|
||||
})
|
||||
}
|
||||
/**
|
||||
|
@ -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))
|
||||
}
|
||||
|
||||
|
@ -6,6 +6,8 @@ import {
|
||||
ArrayExpression,
|
||||
BinaryExpression,
|
||||
ArtifactGraph,
|
||||
LiteralValue,
|
||||
NumericSuffix,
|
||||
} from './wasm'
|
||||
import { filterArtifacts } from 'lang/std/artifactGraph'
|
||||
import { isOverlap } from 'lib/utils'
|
||||
@ -69,3 +71,15 @@ export function isLiteral(e: any): e is Literal {
|
||||
export function isBinaryExpression(e: any): e is BinaryExpression {
|
||||
return e && e.type === 'BinaryExpression'
|
||||
}
|
||||
|
||||
export function isLiteralValueNumber(
|
||||
e: LiteralValue
|
||||
): e is { value: number; suffix: NumericSuffix } {
|
||||
return (
|
||||
typeof e === 'object' &&
|
||||
'value' in e &&
|
||||
typeof e.value === 'number' &&
|
||||
'suffix' in e &&
|
||||
typeof e.suffix === 'string'
|
||||
)
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { err } from 'lib/trap'
|
||||
import { initPromise, parse, ParseResult } from './wasm'
|
||||
import { formatNumber, initPromise, parse, ParseResult } from './wasm'
|
||||
import { enginelessExecutor } from 'lib/testHelpers'
|
||||
import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
import { Program } from '../wasm-lib/kcl/bindings/Program'
|
||||
@ -20,3 +20,12 @@ it('can execute parsed AST', async () => {
|
||||
expect(err(execState)).toEqual(false)
|
||||
expect(execState.memory.get('x')?.value).toEqual(1)
|
||||
})
|
||||
|
||||
it('formats numbers with units', () => {
|
||||
expect(formatNumber(1, 'None')).toEqual('1')
|
||||
expect(formatNumber(1, 'Count')).toEqual('1_')
|
||||
expect(formatNumber(1, 'Mm')).toEqual('1mm')
|
||||
expect(formatNumber(1, 'Inch')).toEqual('1in')
|
||||
expect(formatNumber(0.5, 'Mm')).toEqual('0.5mm')
|
||||
expect(formatNumber(-0.5, 'Mm')).toEqual('-0.5mm')
|
||||
})
|
||||
|
@ -2,6 +2,7 @@ import {
|
||||
init,
|
||||
parse_wasm,
|
||||
recast_wasm,
|
||||
format_number,
|
||||
execute,
|
||||
kcl_lint,
|
||||
modify_ast_for_sketch_wasm,
|
||||
@ -17,6 +18,7 @@ import {
|
||||
default_project_settings,
|
||||
base64_decode,
|
||||
clear_scene_and_bust_cache,
|
||||
change_kcl_settings,
|
||||
reloadModule,
|
||||
} from 'lib/wasm_lib_wrapper'
|
||||
|
||||
@ -54,6 +56,8 @@ 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 'lang/queryAstNodePathUtils'
|
||||
import { NumericSuffix } from 'wasm-lib/kcl/bindings/NumericSuffix'
|
||||
import { MetaSettings } from 'wasm-lib/kcl/bindings/MetaSettings'
|
||||
|
||||
export type { Artifact } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
export type { ArtifactCommand } from 'wasm-lib/kcl/bindings/Artifact'
|
||||
@ -90,6 +94,7 @@ export type { Literal } from '../wasm-lib/kcl/bindings/Literal'
|
||||
export type { LiteralValue } from '../wasm-lib/kcl/bindings/LiteralValue'
|
||||
export type { ArrayExpression } from '../wasm-lib/kcl/bindings/ArrayExpression'
|
||||
export type { SourceRange } from 'wasm-lib/kcl/bindings/SourceRange'
|
||||
export type { NumericSuffix } from 'wasm-lib/kcl/bindings/NumericSuffix'
|
||||
|
||||
export type SyntaxType =
|
||||
| 'Program'
|
||||
@ -566,9 +571,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 +605,7 @@ export const executor = async (
|
||||
}
|
||||
const execOutcome: RustExecOutcome = await execute(
|
||||
JSON.stringify(node),
|
||||
path,
|
||||
JSON.stringify(programMemoryOverride?.toRaw() || null),
|
||||
JSON.stringify({ settings: jsAppSettings }),
|
||||
engineCommandManager,
|
||||
@ -627,6 +643,13 @@ export const recast = (ast: Program): string | Error => {
|
||||
return recast_wasm(JSON.stringify(ast))
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a number with suffix as KCL.
|
||||
*/
|
||||
export function formatNumber(value: number, suffix: NumericSuffix): string {
|
||||
return format_number(value, JSON.stringify(suffix))
|
||||
}
|
||||
|
||||
export const makeDefaultPlanes = async (
|
||||
engineCommandManager: EngineCommandManager
|
||||
): Promise<DefaultPlanes> => {
|
||||
@ -823,3 +846,17 @@ export function base64Decode(base64: string): ArrayBuffer | Error {
|
||||
return new Error('Caught error decoding base64 string: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Change the meta settings for the kcl file.
|
||||
/// Returns the new kcl string with the updated settings.
|
||||
export function changeKclSettings(
|
||||
kcl: string,
|
||||
settings: MetaSettings
|
||||
): string | Error {
|
||||
try {
|
||||
return change_kcl_settings(kcl, JSON.stringify(settings))
|
||||
} catch (e) {
|
||||
console.error('Caught error changing kcl settings: ' + e)
|
||||
return new Error('Caught error changing kcl settings: ' + e)
|
||||
}
|
||||
}
|
||||
|
@ -1,17 +1,14 @@
|
||||
import { StateMachineCommandSetConfig } from 'lib/commandTypes'
|
||||
import { authMachine } from 'machines/authMachine'
|
||||
import { Command } from 'lib/commandTypes'
|
||||
import { authActor } from 'machines/appMachine'
|
||||
import { ACTOR_IDS } from 'machines/machineConstants'
|
||||
|
||||
type AuthCommandSchema = {}
|
||||
|
||||
export const authCommandBarConfig: StateMachineCommandSetConfig<
|
||||
typeof authMachine,
|
||||
AuthCommandSchema
|
||||
> = {
|
||||
'Log in': {
|
||||
hide: 'both',
|
||||
},
|
||||
'Log out': {
|
||||
args: [],
|
||||
export const authCommands: Command[] = [
|
||||
{
|
||||
groupId: ACTOR_IDS.AUTH,
|
||||
name: 'log-out',
|
||||
displayName: 'Log out',
|
||||
icon: 'arrowLeft',
|
||||
needsReview: false,
|
||||
onSubmit: () => authActor.send({ type: 'Log out' }),
|
||||
},
|
||||
}
|
||||
]
|
||||
|
@ -308,7 +308,6 @@ export const modelingMachineCommandConfig: StateMachineCommandSetConfig<
|
||||
description:
|
||||
'Create a 3D body by moving a sketch region along an arbitrary path.',
|
||||
icon: 'sweep',
|
||||
status: 'development',
|
||||
needsReview: false,
|
||||
args: {
|
||||
target: {
|
||||
@ -317,8 +316,6 @@ export const modelingMachineCommandConfig: StateMachineCommandSetConfig<
|
||||
required: true,
|
||||
skip: true,
|
||||
multiple: false,
|
||||
warningMessage:
|
||||
'The sweep workflow is new and under tested. Please break it and report issues.',
|
||||
},
|
||||
trajectory: {
|
||||
inputType: 'selection',
|
||||
@ -368,7 +365,6 @@ export const modelingMachineCommandConfig: StateMachineCommandSetConfig<
|
||||
Revolve: {
|
||||
description: 'Create a 3D body by rotating a sketch region about an axis.',
|
||||
icon: 'revolve',
|
||||
status: 'development',
|
||||
needsReview: true,
|
||||
args: {
|
||||
selection: {
|
||||
@ -377,8 +373,6 @@ export const modelingMachineCommandConfig: StateMachineCommandSetConfig<
|
||||
multiple: false, // TODO: multiple selection
|
||||
required: true,
|
||||
skip: true,
|
||||
warningMessage:
|
||||
'The revolve workflow is new and under tested. Please break it and report issues.',
|
||||
},
|
||||
axisOrEdge: {
|
||||
inputType: 'options',
|
||||
|
@ -41,12 +41,11 @@ export const projectsCommandBarConfig: StateMachineCommandSetConfig<
|
||||
name: {
|
||||
inputType: 'options',
|
||||
required: true,
|
||||
options: [],
|
||||
optionsFromContext: (context) =>
|
||||
context.projects.map((p) => ({
|
||||
name: p.name!,
|
||||
value: p.name!,
|
||||
})),
|
||||
options: (_, context) =>
|
||||
context?.projects.map((p) => ({
|
||||
name: p.name,
|
||||
value: p.name,
|
||||
})) || [],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
19
src/lib/commandBarConfigs/validators.test.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { parseEngineErrorMessage } from './validators'
|
||||
|
||||
describe('parseEngineErrorMessage', () => {
|
||||
it('takes an engine error string and parses its json message', () => {
|
||||
const engineError =
|
||||
'engine error: [{"error_code":"internal_engine","message":"Trajectory curve must be G1 continuous (with continuous tangents)"}]'
|
||||
const message = parseEngineErrorMessage(engineError)
|
||||
expect(message).toEqual(
|
||||
'Trajectory curve must be G1 continuous (with continuous tangents)'
|
||||
)
|
||||
})
|
||||
|
||||
it('retuns undefined on strings with different formats', () => {
|
||||
const s1 = 'engine error: []'
|
||||
const s2 = 'blabla'
|
||||
expect(parseEngineErrorMessage(s1)).toBeUndefined()
|
||||
expect(parseEngineErrorMessage(s2)).toBeUndefined()
|
||||
})
|
||||
})
|
@ -3,6 +3,7 @@ import { engineCommandManager } from 'lib/singletons'
|
||||
import { uuidv4 } from 'lib/utils'
|
||||
import { CommandBarContext } from 'machines/commandBarMachine'
|
||||
import { Selections } from 'lib/selections'
|
||||
import { ApiError_type } from '@kittycad/lib/dist/types/src/models'
|
||||
|
||||
export const disableDryRunWithRetry = async (numberOfRetries = 3) => {
|
||||
for (let tries = 0; tries < numberOfRetries; tries++) {
|
||||
@ -46,6 +47,20 @@ function isSelections(selections: unknown): selections is Selections {
|
||||
)
|
||||
}
|
||||
|
||||
export function parseEngineErrorMessage(engineError: string) {
|
||||
const parts = engineError.split('engine error: ')
|
||||
if (parts.length < 2) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const errors = JSON.parse(parts[1]) as ApiError_type[]
|
||||
if (!errors[0]) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return errors[0].message
|
||||
}
|
||||
|
||||
export const revolveAxisValidator = async ({
|
||||
data,
|
||||
context,
|
||||
@ -83,7 +98,7 @@ export const revolveAxisValidator = async ({
|
||||
value: 360,
|
||||
}
|
||||
|
||||
const revolveAboutEdgeCommand = async () => {
|
||||
const command = async () => {
|
||||
return await engineCommandManager.sendSceneCommand({
|
||||
type: 'modeling_cmd_req',
|
||||
cmd_id: uuidv4(),
|
||||
@ -92,17 +107,18 @@ export const revolveAxisValidator = async ({
|
||||
angle: angleInDegrees,
|
||||
edge_id: edgeSelection,
|
||||
target: sketchSelection,
|
||||
tolerance: 0.0001,
|
||||
// Gotcha: Playwright will fail with larger tolerances, need to use a smaller one.
|
||||
tolerance: 1e-7,
|
||||
},
|
||||
})
|
||||
}
|
||||
const attemptRevolve = await dryRunWrapper(revolveAboutEdgeCommand)
|
||||
if (attemptRevolve?.success) {
|
||||
const result = await dryRunWrapper(command)
|
||||
if (result?.success) {
|
||||
return true
|
||||
} else {
|
||||
// return error message for the toast
|
||||
return 'Unable to revolve with selected edge'
|
||||
}
|
||||
|
||||
const reason = parseEngineErrorMessage(result) || 'unknown'
|
||||
return `Unable to revolve with the current selection. Reason: ${reason}`
|
||||
}
|
||||
|
||||
export const loftValidator = async ({
|
||||
@ -128,7 +144,7 @@ export const loftValidator = async ({
|
||||
return 'Unable to loft, selection contains less than two solid2ds'
|
||||
}
|
||||
|
||||
const loftCommand = async () => {
|
||||
const command = async () => {
|
||||
// TODO: check what to do with these
|
||||
const DEFAULT_V_DEGREE = 2
|
||||
const DEFAULT_TOLERANCE = 2
|
||||
@ -145,13 +161,13 @@ export const loftValidator = async ({
|
||||
},
|
||||
})
|
||||
}
|
||||
const attempt = await dryRunWrapper(loftCommand)
|
||||
if (attempt?.success) {
|
||||
const result = await dryRunWrapper(command)
|
||||
if (result?.success) {
|
||||
return true
|
||||
} else {
|
||||
// return error message for the toast
|
||||
return 'Unable to loft with selected sketches'
|
||||
}
|
||||
|
||||
const reason = parseEngineErrorMessage(result) || 'unknown'
|
||||
return `Unable to loft with the current selection. Reason: ${reason}`
|
||||
}
|
||||
|
||||
export const shellValidator = async ({
|
||||
@ -180,7 +196,7 @@ export const shellValidator = async ({
|
||||
return "Unable to shell, couldn't find the solid"
|
||||
}
|
||||
|
||||
const shellCommand = async () => {
|
||||
const command = async () => {
|
||||
// TODO: figure out something better than an arbitrarily small value
|
||||
const DEFAULT_THICKNESS: Models['LengthUnit_type'] = 1e-9
|
||||
const DEFAULT_HOLLOW = false
|
||||
@ -200,12 +216,13 @@ export const shellValidator = async ({
|
||||
})
|
||||
}
|
||||
|
||||
const attemptShell = await dryRunWrapper(shellCommand)
|
||||
if (attemptShell?.success) {
|
||||
const result = await dryRunWrapper(command)
|
||||
if (result?.success) {
|
||||
return true
|
||||
}
|
||||
|
||||
return 'Unable to shell with the provided selection'
|
||||
const reason = parseEngineErrorMessage(result) || 'unknown'
|
||||
return `Unable to shell with the current selection. Reason: ${reason}`
|
||||
}
|
||||
|
||||
export const sweepValidator = async ({
|
||||
@ -241,7 +258,7 @@ export const sweepValidator = async ({
|
||||
}
|
||||
const target = targetArtifact.pathId
|
||||
|
||||
const sweepCommand = async () => {
|
||||
const command = async () => {
|
||||
// TODO: second look on defaults here
|
||||
const DEFAULT_TOLERANCE: Models['LengthUnit_type'] = 1e-7
|
||||
const DEFAULT_SECTIONAL = false
|
||||
@ -261,10 +278,11 @@ export const sweepValidator = async ({
|
||||
})
|
||||
}
|
||||
|
||||
const attemptSweep = await dryRunWrapper(sweepCommand)
|
||||
if (attemptSweep?.success) {
|
||||
const result = await dryRunWrapper(command)
|
||||
if (result?.success) {
|
||||
return true
|
||||
}
|
||||
|
||||
return 'Unable to sweep with the provided selection'
|
||||
const reason = parseEngineErrorMessage(result) || 'unknown'
|
||||
return `Unable to sweep with the current selection. Reason: ${reason}`
|
||||
}
|
||||
|
@ -26,7 +26,7 @@ export const FILE_EXT = '.kcl'
|
||||
/** Default file to open when a project is opened */
|
||||
export const PROJECT_ENTRYPOINT = `main${FILE_EXT}` as const
|
||||
/** Thumbnail file name */
|
||||
export const PROJECT_IMAGE_NAME = `main.jpg` as const
|
||||
export const PROJECT_IMAGE_NAME = `thumbnail.png` as const
|
||||
/** The localStorage key for last-opened projects */
|
||||
export const FILE_PERSIST_KEY = `${PROJECT_FOLDER}-last-opened` as const
|
||||
/** The default name given to new kcl files in a project */
|
||||
@ -68,8 +68,6 @@ export const KCL_DEFAULT_DEGREE = `360`
|
||||
/** localStorage key for the playwright test-specific app settings file */
|
||||
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'
|
||||
@ -145,7 +143,7 @@ export const VIEW_NAMES_SEMANTIC = {
|
||||
export const SIDEBAR_BUTTON_SUFFIX = '-pane-button'
|
||||
|
||||
/** Custom URL protocol our desktop registers */
|
||||
export const ZOO_STUDIO_PROTOCOL = 'zoo-studio:'
|
||||
export const ZOO_STUDIO_PROTOCOL = 'zoo-studio'
|
||||
|
||||
/**
|
||||
* A query parameter that triggers a modal
|
||||
|
@ -10,6 +10,7 @@ import {
|
||||
import {
|
||||
PROJECT_ENTRYPOINT,
|
||||
PROJECT_FOLDER,
|
||||
PROJECT_IMAGE_NAME,
|
||||
PROJECT_SETTINGS_FILE_NAME,
|
||||
SETTINGS_FILE_NAME,
|
||||
TELEMETRY_FILE_NAME,
|
||||
@ -625,3 +626,19 @@ export const getUser = async (
|
||||
}
|
||||
return Promise.reject(new Error('unreachable'))
|
||||
}
|
||||
|
||||
export const writeProjectThumbnailFile = async (
|
||||
dataUrl: string,
|
||||
projectDirectoryPath: string
|
||||
) => {
|
||||
const filePath = window.electron.path.join(
|
||||
projectDirectoryPath,
|
||||
PROJECT_IMAGE_NAME
|
||||
)
|
||||
const data = atob(dataUrl.substring('data:image/png;base64,'.length))
|
||||
const asArray = new Uint8Array(data.length)
|
||||
for (let i = 0, len = data.length; i < len; ++i) {
|
||||
asArray[i] = data.charCodeAt(i)
|
||||
}
|
||||
return window.electron.writeFile(filePath, asArray)
|
||||
}
|
||||
|
@ -2,13 +2,12 @@ import { CommandBarOverwriteWarning } from 'components/CommandBarOverwriteWarnin
|
||||
import { Command, CommandArgumentOption } from './commandTypes'
|
||||
import { codeManager, kclManager } from './singletons'
|
||||
import { isDesktop } from './isDesktop'
|
||||
import { FILE_EXT, PROJECT_SETTINGS_FILE_NAME } from './constants'
|
||||
import { FILE_EXT } 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 { reportRejection } from './trap'
|
||||
import { IndexLoaderData } from './types'
|
||||
import { IS_NIGHTLY_OR_DEBUG } from 'routes/Settings'
|
||||
import { copyFileShareLink } from './links'
|
||||
|
||||
interface OnSubmitProps {
|
||||
sampleName: string
|
||||
@ -68,56 +67,23 @@ export function kclCommands(commandProps: KclCommandConfig): Command[] {
|
||||
const sampleCodeUrl = `https://raw.githubusercontent.com/KittyCAD/kcl-samples/main/${encodeURIComponent(
|
||||
projectPathPart
|
||||
)}/${encodeURIComponent(primaryKclFile)}`
|
||||
const sampleSettingsFileUrl = `https://raw.githubusercontent.com/KittyCAD/kcl-samples/main/${encodeURIComponent(
|
||||
projectPathPart
|
||||
)}/${PROJECT_SETTINGS_FILE_NAME}`
|
||||
|
||||
Promise.allSettled([fetch(sampleCodeUrl), fetch(sampleSettingsFileUrl)])
|
||||
.then((results) => {
|
||||
const a =
|
||||
'value' in results[0] ? results[0].value : results[0].reason
|
||||
const b =
|
||||
'value' in results[1] ? results[1].value : results[1].reason
|
||||
return [a, b]
|
||||
})
|
||||
.then(
|
||||
async ([
|
||||
codeResponse,
|
||||
settingsResponse,
|
||||
]): Promise<OnSubmitProps> => {
|
||||
if (!codeResponse.ok) {
|
||||
console.error(
|
||||
'Failed to fetch sample code:',
|
||||
codeResponse.statusText
|
||||
)
|
||||
return Promise.reject(new Error('Failed to fetch sample code'))
|
||||
}
|
||||
const code = await codeResponse.text()
|
||||
|
||||
// It's possible that a sample doesn't have a project.toml
|
||||
// associated with it.
|
||||
let projectSettingsPayload: ReturnType<
|
||||
typeof projectConfigurationToSettingsPayload
|
||||
> = {}
|
||||
if (settingsResponse.ok) {
|
||||
const parsedProjectSettings = parseProjectSettings(
|
||||
await settingsResponse.text()
|
||||
)
|
||||
if (!err(parsedProjectSettings)) {
|
||||
projectSettingsPayload =
|
||||
projectConfigurationToSettingsPayload(parsedProjectSettings)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
sampleName: data.sample.split('/')[0] + FILE_EXT,
|
||||
code,
|
||||
method: data.method,
|
||||
sampleUnits:
|
||||
projectSettingsPayload.modeling?.defaultUnit || 'mm',
|
||||
}
|
||||
fetch(sampleCodeUrl)
|
||||
.then(async (codeResponse): Promise<OnSubmitProps> => {
|
||||
if (!codeResponse.ok) {
|
||||
console.error(
|
||||
'Failed to fetch sample code:',
|
||||
codeResponse.statusText
|
||||
)
|
||||
return Promise.reject(new Error('Failed to fetch sample code'))
|
||||
}
|
||||
)
|
||||
const code = await codeResponse.text()
|
||||
return {
|
||||
sampleName: data.sample.split('/')[0] + FILE_EXT,
|
||||
code,
|
||||
method: data.method,
|
||||
}
|
||||
})
|
||||
.then((props) => {
|
||||
if (props?.code) {
|
||||
commandProps.specialPropsForSampleCommand
|
||||
@ -168,21 +134,22 @@ export function kclCommands(commandProps: KclCommandConfig): Command[] {
|
||||
},
|
||||
},
|
||||
},
|
||||
// {
|
||||
// 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)
|
||||
// },
|
||||
// },
|
||||
{
|
||||
name: 'share-file-link',
|
||||
displayName: 'Share file',
|
||||
hide: IS_NIGHTLY_OR_DEBUG ? undefined : 'desktop',
|
||||
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)
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { VITE_KC_SITE_APP_URL } from 'env'
|
||||
import { createCreateFileUrl } from './links'
|
||||
|
||||
describe(`link creation tests`, () => {
|
||||
@ -8,7 +9,7 @@ describe(`link creation tests`, () => {
|
||||
|
||||
// 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 expectedLink = `${VITE_KC_SITE_APP_URL}/?create-file=true&name=test&units=mm&code=${expectedEncodedCode}&ask-open-desktop=true`
|
||||
|
||||
const result = createCreateFileUrl({ code, name, units })
|
||||
expect(result.toString()).toBe(expectedLink)
|
||||
|
@ -1,11 +1,7 @@
|
||||
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 { ASK_TO_OPEN_QUERY_PARAM, CREATE_FILE_URL_PARAM } from './constants'
|
||||
import { stringToBase64 } from './base64'
|
||||
import { DEV, VITE_KC_API_BASE_URL } from 'env'
|
||||
import { VITE_KC_API_BASE_URL, VITE_KC_SITE_APP_URL } from 'env'
|
||||
import toast from 'react-hot-toast'
|
||||
import { err } from './trap'
|
||||
export interface FileLinkParams {
|
||||
@ -51,8 +47,7 @@ export async function copyFileShareLink(
|
||||
* 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
|
||||
let origin = VITE_KC_SITE_APP_URL
|
||||
const searchParams = new URLSearchParams({
|
||||
[CREATE_FILE_URL_PARAM]: String(true),
|
||||
name,
|
||||
|
92
src/lib/rectangleTool.test.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import { expect } from 'vitest'
|
||||
import {
|
||||
recast,
|
||||
assertParse,
|
||||
topLevelRange,
|
||||
VariableDeclaration,
|
||||
initPromise,
|
||||
} from 'lang/wasm'
|
||||
import { updateCenterRectangleSketch } from './rectangleTool'
|
||||
import { getNodePathFromSourceRange } from 'lang/queryAstNodePathUtils'
|
||||
import { getNodeFromPath } from 'lang/queryAst'
|
||||
import { findUniqueName } from 'lang/modifyAst'
|
||||
import { err, trap } from './trap'
|
||||
|
||||
beforeAll(async () => {
|
||||
await initPromise
|
||||
})
|
||||
|
||||
describe('library rectangleTool helper functions', () => {
|
||||
describe('updateCenterRectangleSketch', () => {
|
||||
// regression test for https://github.com/KittyCAD/modeling-app/issues/5157
|
||||
test('should update AST and source code', async () => {
|
||||
// Base source code that will be edited in place
|
||||
const sourceCode = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([120.37, 162.76], %)
|
||||
|> angledLine([0, 0], %, $rectangleSegmentA001)
|
||||
|> angledLine([segAng(rectangleSegmentA001) + 90, 0], %, $rectangleSegmentB001)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA001),
|
||||
-segLen(rectangleSegmentA001)
|
||||
], %, $rectangleSegmentC001)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
`
|
||||
// Create ast
|
||||
const _ast = assertParse(sourceCode)
|
||||
let ast = structuredClone(_ast)
|
||||
|
||||
// Find some nodes and paths to reference
|
||||
const sketchSnippet = `startProfileAt([120.37, 162.76], %)`
|
||||
const sketchRange = topLevelRange(
|
||||
sourceCode.indexOf(sketchSnippet),
|
||||
sourceCode.indexOf(sketchSnippet) + sketchSnippet.length
|
||||
)
|
||||
const sketchPathToNode = getNodePathFromSourceRange(ast, sketchRange)
|
||||
const _node = getNodeFromPath<VariableDeclaration>(
|
||||
ast,
|
||||
sketchPathToNode || [],
|
||||
'VariableDeclaration'
|
||||
)
|
||||
if (trap(_node)) return
|
||||
const sketchInit = _node.node?.declaration.init
|
||||
|
||||
// Hard code inputs that a user would have taken with their mouse
|
||||
const x = 40
|
||||
const y = 60
|
||||
const rectangleOrigin = [120, 180]
|
||||
const tags: [string, string, string] = [
|
||||
'rectangleSegmentA001',
|
||||
'rectangleSegmentB001',
|
||||
'rectangleSegmentC001',
|
||||
]
|
||||
|
||||
// Update the ast
|
||||
if (sketchInit.type === 'PipeExpression') {
|
||||
updateCenterRectangleSketch(
|
||||
sketchInit,
|
||||
x,
|
||||
y,
|
||||
tags[0],
|
||||
rectangleOrigin[0],
|
||||
rectangleOrigin[1]
|
||||
)
|
||||
}
|
||||
|
||||
// ast is edited in place from the updateCenterRectangleSketch
|
||||
const expectedSourceCode = `sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([80, 120], %)
|
||||
|> angledLine([0, 80], %, $rectangleSegmentA001)
|
||||
|> angledLine([segAng(rectangleSegmentA001) + 90, 120], %, $rectangleSegmentB001)
|
||||
|> angledLine([
|
||||
segAng(rectangleSegmentA001),
|
||||
-segLen(rectangleSegmentA001)
|
||||
], %, $rectangleSegmentC001)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)
|
||||
`
|
||||
const recasted = recast(ast)
|
||||
expect(recasted).toEqual(expectedSourceCode)
|
||||
})
|
||||
})
|
||||
})
|
@ -8,13 +8,19 @@ import {
|
||||
createTagDeclarator,
|
||||
createUnaryExpression,
|
||||
} from 'lang/modifyAst'
|
||||
import { ArrayExpression, CallExpression, PipeExpression } from 'lang/wasm'
|
||||
import {
|
||||
ArrayExpression,
|
||||
CallExpression,
|
||||
PipeExpression,
|
||||
recast,
|
||||
} from 'lang/wasm'
|
||||
import { roundOff } from 'lib/utils'
|
||||
import {
|
||||
isCallExpression,
|
||||
isArrayExpression,
|
||||
isLiteral,
|
||||
isBinaryExpression,
|
||||
isLiteralValueNumber,
|
||||
} from 'lang/util'
|
||||
|
||||
/**
|
||||
@ -140,10 +146,12 @@ export function updateCenterRectangleSketch(
|
||||
if (isArrayExpression(arrayExpression)) {
|
||||
const literal = arrayExpression.elements[0]
|
||||
if (isLiteral(literal)) {
|
||||
callExpression.arguments[0] = createArrayExpression([
|
||||
createLiteral(literal.value),
|
||||
createLiteral(Math.abs(twoX)),
|
||||
])
|
||||
if (isLiteralValueNumber(literal.value)) {
|
||||
callExpression.arguments[0] = createArrayExpression([
|
||||
createLiteral(literal.value),
|
||||
createLiteral(Math.abs(twoX)),
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
function takeScreenshotOfVideoStreamCanvas() {
|
||||
export function takeScreenshotOfVideoStreamCanvas() {
|
||||
const canvas = document.querySelector('[data-engine]')
|
||||
const video = document.getElementById('video-stream')
|
||||
if (
|
||||
|
@ -577,10 +577,9 @@ export function getSelectionTypeDisplayText(
|
||||
.map(
|
||||
// Hack for showing "face" instead of "extrude-wall" in command bar text
|
||||
([type, count]) =>
|
||||
`${count} ${type
|
||||
.replace('wall', 'face')
|
||||
.replace('solid2d', 'face')
|
||||
.replace('segment', 'face')}${count > 1 ? 's' : ''}`
|
||||
`${count} ${type.replace('wall', 'face').replace('solid2d', 'face')}${
|
||||
count > 1 ? 's' : ''
|
||||
}`
|
||||
)
|
||||
.toArray()
|
||||
.join(', ')
|
||||
|
@ -20,6 +20,7 @@ import { toSync } from 'lib/utils'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
import { CameraProjectionType } from 'wasm-lib/kcl/bindings/CameraProjectionType'
|
||||
import { OnboardingStatus } from 'wasm-lib/kcl/bindings/OnboardingStatus'
|
||||
import { CameraOrbitType } from 'wasm-lib/kcl/bindings/CameraOrbitType'
|
||||
|
||||
/**
|
||||
* A setting that can be set at the user or project level
|
||||
@ -380,6 +381,30 @@ export function createSettings() {
|
||||
})),
|
||||
},
|
||||
}),
|
||||
/**
|
||||
* What methodology to use for orbiting the camera
|
||||
*/
|
||||
cameraOrbit: new Setting<CameraOrbitType>({
|
||||
defaultValue: 'spherical',
|
||||
hideOnLevel: 'project',
|
||||
description: 'What methodology to use for orbiting the camera',
|
||||
validate: (v) => ['spherical', 'trackball'].includes(v),
|
||||
commandConfig: {
|
||||
inputType: 'options',
|
||||
defaultValueFromContext: (context) =>
|
||||
context.modeling.cameraOrbit.current,
|
||||
options: (cmdContext, settingsContext) =>
|
||||
(['spherical', 'trackball'] as const).map((v) => ({
|
||||
name: v.charAt(0).toUpperCase() + v.slice(1),
|
||||
value: v,
|
||||
isCurrent:
|
||||
settingsContext.modeling.cameraOrbit.shouldShowCurrentLabel(
|
||||
cmdContext.argumentsToSubmit.level as SettingsLevel,
|
||||
v
|
||||
),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
/**
|
||||
* Whether to highlight edges of 3D objects
|
||||
*/
|
||||
|
@ -4,6 +4,7 @@ import { AtLeast, PathValue, Paths } from 'lib/types'
|
||||
import { CommandArgumentConfig } from 'lib/commandTypes'
|
||||
import { Themes } from 'lib/theme'
|
||||
import { CameraProjectionType } from 'wasm-lib/kcl/bindings/CameraProjectionType'
|
||||
import { CameraOrbitType } from 'wasm-lib/kcl/bindings/CameraOrbitType'
|
||||
|
||||
export interface SettingsViaQueryString {
|
||||
pool: string | null
|
||||
@ -12,6 +13,7 @@ export interface SettingsViaQueryString {
|
||||
enableSSAO: boolean
|
||||
showScaleGrid: boolean
|
||||
cameraProjection: CameraProjectionType
|
||||
cameraOrbit: CameraOrbitType
|
||||
}
|
||||
|
||||
export enum UnitSystem {
|
||||
|
@ -49,6 +49,7 @@ export function configurationToSettingsPayload(
|
||||
modeling: {
|
||||
defaultUnit: configuration?.settings?.modeling?.base_unit,
|
||||
cameraProjection: configuration?.settings?.modeling?.camera_projection,
|
||||
cameraOrbit: configuration?.settings?.modeling?.camera_orbit,
|
||||
mouseControls: mouseControlsToCameraSystem(
|
||||
configuration?.settings?.modeling?.mouse_controls
|
||||
),
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -103,7 +103,7 @@ export const toolbarConfig: Record<ToolbarModeName, ToolbarMode> = {
|
||||
data: { name: 'Revolve', groupId: 'modeling' },
|
||||
}),
|
||||
icon: 'revolve',
|
||||
status: DEV || IS_NIGHTLY_OR_DEBUG ? 'available' : 'kcl-only',
|
||||
status: 'available',
|
||||
title: 'Revolve',
|
||||
hotkey: 'R',
|
||||
description:
|
||||
@ -124,7 +124,7 @@ export const toolbarConfig: Record<ToolbarModeName, ToolbarMode> = {
|
||||
data: { name: 'Sweep', groupId: 'modeling' },
|
||||
}),
|
||||
icon: 'sweep',
|
||||
status: DEV || IS_NIGHTLY_OR_DEBUG ? 'available' : 'kcl-only',
|
||||
status: 'available',
|
||||
title: 'Sweep',
|
||||
hotkey: 'W',
|
||||
description:
|
||||
|
@ -10,6 +10,7 @@
|
||||
import {
|
||||
parse_wasm as ParseWasm,
|
||||
recast_wasm as RecastWasm,
|
||||
format_number as FormatNumber,
|
||||
execute as Execute,
|
||||
kcl_lint as KclLint,
|
||||
modify_ast_for_sketch_wasm as ModifyAstForSketch,
|
||||
@ -25,6 +26,7 @@ import {
|
||||
default_project_settings as DefaultProjectSettings,
|
||||
base64_decode as Base64Decode,
|
||||
clear_scene_and_bust_cache as ClearSceneAndBustCache,
|
||||
change_kcl_settings as ChangeKclSettings,
|
||||
} from '../wasm-lib/pkg/wasm_lib'
|
||||
|
||||
type ModuleType = typeof import('../wasm-lib/pkg/wasm_lib')
|
||||
@ -51,6 +53,9 @@ export const parse_wasm: typeof ParseWasm = (...args) => {
|
||||
export const recast_wasm: typeof RecastWasm = (...args) => {
|
||||
return getModule().recast_wasm(...args)
|
||||
}
|
||||
export const format_number: typeof FormatNumber = (...args) => {
|
||||
return getModule().format_number(...args)
|
||||
}
|
||||
export const execute: typeof Execute = (...args) => {
|
||||
return getModule().execute(...args)
|
||||
}
|
||||
@ -106,3 +111,6 @@ export const clear_scene_and_bust_cache: typeof ClearSceneAndBustCache = (
|
||||
) => {
|
||||
return getModule().clear_scene_and_bust_cache(...args)
|
||||
}
|
||||
export const change_kcl_settings: typeof ChangeKclSettings = (...args) => {
|
||||
return getModule().change_kcl_settings(...args)
|
||||
}
|
||||
|
30
src/machines/appMachine.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { ActorRefFrom, createActor, setup } from 'xstate'
|
||||
import { authMachine } from './authMachine'
|
||||
import { useSelector } from '@xstate/react'
|
||||
import { ACTOR_IDS } from './machineConstants'
|
||||
|
||||
const appMachine = setup({
|
||||
actors: {
|
||||
[ACTOR_IDS.AUTH]: authMachine,
|
||||
},
|
||||
}).createMachine({
|
||||
/** @xstate-layout N4IgpgJg5mDOIC5gF8A0IB2B7CdGgAoBbAQwGMALASwzAEp8QAHLWKgFyqw0YA9EAjACZ0AT0FDkU5EA */
|
||||
id: 'modeling-app',
|
||||
invoke: [
|
||||
{
|
||||
src: ACTOR_IDS.AUTH,
|
||||
systemId: ACTOR_IDS.AUTH,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
export const appActor = createActor(appMachine).start()
|
||||
|
||||
export const authActor = appActor.system.get(ACTOR_IDS.AUTH) as ActorRefFrom<
|
||||
typeof authMachine
|
||||
>
|
||||
export const useAuthState = () => useSelector(authActor, (state) => state)
|
||||
export const useToken = () =>
|
||||
useSelector(authActor, (state) => state.context.token)
|
||||
export const useUser = () =>
|
||||
useSelector(authActor, (state) => state.context.user)
|
@ -15,6 +15,8 @@ import {
|
||||
} from 'lib/desktop'
|
||||
import { COOKIE_NAME } from 'lib/constants'
|
||||
import { markOnce } from 'lib/performance'
|
||||
import { ACTOR_IDS } from './machineConstants'
|
||||
import withBaseUrl from '../lib/withBaseURL'
|
||||
|
||||
const SKIP_AUTH = VITE_KC_SKIP_AUTH === 'true' && DEV
|
||||
|
||||
@ -50,7 +52,7 @@ export type Events =
|
||||
}
|
||||
|
||||
export const TOKEN_PERSIST_KEY = 'TOKEN_PERSIST_KEY'
|
||||
const persistedToken =
|
||||
export const persistedToken =
|
||||
VITE_KC_DEV_TOKEN ||
|
||||
getCookie(COOKIE_NAME) ||
|
||||
localStorage?.getItem(TOKEN_PERSIST_KEY) ||
|
||||
@ -69,18 +71,17 @@ export const authMachine = setup({
|
||||
}
|
||||
}
|
||||
},
|
||||
actions: {
|
||||
goToIndexPage: () => {},
|
||||
goToSignInPage: () => {},
|
||||
},
|
||||
actors: {
|
||||
getUser: fromPromise(({ input }: { input: { token?: string } }) =>
|
||||
getUser(input)
|
||||
),
|
||||
logout: fromPromise(async () =>
|
||||
isDesktop() ? writeTokenFile('') : logout()
|
||||
),
|
||||
},
|
||||
}).createMachine({
|
||||
/** @xstate-layout N4IgpgJg5mDOIC5QEECuAXAFgOgMabFwGsBJAMwBkB7KGCEgOwGIIqGxsBLBgNyqI75CRALQAbGnRHcA2gAYAuolAAHKrE7pObZSAAeiAIwAWQ9gBspuQCYAnAGYAHPYCsx+4ccAaEAE9E1q7YcoZyxrYR1m7mcrYAvnE+aFh4BMTk1LSQjExgAE55VHnYKmIAhuhkRQC2qcLikpDSDPJKSCBqGlo67QYI9gDs5tge5o6h5vau7oY+-v3mA9jWco4u5iu21ua2YcYJSRg4Eln0zJkABFQYrbqdmtoMun2GA7YjxuPmLqvGNh5zRCfJaOcyLUzuAYuFyGcwHEDJY6NCAAeQwTEuskUd3UDx6oD6Im2wUcAzkMJ2cjBxlMgIWLmwZLWljecjJTjh8IYVAgcF0iJxXUez0QIgGxhJZIpu2ptL8AWwtje1nCW2iq1shns8MRdXSlGRjEFeKevUQjkcy3sqwGHimbg83nlCF22GMytVUWMMUc8USCKO2BOdCN7Xu3VNBKMKsVFp2hm2vu+1id83slkVrgTxhcW0pNJ1geDkDR6GNEZFCAT1kZZLk9cMLltb0WdPMjewjjC1mzOZCtk5CSAA */
|
||||
id: 'Auth',
|
||||
/** @xstate-layout N4IgpgJg5mDOIC5QAoC2BDAxgCwJYDswBKAOhzEwGsBJAMwBkB7KGCa-AYgkcJIIDdGlMGWwVKAWgA2zVhIIBtAAwBdRKAAOjWLgAuuHupAAPRAGYArAEYSADgu2AnGYBMLpVYBsZz7YA0IACeiG6OJM62tmZKLgDsno5KtvEAvikBaFh4hKTkVHRMLJDsHGAATmWMZSQaUui6tFWoouLSspDy+MpqSCBaOvqGvaYIljb2Tq7uXj7+QYgALFYW4clWy1ZmVgsWsZtpGRg4BMQkMkVsnIUABIwArrrdRv16BvhGI74LJBYW7o5WKJmKILObBUZeEgJP4LTxKMwIhZmBYLA4gTLHHJnWQEKAAeQeXB4IgEQhEGOyp3OUFxBN0CFJmHqb26T16L0G72GiCsSg8PyszkBCViTiUjgC4Jcnhc4SUsQcvgsoL2VjRFJOpGptMJ5Uq1Vq9UaZWaGqx2vw+IeDPwgiZnNZqme2leQ1An1s31+-0BCJBYJCLm+lk8CRl9hRyos6qOlK17QgdI4N0UTvZLs5Hx58NsJARuys0tDSl+AYQthsgNi0TMqt2LjVaPwjAgcCMZuIzoGbyzCAknkliH7Maympa+QYCfYXddXPdixcg4QvKUdk2u2iLkcsXhCRHmKpU7nfQzPe5CAsMpIXi8MvFKM8VliS5c1jzj53W3isNFqPS6NjMcLStXQZ0zc8ohsJI-kcFxXEcR9HAWF9gTzDxbCUXxAQWEsdn3ONsQuOkwLPedl22MIzFg3YP1gl9PG+bYvGsSxlUcRJozSFIgA */
|
||||
id: ACTOR_IDS.AUTH,
|
||||
initial: 'checkIfLoggedIn',
|
||||
context: {
|
||||
token: persistedToken,
|
||||
@ -112,19 +113,30 @@ export const authMachine = setup({
|
||||
},
|
||||
},
|
||||
loggedIn: {
|
||||
entry: ['goToIndexPage'],
|
||||
on: {
|
||||
'Log out': {
|
||||
target: 'loggedOut',
|
||||
actions: () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
if (isDesktop()) writeTokenFile('')
|
||||
},
|
||||
target: 'loggingOut',
|
||||
},
|
||||
},
|
||||
},
|
||||
loggingOut: {
|
||||
invoke: {
|
||||
src: 'logout',
|
||||
onDone: 'loggedOut',
|
||||
onError: {
|
||||
target: 'loggedIn',
|
||||
actions: [
|
||||
({ event }) => {
|
||||
console.error(
|
||||
'Error while logging out',
|
||||
'error' in event ? `: ${event.error}` : ''
|
||||
)
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
loggedOut: {
|
||||
entry: ['goToSignInPage'],
|
||||
on: {
|
||||
'Log in': {
|
||||
target: 'checkIfLoggedIn',
|
||||
@ -235,3 +247,12 @@ async function getAndSyncStoredToken(input: {
|
||||
localStorage.setItem(TOKEN_PERSIST_KEY, fileToken)
|
||||
return fileToken
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
localStorage.removeItem(TOKEN_PERSIST_KEY)
|
||||
if (isDesktop()) return Promise.resolve(null)
|
||||
return fetch(withBaseUrl('/logout'), {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
})
|
||||
}
|
||||
|
@ -10,6 +10,7 @@ import { getCommandArgumentKclValuesOnly } from 'lib/commandUtils'
|
||||
import { MachineManager } from 'components/MachineManagerProvider'
|
||||
import toast from 'react-hot-toast'
|
||||
import { useSelector } from '@xstate/react'
|
||||
import { authCommands } from 'lib/commandBarConfigs/authCommandConfig'
|
||||
|
||||
export type CommandBarContext = {
|
||||
commands: Command[]
|
||||
@ -80,6 +81,7 @@ export type CommandBarMachineEvent =
|
||||
export const commandBarMachine = setup({
|
||||
types: {
|
||||
context: {} as CommandBarContext,
|
||||
input: {} as { commands: Command[] },
|
||||
events: {} as CommandBarMachineEvent,
|
||||
},
|
||||
actions: {
|
||||
@ -409,8 +411,8 @@ export const commandBarMachine = setup({
|
||||
},
|
||||
}).createMachine({
|
||||
/** @xstate-layout N4IgpgJg5mDOIC5QGED2BbdBDAdhABAEJYBOAxMgDaqxgDaADALqKgAONAlgC6eo6sQAD0QBaAIwB2AHTiAHAE45AZjkAmdcoaSArCoA0IAJ6JxDOdJ2SF4gCySHaqZIa2Avm8NpMuAsXJUYKSMLEggHLA8fAJhIgiiOgBssokKTpJqiXK2OsqJaoYm8eJqytKJ9hqq+eJW2h5eGNh4RKRkAGKcLb74tJRgAMbc+ANNviGCEVH8gnEKubK5ympVrrlyhabm0rZ5CtYM4hVq83ININ7NfqTSVDSQZADybGA4E2FTvDOxiGoMDNJMjo9H9lLYGDpKpsEModOJpA5XOIwakwcidOdLj1-LdqLQIGQAIIQAijHx4WDvdhcL4xUBxURqSTw3LzfYKZSSOQZWzQ5S1crMuTAiElRKuTFjFo4u74sgAJTA6FQADcwCMpRBKcxJjTorMxEzkhouftuXCGGpIdCpADmZJxfzJLY5Cp5pLydcSLj7gSqeE9d96Yh+TppKoXfkGKdlHloUyFIDUvMXBzbFl3J4LprWt6AMpgfpDLpQDWesgFovDMlXf2ffU-BBZZKuczWWylRRwvlM6Q2LIMZQ2QdHZQeq65245vqDbgPOuBunCEP88MqPQchwVNLKaHptTSYUuRI6f4npyJcfYm5Ylozobz8ShamRWkGhBmeTSQeJX+JXQ6H88jQnCMiugoELCpypQKJeWa3l6U6er0hazvOajPgGr4NsGH6WhYsHOkycglLCEJ7iclgaIosKSLGGgKFe0o3AA4lg3AABZgCQJb4KQUAAK7oK83CwBQHG4DAIwCSQJAiXxJCCcJODcAu2FBsuH55GGJ7irYHYqHpGzGKYWiWB2nK2Kcv6wWO8E5jibGcdxvH8UJIliQAInAqFDGWtY6h8i7vlkZREbYZg6JuwEmQgfxhnkHbiHYJ7yHYTGIU5XE8TgpZucponSISADuWBRLl+BdGwAncBWAkAEboDwClKSJanTEucS1Bk36DicDCpOYLoKHu-x9tGuhgoozKpBlk5ZS5FX5R50gAGpYJQnAQOxJZkBA-BgNIXQqqgADWh0qhtW3sWAeYlv0hKKe5KntW+YRFGi5RyOKDrZEaUW8pppTguGuwDRFEO-nNjnsdlrlPQVsBrVd228LlZDcSQqDemwlDsQAZtj6DSJdm2o7d91gI9rUvYFL4dYIH0RV9P0Zv9CiA3EwMAmCWgVHYKVwY0yE4oqKqcGAxV1Y1zU1uMdNYQzjbMpYcgQlFxFq66u6xXRALbkyg7-Bz0bQzcYsS1LxIEMttOYfWGldYcCWwQmNiRrU0Jq2GRxJCbHZqC6ahm96FuSwqSqquqtuqQrDudVs4iJhUyZtn9qjQokYKHjk6hSLsZhciH0hh1LACiEDNTHr04ZpJT6bIEXxcKp50YDRT-mGrrJbUgFDp3xfIFxAynbx1PPaJe0HUdOAnedJMozd4+IzXjuIJCLIQqUWjJS4MVFBByS7BzyJq38WTB-ZIs3sPo8VcvHlTzgh3HWdF2L3OD8qZST66upCdxUTLBJOUUHB6GFPpSQXt1CWEGpaOiv4EyD1vmPBGj9MbY2kLjAmRMF5kyXmg7+q8AFJwbjkXQEVsj5FyO3RAiQjjfi5CReYPck7iA8FmHAqAIBwEEAhXMf8la4VEMsWwgJuTTXNGYK0tC4rwkDvsAaSQ-qlAhIPPEkBBFvWEVycoFQhywUHGaHWH04Q7FUNBdc+x2FXwnDiSss5eJyzwFo2ucQIplBWHrcEVhuoFFirCeEuxsj8mWEOFYmZhZ2JvNOXyc4ICuLXggaxCJwG70AiUHQfIzHBKHGYDMJFhTFwWjlPKhDRKJJIRFGQcIFBsiOIHJw8ZIQ7CUGrY+9g9AnmKbDRaZSaaFRKmVNGpYqo1Uqe+FKYZan1PyElbJYjrB6C5CUJQ9DL5ROvN6Ep8MBlI3WvgkZEzGzyAbnkZK-wjan38UzeEzZtBswdADYupdjm4XoTIOwuwHB5HyGkYyRRdBBLosCIE6ZvpnFsVs24KD77lPgEFf+kzxRH32EyFYlpOzQjAZYV2ehTkfI4W4IAA */
|
||||
context: {
|
||||
commands: [],
|
||||
context: ({ input }) => ({
|
||||
commands: input.commands || [],
|
||||
selectedCommand: undefined,
|
||||
currentArgument: undefined,
|
||||
selectionRanges: {
|
||||
@ -425,7 +427,7 @@ export const commandBarMachine = setup({
|
||||
setCurrentMachine: () => {},
|
||||
noMachinesReason: () => undefined,
|
||||
},
|
||||
},
|
||||
}),
|
||||
id: 'Command Bar',
|
||||
initial: 'Closed',
|
||||
states: {
|
||||
@ -631,7 +633,11 @@ function sortCommands(a: Command, b: Command) {
|
||||
return a.name.localeCompare(b.name)
|
||||
}
|
||||
|
||||
export const commandBarActor = createActor(commandBarMachine).start()
|
||||
export const commandBarActor = createActor(commandBarMachine, {
|
||||
input: {
|
||||
commands: [...authCommands],
|
||||
},
|
||||
}).start()
|
||||
|
||||
/** Basic state snapshot selector */
|
||||
const cmdBarStateSelector = (state: SnapshotFrom<typeof commandBarActor>) =>
|
||||
|
3
src/machines/machineConstants.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export const ACTOR_IDS = {
|
||||
AUTH: 'auth',
|
||||
}
|
@ -583,6 +583,13 @@ export const modelingMachine = setup({
|
||||
},
|
||||
// end guards
|
||||
actions: {
|
||||
toastError: ({ event }) => {
|
||||
if ('output' in event && event.output instanceof Error) {
|
||||
toast.error(event.output.message)
|
||||
} else if ('data' in event && event.data instanceof Error) {
|
||||
toast.error(event.data.message)
|
||||
}
|
||||
},
|
||||
'assign tool in context': assign({
|
||||
currentTool: ({ event }) =>
|
||||
'data' in event && event.data && 'tool' in event.data
|
||||
@ -637,56 +644,6 @@ export const modelingMachine = setup({
|
||||
sketchDetails: event.output,
|
||||
}
|
||||
}),
|
||||
'AST extrude': ({ context: { store }, event }) => {
|
||||
if (event.type !== 'Extrude') return
|
||||
;(async () => {
|
||||
if (!event.data) return
|
||||
const { selection, distance } = event.data
|
||||
let ast = kclManager.ast
|
||||
if (
|
||||
'variableName' in distance &&
|
||||
distance.variableName &&
|
||||
distance.insertIndex !== undefined
|
||||
) {
|
||||
const newBody = [...ast.body]
|
||||
newBody.splice(
|
||||
distance.insertIndex,
|
||||
0,
|
||||
distance.variableDeclarationAst
|
||||
)
|
||||
ast.body = newBody
|
||||
}
|
||||
const pathToNode = getNodePathFromSourceRange(
|
||||
ast,
|
||||
selection.graphSelections[0]?.codeRef.range
|
||||
)
|
||||
const extrudeSketchRes = extrudeSketch(
|
||||
ast,
|
||||
pathToNode,
|
||||
false,
|
||||
'variableName' in distance
|
||||
? distance.variableIdentifierAst
|
||||
: distance.valueAst
|
||||
)
|
||||
if (trap(extrudeSketchRes)) return
|
||||
const { modifiedAst, pathToExtrudeArg } = extrudeSketchRes
|
||||
|
||||
const updatedAst = await kclManager.updateAst(modifiedAst, true, {
|
||||
focusPath: [pathToExtrudeArg],
|
||||
zoomToFit: true,
|
||||
zoomOnRangeAndType: {
|
||||
range: selection.graphSelections[0]?.codeRef.range,
|
||||
type: 'path',
|
||||
},
|
||||
})
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
if (updatedAst?.selections) {
|
||||
editorManager.selectRange(updatedAst?.selections)
|
||||
}
|
||||
})().catch(reportRejection)
|
||||
},
|
||||
'AST revolve': ({ context: { store }, event }) => {
|
||||
if (event.type !== 'Revolve') return
|
||||
;(async () => {
|
||||
@ -1491,6 +1448,63 @@ export const modelingMachine = setup({
|
||||
return {} as SetSelections
|
||||
}
|
||||
),
|
||||
extrudeAstMod: fromPromise<
|
||||
void,
|
||||
ModelingCommandSchema['Extrude'] | undefined
|
||||
>(async ({ input }) => {
|
||||
if (!input) return Promise.reject('No input provided')
|
||||
const { selection, distance } = input
|
||||
let ast = structuredClone(kclManager.ast)
|
||||
let extrudeName: string | undefined = undefined
|
||||
|
||||
const pathToNode = getNodePathFromSourceRange(
|
||||
ast,
|
||||
selection.graphSelections[0]?.codeRef.range
|
||||
)
|
||||
// Add an extrude statement to the AST
|
||||
const extrudeSketchRes = extrudeSketch(
|
||||
ast,
|
||||
pathToNode,
|
||||
false,
|
||||
'variableName' in distance
|
||||
? distance.variableIdentifierAst
|
||||
: distance.valueAst
|
||||
)
|
||||
if (err(extrudeSketchRes)) return Promise.reject(extrudeSketchRes)
|
||||
const { modifiedAst, pathToExtrudeArg } = extrudeSketchRes
|
||||
|
||||
// Insert the distance variable if the user has provided a variable name
|
||||
if (
|
||||
'variableName' in distance &&
|
||||
distance.variableName &&
|
||||
typeof pathToExtrudeArg[1][0] === 'number'
|
||||
) {
|
||||
const insertIndex = Math.min(
|
||||
pathToExtrudeArg[1][0],
|
||||
distance.insertIndex
|
||||
)
|
||||
const newBody = [...modifiedAst.body]
|
||||
newBody.splice(insertIndex, 0, distance.variableDeclarationAst)
|
||||
modifiedAst.body = newBody
|
||||
// Since we inserted a new variable, we need to update the path to the extrude argument
|
||||
pathToExtrudeArg[1][0]++
|
||||
}
|
||||
|
||||
const updatedAst = await kclManager.updateAst(modifiedAst, true, {
|
||||
focusPath: [pathToExtrudeArg],
|
||||
zoomToFit: true,
|
||||
zoomOnRangeAndType: {
|
||||
range: selection.graphSelections[0]?.codeRef.range,
|
||||
type: 'path',
|
||||
},
|
||||
})
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
if (updatedAst?.selections) {
|
||||
editorManager.selectRange(updatedAst?.selections)
|
||||
}
|
||||
}),
|
||||
offsetPlaneAstMod: fromPromise(
|
||||
async ({
|
||||
input,
|
||||
@ -1821,9 +1835,8 @@ export const modelingMachine = setup({
|
||||
],
|
||||
|
||||
Extrude: {
|
||||
target: 'idle',
|
||||
actions: ['AST extrude'],
|
||||
reenter: false,
|
||||
target: 'Applying extrude',
|
||||
reenter: true,
|
||||
},
|
||||
|
||||
Revolve: {
|
||||
@ -2548,7 +2561,7 @@ export const modelingMachine = setup({
|
||||
|
||||
'Delete segment': {
|
||||
reenter: false,
|
||||
actions: ['Delete segment', 'Set sketchDetails'],
|
||||
actions: ['Delete segment', 'Set sketchDetails', 'reset selections'],
|
||||
},
|
||||
'code edit during sketch': '.clean slate',
|
||||
},
|
||||
@ -2620,6 +2633,22 @@ export const modelingMachine = setup({
|
||||
},
|
||||
},
|
||||
|
||||
'Applying extrude': {
|
||||
invoke: {
|
||||
src: 'extrudeAstMod',
|
||||
id: 'extrudeAstMod',
|
||||
input: ({ event }) => {
|
||||
if (event.type !== 'Extrude') return undefined
|
||||
return event.data
|
||||
},
|
||||
onDone: ['idle'],
|
||||
onError: {
|
||||
target: 'idle',
|
||||
actions: 'toastError',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Applying offset plane': {
|
||||
invoke: {
|
||||
src: 'offsetPlaneAstMod',
|
||||
|
71
src/main.ts
@ -31,23 +31,27 @@ let mainWindow: BrowserWindow | null = null
|
||||
// Check the command line arguments for a project path
|
||||
const args = parseCLIArgs()
|
||||
|
||||
// If it's not set, scream.
|
||||
const NODE_ENV = process.env.NODE_ENV || 'production'
|
||||
if (!process.env.NODE_ENV)
|
||||
console.warn(
|
||||
'*FOX SCREAM* process.env.NODE_ENV is not explicitly set!, defaulting to production'
|
||||
)
|
||||
// Default prod values
|
||||
// @ts-ignore: TS1343
|
||||
const viteEnv = import.meta.env
|
||||
const NODE_ENV = process.env.NODE_ENV || viteEnv.MODE
|
||||
|
||||
// dotenv override when present
|
||||
dotenv.config({ path: [`.env.${NODE_ENV}.local`, `.env.${NODE_ENV}`] })
|
||||
|
||||
process.env.VITE_KC_API_WS_MODELING_URL ??=
|
||||
'wss://api.zoo.dev/ws/modeling/commands'
|
||||
process.env.VITE_KC_API_BASE_URL ??= 'https://api.zoo.dev'
|
||||
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'
|
||||
// default vite values based on mode
|
||||
process.env.NODE_ENV ??= viteEnv.MODE
|
||||
process.env.DEV ??= viteEnv.DEV + ''
|
||||
process.env.BASE_URL ??= viteEnv.VITE_KC_API_BASE_URL
|
||||
process.env.VITE_KC_API_WS_MODELING_URL ??= viteEnv.VITE_KC_API_WS_MODELING_URL
|
||||
process.env.VITE_KC_API_BASE_URL ??= viteEnv.VITE_KC_API_BASE_URL
|
||||
process.env.VITE_KC_SITE_BASE_URL ??= viteEnv.VITE_KC_SITE_BASE_URL
|
||||
process.env.VITE_KC_SITE_APP_URL ??= viteEnv.VITE_KC_SITE_APP_URL
|
||||
process.env.VITE_KC_SKIP_AUTH ??= viteEnv.VITE_KC_SKIP_AUTH
|
||||
process.env.VITE_KC_CONNECTION_TIMEOUT_MS ??=
|
||||
viteEnv.VITE_KC_CONNECTION_TIMEOUT_MS
|
||||
|
||||
// Likely convenient to keep for debugging
|
||||
console.log('process.env', process.env)
|
||||
|
||||
/// Register our application to handle all "zoo-studio:" protocols.
|
||||
if (process.defaultApp) {
|
||||
@ -89,22 +93,43 @@ const createWindow = (pathToOpen?: string, reuse?: boolean): BrowserWindow => {
|
||||
})
|
||||
}
|
||||
|
||||
// Deep Link: Case of a cold start from Windows or Linux
|
||||
if (
|
||||
!pathToOpen &&
|
||||
process.argv.length > 1 &&
|
||||
process.argv[1].indexOf(ZOO_STUDIO_PROTOCOL + '://') > -1
|
||||
) {
|
||||
pathToOpen = process.argv[1]
|
||||
console.log('Retrieved deep link from argv', pathToOpen)
|
||||
}
|
||||
|
||||
// Deep Link: Case of a second window opened for macOS
|
||||
// @ts-ignore
|
||||
if (!pathToOpen && global['openUrls'] && global['openUrls'][0]) {
|
||||
// @ts-ignore
|
||||
pathToOpen = global['openUrls'][0]
|
||||
console.log('Retrieved deep link from open-url', pathToOpen)
|
||||
}
|
||||
|
||||
const pathIsCustomProtocolLink =
|
||||
pathToOpen?.startsWith(ZOO_STUDIO_PROTOCOL) ?? false
|
||||
|
||||
// and load the index.html of the app.
|
||||
if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
|
||||
const filteredPath = pathToOpen
|
||||
? decodeURI(pathToOpen.replace(ZOO_STUDIO_PROTOCOL, ''))
|
||||
? decodeURI(pathToOpen.replace(ZOO_STUDIO_PROTOCOL + '://', ''))
|
||||
: ''
|
||||
const fullHashBasedUrl = `${MAIN_WINDOW_VITE_DEV_SERVER_URL}/#/${filteredPath}`
|
||||
newWindow.loadURL(fullHashBasedUrl).catch(reportRejection)
|
||||
} else {
|
||||
if (pathIsCustomProtocolLink && pathToOpen) {
|
||||
// We're trying to open a custom protocol link
|
||||
const filteredPath = pathToOpen
|
||||
? decodeURI(pathToOpen.replace(ZOO_STUDIO_PROTOCOL, ''))
|
||||
: ''
|
||||
// TODO: fix the replace %3 thing
|
||||
const urlNoProtocol = pathToOpen
|
||||
.replace(ZOO_STUDIO_PROTOCOL + '://', '')
|
||||
.replaceAll('%3D', '')
|
||||
.replaceAll('%3', '')
|
||||
const filteredPath = decodeURI(urlNoProtocol)
|
||||
const startIndex = path.join(
|
||||
__dirname,
|
||||
`../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`
|
||||
@ -342,7 +367,7 @@ export function getAutoUpdater(): AppUpdater {
|
||||
|
||||
app.on('ready', () => {
|
||||
// Disable auto updater on non-versioned builds
|
||||
if (packageJSON.version === '0.0.0') {
|
||||
if (packageJSON.version === '0.0.0' && viteEnv.MODE !== 'production') {
|
||||
return
|
||||
}
|
||||
|
||||
@ -459,6 +484,14 @@ function parseCLIArgs(): minimist.ParsedArgs {
|
||||
}
|
||||
|
||||
function registerStartupListeners() {
|
||||
// Linux and Windows from https://www.electronjs.org/docs/latest/tutorial/launch-app-from-url-in-another-app
|
||||
app.on('second-instance', (event, commandLine, workingDirectory) => {
|
||||
// Deep Link: second instance for Windows and Linux
|
||||
const url = commandLine.pop()?.slice(0, -1)
|
||||
console.log('Retrieved deep link from commandLine', url)
|
||||
createWindow(url)
|
||||
})
|
||||
|
||||
/**
|
||||
* macOS: when someone drops a file to the not-yet running VSCode, the open-file event fires even before
|
||||
* the app-ready event. We listen very early for open-file and remember this upon startup as path to open.
|
||||
@ -478,7 +511,7 @@ function registerStartupListeners() {
|
||||
})
|
||||
|
||||
/**
|
||||
* macOS: react to open-url requests.
|
||||
* macOS: react to open-url requests (including Deep Link on second instances)
|
||||
*/
|
||||
const openUrls: string[] = []
|
||||
// @ts-ignore
|
||||
|
@ -185,6 +185,7 @@ contextBridge.exposeInMainWorld('electron', {
|
||||
'VITE_KC_API_WS_MODELING_URL',
|
||||
'VITE_KC_API_BASE_URL',
|
||||
'VITE_KC_SITE_BASE_URL',
|
||||
'VITE_KC_SITE_APP_URL',
|
||||
'VITE_KC_SKIP_AUTH',
|
||||
'VITE_KC_CONNECTION_TIMEOUT_MS',
|
||||
'VITE_KC_DEV_TOKEN',
|
||||
|
@ -1,15 +1,14 @@
|
||||
import { OnboardingButtons, useDismiss, useNextClick } from '.'
|
||||
import { onboardingPaths } from 'routes/Onboarding/paths'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
|
||||
import { useUser } from 'machines/appMachine'
|
||||
|
||||
export default function UserMenu() {
|
||||
const { auth } = useSettingsAuthContext()
|
||||
const user = useUser()
|
||||
const dismiss = useDismiss()
|
||||
const next = useNextClick(onboardingPaths.PROJECT_MENU)
|
||||
const [avatarErrored, setAvatarErrored] = useState(false)
|
||||
|
||||
const user = auth?.context?.user
|
||||
const errorOrNoImage = !user?.image || avatarErrored
|
||||
const buttonDescription = errorOrNoImage ? 'the menu button' : 'your avatar'
|
||||
|
||||
|
@ -14,6 +14,7 @@ import { openExternalBrowserIfDesktop } from 'lib/openWindow'
|
||||
import { toSync } from 'lib/utils'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
import toast from 'react-hot-toast'
|
||||
import { authActor } from 'machines/appMachine'
|
||||
|
||||
const subtleBorder =
|
||||
'border border-solid border-chalkboard-30 dark:border-chalkboard-80'
|
||||
@ -22,7 +23,6 @@ const cardArea = `${subtleBorder} rounded-lg px-6 py-3 text-chalkboard-70 dark:t
|
||||
const SignIn = () => {
|
||||
const [userCode, setUserCode] = useState('')
|
||||
const {
|
||||
auth: { send },
|
||||
settings: {
|
||||
state: {
|
||||
context: {
|
||||
@ -70,7 +70,7 @@ const SignIn = () => {
|
||||
toast.error('Error while trying to log in')
|
||||
return
|
||||
}
|
||||
send({ type: 'Log in', token })
|
||||
authActor.send({ type: 'Log in', token })
|
||||
}
|
||||
|
||||
return (
|
||||
|
6
src/wasm-lib/Cargo.lock
generated
@ -1710,7 +1710,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kcl-lib"
|
||||
version = "0.2.30"
|
||||
version = "0.2.33"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"approx 0.5.1",
|
||||
@ -1844,9 +1844,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "kittycad-modeling-cmds"
|
||||
version = "0.2.92"
|
||||
version = "0.2.93"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5fc91d0cdacd1c2ba906f564e58ce07c70a5c471f19b0f4c0b67e754077bfdc"
|
||||
checksum = "67a993046541732e3c3ddd8a0364b55b7b138a9258beff353b6e7a043a41dce3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
|
@ -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.92", 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.33"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/KittyCAD/modeling-app"
|
||||
|
@ -13,9 +13,7 @@ use tower_lsp::lsp_types::{
|
||||
MarkupKind, ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation,
|
||||
};
|
||||
|
||||
use crate::execution::Sketch;
|
||||
|
||||
use crate::std::Primitive;
|
||||
use crate::{execution::Sketch, std::Primitive};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, ts_rs::TS)]
|
||||
#[ts(export)]
|
||||
|
@ -197,10 +197,6 @@ pub trait EngineManager: std::fmt::Debug + Send + Sync + 'static {
|
||||
source_range: SourceRange,
|
||||
cmd: &ModelingCmd,
|
||||
) -> Result<(), crate::errors::KclError> {
|
||||
let execution_kind = self.execution_kind();
|
||||
if execution_kind.is_isolated() {
|
||||
return Err(KclError::Semantic(KclErrorDetails { message: "Cannot send modeling commands while importing. Wrap your code in a function if you want to import the file.".to_owned(), source_ranges: vec![source_range] }));
|
||||
}
|
||||
let req = WebSocketRequest::ModelingCmdReq(ModelingCmdReq {
|
||||
cmd: cmd.clone(),
|
||||
cmd_id: id.into(),
|
||||
|
@ -7,9 +7,9 @@ use crate::{
|
||||
KclError, SourceRange,
|
||||
};
|
||||
|
||||
pub(super) const SETTINGS: &str = "settings";
|
||||
pub(super) const SETTINGS_UNIT_LENGTH: &str = "defaultLengthUnit";
|
||||
pub(super) const SETTINGS_UNIT_ANGLE: &str = "defaultAngleUnit";
|
||||
pub(crate) const SETTINGS: &str = "settings";
|
||||
pub(crate) const SETTINGS_UNIT_LENGTH: &str = "defaultLengthUnit";
|
||||
pub(crate) const SETTINGS_UNIT_ANGLE: &str = "defaultAngleUnit";
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
|
||||
pub(super) enum AnnotationScope {
|
||||
|
@ -186,6 +186,9 @@ pub struct Wall {
|
||||
pub sweep_id: ArtifactId,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub path_ids: Vec<ArtifactId>,
|
||||
/// This is for the sketch-on-face plane, not for the wall itself. Traverse
|
||||
/// to the extrude and/or segment to get the wall's code_ref.
|
||||
pub face_code_ref: CodeRef,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS)]
|
||||
@ -199,6 +202,9 @@ pub struct Cap {
|
||||
pub sweep_id: ArtifactId,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub path_ids: Vec<ArtifactId>,
|
||||
/// This is for the sketch-on-face plane, not for the cap itself. Traverse
|
||||
/// to the extrude and/or segment to get the cap's code_ref.
|
||||
pub face_code_ref: CodeRef,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS)]
|
||||
@ -608,6 +614,17 @@ fn artifacts_to_update(
|
||||
edge_cut_edge_ids: wall.edge_cut_edge_ids.clone(),
|
||||
sweep_id: wall.sweep_id,
|
||||
path_ids: wall.path_ids.clone(),
|
||||
face_code_ref: wall.face_code_ref.clone(),
|
||||
})]);
|
||||
}
|
||||
Some(Artifact::Cap(cap)) => {
|
||||
return Ok(vec![Artifact::Cap(Cap {
|
||||
id: current_plane_id.into(),
|
||||
sub_type: cap.sub_type,
|
||||
edge_cut_edge_ids: cap.edge_cut_edge_ids.clone(),
|
||||
sweep_id: cap.sweep_id,
|
||||
path_ids: cap.path_ids.clone(),
|
||||
face_code_ref: cap.face_code_ref.clone(),
|
||||
})]);
|
||||
}
|
||||
Some(_) | None => {
|
||||
@ -654,6 +671,7 @@ fn artifacts_to_update(
|
||||
edge_cut_edge_ids: wall.edge_cut_edge_ids.clone(),
|
||||
sweep_id: wall.sweep_id,
|
||||
path_ids: vec![id],
|
||||
face_code_ref: wall.face_code_ref.clone(),
|
||||
}));
|
||||
}
|
||||
return Ok(return_arr);
|
||||
@ -776,13 +794,15 @@ fn artifacts_to_update(
|
||||
"Expected a sweep ID on the path when processing Solid3dGetExtrusionFaceInfo command, but we have none: {id:?}, {path:?}"
|
||||
))
|
||||
})?;
|
||||
return_arr.push(Artifact::Wall(Wall {
|
||||
let extraArtifacts = ;
|
||||
let wall = Wall {
|
||||
id: face_id,
|
||||
seg_id: curve_id,
|
||||
edge_cut_edge_ids: Vec::new(),
|
||||
sweep_id: path_sweep_id,
|
||||
path_ids: vec![],
|
||||
}));
|
||||
};
|
||||
return_arr.push(Artifact::Wall(wall));
|
||||
let mut new_seg = seg.clone();
|
||||
new_seg.surface_id = Some(face_id);
|
||||
return_arr.push(Artifact::Segment(new_seg));
|
||||
|
@ -462,12 +462,14 @@ impl ArtifactGraph {
|
||||
output.push_str("mindmap\n");
|
||||
output.push_str(" root\n");
|
||||
|
||||
let mut ids_seen: fnv::FnvHashSet<ArtifactId> = Default::default();
|
||||
|
||||
for (_, artifact) in &self.map {
|
||||
// Only the planes are roots.
|
||||
let Artifact::Plane(_) = artifact else {
|
||||
continue;
|
||||
};
|
||||
self.mind_map_artifact(&mut output, artifact, " ")?;
|
||||
self.mind_map_artifact(&mut output, &mut ids_seen, artifact, " ")?;
|
||||
}
|
||||
|
||||
output.push_str("```\n");
|
||||
@ -475,9 +477,16 @@ impl ArtifactGraph {
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
fn mind_map_artifact<W: Write>(&self, output: &mut W, artifact: &Artifact, prefix: &str) -> std::fmt::Result {
|
||||
fn mind_map_artifact<W: Write>(
|
||||
&self,
|
||||
output: &mut W,
|
||||
ids_seen: &mut fnv::FnvHashSet<ArtifactId>,
|
||||
artifact: &Artifact,
|
||||
prefix: &str,
|
||||
) -> std::fmt::Result {
|
||||
match artifact {
|
||||
Artifact::Plane(_plane) => {
|
||||
ids_seen.clear();
|
||||
writeln!(output, "{prefix}Plane")?;
|
||||
}
|
||||
Artifact::Path(_path) => {
|
||||
@ -515,11 +524,17 @@ impl ArtifactGraph {
|
||||
}
|
||||
}
|
||||
|
||||
if ids_seen.contains(&artifact.id()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
ids_seen.insert(artifact.id());
|
||||
|
||||
for child_id in artifact.child_ids() {
|
||||
let Some(child_artifact) = self.map.get(&child_id) else {
|
||||
continue;
|
||||
};
|
||||
self.mind_map_artifact(output, child_artifact, &format!("{} ", prefix))?;
|
||||
self.mind_map_artifact(output, ids_seen, child_artifact, &format!("{} ", prefix))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|