Compare commits
31 Commits
derive-doc
...
cut-releas
Author | SHA1 | Date | |
---|---|---|---|
14db5d3141 | |||
66bbbf81e2 | |||
b1656b2c50 | |||
652519aeae | |||
042a872f18 | |||
f826afb32d | |||
f71fafdece | |||
16b7544d69 | |||
34f019305b | |||
79e06b3a00 | |||
24bc4fcd8c | |||
97b9529c81 | |||
637acf1cf9 | |||
8e5fc02941 | |||
909690f3c7 | |||
14ba66378d | |||
b2e895e508 | |||
05f4f34269 | |||
fbb7b08b62 | |||
16c7a2457a | |||
c429bc6ed7 | |||
a0493cb332 | |||
b798f7da03 | |||
c5d051855f | |||
0b24216dc5 | |||
2d3841bf61 | |||
51a71a180e | |||
1ec25dfe96 | |||
8de29dd461 | |||
b11040c23c | |||
2bc4f076cb |
4
.github/workflows/cargo-test.yml
vendored
@ -5,6 +5,8 @@ on:
|
||||
paths:
|
||||
- 'src/wasm-lib/**.rs'
|
||||
- 'src/wasm-lib/**.hbs'
|
||||
- 'src/wasm-lib/**.gen'
|
||||
- 'src/wasm-lib/**.snap'
|
||||
- '**/Cargo.toml'
|
||||
- '**/Cargo.lock'
|
||||
- '**/rust-toolchain.toml'
|
||||
@ -15,6 +17,8 @@ on:
|
||||
paths:
|
||||
- 'src/wasm-lib/**.rs'
|
||||
- 'src/wasm-lib/**.hbs'
|
||||
- 'src/wasm-lib/**.gen'
|
||||
- 'src/wasm-lib/**.snap'
|
||||
- '**/Cargo.toml'
|
||||
- '**/Cargo.lock'
|
||||
- '**/rust-toolchain.toml'
|
||||
|
2
Makefile
@ -19,7 +19,7 @@ $(XSTATE_TYPEGENS): $(TS_SRC)
|
||||
yarn xstate typegen 'src/**/*.ts?(x)'
|
||||
|
||||
public/wasm_lib_bg.wasm: $(WASM_LIB_FILES)
|
||||
yarn build:wasm-dev
|
||||
yarn build:wasm
|
||||
|
||||
node_modules: package.json yarn.lock
|
||||
yarn install
|
||||
|
@ -110,7 +110,7 @@ Which commands from setup are one off vs need to be run every time?
|
||||
The following will need to be run when checking out a new commit and guarantees the build is not stale:
|
||||
```bash
|
||||
yarn install
|
||||
yarn build:wasm-dev # or yarn build:wasm for slower but more production-like build
|
||||
yarn build:wasm
|
||||
yarn start # or yarn build:local && yarn serve for slower but more production-like build
|
||||
```
|
||||
|
||||
|
@ -1,10 +1,10 @@
|
||||
---
|
||||
title: "angleToMatchLengthX"
|
||||
excerpt: "Compute the angle (in degrees) in o"
|
||||
excerpt: "Returns the angle to match the given length for x."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
Compute the angle (in degrees) in o
|
||||
Returns the angle to match the given length for x.
|
||||
|
||||
|
||||
|
||||
|
41
docs/kcl/arcTo.md
Normal file
@ -7,6 +7,7 @@ layout: manual
|
||||
## Table of Contents
|
||||
|
||||
* [Types](kcl/types)
|
||||
* [Modules](kcl/modules)
|
||||
* [Known Issues](kcl/KNOWN-ISSUES)
|
||||
* [`abs`](kcl/abs)
|
||||
* [`acos`](kcl/acos)
|
||||
@ -19,6 +20,7 @@ layout: manual
|
||||
* [`angledLineToX`](kcl/angledLineToX)
|
||||
* [`angledLineToY`](kcl/angledLineToY)
|
||||
* [`arc`](kcl/arc)
|
||||
* [`arcTo`](kcl/arcTo)
|
||||
* [`asin`](kcl/asin)
|
||||
* [`assert`](kcl/assert)
|
||||
* [`assertEqual`](kcl/assertEqual)
|
||||
|
59
docs/kcl/modules.md
Normal file
@ -0,0 +1,59 @@
|
||||
---
|
||||
title: "KCL Modules"
|
||||
excerpt: "Documentation of modules for the KCL language for the Zoo Modeling App."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
`KCL` allows splitting code up into multiple files. Each file is somewhat
|
||||
isolated from other files as a separate module.
|
||||
|
||||
When you define a function, you can use `export` before it to make it available
|
||||
to other modules.
|
||||
|
||||
```
|
||||
// util.kcl
|
||||
export fn increment = (x) => {
|
||||
return x + 1
|
||||
}
|
||||
```
|
||||
|
||||
Other files in the project can now import functions that have been exported.
|
||||
This makes them available to use in another file.
|
||||
|
||||
```
|
||||
// main.kcl
|
||||
import increment from "util.kcl"
|
||||
|
||||
answer = increment(41)
|
||||
```
|
||||
|
||||
Imported files _must_ be in the same project so that units are uniform across
|
||||
modules. This means that it must be in the same directory.
|
||||
|
||||
Import statements must be at the top-level of a file. It is not allowed to have
|
||||
an `import` statement inside a function or in the body of an if-else.
|
||||
|
||||
Multiple functions can be exported in a file.
|
||||
|
||||
```
|
||||
// util.kcl
|
||||
export fn increment = (x) => {
|
||||
return x + 1
|
||||
}
|
||||
|
||||
export fn decrement = (x) => {
|
||||
return x - 1
|
||||
}
|
||||
```
|
||||
|
||||
When importing, you can import multiple functions at once.
|
||||
|
||||
```
|
||||
import increment, decrement from "util.kcl"
|
||||
```
|
||||
|
||||
Imported symbols can be renamed for convenience or to avoid name collisions.
|
||||
|
||||
```
|
||||
import increment as inc, decrement as dec from "util.kcl"
|
||||
```
|
9449
docs/kcl/std.json
22
docs/kcl/types/ArcToData.md
Normal file
@ -0,0 +1,22 @@
|
||||
---
|
||||
title: "ArcToData"
|
||||
excerpt: "Data to draw a three point arc (arcTo)."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
Data to draw a three point arc (arcTo).
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `end` |`[number, number]`| End point of the arc. A point in 3D space | No |
|
||||
| `interior` |`[number, number]`| Interior point of the arc. A point in 3D space | No |
|
||||
|
||||
|
16
docs/kcl/types/KclNone.md
Normal file
@ -0,0 +1,16 @@
|
||||
---
|
||||
title: "KclNone"
|
||||
excerpt: "KCL value for an optional parameter which was not given an argument. (remember, parameters are in the function declaration, arguments are in the function call/application)."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
KCL value for an optional parameter which was not given an argument. (remember, parameters are in the function declaration, arguments are in the function call/application).
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -23,8 +23,110 @@ Any KCL value.
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `UserVal`| | No |
|
||||
| `value` |``| | No |
|
||||
| `type` |enum: `Uuid`| | No |
|
||||
| `value` |`string`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Bool`| | No |
|
||||
| `value` |`boolean`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Number`| | No |
|
||||
| `value` |`number`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Int`| | No |
|
||||
| `value` |`integer`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `String`| | No |
|
||||
| `value` |`string`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Array`| | No |
|
||||
| `value` |`[` [`KclValue`](/docs/kcl/types/KclValue) `]`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Object`| | No |
|
||||
| `value` |`object`| | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
@ -78,7 +180,7 @@ A plane.
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Plane`| | No |
|
||||
| `type` |enum: [`Plane`](/docs/kcl/types/Plane)| | No |
|
||||
| `id` |`string`| The id of the plane. | No |
|
||||
| `value` |[`PlaneType`](/docs/kcl/types/PlaneType)| Any KCL value. | No |
|
||||
| `origin` |[`Point3d`](/docs/kcl/types/Point3d)| Origin of the plane. | No |
|
||||
@ -111,6 +213,38 @@ A face.
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: [`Sketch`](/docs/kcl/types/Sketch)| | No |
|
||||
| `value` |[`Sketch`](/docs/kcl/types/Sketch)| Any KCL value. | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: `Sketches`| | No |
|
||||
| `value` |`[` [`Sketch`](/docs/kcl/types/Sketch) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
An solid is a collection of extrude surfaces.
|
||||
|
||||
@ -190,6 +324,23 @@ Data for an imported geometry.
|
||||
|
||||
----
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `type` |enum: [`KclNone`](/docs/kcl/types/KclNone)| | No |
|
||||
| `value` |[`KclNone`](/docs/kcl/types/KclNone)| Any KCL value. | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
||||
----
|
||||
|
||||
|
||||
|
||||
|
||||
|
27
docs/kcl/types/Plane.md
Normal file
@ -0,0 +1,27 @@
|
||||
---
|
||||
title: "Plane"
|
||||
excerpt: "A plane."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
A plane.
|
||||
|
||||
**Type:** `object`
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## Properties
|
||||
|
||||
| Property | Type | Description | Required |
|
||||
|----------|------|-------------|----------|
|
||||
| `id` |`string`| The id of the plane. | No |
|
||||
| `value` |[`PlaneType`](/docs/kcl/types/PlaneType)| A plane. | No |
|
||||
| `origin` |[`Point3d`](/docs/kcl/types/Point3d)| Origin of the plane. | No |
|
||||
| `xAxis` |[`Point3d`](/docs/kcl/types/Point3d)| What should the plane’s X axis be? | No |
|
||||
| `yAxis` |[`Point3d`](/docs/kcl/types/Point3d)| What should the plane’s Y axis be? | No |
|
||||
| `zAxis` |[`Point3d`](/docs/kcl/types/Point3d)| The z-axis (normal). | No |
|
||||
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
|
||||
|
||||
|
@ -1,10 +1,10 @@
|
||||
---
|
||||
title: "PlaneData"
|
||||
excerpt: "Data for a plane."
|
||||
excerpt: "Orientation data that can be used to construct a plane, not a plane in itself."
|
||||
layout: manual
|
||||
---
|
||||
|
||||
Data for a plane.
|
||||
Orientation data that can be used to construct a plane, not a plane in itself.
|
||||
|
||||
|
||||
|
||||
|
@ -22,6 +22,18 @@ Data for start sketch on. You can start a sketch on a plane or an solid.
|
||||
|
||||
|
||||
|
||||
----
|
||||
Data for start sketch on. You can start a sketch on a plane or an solid.
|
||||
|
||||
[`Plane`](/docs/kcl/types/Plane)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
----
|
||||
Data for start sketch on. You can start a sketch on a plane or an solid.
|
||||
|
||||
|
@ -67,15 +67,15 @@ async function doBasicSketch(page: Page, openPanes: string[]) {
|
||||
if (openPanes.includes('code')) {
|
||||
await expect(u.codeLocator).toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)`)
|
||||
}
|
||||
await page.waitForTimeout(500)
|
||||
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20)
|
||||
if (openPanes.includes('code')) {
|
||||
await expect(u.codeLocator).toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)
|
||||
|> line([0, ${commonPoints.num1 + 0.01}], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)
|
||||
|> yLine(${commonPoints.num1 + 0.01}, %)`)
|
||||
} else {
|
||||
await page.waitForTimeout(500)
|
||||
}
|
||||
@ -84,9 +84,9 @@ async function doBasicSketch(page: Page, openPanes: string[]) {
|
||||
if (openPanes.includes('code')) {
|
||||
await expect(u.codeLocator).toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)
|
||||
|> line([0, ${commonPoints.num1 + 0.01}], %)
|
||||
|> lineTo([0, ${commonPoints.num3}], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)
|
||||
|> yLine(${commonPoints.num1 + 0.01}, %)
|
||||
|> xLine(${commonPoints.num2 * -1}, %)`)
|
||||
}
|
||||
|
||||
// deselect line tool
|
||||
@ -142,9 +142,9 @@ async function doBasicSketch(page: Page, openPanes: string[]) {
|
||||
await u.openKclCodePanel()
|
||||
await expect(u.codeLocator).toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %, $seg01)
|
||||
|> line([0, ${commonPoints.num1 + 0.01}], %)
|
||||
|> angledLine([180, segLen(seg01)], %)`)
|
||||
|> xLine(${commonPoints.num1}, %, $seg01)
|
||||
|> yLine(${commonPoints.num1 + 0.01}, %)
|
||||
|> xLine(-segLen(seg01), %)`)
|
||||
}
|
||||
|
||||
test.describe('Basic sketch', () => {
|
||||
|
@ -62,6 +62,8 @@ test(
|
||||
const errorToastMessage = page.getByText(`Error while exporting`)
|
||||
const engineErrorToastMessage = page.getByText(`Nothing to export`)
|
||||
const alreadyExportingToastMessage = page.getByText(`Already exporting`)
|
||||
// The open file's name is `main.kcl`, so the export file name should be `main.gltf`
|
||||
const exportFileName = `main.gltf`
|
||||
|
||||
// Click the export button
|
||||
await exportButton.click()
|
||||
@ -96,7 +98,7 @@ test(
|
||||
.poll(
|
||||
async () => {
|
||||
try {
|
||||
const outputGltf = await fsp.readFile('output.gltf')
|
||||
const outputGltf = await fsp.readFile(exportFileName)
|
||||
return outputGltf.byteLength
|
||||
} catch (e) {
|
||||
return 0
|
||||
@ -106,8 +108,8 @@ test(
|
||||
)
|
||||
.toBeGreaterThan(300_000)
|
||||
|
||||
// clean up output.gltf
|
||||
await fsp.rm('output.gltf')
|
||||
// clean up exported file
|
||||
await fsp.rm(exportFileName)
|
||||
})
|
||||
})
|
||||
|
||||
@ -138,6 +140,8 @@ test(
|
||||
const errorToastMessage = page.getByText(`Error while exporting`)
|
||||
const engineErrorToastMessage = page.getByText(`Nothing to export`)
|
||||
const alreadyExportingToastMessage = page.getByText(`Already exporting`)
|
||||
// The open file's name is `other.kcl`, so the export file name should be `other.gltf`
|
||||
const exportFileName = `other.gltf`
|
||||
|
||||
// Click the export button
|
||||
await exportButton.click()
|
||||
@ -171,7 +175,7 @@ test(
|
||||
.poll(
|
||||
async () => {
|
||||
try {
|
||||
const outputGltf = await fsp.readFile('output.gltf')
|
||||
const outputGltf = await fsp.readFile(exportFileName)
|
||||
return outputGltf.byteLength
|
||||
} catch (e) {
|
||||
return 0
|
||||
@ -181,8 +185,8 @@ test(
|
||||
)
|
||||
.toBeGreaterThan(100_000)
|
||||
|
||||
// clean up output.gltf
|
||||
await fsp.rm('output.gltf')
|
||||
// clean up exported file
|
||||
await fsp.rm(exportFileName)
|
||||
})
|
||||
await electronApp.close()
|
||||
})
|
||||
|
@ -694,6 +694,9 @@ test.describe('Editor tests', () => {
|
||||
.toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([3.14, 12], %)
|
||||
|> xLine(5, %) // lin`)
|
||||
|
||||
// expect there to be no KCL errors
|
||||
await expect(page.locator('.cm-lint-marker-error')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('with tab to accept the completion', async ({ page }) => {
|
||||
|
@ -1135,3 +1135,189 @@ _test.describe('Deleting items from the file pane', () => {
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
_test.describe(
|
||||
'Undo and redo do not keep history when navigating between files',
|
||||
() => {
|
||||
_test(
|
||||
`open a file, change something, open a different file, hitting undo should do nothing`,
|
||||
{ tag: '@electron' },
|
||||
async ({ browserName }, testInfo) => {
|
||||
const { page } = await setupElectron({
|
||||
testInfo,
|
||||
folderSetupFn: async (dir) => {
|
||||
const testDir = join(dir, 'testProject')
|
||||
await fsp.mkdir(testDir, { recursive: true })
|
||||
await fsp.copyFile(
|
||||
executorInputPath('cylinder.kcl'),
|
||||
join(testDir, 'main.kcl')
|
||||
)
|
||||
await fsp.copyFile(
|
||||
executorInputPath('basic_fillet_cube_end.kcl'),
|
||||
join(testDir, 'other.kcl')
|
||||
)
|
||||
},
|
||||
})
|
||||
const u = await getUtils(page)
|
||||
await page.setViewportSize({ width: 1200, height: 500 })
|
||||
page.on('console', console.log)
|
||||
|
||||
// Constants and locators
|
||||
const projectCard = page.getByText('testProject')
|
||||
const otherFile = page
|
||||
.getByRole('listitem')
|
||||
.filter({ has: page.getByRole('button', { name: 'other.kcl' }) })
|
||||
|
||||
await _test.step(
|
||||
'Open project and make a change to the file',
|
||||
async () => {
|
||||
await projectCard.click()
|
||||
await u.waitForPageLoad()
|
||||
|
||||
// Get the text in the code locator.
|
||||
const originalText = await u.codeLocator.innerText()
|
||||
// Click in the editor and add some new lines.
|
||||
await u.codeLocator.click()
|
||||
|
||||
await page.keyboard.type(`sketch001 = startSketchOn('XY')
|
||||
some other shit`)
|
||||
|
||||
// Ensure the content in the editor changed.
|
||||
const newContent = await u.codeLocator.innerText()
|
||||
|
||||
expect(originalText !== newContent)
|
||||
}
|
||||
)
|
||||
|
||||
await _test.step('navigate to other.kcl', async () => {
|
||||
await u.openFilePanel()
|
||||
|
||||
await otherFile.click()
|
||||
await u.waitForPageLoad()
|
||||
await u.openKclCodePanel()
|
||||
await _expect(u.codeLocator).toContainText('getOppositeEdge(thing)')
|
||||
})
|
||||
|
||||
await _test.step('hit undo', async () => {
|
||||
// Get the original content of the file.
|
||||
const originalText = await u.codeLocator.innerText()
|
||||
// Now hit undo
|
||||
await page.keyboard.down('ControlOrMeta')
|
||||
await page.keyboard.press('KeyZ')
|
||||
await page.keyboard.up('ControlOrMeta')
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
await expect(u.codeLocator).toContainText(originalText)
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
_test(
|
||||
`open a file, change something, undo it, open a different file, hitting redo should do nothing`,
|
||||
{ tag: '@electron' },
|
||||
// Skip on windows i think the keybindings are different for redo.
|
||||
async ({ browserName }, testInfo) => {
|
||||
test.skip(process.platform === 'win32', 'Skip on windows')
|
||||
const { page } = await setupElectron({
|
||||
testInfo,
|
||||
folderSetupFn: async (dir) => {
|
||||
const testDir = join(dir, 'testProject')
|
||||
await fsp.mkdir(testDir, { recursive: true })
|
||||
await fsp.copyFile(
|
||||
executorInputPath('cylinder.kcl'),
|
||||
join(testDir, 'main.kcl')
|
||||
)
|
||||
await fsp.copyFile(
|
||||
executorInputPath('basic_fillet_cube_end.kcl'),
|
||||
join(testDir, 'other.kcl')
|
||||
)
|
||||
},
|
||||
})
|
||||
const u = await getUtils(page)
|
||||
await page.setViewportSize({ width: 1200, height: 500 })
|
||||
page.on('console', console.log)
|
||||
|
||||
// Constants and locators
|
||||
const projectCard = page.getByText('testProject')
|
||||
const otherFile = page
|
||||
.getByRole('listitem')
|
||||
.filter({ has: page.getByRole('button', { name: 'other.kcl' }) })
|
||||
|
||||
const badContent = 'this shit'
|
||||
await _test.step(
|
||||
'Open project and make a change to the file',
|
||||
async () => {
|
||||
await projectCard.click()
|
||||
await u.waitForPageLoad()
|
||||
|
||||
// Get the text in the code locator.
|
||||
const originalText = await u.codeLocator.innerText()
|
||||
// Click in the editor and add some new lines.
|
||||
await u.codeLocator.click()
|
||||
|
||||
await page.keyboard.type(badContent)
|
||||
|
||||
// Ensure the content in the editor changed.
|
||||
const newContent = await u.codeLocator.innerText()
|
||||
|
||||
expect(originalText !== newContent)
|
||||
|
||||
// Now hit undo
|
||||
await page.keyboard.down('ControlOrMeta')
|
||||
await page.keyboard.press('KeyZ')
|
||||
await page.keyboard.up('ControlOrMeta')
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
await expect(u.codeLocator).toContainText(originalText)
|
||||
await expect(u.codeLocator).not.toContainText(badContent)
|
||||
|
||||
// Hit redo.
|
||||
await page.keyboard.down('Shift')
|
||||
await page.keyboard.down('ControlOrMeta')
|
||||
await page.keyboard.press('KeyZ')
|
||||
await page.keyboard.up('ControlOrMeta')
|
||||
await page.keyboard.up('Shift')
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
await expect(u.codeLocator).toContainText(originalText)
|
||||
await expect(u.codeLocator).toContainText(badContent)
|
||||
|
||||
// Now hit undo
|
||||
await page.keyboard.down('ControlOrMeta')
|
||||
await page.keyboard.press('KeyZ')
|
||||
await page.keyboard.up('ControlOrMeta')
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
await expect(u.codeLocator).toContainText(originalText)
|
||||
await expect(u.codeLocator).not.toContainText(badContent)
|
||||
}
|
||||
)
|
||||
|
||||
await _test.step('navigate to other.kcl', async () => {
|
||||
await u.openFilePanel()
|
||||
|
||||
await otherFile.click()
|
||||
await u.waitForPageLoad()
|
||||
await u.openKclCodePanel()
|
||||
await _expect(u.codeLocator).toContainText('getOppositeEdge(thing)')
|
||||
await expect(u.codeLocator).not.toContainText(badContent)
|
||||
})
|
||||
|
||||
await _test.step('hit redo', async () => {
|
||||
// Get the original content of the file.
|
||||
const originalText = await u.codeLocator.innerText()
|
||||
// Now hit redo
|
||||
await page.keyboard.down('Shift')
|
||||
await page.keyboard.down('ControlOrMeta')
|
||||
await page.keyboard.press('KeyZ')
|
||||
await page.keyboard.up('ControlOrMeta')
|
||||
await page.keyboard.up('Shift')
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
await expect(u.codeLocator).toContainText(originalText)
|
||||
await expect(u.codeLocator).not.toContainText(badContent)
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
|
@ -452,7 +452,7 @@ sketch002 = startSketchOn(extrude001, seg03)
|
||||
)
|
||||
})
|
||||
|
||||
test(`Verify axis and origin snapping`, async ({
|
||||
test(`Verify axis, origin, and horizontal snapping`, async ({
|
||||
app,
|
||||
editor,
|
||||
toolbar,
|
||||
@ -505,7 +505,7 @@ test(`Verify axis and origin snapping`, async ({
|
||||
const expectedCodeSnippets = {
|
||||
sketchOnXzPlane: `sketch001 = startSketchOn('XZ')`,
|
||||
pointAtOrigin: `startProfileAt([${originSloppy.kcl[0]}, ${originSloppy.kcl[1]}], %)`,
|
||||
segmentOnXAxis: `lineTo([${xAxisSloppy.kcl[0]}, ${xAxisSloppy.kcl[1]}], %)`,
|
||||
segmentOnXAxis: `xLine(${xAxisSloppy.kcl[0]}, %)`,
|
||||
afterSegmentDraggedOffYAxis: `startProfileAt([${offYAxis.kcl[0]}, ${offYAxis.kcl[1]}], %)`,
|
||||
afterSegmentDraggedOnYAxis: `startProfileAt([${yAxisSloppy.kcl[0]}, ${yAxisSloppy.kcl[1]}], %)`,
|
||||
}
|
||||
|
@ -247,7 +247,7 @@ test.describe('Can export from electron app', () => {
|
||||
.poll(
|
||||
async () => {
|
||||
try {
|
||||
const outputGltf = await fsp.readFile('output.gltf')
|
||||
const outputGltf = await fsp.readFile('main.gltf')
|
||||
return outputGltf.byteLength
|
||||
} catch (e) {
|
||||
return 0
|
||||
@ -257,8 +257,8 @@ test.describe('Can export from electron app', () => {
|
||||
)
|
||||
.toBeGreaterThan(300_000)
|
||||
|
||||
// clean up output.gltf
|
||||
await fsp.rm('output.gltf')
|
||||
// clean up exported file
|
||||
await fsp.rm('main.gltf')
|
||||
})
|
||||
|
||||
await electronApp.close()
|
||||
|
@ -115,7 +115,7 @@ test.describe('Sketch tests', () => {
|
||||
'persistCode',
|
||||
`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([4.61, -14.01], %)
|
||||
|> line([12.73, -0.09], %)
|
||||
|> xLine(12.73, %)
|
||||
|> tangentialArcTo([24.95, -5.38], %)`
|
||||
)
|
||||
})
|
||||
@ -156,7 +156,7 @@ test.describe('Sketch tests', () => {
|
||||
await expect.poll(u.normalisedEditorCode, { timeout: 1000 })
|
||||
.toBe(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([12.34, -12.34], %)
|
||||
|> line([-12.34, 12.34], %)
|
||||
|> yLine(12.34, %)
|
||||
|
||||
`)
|
||||
}).toPass({ timeout: 40_000, intervals: [1_000] })
|
||||
@ -645,7 +645,7 @@ test.describe('Sketch tests', () => {
|
||||
await u.openDebugPanel()
|
||||
|
||||
const center = { x: viewportSize.width / 2, y: viewportSize.height / 2 }
|
||||
const { toSU, click00r } = getMovementUtils({ center, page })
|
||||
const { toSU, toU, click00r } = getMovementUtils({ center, page })
|
||||
|
||||
await expect(
|
||||
page.getByRole('button', { name: 'Start Sketch' })
|
||||
@ -674,16 +674,15 @@ test.describe('Sketch tests', () => {
|
||||
|
||||
await click00r(50, 0)
|
||||
await page.waitForTimeout(100)
|
||||
codeStr += ` |> lineTo(${toSU([50, 0])}, %)`
|
||||
codeStr += ` |> xLine(${toU(50, 0)[0]}, %)`
|
||||
await expect(u.codeLocator).toHaveText(codeStr)
|
||||
|
||||
await click00r(0, 50)
|
||||
codeStr += ` |> line(${toSU([0, 50])}, %)`
|
||||
codeStr += ` |> yLine(${toU(0, 50)[1]}, %)`
|
||||
await expect(u.codeLocator).toHaveText(codeStr)
|
||||
|
||||
let clickCoords = await click00r(-50, 0)
|
||||
expect(clickCoords).not.toBeUndefined()
|
||||
codeStr += ` |> lineTo(${toSU(clickCoords!)}, %)`
|
||||
await click00r(-50, 0)
|
||||
codeStr += ` |> xLine(${toU(-50, 0)[0]}, %)`
|
||||
await expect(u.codeLocator).toHaveText(codeStr)
|
||||
|
||||
// exit the sketch, reset relative clicker
|
||||
@ -712,15 +711,15 @@ test.describe('Sketch tests', () => {
|
||||
// TODO: I couldn't use `toSU` here because of some rounding error causing
|
||||
// it to be off by 0.01
|
||||
await click00r(30, 0)
|
||||
codeStr += ` |> lineTo([4.07, 0], %)`
|
||||
codeStr += ` |> xLine(2.04, %)`
|
||||
await expect(u.codeLocator).toHaveText(codeStr)
|
||||
|
||||
await click00r(0, 30)
|
||||
codeStr += ` |> line([0, -2.03], %)`
|
||||
codeStr += ` |> yLine(-2.03, %)`
|
||||
await expect(u.codeLocator).toHaveText(codeStr)
|
||||
|
||||
await click00r(-30, 0)
|
||||
codeStr += ` |> line([-2.04, 0], %)`
|
||||
codeStr += ` |> xLine(-2.04, %)`
|
||||
await expect(u.codeLocator).toHaveText(codeStr)
|
||||
|
||||
await click00r(undefined, undefined)
|
||||
@ -744,8 +743,8 @@ test.describe('Sketch tests', () => {
|
||||
|
||||
const code = `sketch001 = startSketchOn('-XZ')
|
||||
|> startProfileAt([${roundOff(scale * 69.6)}, ${roundOff(scale * 34.8)}], %)
|
||||
|> line([${roundOff(scale * 139.19)}, 0], %)
|
||||
|> line([0, -${roundOff(scale * 139.2)}], %)
|
||||
|> xLine(${roundOff(scale * 139.19)}, %)
|
||||
|> yLine(-${roundOff(scale * 139.2)}, %)
|
||||
|> lineTo([profileStartX(%), profileStartY(%)], %)
|
||||
|> close(%)`
|
||||
|
||||
@ -1275,3 +1274,44 @@ test2.describe('Sketch mode should be toleratant to syntax errors', () => {
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
test2.describe(`Sketching with offset planes`, () => {
|
||||
test2(
|
||||
`Can select an offset plane to sketch on`,
|
||||
async ({ app, scene, toolbar, editor }) => {
|
||||
// We seed the scene with a single offset plane
|
||||
await app.initialise(`offsetPlane001 = offsetPlane("XY", 10)`)
|
||||
|
||||
const [planeClick, planeHover] = scene.makeMouseHelpers(650, 200)
|
||||
|
||||
await test2.step(`Start sketching on the offset plane`, async () => {
|
||||
await toolbar.startSketchPlaneSelection()
|
||||
|
||||
await test2.step(`Hovering should highlight code`, async () => {
|
||||
await planeHover()
|
||||
await editor.expectState({
|
||||
activeLines: [`offsetPlane001=offsetPlane("XY",10)`],
|
||||
diagnostics: [],
|
||||
highlightedCode: 'offsetPlane("XY", 10)',
|
||||
})
|
||||
})
|
||||
|
||||
await test2.step(
|
||||
`Clicking should select the plane and enter sketch mode`,
|
||||
async () => {
|
||||
await planeClick()
|
||||
// Have to wait for engine-side animation to finish
|
||||
await app.page.waitForTimeout(600)
|
||||
await expect2(toolbar.lineBtn).toBeEnabled()
|
||||
await editor.expectEditor.toContain('startSketchOn(offsetPlane001)')
|
||||
await editor.expectState({
|
||||
activeLines: [`offsetPlane001=offsetPlane("XY",10)`],
|
||||
diagnostics: [],
|
||||
highlightedCode: '',
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
|
@ -283,7 +283,7 @@ part001 = startSketchOn('-XZ')
|
||||
const gltfFilename = filenames.filter((t: string) =>
|
||||
t.includes('.gltf')
|
||||
)[0]
|
||||
if (!gltfFilename) throw new Error('No output.gltf in this archive')
|
||||
if (!gltfFilename) throw new Error('No gLTF in this archive')
|
||||
cliCommand = `export ZOO_TOKEN=${secrets.snapshottoken} && zoo file snapshot --output-format=png --src-format=${outputType} ${parentPath}/${gltfFilename} ${imagePath}`
|
||||
}
|
||||
|
||||
@ -462,7 +462,7 @@ test(
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
code += `
|
||||
|> line([7.25, 0], %)`
|
||||
|> xLine(7.25, %)`
|
||||
await expect(page.locator('.cm-content')).toHaveText(code)
|
||||
|
||||
await page
|
||||
@ -647,7 +647,7 @@ test.describe(
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
code += `
|
||||
|> line([7.25, 0], %)`
|
||||
|> xLine(7.25, %)`
|
||||
await expect(u.codeLocator).toHaveText(code)
|
||||
|
||||
await page
|
||||
@ -752,7 +752,7 @@ test.describe(
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
code += `
|
||||
|> line([184.3, 0], %)`
|
||||
|> xLine(184.3, %)`
|
||||
await expect(u.codeLocator).toHaveText(code)
|
||||
|
||||
await page
|
||||
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 52 KiB |
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 46 KiB |
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 58 KiB |
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 50 KiB |
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 47 KiB |
Before Width: | Height: | Size: 49 KiB After Width: | Height: | Size: 49 KiB |
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 47 KiB |
Before Width: | Height: | Size: 47 KiB After Width: | Height: | Size: 47 KiB |
Before Width: | Height: | Size: 65 KiB After Width: | Height: | Size: 65 KiB |
Before Width: | Height: | Size: 40 KiB After Width: | Height: | Size: 40 KiB |
@ -141,7 +141,7 @@ test.describe('Test network and connection issues', () => {
|
||||
await expect(page.locator('.cm-content'))
|
||||
.toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)`)
|
||||
|
||||
// Expect the network to be up
|
||||
await expect(networkToggle).toContainText('Connected')
|
||||
@ -207,7 +207,7 @@ test.describe('Test network and connection issues', () => {
|
||||
await expect.poll(u.normalisedEditorCode)
|
||||
.toBe(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([12.34, -12.34], %)
|
||||
|> line([12.34, 0], %)
|
||||
|> xLine(12.34, %)
|
||||
|> line([-12.34, 12.34], %)
|
||||
|
||||
`)
|
||||
@ -217,9 +217,9 @@ test.describe('Test network and connection issues', () => {
|
||||
await expect.poll(u.normalisedEditorCode)
|
||||
.toBe(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt([12.34, -12.34], %)
|
||||
|> line([12.34, 0], %)
|
||||
|> xLine(12.34, %)
|
||||
|> line([-12.34, 12.34], %)
|
||||
|> lineTo([0, -12.34], %)
|
||||
|> xLine(-12.34, %)
|
||||
|
||||
`)
|
||||
|
||||
|
@ -305,7 +305,7 @@ export const getMovementUtils = (opts: any) => {
|
||||
return [last.x, last.y]
|
||||
}
|
||||
|
||||
return { toSU, click00r }
|
||||
return { toSU, toU, click00r }
|
||||
}
|
||||
|
||||
async function waitForAuthAndLsp(page: Page) {
|
||||
|
@ -32,10 +32,17 @@ test.describe('Testing selections', () => {
|
||||
await u.waitForAuthSkipAppStart()
|
||||
await u.openDebugPanel()
|
||||
|
||||
const xAxisClick = () =>
|
||||
page.mouse.click(700, 253).then(() => page.waitForTimeout(100))
|
||||
const yAxisClick = () =>
|
||||
test.step('Click on Y axis', async () => {
|
||||
await page.mouse.move(600, 200, { steps: 5 })
|
||||
await page.mouse.click(600, 200)
|
||||
await page.waitForTimeout(100)
|
||||
})
|
||||
const xAxisClickAfterExitingSketch = () =>
|
||||
page.mouse.click(639, 278).then(() => page.waitForTimeout(100))
|
||||
test.step(`Click on X axis after exiting sketch, which shifts it at the moment`, async () => {
|
||||
await page.mouse.click(639, 278)
|
||||
await page.waitForTimeout(100)
|
||||
})
|
||||
const emptySpaceHover = () =>
|
||||
test.step('Hover over empty space', async () => {
|
||||
await page.mouse.move(700, 143, { steps: 5 })
|
||||
@ -80,23 +87,23 @@ test.describe('Testing selections', () => {
|
||||
await expect(page.locator('.cm-content'))
|
||||
.toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)`)
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20)
|
||||
await expect(page.locator('.cm-content'))
|
||||
.toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)
|
||||
|> line([0, ${commonPoints.num1 + 0.01}], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)
|
||||
|> yLine(${commonPoints.num1 + 0.01}, %)`)
|
||||
await page.waitForTimeout(100)
|
||||
await page.mouse.click(startXPx, 500 - PUR * 20)
|
||||
await expect(page.locator('.cm-content'))
|
||||
.toHaveText(`sketch001 = startSketchOn('XZ')
|
||||
|> startProfileAt(${commonPoints.startAt}, %)
|
||||
|> line([${commonPoints.num1}, 0], %)
|
||||
|> line([0, ${commonPoints.num1 + 0.01}], %)
|
||||
|> lineTo([0, ${commonPoints.num3}], %)`)
|
||||
|> xLine(${commonPoints.num1}, %)
|
||||
|> yLine(${commonPoints.num1 + 0.01}, %)
|
||||
|> xLine(${commonPoints.num2 * -1}, %)`)
|
||||
|
||||
// deselect line tool
|
||||
await page.getByRole('button', { name: 'line Line', exact: true }).click()
|
||||
@ -121,53 +128,58 @@ test.describe('Testing selections', () => {
|
||||
// now check clicking works including axis
|
||||
|
||||
// click a segment hold shift and click an axis, see that a relevant constraint is enabled
|
||||
await topHorzSegmentClick()
|
||||
await page.keyboard.down('Shift')
|
||||
const constrainButton = page.getByRole('button', {
|
||||
name: 'Length: open menu',
|
||||
})
|
||||
const absYButton = page.getByRole('button', { name: 'Absolute Y' })
|
||||
await constrainButton.click()
|
||||
await expect(absYButton).toBeDisabled()
|
||||
await page.waitForTimeout(100)
|
||||
await xAxisClick()
|
||||
await page.keyboard.up('Shift')
|
||||
await constrainButton.click()
|
||||
await absYButton.and(page.locator(':not([disabled])')).waitFor()
|
||||
await expect(absYButton).not.toBeDisabled()
|
||||
const absXButton = page.getByRole('button', { name: 'Absolute X' })
|
||||
|
||||
await test.step(`Select a segment and an axis, see that a relevant constraint is enabled`, async () => {
|
||||
await topHorzSegmentClick()
|
||||
await page.keyboard.down('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absXButton).toBeDisabled()
|
||||
await page.waitForTimeout(100)
|
||||
await yAxisClick()
|
||||
await page.keyboard.up('Shift')
|
||||
await constrainButton.click()
|
||||
await absXButton.and(page.locator(':not([disabled])')).waitFor()
|
||||
await expect(absXButton).not.toBeDisabled()
|
||||
})
|
||||
|
||||
// clear selection by clicking on nothing
|
||||
await emptySpaceClick()
|
||||
|
||||
await page.waitForTimeout(100)
|
||||
// same selection but click the axis first
|
||||
await xAxisClick()
|
||||
await constrainButton.click()
|
||||
await expect(absYButton).toBeDisabled()
|
||||
await page.keyboard.down('Shift')
|
||||
await page.waitForTimeout(100)
|
||||
await topHorzSegmentClick()
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
await page.keyboard.up('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absYButton).not.toBeDisabled()
|
||||
await test.step(`Same selection but click the axis first`, async () => {
|
||||
await yAxisClick()
|
||||
await constrainButton.click()
|
||||
await expect(absXButton).toBeDisabled()
|
||||
await page.keyboard.down('Shift')
|
||||
await page.waitForTimeout(100)
|
||||
await topHorzSegmentClick()
|
||||
await page.waitForTimeout(100)
|
||||
|
||||
await page.keyboard.up('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absXButton).not.toBeDisabled()
|
||||
})
|
||||
|
||||
// clear selection by clicking on nothing
|
||||
await emptySpaceClick()
|
||||
|
||||
// check the same selection again by putting cursor in code first then selecting axis
|
||||
await page
|
||||
.getByText(` |> lineTo([0, ${commonPoints.num3}], %)`)
|
||||
.click()
|
||||
await page.keyboard.down('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absYButton).toBeDisabled()
|
||||
await page.waitForTimeout(100)
|
||||
await xAxisClick()
|
||||
await page.keyboard.up('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absYButton).not.toBeDisabled()
|
||||
await test.step(`Same selection but code selection then axis`, async () => {
|
||||
await page
|
||||
.getByText(` |> xLine(${commonPoints.num2 * -1}, %)`)
|
||||
.click()
|
||||
await page.keyboard.down('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absXButton).toBeDisabled()
|
||||
await page.waitForTimeout(100)
|
||||
await yAxisClick()
|
||||
await page.keyboard.up('Shift')
|
||||
await constrainButton.click()
|
||||
await expect(absXButton).not.toBeDisabled()
|
||||
})
|
||||
|
||||
// clear selection by clicking on nothing
|
||||
await emptySpaceClick()
|
||||
@ -182,9 +194,7 @@ test.describe('Testing selections', () => {
|
||||
process.platform === 'linux' ? 'Control' : 'Meta'
|
||||
)
|
||||
await page.waitForTimeout(100)
|
||||
await page
|
||||
.getByText(` |> lineTo([0, ${commonPoints.num3}], %)`)
|
||||
.click()
|
||||
await page.getByText(` |> xLine(${commonPoints.num2 * -1}, %)`).click()
|
||||
|
||||
await expect(page.locator('.cm-cursor')).toHaveCount(2)
|
||||
await page.waitForTimeout(500)
|
||||
@ -928,6 +938,7 @@ sketch002 = startSketchOn(extrude001, $seg01)
|
||||
// test fillet button with the body in the scene
|
||||
const codeToAdd = `${await u.codeLocator.allInnerTexts()}
|
||||
extrude001 = extrude(10, sketch001)`
|
||||
await u.codeLocator.clear()
|
||||
await u.codeLocator.fill(codeToAdd)
|
||||
await selectSegment()
|
||||
await expect(page.getByRole('button', { name: 'Fillet' })).toBeEnabled()
|
||||
|
@ -258,7 +258,7 @@ test.describe('Testing settings', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test(
|
||||
test.fixme(
|
||||
`Project settings override user settings on desktop`,
|
||||
{ tag: ['@electron', '@skipWin'] },
|
||||
async ({ browser: _ }, testInfo) => {
|
||||
@ -318,7 +318,6 @@ test.describe('Testing settings', () => {
|
||||
timeout: 5_000,
|
||||
})
|
||||
.toContain(`themeColor = "${userThemeColor}"`)
|
||||
// Only close the button after we've confirmed
|
||||
})
|
||||
|
||||
await test.step('Set project theme color', async () => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "zoo-modeling-app",
|
||||
"version": "0.26.3",
|
||||
"version": "0.26.6",
|
||||
"private": true,
|
||||
"productName": "Zoo Modeling App",
|
||||
"author": {
|
||||
@ -40,7 +40,7 @@
|
||||
"codemirror": "^6.0.1",
|
||||
"decamelize": "^6.0.0",
|
||||
"electron-squirrel-startup": "^1.0.1",
|
||||
"electron-updater": "^6.3.9",
|
||||
"electron-updater": "6.3.0",
|
||||
"fuse.js": "^7.0.0",
|
||||
"html2canvas-pro": "^1.5.8",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
|
@ -141,6 +141,7 @@ export function Toolbar({
|
||||
>
|
||||
{/* A menu item will either be a vertical line break, a button with a dropdown, or a single button */}
|
||||
{currentModeItems.map((maybeIconConfig, i) => {
|
||||
// Vertical Line Break
|
||||
if (maybeIconConfig === 'break') {
|
||||
return (
|
||||
<div
|
||||
@ -149,6 +150,7 @@ export function Toolbar({
|
||||
/>
|
||||
)
|
||||
} else if (Array.isArray(maybeIconConfig)) {
|
||||
// A button with a dropdown
|
||||
return (
|
||||
<ActionButtonDropdown
|
||||
Element="button"
|
||||
@ -215,6 +217,7 @@ export function Toolbar({
|
||||
}
|
||||
const itemConfig = maybeIconConfig
|
||||
|
||||
// A single button
|
||||
return (
|
||||
<div className="relative" key={itemConfig.id}>
|
||||
<ActionButton
|
||||
|
@ -202,12 +202,20 @@ const Overlay = ({
|
||||
let xAlignment = overlay.angle < 0 ? '0%' : '-100%'
|
||||
let yAlignment = overlay.angle < -90 || overlay.angle >= 90 ? '0%' : '-100%'
|
||||
|
||||
// It's possible for the pathToNode to request a newer AST node
|
||||
// than what's available in the AST at the moment of query.
|
||||
// It eventually settles on being updated.
|
||||
const _node1 = getNodeFromPath<Node<CallExpression>>(
|
||||
kclManager.ast,
|
||||
overlay.pathToNode,
|
||||
'CallExpression'
|
||||
)
|
||||
if (err(_node1)) return
|
||||
|
||||
// For that reason, to prevent console noise, we do not use err here.
|
||||
if (_node1 instanceof Error) {
|
||||
console.warn('ast older than pathToNode, not fatal, eventually settles', '')
|
||||
return
|
||||
}
|
||||
const callExpression = _node1.node
|
||||
|
||||
const constraints = getConstraintInfo(
|
||||
@ -637,10 +645,16 @@ const ConstraintSymbol = ({
|
||||
kclManager.ast,
|
||||
kclManager.programMemory
|
||||
)
|
||||
|
||||
if (!transform) return
|
||||
const { modifiedAst } = transform
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
kclManager.updateAst(modifiedAst, true)
|
||||
|
||||
await kclManager.updateAst(modifiedAst, true)
|
||||
|
||||
// Code editor will be updated in the modelingMachine.
|
||||
const newCode = recast(modifiedAst)
|
||||
if (err(newCode)) return
|
||||
await codeManager.updateCodeEditor(newCode)
|
||||
} catch (e) {
|
||||
console.log('error', e)
|
||||
}
|
||||
|
@ -17,6 +17,7 @@ import {
|
||||
Vector3,
|
||||
} from 'three'
|
||||
import {
|
||||
ANGLE_SNAP_THRESHOLD_DEGREES,
|
||||
ARROWHEAD,
|
||||
AXIS_GROUP,
|
||||
DRAFT_POINT,
|
||||
@ -88,6 +89,7 @@ import { EngineCommandManager } from 'lang/std/engineConnection'
|
||||
import {
|
||||
getRectangleCallExpressions,
|
||||
updateRectangleSketch,
|
||||
updateCenterRectangleSketch,
|
||||
} from 'lib/rectangleTool'
|
||||
import { getThemeColorForThreeJs, Themes } from 'lib/theme'
|
||||
import { err, reportRejection, trap } from 'lib/trap'
|
||||
@ -95,6 +97,7 @@ import { CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer'
|
||||
import { Point3d } from 'wasm-lib/kcl/bindings/Point3d'
|
||||
import { SegmentInputs } from 'lang/std/stdTypes'
|
||||
import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
import { radToDeg } from 'three/src/math/MathUtils'
|
||||
|
||||
type DraftSegment = 'line' | 'tangentialArcTo'
|
||||
|
||||
@ -451,6 +454,7 @@ export class SceneEntities {
|
||||
const { modifiedAst } = addStartProfileAtRes
|
||||
|
||||
await kclManager.updateAst(modifiedAst, false)
|
||||
|
||||
this.removeIntersectionPlane()
|
||||
this.scene.remove(draftPointGroup)
|
||||
|
||||
@ -683,7 +687,7 @@ export class SceneEntities {
|
||||
})
|
||||
return nextAst
|
||||
}
|
||||
setUpDraftSegment = async (
|
||||
setupDraftSegment = async (
|
||||
sketchPathToNode: PathToNode,
|
||||
forward: [number, number, number],
|
||||
up: [number, number, number],
|
||||
@ -798,11 +802,24 @@ export class SceneEntities {
|
||||
(sceneObject) => sceneObject.object.name === X_AXIS
|
||||
)
|
||||
|
||||
const lastSegment = sketch.paths.slice(-1)[0]
|
||||
const lastSegment = sketch.paths.slice(-1)[0] || sketch.start
|
||||
const snappedPoint = {
|
||||
x: intersectsYAxis ? 0 : intersection2d.x,
|
||||
y: intersectsXAxis ? 0 : intersection2d.y,
|
||||
}
|
||||
// Get the angle between the previous segment (or sketch start)'s end and this one's
|
||||
const angle = Math.atan2(
|
||||
snappedPoint.y - lastSegment.to[1],
|
||||
snappedPoint.x - lastSegment.to[0]
|
||||
)
|
||||
|
||||
const isHorizontal =
|
||||
radToDeg(Math.abs(angle)) < ANGLE_SNAP_THRESHOLD_DEGREES ||
|
||||
Math.abs(radToDeg(Math.abs(angle) - Math.PI)) <
|
||||
ANGLE_SNAP_THRESHOLD_DEGREES
|
||||
const isVertical =
|
||||
Math.abs(radToDeg(Math.abs(angle) - Math.PI / 2)) <
|
||||
ANGLE_SNAP_THRESHOLD_DEGREES
|
||||
|
||||
let resolvedFunctionName: ToolTip = 'line'
|
||||
|
||||
@ -810,6 +827,12 @@ export class SceneEntities {
|
||||
// case-based logic for different segment types
|
||||
if (lastSegment.type === 'TangentialArcTo') {
|
||||
resolvedFunctionName = 'tangentialArcTo'
|
||||
} else if (isHorizontal) {
|
||||
// If the angle between is 0 or 180 degrees (+/- the snapping angle), make the line an xLine
|
||||
resolvedFunctionName = 'xLine'
|
||||
} else if (isVertical) {
|
||||
// If the angle between is 90 or 270 degrees (+/- the snapping angle), make the line a yLine
|
||||
resolvedFunctionName = 'yLine'
|
||||
} else if (snappedPoint.x === 0 || snappedPoint.y === 0) {
|
||||
// We consider a point placed on axes or origin to be absolute
|
||||
resolvedFunctionName = 'lineTo'
|
||||
@ -835,10 +858,11 @@ export class SceneEntities {
|
||||
}
|
||||
|
||||
await kclManager.executeAstMock(modifiedAst)
|
||||
|
||||
if (intersectsProfileStart) {
|
||||
sceneInfra.modelingSend({ type: 'CancelSketch' })
|
||||
} else {
|
||||
await this.setUpDraftSegment(
|
||||
await this.setupDraftSegment(
|
||||
sketchPathToNode,
|
||||
forward,
|
||||
up,
|
||||
@ -846,6 +870,8 @@ export class SceneEntities {
|
||||
segmentName
|
||||
)
|
||||
}
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(modifiedAst)
|
||||
},
|
||||
onMove: (args) => {
|
||||
this.onDragSegment({
|
||||
@ -970,8 +996,179 @@ export class SceneEntities {
|
||||
if (trap(_node)) return
|
||||
const sketchInit = _node.node?.declarations?.[0]?.init
|
||||
|
||||
if (sketchInit.type !== 'PipeExpression') {
|
||||
return
|
||||
}
|
||||
|
||||
updateRectangleSketch(sketchInit, x, y, tags[0])
|
||||
|
||||
const newCode = recast(_ast)
|
||||
let _recastAst = parse(newCode)
|
||||
if (trap(_recastAst)) return
|
||||
_ast = _recastAst
|
||||
|
||||
// Update the primary AST and unequip the rectangle tool
|
||||
await kclManager.executeAstMock(_ast)
|
||||
sceneInfra.modelingSend({ type: 'Finish rectangle' })
|
||||
|
||||
// lee: I had this at the bottom of the function, but it's
|
||||
// possible sketchFromKclValue "fails" when sketching on a face,
|
||||
// and this couldn't wouldn't run.
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(_ast)
|
||||
|
||||
const { execState } = await executeAst({
|
||||
ast: _ast,
|
||||
useFakeExecutor: true,
|
||||
engineCommandManager: this.engineCommandManager,
|
||||
programMemoryOverride,
|
||||
idGenerator: kclManager.execState.idGenerator,
|
||||
})
|
||||
const programMemory = execState.memory
|
||||
|
||||
// Prepare to update the THREEjs scene
|
||||
this.sceneProgramMemory = programMemory
|
||||
const sketch = sketchFromKclValue(
|
||||
programMemory.get(variableDeclarationName),
|
||||
variableDeclarationName
|
||||
)
|
||||
if (err(sketch)) return
|
||||
const sgPaths = sketch.paths
|
||||
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
|
||||
|
||||
// Update the starting segment of the THREEjs scene
|
||||
this.updateSegment(sketch.start, 0, 0, _ast, orthoFactor, sketch)
|
||||
// Update the rest of the segments of the THREEjs scene
|
||||
sgPaths.forEach((seg, index) =>
|
||||
this.updateSegment(seg, index, 0, _ast, orthoFactor, sketch)
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
setupDraftCenterRectangle = async (
|
||||
sketchPathToNode: PathToNode,
|
||||
forward: [number, number, number],
|
||||
up: [number, number, number],
|
||||
sketchOrigin: [number, number, number],
|
||||
rectangleOrigin: [x: number, y: number]
|
||||
) => {
|
||||
let _ast = structuredClone(kclManager.ast)
|
||||
const _node1 = getNodeFromPath<VariableDeclaration>(
|
||||
_ast,
|
||||
sketchPathToNode || [],
|
||||
'VariableDeclaration'
|
||||
)
|
||||
if (trap(_node1)) return Promise.reject(_node1)
|
||||
|
||||
// startSketchOn already exists
|
||||
const variableDeclarationName =
|
||||
_node1.node?.declarations?.[0]?.id?.name || ''
|
||||
const startSketchOn = _node1.node?.declarations
|
||||
const startSketchOnInit = startSketchOn?.[0]?.init
|
||||
|
||||
const tags: [string, string, string] = [
|
||||
findUniqueName(_ast, 'rectangleSegmentA'),
|
||||
findUniqueName(_ast, 'rectangleSegmentB'),
|
||||
findUniqueName(_ast, 'rectangleSegmentC'),
|
||||
]
|
||||
|
||||
startSketchOn[0].init = createPipeExpression([
|
||||
startSketchOnInit,
|
||||
...getRectangleCallExpressions(rectangleOrigin, tags),
|
||||
])
|
||||
|
||||
let _recastAst = parse(recast(_ast))
|
||||
if (trap(_recastAst)) return Promise.reject(_recastAst)
|
||||
_ast = _recastAst
|
||||
|
||||
const { programMemoryOverride, truncatedAst } = await this.setupSketch({
|
||||
sketchPathToNode,
|
||||
forward,
|
||||
up,
|
||||
position: sketchOrigin,
|
||||
maybeModdedAst: _ast,
|
||||
draftExpressionsIndices: { start: 0, end: 3 },
|
||||
})
|
||||
|
||||
sceneInfra.setCallbacks({
|
||||
onMove: async (args) => {
|
||||
// Update the width and height of the draft rectangle
|
||||
const pathToNodeTwo = structuredClone(sketchPathToNode)
|
||||
pathToNodeTwo[1][0] = 0
|
||||
|
||||
const _node = getNodeFromPath<VariableDeclaration>(
|
||||
truncatedAst,
|
||||
pathToNodeTwo || [],
|
||||
'VariableDeclaration'
|
||||
)
|
||||
if (trap(_node)) return Promise.reject(_node)
|
||||
const sketchInit = _node.node?.declarations?.[0]?.init
|
||||
|
||||
const x = (args.intersectionPoint.twoD.x || 0) - rectangleOrigin[0]
|
||||
const y = (args.intersectionPoint.twoD.y || 0) - rectangleOrigin[1]
|
||||
|
||||
if (sketchInit.type === 'PipeExpression') {
|
||||
updateRectangleSketch(sketchInit, x, y, tags[0])
|
||||
updateCenterRectangleSketch(
|
||||
sketchInit,
|
||||
x,
|
||||
y,
|
||||
tags[0],
|
||||
rectangleOrigin[0],
|
||||
rectangleOrigin[1]
|
||||
)
|
||||
}
|
||||
|
||||
const { execState } = await executeAst({
|
||||
ast: truncatedAst,
|
||||
useFakeExecutor: true,
|
||||
engineCommandManager: this.engineCommandManager,
|
||||
programMemoryOverride,
|
||||
idGenerator: kclManager.execState.idGenerator,
|
||||
})
|
||||
const programMemory = execState.memory
|
||||
this.sceneProgramMemory = programMemory
|
||||
const sketch = sketchFromKclValue(
|
||||
programMemory.get(variableDeclarationName),
|
||||
variableDeclarationName
|
||||
)
|
||||
if (err(sketch)) return Promise.reject(sketch)
|
||||
const sgPaths = sketch.paths
|
||||
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
|
||||
|
||||
this.updateSegment(sketch.start, 0, 0, _ast, orthoFactor, sketch)
|
||||
sgPaths.forEach((seg, index) =>
|
||||
this.updateSegment(seg, index, 0, _ast, orthoFactor, sketch)
|
||||
)
|
||||
},
|
||||
onClick: async (args) => {
|
||||
// If there is a valid camera interaction that matches, do that instead
|
||||
const interaction = sceneInfra.camControls.getInteractionType(
|
||||
args.mouseEvent
|
||||
)
|
||||
if (interaction !== 'none') return
|
||||
// Commit the rectangle to the full AST/code and return to sketch.idle
|
||||
const cornerPoint = args.intersectionPoint?.twoD
|
||||
if (!cornerPoint || args.mouseEvent.button !== 0) return
|
||||
|
||||
const x = roundOff((cornerPoint.x || 0) - rectangleOrigin[0])
|
||||
const y = roundOff((cornerPoint.y || 0) - rectangleOrigin[1])
|
||||
|
||||
const _node = getNodeFromPath<VariableDeclaration>(
|
||||
_ast,
|
||||
sketchPathToNode || [],
|
||||
'VariableDeclaration'
|
||||
)
|
||||
if (trap(_node)) return
|
||||
const sketchInit = _node.node?.declarations?.[0]?.init
|
||||
|
||||
if (sketchInit.type === 'PipeExpression') {
|
||||
updateCenterRectangleSketch(
|
||||
sketchInit,
|
||||
x,
|
||||
y,
|
||||
tags[0],
|
||||
rectangleOrigin[0],
|
||||
rectangleOrigin[1]
|
||||
)
|
||||
|
||||
let _recastAst = parse(recast(_ast))
|
||||
if (trap(_recastAst)) return
|
||||
@ -979,7 +1176,12 @@ export class SceneEntities {
|
||||
|
||||
// Update the primary AST and unequip the rectangle tool
|
||||
await kclManager.executeAstMock(_ast)
|
||||
sceneInfra.modelingSend({ type: 'Finish rectangle' })
|
||||
sceneInfra.modelingSend({ type: 'Finish center rectangle' })
|
||||
|
||||
// lee: I had this at the bottom of the function, but it's
|
||||
// possible sketchFromKclValue "fails" when sketching on a face,
|
||||
// and this couldn't wouldn't run.
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(_ast)
|
||||
|
||||
const { execState } = await executeAst({
|
||||
ast: _ast,
|
||||
@ -1166,13 +1368,17 @@ export class SceneEntities {
|
||||
if (err(moddedResult)) return
|
||||
modded = moddedResult.modifiedAst
|
||||
|
||||
let _recastAst = parse(recast(modded))
|
||||
const newCode = recast(modded)
|
||||
if (err(newCode)) return
|
||||
let _recastAst = parse(newCode)
|
||||
if (trap(_recastAst)) return Promise.reject(_recastAst)
|
||||
_ast = _recastAst
|
||||
|
||||
// Update the primary AST and unequip the rectangle tool
|
||||
await kclManager.executeAstMock(_ast)
|
||||
sceneInfra.modelingSend({ type: 'Finish circle' })
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(_ast)
|
||||
}
|
||||
},
|
||||
})
|
||||
@ -1208,6 +1414,7 @@ export class SceneEntities {
|
||||
forward,
|
||||
position,
|
||||
})
|
||||
await codeManager.writeToFile()
|
||||
}
|
||||
},
|
||||
onDrag: async ({
|
||||
|
@ -50,6 +50,8 @@ export const RAYCASTABLE_PLANE = 'raycastable-plane'
|
||||
|
||||
export const X_AXIS = 'xAxis'
|
||||
export const Y_AXIS = 'yAxis'
|
||||
/** If a segment angle is less than this many degrees off a meanginful angle it'll snap to it */
|
||||
export const ANGLE_SNAP_THRESHOLD_DEGREES = 3
|
||||
/** the THREEjs representation of the group surrounding a "snapped" point that is not yet placed */
|
||||
export const DRAFT_POINT_GROUP = 'draft-point-group'
|
||||
/** the THREEjs representation of a "snapped" point that is not yet placed */
|
||||
|
@ -145,7 +145,7 @@ export function useCalc({
|
||||
const _programMem: ProgramMemory = ProgramMemory.empty()
|
||||
for (const { key, value } of availableVarInfo.variables) {
|
||||
const error = _programMem.set(key, {
|
||||
type: 'UserVal',
|
||||
type: 'String',
|
||||
value,
|
||||
__meta: [],
|
||||
})
|
||||
|
@ -22,6 +22,7 @@ import usePlatform from 'hooks/usePlatform'
|
||||
import { FileEntry } from 'lib/project'
|
||||
import { useFileSystemWatcher } from 'hooks/useFileSystemWatcher'
|
||||
import { normalizeLineEndings } from 'lib/codeEditor'
|
||||
import { reportRejection } from 'lib/trap'
|
||||
|
||||
function getIndentationCSS(level: number) {
|
||||
return `calc(1rem * ${level + 1})`
|
||||
@ -196,8 +197,7 @@ const FileTreeItem = ({
|
||||
return
|
||||
}
|
||||
|
||||
// Don't try to read a file that was removed.
|
||||
if (isCurrentFile && eventType !== 'unlink') {
|
||||
if (isCurrentFile && eventType === 'change') {
|
||||
let code = await window.electron.readFile(path, { encoding: 'utf-8' })
|
||||
code = normalizeLineEndings(code)
|
||||
codeManager.updateCodeStateEditor(code)
|
||||
@ -242,7 +242,7 @@ const FileTreeItem = ({
|
||||
// Show the renaming form
|
||||
addCurrentItemToRenaming()
|
||||
} else if (e.code === 'Space') {
|
||||
void handleClick()
|
||||
void handleClick().catch(reportRejection)
|
||||
}
|
||||
}
|
||||
|
||||
@ -293,7 +293,7 @@ const FileTreeItem = ({
|
||||
style={{ paddingInlineStart: getIndentationCSS(level) }}
|
||||
onClick={(e) => {
|
||||
e.currentTarget.focus()
|
||||
void handleClick()
|
||||
void handleClick().catch(reportRejection)
|
||||
}}
|
||||
onKeyUp={handleKeyUp}
|
||||
>
|
||||
|
@ -63,6 +63,7 @@ import {
|
||||
import {
|
||||
moveValueIntoNewVariablePath,
|
||||
sketchOnExtrudedFace,
|
||||
sketchOnOffsetPlane,
|
||||
startSketchOnDefault,
|
||||
} from 'lang/modifyAst'
|
||||
import { Program, parse, recast } from 'lang/wasm'
|
||||
@ -304,6 +305,7 @@ export const ModelingMachineProvider = ({
|
||||
const dispatchSelection = (selection?: EditorSelection) => {
|
||||
if (!selection) return // TODO less of hack for the below please
|
||||
if (!editorManager.editorView) return
|
||||
|
||||
setTimeout(() => {
|
||||
if (!editorManager.editorView) return
|
||||
editorManager.editorView.dispatch({
|
||||
@ -482,7 +484,7 @@ export const ModelingMachineProvider = ({
|
||||
engineCommandManager.exportInfo = {
|
||||
intent: ExportIntent.Save,
|
||||
// This never gets used its only for make.
|
||||
name: '',
|
||||
name: file?.name?.replace('.kcl', `.${event.data.type}`) || '',
|
||||
}
|
||||
|
||||
const format = {
|
||||
@ -635,13 +637,16 @@ export const ModelingMachineProvider = ({
|
||||
),
|
||||
'animate-to-face': fromPromise(async ({ input }) => {
|
||||
if (!input) return undefined
|
||||
if (input.type === 'extrudeFace') {
|
||||
const sketched = sketchOnExtrudedFace(
|
||||
kclManager.ast,
|
||||
input.sketchPathToNode,
|
||||
input.extrudePathToNode,
|
||||
input.faceInfo
|
||||
)
|
||||
if (input.type === 'extrudeFace' || input.type === 'offsetPlane') {
|
||||
const sketched =
|
||||
input.type === 'extrudeFace'
|
||||
? sketchOnExtrudedFace(
|
||||
kclManager.ast,
|
||||
input.sketchPathToNode,
|
||||
input.extrudePathToNode,
|
||||
input.faceInfo
|
||||
)
|
||||
: sketchOnOffsetPlane(kclManager.ast, input.pathToNode)
|
||||
if (err(sketched)) {
|
||||
const sketchedError = new Error(
|
||||
'Incompatible face, please try another'
|
||||
@ -653,10 +658,9 @@ export const ModelingMachineProvider = ({
|
||||
|
||||
await kclManager.executeAstMock(modifiedAst)
|
||||
|
||||
await letEngineAnimateAndSyncCamAfter(
|
||||
engineCommandManager,
|
||||
input.faceId
|
||||
)
|
||||
const id =
|
||||
input.type === 'extrudeFace' ? input.faceId : input.planeId
|
||||
await letEngineAnimateAndSyncCamAfter(engineCommandManager, id)
|
||||
sceneInfra.camControls.syncDirection = 'clientToEngine'
|
||||
return {
|
||||
sketchPathToNode: pathToNewSketchNode,
|
||||
@ -732,6 +736,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -768,6 +777,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -813,6 +827,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -846,6 +865,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -881,6 +905,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -917,6 +946,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -953,6 +987,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -999,6 +1038,11 @@ export const ModelingMachineProvider = ({
|
||||
sketchDetails.origin
|
||||
)
|
||||
if (err(updatedAst)) return Promise.reject(updatedAst)
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(
|
||||
updatedAst.newAst
|
||||
)
|
||||
|
||||
const selection = updateSelections(
|
||||
{ 0: pathToReplacedNode },
|
||||
selectionRanges,
|
||||
|
@ -43,6 +43,7 @@ import {
|
||||
completionKeymap,
|
||||
} from '@codemirror/autocomplete'
|
||||
import CodeEditor from './CodeEditor'
|
||||
import { codeManagerHistoryCompartment } from 'lang/codeManager'
|
||||
|
||||
export const editorShortcutMeta = {
|
||||
formatCode: {
|
||||
@ -89,7 +90,7 @@ export const KclEditorPane = () => {
|
||||
cursorBlinkRate: cursorBlinking.current ? 1200 : 0,
|
||||
}),
|
||||
lineHighlightField,
|
||||
history(),
|
||||
codeManagerHistoryCompartment.of(history()),
|
||||
closeBrackets(),
|
||||
codeFolding(),
|
||||
keymap.of([
|
||||
@ -121,7 +122,6 @@ export const KclEditorPane = () => {
|
||||
lineNumbers(),
|
||||
highlightActiveLineGutter(),
|
||||
highlightSpecialChars(),
|
||||
history(),
|
||||
foldGutter(),
|
||||
EditorState.allowMultipleSelections.of(true),
|
||||
indentOnInput(),
|
||||
|
@ -89,9 +89,9 @@ export const processMemory = (programMemory: ProgramMemory) => {
|
||||
const processedMemory: any = {}
|
||||
for (const [key, val] of programMemory?.visibleEntries()) {
|
||||
if (
|
||||
(val.type === 'UserVal' && val.value.type === 'Sketch') ||
|
||||
val.type === 'Sketch' ||
|
||||
// @ts-ignore
|
||||
(val.type !== 'Function' && val.type !== 'UserVal')
|
||||
val.type !== 'Function'
|
||||
) {
|
||||
const sg = sketchFromKclValue(val, key)
|
||||
if (val.type === 'Solid') {
|
||||
@ -110,8 +110,6 @@ export const processMemory = (programMemory: ProgramMemory) => {
|
||||
processedMemory[key] = `__function(${(val as any)?.expression?.params
|
||||
?.map?.(({ identifier }: any) => identifier?.name || '')
|
||||
.join(', ')})__`
|
||||
} else {
|
||||
processedMemory[key] = val.value
|
||||
}
|
||||
}
|
||||
return processedMemory
|
||||
|
81
src/editor/manager.test.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import { editorManager } from 'lib/singletons'
|
||||
import { Diagnostic } from '@codemirror/lint'
|
||||
|
||||
describe('EditorManager Class', () => {
|
||||
describe('makeUniqueDiagnostics', () => {
|
||||
it('should filter out duplicated diagnostics', () => {
|
||||
const duplicatedDiagnostics: Diagnostic[] = [
|
||||
{
|
||||
from: 2,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
{
|
||||
from: 2,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
{
|
||||
from: 2,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
]
|
||||
|
||||
const expected: Diagnostic[] = [
|
||||
{
|
||||
from: 2,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
]
|
||||
|
||||
const actual = editorManager.makeUniqueDiagnostics(duplicatedDiagnostics)
|
||||
expect(actual).toStrictEqual(expected)
|
||||
})
|
||||
it('should filter out duplicated diagnostic and keep some original ones', () => {
|
||||
const duplicatedDiagnostics: Diagnostic[] = [
|
||||
{
|
||||
from: 0,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
{
|
||||
from: 0,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
{
|
||||
from: 88,
|
||||
to: 99,
|
||||
severity: 'hint',
|
||||
message: 'my super cool message',
|
||||
},
|
||||
]
|
||||
|
||||
const expected: Diagnostic[] = [
|
||||
{
|
||||
from: 0,
|
||||
to: 10,
|
||||
severity: 'hint',
|
||||
message: 'my cool message',
|
||||
},
|
||||
{
|
||||
from: 88,
|
||||
to: 99,
|
||||
severity: 'hint',
|
||||
message: 'my super cool message',
|
||||
},
|
||||
]
|
||||
|
||||
const actual = editorManager.makeUniqueDiagnostics(duplicatedDiagnostics)
|
||||
expect(actual).toStrictEqual(expected)
|
||||
})
|
||||
})
|
||||
})
|
@ -24,10 +24,6 @@ export const modelingMachineEvent = modelingMachineAnnotation.of(true)
|
||||
const setDiagnosticsAnnotation = Annotation.define<boolean>()
|
||||
export const setDiagnosticsEvent = setDiagnosticsAnnotation.of(true)
|
||||
|
||||
function diagnosticIsEqual(d1: Diagnostic, d2: Diagnostic): boolean {
|
||||
return d1.from === d2.from && d1.to === d2.to && d1.message === d2.message
|
||||
}
|
||||
|
||||
export default class EditorManager {
|
||||
private _editorView: EditorView | null = null
|
||||
private _copilotEnabled: boolean = true
|
||||
@ -72,9 +68,10 @@ export default class EditorManager {
|
||||
// we cannot use <>.constructor.name since it will get destroyed
|
||||
// when packaging the application.
|
||||
const isTreeHighlightPlugin =
|
||||
e.value.hasOwnProperty('tree') &&
|
||||
e.value.hasOwnProperty('decoratedTo') &&
|
||||
e.value.hasOwnProperty('decorations')
|
||||
e?.value &&
|
||||
e.value?.hasOwnProperty('tree') &&
|
||||
e.value?.hasOwnProperty('decoratedTo') &&
|
||||
e.value?.hasOwnProperty('decorations')
|
||||
|
||||
if (isTreeHighlightPlugin) {
|
||||
let originalUpdate = e.value.update
|
||||
@ -161,20 +158,29 @@ export default class EditorManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an array of Diagnostics remove any duplicates by hashing a key
|
||||
* in the format of from + ' ' + to + ' ' + message.
|
||||
*/
|
||||
makeUniqueDiagnostics(duplicatedDiagnostics: Diagnostic[]): Diagnostic[] {
|
||||
const uniqueDiagnostics: Diagnostic[] = []
|
||||
const seenDiagnostic: { [key: string]: boolean } = {}
|
||||
|
||||
duplicatedDiagnostics.forEach((diagnostic: Diagnostic) => {
|
||||
const hash = `${diagnostic.from} ${diagnostic.to} ${diagnostic.message}`
|
||||
if (!seenDiagnostic[hash]) {
|
||||
uniqueDiagnostics.push(diagnostic)
|
||||
seenDiagnostic[hash] = true
|
||||
}
|
||||
})
|
||||
|
||||
return uniqueDiagnostics
|
||||
}
|
||||
|
||||
setDiagnostics(diagnostics: Diagnostic[]): void {
|
||||
if (!this._editorView) return
|
||||
// Clear out any existing diagnostics that are the same.
|
||||
for (const diagnostic of diagnostics) {
|
||||
for (const otherDiagnostic of diagnostics) {
|
||||
if (diagnosticIsEqual(diagnostic, otherDiagnostic)) {
|
||||
diagnostics = diagnostics.filter(
|
||||
(d) => !diagnosticIsEqual(d, diagnostic)
|
||||
)
|
||||
diagnostics.push(diagnostic)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
diagnostics = this.makeUniqueDiagnostics(diagnostics)
|
||||
|
||||
this._editorView.dispatch({
|
||||
effects: [setDiagnosticsEffect.of(diagnostics)],
|
||||
|
@ -88,6 +88,10 @@ export function useEngineConnectionSubscriptions() {
|
||||
? [codeRef.range]
|
||||
: [codeRef.range, consumedCodeRef.range]
|
||||
)
|
||||
} else if (artifact?.type === 'plane') {
|
||||
const codeRef = artifact.codeRef
|
||||
if (err(codeRef)) return
|
||||
editorManager.setHighlightRange([codeRef.range])
|
||||
} else {
|
||||
editorManager.setHighlightRange([[0, 0]])
|
||||
}
|
||||
@ -186,8 +190,42 @@ export function useEngineConnectionSubscriptions() {
|
||||
})
|
||||
return
|
||||
}
|
||||
const artifact =
|
||||
engineCommandManager.artifactGraph.get(planeOrFaceId)
|
||||
|
||||
if (artifact?.type === 'plane') {
|
||||
const planeInfo = await getFaceDetails(planeOrFaceId)
|
||||
sceneInfra.modelingSend({
|
||||
type: 'Select default plane',
|
||||
data: {
|
||||
type: 'offsetPlane',
|
||||
zAxis: [
|
||||
planeInfo.z_axis.x,
|
||||
planeInfo.z_axis.y,
|
||||
planeInfo.z_axis.z,
|
||||
],
|
||||
yAxis: [
|
||||
planeInfo.y_axis.x,
|
||||
planeInfo.y_axis.y,
|
||||
planeInfo.y_axis.z,
|
||||
],
|
||||
position: [
|
||||
planeInfo.origin.x,
|
||||
planeInfo.origin.y,
|
||||
planeInfo.origin.z,
|
||||
].map((num) => num / sceneInfra._baseUnitMultiplier) as [
|
||||
number,
|
||||
number,
|
||||
number
|
||||
],
|
||||
planeId: planeOrFaceId,
|
||||
pathToNode: artifact.codeRef.pathToNode,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Artifact is likely an extrusion face
|
||||
const faceId = planeOrFaceId
|
||||
const artifact = engineCommandManager.artifactGraph.get(faceId)
|
||||
const extrusion = getSweepFromSuspectedSweepSurface(
|
||||
faceId,
|
||||
engineCommandManager.artifactGraph
|
||||
|
@ -2,13 +2,13 @@ import {
|
||||
SetVarNameModal,
|
||||
createSetVarNameModal,
|
||||
} from 'components/SetVarNameModal'
|
||||
import { editorManager, kclManager } from 'lib/singletons'
|
||||
import { reportRejection, trap } from 'lib/trap'
|
||||
import { editorManager, kclManager, codeManager } from 'lib/singletons'
|
||||
import { reportRejection, trap, err } from 'lib/trap'
|
||||
import { moveValueIntoNewVariable } from 'lang/modifyAst'
|
||||
import { isNodeSafeToReplace } from 'lang/queryAst'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useModelingContext } from './useModelingContext'
|
||||
import { PathToNode, SourceRange } from 'lang/wasm'
|
||||
import { PathToNode, SourceRange, recast } from 'lang/wasm'
|
||||
import { useKclContext } from 'lang/KclProvider'
|
||||
import { toSync } from 'lib/utils'
|
||||
|
||||
@ -57,6 +57,11 @@ export function useConvertToVariable(range?: SourceRange) {
|
||||
)
|
||||
|
||||
await kclManager.updateAst(_modifiedAst, true)
|
||||
|
||||
const newCode = recast(_modifiedAst)
|
||||
if (err(newCode)) return
|
||||
codeManager.updateCodeEditor(newCode)
|
||||
|
||||
return pathToReplacedNode
|
||||
} catch (e) {
|
||||
console.log('error', e)
|
||||
|
@ -125,7 +125,7 @@ export class KclManager {
|
||||
if (this.lints.length > 0) {
|
||||
diagnostics = diagnostics.concat(this.lints)
|
||||
}
|
||||
editorManager.setDiagnostics(diagnostics)
|
||||
editorManager?.setDiagnostics(diagnostics)
|
||||
}
|
||||
|
||||
addKclErrors(kclErrors: KCLError[]) {
|
||||
@ -357,9 +357,6 @@ export class KclManager {
|
||||
this.clearAst()
|
||||
return
|
||||
}
|
||||
codeManager.updateCodeEditor(newCode)
|
||||
// Write the file to disk.
|
||||
await codeManager.writeToFile()
|
||||
this._ast = { ...newAst }
|
||||
|
||||
const { logs, errors, execState } = await executeAst({
|
||||
@ -497,11 +494,6 @@ export class KclManager {
|
||||
}
|
||||
|
||||
if (execute) {
|
||||
// Call execute on the set ast.
|
||||
// Update the code state and editor.
|
||||
codeManager.updateCodeEditor(newCode)
|
||||
// Write the file to disk.
|
||||
await codeManager.writeToFile()
|
||||
await this.executeAst({
|
||||
ast: astWithUpdatedSource,
|
||||
zoomToFit: optionalParams?.zoomToFit,
|
||||
|
@ -18,8 +18,7 @@ const mySketch001 = startSketchOn('XY')
|
||||
// @ts-ignore
|
||||
const sketch001 = execState.memory.get('mySketch001')
|
||||
expect(sketch001).toEqual({
|
||||
type: 'UserVal',
|
||||
__meta: [{ sourceRange: [46, 71, 0] }],
|
||||
type: 'Sketch',
|
||||
value: {
|
||||
type: 'Sketch',
|
||||
on: expect.any(Object),
|
||||
|
@ -6,12 +6,17 @@ import { isDesktop } from 'lib/isDesktop'
|
||||
import toast from 'react-hot-toast'
|
||||
import { editorManager } from 'lib/singletons'
|
||||
import { Annotation, Transaction } from '@codemirror/state'
|
||||
import { KeyBinding } from '@codemirror/view'
|
||||
import { EditorView, KeyBinding } from '@codemirror/view'
|
||||
import { recast, Program } from 'lang/wasm'
|
||||
import { err } from 'lib/trap'
|
||||
import { Compartment } from '@codemirror/state'
|
||||
import { history } from '@codemirror/commands'
|
||||
|
||||
const PERSIST_CODE_KEY = 'persistCode'
|
||||
|
||||
const codeManagerUpdateAnnotation = Annotation.define<boolean>()
|
||||
export const codeManagerUpdateEvent = codeManagerUpdateAnnotation.of(true)
|
||||
export const codeManagerHistoryCompartment = new Compartment()
|
||||
|
||||
export default class CodeManager {
|
||||
private _code: string = bracket
|
||||
@ -88,9 +93,12 @@ export default class CodeManager {
|
||||
/**
|
||||
* Update the code in the editor.
|
||||
*/
|
||||
updateCodeEditor(code: string): void {
|
||||
updateCodeEditor(code: string, clearHistory?: boolean): void {
|
||||
this.code = code
|
||||
if (editorManager.editorView) {
|
||||
if (clearHistory) {
|
||||
clearCodeMirrorHistory(editorManager.editorView)
|
||||
}
|
||||
editorManager.editorView.dispatch({
|
||||
changes: {
|
||||
from: 0,
|
||||
@ -99,7 +107,7 @@ export default class CodeManager {
|
||||
},
|
||||
annotations: [
|
||||
codeManagerUpdateEvent,
|
||||
Transaction.addToHistory.of(true),
|
||||
Transaction.addToHistory.of(!clearHistory),
|
||||
],
|
||||
})
|
||||
}
|
||||
@ -108,11 +116,11 @@ export default class CodeManager {
|
||||
/**
|
||||
* Update the code, state, and the code the code mirror editor sees.
|
||||
*/
|
||||
updateCodeStateEditor(code: string): void {
|
||||
updateCodeStateEditor(code: string, clearHistory?: boolean): void {
|
||||
if (this._code !== code) {
|
||||
this.code = code
|
||||
this.#updateState(code)
|
||||
this.updateCodeEditor(code)
|
||||
this.updateCodeEditor(code, clearHistory)
|
||||
}
|
||||
}
|
||||
|
||||
@ -147,6 +155,13 @@ export default class CodeManager {
|
||||
safeLSSetItem(PERSIST_CODE_KEY, this.code)
|
||||
}
|
||||
}
|
||||
|
||||
async updateEditorWithAstAndWriteToFile(ast: Program) {
|
||||
const newCode = recast(ast)
|
||||
if (err(newCode)) return
|
||||
this.updateCodeStateEditor(newCode)
|
||||
await this.writeToFile()
|
||||
}
|
||||
}
|
||||
|
||||
function safeLSGetItem(key: string) {
|
||||
@ -158,3 +173,17 @@ function safeLSSetItem(key: string, value: string) {
|
||||
if (typeof window === 'undefined') return
|
||||
localStorage?.setItem(key, value)
|
||||
}
|
||||
|
||||
function clearCodeMirrorHistory(view: EditorView) {
|
||||
// Clear history
|
||||
view.dispatch({
|
||||
effects: [codeManagerHistoryCompartment.reconfigure([])],
|
||||
annotations: [codeManagerUpdateEvent],
|
||||
})
|
||||
|
||||
// Add history back
|
||||
view.dispatch({
|
||||
effects: [codeManagerHistoryCompartment.reconfigure([history()])],
|
||||
annotations: [codeManagerUpdateEvent],
|
||||
})
|
||||
}
|
||||
|
@ -58,7 +58,13 @@ const newVar = myVar + 1`
|
||||
`
|
||||
const mem = await exe(code)
|
||||
// geo is three js buffer geometry and is very bloated to have in tests
|
||||
const minusGeo = mem.get('mySketch')?.value?.paths
|
||||
const sk = mem.get('mySketch')
|
||||
expect(sk?.type).toEqual('Sketch')
|
||||
if (sk?.type !== 'Sketch') {
|
||||
return
|
||||
}
|
||||
|
||||
const minusGeo = sk?.value?.paths
|
||||
expect(minusGeo).toEqual([
|
||||
{
|
||||
type: 'ToPoint',
|
||||
@ -150,7 +156,7 @@ const newVar = myVar + 1`
|
||||
].join('\n')
|
||||
const mem = await exe(code)
|
||||
expect(mem.get('mySk1')).toEqual({
|
||||
type: 'UserVal',
|
||||
type: 'Sketch',
|
||||
value: {
|
||||
type: 'Sketch',
|
||||
on: expect.any(Object),
|
||||
@ -215,7 +221,6 @@ const newVar = myVar + 1`
|
||||
id: expect.any(String),
|
||||
__meta: [{ sourceRange: [39, 63, 0] }],
|
||||
},
|
||||
__meta: [{ sourceRange: [39, 63, 0] }],
|
||||
})
|
||||
})
|
||||
it('execute array expression', async () => {
|
||||
@ -225,7 +230,7 @@ const newVar = myVar + 1`
|
||||
const mem = await exe(code)
|
||||
// TODO path to node is probably wrong here, zero indexes are not correct
|
||||
expect(mem.get('three')).toEqual({
|
||||
type: 'UserVal',
|
||||
type: 'Int',
|
||||
value: 3,
|
||||
__meta: [
|
||||
{
|
||||
@ -234,8 +239,17 @@ const newVar = myVar + 1`
|
||||
],
|
||||
})
|
||||
expect(mem.get('yo')).toEqual({
|
||||
type: 'UserVal',
|
||||
value: [1, '2', 3, 9],
|
||||
type: 'Array',
|
||||
value: [
|
||||
{ type: 'Int', value: 1, __meta: [{ sourceRange: [28, 29, 0] }] },
|
||||
{ type: 'String', value: '2', __meta: [{ sourceRange: [31, 34, 0] }] },
|
||||
{ type: 'Int', value: 3, __meta: [{ sourceRange: [14, 15, 0] }] },
|
||||
{
|
||||
type: 'Number',
|
||||
value: 9,
|
||||
__meta: [{ sourceRange: [43, 44, 0] }, { sourceRange: [47, 48, 0] }],
|
||||
},
|
||||
],
|
||||
__meta: [
|
||||
{
|
||||
sourceRange: [27, 49, 0],
|
||||
@ -253,8 +267,25 @@ const newVar = myVar + 1`
|
||||
].join('\n')
|
||||
const mem = await exe(code)
|
||||
expect(mem.get('yo')).toEqual({
|
||||
type: 'UserVal',
|
||||
value: { aStr: 'str', anum: 2, identifier: 3, binExp: 9 },
|
||||
type: 'Object',
|
||||
value: {
|
||||
aStr: {
|
||||
type: 'String',
|
||||
value: 'str',
|
||||
__meta: [{ sourceRange: [34, 39, 0] }],
|
||||
},
|
||||
anum: { type: 'Int', value: 2, __meta: [{ sourceRange: [47, 48, 0] }] },
|
||||
identifier: {
|
||||
type: 'Int',
|
||||
value: 3,
|
||||
__meta: [{ sourceRange: [14, 15, 0] }],
|
||||
},
|
||||
binExp: {
|
||||
type: 'Number',
|
||||
value: 9,
|
||||
__meta: [{ sourceRange: [77, 78, 0] }, { sourceRange: [81, 82, 0] }],
|
||||
},
|
||||
},
|
||||
__meta: [
|
||||
{
|
||||
sourceRange: [27, 83, 0],
|
||||
@ -268,11 +299,11 @@ const newVar = myVar + 1`
|
||||
)
|
||||
const mem = await exe(code)
|
||||
expect(mem.get('myVar')).toEqual({
|
||||
type: 'UserVal',
|
||||
type: 'String',
|
||||
value: '123',
|
||||
__meta: [
|
||||
{
|
||||
sourceRange: [41, 50, 0],
|
||||
sourceRange: [19, 24, 0],
|
||||
},
|
||||
],
|
||||
})
|
||||
@ -356,7 +387,26 @@ describe('testing math operators', () => {
|
||||
it('with unaryExpression in ArrayExpression', async () => {
|
||||
const code = 'const myVar = [1,-legLen(5, 4)]'
|
||||
const mem = await exe(code)
|
||||
expect(mem.get('myVar')?.value).toEqual([1, -3])
|
||||
expect(mem.get('myVar')?.value).toEqual([
|
||||
{
|
||||
__meta: [
|
||||
{
|
||||
sourceRange: [15, 16, 0],
|
||||
},
|
||||
],
|
||||
type: 'Int',
|
||||
value: 1,
|
||||
},
|
||||
{
|
||||
__meta: [
|
||||
{
|
||||
sourceRange: [17, 30, 0],
|
||||
},
|
||||
],
|
||||
type: 'Number',
|
||||
value: -3,
|
||||
},
|
||||
])
|
||||
})
|
||||
it('with unaryExpression in ArrayExpression in CallExpression, checking nothing funny happens when used in a sketch', async () => {
|
||||
const code = [
|
||||
|
@ -55,18 +55,13 @@ describe('Test KCL Samples from public Github repository', () => {
|
||||
})
|
||||
// Run through all of the files in the manifest json. This will allow us to be automatically updated
|
||||
// with the latest changes in github. We won't be hard coding the filenames
|
||||
it(
|
||||
'should run through all the files',
|
||||
async () => {
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file: KclSampleFile = files[i]
|
||||
const code = await getKclSampleCodeFromGithub(file.filename)
|
||||
const parsed = parse(code)
|
||||
assert(!(parsed instanceof Error))
|
||||
}
|
||||
},
|
||||
files.length * 1000
|
||||
)
|
||||
files.forEach((file: KclSampleFile) => {
|
||||
it(`should parse ${file.filename} without errors`, async () => {
|
||||
const code = await getKclSampleCodeFromGithub(file.filename)
|
||||
const parsed = parse(code)
|
||||
assert(!(parsed instanceof Error))
|
||||
}, 1000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('when performing enginelessExecutor', () => {
|
||||
|
@ -8,6 +8,7 @@ import {
|
||||
VariableDeclarator,
|
||||
Expr,
|
||||
Literal,
|
||||
LiteralValue,
|
||||
PipeSubstitution,
|
||||
Identifier,
|
||||
ArrayExpression,
|
||||
@ -18,6 +19,7 @@ import {
|
||||
ProgramMemory,
|
||||
SourceRange,
|
||||
sketchFromKclValue,
|
||||
isPathToNodeNumber,
|
||||
} from './wasm'
|
||||
import {
|
||||
isNodeSafeToReplacePath,
|
||||
@ -525,6 +527,60 @@ export function sketchOnExtrudedFace(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Modify the AST to create a new sketch using the variable declaration
|
||||
* of an offset plane. The new sketch just has to come after the offset
|
||||
* plane declaration.
|
||||
*/
|
||||
export function sketchOnOffsetPlane(
|
||||
node: Node<Program>,
|
||||
offsetPathToNode: PathToNode
|
||||
) {
|
||||
let _node = { ...node }
|
||||
|
||||
// Find the offset plane declaration
|
||||
const offsetPlaneDeclarator = getNodeFromPath<VariableDeclarator>(
|
||||
_node,
|
||||
offsetPathToNode,
|
||||
'VariableDeclarator',
|
||||
true
|
||||
)
|
||||
if (err(offsetPlaneDeclarator)) return offsetPlaneDeclarator
|
||||
const { node: offsetPlaneNode } = offsetPlaneDeclarator
|
||||
const offsetPlaneName = offsetPlaneNode.id.name
|
||||
|
||||
// Create a new sketch declaration
|
||||
const newSketchName = findUniqueName(
|
||||
node,
|
||||
KCL_DEFAULT_CONSTANT_PREFIXES.SKETCH
|
||||
)
|
||||
const newSketch = createVariableDeclaration(
|
||||
newSketchName,
|
||||
createCallExpressionStdLib('startSketchOn', [
|
||||
createIdentifier(offsetPlaneName),
|
||||
]),
|
||||
undefined,
|
||||
'const'
|
||||
)
|
||||
|
||||
// Decide where to insert the new sketch declaration
|
||||
const offsetIndex = offsetPathToNode[1][0]
|
||||
|
||||
if (!isPathToNodeNumber(offsetIndex)) {
|
||||
return new Error('Expected offsetIndex to be a number')
|
||||
}
|
||||
// and insert it
|
||||
_node.body.splice(offsetIndex + 1, 0, newSketch)
|
||||
const newPathToNode = structuredClone(offsetPathToNode)
|
||||
newPathToNode[1][0] = offsetIndex + 1
|
||||
|
||||
// Return the modified AST and the path to the new sketch declaration
|
||||
return {
|
||||
modifiedAst: _node,
|
||||
pathToNode: newPathToNode,
|
||||
}
|
||||
}
|
||||
|
||||
export const getLastIndex = (pathToNode: PathToNode): number =>
|
||||
splitPathAtLastIndex(pathToNode).index
|
||||
|
||||
@ -573,7 +629,7 @@ export function splitPathAtPipeExpression(pathToNode: PathToNode): {
|
||||
return splitPathAtPipeExpression(pathToNode.slice(0, -1))
|
||||
}
|
||||
|
||||
export function createLiteral(value: string | number): Node<Literal> {
|
||||
export function createLiteral(value: LiteralValue): Node<Literal> {
|
||||
return {
|
||||
type: 'Literal',
|
||||
start: 0,
|
||||
|
@ -35,7 +35,12 @@ import {
|
||||
ArtifactGraph,
|
||||
getSweepFromSuspectedPath,
|
||||
} from 'lang/std/artifactGraph'
|
||||
import { kclManager, engineCommandManager, editorManager } from 'lib/singletons'
|
||||
import {
|
||||
kclManager,
|
||||
engineCommandManager,
|
||||
editorManager,
|
||||
codeManager,
|
||||
} from 'lib/singletons'
|
||||
import { Node } from 'wasm-lib/kcl/bindings/Node'
|
||||
|
||||
// Apply Fillet To Selection
|
||||
@ -253,6 +258,9 @@ async function updateAstAndFocus(
|
||||
const updatedAst = await kclManager.updateAst(modifiedAst, true, {
|
||||
focusPath: pathToFilletNode,
|
||||
})
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
if (updatedAst?.selections) {
|
||||
editorManager.selectRange(updatedAst?.selections)
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
import { parse, recast, initPromise, PathToNode } from './wasm'
|
||||
import { parse, recast, initPromise, PathToNode, Identifier } from './wasm'
|
||||
import {
|
||||
findAllPreviousVariables,
|
||||
isNodeSafeToReplace,
|
||||
@ -10,6 +10,7 @@ import {
|
||||
hasSketchPipeBeenExtruded,
|
||||
doesSceneHaveSweepableSketch,
|
||||
traverse,
|
||||
getNodeFromPath,
|
||||
} from './queryAst'
|
||||
import { enginelessExecutor } from '../lib/testHelpers'
|
||||
import {
|
||||
@ -266,6 +267,86 @@ describe('testing getNodePathFromSourceRange', () => {
|
||||
])
|
||||
expect(selectWholeThing).toEqual(expected)
|
||||
})
|
||||
|
||||
it('finds the node in if-else condition', () => {
|
||||
const code = `y = 0
|
||||
x = if x > y {
|
||||
x + 1
|
||||
} else {
|
||||
y
|
||||
}`
|
||||
const searchLn = `x > y`
|
||||
const sourceIndex = code.indexOf(searchLn)
|
||||
const ast = parse(code)
|
||||
if (err(ast)) throw ast
|
||||
|
||||
const result = getNodePathFromSourceRange(ast, [sourceIndex, sourceIndex])
|
||||
expect(result).toEqual([
|
||||
['body', ''],
|
||||
[1, 'index'],
|
||||
['declarations', 'VariableDeclaration'],
|
||||
[0, 'index'],
|
||||
['init', ''],
|
||||
['cond', 'IfExpression'],
|
||||
['left', 'BinaryExpression'],
|
||||
])
|
||||
const _node = getNodeFromPath<Identifier>(ast, result)
|
||||
if (err(_node)) throw _node
|
||||
expect(_node.node.type).toEqual('Identifier')
|
||||
expect(_node.node.name).toEqual('x')
|
||||
})
|
||||
|
||||
it('finds the node in if-else then', () => {
|
||||
const code = `y = 0
|
||||
x = if x > y {
|
||||
x + 1
|
||||
} else {
|
||||
y
|
||||
}`
|
||||
const searchLn = `x + 1`
|
||||
const sourceIndex = code.indexOf(searchLn)
|
||||
const ast = parse(code)
|
||||
if (err(ast)) throw ast
|
||||
|
||||
const result = getNodePathFromSourceRange(ast, [sourceIndex, sourceIndex])
|
||||
expect(result).toEqual([
|
||||
['body', ''],
|
||||
[1, 'index'],
|
||||
['declarations', 'VariableDeclaration'],
|
||||
[0, 'index'],
|
||||
['init', ''],
|
||||
['then_val', 'IfExpression'],
|
||||
['body', 'IfExpression'],
|
||||
[0, 'index'],
|
||||
['expression', 'ExpressionStatement'],
|
||||
['left', 'BinaryExpression'],
|
||||
])
|
||||
const _node = getNodeFromPath<Identifier>(ast, result)
|
||||
if (err(_node)) throw _node
|
||||
expect(_node.node.type).toEqual('Identifier')
|
||||
expect(_node.node.name).toEqual('x')
|
||||
})
|
||||
|
||||
it('finds the node in import statement item', () => {
|
||||
const code = `import foo, bar as baz from 'thing.kcl'`
|
||||
const searchLn = `bar`
|
||||
const sourceIndex = code.indexOf(searchLn)
|
||||
const ast = parse(code)
|
||||
if (err(ast)) throw ast
|
||||
|
||||
const result = getNodePathFromSourceRange(ast, [sourceIndex, sourceIndex])
|
||||
expect(result).toEqual([
|
||||
['body', ''],
|
||||
[0, 'index'],
|
||||
['items', 'ImportStatement'],
|
||||
[1, 'index'],
|
||||
['name', 'ImportItem'],
|
||||
])
|
||||
const _node = getNodeFromPath<Identifier>(ast, result)
|
||||
if (err(_node)) throw _node
|
||||
expect(_node.node.type).toEqual('Identifier')
|
||||
expect(_node.node.name).toEqual('bar')
|
||||
})
|
||||
})
|
||||
|
||||
describe('testing doesPipeHave', () => {
|
||||
|
@ -317,6 +317,62 @@ function moreNodePathFromSourceRange(
|
||||
}
|
||||
|
||||
if (_node.type === 'PipeSubstitution' && isInRange) return path
|
||||
|
||||
if (_node.type === 'IfExpression' && isInRange) {
|
||||
const { cond, then_val, else_ifs, final_else } = _node
|
||||
if (cond.start <= start && cond.end >= end) {
|
||||
path.push(['cond', 'IfExpression'])
|
||||
return moreNodePathFromSourceRange(cond, sourceRange, path)
|
||||
}
|
||||
if (then_val.start <= start && then_val.end >= end) {
|
||||
path.push(['then_val', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(then_val, sourceRange, path)
|
||||
}
|
||||
for (let i = 0; i < else_ifs.length; i++) {
|
||||
const else_if = else_ifs[i]
|
||||
if (else_if.start <= start && else_if.end >= end) {
|
||||
path.push(['else_ifs', 'IfExpression'])
|
||||
path.push([i, 'index'])
|
||||
const { cond, then_val } = else_if
|
||||
if (cond.start <= start && cond.end >= end) {
|
||||
path.push(['cond', 'IfExpression'])
|
||||
return moreNodePathFromSourceRange(cond, sourceRange, path)
|
||||
}
|
||||
path.push(['then_val', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(then_val, sourceRange, path)
|
||||
}
|
||||
}
|
||||
if (final_else.start <= start && final_else.end >= end) {
|
||||
path.push(['final_else', 'IfExpression'])
|
||||
path.push(['body', 'IfExpression'])
|
||||
return getNodePathFromSourceRange(final_else, sourceRange, path)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
if (_node.type === 'ImportStatement' && isInRange) {
|
||||
const { items } = _node
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]
|
||||
if (item.start <= start && item.end >= end) {
|
||||
path.push(['items', 'ImportStatement'])
|
||||
path.push([i, 'index'])
|
||||
if (item.name.start <= start && item.name.end >= end) {
|
||||
path.push(['name', 'ImportItem'])
|
||||
return path
|
||||
}
|
||||
if (item.alias && item.alias.start <= start && item.alias.end >= end) {
|
||||
path.push(['alias', 'ImportItem'])
|
||||
return path
|
||||
}
|
||||
return path
|
||||
}
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
console.error('not implemented: ' + node.type)
|
||||
|
||||
return path
|
||||
|
@ -98,12 +98,22 @@ sketch004 = startSketchOn(extrude003, seg02)
|
||||
|> close(%)
|
||||
extrude004 = extrude(3, sketch004)
|
||||
`
|
||||
const exampleCodeOffsetPlanes = `
|
||||
offsetPlane001 = offsetPlane("XY", 20)
|
||||
offsetPlane002 = offsetPlane("XZ", -50)
|
||||
offsetPlane003 = offsetPlane("YZ", 10)
|
||||
|
||||
sketch002 = startSketchOn(offsetPlane001)
|
||||
|> startProfileAt([0, 0], %)
|
||||
|> line([6.78, 15.01], %)
|
||||
`
|
||||
|
||||
// add more code snippets here and use `getCommands` to get the orderedCommands and responseMap for more tests
|
||||
const codeToWriteCacheFor = {
|
||||
exampleCode1,
|
||||
sketchOnFaceOnFaceEtc,
|
||||
exampleCodeNo3D,
|
||||
exampleCodeOffsetPlanes,
|
||||
} as const
|
||||
|
||||
type CodeKey = keyof typeof codeToWriteCacheFor
|
||||
@ -165,6 +175,52 @@ afterAll(() => {
|
||||
})
|
||||
|
||||
describe('testing createArtifactGraph', () => {
|
||||
describe('code with offset planes and a sketch:', () => {
|
||||
let ast: Program
|
||||
let theMap: ReturnType<typeof createArtifactGraph>
|
||||
|
||||
it('setup', () => {
|
||||
// putting this logic in here because describe blocks runs before beforeAll has finished
|
||||
const {
|
||||
orderedCommands,
|
||||
responseMap,
|
||||
ast: _ast,
|
||||
} = getCommands('exampleCodeOffsetPlanes')
|
||||
ast = _ast
|
||||
theMap = createArtifactGraph({ orderedCommands, responseMap, ast })
|
||||
})
|
||||
|
||||
it(`there should be one sketch`, () => {
|
||||
const sketches = [...filterArtifacts({ types: ['path'] }, theMap)].map(
|
||||
(path) => expandPath(path[1], theMap)
|
||||
)
|
||||
expect(sketches).toHaveLength(1)
|
||||
sketches.forEach((path) => {
|
||||
if (err(path)) throw path
|
||||
expect(path.type).toBe('path')
|
||||
})
|
||||
})
|
||||
|
||||
it(`there should be three offsetPlanes`, () => {
|
||||
const offsetPlanes = [
|
||||
...filterArtifacts({ types: ['plane'] }, theMap),
|
||||
].map((plane) => expandPlane(plane[1], theMap))
|
||||
expect(offsetPlanes).toHaveLength(3)
|
||||
offsetPlanes.forEach((path) => {
|
||||
expect(path.type).toBe('plane')
|
||||
})
|
||||
})
|
||||
|
||||
it(`Only one offset plane should have a path`, () => {
|
||||
const offsetPlanes = [
|
||||
...filterArtifacts({ types: ['plane'] }, theMap),
|
||||
].map((plane) => expandPlane(plane[1], theMap))
|
||||
const offsetPlaneWithPaths = offsetPlanes.filter(
|
||||
(plane) => plane.paths.length
|
||||
)
|
||||
expect(offsetPlaneWithPaths).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
describe('code with an extrusion, fillet and sketch of face:', () => {
|
||||
let ast: Program
|
||||
let theMap: ReturnType<typeof createArtifactGraph>
|
||||
|
@ -249,7 +249,20 @@ export function getArtifactsToUpdate({
|
||||
const cmd = command.cmd
|
||||
const returnArr: ReturnType<typeof getArtifactsToUpdate> = []
|
||||
if (!response) return returnArr
|
||||
if (cmd.type === 'enable_sketch_mode') {
|
||||
if (cmd.type === 'make_plane' && range[1] !== 0) {
|
||||
// If we're calling `make_plane` and the code range doesn't end at `0`
|
||||
// it's not a default plane, but a custom one from the offsetPlane standard library function
|
||||
return [
|
||||
{
|
||||
id,
|
||||
artifact: {
|
||||
type: 'plane',
|
||||
pathIds: [],
|
||||
codeRef: { range, pathToNode },
|
||||
},
|
||||
},
|
||||
]
|
||||
} else if (cmd.type === 'enable_sketch_mode') {
|
||||
const plane = getArtifact(currentPlaneId)
|
||||
const pathIds = plane?.type === 'plane' ? plane?.pathIds : []
|
||||
const codeRef =
|
||||
@ -633,7 +646,7 @@ export function expandSweep(
|
||||
if (err(path)) return path
|
||||
return {
|
||||
type: 'sweep',
|
||||
subType: 'extrusion',
|
||||
subType: sweep.subType,
|
||||
surfaces: Array.from(surfs.values()),
|
||||
edges: Array.from(edges.values()),
|
||||
path,
|
||||
|
@ -1631,7 +1631,11 @@ export class EngineCommandManager extends EventTarget {
|
||||
|
||||
switch (this.exportInfo.intent) {
|
||||
case ExportIntent.Save: {
|
||||
exportSave(event.data, this.pendingExport.toastId).then(() => {
|
||||
exportSave({
|
||||
data: event.data,
|
||||
fileName: this.exportInfo.name,
|
||||
toastId: this.pendingExport.toastId,
|
||||
}).then(() => {
|
||||
this.pendingExport?.resolve(null)
|
||||
}, this.pendingExport?.reject)
|
||||
break
|
||||
|
@ -1,5 +1,12 @@
|
||||
import { Selections } from 'lib/selections'
|
||||
import { Program, PathToNode } from './wasm'
|
||||
import {
|
||||
Program,
|
||||
PathToNode,
|
||||
CallExpression,
|
||||
Literal,
|
||||
ArrayExpression,
|
||||
BinaryExpression,
|
||||
} from './wasm'
|
||||
import { getNodeFromPath } from './queryAst'
|
||||
import { ArtifactGraph, filterArtifacts } from 'lang/std/artifactGraph'
|
||||
import { isOverlap } from 'lib/utils'
|
||||
@ -84,3 +91,19 @@ export function isCursorInSketchCommandRange(
|
||||
([, artifact]) => artifact.type === 'path'
|
||||
)?.[0] || false
|
||||
}
|
||||
|
||||
export function isCallExpression(e: any): e is CallExpression {
|
||||
return e && e.type === 'CallExpression'
|
||||
}
|
||||
|
||||
export function isArrayExpression(e: any): e is ArrayExpression {
|
||||
return e && e.type === 'ArrayExpression'
|
||||
}
|
||||
|
||||
export function isLiteral(e: any): e is Literal {
|
||||
return e && e.type === 'Literal'
|
||||
}
|
||||
|
||||
export function isBinaryExpression(e: any): e is BinaryExpression {
|
||||
return e && e.type === 'BinaryExpression'
|
||||
}
|
||||
|
@ -62,6 +62,7 @@ export type { CallExpression } from '../wasm-lib/kcl/bindings/CallExpression'
|
||||
export type { VariableDeclarator } from '../wasm-lib/kcl/bindings/VariableDeclarator'
|
||||
export type { BinaryPart } from '../wasm-lib/kcl/bindings/BinaryPart'
|
||||
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 SyntaxType =
|
||||
@ -81,6 +82,7 @@ export type SyntaxType =
|
||||
| 'PipeExpression'
|
||||
| 'PipeSubstitution'
|
||||
| 'Literal'
|
||||
| 'LiteralValue'
|
||||
| 'NonCodeNode'
|
||||
| 'UnaryExpression'
|
||||
|
||||
@ -142,6 +144,12 @@ export const parse = (code: string | Error): Node<Program> | Error => {
|
||||
|
||||
export type PathToNode = [string | number, string][]
|
||||
|
||||
export const isPathToNodeNumber = (
|
||||
pathToNode: string | number
|
||||
): pathToNode is number => {
|
||||
return typeof pathToNode === 'number'
|
||||
}
|
||||
|
||||
export interface ExecState {
|
||||
memory: ProgramMemory
|
||||
idGenerator: IdGenerator
|
||||
@ -336,7 +344,7 @@ export class ProgramMemory {
|
||||
*/
|
||||
hasSketchOrSolid(): boolean {
|
||||
for (const node of this.visibleEntries().values()) {
|
||||
if (node.type === 'Solid' || node.value?.type === 'Sketch') {
|
||||
if (node.type === 'Solid' || node.type === 'Sketch') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
@ -68,7 +68,16 @@ const save_ = async (file: ModelingAppFile, toastId: string) => {
|
||||
}
|
||||
|
||||
// Saves files locally from an export call.
|
||||
export async function exportSave(data: ArrayBuffer, toastId: string) {
|
||||
// We override the file's name with one passed in from the client side.
|
||||
export async function exportSave({
|
||||
data,
|
||||
fileName,
|
||||
toastId,
|
||||
}: {
|
||||
data: ArrayBuffer
|
||||
fileName: string
|
||||
toastId: string
|
||||
}) {
|
||||
// This converts the ArrayBuffer to a Rust equivalent Vec<u8>.
|
||||
let uintArray = new Uint8Array(data)
|
||||
|
||||
@ -80,9 +89,10 @@ export async function exportSave(data: ArrayBuffer, toastId: string) {
|
||||
zip.file(file.name, new Uint8Array(file.contents), { binary: true })
|
||||
}
|
||||
return zip.generateAsync({ type: 'array' }).then((contents) => {
|
||||
return save_({ name: 'output.zip', contents }, toastId)
|
||||
return save_({ name: `${fileName || 'output'}.zip`, contents }, toastId)
|
||||
})
|
||||
} else {
|
||||
files[0].name = fileName || files[0].name
|
||||
return save_(files[0], toastId)
|
||||
}
|
||||
}
|
||||
|
@ -9,8 +9,16 @@ import {
|
||||
createUnaryExpression,
|
||||
} from 'lang/modifyAst'
|
||||
import { ArrayExpression, CallExpression, PipeExpression } from 'lang/wasm'
|
||||
import { roundOff } from 'lib/utils'
|
||||
import {
|
||||
isCallExpression,
|
||||
isArrayExpression,
|
||||
isLiteral,
|
||||
isBinaryExpression,
|
||||
} from 'lang/util'
|
||||
|
||||
/**
|
||||
* It does not create the startSketchOn and it does not create the startProfileAt.
|
||||
* Returns AST expressions for this KCL code:
|
||||
* const yo = startSketchOn('XY')
|
||||
* |> startProfileAt([0, 0], %)
|
||||
@ -92,3 +100,69 @@ export function updateRectangleSketch(
|
||||
createLiteral(Math.abs(y)), // This will be the height of the rectangle
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutates the pipeExpression to update the center rectangle sketch
|
||||
* @param pipeExpression
|
||||
* @param x
|
||||
* @param y
|
||||
* @param tag
|
||||
*/
|
||||
export function updateCenterRectangleSketch(
|
||||
pipeExpression: PipeExpression,
|
||||
deltaX: number,
|
||||
deltaY: number,
|
||||
tag: string,
|
||||
originX: number,
|
||||
originY: number
|
||||
) {
|
||||
let startX = originX - Math.abs(deltaX)
|
||||
let startY = originY - Math.abs(deltaY)
|
||||
|
||||
// pipeExpression.body[1] is startProfileAt
|
||||
let callExpression = pipeExpression.body[1]
|
||||
if (isCallExpression(callExpression)) {
|
||||
const arrayExpression = callExpression.arguments[0]
|
||||
if (isArrayExpression(arrayExpression)) {
|
||||
callExpression.arguments[0] = createArrayExpression([
|
||||
createLiteral(roundOff(startX)),
|
||||
createLiteral(roundOff(startY)),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
const twoX = deltaX * 2
|
||||
const twoY = deltaY * 2
|
||||
|
||||
callExpression = pipeExpression.body[2]
|
||||
if (isCallExpression(callExpression)) {
|
||||
const arrayExpression = callExpression.arguments[0]
|
||||
if (isArrayExpression(arrayExpression)) {
|
||||
const literal = arrayExpression.elements[0]
|
||||
if (isLiteral(literal)) {
|
||||
callExpression.arguments[0] = createArrayExpression([
|
||||
createLiteral(literal.value),
|
||||
createLiteral(Math.abs(twoX)),
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
callExpression = pipeExpression.body[3]
|
||||
if (isCallExpression(callExpression)) {
|
||||
const arrayExpression = callExpression.arguments[0]
|
||||
if (isArrayExpression(arrayExpression)) {
|
||||
const binaryExpression = arrayExpression.elements[0]
|
||||
if (isBinaryExpression(binaryExpression)) {
|
||||
callExpression.arguments[0] = createArrayExpression([
|
||||
createBinaryExpression([
|
||||
createCallExpressionStdLib('segAng', [createIdentifier(tag)]),
|
||||
binaryExpression.operator,
|
||||
createLiteral(90),
|
||||
]), // 90 offset from the previous line
|
||||
createLiteral(Math.abs(twoY)), // This will be the height of the rectangle
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -124,7 +124,9 @@ export const fileLoader: LoaderFunction = async (
|
||||
// We explicitly do not write to the file here since we are loading from
|
||||
// the file system and not the editor.
|
||||
codeManager.updateCurrentFilePath(currentFilePath)
|
||||
codeManager.updateCodeStateEditor(code)
|
||||
// We pass true on the end here to clear the code editor history.
|
||||
// This way undo and redo are not super weird when opening new files.
|
||||
codeManager.updateCodeStateEditor(code, true)
|
||||
}
|
||||
|
||||
// Set the file system manager to the project path
|
||||
|
@ -407,8 +407,9 @@ export const toolbarConfig: Record<ToolbarModeName, ToolbarMode> = {
|
||||
status: 'available',
|
||||
title: 'Center circle',
|
||||
disabled: (state) =>
|
||||
!canRectangleOrCircleTool(state.context) &&
|
||||
!state.matches({ Sketch: 'Circle tool' }),
|
||||
state.matches('Sketch no face') ||
|
||||
(!canRectangleOrCircleTool(state.context) &&
|
||||
!state.matches({ Sketch: 'Circle tool' })),
|
||||
isActive: (state) => state.matches({ Sketch: 'Circle tool' }),
|
||||
hotkey: (state) =>
|
||||
state.matches({ Sketch: 'Circle tool' }) ? ['Esc', 'C'] : 'C',
|
||||
@ -448,8 +449,9 @@ export const toolbarConfig: Record<ToolbarModeName, ToolbarMode> = {
|
||||
icon: 'rectangle',
|
||||
status: 'available',
|
||||
disabled: (state) =>
|
||||
!canRectangleOrCircleTool(state.context) &&
|
||||
!state.matches({ Sketch: 'Rectangle tool' }),
|
||||
state.matches('Sketch no face') ||
|
||||
(!canRectangleOrCircleTool(state.context) &&
|
||||
!state.matches({ Sketch: 'Rectangle tool' })),
|
||||
title: 'Corner rectangle',
|
||||
hotkey: (state) =>
|
||||
state.matches({ Sketch: 'Rectangle tool' }) ? ['Esc', 'R'] : 'R',
|
||||
@ -459,13 +461,33 @@ export const toolbarConfig: Record<ToolbarModeName, ToolbarMode> = {
|
||||
},
|
||||
{
|
||||
id: 'center-rectangle',
|
||||
onClick: () => console.error('Center rectangle not yet implemented'),
|
||||
icon: 'rectangle',
|
||||
status: 'unavailable',
|
||||
onClick: ({ modelingState, modelingSend }) =>
|
||||
modelingSend({
|
||||
type: 'change tool',
|
||||
data: {
|
||||
tool: !modelingState.matches({
|
||||
Sketch: 'Center Rectangle tool',
|
||||
})
|
||||
? 'center rectangle'
|
||||
: 'none',
|
||||
},
|
||||
}),
|
||||
icon: 'arc',
|
||||
status: 'available',
|
||||
disabled: (state) =>
|
||||
state.matches('Sketch no face') ||
|
||||
(!canRectangleOrCircleTool(state.context) &&
|
||||
!state.matches({ Sketch: 'Center Rectangle tool' })),
|
||||
title: 'Center rectangle',
|
||||
showTitle: false,
|
||||
hotkey: (state) =>
|
||||
state.matches({ Sketch: 'Center Rectangle tool' })
|
||||
? ['Esc', 'C']
|
||||
: 'C',
|
||||
description: 'Start drawing a rectangle from its center',
|
||||
links: [],
|
||||
isActive: (state) => {
|
||||
return state.matches({ Sketch: 'Center Rectangle tool' })
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
|
@ -91,7 +91,7 @@ export function useCalculateKclExpression({
|
||||
const _programMem: ProgramMemory = ProgramMemory.empty()
|
||||
for (const { key, value } of availableVarInfo.variables) {
|
||||
const error = _programMem.set(key, {
|
||||
type: 'UserVal',
|
||||
type: 'String',
|
||||
value,
|
||||
__meta: [],
|
||||
})
|
||||
@ -115,6 +115,7 @@ export function useCalculateKclExpression({
|
||||
setCalcResult(typeof result === 'number' ? String(result) : 'NAN')
|
||||
init && setValueNode(init)
|
||||
}
|
||||
if (!value) return
|
||||
execAstAndSetResult().catch(() => {
|
||||
setCalcResult('NAN')
|
||||
setValueNode(null)
|
||||
|
@ -18,6 +18,7 @@ import {
|
||||
sceneEntitiesManager,
|
||||
engineCommandManager,
|
||||
editorManager,
|
||||
codeManager,
|
||||
} from 'lib/singletons'
|
||||
import {
|
||||
horzVertInfo,
|
||||
@ -158,6 +159,15 @@ export type DefaultPlane = {
|
||||
yAxis: [number, number, number]
|
||||
}
|
||||
|
||||
export type OffsetPlane = {
|
||||
type: 'offsetPlane'
|
||||
position: [number, number, number]
|
||||
planeId: string
|
||||
pathToNode: PathToNode
|
||||
zAxis: [number, number, number]
|
||||
yAxis: [number, number, number]
|
||||
}
|
||||
|
||||
export type SegmentOverlayPayload =
|
||||
| {
|
||||
type: 'set-one'
|
||||
@ -183,6 +193,7 @@ export type SketchTool =
|
||||
| 'line'
|
||||
| 'tangentialArc'
|
||||
| 'rectangle'
|
||||
| 'center rectangle'
|
||||
| 'circle'
|
||||
| 'none'
|
||||
|
||||
@ -196,7 +207,7 @@ export type ModelingMachineEvent =
|
||||
| { type: 'Sketch On Face' }
|
||||
| {
|
||||
type: 'Select default plane'
|
||||
data: DefaultPlane | ExtrudeFacePlane
|
||||
data: DefaultPlane | ExtrudeFacePlane | OffsetPlane
|
||||
}
|
||||
| {
|
||||
type: 'Set selection'
|
||||
@ -237,6 +248,10 @@ export type ModelingMachineEvent =
|
||||
type: 'Add rectangle origin'
|
||||
data: [x: number, y: number]
|
||||
}
|
||||
| {
|
||||
type: 'Add center rectangle origin'
|
||||
data: [x: number, y: number]
|
||||
}
|
||||
| {
|
||||
type: 'Add circle origin'
|
||||
data: [x: number, y: number]
|
||||
@ -277,6 +292,7 @@ export type ModelingMachineEvent =
|
||||
}
|
||||
}
|
||||
| { type: 'Finish rectangle' }
|
||||
| { type: 'Finish center rectangle' }
|
||||
| { type: 'Finish circle' }
|
||||
| { type: 'Artifact graph populated' }
|
||||
| { type: 'Artifact graph emptied' }
|
||||
@ -505,6 +521,9 @@ export const modelingMachine = setup({
|
||||
'next is rectangle': ({ context: { sketchDetails, currentTool } }) =>
|
||||
currentTool === 'rectangle' &&
|
||||
canRectangleOrCircleTool({ sketchDetails }),
|
||||
'next is center rectangle': ({ context: { sketchDetails, currentTool } }) =>
|
||||
currentTool === 'center rectangle' &&
|
||||
canRectangleOrCircleTool({ sketchDetails }),
|
||||
'next is circle': ({ context: { sketchDetails, currentTool } }) =>
|
||||
currentTool === 'circle' && canRectangleOrCircleTool({ sketchDetails }),
|
||||
'next is line': ({ context }) => context.currentTool === 'line',
|
||||
@ -531,8 +550,10 @@ export const modelingMachine = setup({
|
||||
}
|
||||
}
|
||||
),
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
'hide default planes': () => kclManager.hidePlanes(),
|
||||
'hide default planes': () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
kclManager.hidePlanes()
|
||||
},
|
||||
'reset sketch metadata': assign({
|
||||
sketchDetails: null,
|
||||
sketchEnginePathId: '',
|
||||
@ -595,7 +616,6 @@ export const modelingMachine = setup({
|
||||
if (trap(extrudeSketchRes)) return
|
||||
const { modifiedAst, pathToExtrudeArg } = extrudeSketchRes
|
||||
|
||||
store.videoElement?.pause()
|
||||
const updatedAst = await kclManager.updateAst(modifiedAst, true, {
|
||||
focusPath: [pathToExtrudeArg],
|
||||
zoomToFit: true,
|
||||
@ -604,11 +624,9 @@ export const modelingMachine = setup({
|
||||
type: 'path',
|
||||
},
|
||||
})
|
||||
if (!engineCommandManager.engineConnection?.idleMode) {
|
||||
store.videoElement?.play().catch((e) => {
|
||||
console.warn('Video playing was prevented', e)
|
||||
})
|
||||
}
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
if (updatedAst?.selections) {
|
||||
editorManager.selectRange(updatedAst?.selections)
|
||||
}
|
||||
@ -642,7 +660,6 @@ export const modelingMachine = setup({
|
||||
if (trap(revolveSketchRes)) return
|
||||
const { modifiedAst, pathToRevolveArg } = revolveSketchRes
|
||||
|
||||
store.videoElement?.pause()
|
||||
const updatedAst = await kclManager.updateAst(modifiedAst, true, {
|
||||
focusPath: [pathToRevolveArg],
|
||||
zoomToFit: true,
|
||||
@ -651,11 +668,9 @@ export const modelingMachine = setup({
|
||||
type: 'path',
|
||||
},
|
||||
})
|
||||
if (!engineCommandManager.engineConnection?.idleMode) {
|
||||
store.videoElement?.play().catch((e) => {
|
||||
console.warn('Video playing was prevented', e)
|
||||
})
|
||||
}
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
if (updatedAst?.selections) {
|
||||
editorManager.selectRange(updatedAst?.selections)
|
||||
}
|
||||
@ -685,6 +700,7 @@ export const modelingMachine = setup({
|
||||
}
|
||||
|
||||
await kclManager.updateAst(modifiedAst, true)
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(modifiedAst)
|
||||
})().catch(reportRejection)
|
||||
},
|
||||
'AST fillet': ({ event }) => {
|
||||
@ -702,6 +718,9 @@ export const modelingMachine = setup({
|
||||
radius
|
||||
)
|
||||
if (err(applyFilletToSelectionResult)) return applyFilletToSelectionResult
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
},
|
||||
'set selection filter to curves only': () => {
|
||||
;(async () => {
|
||||
@ -758,25 +777,35 @@ export const modelingMachine = setup({
|
||||
'remove sketch grid': () => sceneEntitiesManager.removeSketchGrid(),
|
||||
'set up draft line': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.setUpDraftSegment(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
'line'
|
||||
)
|
||||
sceneEntitiesManager
|
||||
.setupDraftSegment(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
'line'
|
||||
)
|
||||
.then(() => {
|
||||
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
})
|
||||
},
|
||||
'set up draft arc': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.setUpDraftSegment(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
'tangentialArcTo'
|
||||
)
|
||||
sceneEntitiesManager
|
||||
.setupDraftSegment(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
'tangentialArcTo'
|
||||
)
|
||||
.then(() => {
|
||||
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
})
|
||||
},
|
||||
'listen for rectangle origin': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
@ -795,6 +824,26 @@ export const modelingMachine = setup({
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
'listen for center rectangle origin': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
// setupNoPointsListener has the code for startProfileAt onClick
|
||||
sceneEntitiesManager.setupNoPointsListener({
|
||||
sketchDetails,
|
||||
afterClick: (args) => {
|
||||
const twoD = args.intersectionPoint?.twoD
|
||||
if (twoD) {
|
||||
sceneInfra.modelingSend({
|
||||
type: 'Add center rectangle origin',
|
||||
data: [twoD.x, twoD.y],
|
||||
})
|
||||
} else {
|
||||
console.error('No intersection point found')
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
'listen for circle origin': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
sceneEntitiesManager.createIntersectionPlane()
|
||||
@ -834,8 +883,28 @@ export const modelingMachine = setup({
|
||||
'set up draft rectangle': ({ context: { sketchDetails }, event }) => {
|
||||
if (event.type !== 'Add rectangle origin') return
|
||||
if (!sketchDetails || !event.data) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.setupDraftRectangle(
|
||||
sceneEntitiesManager
|
||||
.setupDraftRectangle(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
event.data
|
||||
)
|
||||
.then(() => {
|
||||
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
})
|
||||
},
|
||||
'set up draft center rectangle': ({
|
||||
context: { sketchDetails },
|
||||
event,
|
||||
}) => {
|
||||
if (event.type !== 'Add center rectangle origin') return
|
||||
if (!sketchDetails || !event.data) return
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.setupDraftCenterRectangle(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
@ -846,26 +915,36 @@ export const modelingMachine = setup({
|
||||
'set up draft circle': ({ context: { sketchDetails }, event }) => {
|
||||
if (event.type !== 'Add circle origin') return
|
||||
if (!sketchDetails || !event.data) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.setupDraftCircle(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
event.data
|
||||
)
|
||||
sceneEntitiesManager
|
||||
.setupDraftCircle(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
event.data
|
||||
)
|
||||
.then(() => {
|
||||
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
})
|
||||
},
|
||||
'set up draft line without teardown': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.setUpDraftSegment(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
'line',
|
||||
false
|
||||
)
|
||||
sceneEntitiesManager
|
||||
.setupDraftSegment(
|
||||
sketchDetails.sketchPathToNode,
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin,
|
||||
'line',
|
||||
false
|
||||
)
|
||||
.then(() => {
|
||||
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
})
|
||||
},
|
||||
'show default planes': () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
@ -882,12 +961,17 @@ export const modelingMachine = setup({
|
||||
'add axis n grid': ({ context: { sketchDetails } }) => {
|
||||
if (!sketchDetails) return
|
||||
if (localStorage.getItem('disableAxis')) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
sceneEntitiesManager.createSketchAxis(
|
||||
sketchDetails.sketchPathToNode || [],
|
||||
sketchDetails.zAxis,
|
||||
sketchDetails.yAxis,
|
||||
sketchDetails.origin
|
||||
)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
},
|
||||
'reset client scene mouse handlers': () => {
|
||||
// when not in sketch mode we don't need any mouse listeners
|
||||
@ -916,10 +1000,13 @@ export const modelingMachine = setup({
|
||||
'Delete segment': ({ context: { sketchDetails }, event }) => {
|
||||
if (event.type !== 'Delete segment') return
|
||||
if (!sketchDetails || !event.data) return
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
||||
deleteSegment({
|
||||
pathToNode: event.data,
|
||||
sketchDetails,
|
||||
}).then(() => {
|
||||
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
|
||||
})
|
||||
},
|
||||
'Reset Segment Overlays': () => sceneEntitiesManager.resetOverlays(),
|
||||
@ -984,6 +1071,9 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
return {
|
||||
selectionType: 'completeSelection',
|
||||
selection: updateSelections(
|
||||
@ -1018,6 +1108,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
return {
|
||||
selectionType: 'completeSelection',
|
||||
selection: updateSelections(
|
||||
@ -1052,6 +1143,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
return {
|
||||
selectionType: 'completeSelection',
|
||||
selection: updateSelections(
|
||||
@ -1084,6 +1176,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
const updatedSelectionRanges = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -1117,6 +1210,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
const updatedSelectionRanges = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -1150,6 +1244,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
const updatedSelectionRanges = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -1183,6 +1278,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
const updatedSelectionRanges = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -1220,6 +1316,8 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
|
||||
const updatedSelectionRanges = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -1252,6 +1350,7 @@ export const modelingMachine = setup({
|
||||
)
|
||||
if (trap(updatedAst, { suppress: true })) return
|
||||
if (!updatedAst) return
|
||||
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
|
||||
const updatedSelectionRanges = updateSelections(
|
||||
pathToNodeMap,
|
||||
selectionRanges,
|
||||
@ -1304,7 +1403,7 @@ export const modelingMachine = setup({
|
||||
}
|
||||
),
|
||||
'animate-to-face': fromPromise(
|
||||
async (_: { input?: ExtrudeFacePlane | DefaultPlane }) => {
|
||||
async (_: { input?: ExtrudeFacePlane | DefaultPlane | OffsetPlane }) => {
|
||||
return {} as
|
||||
| undefined
|
||||
| {
|
||||
@ -1556,7 +1655,7 @@ export const modelingMachine = setup({
|
||||
},
|
||||
},
|
||||
|
||||
entry: 'setup client side sketch segments',
|
||||
entry: ['setup client side sketch segments'],
|
||||
},
|
||||
|
||||
'Await horizontal distance info': {
|
||||
@ -1776,6 +1875,40 @@ export const modelingMachine = setup({
|
||||
},
|
||||
},
|
||||
|
||||
'Center Rectangle tool': {
|
||||
entry: ['listen for center rectangle origin'],
|
||||
|
||||
states: {
|
||||
'Awaiting corner': {
|
||||
on: {
|
||||
'Finish center rectangle': 'Finished Center Rectangle',
|
||||
},
|
||||
},
|
||||
|
||||
'Awaiting origin': {
|
||||
on: {
|
||||
'Add center rectangle origin': {
|
||||
target: 'Awaiting corner',
|
||||
// TODO
|
||||
actions: 'set up draft center rectangle',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'Finished Center Rectangle': {
|
||||
always: '#Modeling.Sketch.SketchIdle',
|
||||
},
|
||||
},
|
||||
|
||||
initial: 'Awaiting origin',
|
||||
|
||||
on: {
|
||||
'change tool': {
|
||||
target: 'Change Tool',
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
'clean slate': {
|
||||
always: 'SketchIdle',
|
||||
},
|
||||
@ -1801,7 +1934,7 @@ export const modelingMachine = setup({
|
||||
onError: 'SketchIdle',
|
||||
onDone: {
|
||||
target: 'SketchIdle',
|
||||
actions: ['Set selection'],
|
||||
actions: 'Set selection',
|
||||
},
|
||||
},
|
||||
},
|
||||
@ -1969,6 +2102,10 @@ export const modelingMachine = setup({
|
||||
target: 'Circle tool',
|
||||
guard: 'next is circle',
|
||||
},
|
||||
{
|
||||
target: 'Center Rectangle tool',
|
||||
guard: 'next is center rectangle',
|
||||
},
|
||||
],
|
||||
|
||||
entry: 'assign tool in context',
|
||||
|
3
src/wasm-lib/Cargo.lock
generated
@ -1589,6 +1589,8 @@ dependencies = [
|
||||
"console",
|
||||
"lazy_static",
|
||||
"linked-hash-map",
|
||||
"pest",
|
||||
"pest_derive",
|
||||
"regex",
|
||||
"serde",
|
||||
"similar",
|
||||
@ -1689,6 +1691,7 @@ dependencies = [
|
||||
"databake",
|
||||
"derive-docs",
|
||||
"expectorate",
|
||||
"fnv",
|
||||
"form_urlencoded",
|
||||
"futures",
|
||||
"git_rev",
|
||||
|
@ -9,21 +9,16 @@ new-test name:
|
||||
lint:
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
|
||||
# Generate the stdlib image artifacts
|
||||
# Then run the stdlib docs generation
|
||||
redo-kcl-stdlib-docs:
|
||||
TWENTY_TWENTY=overwrite {{cnr}} -p kcl-lib kcl_test_example
|
||||
EXPECTORATE=overwrite {{cnr}} -p kcl-lib docs::gen_std_tests::test_generate_stdlib
|
||||
|
||||
# Create a new KCL deterministic simulation test case.
|
||||
new-sim-test test_name kcl_program render_to_png="true":
|
||||
# Each test file gets its own directory. This will contain the KCL program, and its
|
||||
# snapshotted artifacts (e.g. serialized tokens, serialized ASTs, program memory,
|
||||
# PNG snapshots, etc).
|
||||
mkdir kcl/tests/{{test_name}}
|
||||
echo "{{kcl_program}}" > kcl/tests/{{test_name}}/input.kcl
|
||||
# Add the various tests for this new test case.
|
||||
cat kcl/tests/simtest.tmpl | sed "s/TEST_NAME_HERE/{{test_name}}/" | sed "s/RENDER_TO_PNG/{{render_to_png}}/" >> kcl/src/simulation_tests.rs
|
||||
# Run all the tests for the first time, in the right order.
|
||||
new-sim-test test_name render_to_png="true":
|
||||
{{cita}} -p kcl-lib -- tests::{{test_name}}::tokenize
|
||||
{{cita}} -p kcl-lib -- tests::{{test_name}}::parse
|
||||
{{cita}} -p kcl-lib -- tests::{{test_name}}::unparse
|
||||
TWENTY_TWENTY=overwrite {{cita}} -p kcl-lib -- tests::{{test_name}}::kcl_test_execute
|
||||
|
||||
|
||||
|
@ -21,6 +21,7 @@ convert_case = "0.6.0"
|
||||
dashmap = "6.1.0"
|
||||
databake = { version = "0.1.8", features = ["derive"] }
|
||||
derive-docs = { version = "0.1.29", path = "../derive-docs" }
|
||||
fnv = "1.0.7"
|
||||
form_urlencoded = "1.2.1"
|
||||
futures = { version = "0.3.31" }
|
||||
git_rev = "0.1.0"
|
||||
@ -86,7 +87,7 @@ expectorate = "1.1.0"
|
||||
handlebars = "6.2.0"
|
||||
iai = "0.1"
|
||||
image = { version = "0.25.5", default-features = false, features = ["png"] }
|
||||
insta = { version = "1.41.1", features = ["json", "filters"] }
|
||||
insta = { version = "1.41.1", features = ["json", "filters", "redactions"] }
|
||||
itertools = "0.13.0"
|
||||
pretty_assertions = "1.4.1"
|
||||
tokio = { version = "1.40.0", features = ["rt-multi-thread", "macros", "time"] }
|
||||
|
@ -39,5 +39,5 @@ const KITT_PROGRAM: &str = include_str!("../../tests/executor/inputs/kittycad_sv
|
||||
const PIPES_PROGRAM: &str = include_str!("../../tests/executor/inputs/pipes_on_pipes.kcl");
|
||||
const CUBE_PROGRAM: &str = include_str!("../../tests/executor/inputs/cube.kcl");
|
||||
const MATH_PROGRAM: &str = include_str!("../../tests/executor/inputs/math.kcl");
|
||||
const MIKE_STRESS_TEST_PROGRAM: &str = include_str!("../../tests/executor/inputs/mike_stress_test.kcl");
|
||||
const MIKE_STRESS_TEST_PROGRAM: &str = include_str!("../tests/mike_stress_test/input.kcl");
|
||||
const LSYSTEM_KOCH_SNOWFLAKE_PROGRAM: &str = include_str!("../../tests/executor/inputs/lsystem.kcl");
|
||||
|
@ -28,5 +28,5 @@ const KITT_PROGRAM: &str = include_str!("../../tests/executor/inputs/kittycad_sv
|
||||
const PIPES_PROGRAM: &str = include_str!("../../tests/executor/inputs/pipes_on_pipes.kcl");
|
||||
const CUBE_PROGRAM: &str = include_str!("../../tests/executor/inputs/cube.kcl");
|
||||
const MATH_PROGRAM: &str = include_str!("../../tests/executor/inputs/math.kcl");
|
||||
const MIKE_STRESS_TEST_PROGRAM: &str = include_str!("../../tests/executor/inputs/mike_stress_test.kcl");
|
||||
const MIKE_STRESS_TEST_PROGRAM: &str = include_str!("../tests/mike_stress_test/input.kcl");
|
||||
const LSYSTEM_PROGRAM: &str = include_str!("../../tests/executor/inputs/lsystem.kcl");
|
||||
|
@ -62,6 +62,6 @@ const KITT_PROGRAM: &str = include_str!("../../tests/executor/inputs/kittycad_sv
|
||||
const PIPES_PROGRAM: &str = include_str!("../../tests/executor/inputs/pipes_on_pipes.kcl");
|
||||
const CUBE_PROGRAM: &str = include_str!("../../tests/executor/inputs/cube.kcl");
|
||||
const MATH_PROGRAM: &str = include_str!("../../tests/executor/inputs/math.kcl");
|
||||
const MIKE_STRESS_TEST_PROGRAM: &str = include_str!("../../tests/executor/inputs/mike_stress_test.kcl");
|
||||
const MIKE_STRESS_TEST_PROGRAM: &str = include_str!("../tests/mike_stress_test/input.kcl");
|
||||
const GLOBAL_TAGS_FILE: &str = include_str!("../../tests/executor/inputs/global-tags.kcl");
|
||||
const LSYSTEM_PROGRAM: &str = include_str!("../../tests/executor/inputs/lsystem.kcl");
|
||||
|
20
src/wasm-lib/kcl/common.kcl
Normal file
@ -0,0 +1,20 @@
|
||||
// This file is used by the import docs.
|
||||
|
||||
export fn width = () => {
|
||||
return 10
|
||||
}
|
||||
|
||||
export fn height = () => {
|
||||
return 10
|
||||
}
|
||||
|
||||
export fn buildSketch = (plane, offset) => {
|
||||
w = width()
|
||||
h = height()
|
||||
return startSketchOn(plane)
|
||||
|> startProfileAt(offset, %)
|
||||
|> line([w, 0], %)
|
||||
|> line([0, h], %)
|
||||
|> line([-w, 0], %)
|
||||
|> close(%)
|
||||
}
|
@ -27,7 +27,7 @@ pub use crate::ast::types::{
|
||||
use crate::{
|
||||
docs::StdLibFn,
|
||||
errors::KclError,
|
||||
executor::{ExecState, ExecutorContext, KclValue, Metadata, SourceRange, TagIdentifier, UserVal},
|
||||
executor::{ExecState, ExecutorContext, KclValue, Metadata, SourceRange, TagIdentifier},
|
||||
parser::PIPE_OPERATOR,
|
||||
std::kcl_stdlib::KclStdLibFn,
|
||||
};
|
||||
@ -59,6 +59,14 @@ pub struct Node<T> {
|
||||
pub module_id: ModuleId,
|
||||
}
|
||||
|
||||
impl<T> Node<T> {
|
||||
pub fn metadata(&self) -> Metadata {
|
||||
Metadata {
|
||||
source_range: SourceRange([self.start, self.end, self.module_id.0 as usize]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: JsonSchema> schemars::JsonSchema for Node<T> {
|
||||
fn schema_name() -> String {
|
||||
T::schema_name()
|
||||
@ -1708,34 +1716,26 @@ impl Literal {
|
||||
|
||||
impl From<Node<Literal>> for KclValue {
|
||||
fn from(literal: Node<Literal>) -> Self {
|
||||
KclValue::UserVal(UserVal {
|
||||
value: JValue::from(literal.value.clone()),
|
||||
meta: vec![Metadata {
|
||||
source_range: literal.into(),
|
||||
}],
|
||||
})
|
||||
let meta = vec![literal.metadata()];
|
||||
match literal.inner.value {
|
||||
LiteralValue::IInteger(value) => KclValue::Int { value, meta },
|
||||
LiteralValue::Fractional(value) => KclValue::Number { value, meta },
|
||||
LiteralValue::String(value) => KclValue::String { value, meta },
|
||||
LiteralValue::Bool(value) => KclValue::Bool { value, meta },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Node<Literal>> for KclValue {
|
||||
fn from(literal: &Node<Literal>) -> Self {
|
||||
KclValue::UserVal(UserVal {
|
||||
value: JValue::from(literal.value.clone()),
|
||||
meta: vec![Metadata {
|
||||
source_range: literal.into(),
|
||||
}],
|
||||
})
|
||||
Self::from(literal.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&BoxNode<Literal>> for KclValue {
|
||||
fn from(literal: &BoxNode<Literal>) -> Self {
|
||||
KclValue::UserVal(UserVal {
|
||||
value: JValue::from(literal.value.clone()),
|
||||
meta: vec![Metadata {
|
||||
source_range: literal.into(),
|
||||
}],
|
||||
})
|
||||
let b: &Node<Literal> = literal;
|
||||
Self::from(b)
|
||||
}
|
||||
}
|
||||
|
||||
@ -3010,17 +3010,6 @@ impl ConstraintLevels {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn human_friendly_type(j: &JValue) -> &'static str {
|
||||
match j {
|
||||
JValue::Null => "null",
|
||||
JValue::Bool(_) => "boolean (true/false value)",
|
||||
JValue::Number(_) => "number",
|
||||
JValue::String(_) => "string (text)",
|
||||
JValue::Array(_) => "array (list)",
|
||||
JValue::Object(_) => "object",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
@ -1,18 +1,21 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use super::{
|
||||
human_friendly_type, ArrayExpression, ArrayRangeExpression, BinaryExpression, BinaryOperator, BinaryPart,
|
||||
CallExpression, Expr, IfExpression, LiteralIdentifier, LiteralValue, MemberExpression, MemberObject, Node,
|
||||
ObjectExpression, TagDeclarator, UnaryExpression, UnaryOperator,
|
||||
ArrayExpression, ArrayRangeExpression, BinaryExpression, BinaryOperator, BinaryPart, CallExpression, Expr,
|
||||
IfExpression, KclNone, LiteralIdentifier, LiteralValue, MemberExpression, MemberObject, Node, ObjectExpression,
|
||||
TagDeclarator, UnaryExpression, UnaryOperator,
|
||||
};
|
||||
use crate::{
|
||||
errors::{KclError, KclErrorDetails},
|
||||
executor::{
|
||||
BodyType, ExecState, ExecutorContext, KclValue, Metadata, Sketch, SourceRange, StatementKind, TagEngineInfo,
|
||||
TagIdentifier, UserVal,
|
||||
BodyType, ExecState, ExecutorContext, KclValue, Metadata, SourceRange, StatementKind, TagEngineInfo,
|
||||
TagIdentifier,
|
||||
},
|
||||
std::FunctionKind,
|
||||
};
|
||||
use async_recursion::async_recursion;
|
||||
use serde_json::Value as JValue;
|
||||
|
||||
const FLOAT_TO_INT_MAX_DELTA: f64 = 0.01;
|
||||
|
||||
impl BinaryPart {
|
||||
#[async_recursion]
|
||||
@ -42,26 +45,19 @@ impl Node<MemberExpression> {
|
||||
}
|
||||
};
|
||||
|
||||
let array_json = array.get_json_value()?;
|
||||
|
||||
if let serde_json::Value::Array(array) = array_json {
|
||||
if let Some(value) = array.get(index) {
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: value.clone(),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
} else {
|
||||
Err(KclError::UndefinedValue(KclErrorDetails {
|
||||
message: format!("index {} not found in array", index),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}))
|
||||
}
|
||||
} else {
|
||||
Err(KclError::Semantic(KclErrorDetails {
|
||||
let KclValue::Array { value: array, meta: _ } = array else {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!("MemberExpression array is not an array: {:?}", array),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}));
|
||||
};
|
||||
|
||||
if let Some(value) = array.get(index) {
|
||||
Ok(value.to_owned())
|
||||
} else {
|
||||
Err(KclError::UndefinedValue(KclErrorDetails {
|
||||
message: format!("index {} not found in array", index),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}))
|
||||
}
|
||||
}
|
||||
@ -77,18 +73,11 @@ impl Node<MemberExpression> {
|
||||
}
|
||||
};
|
||||
|
||||
let object_json = object.get_json_value()?;
|
||||
|
||||
// Check the property and object match -- e.g. ints for arrays, strs for objects.
|
||||
match (object_json, property) {
|
||||
(JValue::Object(map), Property::String(property)) => {
|
||||
match (object, property) {
|
||||
(KclValue::Object { value: map, meta: _ }, Property::String(property)) => {
|
||||
if let Some(value) = map.get(&property) {
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: value.clone(),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
Ok(value.to_owned())
|
||||
} else {
|
||||
Err(KclError::UndefinedValue(KclErrorDetails {
|
||||
message: format!("Property '{property}' not found in object"),
|
||||
@ -96,22 +85,20 @@ impl Node<MemberExpression> {
|
||||
}))
|
||||
}
|
||||
}
|
||||
(JValue::Object(_), p) => Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"Only strings can be used as the property of an object, but you're using a {}",
|
||||
p.type_name()
|
||||
),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
})),
|
||||
(JValue::Array(arr), Property::Number(index)) => {
|
||||
let value_of_arr: Option<&JValue> = arr.get(index);
|
||||
(KclValue::Object { .. }, p) => {
|
||||
let t = p.type_name();
|
||||
let article = article_for(t);
|
||||
Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"Only strings can be used as the property of an object, but you're using {article} {t}",
|
||||
),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}))
|
||||
}
|
||||
(KclValue::Array { value: arr, meta: _ }, Property::Number(index)) => {
|
||||
let value_of_arr = arr.get(index);
|
||||
if let Some(value) = value_of_arr {
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: value.clone(),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
Ok(value.to_owned())
|
||||
} else {
|
||||
Err(KclError::UndefinedValue(KclErrorDetails {
|
||||
message: format!("The array doesn't have any item at index {index}"),
|
||||
@ -119,17 +106,36 @@ impl Node<MemberExpression> {
|
||||
}))
|
||||
}
|
||||
}
|
||||
(JValue::Array(_), p) => Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"Only integers >= 0 can be used as the index of an array, but you're using a {}",
|
||||
p.type_name()
|
||||
),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
})),
|
||||
(being_indexed, _) => {
|
||||
let t = human_friendly_type(&being_indexed);
|
||||
(KclValue::Array { .. }, p) => {
|
||||
let t = p.type_name();
|
||||
let article = article_for(t);
|
||||
Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!("Only arrays and objects can be indexed, but you're trying to index a {t}"),
|
||||
message: format!(
|
||||
"Only integers >= 0 can be used as the index of an array, but you're using {article} {t}",
|
||||
),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}))
|
||||
}
|
||||
(KclValue::Solid(solid), Property::String(prop)) if prop == "sketch" => Ok(KclValue::Sketch {
|
||||
value: Box::new(solid.sketch),
|
||||
}),
|
||||
(KclValue::Sketch { value: sk }, Property::String(prop)) if prop == "tags" => Ok(KclValue::Object {
|
||||
meta: vec![Metadata {
|
||||
source_range: SourceRange::from(self.clone()),
|
||||
}],
|
||||
value: sk
|
||||
.tags
|
||||
.iter()
|
||||
.map(|(k, tag)| (k.to_owned(), KclValue::TagIdentifier(Box::new(tag.to_owned()))))
|
||||
.collect(),
|
||||
}),
|
||||
(being_indexed, _) => {
|
||||
let t = being_indexed.human_friendly_type();
|
||||
let article = article_for(t);
|
||||
Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"Only arrays and objects can be indexed, but you're trying to index {article} {t}"
|
||||
),
|
||||
source_ranges: vec![self.clone().into()],
|
||||
}))
|
||||
}
|
||||
@ -140,81 +146,134 @@ impl Node<MemberExpression> {
|
||||
impl Node<BinaryExpression> {
|
||||
#[async_recursion]
|
||||
pub async fn get_result(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
|
||||
let left_json_value = self.left.get_result(exec_state, ctx).await?.get_json_value()?;
|
||||
let right_json_value = self.right.get_result(exec_state, ctx).await?.get_json_value()?;
|
||||
let left_value = self.left.get_result(exec_state, ctx).await?;
|
||||
let right_value = self.right.get_result(exec_state, ctx).await?;
|
||||
let mut meta = left_value.metadata();
|
||||
meta.extend(right_value.metadata());
|
||||
|
||||
// First check if we are doing string concatenation.
|
||||
if self.operator == BinaryOperator::Add {
|
||||
if let (Some(left), Some(right)) = (
|
||||
parse_json_value_as_string(&left_json_value),
|
||||
parse_json_value_as_string(&right_json_value),
|
||||
) {
|
||||
let value = serde_json::Value::String(format!("{}{}", left, right));
|
||||
return Ok(KclValue::UserVal(UserVal {
|
||||
value,
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}));
|
||||
if let (KclValue::String { value: left, meta: _ }, KclValue::String { value: right, meta: _ }) =
|
||||
(&left_value, &right_value)
|
||||
{
|
||||
return Ok(KclValue::String {
|
||||
value: format!("{}{}", left, right),
|
||||
meta,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let left = parse_json_number_as_f64(&left_json_value, self.left.clone().into())?;
|
||||
let right = parse_json_number_as_f64(&right_json_value, self.right.clone().into())?;
|
||||
let left = parse_number_as_f64(&left_value, self.left.clone().into())?;
|
||||
let right = parse_number_as_f64(&right_value, self.right.clone().into())?;
|
||||
|
||||
let value: serde_json::Value = match self.operator {
|
||||
BinaryOperator::Add => (left + right).into(),
|
||||
BinaryOperator::Sub => (left - right).into(),
|
||||
BinaryOperator::Mul => (left * right).into(),
|
||||
BinaryOperator::Div => (left / right).into(),
|
||||
BinaryOperator::Mod => (left % right).into(),
|
||||
BinaryOperator::Pow => (left.powf(right)).into(),
|
||||
BinaryOperator::Eq => (left == right).into(),
|
||||
BinaryOperator::Neq => (left != right).into(),
|
||||
BinaryOperator::Gt => (left > right).into(),
|
||||
BinaryOperator::Gte => (left >= right).into(),
|
||||
BinaryOperator::Lt => (left < right).into(),
|
||||
BinaryOperator::Lte => (left <= right).into(),
|
||||
let value = match self.operator {
|
||||
BinaryOperator::Add => KclValue::Number {
|
||||
value: left + right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Sub => KclValue::Number {
|
||||
value: left - right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Mul => KclValue::Number {
|
||||
value: left * right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Div => KclValue::Number {
|
||||
value: left / right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Mod => KclValue::Number {
|
||||
value: left % right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Pow => KclValue::Number {
|
||||
value: left.powf(right),
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Neq => KclValue::Bool {
|
||||
value: left != right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Gt => KclValue::Bool {
|
||||
value: left > right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Gte => KclValue::Bool {
|
||||
value: left >= right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Lt => KclValue::Bool {
|
||||
value: left < right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Lte => KclValue::Bool {
|
||||
value: left <= right,
|
||||
meta,
|
||||
},
|
||||
BinaryOperator::Eq => KclValue::Bool {
|
||||
value: left == right,
|
||||
meta,
|
||||
},
|
||||
};
|
||||
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value,
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
Ok(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl Node<UnaryExpression> {
|
||||
pub async fn get_result(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
|
||||
if self.operator == UnaryOperator::Not {
|
||||
let value = self.argument.get_result(exec_state, ctx).await?.get_json_value()?;
|
||||
let Some(bool_value) = json_as_bool(&value) else {
|
||||
let value = self.argument.get_result(exec_state, ctx).await?;
|
||||
let KclValue::Bool {
|
||||
value: bool_value,
|
||||
meta: _,
|
||||
} = value
|
||||
else {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!("Cannot apply unary operator ! to non-boolean value: {}", value),
|
||||
message: format!(
|
||||
"Cannot apply unary operator ! to non-boolean value: {}",
|
||||
value.human_friendly_type()
|
||||
),
|
||||
source_ranges: vec![self.into()],
|
||||
}));
|
||||
};
|
||||
let negated = !bool_value;
|
||||
return Ok(KclValue::UserVal(UserVal {
|
||||
value: serde_json::Value::Bool(negated),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}));
|
||||
let meta = vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}];
|
||||
let negated = KclValue::Bool {
|
||||
value: !bool_value,
|
||||
meta,
|
||||
};
|
||||
|
||||
return Ok(negated);
|
||||
}
|
||||
|
||||
let num = parse_json_number_as_f64(
|
||||
&self.argument.get_result(exec_state, ctx).await?.get_json_value()?,
|
||||
self.into(),
|
||||
)?;
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: (-(num)).into(),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
let value = &self.argument.get_result(exec_state, ctx).await?;
|
||||
match value {
|
||||
KclValue::Number { value, meta: _ } => {
|
||||
let meta = vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}];
|
||||
Ok(KclValue::Number { value: -value, meta })
|
||||
}
|
||||
KclValue::Int { value, meta: _ } => {
|
||||
let meta = vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}];
|
||||
Ok(KclValue::Number {
|
||||
value: (-value) as f64,
|
||||
meta,
|
||||
})
|
||||
}
|
||||
_ => Err(KclError::Semantic(KclErrorDetails {
|
||||
message: format!(
|
||||
"You can only negate numbers, but this is a {}",
|
||||
value.human_friendly_type()
|
||||
),
|
||||
source_ranges: vec![self.into()],
|
||||
})),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -325,13 +384,10 @@ impl Node<CallExpression> {
|
||||
// TODO: This could probably be done in a better way, but as of now this was my only idea
|
||||
// and it works.
|
||||
match result {
|
||||
KclValue::UserVal(ref mut uval) => {
|
||||
uval.mutate(|sketch: &mut Sketch| {
|
||||
for (_, tag) in sketch.tags.iter() {
|
||||
exec_state.memory.update_tag(&tag.value, tag.clone())?;
|
||||
}
|
||||
Ok::<_, KclError>(())
|
||||
})?;
|
||||
KclValue::Sketch { value: ref mut sketch } => {
|
||||
for (_, tag) in sketch.tags.iter() {
|
||||
exec_state.memory.update_tag(&tag.value, tag.clone())?;
|
||||
}
|
||||
}
|
||||
KclValue::Solid(ref mut solid) => {
|
||||
for value in &solid.value {
|
||||
@ -425,10 +481,10 @@ impl Node<CallExpression> {
|
||||
} else {
|
||||
fn_memory.add(
|
||||
¶m.identifier.name,
|
||||
KclValue::UserVal(UserVal {
|
||||
value: serde_json::value::Value::Null,
|
||||
meta: Default::default(),
|
||||
}),
|
||||
KclValue::KclNone {
|
||||
value: KclNone::new(),
|
||||
meta: vec![self.into()],
|
||||
},
|
||||
param.identifier.clone().into(),
|
||||
)?;
|
||||
}
|
||||
@ -531,15 +587,13 @@ impl Node<ArrayExpression> {
|
||||
.execute_expr(element, exec_state, &metadata, StatementKind::Expression)
|
||||
.await?;
|
||||
|
||||
results.push(value.get_json_value()?);
|
||||
results.push(value);
|
||||
}
|
||||
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: results.into(),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
Ok(KclValue::Array {
|
||||
value: results,
|
||||
meta: vec![self.into()],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@ -549,15 +603,19 @@ impl Node<ArrayRangeExpression> {
|
||||
let metadata = Metadata::from(&self.start_element);
|
||||
let start = ctx
|
||||
.execute_expr(&self.start_element, exec_state, &metadata, StatementKind::Expression)
|
||||
.await?
|
||||
.get_json_value()?;
|
||||
let start = parse_json_number_as_i64(&start, (&self.start_element).into())?;
|
||||
.await?;
|
||||
let start = start.as_int().ok_or(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: vec![self.into()],
|
||||
message: format!("Expected int but found {}", start.human_friendly_type()),
|
||||
}))?;
|
||||
let metadata = Metadata::from(&self.end_element);
|
||||
let end = ctx
|
||||
.execute_expr(&self.end_element, exec_state, &metadata, StatementKind::Expression)
|
||||
.await?
|
||||
.get_json_value()?;
|
||||
let end = parse_json_number_as_i64(&end, (&self.end_element).into())?;
|
||||
.await?;
|
||||
let end = end.as_int().ok_or(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: vec![self.into()],
|
||||
message: format!("Expected int but found {}", end.human_friendly_type()),
|
||||
}))?;
|
||||
|
||||
if end < start {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
@ -567,94 +625,76 @@ impl Node<ArrayRangeExpression> {
|
||||
}
|
||||
|
||||
let range: Vec<_> = if self.end_inclusive {
|
||||
(start..=end).map(JValue::from).collect()
|
||||
(start..=end).collect()
|
||||
} else {
|
||||
(start..end).map(JValue::from).collect()
|
||||
(start..end).collect()
|
||||
};
|
||||
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: range.into(),
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
let meta = vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}];
|
||||
Ok(KclValue::Array {
|
||||
value: range
|
||||
.into_iter()
|
||||
.map(|num| KclValue::Int {
|
||||
value: num,
|
||||
meta: meta.clone(),
|
||||
})
|
||||
.collect(),
|
||||
meta,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Node<ObjectExpression> {
|
||||
#[async_recursion]
|
||||
pub async fn execute(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
|
||||
let mut object = serde_json::Map::new();
|
||||
let mut object = HashMap::with_capacity(self.properties.len());
|
||||
for property in &self.properties {
|
||||
let metadata = Metadata::from(&property.value);
|
||||
let result = ctx
|
||||
.execute_expr(&property.value, exec_state, &metadata, StatementKind::Expression)
|
||||
.await?;
|
||||
|
||||
object.insert(property.key.name.clone(), result.get_json_value()?);
|
||||
object.insert(property.key.name.clone(), result);
|
||||
}
|
||||
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: object.into(),
|
||||
Ok(KclValue::Object {
|
||||
value: object,
|
||||
meta: vec![Metadata {
|
||||
source_range: self.into(),
|
||||
}],
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_json_number_as_i64(j: &serde_json::Value, source_range: SourceRange) -> Result<i64, KclError> {
|
||||
if let serde_json::Value::Number(n) = &j {
|
||||
n.as_i64().ok_or_else(|| {
|
||||
KclError::Syntax(KclErrorDetails {
|
||||
source_ranges: vec![source_range],
|
||||
message: format!("Invalid integer: {}", j),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn article_for(s: &str) -> &'static str {
|
||||
if s.starts_with(['a', 'e', 'i', 'o', 'u']) {
|
||||
"an"
|
||||
} else {
|
||||
Err(KclError::Syntax(KclErrorDetails {
|
||||
"a"
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_number_as_f64(v: &KclValue, source_range: SourceRange) -> Result<f64, KclError> {
|
||||
if let KclValue::Number { value: n, .. } = &v {
|
||||
Ok(*n)
|
||||
} else if let KclValue::Int { value: n, .. } = &v {
|
||||
Ok(*n as f64)
|
||||
} else {
|
||||
let actual_type = v.human_friendly_type();
|
||||
let article = if actual_type.starts_with(['a', 'e', 'i', 'o', 'u']) {
|
||||
"an"
|
||||
} else {
|
||||
"a"
|
||||
};
|
||||
Err(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: vec![source_range],
|
||||
message: format!("Invalid integer: {}", j),
|
||||
message: format!("Expected a number, but found {article} {actual_type}",),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_json_number_as_f64(j: &serde_json::Value, source_range: SourceRange) -> Result<f64, KclError> {
|
||||
if let serde_json::Value::Number(n) = &j {
|
||||
n.as_f64().ok_or_else(|| {
|
||||
KclError::Syntax(KclErrorDetails {
|
||||
source_ranges: vec![source_range],
|
||||
message: format!("Invalid number: {}", j),
|
||||
})
|
||||
})
|
||||
} else {
|
||||
Err(KclError::Syntax(KclErrorDetails {
|
||||
source_ranges: vec![source_range],
|
||||
message: format!("Invalid number: {}", j),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_json_value_as_string(j: &serde_json::Value) -> Option<String> {
|
||||
if let serde_json::Value::String(n) = &j {
|
||||
Some(n.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON value as bool. If it isn't a bool, returns None.
|
||||
pub fn json_as_bool(j: &serde_json::Value) -> Option<bool> {
|
||||
match j {
|
||||
JValue::Null => None,
|
||||
JValue::Bool(b) => Some(*b),
|
||||
JValue::Number(_) => None,
|
||||
JValue::String(_) => None,
|
||||
JValue::Array(_) => None,
|
||||
JValue::Object(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Node<IfExpression> {
|
||||
#[async_recursion]
|
||||
pub async fn get_result(&self, exec_state: &mut ExecState, ctx: &ExecutorContext) -> Result<KclValue, KclError> {
|
||||
@ -724,15 +764,7 @@ impl Property {
|
||||
} else {
|
||||
// Actually evaluate memory to compute the property.
|
||||
let prop = exec_state.memory.get(name, property_src)?;
|
||||
let KclValue::UserVal(prop) = prop else {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: property_sr,
|
||||
message: format!(
|
||||
"{name} is not a valid property/index, you can only use a string or int (>= 0) here",
|
||||
),
|
||||
}));
|
||||
};
|
||||
jvalue_to_prop(&prop.value, property_sr, name)
|
||||
jvalue_to_prop(prop, property_sr, name)
|
||||
}
|
||||
}
|
||||
LiteralIdentifier::Literal(literal) => {
|
||||
@ -759,35 +791,37 @@ impl Property {
|
||||
}
|
||||
}
|
||||
|
||||
fn jvalue_to_prop(value: &JValue, property_sr: Vec<SourceRange>, name: &str) -> Result<Property, KclError> {
|
||||
fn jvalue_to_prop(value: &KclValue, property_sr: Vec<SourceRange>, name: &str) -> Result<Property, KclError> {
|
||||
let make_err = |message: String| {
|
||||
Err::<Property, _>(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: property_sr,
|
||||
message,
|
||||
}))
|
||||
};
|
||||
const MUST_BE_POSINT: &str = "indices must be whole positive numbers";
|
||||
const TRY_INT: &str = "try using the int() function to make this a whole number";
|
||||
match value {
|
||||
JValue::Number(ref num) => {
|
||||
let maybe_uint = num.as_u64().and_then(|x| usize::try_from(x).ok());
|
||||
if let Some(uint) = maybe_uint {
|
||||
KclValue::Int { value:num, meta: _ } => {
|
||||
let maybe_int: Result<usize, _> = (*num).try_into();
|
||||
if let Ok(uint) = maybe_int {
|
||||
Ok(Property::Number(uint))
|
||||
} else if let Some(iint) = num.as_i64() {
|
||||
make_err(format!("'{iint}' is not a valid index, {MUST_BE_POSINT}"))
|
||||
} else if let Some(fnum) = num.as_f64() {
|
||||
if fnum < 0.0 {
|
||||
make_err(format!("'{fnum}' is not a valid index, {MUST_BE_POSINT}"))
|
||||
} else if fnum.fract() == 0.0 {
|
||||
make_err(format!("'{fnum:.1}' is stored as a fractional number but indices must be whole numbers, {TRY_INT}"))
|
||||
} else {
|
||||
make_err(format!("'{fnum}' is not a valid index, {MUST_BE_POSINT}, {TRY_INT}"))
|
||||
}
|
||||
} else {
|
||||
make_err(format!("'{num}' is not a valid index, {MUST_BE_POSINT}"))
|
||||
}
|
||||
else {
|
||||
make_err(format!("'{num}' is negative, so you can't index an array with it"))
|
||||
}
|
||||
}
|
||||
JValue::String(ref x) => Ok(Property::String(x.to_owned())),
|
||||
KclValue::Number{value: num, meta:_} => {
|
||||
let num = *num;
|
||||
if num < 0.0 {
|
||||
return make_err(format!("'{num}' is negative, so you can't index an array with it"))
|
||||
}
|
||||
let nearest_int = num.round();
|
||||
let delta = num-nearest_int;
|
||||
if delta < FLOAT_TO_INT_MAX_DELTA {
|
||||
Ok(Property::Number(nearest_int as usize))
|
||||
} else {
|
||||
make_err(format!("'{num}' is not an integer, so you can't index an array with it"))
|
||||
}
|
||||
}
|
||||
KclValue::String{value: x, meta:_} => Ok(Property::String(x.to_owned())),
|
||||
_ => {
|
||||
make_err(format!("{name} is not a valid property/index, you can only use a string to get the property of an object, or an int (>= 0) to get an item in an array"))
|
||||
}
|
||||
|
@ -4,10 +4,7 @@ use databake::*;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
ast::types::ConstraintLevel,
|
||||
executor::{KclValue, UserVal},
|
||||
};
|
||||
use crate::{ast::types::ConstraintLevel, executor::KclValue};
|
||||
|
||||
use super::Node;
|
||||
|
||||
@ -16,7 +13,7 @@ const KCL_NONE_ID: &str = "KCL_NONE_ID";
|
||||
/// KCL value for an optional parameter which was not given an argument.
|
||||
/// (remember, parameters are in the function declaration,
|
||||
/// arguments are in the function call/application).
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Bake, Default)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, JsonSchema, Bake, Default, Copy)]
|
||||
#[databake(path = kcl_lib::ast::types)]
|
||||
#[ts(export)]
|
||||
#[serde(tag = "type")]
|
||||
@ -58,19 +55,12 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&KclNone> for UserVal {
|
||||
fn from(none: &KclNone) -> Self {
|
||||
UserVal {
|
||||
value: serde_json::to_value(none).expect("can always serialize a None"),
|
||||
meta: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&KclNone> for KclValue {
|
||||
fn from(none: &KclNone) -> Self {
|
||||
let val = UserVal::from(none);
|
||||
KclValue::UserVal(val)
|
||||
KclValue::KclNone {
|
||||
value: *none,
|
||||
meta: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -790,6 +790,7 @@ fn test_generate_stdlib_json_schema() {
|
||||
// If this test fails and you've modified the AST or something else which affects the json repr
|
||||
// of stdlib functions, you should rerun the test with `EXPECTORATE=overwrite` to create new
|
||||
// test data, then check `/docs/kcl/std.json` to ensure the changes are expected.
|
||||
// Alternatively, run `just redo-kcl-stdlib-docs` (make sure to have just installed).
|
||||
let stdlib = StdLib::new();
|
||||
let combined = stdlib.combined();
|
||||
|
||||
|
@ -7,6 +7,7 @@ layout: manual
|
||||
## Table of Contents
|
||||
|
||||
* [Types](kcl/types)
|
||||
* [Modules](kcl/modules)
|
||||
* [Known Issues](kcl/KNOWN-ISSUES)
|
||||
{{#each functions}}
|
||||
* [`{{name}}`](kcl/{{name}})
|
||||
|
@ -2,7 +2,7 @@ use std::collections::BTreeMap;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use tower_lsp::{
|
||||
lsp_types::{SemanticTokenModifier, SemanticTokenType},
|
||||
lsp_types::{Diagnostic, SemanticTokenModifier, SemanticTokenType},
|
||||
LanguageServer,
|
||||
};
|
||||
|
||||
@ -2369,7 +2369,14 @@ async fn kcl_test_kcl_lsp_diagnostics_on_execution_error() {
|
||||
|
||||
// Get the diagnostics.
|
||||
let diagnostics = server.diagnostics_map.get("file:///test.kcl");
|
||||
assert!(diagnostics.is_none());
|
||||
if let Some(diagnostics) = diagnostics {
|
||||
let ds: Vec<Diagnostic> = diagnostics.to_owned();
|
||||
eprintln!("Expected no diagnostics, but found some.");
|
||||
for d in ds {
|
||||
eprintln!("{:?}: {}", d.severity, d.message);
|
||||
}
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
@ -2040,11 +2040,39 @@ fn fn_call(i: TokenSlice) -> PResult<Node<CallExpression>> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use itertools::Itertools;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
use crate::ast::types::{BodyItem, Expr, ModuleId, VariableKind};
|
||||
|
||||
fn assert_reserved(word: &str) {
|
||||
// Try to use it as a variable name.
|
||||
let code = format!(r#"{} = 0"#, word);
|
||||
let result = crate::parser::top_level_parse(code.as_str());
|
||||
let err = result.unwrap_err();
|
||||
// Which token causes the error may change. In "return = 0", for
|
||||
// example, "return" is the problem.
|
||||
assert!(
|
||||
err.message().starts_with("Unexpected token: ")
|
||||
|| err
|
||||
.message()
|
||||
.starts_with("Cannot assign a variable to a reserved keyword: "),
|
||||
"Error message is: {}",
|
||||
err.message(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_words() {
|
||||
// Since these are stored in a set, we sort to make the tests
|
||||
// deterministic.
|
||||
for word in crate::token::RESERVED_WORDS.keys().sorted() {
|
||||
assert_reserved(word);
|
||||
}
|
||||
assert_reserved("import");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_args() {
|
||||
for (i, (test, expected_len)) in [("someVar", 1), ("5, 3", 2), (r#""a""#, 1)].into_iter().enumerate() {
|
||||
|
@ -1,47 +1,25 @@
|
||||
use derive_docs::stdlib;
|
||||
use serde_json::Value as JValue;
|
||||
|
||||
use super::{args::FromArgs, Args, FnAsArg};
|
||||
use crate::{
|
||||
errors::{KclError, KclErrorDetails},
|
||||
executor::{ExecState, KclValue, SourceRange, UserVal},
|
||||
executor::{ExecState, KclValue, SourceRange},
|
||||
function_param::FunctionParam,
|
||||
};
|
||||
|
||||
/// Apply a function to each element of an array.
|
||||
pub async fn map(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (array, f): (Vec<JValue>, FnAsArg<'_>) = FromArgs::from_args(&args, 0)?;
|
||||
let array: Vec<KclValue> = array
|
||||
.into_iter()
|
||||
.map(|jval| {
|
||||
KclValue::UserVal(UserVal {
|
||||
value: jval,
|
||||
meta: vec![args.source_range.into()],
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (array, f): (Vec<KclValue>, FnAsArg<'_>) = FromArgs::from_args(&args, 0)?;
|
||||
let meta = vec![args.source_range.into()];
|
||||
let map_fn = FunctionParam {
|
||||
inner: f.func,
|
||||
fn_expr: f.expr,
|
||||
meta: vec![args.source_range.into()],
|
||||
meta: meta.clone(),
|
||||
ctx: args.ctx.clone(),
|
||||
memory: *f.memory,
|
||||
};
|
||||
let new_array = inner_map(array, map_fn, exec_state, &args).await?;
|
||||
let unwrapped = new_array
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|k| match k {
|
||||
KclValue::UserVal(user_val) => Ok(user_val.value),
|
||||
_ => Err(()),
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>();
|
||||
if let Ok(unwrapped) = unwrapped {
|
||||
let uv = UserVal::new(vec![args.source_range.into()], unwrapped);
|
||||
return Ok(KclValue::UserVal(uv));
|
||||
}
|
||||
let uv = UserVal::new(vec![args.source_range.into()], new_array);
|
||||
Ok(KclValue::UserVal(uv))
|
||||
Ok(KclValue::Array { value: new_array, meta })
|
||||
}
|
||||
|
||||
/// Apply a function to every element of a list.
|
||||
@ -110,16 +88,7 @@ async fn call_map_closure<'a>(
|
||||
|
||||
/// For each item in an array, update a value.
|
||||
pub async fn reduce(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (array, start, f): (Vec<JValue>, KclValue, FnAsArg<'_>) = FromArgs::from_args(&args, 0)?;
|
||||
let array: Vec<KclValue> = array
|
||||
.into_iter()
|
||||
.map(|jval| {
|
||||
KclValue::UserVal(UserVal {
|
||||
value: jval,
|
||||
meta: vec![args.source_range.into()],
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let (array, start, f): (Vec<KclValue>, KclValue, FnAsArg<'_>) = FromArgs::from_args(&args, 0)?;
|
||||
let reduce_fn = FunctionParam {
|
||||
inner: f.func,
|
||||
fn_expr: f.expr,
|
||||
@ -133,26 +102,79 @@ pub async fn reduce(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
|
||||
/// Take a starting value. Then, for each element of an array, calculate the next value,
|
||||
/// using the previous value and the element.
|
||||
/// ```no_run
|
||||
/// fn decagon = (radius) => {
|
||||
/// let step = (1/10) * tau()
|
||||
/// let sketch001 = startSketchAt([(cos(0)*radius), (sin(0) * radius)])
|
||||
/// return reduce([1..10], sketch001, (i, sg) => {
|
||||
/// let x = cos(step * i) * radius
|
||||
/// let y = sin(step * i) * radius
|
||||
/// return lineTo([x, y], sg)
|
||||
/// })
|
||||
/// }
|
||||
/// decagon(5.0) |> close(%)
|
||||
/// // This function adds two numbers.
|
||||
/// fn add = (a, b) => { return a + b }
|
||||
///
|
||||
/// // This function adds an array of numbers.
|
||||
/// // It uses the `reduce` function, to call the `add` function on every
|
||||
/// // element of the `arr` parameter. The starting value is 0.
|
||||
/// fn sum = (arr) => { return reduce(arr, 0, add) }
|
||||
///
|
||||
/// /*
|
||||
/// The above is basically like this pseudo-code:
|
||||
/// fn sum(arr):
|
||||
/// let sumSoFar = 0
|
||||
/// for i in arr:
|
||||
/// sumSoFar = add(sumSoFar, i)
|
||||
/// return sumSoFar
|
||||
/// */
|
||||
///
|
||||
/// // We use `assertEqual` to check that our `sum` function gives the
|
||||
/// // expected result. It's good to check your work!
|
||||
/// assertEqual(sum([1, 2, 3]), 6, 0.00001, "1 + 2 + 3 summed is 6")
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// array = [1, 2, 3]
|
||||
/// sum = reduce(array, 0, (i, result_so_far) => { return i + result_so_far })
|
||||
/// // This example works just like the previous example above, but it uses
|
||||
/// // an anonymous `add` function as its parameter, instead of declaring a
|
||||
/// // named function outside.
|
||||
/// arr = [1, 2, 3]
|
||||
/// sum = reduce(arr, 0, (i, result_so_far) => { return i + result_so_far })
|
||||
///
|
||||
/// // We use `assertEqual` to check that our `sum` function gives the
|
||||
/// // expected result. It's good to check your work!
|
||||
/// assertEqual(sum, 6, 0.00001, "1 + 2 + 3 summed is 6")
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// fn add = (a, b) => { return a + b }
|
||||
/// fn sum = (array) => { return reduce(array, 0, add) }
|
||||
/// assertEqual(sum([1, 2, 3]), 6, 0.00001, "1 + 2 + 3 summed is 6")
|
||||
/// // Declare a function that sketches a decagon.
|
||||
/// fn decagon = (radius) => {
|
||||
/// // Each side of the decagon is turned this many degrees from the previous angle.
|
||||
/// stepAngle = (1/10) * tau()
|
||||
///
|
||||
/// // Start the decagon sketch at this point.
|
||||
/// startOfDecagonSketch = startSketchAt([(cos(0)*radius), (sin(0) * radius)])
|
||||
///
|
||||
/// // Use a `reduce` to draw the remaining decagon sides.
|
||||
/// // For each number in the array 1..10, run the given function,
|
||||
/// // which takes a partially-sketched decagon and adds one more edge to it.
|
||||
/// fullDecagon = reduce([1..10], startOfDecagonSketch, (i, partialDecagon) => {
|
||||
/// // Draw one edge of the decagon.
|
||||
/// let x = cos(stepAngle * i) * radius
|
||||
/// let y = sin(stepAngle * i) * radius
|
||||
/// return lineTo([x, y], partialDecagon)
|
||||
/// })
|
||||
///
|
||||
/// return fullDecagon
|
||||
///
|
||||
/// }
|
||||
///
|
||||
/// /*
|
||||
/// The `decagon` above is basically like this pseudo-code:
|
||||
/// fn decagon(radius):
|
||||
/// let stepAngle = (1/10) * tau()
|
||||
/// let startOfDecagonSketch = startSketchAt([(cos(0)*radius), (sin(0) * radius)])
|
||||
///
|
||||
/// // Here's the reduce part.
|
||||
/// let partialDecagon = startOfDecagonSketch
|
||||
/// for i in [1..10]:
|
||||
/// let x = cos(stepAngle * i) * radius
|
||||
/// let y = sin(stepAngle * i) * radius
|
||||
/// partialDecagon = lineTo([x, y], partialDecagon)
|
||||
/// fullDecagon = partialDecagon // it's now full
|
||||
/// return fullDecagon
|
||||
/// */
|
||||
///
|
||||
/// // Use the `decagon` function declared above, to sketch a decagon with radius 5.
|
||||
/// decagon(5.0) |> close(%)
|
||||
/// ```
|
||||
#[stdlib {
|
||||
name = "reduce",
|
||||
@ -206,50 +228,26 @@ async fn call_reduce_closure<'a>(
|
||||
#[stdlib {
|
||||
name = "push",
|
||||
}]
|
||||
async fn inner_push(array: Vec<KclValue>, elem: KclValue, args: &Args) -> Result<KclValue, KclError> {
|
||||
async fn inner_push(mut array: Vec<KclValue>, elem: KclValue, args: &Args) -> Result<KclValue, KclError> {
|
||||
// Unwrap the KclValues to JValues for manipulation
|
||||
let mut unwrapped_array = array
|
||||
.into_iter()
|
||||
.map(|k| match k {
|
||||
KclValue::UserVal(user_val) => Ok(user_val.value),
|
||||
_ => Err(KclError::Semantic(KclErrorDetails {
|
||||
message: "Expected a UserVal in array".to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
})),
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
// Unwrap the element
|
||||
let unwrapped_elem = match elem {
|
||||
KclValue::UserVal(user_val) => user_val.value,
|
||||
_ => {
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
message: "Expected a UserVal as element".to_string(),
|
||||
source_ranges: vec![args.source_range],
|
||||
}));
|
||||
}
|
||||
};
|
||||
|
||||
// Append the element to the array
|
||||
unwrapped_array.push(unwrapped_elem);
|
||||
|
||||
// Wrap the new array into a UserVal with the source range metadata
|
||||
let uv = UserVal::new(vec![args.source_range.into()], unwrapped_array);
|
||||
|
||||
// Return the new array wrapped as a KclValue::UserVal
|
||||
Ok(KclValue::UserVal(uv))
|
||||
array.push(elem);
|
||||
Ok(KclValue::Array {
|
||||
value: array,
|
||||
meta: vec![args.source_range.into()],
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn push(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
// Extract the array and the element from the arguments
|
||||
let (array_jvalues, elem): (Vec<JValue>, KclValue) = FromArgs::from_args(&args, 0)?;
|
||||
let (val, elem): (KclValue, KclValue) = FromArgs::from_args(&args, 0)?;
|
||||
|
||||
// Convert the array of JValue into Vec<KclValue>
|
||||
let array: Vec<KclValue> = array_jvalues
|
||||
.into_iter()
|
||||
.map(|jval| KclValue::UserVal(UserVal::new(vec![args.source_range.into()], jval)))
|
||||
.collect();
|
||||
|
||||
// Call the inner_push function
|
||||
let meta = vec![args.source_range];
|
||||
let KclValue::Array { value: array, meta: _ } = val else {
|
||||
let actual_type = val.human_friendly_type();
|
||||
return Err(KclError::Semantic(KclErrorDetails {
|
||||
source_ranges: meta,
|
||||
message: format!("You can't push to a value of type {actual_type}, only an array"),
|
||||
}));
|
||||
};
|
||||
inner_push(array, elem, &args).await
|
||||
}
|
||||
|
@ -24,7 +24,7 @@ async fn _assert(value: bool, message: &str, args: &Args) -> Result<(), KclError
|
||||
pub async fn assert(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (data, description): (bool, String) = args.get_data()?;
|
||||
inner_assert(data, &description, &args).await?;
|
||||
Ok(args.make_null_user_val())
|
||||
Ok(args.make_user_val_from_f64(0.0)) // TODO: Add a new Void enum for fns that don't return anything.
|
||||
}
|
||||
|
||||
/// Check a value at runtime, and raise an error if the argument provided
|
||||
@ -44,7 +44,7 @@ async fn inner_assert(data: bool, message: &str, args: &Args) -> Result<(), KclE
|
||||
pub async fn assert_lt(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (left, right, description): (f64, f64, String) = args.get_data()?;
|
||||
inner_assert_lt(left, right, &description, &args).await?;
|
||||
Ok(args.make_null_user_val())
|
||||
Ok(args.make_user_val_from_f64(0.0)) // TODO: Add a new Void enum for fns that don't return anything.
|
||||
}
|
||||
|
||||
/// Check that a numerical value is less than to another at runtime,
|
||||
@ -63,7 +63,7 @@ async fn inner_assert_lt(left: f64, right: f64, message: &str, args: &Args) -> R
|
||||
pub async fn assert_gt(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (left, right, description): (f64, f64, String) = args.get_data()?;
|
||||
inner_assert_gt(left, right, &description, &args).await?;
|
||||
Ok(args.make_null_user_val())
|
||||
Ok(args.make_user_val_from_f64(0.0)) // TODO: Add a new Void enum for fns that don't return anything.
|
||||
}
|
||||
|
||||
/// Check that a numerical value equals another at runtime,
|
||||
@ -96,7 +96,7 @@ async fn inner_assert_equal(left: f64, right: f64, epsilon: f64, message: &str,
|
||||
pub async fn assert_equal(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (left, right, epsilon, description): (f64, f64, f64, String) = args.get_data()?;
|
||||
inner_assert_equal(left, right, epsilon, &description, &args).await?;
|
||||
Ok(args.make_null_user_val())
|
||||
Ok(args.make_user_val_from_f64(0.0)) // TODO: Add a new Void enum for fns that don't return anything.
|
||||
}
|
||||
|
||||
/// Check that a numerical value is greater than another at runtime,
|
||||
@ -115,7 +115,7 @@ async fn inner_assert_gt(left: f64, right: f64, message: &str, args: &Args) -> R
|
||||
pub async fn assert_lte(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (left, right, description): (f64, f64, String) = args.get_data()?;
|
||||
inner_assert_lte(left, right, &description, &args).await?;
|
||||
Ok(args.make_null_user_val())
|
||||
Ok(args.make_user_val_from_f64(0.0)) // TODO: Add a new Void enum for fns that don't return anything.
|
||||
}
|
||||
|
||||
/// Check that a numerical value is less than or equal to another at runtime,
|
||||
@ -135,7 +135,7 @@ async fn inner_assert_lte(left: f64, right: f64, message: &str, args: &Args) ->
|
||||
pub async fn assert_gte(_exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
|
||||
let (left, right, description): (f64, f64, String) = args.get_data()?;
|
||||
inner_assert_gte(left, right, &description, &args).await?;
|
||||
Ok(args.make_null_user_val())
|
||||
Ok(args.make_user_val_from_f64(0.0)) // TODO: Add a new Void enum for fns that don't return anything.
|
||||
}
|
||||
|
||||
/// Check that a numerical value is greater than or equal to another at runtime,
|
||||
|
@ -233,7 +233,7 @@ pub(crate) async fn do_post_extrude(
|
||||
tag: path.get_base().tag.clone(),
|
||||
geo_meta: GeoMeta {
|
||||
id: path.get_base().geo_meta.id,
|
||||
metadata: path.get_base().geo_meta.metadata.clone(),
|
||||
metadata: path.get_base().geo_meta.metadata,
|
||||
},
|
||||
});
|
||||
Some(extrude_surface)
|
||||
@ -244,7 +244,7 @@ pub(crate) async fn do_post_extrude(
|
||||
tag: path.get_base().tag.clone(),
|
||||
geo_meta: GeoMeta {
|
||||
id: path.get_base().geo_meta.id,
|
||||
metadata: path.get_base().geo_meta.metadata.clone(),
|
||||
metadata: path.get_base().geo_meta.metadata,
|
||||
},
|
||||
});
|
||||
Some(extrude_surface)
|
||||
@ -259,7 +259,7 @@ pub(crate) async fn do_post_extrude(
|
||||
tag: path.get_base().tag.clone(),
|
||||
geo_meta: GeoMeta {
|
||||
id: path.get_base().geo_meta.id,
|
||||
metadata: path.get_base().geo_meta.metadata.clone(),
|
||||
metadata: path.get_base().geo_meta.metadata,
|
||||
},
|
||||
});
|
||||
Some(extrude_surface)
|
||||
|
@ -14,7 +14,7 @@ use uuid::Uuid;
|
||||
use crate::{
|
||||
ast::types::TagNode,
|
||||
errors::{KclError, KclErrorDetails},
|
||||
executor::{EdgeCut, ExecState, ExtrudeSurface, FilletSurface, GeoMeta, KclValue, Solid, TagIdentifier, UserVal},
|
||||
executor::{EdgeCut, ExecState, ExtrudeSurface, FilletSurface, GeoMeta, KclValue, Solid, TagIdentifier},
|
||||
settings::types::UnitLength,
|
||||
std::Args,
|
||||
};
|
||||
@ -186,15 +186,10 @@ pub async fn get_opposite_edge(exec_state: &mut ExecState, args: Args) -> Result
|
||||
let tag: TagIdentifier = args.get_data()?;
|
||||
|
||||
let edge = inner_get_opposite_edge(tag, exec_state, args.clone()).await?;
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: serde_json::to_value(edge).map_err(|e| {
|
||||
KclError::Type(KclErrorDetails {
|
||||
message: format!("Failed to convert Uuid to json: {}", e),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?,
|
||||
Ok(KclValue::Uuid {
|
||||
value: edge,
|
||||
meta: vec![args.source_range.into()],
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the opposite edge to the edge given.
|
||||
@ -264,15 +259,10 @@ pub async fn get_next_adjacent_edge(exec_state: &mut ExecState, args: Args) -> R
|
||||
let tag: TagIdentifier = args.get_data()?;
|
||||
|
||||
let edge = inner_get_next_adjacent_edge(tag, exec_state, args.clone()).await?;
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: serde_json::to_value(edge).map_err(|e| {
|
||||
KclError::Type(KclErrorDetails {
|
||||
message: format!("Failed to convert Uuid to json: {}", e),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?,
|
||||
Ok(KclValue::Uuid {
|
||||
value: edge,
|
||||
meta: vec![args.source_range.into()],
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the next adjacent edge to the edge given.
|
||||
@ -354,15 +344,10 @@ pub async fn get_previous_adjacent_edge(exec_state: &mut ExecState, args: Args)
|
||||
let tag: TagIdentifier = args.get_data()?;
|
||||
|
||||
let edge = inner_get_previous_adjacent_edge(tag, exec_state, args.clone()).await?;
|
||||
Ok(KclValue::UserVal(UserVal {
|
||||
value: serde_json::to_value(edge).map_err(|e| {
|
||||
KclError::Type(KclErrorDetails {
|
||||
message: format!("Failed to convert Uuid to json: {}", e),
|
||||
source_ranges: vec![args.source_range],
|
||||
})
|
||||
})?,
|
||||
Ok(KclValue::Uuid {
|
||||
value: edge,
|
||||
meta: vec![args.source_range.into()],
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Get the previous adjacent edge to the edge given.
|
||||
|
@ -144,6 +144,9 @@ pub async fn import(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
|
||||
/// 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).
|
||||
///
|
||||
/// ```no_run
|
||||
/// const model = import("tests/inputs/cube.obj")
|
||||
/// ```
|
||||
@ -163,6 +166,15 @@ pub async fn import(exec_state: &mut ExecState, args: Args) -> Result<KclValue,
|
||||
/// ```no_run
|
||||
/// const model = import("tests/inputs/cube.step")
|
||||
/// ```
|
||||
///
|
||||
/// ```no_run
|
||||
/// import height, buildSketch from 'common.kcl'
|
||||
///
|
||||
/// plane = 'XZ'
|
||||
/// margin = 2
|
||||
/// s1 = buildSketch(plane, [0, 0])
|
||||
/// s2 = buildSketch(plane, [0, height() + margin])
|
||||
/// ```
|
||||
#[stdlib {
|
||||
name = "import",
|
||||
tags = [],
|
||||
|