Compare commits

...

49 Commits

Author SHA1 Message Date
3630696848 KCL: Unlabeled first param defaults to % (#4817)
Part of #4600

KCL functions can declare one special argument that doesn't require a label on its parameter when called.

This PR will default that arg to % (the current pipeline) if not given.
2024-12-16 21:01:23 -06:00
f165d19fda Annotations syntax and per-file default units preparatory work (#4822)
* Parse annotations

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* Propagate settings from annotations to exec_state

Signed-off-by: Nick Cameron <nrc@ncameron.org>

---------

Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-17 15:23:00 +13:00
3dd98ae1d5 Implements boolean logical and/or in kcl (#4678)
* redoing bool logic impl on latest main

* adding snapshot tests (removing .new)

* removing accidental change smh:(

* accepting client side scene snapshot

* accepting png snapshot and triggering ci

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* accepting png again?

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores)

* accepting grid visibility snapshot

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores)

* accepting png snapshot

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores)

* accepting png snapshot

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* accepting png snapshot

* rerunning simtest creation to get ops.snap files

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
2024-12-16 17:33:08 -05:00
a46e0a0fe7 Support completions from import statements (#4768)
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-17 10:48:38 +13:00
8f9dc06228 Whole module imports (#4767)
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-16 20:38:32 +00:00
fa22c14723 Reserve syntax for units of measure (#4783)
* Allow underscores but only for un-referenced names

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* Support numeric suffixes for UoM types

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* UoM type arguments

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* warnings -> non-fatal errors

Signed-off-by: Nick Cameron <nrc@ncameron.org>

* type ascription

Signed-off-by: Nick Cameron <nrc@ncameron.org>

---------

Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-17 09:01:51 +13:00
1d39983b08 Change KCL completion to use new object/record syntax (#4815) 2024-12-16 18:29:50 +00:00
da301ba862 Add tracking of operations for the feature tree (#4746)
* Add operations tracking for the timeline

* Change to only track certain stdlib functions as operations

* Update gen files

* Add operations to simulation snapshot tests

* Add tracking of positional function calls

* Fix generated field names to be camel case in TS

* Fix generated TS field names to match and better docs

* Fix order of ops with patternTransform

* Fix sweep to be included

* Add new expected test outputs

* Add tracking for startSketchOn

* Update ops output to include startSketchOn

* Fix serde field name

* Fix output field name

* Add tracking of operations that fail

* Add snapshots of operations even when there's a KCL execution error

* Add ops output for error executions

* Add operations output to executor error

* Update op source ranges

* Remove tracking of circle() and polygon() since they're not needed

* Update output without circle and polygon

* Fix to track patternCircular3d and patternLinear3d

* Remove tracking for mirror2d

* Update ops output

* Fix to track the correct source range of function definitions

---------

Co-authored-by: Frank Noirot <frank@zoo.dev>
2024-12-16 13:10:31 -05:00
efe8089b08 Revert multi-profile (#4812)
* Revert "multi-profile follow up. (#4802)"

This reverts commit 2b2ed470c1.

* Revert "multi profile (#4532)"

This reverts commit 04e586d07b.

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* Re-run CI after snapshots

* Re-run CI after snapshots

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores)

* Re-run CI after snapshots

* Add `fixme` to onboarding test

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-12-16 10:34:11 -05:00
49de3b0ac9 get ready to bump (kcl-lib and friends) world (#4794)
get ready to bump world

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-12-16 18:37:03 +11:00
2b2ed470c1 multi-profile follow up. (#4802)
* multi-profile work

* fix enter sketch on cap

* fix coderef problem for walls and caps

* allow sketch mode entry from circle

* clean up

* update snapshot

* Look at this (photo)Graph *in the voice of Nickelback*

* trigger CI

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* add test

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* fix how expression index is corrected, to make compatible with offset planes

* another test

* tweak test

* more test tweaks

* break up test to fix it hopfully

* fix onboarding test

* remove bad comment

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-12-16 18:36:48 +11:00
96652a0c48 Fix onboarding rendering (#4789)
* fix onboarding rendering

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* empty string

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores)

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* empty

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* empty

* can be off by 20

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* can be off by 20

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-12-14 01:35:34 +00:00
04e586d07b multi profile (#4532)
* multi-profile work

* another test

* clean up

* cover a quirk with a test

* last of tests

* fix typos

* Fix source range in snap test

---------

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
2024-12-13 17:57:33 -05:00
fe5f574a77 Revert "Fix so that tag declarators can be used as parameters (#4692)" (#4788)
This reverts commit e27840219b.
2024-12-13 21:39:40 +00:00
e787495ad0 add a test to make sure we cant shebang in a fn (#4781)
Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-12-13 20:10:33 +00:00
8bb9be7a5e Bump kittycad-modeling-cmds (#4777) 2024-12-13 19:42:41 +00:00
00892464e8 Always run cargo test in CI so that it can be required (#4786) 2024-12-13 14:34:23 -05:00
05ed2a3367 Loft uses kw arguments (#4757)
Part of #4600
2024-12-13 13:07:52 -06:00
10cc5bce59 Fix SourceRange values in OrderedCommands to match the TS type (#4785)
* Fix SourceRange type to match WASM commands

* Update artifact graph test snap

* Update artifact graph test
2024-12-13 19:03:24 +00:00
a32f150fc1 KCL tests: Update engine API snapshot (#4784)
When engine merged their big extrude ID bugfix,
they changed the response for extrudes on face.

Basically there's no longer a start face for
something you extrude from a face, because there
just isn't. There's a hole in a previous face,
it's just a gap.

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
2024-12-13 11:24:29 -06:00
ac60082e67 Fix ids for kurt so front end re-uses same ones on executions (#4780)
* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* working test;

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fix tests

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* Update src/wasm-lib/tests/executor/main.rs

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>

* Update src/wasm-lib/tests/executor/main.rs

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>

* fix race condition

* fix whoopsie

* fix tsc

* for some dumb ass reason the model executes twice on load

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
2024-12-13 02:06:26 +00:00
d44dc1b21a Bump wasm-bindgen from 0.2.91 to 0.2.99 and wasm-bindgen-futures from… (#4732)
* Bump wasm-bindgen from 0.2.91 to 0.2.99 and wasm-bindgen-futures from 0.4.44 to 0.4.49

* Upgrade in the kcl crate also

* Update web-sys version constraint to match lock
2024-12-12 15:37:50 -06:00
813962ea4c Revert "warn on unneccessary brackets (#4769)" (#4776)
This reverts commit 4b6bbbe2c5 (PR #4769) because these tests are failing:

        FAIL [   0.013s] kcl-lib parsing::parser::tests::assign_brackets
        FAIL [   0.012s] kcl-lib parsing::parser::tests::test_arg
2024-12-12 15:37:37 -06:00
738443a6ab add test that ensures we use the cache, from playwright (#4721)
add test that ensures we use the cache;

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-12-12 15:37:23 -06:00
4b6bbbe2c5 warn on unneccessary brackets (#4769)
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-13 08:20:57 +13:00
6ff8addc8b Remove non code from Digests (#4772)
Remove non code from Digests

@jessfraz and I talked it over; for the time being we're going to remove
comments from the AST digest. We already exclude source position, so
this is just increasing the degree to which we're going to ignore things
that are not germane to execution.

Before, we'd digest *some* but not all of the comments in the AST.
Silly, I know, right?

So, this code:

```
firstSketch = startSketchOn('XY')
  |> startProfileAt([-12, 12], %)
  |> line([-24, 0], %) // my thing
  |> close(%)
  |> extrude(6, %)
```

Would digest differently than:

```
firstSketch = startSketchOn('XY')
  |> startProfileAt([-12, 12], %)
  |> line([-24, 0], %)
  |> close(%)
  |> extrude(6, %)
```

Which is wrong. We've fully divested of hashing code comments, so this
will now hash to be the same. Hooray.
2024-12-12 18:55:09 +00:00
da05c38b9e KCL stdlib: Add atan2 function (#4771)
At Lee's request
2024-12-12 18:11:07 +00:00
191b9b71fd KCL: Keyword fn args like "x = 1" not like "x: 1" (#4770)
Aligns with how we're doing objects.
2024-12-12 17:53:35 +00:00
05163fdded Fix KCL warnings in doc comments from let, const, and new fn syntax (#4756)
* Fix KCL warnings in doc comments from let, const, and new fn syntax

* Update docs
2024-12-12 11:33:37 -05:00
7ed26e21c6 More Walk cleanup (#4738)
* More Walk cleanup

 - The `Node` type contained two enums by mistake. Those have been
   removed.

 - Export the `Visitor` and `Visitable` traits, as I start to migrate
   stuff to them.

 - Add a wrapper to pull the `digest` off the node without doing a
   `match` elsewhere.
2024-12-12 01:49:18 +00:00
c668d40efc make pipe have a hole (#4766)
Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-12-12 01:07:14 +00:00
f38c6b90b7 Color picker in the code pane (#4761)
* add color plugin

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fixes

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fmt

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* snapshot test goober

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores)

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-12-12 00:45:39 +00:00
7bc8bae0ec Update Camera Controls to Zoo (#4755)
* update camera controls to Zoo

* update e2e and initial settings

* update types and camera controls ts

* update mod.rs test

* update test, test locally
2024-12-11 15:03:51 -08:00
3804aca27e Bump codecov/codecov-action from 4 to 5 (#4498)
Bumps [codecov/codecov-action](https://github.com/codecov/codecov-action) from 4 to 5.
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codecov/codecov-action/compare/v4...v5)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-11 14:19:43 -08:00
b127680f2f Remove type coercion (#4759)
remove type coercion
2024-12-11 22:04:36 +00:00
b7de8e60cf Sweep in kcl (#4754)
* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores)

* empty

* Update src/wasm-lib/kcl/src/docs/mod.rs

Co-authored-by: Jonathan Tran <jonnytran@gmail.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Jonathan Tran <jonnytran@gmail.com>
2024-12-11 20:59:02 +00:00
058fccb5e1 Add a right-click menu to the stream, but only when not dragging (#4745)
* Refactor ContextMenu to be able to take a guard and other event types

* refactor: break out ViewControlMenu into its own component

* Add ViewControlMenu to Stream, but only on right-click non-drag mouseup

* Fix lints

* Don't use `useCallback` for contextmenu guard

* Update context menu position on subsequent right-clicks
2024-12-11 17:57:38 +00:00
00e97257ae Set disableDifferentialDownload to true for the auto updater (#4742)
Fixes #4120
2024-12-11 09:04:02 -06:00
aeb656d176 Remove flags we had for code sign on Cut Release PRs (#4728) 2024-12-11 09:03:12 -06:00
ac49ebd6e0 Revert "chore: implemented multiple instances instead of multiple appications?" (#4750)
Revert "chore: implemented multiple instances instead of multiple appications…"

This reverts commit 548c664db0.
2024-12-11 08:58:42 -06:00
b40f03ad25 Fix wasm init deprecation warning (#4747)
See `__wbg_init()` in `src/wasm-lib/pkg/wasm_lib.js`.
2024-12-11 04:54:20 -05:00
a8ad86e645 Add some comments to new API in wasm.ts (#4712)
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-11 21:37:03 +13:00
87f50cd5e9 Implement as aliases for sub-expressions (#4723)
Signed-off-by: Nick Cameron <nrc@ncameron.org>
2024-12-11 21:26:42 +13:00
0400e6228e Add a "current" marker to UnitsMenu (#4744) 2024-12-11 06:00:19 +00:00
26f150fd6c Change diagnostic action button to primary color (#4737) 2024-12-11 00:25:43 -05:00
3049f405f5 Reapply "More aggressive using of cache on engine settings changes" (#4736)
* Reapply "More aggressive using of cache on engine settings changes (#4691)" (#4729)

This reverts commit 3f1f40eeba.

* Add a utility to get all the current values from the settings object

* Use an XState selector to get the latest settings snapshot for WASM

---------

Co-authored-by: Frank Noirot <frank@kittycad.io>
2024-12-11 02:50:22 +00:00
53d40301dc start of Appearance function (#4743)
* initial commit

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fix docs

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* add more samples

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updatres

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* regenerate docs

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* patterns and appearance samples

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fmt

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-12-11 01:51:51 +00:00
671c01e36f More consistent GitHub links (#4741)
Fixes #4726
Tested locally with regular and nightly (`yarn files:flip-to-nightly`) configs.
2024-12-10 15:52:57 -06:00
e80151979b Pin electron versions and remove unused packages (#4708)
* Remove forge dependencies for packaging
Fixes #4628

* More clean up and pin current electron versions
2024-12-10 16:37:08 -05:00
306 changed files with 26694 additions and 4360 deletions

View File

@ -165,7 +165,6 @@ jobs:
- name: Build the app (release) - name: Build the app (release)
if: ${{ env.IS_RELEASE == 'true' || env.IS_NIGHTLY == 'true' }} if: ${{ env.IS_RELEASE == 'true' || env.IS_NIGHTLY == 'true' }}
env: env:
PUBLISH_FOR_PULL_REQUEST: true
APPLE_ID: ${{ secrets.APPLE_ID }} APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_PASSWORD }} APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
@ -173,7 +172,6 @@ jobs:
CSC_LINK: ${{ secrets.APPLE_CERTIFICATE }} CSC_LINK: ${{ secrets.APPLE_CERTIFICATE }}
CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
CSC_KEYCHAIN: ${{ secrets.APPLE_SIGNING_IDENTITY }} CSC_KEYCHAIN: ${{ secrets.APPLE_SIGNING_IDENTITY }}
CSC_FOR_PULL_REQUEST: true
WINDOWS_CERTIFICATE_THUMBPRINT: ${{ secrets.WINDOWS_CERTIFICATE_THUMBPRINT }} WINDOWS_CERTIFICATE_THUMBPRINT: ${{ secrets.WINDOWS_CERTIFICATE_THUMBPRINT }}
run: yarn electron-builder --config --publish always run: yarn electron-builder --config --publish always
@ -229,7 +227,6 @@ jobs:
CSC_LINK: ${{ secrets.APPLE_CERTIFICATE }} CSC_LINK: ${{ secrets.APPLE_CERTIFICATE }}
CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} CSC_KEY_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
CSC_KEYCHAIN: ${{ secrets.APPLE_SIGNING_IDENTITY }} CSC_KEYCHAIN: ${{ secrets.APPLE_SIGNING_IDENTITY }}
CSC_FOR_PULL_REQUEST: true
WINDOWS_CERTIFICATE_THUMBPRINT: ${{ secrets.WINDOWS_CERTIFICATE_THUMBPRINT }} WINDOWS_CERTIFICATE_THUMBPRINT: ${{ secrets.WINDOWS_CERTIFICATE_THUMBPRINT }}
run: yarn electron-builder --config --publish always run: yarn electron-builder --config --publish always

View File

@ -2,28 +2,8 @@ on:
push: push:
branches: branches:
- main - main
paths:
- 'src/wasm-lib/**.rs'
- 'src/wasm-lib/**.hbs'
- 'src/wasm-lib/**.gen'
- 'src/wasm-lib/**.snap'
- '**/Cargo.toml'
- '**/Cargo.lock'
- '**/rust-toolchain.toml'
- 'src/wasm-lib/**.kcl'
- .github/workflows/cargo-test.yml
pull_request: pull_request:
paths:
- 'src/wasm-lib/**.rs'
- 'src/wasm-lib/**.hbs'
- 'src/wasm-lib/**.gen'
- 'src/wasm-lib/**.snap'
- '**/Cargo.toml'
- '**/Cargo.lock'
- '**/rust-toolchain.toml'
- 'src/wasm-lib/**.kcl'
- .github/workflows/cargo-test.yml
workflow_dispatch: workflow_dispatch:
permissions: read-all permissions: read-all
concurrency: concurrency:
@ -71,7 +51,7 @@ jobs:
KITTYCAD_API_TOKEN: ${{secrets.KITTYCAD_API_TOKEN}} KITTYCAD_API_TOKEN: ${{secrets.KITTYCAD_API_TOKEN}}
RUST_MIN_STACK: 10485760000 RUST_MIN_STACK: 10485760000
- name: Upload to codecov.io - name: Upload to codecov.io
uses: codecov/codecov-action@v4 uses: codecov/codecov-action@v5
with: with:
token: ${{secrets.CODECOV_TOKEN}} token: ${{secrets.CODECOV_TOKEN}}
fail_ci_if_error: true fail_ci_if_error: true

View File

@ -22,3 +22,5 @@ once fixed in engine will just start working here with no language changes.
- **Chamfers**: Chamfers cannot intersect, you will get an error. Only simple - **Chamfers**: Chamfers cannot intersect, you will get an error. Only simple
chamfer cases work currently. chamfer cases work currently.
- **Appearance**: Changing the appearance on a loft does not work.

239
docs/kcl/appearance.md Normal file

File diff suppressed because one or more lines are too long

49
docs/kcl/atan2.md Normal file

File diff suppressed because one or more lines are too long

View File

@ -19,6 +19,7 @@ layout: manual
* [`angledLineThatIntersects`](kcl/angledLineThatIntersects) * [`angledLineThatIntersects`](kcl/angledLineThatIntersects)
* [`angledLineToX`](kcl/angledLineToX) * [`angledLineToX`](kcl/angledLineToX)
* [`angledLineToY`](kcl/angledLineToY) * [`angledLineToY`](kcl/angledLineToY)
* [`appearance`](kcl/appearance)
* [`arc`](kcl/arc) * [`arc`](kcl/arc)
* [`arcTo`](kcl/arcTo) * [`arcTo`](kcl/arcTo)
* [`asin`](kcl/asin) * [`asin`](kcl/asin)
@ -29,6 +30,7 @@ layout: manual
* [`assertLessThan`](kcl/assertLessThan) * [`assertLessThan`](kcl/assertLessThan)
* [`assertLessThanOrEq`](kcl/assertLessThanOrEq) * [`assertLessThanOrEq`](kcl/assertLessThanOrEq)
* [`atan`](kcl/atan) * [`atan`](kcl/atan)
* [`atan2`](kcl/atan2)
* [`bezierCurve`](kcl/bezierCurve) * [`bezierCurve`](kcl/bezierCurve)
* [`ceil`](kcl/ceil) * [`ceil`](kcl/ceil)
* [`chamfer`](kcl/chamfer) * [`chamfer`](kcl/chamfer)
@ -101,6 +103,7 @@ layout: manual
* [`startProfileAt`](kcl/startProfileAt) * [`startProfileAt`](kcl/startProfileAt)
* [`startSketchAt`](kcl/startSketchAt) * [`startSketchAt`](kcl/startSketchAt)
* [`startSketchOn`](kcl/startSketchOn) * [`startSketchOn`](kcl/startSketchOn)
* [`sweep`](kcl/sweep)
* [`tan`](kcl/tan) * [`tan`](kcl/tan)
* [`tangentToEnd`](kcl/tangentToEnd) * [`tangentToEnd`](kcl/tangentToEnd)
* [`tangentialArc`](kcl/tangentialArc) * [`tangentialArc`](kcl/tangentialArc)

File diff suppressed because one or more lines are too long

View File

@ -35,7 +35,7 @@ The transform function returns a transform object. All properties of the object
- `rotation.origin` (either "local" i.e. rotate around its own center, "global" i.e. rotate around the scene's center, or a 3D point, defaults to "local") - `rotation.origin` (either "local" i.e. rotate around its own center, "global" i.e. rotate around the scene's center, or a 3D point, defaults to "local")
```js ```js
patternTransform(total_instances: u32, transform_function: FunctionParam, solid_set: SolidSet) -> [Solid] patternTransform(total_instances: integer, transform_function: FunctionParam, solid_set: SolidSet) -> [Solid]
``` ```
@ -43,7 +43,7 @@ patternTransform(total_instances: u32, transform_function: FunctionParam, solid_
| Name | Type | Description | Required | | Name | Type | Description | Required |
|----------|------|-------------|----------| |----------|------|-------------|----------|
| `total_instances` | `u32` | | Yes | | `total_instances` | `integer` | | Yes |
| `transform_function` | `FunctionParam` | | Yes | | `transform_function` | `FunctionParam` | | Yes |
| `solid_set` | [`SolidSet`](/docs/kcl/types/SolidSet) | A solid or a group of solids. | Yes | | `solid_set` | [`SolidSet`](/docs/kcl/types/SolidSet) | A solid or a group of solids. | Yes |

View File

@ -9,7 +9,7 @@ Just like patternTransform, but works on 2D sketches not 3D solids.
```js ```js
patternTransform2d(total_instances: u32, transform_function: FunctionParam, solid_set: SketchSet) -> [Sketch] patternTransform2d(total_instances: integer, transform_function: FunctionParam, solid_set: SketchSet) -> [Sketch]
``` ```
@ -17,7 +17,7 @@ patternTransform2d(total_instances: u32, transform_function: FunctionParam, soli
| Name | Type | Description | Required | | Name | Type | Description | Required |
|----------|------|-------------|----------| |----------|------|-------------|----------|
| `total_instances` | `u32` | | Yes | | `total_instances` | `integer` | | Yes |
| `transform_function` | `FunctionParam` | | Yes | | `transform_function` | `FunctionParam` | | Yes |
| `solid_set` | [`SketchSet`](/docs/kcl/types/SketchSet) | A sketch or a group of sketches. | Yes | | `solid_set` | [`SketchSet`](/docs/kcl/types/SketchSet) | A sketch or a group of sketches. | Yes |

View File

@ -43,7 +43,7 @@ fn sum(arr) {
/* The above is basically like this pseudo-code: /* The above is basically like this pseudo-code:
fn sum(arr): fn sum(arr):
let sumSoFar = 0 sumSoFar = 0
for i in arr: for i in arr:
sumSoFar = add(sumSoFar, i) sumSoFar = add(sumSoFar, i)
return sumSoFar */ return sumSoFar */
@ -96,14 +96,14 @@ fn decagon(radius) {
/* The `decagon` above is basically like this pseudo-code: /* The `decagon` above is basically like this pseudo-code:
fn decagon(radius): fn decagon(radius):
let stepAngle = (1/10) * tau() stepAngle = (1/10) * tau()
let startOfDecagonSketch = startSketchAt([(cos(0)*radius), (sin(0) * radius)]) startOfDecagonSketch = startSketchAt([(cos(0)*radius), (sin(0) * radius)])
// Here's the reduce part. // Here's the reduce part.
let partialDecagon = startOfDecagonSketch partialDecagon = startOfDecagonSketch
for i in [1..10]: for i in [1..10]:
let x = cos(stepAngle * i) * radius x = cos(stepAngle * i) * radius
let y = sin(stepAngle * i) * radius y = sin(stepAngle * i) * radius
partialDecagon = lineTo([x, y], partialDecagon) partialDecagon = lineTo([x, y], partialDecagon)
fullDecagon = partialDecagon // it's now full fullDecagon = partialDecagon // it's now full
return fullDecagon */ return fullDecagon */

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

55
docs/kcl/sweep.md Normal file

File diff suppressed because one or more lines are too long

View File

@ -13,13 +13,18 @@ Data to draw an angled line.
An angle and length with explicitly named parameters An angle and length with explicitly named parameters
[`PolarCoordsData`](/docs/kcl/types/PolarCoordsData) **Type:** `object`
## Properties
| Property | Type | Description | Required |
|----------|------|-------------|----------|
| `angle` |`number`| The angle of the line (in degrees). | No |
| `length` |`number`| The length of the line. | No |
---- ----

View File

@ -0,0 +1,23 @@
---
title: "AppearanceData"
excerpt: "Data for appearance."
layout: manual
---
Data for appearance.
**Type:** `object`
## Properties
| Property | Type | Description | Required |
|----------|------|-------------|----------|
| `color` |`string`| Color of the new material, a hex string like "#ff0000". | No |
| `metalness` |`number` (**maximum:** 100.0)| Metalness of the new material, a percentage like 95.7. | No |
| `roughness` |`number` (**maximum:** 100.0)| Roughness of the new material, a percentage like 95.7. | No |

View File

@ -12,5 +12,10 @@ KCL value for an optional parameter which was not given an argument. (remember,
## Properties
| Property | Type | Description | Required |
|----------|------|-------------|----------|
| `digest` |`[, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`, `integer`]`| | No |

View File

@ -329,6 +329,23 @@ Data for an imported geometry.
## Properties
| Property | Type | Description | Required |
|----------|------|-------------|----------|
| `type` |enum: `Module`| | No |
| `value` |[`ModuleId`](/docs/kcl/types/ModuleId)| Any KCL value. | No |
| `__meta` |`[` [`Metadata`](/docs/kcl/types/Metadata) `]`| | No |
----
**Type:** `object`
## Properties ## Properties
| Property | Type | Description | Required | | Property | Type | Description | Required |

View File

@ -0,0 +1,16 @@
---
title: "ModuleId"
excerpt: "Identifier of a source file. Uses a u32 to keep the size small."
layout: manual
---
Identifier of a source file. Uses a u32 to keep the size small.
**Type:** `integer` (`uint32`)

View File

@ -0,0 +1,23 @@
---
title: "SweepData"
excerpt: "Data for a sweep."
layout: manual
---
Data for a sweep.
**Type:** `object`
## Properties
| Property | Type | Description | Required |
|----------|------|-------------|----------|
| `path` |[`Sketch`](/docs/kcl/types/Sketch)| The path to sweep along. | No |
| `sectional` |`boolean`| If true, the sweep will be broken up into sub-sweeps (extrusions, revolves, sweeps) based on the trajectory path components. | No |
| `tolerance` |`number`| Tolerance for the sweep operation. | No |

View File

@ -94,6 +94,51 @@ test.describe('Editor tests', () => {
|> close(%)`) |> close(%)`)
}) })
test('ensure we use the cache, and do not re-execute', async ({ page }) => {
const u = await getUtils(page)
await page.setViewportSize({ width: 1000, height: 500 })
await u.waitForAuthSkipAppStart()
await u.codeLocator.click()
await page.keyboard.type(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %)
|> line([20, 0], %)
|> line([0, 20], %)
|> line([-20, 0], %)
|> close(%)`)
// Ensure we execute the first time.
await u.openDebugPanel()
await expect(
page.locator('[data-receive-command-type="scene_clear_all"]')
).toHaveCount(2)
await expect(
page.locator('[data-message-type="execution-done"]')
).toHaveCount(2)
// Add whitespace to the end of the code.
await u.codeLocator.click()
await page.keyboard.press('ArrowUp')
await page.keyboard.press('ArrowUp')
await page.keyboard.press('ArrowUp')
await page.keyboard.press('ArrowUp')
await page.keyboard.press('Home')
await page.keyboard.type(' ')
await page.keyboard.press('Enter')
await page.keyboard.type(' ')
// Ensure we don't execute the second time.
await u.openDebugPanel()
// Make sure we didn't clear the scene.
await expect(
page.locator('[data-message-type="execution-done"]')
).toHaveCount(3)
await expect(
page.locator('[data-receive-command-type="scene_clear_all"]')
).toHaveCount(2)
})
test('if you click the format button it formats your code and executes so lints are still there', async ({ test('if you click the format button it formats your code and executes so lints are still there', async ({
page, page,
}) => { }) => {

View File

@ -214,23 +214,7 @@ export class SceneFixture {
coords: { x: number; y: number }, coords: { x: number; y: number },
diff: number diff: number
) => { ) => {
let finalValue = colour await expectPixelColor(this.page, colour, coords, diff)
await expect
.poll(async () => {
const pixel = (await getPixelRGBs(this.page)(coords, 1))[0]
if (!pixel) return null
finalValue = pixel
return pixel.every(
(channel, index) => Math.abs(channel - colour[index]) < diff
)
})
.toBeTruthy()
.catch((cause) => {
throw new Error(
`ExpectPixelColor: expecting ${colour} got ${finalValue}`,
{ cause }
)
})
} }
get gizmo() { get gizmo() {
@ -246,3 +230,28 @@ export class SceneFixture {
await buttonToTest.click() await buttonToTest.click()
} }
} }
export async function expectPixelColor(
page: Page,
colour: [number, number, number],
coords: { x: number; y: number },
diff: number
) {
let finalValue = colour
await expect
.poll(async () => {
const pixel = (await getPixelRGBs(page)(coords, 1))[0]
if (!pixel) return null
finalValue = pixel
return pixel.every(
(channel, index) => Math.abs(channel - colour[index]) < diff
)
})
.toBeTruthy()
.catch((cause) => {
throw new Error(
`ExpectPixelColor: expecting ${colour} got ${finalValue}`,
{ cause }
)
})
}

View File

@ -19,6 +19,7 @@ import {
TEST_SETTINGS_ONBOARDING_USER_MENU, TEST_SETTINGS_ONBOARDING_USER_MENU,
} from './storageStates' } from './storageStates'
import * as TOML from '@iarna/toml' import * as TOML from '@iarna/toml'
import { expectPixelColor } from './fixtures/sceneFixture'
test.beforeEach(async ({ context, page }, testInfo) => { test.beforeEach(async ({ context, page }, testInfo) => {
if (testInfo.tags.includes('@electron')) { if (testInfo.tags.includes('@electron')) {
@ -45,7 +46,7 @@ test.describe('Onboarding tests', () => {
{ settingsKey: TEST_SETTINGS_KEY } { settingsKey: TEST_SETTINGS_KEY }
) )
await page.setViewportSize({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 1000 })
await u.waitForAuthSkipAppStart() await u.waitForAuthSkipAppStart()
@ -54,6 +55,12 @@ test.describe('Onboarding tests', () => {
// *and* that the code is shown in the editor // *and* that the code is shown in the editor
await expect(page.locator('.cm-content')).toContainText('// Shelf Bracket') await expect(page.locator('.cm-content')).toContainText('// Shelf Bracket')
// Make sure the model loaded
const XYPlanePoint = { x: 774, y: 116 } as const
const modelColor: [number, number, number] = [45, 45, 45]
await page.mouse.move(XYPlanePoint.x, XYPlanePoint.y)
expect(await u.getGreatestPixDiff(XYPlanePoint, modelColor)).toBeLessThan(8)
}) })
test( test(
@ -72,7 +79,7 @@ test.describe('Onboarding tests', () => {
const u = await getUtils(page) const u = await getUtils(page)
const viewportSize = { width: 1200, height: 500 } const viewportSize = { width: 1200, height: 1000 }
await page.setViewportSize(viewportSize) await page.setViewportSize(viewportSize)
await test.step(`Create a project and open to the onboarding`, async () => { await test.step(`Create a project and open to the onboarding`, async () => {
@ -92,6 +99,14 @@ test.describe('Onboarding tests', () => {
await expect(page.locator('.cm-content')).toContainText( await expect(page.locator('.cm-content')).toContainText(
'// Shelf Bracket' '// Shelf Bracket'
) )
// TODO: jess make less shit
// Make sure the model loaded
//const XYPlanePoint = { x: 986, y: 522 } as const
//const modelColor: [number, number, number] = [76, 76, 76]
//await page.mouse.move(XYPlanePoint.x, XYPlanePoint.y)
//await expectPixelColor(page, modelColor, XYPlanePoint, 8)
}) })
await electronApp.close() await electronApp.close()
@ -108,7 +123,7 @@ test.describe('Onboarding tests', () => {
}, initialCode) }, initialCode)
const u = await getUtils(page) const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 1000 })
await u.waitForAuthSkipAppStart() await u.waitForAuthSkipAppStart()
// Replay the onboarding // Replay the onboarding
@ -140,6 +155,12 @@ test.describe('Onboarding tests', () => {
return localStorage.getItem('persistCode') return localStorage.getItem('persistCode')
}) })
).toContain('// Shelf Bracket') ).toContain('// Shelf Bracket')
// Make sure the model loaded
const XYPlanePoint = { x: 986, y: 522 } as const
const modelColor: [number, number, number] = [76, 76, 76]
await page.mouse.move(XYPlanePoint.x, XYPlanePoint.y)
await expectPixelColor(page, modelColor, XYPlanePoint, 8)
}) })
test('Click through each onboarding step', async ({ page }) => { test('Click through each onboarding step', async ({ page }) => {
@ -179,6 +200,17 @@ test.describe('Onboarding tests', () => {
// Test that the onboarding pane is gone // Test that the onboarding pane is gone
await expect(page.getByTestId('onboarding-content')).not.toBeVisible() await expect(page.getByTestId('onboarding-content')).not.toBeVisible()
await expect(page.url()).not.toContain('onboarding') await expect(page.url()).not.toContain('onboarding')
await u.openAndClearDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel()
// TODO: jess to fix
// Make sure the model loaded
//const XYPlanePoint = { x: 774, y: 516 } as const
// const modelColor: [number, number, number] = [129, 129, 129]
// await page.mouse.move(XYPlanePoint.x, XYPlanePoint.y)
// await expectPixelColor(page, modelColor, XYPlanePoint, 20)
}) })
test('Onboarding redirects and code updating', async ({ page }) => { test('Onboarding redirects and code updating', async ({ page }) => {
@ -393,7 +425,7 @@ test.describe('Onboarding tests', () => {
}) })
}) })
test( test.fixme(
'Restarting onboarding on desktop takes one attempt', 'Restarting onboarding on desktop takes one attempt',
{ tag: '@electron' }, { tag: '@electron' },
async ({ browser: _ }, testInfo) => { async ({ browser: _ }, testInfo) => {
@ -439,7 +471,7 @@ test(
}) })
await test.step('Navigate into project', async () => { await test.step('Navigate into project', async () => {
await page.setViewportSize({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 1000 })
page.on('console', console.log) page.on('console', console.log)
@ -462,7 +494,15 @@ test(
await test.step('Confirm that the onboarding has restarted', async () => { await test.step('Confirm that the onboarding has restarted', async () => {
await expect(tutorialProjectIndicator).toBeVisible() await expect(tutorialProjectIndicator).toBeVisible()
await expect(tutorialModalText).toBeVisible() await expect(tutorialModalText).toBeVisible()
// Make sure the model loaded
const XYPlanePoint = { x: 988, y: 523 } as const
const modelColor: [number, number, number] = [76, 76, 76]
await page.mouse.move(XYPlanePoint.x, XYPlanePoint.y)
await expectPixelColor(page, modelColor, XYPlanePoint, 8)
await tutorialDismissButton.click() await tutorialDismissButton.click()
// Make sure model still there.
await expectPixelColor(page, modelColor, XYPlanePoint, 8)
}) })
await test.step('Clear code and restart onboarding from settings', async () => { await test.step('Clear code and restart onboarding from settings', async () => {

View File

@ -950,7 +950,75 @@ test(
test.describe('Grid visibility', { tag: '@snapshot' }, () => { test.describe('Grid visibility', { tag: '@snapshot' }, () => {
// FIXME: Skip on macos its being weird. // FIXME: Skip on macos its being weird.
test.skip(process.platform === 'darwin', 'Skip on macos') // test.skip(process.platform === 'darwin', 'Skip on macos')
test('Grid turned off to on via command bar', async ({ page }) => {
const u = await getUtils(page)
const stream = page.getByTestId('stream')
const mask = [
page.locator('#app-header'),
page.locator('#sidebar-top-ribbon'),
page.locator('#sidebar-bottom-ribbon'),
]
await page.setViewportSize({ width: 1200, height: 500 })
await page.goto('/')
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
// wait for execution done
await expect(
page.locator('[data-message-type="execution-done"]')
).toHaveCount(1)
await u.closeDebugPanel()
await u.closeKclCodePanel()
// TODO: Find a way to truly know that the objects have finished
// rendering, because an execution-done message is not sufficient.
await page.waitForTimeout(1000)
// Open the command bar.
await page
.getByRole('button', { name: 'Commands', exact: false })
.or(page.getByRole('button', { name: '⌘K' }))
.click()
const commandName = 'show scale grid'
const commandOption = page.getByRole('option', {
name: commandName,
exact: false,
})
const cmdSearchBar = page.getByPlaceholder('Search commands')
// This selector changes after we set the setting
await cmdSearchBar.fill(commandName)
await expect(commandOption).toBeVisible()
await commandOption.click()
const toggleInput = page.getByPlaceholder('Off')
await expect(toggleInput).toBeVisible()
await expect(toggleInput).toBeFocused()
// Select On
await page.keyboard.press('ArrowDown')
await expect(page.getByRole('option', { name: 'Off' })).toHaveAttribute(
'data-headlessui-state',
'active selected'
)
await page.keyboard.press('ArrowUp')
await expect(page.getByRole('option', { name: 'On' })).toHaveAttribute(
'data-headlessui-state',
'active'
)
await page.keyboard.press('Enter')
// Check the toast appeared
await expect(
page.getByText(`Set show scale grid to "true" as a user default`)
).toBeVisible()
await expect(stream).toHaveScreenshot({
maxDiffPixels: 100,
mask,
})
})
test('Grid turned off', async ({ page }) => { test('Grid turned off', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
@ -1096,3 +1164,109 @@ test.fixme('theme persists', async ({ page, context }) => {
maxDiffPixels: 100, maxDiffPixels: 100,
}) })
}) })
test.describe('code color goober', { tag: '@snapshot' }, () => {
test('code color goober', async ({ page, context }) => {
const u = await getUtils(page)
await context.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`// Create a pipe using a sweep.
// Create a path for the sweep.
sweepPath = startSketchOn('XZ')
|> startProfileAt([0.05, 0.05], %)
|> line([0, 7], %)
|> tangentialArc({ offset = 90, radius = 5 }, %)
|> line([-3, 0], %)
|> tangentialArc({ offset = -90, radius = 5 }, %)
|> line([0, 7], %)
sweepSketch = startSketchOn('XY')
|> startProfileAt([2, 0], %)
|> arc({
angleEnd = 360,
angleStart = 0,
radius = 2
}, %)
|> sweep({
path = sweepPath,
}, %)
|> appearance({
color = "#bb00ff",
metalness = 90,
roughness = 90
}, %)
`
)
})
await page.setViewportSize({ width: 1200, height: 1000 })
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]')
await u.clearAndCloseDebugPanel()
await expect(page, 'expect small color widget').toHaveScreenshot({
maxDiffPixels: 100,
})
})
test('code color goober opening window', async ({ page, context }) => {
const u = await getUtils(page)
await context.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`// Create a pipe using a sweep.
// Create a path for the sweep.
sweepPath = startSketchOn('XZ')
|> startProfileAt([0.05, 0.05], %)
|> line([0, 7], %)
|> tangentialArc({ offset = 90, radius = 5 }, %)
|> line([-3, 0], %)
|> tangentialArc({ offset = -90, radius = 5 }, %)
|> line([0, 7], %)
sweepSketch = startSketchOn('XY')
|> startProfileAt([2, 0], %)
|> arc({
angleEnd = 360,
angleStart = 0,
radius = 2
}, %)
|> sweep({
path = sweepPath,
}, %)
|> appearance({
color = "#bb00ff",
metalness = 90,
roughness = 90
}, %)
`
)
})
await page.setViewportSize({ width: 1200, height: 1000 })
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]')
await u.clearAndCloseDebugPanel()
await expect(page.locator('.cm-css-color-picker-wrapper')).toBeVisible()
// Click the color widget
await page.locator('.cm-css-color-picker-wrapper input').click()
await expect(
page,
'expect small color widget to have window open'
).toHaveScreenshot({
maxDiffPixels: 100,
})
})
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 40 KiB

View File

@ -14,7 +14,7 @@ export const TEST_SETTINGS = {
}, },
modeling: { modeling: {
defaultUnit: 'in', defaultUnit: 'in',
mouseControls: 'KittyCAD', mouseControls: 'Zoo',
cameraProjection: 'perspective', cameraProjection: 'perspective',
showDebugPanel: true, showDebugPanel: true,
}, },

View File

@ -479,4 +479,26 @@ test.describe('Testing Camera Movement', () => {
}) })
} }
}) })
test('Right-click opens context menu when not dragged', async ({ page }) => {
const u = await getUtils(page)
await u.waitForAuthSkipAppStart()
await test.step(`The menu should not show if we drag the mouse`, async () => {
await page.mouse.move(900, 200)
await page.mouse.down({ button: 'right' })
await page.mouse.move(900, 300)
await page.mouse.up({ button: 'right' })
await expect(page.getByTestId('view-controls-menu')).not.toBeVisible()
})
await test.step(`The menu should show if we don't drag the mouse`, async () => {
await page.mouse.move(900, 200)
await page.mouse.down({ button: 'right' })
await page.mouse.up({ button: 'right' })
await expect(page.getByTestId('view-controls-menu')).toBeVisible()
})
})
}) })

View File

@ -1,20 +1,9 @@
import type { ForgeConfig } from '@electron-forge/shared-types' import type { ForgeConfig } from '@electron-forge/shared-types'
import { MakerSquirrel } from '@electron-forge/maker-squirrel'
import { MakerZIP } from '@electron-forge/maker-zip'
import { MakerDeb } from '@electron-forge/maker-deb'
import { MakerRpm } from '@electron-forge/maker-rpm'
import { VitePlugin } from '@electron-forge/plugin-vite' import { VitePlugin } from '@electron-forge/plugin-vite'
import { MakerWix, MakerWixConfig } from '@electron-forge/maker-wix'
import { FusesPlugin } from '@electron-forge/plugin-fuses' import { FusesPlugin } from '@electron-forge/plugin-fuses'
import { FuseV1Options, FuseVersion } from '@electron/fuses' import { FuseV1Options, FuseVersion } from '@electron/fuses'
import path from 'path' import path from 'path'
interface ExtendedMakerWixConfig extends MakerWixConfig {
// see https://github.com/electron/forge/issues/3673
// this is an undocumented property of electron-wix-msi
associateExtensions?: string
}
const rootDir = process.cwd() const rootDir = process.cwd()
const config: ForgeConfig = { const config: ForgeConfig = {
@ -39,26 +28,7 @@ const config: ForgeConfig = {
extendInfo: 'Info.plist', // Information for file associations. extendInfo: 'Info.plist', // Information for file associations.
}, },
rebuildConfig: {}, rebuildConfig: {},
makers: [ makers: [],
new MakerSquirrel({
setupIcon: path.resolve(rootDir, 'assets', 'icon.ico'),
}),
new MakerWix({
icon: path.resolve(rootDir, 'assets', 'icon.ico'),
associateExtensions: 'kcl',
} as ExtendedMakerWixConfig),
new MakerZIP({}, ['darwin']),
new MakerRpm({
options: {
icon: path.resolve(rootDir, 'assets', 'icon.png'),
},
}),
new MakerDeb({
options: {
icon: path.resolve(rootDir, 'assets', 'icon.png'),
},
}),
],
plugins: [ plugins: [
new VitePlugin({ new VitePlugin({
// `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc. // `build` can specify multiple entry builds, which can be Main process, Preload scripts, Worker process, etc.

View File

@ -39,7 +39,6 @@
"chokidar": "^4.0.1", "chokidar": "^4.0.1",
"codemirror": "^6.0.1", "codemirror": "^6.0.1",
"decamelize": "^6.0.0", "decamelize": "^6.0.0",
"electron-squirrel-startup": "^1.0.1",
"electron-updater": "6.3.0", "electron-updater": "6.3.0",
"fuse.js": "^7.0.0", "fuse.js": "^7.0.0",
"html2canvas-pro": "^1.5.8", "html2canvas-pro": "^1.5.8",
@ -69,7 +68,7 @@
"yargs": "^17.7.2" "yargs": "^17.7.2"
}, },
"scripts": { "scripts": {
"start": "vite", "start": "vite --port=3000 --host=0.0.0.0",
"start:prod": "vite preview --port=3000", "start:prod": "vite preview --port=3000",
"serve": "vite serve --port=3000", "serve": "vite serve --port=3000",
"build": "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && source \"$HOME/.cargo/env\" && curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -y && yarn build:wasm && vite build", "build": "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && source \"$HOME/.cargo/env\" && curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -y && yarn build:wasm && vite build",
@ -104,8 +103,6 @@
"generate:machine-api": "npx openapi-typescript ./openapi/machine-api.json -o src/lib/machine-api.d.ts", "generate:machine-api": "npx openapi-typescript ./openapi/machine-api.json -o src/lib/machine-api.d.ts",
"tron:start": "electron-forge start", "tron:start": "electron-forge start",
"tron:package": "electron-forge package", "tron:package": "electron-forge package",
"tron:make": "electron-forge make",
"tron:publish": "electron-forge publish",
"tron:test": "NODE_ENV=development yarn playwright test --config=playwright.electron.config.ts --grep=@electron", "tron:test": "NODE_ENV=development yarn playwright test --config=playwright.electron.config.ts --grep=@electron",
"tronb:vite": "vite build -c vite.main.config.ts && vite build -c vite.preload.config.ts && vite build -c vite.renderer.config.ts", "tronb:vite": "vite build -c vite.main.config.ts && vite build -c vite.preload.config.ts && vite build -c vite.renderer.config.ts",
"tronb:package": "electron-builder --config electron-builder.yml", "tronb:package": "electron-builder --config electron-builder.yml",
@ -148,17 +145,10 @@
"devDependencies": { "devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11", "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@babel/preset-env": "^7.25.4", "@babel/preset-env": "^7.25.4",
"@electron-forge/cli": "^7.4.0", "@electron-forge/cli": "7.4.0",
"@electron-forge/maker-deb": "^7.4.0", "@electron-forge/plugin-fuses": "7.4.0",
"@electron-forge/maker-rpm": "^7.4.0", "@electron-forge/plugin-vite": "7.4.0",
"@electron-forge/maker-squirrel": "^7.4.0", "@electron/fuses": "1.8.0",
"@electron-forge/maker-wix": "^7.5.0",
"@electron-forge/maker-zip": "^7.5.0",
"@electron-forge/plugin-auto-unpack-natives": "^7.4.0",
"@electron-forge/plugin-fuses": "^7.4.0",
"@electron-forge/plugin-vite": "^7.4.0",
"@electron/fuses": "^1.8.0",
"@electron/rebuild": "^3.6.0",
"@iarna/toml": "^2.2.5", "@iarna/toml": "^2.2.5",
"@lezer/generator": "^1.7.1", "@lezer/generator": "^1.7.1",
"@nabla/vite-plugin-eslint": "^2.0.5", "@nabla/vite-plugin-eslint": "^2.0.5",
@ -188,9 +178,9 @@
"@xstate/cli": "^0.5.17", "@xstate/cli": "^0.5.17",
"autoprefixer": "^10.4.19", "autoprefixer": "^10.4.19",
"d3-force": "^3.0.0", "d3-force": "^3.0.0",
"electron": "^32.1.2", "electron": "32.1.2",
"electron-builder": "^24.13.3", "electron-builder": "24.13.3",
"electron-notarize": "^1.2.2", "electron-notarize": "1.2.2",
"eslint": "^8.0.1", "eslint": "^8.0.1",
"eslint-config-react-app": "^7.0.1", "eslint-config-react-app": "^7.0.1",
"eslint-plugin-css-modules": "^2.12.0", "eslint-plugin-css-modules": "^2.12.0",

View File

@ -119,6 +119,11 @@
"title": "Pipe and Flange Assembly", "title": "Pipe and Flange Assembly",
"description": "A crucial component in various piping systems, designed to facilitate the connection, disconnection, and access to piping for inspection, cleaning, and modifications. This assembly combines pipes (long cylindrical conduits) with flanges (plate-like fittings) to create a secure yet detachable joint." "description": "A crucial component in various piping systems, designed to facilitate the connection, disconnection, and access to piping for inspection, cleaning, and modifications. This assembly combines pipes (long cylindrical conduits) with flanges (plate-like fittings) to create a secure yet detachable joint."
}, },
{
"file": "pipe-with-bend.kcl",
"title": "Pipe with bend",
"description": "A tubular section or hollow cylinder, usually but not necessarily of circular cross-section, used mainly to convey substances that can flow."
},
{ {
"file": "poopy-shoe.kcl", "file": "poopy-shoe.kcl",
"title": "Poopy Shoe", "title": "Poopy Shoe",

View File

@ -105,7 +105,7 @@ export class CameraControls {
pendingZoom: number | null = null pendingZoom: number | null = null
pendingRotation: Vector2 | null = null pendingRotation: Vector2 | null = null
pendingPan: Vector2 | null = null pendingPan: Vector2 | null = null
interactionGuards: MouseGuard = cameraMouseDragGuards.KittyCAD interactionGuards: MouseGuard = cameraMouseDragGuards.Zoo
isFovAnimationInProgress = false isFovAnimationInProgress = false
perspectiveFovBeforeOrtho = 45 perspectiveFovBeforeOrtho = 45
get isPerspective() { get isPerspective() {

View File

@ -1,13 +1,23 @@
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { ActionIcon, ActionIconProps } from './ActionIcon' import { ActionIcon, ActionIconProps } from './ActionIcon'
import { RefObject, useEffect, useMemo, useRef, useState } from 'react' import {
MouseEvent,
RefObject,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { useHotkeys } from 'react-hotkeys-hook' import { useHotkeys } from 'react-hotkeys-hook'
import { Dialog } from '@headlessui/react' import { Dialog } from '@headlessui/react'
interface ContextMenuProps export interface ContextMenuProps
extends Omit<React.HTMLAttributes<HTMLUListElement>, 'children'> { extends Omit<React.HTMLAttributes<HTMLUListElement>, 'children'> {
items?: React.ReactElement[] items?: React.ReactElement[]
menuTargetElement?: RefObject<HTMLElement> menuTargetElement?: RefObject<HTMLElement>
guard?: (e: globalThis.MouseEvent) => boolean
event?: 'contextmenu' | 'mouseup'
} }
const DefaultContextMenuItems = [ const DefaultContextMenuItems = [
@ -20,6 +30,8 @@ export function ContextMenu({
items = DefaultContextMenuItems, items = DefaultContextMenuItems,
menuTargetElement, menuTargetElement,
className, className,
guard,
event = 'contextmenu',
...props ...props
}: ContextMenuProps) { }: ContextMenuProps) {
const dialogRef = useRef<HTMLDivElement>(null) const dialogRef = useRef<HTMLDivElement>(null)
@ -32,6 +44,15 @@ export function ContextMenu({
useHotkeys('esc', () => setOpen(false), { useHotkeys('esc', () => setOpen(false), {
enabled: open, enabled: open,
}) })
const handleContextMenu = useCallback(
(e: globalThis.MouseEvent) => {
if (guard && !guard(e)) return
e.preventDefault()
setPosition({ x: e.clientX, y: e.clientY })
setOpen(true)
},
[guard, setPosition, setOpen]
)
const dialogPositionStyle = useMemo(() => { const dialogPositionStyle = useMemo(() => {
if (!dialogRef.current) if (!dialogRef.current)
@ -78,21 +99,9 @@ export function ContextMenu({
// Add context menu listener to target once mounted // Add context menu listener to target once mounted
useEffect(() => { useEffect(() => {
const handleContextMenu = (e: MouseEvent) => { menuTargetElement?.current?.addEventListener(event, handleContextMenu)
console.log('context menu', e)
e.preventDefault()
setPosition({ x: e.x, y: e.y })
setOpen(true)
}
menuTargetElement?.current?.addEventListener(
'contextmenu',
handleContextMenu
)
return () => { return () => {
menuTargetElement?.current?.removeEventListener( menuTargetElement?.current?.removeEventListener(event, handleContextMenu)
'contextmenu',
handleContextMenu
)
} }
}, [menuTargetElement?.current]) }, [menuTargetElement?.current])
@ -100,7 +109,10 @@ export function ContextMenu({
<Dialog open={open} onClose={() => setOpen(false)}> <Dialog open={open} onClose={() => setOpen(false)}>
<div <div
className="fixed inset-0 z-50 w-screen h-screen" className="fixed inset-0 z-50 w-screen h-screen"
onContextMenu={(e) => e.preventDefault()} onContextMenu={(e) => {
e.preventDefault()
setPosition({ x: e.clientX, y: e.clientY })
}}
> >
<Dialog.Backdrop className="fixed z-10 inset-0" /> <Dialog.Backdrop className="fixed z-10 inset-0" />
<Dialog.Panel <Dialog.Panel

View File

@ -1,6 +1,6 @@
import { SceneInfra } from 'clientSideScene/sceneInfra' import { SceneInfra } from 'clientSideScene/sceneInfra'
import { sceneInfra } from 'lib/singletons' import { sceneInfra } from 'lib/singletons'
import { MutableRefObject, useEffect, useMemo, useRef } from 'react' import { MutableRefObject, useEffect, useRef } from 'react'
import { import {
WebGLRenderer, WebGLRenderer,
Scene, Scene,
@ -19,16 +19,14 @@ import {
Intersection, Intersection,
Object3D, Object3D,
} from 'three' } from 'three'
import {
ContextMenu,
ContextMenuDivider,
ContextMenuItem,
ContextMenuItemRefresh,
} from './ContextMenu'
import { Popover } from '@headlessui/react' import { Popover } from '@headlessui/react'
import { CustomIcon } from './CustomIcon' import { CustomIcon } from './CustomIcon'
import { reportRejection } from 'lib/trap' import { reportRejection } from 'lib/trap'
import { useModelingContext } from 'hooks/useModelingContext' import {
useViewControlMenuItems,
ViewControlContextMenu,
} from './ViewControlMenu'
import { AxisNames } from 'lib/constants'
const CANVAS_SIZE = 80 const CANVAS_SIZE = 80
const FRUSTUM_SIZE = 0.5 const FRUSTUM_SIZE = 0.5
@ -40,64 +38,14 @@ enum AxisColors {
Z = '#6689ef', Z = '#6689ef',
Gray = '#c6c7c2', Gray = '#c6c7c2',
} }
enum AxisNames {
X = 'x',
Y = 'y',
Z = 'z',
NEG_X = '-x',
NEG_Y = '-y',
NEG_Z = '-z',
}
const axisNamesSemantic: Record<AxisNames, string> = {
[AxisNames.X]: 'Right',
[AxisNames.Y]: 'Back',
[AxisNames.Z]: 'Top',
[AxisNames.NEG_X]: 'Left',
[AxisNames.NEG_Y]: 'Front',
[AxisNames.NEG_Z]: 'Bottom',
}
export default function Gizmo() { export default function Gizmo() {
const menuItems = useViewControlMenuItems()
const wrapperRef = useRef<HTMLDivElement | null>(null) const wrapperRef = useRef<HTMLDivElement | null>(null)
const canvasRef = useRef<HTMLCanvasElement | null>(null) const canvasRef = useRef<HTMLCanvasElement | null>(null)
const raycasterIntersect = useRef<Intersection<Object3D> | null>(null) const raycasterIntersect = useRef<Intersection<Object3D> | null>(null)
const cameraPassiveUpdateTimer = useRef(0) const cameraPassiveUpdateTimer = useRef(0)
const raycasterPassiveUpdateTimer = useRef(0) const raycasterPassiveUpdateTimer = useRef(0)
const { send: modelingSend } = useModelingContext()
const menuItems = useMemo(
() => [
...Object.entries(axisNamesSemantic).map(([axisName, axisSemantic]) => (
<ContextMenuItem
key={axisName}
onClick={() => {
sceneInfra.camControls
.updateCameraToAxis(axisName as AxisNames)
.catch(reportRejection)
}}
>
{axisSemantic} view
</ContextMenuItem>
)),
<ContextMenuDivider />,
<ContextMenuItem
onClick={() => {
sceneInfra.camControls.resetCameraPosition().catch(reportRejection)
}}
>
Reset view
</ContextMenuItem>,
<ContextMenuItem
onClick={() => {
modelingSend({ type: 'Center camera on selection' })
}}
>
Center view on selection
</ContextMenuItem>,
<ContextMenuDivider />,
<ContextMenuItemRefresh />,
],
[axisNamesSemantic]
)
useEffect(() => { useEffect(() => {
if (!canvasRef.current) return if (!canvasRef.current) return
@ -161,7 +109,7 @@ export default function Gizmo() {
className="grid place-content-center rounded-full overflow-hidden border border-solid border-primary/50 pointer-events-auto bg-chalkboard-10/70 dark:bg-chalkboard-100/80 backdrop-blur-sm" className="grid place-content-center rounded-full overflow-hidden border border-solid border-primary/50 pointer-events-auto bg-chalkboard-10/70 dark:bg-chalkboard-100/80 backdrop-blur-sm"
> >
<canvas ref={canvasRef} /> <canvas ref={canvasRef} />
<ContextMenu menuTargetElement={wrapperRef} items={menuItems} /> <ViewControlContextMenu menuTargetElement={wrapperRef} />
</div> </div>
<GizmoDropdown items={menuItems} /> <GizmoDropdown items={menuItems} />
</div> </div>

View File

@ -1,4 +1,4 @@
import { APP_VERSION, RELEASE_URL } from 'routes/Settings' import { APP_VERSION, getReleaseUrl } from 'routes/Settings'
import { CustomIcon } from 'components/CustomIcon' import { CustomIcon } from 'components/CustomIcon'
import Tooltip from 'components/Tooltip' import Tooltip from 'components/Tooltip'
import { PATHS } from 'lib/paths' import { PATHS } from 'lib/paths'
@ -72,8 +72,8 @@ export function LowerRightControls({
<menu className="flex items-center justify-end gap-3 pointer-events-auto"> <menu className="flex items-center justify-end gap-3 pointer-events-auto">
{!location.pathname.startsWith(PATHS.HOME) && <ModelStateIndicator />} {!location.pathname.startsWith(PATHS.HOME) && <ModelStateIndicator />}
<a <a
onClick={openExternalBrowserIfDesktop(RELEASE_URL)} onClick={openExternalBrowserIfDesktop(getReleaseUrl())}
href={RELEASE_URL} href={getReleaseUrl()}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className={'!no-underline font-mono text-xs ' + linkOverrideClassName} className={'!no-underline font-mono text-xs ' + linkOverrideClassName}

View File

@ -69,14 +69,7 @@ export const LspProvider = ({ children }: { children: React.ReactNode }) => {
const [isKclLspReady, setIsKclLspReady] = useState(false) const [isKclLspReady, setIsKclLspReady] = useState(false)
const [isCopilotLspReady, setIsCopilotLspReady] = useState(false) const [isCopilotLspReady, setIsCopilotLspReady] = useState(false)
const { const { auth } = useSettingsAuthContext()
auth,
settings: {
context: {
modeling: { defaultUnit },
},
},
} = useSettingsAuthContext()
const token = auth?.context.token const token = auth?.context.token
const navigate = useNavigate() const navigate = useNavigate()
@ -92,7 +85,6 @@ export const LspProvider = ({ children }: { children: React.ReactNode }) => {
const initEvent: KclWorkerOptions = { const initEvent: KclWorkerOptions = {
wasmUrl: wasmUrl(), wasmUrl: wasmUrl(),
token: token, token: token,
baseUnit: defaultUnit.current,
apiBaseUrl: VITE_KC_API_BASE_URL, apiBaseUrl: VITE_KC_API_BASE_URL,
} }
lspWorker.postMessage({ lspWorker.postMessage({

View File

@ -6,6 +6,7 @@ import Tooltip from 'components/Tooltip'
import { CustomIconName } from 'components/CustomIcon' import { CustomIconName } from 'components/CustomIcon'
import { IconDefinition } from '@fortawesome/free-solid-svg-icons' import { IconDefinition } from '@fortawesome/free-solid-svg-icons'
import { ActionIcon } from 'components/ActionIcon' import { ActionIcon } from 'components/ActionIcon'
import { onboardingPaths } from 'routes/Onboarding/paths'
export interface ModelingPaneProps { export interface ModelingPaneProps {
id: string id: string
@ -70,7 +71,7 @@ export const ModelingPane = ({
const { settings } = useSettingsAuthContext() const { settings } = useSettingsAuthContext()
const onboardingStatus = settings.context.app.onboardingStatus const onboardingStatus = settings.context.app.onboardingStatus
const pointerEventsCssClass = const pointerEventsCssClass =
onboardingStatus.current === 'camera' onboardingStatus.current === onboardingPaths.CAMERA
? 'pointer-events-none ' ? 'pointer-events-none '
: 'pointer-events-auto ' : 'pointer-events-auto '
return ( return (

View File

@ -19,6 +19,7 @@ import { useCommandsContext } from 'hooks/useCommandsContext'
import { IconDefinition } from '@fortawesome/free-solid-svg-icons' import { IconDefinition } from '@fortawesome/free-solid-svg-icons'
import { useKclContext } from 'lang/KclProvider' import { useKclContext } from 'lang/KclProvider'
import { MachineManagerContext } from 'components/MachineManagerProvider' import { MachineManagerContext } from 'components/MachineManagerProvider'
import { onboardingPaths } from 'routes/Onboarding/paths'
interface ModelingSidebarProps { interface ModelingSidebarProps {
paneOpacity: '' | 'opacity-20' | 'opacity-40' paneOpacity: '' | 'opacity-20' | 'opacity-40'
@ -41,7 +42,7 @@ export function ModelingSidebar({ paneOpacity }: ModelingSidebarProps) {
const onboardingStatus = settings.context.app.onboardingStatus const onboardingStatus = settings.context.app.onboardingStatus
const { send, context } = useModelingContext() const { send, context } = useModelingContext()
const pointerEventsCssClass = const pointerEventsCssClass =
onboardingStatus.current === 'camera' || onboardingStatus.current === onboardingPaths.CAMERA ||
context.store?.openPanes.length === 0 context.store?.openPanes.length === 0
? 'pointer-events-none ' ? 'pointer-events-none '
: 'pointer-events-auto ' : 'pointer-events-auto '

View File

@ -13,7 +13,7 @@ import { isDesktop } from 'lib/isDesktop'
import { ActionButton } from 'components/ActionButton' import { ActionButton } from 'components/ActionButton'
import { SettingsFieldInput } from './SettingsFieldInput' import { SettingsFieldInput } from './SettingsFieldInput'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { APP_VERSION, IS_NIGHTLY, RELEASE_URL } from 'routes/Settings' import { APP_VERSION, IS_NIGHTLY, getReleaseUrl } from 'routes/Settings'
import { PATHS } from 'lib/paths' import { PATHS } from 'lib/paths'
import { import {
createAndOpenNewTutorialProject, createAndOpenNewTutorialProject,
@ -246,8 +246,8 @@ export const AllSettingsFields = forwardRef(
to inject the version from package.json */} to inject the version from package.json */}
App version {APP_VERSION}.{' '} App version {APP_VERSION}.{' '}
<a <a
onClick={openExternalBrowserIfDesktop(RELEASE_URL)} onClick={openExternalBrowserIfDesktop(getReleaseUrl())}
href={RELEASE_URL} href={getReleaseUrl()}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >

View File

@ -1,5 +1,5 @@
import { trap } from 'lib/trap' import { trap } from 'lib/trap'
import { useMachine } from '@xstate/react' import { useMachine, useSelector } from '@xstate/react'
import { useNavigate, useRouteLoaderData, useLocation } from 'react-router-dom' import { useNavigate, useRouteLoaderData, useLocation } from 'react-router-dom'
import { PATHS, BROWSER_PATH } from 'lib/paths' import { PATHS, BROWSER_PATH } from 'lib/paths'
import { authMachine, TOKEN_PERSIST_KEY } from '../machines/authMachine' import { authMachine, TOKEN_PERSIST_KEY } from '../machines/authMachine'
@ -23,7 +23,6 @@ import {
engineCommandManager, engineCommandManager,
sceneEntitiesManager, sceneEntitiesManager,
} from 'lib/singletons' } from 'lib/singletons'
import { uuidv4 } from 'lib/utils'
import { IndexLoaderData } from 'lib/types' import { IndexLoaderData } from 'lib/types'
import { settings } from 'lib/settings/initialSettings' import { settings } from 'lib/settings/initialSettings'
import { import {
@ -55,11 +54,15 @@ type SettingsAuthContextType = {
settings: MachineContext<typeof settingsMachine> settings: MachineContext<typeof settingsMachine>
} }
// a little hacky for sure, open to changing it /**
// this implies that we should only even have one instance of this provider mounted at any one time * This variable is used to store the last snapshot of the settings context
// but I think that's a safe assumption * for use outside of React, such as in `wasm.ts`. It is updated every time
let settingsStateRef: ContextFrom<typeof settingsMachine> | undefined * the settings machine changes with `useSelector`.
export const getSettingsState = () => settingsStateRef * TODO: when we decouple XState from React, we can just subscribe to the actor directly from `wasm.ts`
*/
export let lastSettingsContextSnapshot:
| ContextFrom<typeof settingsMachine>
| undefined
export const SettingsAuthContext = createContext({} as SettingsAuthContextType) export const SettingsAuthContext = createContext({} as SettingsAuthContextType)
@ -129,27 +132,11 @@ export const SettingsAuthProviderBase = ({
.setTheme(context.app.theme.current) .setTheme(context.app.theme.current)
.catch(reportRejection) .catch(reportRejection)
}, },
setEngineScaleGridVisibility: ({ context }) => {
engineCommandManager.setScaleGridVisibility(
context.modeling.showScaleGrid.current
)
},
setClientTheme: ({ context }) => { setClientTheme: ({ context }) => {
const opposingTheme = getOppositeTheme(context.app.theme.current) const opposingTheme = getOppositeTheme(context.app.theme.current)
sceneInfra.theme = opposingTheme sceneInfra.theme = opposingTheme
sceneEntitiesManager.updateSegmentBaseColor(opposingTheme) sceneEntitiesManager.updateSegmentBaseColor(opposingTheme)
}, },
setEngineEdges: ({ context }) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
engineCommandManager.sendSceneCommand({
cmd_id: uuidv4(),
type: 'modeling_cmd_req',
cmd: {
type: 'edge_lines_visible' as any, // TODO update kittycad.ts to get this new command type
hidden: !context.modeling.highlightEdges.current,
},
})
},
toastSuccess: ({ event }) => { toastSuccess: ({ event }) => {
if (!('data' in event)) return if (!('data' in event)) return
const eventParts = event.type.replace(/^set./, '').split('.') as [ const eventParts = event.type.replace(/^set./, '').split('.') as [
@ -175,17 +162,27 @@ export const SettingsAuthProviderBase = ({
}, },
'Execute AST': ({ context, event }) => { 'Execute AST': ({ context, event }) => {
try { try {
const relevantSetting = (s: typeof settings) => {
return (
s.modeling?.defaultUnit?.current !==
context.modeling.defaultUnit.current ||
s.modeling.showScaleGrid.current !==
context.modeling.showScaleGrid.current ||
s.modeling?.highlightEdges.current !==
context.modeling.highlightEdges.current
)
}
const allSettingsIncludesUnitChange = const allSettingsIncludesUnitChange =
event.type === 'Set all settings' && event.type === 'Set all settings' &&
event.settings?.modeling?.defaultUnit?.current !== relevantSetting(event.settings)
context.modeling.defaultUnit.current
const resetSettingsIncludesUnitChange = const resetSettingsIncludesUnitChange =
event.type === 'Reset settings' && event.type === 'Reset settings' && relevantSetting(settings)
context.modeling.defaultUnit.current !==
settings?.modeling?.defaultUnit?.default
if ( if (
event.type === 'set.modeling.defaultUnit' || event.type === 'set.modeling.defaultUnit' ||
event.type === 'set.modeling.showScaleGrid' ||
event.type === 'set.modeling.highlightEdges' ||
allSettingsIncludesUnitChange || allSettingsIncludesUnitChange ||
resetSettingsIncludesUnitChange resetSettingsIncludesUnitChange
) { ) {
@ -214,7 +211,10 @@ export const SettingsAuthProviderBase = ({
}), }),
{ input: loadedSettings } { input: loadedSettings }
) )
settingsStateRef = settingsState.context // Any time the actor changes, update the settings state for external use
useSelector(settingsActor, (s) => {
lastSettingsContextSnapshot = s.context
})
useEffect(() => { useEffect(() => {
if (!isDesktop()) return if (!isDesktop()) return

View File

@ -20,6 +20,7 @@ import { IndexLoaderData } from 'lib/types'
import { useCommandsContext } from 'hooks/useCommandsContext' import { useCommandsContext } from 'hooks/useCommandsContext'
import { err, reportRejection } from 'lib/trap' import { err, reportRejection } from 'lib/trap'
import { getArtifactOfTypes } from 'lang/std/artifactGraph' import { getArtifactOfTypes } from 'lang/std/artifactGraph'
import { ViewControlContextMenu } from './ViewControlMenu'
enum StreamState { enum StreamState {
Playing = 'playing', Playing = 'playing',
@ -30,6 +31,7 @@ enum StreamState {
export const Stream = () => { export const Stream = () => {
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const videoWrapperRef = useRef<HTMLDivElement>(null)
const videoRef = useRef<HTMLVideoElement>(null) const videoRef = useRef<HTMLVideoElement>(null)
const { settings } = useSettingsAuthContext() const { settings } = useSettingsAuthContext()
const { state, send } = useModelingContext() const { state, send } = useModelingContext()
@ -258,7 +260,7 @@ export const Stream = () => {
setIsLoading(false) setIsLoading(false)
}, [mediaStream]) }, [mediaStream])
const handleMouseUp: MouseEventHandler<HTMLDivElement> = (e) => { const handleClick: MouseEventHandler<HTMLDivElement> = (e) => {
// If we've got no stream or connection, don't do anything // If we've got no stream or connection, don't do anything
if (!isNetworkOkay) return if (!isNetworkOkay) return
if (!videoRef.current) return if (!videoRef.current) return
@ -320,10 +322,11 @@ export const Stream = () => {
return ( return (
<div <div
ref={videoWrapperRef}
className="absolute inset-0 z-0" className="absolute inset-0 z-0"
id="stream" id="stream"
data-testid="stream" data-testid="stream"
onClick={handleMouseUp} onClick={handleClick}
onDoubleClick={enterSketchModeIfSelectingSketch} onDoubleClick={enterSketchModeIfSelectingSketch}
onContextMenu={(e) => e.preventDefault()} onContextMenu={(e) => e.preventDefault()}
onContextMenuCapture={(e) => e.preventDefault()} onContextMenuCapture={(e) => e.preventDefault()}
@ -384,6 +387,14 @@ export const Stream = () => {
</Loading> </Loading>
</div> </div>
)} )}
<ViewControlContextMenu
event="mouseup"
guard={(e) =>
sceneInfra.camControls.wasDragging === false &&
btnName(e).right === true
}
menuTargetElement={videoWrapperRef}
/>
</div> </div>
) )
} }

View File

@ -2,6 +2,7 @@ import toast from 'react-hot-toast'
import { ActionButton } from './ActionButton' import { ActionButton } from './ActionButton'
import { openExternalBrowserIfDesktop } from 'lib/openWindow' import { openExternalBrowserIfDesktop } from 'lib/openWindow'
import { Marked } from '@ts-stack/markdown' import { Marked } from '@ts-stack/markdown'
import { getReleaseUrl } from 'routes/Settings'
export function ToastUpdate({ export function ToastUpdate({
version, version,
@ -32,10 +33,8 @@ export function ToastUpdate({
A new update has downloaded and will be available next time you A new update has downloaded and will be available next time you
start the app. You can view the release notes{' '} start the app. You can view the release notes{' '}
<a <a
onClick={openExternalBrowserIfDesktop( onClick={openExternalBrowserIfDesktop(getReleaseUrl(version))}
`https://github.com/KittyCAD/modeling-app/releases/tag/v${version}` href={getReleaseUrl(version)}
)}
href={`https://github.com/KittyCAD/modeling-app/releases/tag/v${version}`}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
> >

View File

@ -41,7 +41,10 @@ export function UnitsMenu() {
close() close()
}} }}
> >
{baseUnitLabels[unit]} <span className="flex-1">{baseUnitLabels[unit]}</span>
{unit === settings.context.modeling.defaultUnit.current && (
<span className="text-chalkboard-60">current</span>
)}
</button> </button>
</li> </li>
))} ))}

View File

@ -0,0 +1,66 @@
import { reportRejection } from 'lib/trap'
import {
ContextMenu,
ContextMenuDivider,
ContextMenuItem,
ContextMenuItemRefresh,
ContextMenuProps,
} from './ContextMenu'
import { AxisNames, VIEW_NAMES_SEMANTIC } from 'lib/constants'
import { useModelingContext } from 'hooks/useModelingContext'
import { useMemo } from 'react'
import { sceneInfra } from 'lib/singletons'
export function useViewControlMenuItems() {
const { send: modelingSend } = useModelingContext()
const menuItems = useMemo(
() => [
...Object.entries(VIEW_NAMES_SEMANTIC).map(([axisName, axisSemantic]) => (
<ContextMenuItem
key={axisName}
onClick={() => {
sceneInfra.camControls
.updateCameraToAxis(axisName as AxisNames)
.catch(reportRejection)
}}
>
{axisSemantic} view
</ContextMenuItem>
)),
<ContextMenuDivider />,
<ContextMenuItem
onClick={() => {
sceneInfra.camControls.resetCameraPosition().catch(reportRejection)
}}
>
Reset view
</ContextMenuItem>,
<ContextMenuItem
onClick={() => {
modelingSend({ type: 'Center camera on selection' })
}}
>
Center view on selection
</ContextMenuItem>,
<ContextMenuDivider />,
<ContextMenuItemRefresh />,
],
[VIEW_NAMES_SEMANTIC]
)
return menuItems
}
export function ViewControlContextMenu({
menuTargetElement: wrapperRef,
...props
}: ContextMenuProps) {
const menuItems = useViewControlMenuItems()
return (
<ContextMenu
data-testid="view-controls-menu"
menuTargetElement={wrapperRef}
items={menuItems}
{...props}
/>
)
}

View File

@ -0,0 +1,327 @@
import {
EditorView,
WidgetType,
ViewUpdate,
ViewPlugin,
DecorationSet,
Decoration,
} from '@codemirror/view'
import { Range, Extension, Text } from '@codemirror/state'
import { NodeProp, Tree } from '@lezer/common'
import { language, syntaxTree } from '@codemirror/language'
interface PickerState {
from: number
to: number
alpha: string
colorType: ColorType
}
export interface WidgetOptions extends PickerState {
color: string
}
export type ColorData = Omit<WidgetOptions, 'from' | 'to'>
const pickerState = new WeakMap<HTMLInputElement, PickerState>()
export enum ColorType {
hex = 'HEX',
}
const hexRegex = /(^|\b)(#[0-9a-f]{3,9})(\b|$)/i
function discoverColorsInKCL(
syntaxTree: Tree,
from: number,
to: number,
typeName: string,
doc: Text,
language?: string
): WidgetOptions | Array<WidgetOptions> | null {
switch (typeName) {
case 'Program':
case 'VariableDeclaration':
case 'CallExpression':
case 'ObjectExpression':
case 'ObjectProperty':
case 'ArgumentList':
case 'PipeExpression': {
let innerTree = syntaxTree.resolveInner(from, 0).tree
if (!innerTree) {
innerTree = syntaxTree.resolveInner(from, 1).tree
if (!innerTree) {
return null
}
}
const overlayTree = innerTree.prop(NodeProp.mounted)?.tree
if (overlayTree?.type.name !== 'Styles') {
return null
}
const ret: Array<WidgetOptions> = []
overlayTree.iterate({
from: 0,
to: overlayTree.length,
enter: ({ type, from: overlayFrom, to: overlayTo }) => {
const maybeWidgetOptions = discoverColorsInKCL(
syntaxTree,
// We add one because the tree doesn't include the
// quotation mark from the style tag
from + 1 + overlayFrom,
from + 1 + overlayTo,
type.name,
doc,
language
)
if (maybeWidgetOptions) {
if (Array.isArray(maybeWidgetOptions)) {
console.error('Unexpected nested overlays')
ret.push(...maybeWidgetOptions)
} else {
ret.push(maybeWidgetOptions)
}
}
},
})
return ret
}
case 'String': {
const result = parseColorLiteral(doc.sliceString(from, to))
if (!result) {
return null
}
return {
...result,
from,
to,
}
}
default:
return null
}
}
export function parseColorLiteral(colorLiteral: string): ColorData | null {
const literal = colorLiteral.replace(/"/g, '')
const match = hexRegex.exec(literal)
if (!match) {
return null
}
const [color, alpha] = toFullHex(literal)
return {
colorType: ColorType.hex,
color,
alpha,
}
}
function colorPickersDecorations(
view: EditorView,
discoverColors: typeof discoverColorsInKCL
) {
const widgets: Array<Range<Decoration>> = []
const st = syntaxTree(view.state)
for (const range of view.visibleRanges) {
st.iterate({
from: range.from,
to: range.to,
enter: ({ type, from, to }) => {
const maybeWidgetOptions = discoverColors(
st,
from,
to,
type.name,
view.state.doc,
view.state.facet(language)?.name
)
if (!maybeWidgetOptions) {
return
}
if (!Array.isArray(maybeWidgetOptions)) {
widgets.push(
Decoration.widget({
widget: new ColorPickerWidget(maybeWidgetOptions),
side: 1,
}).range(maybeWidgetOptions.from)
)
return
}
for (const wo of maybeWidgetOptions) {
widgets.push(
Decoration.widget({
widget: new ColorPickerWidget(wo),
side: 1,
}).range(wo.from)
)
}
},
})
}
return Decoration.set(widgets)
}
function toFullHex(color: string): string[] {
if (color.length === 4) {
// 3-char hex
return [
`#${color[1].repeat(2)}${color[2].repeat(2)}${color[3].repeat(2)}`,
'',
]
}
if (color.length === 5) {
// 4-char hex (alpha)
return [
`#${color[1].repeat(2)}${color[2].repeat(2)}${color[3].repeat(2)}`,
color[4].repeat(2),
]
}
if (color.length === 9) {
// 8-char hex (alpha)
return [`#${color.slice(1, -2)}`, color.slice(-2)]
}
return [color, '']
}
export const wrapperClassName = 'cm-css-color-picker-wrapper'
class ColorPickerWidget extends WidgetType {
private readonly state: PickerState
private readonly color: string
constructor({ color, ...state }: WidgetOptions) {
super()
this.state = state
this.color = color
}
eq(other: ColorPickerWidget) {
return (
other.state.colorType === this.state.colorType &&
other.color === this.color &&
other.state.from === this.state.from &&
other.state.to === this.state.to &&
other.state.alpha === this.state.alpha
)
}
toDOM() {
const picker = document.createElement('input')
pickerState.set(picker, this.state)
picker.type = 'color'
picker.value = this.color
const wrapper = document.createElement('span')
wrapper.appendChild(picker)
wrapper.className = wrapperClassName
return wrapper
}
ignoreEvent() {
return false
}
}
export const colorPickerTheme = EditorView.baseTheme({
[`.${wrapperClassName}`]: {
display: 'inline-block',
outline: '1px solid #eee',
marginRight: '0.6ch',
height: '1em',
width: '1em',
transform: 'translateY(1px)',
},
[`.${wrapperClassName} input[type="color"]`]: {
cursor: 'pointer',
height: '100%',
width: '100%',
padding: 0,
border: 'none',
'&::-webkit-color-swatch-wrapper': {
padding: 0,
},
'&::-webkit-color-swatch': {
border: 'none',
},
'&::-moz-color-swatch': {
border: 'none',
},
},
})
interface IFactoryOptions {
discoverColors: typeof discoverColorsInKCL
}
export const makeColorPicker = (options: IFactoryOptions) =>
ViewPlugin.fromClass(
class ColorPickerViewPlugin {
decorations: DecorationSet
constructor(view: EditorView) {
this.decorations = colorPickersDecorations(view, options.discoverColors)
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged) {
this.decorations = colorPickersDecorations(
update.view,
options.discoverColors
)
}
}
},
{
decorations: (v) => v.decorations,
eventHandlers: {
change: (e, view) => {
const target = e.target as HTMLInputElement
if (
target.nodeName !== 'INPUT' ||
!target.parentElement ||
!target.parentElement.classList.contains(wrapperClassName)
) {
return false
}
const data = pickerState.get(target)!
let converted = '"' + target.value + data.alpha + '"'
view.dispatch({
changes: {
from: data.from,
to: data.to,
insert: converted,
},
})
return true
},
},
}
)
export const colorPicker: Extension = [
makeColorPicker({ discoverColors: discoverColorsInKCL }),
colorPickerTheme,
]

View File

@ -12,6 +12,7 @@ export const kclHighlight = styleTags({
'AddOp MultOp ExpOp': t.arithmeticOperator, 'AddOp MultOp ExpOp': t.arithmeticOperator,
BangOp: t.logicOperator, BangOp: t.logicOperator,
CompOp: t.compareOperator, CompOp: t.compareOperator,
LogicOp: t.logicOperator,
'Equals Arrow': t.definitionOperator, 'Equals Arrow': t.definitionOperator,
PipeOperator: t.controlOperator, PipeOperator: t.controlOperator,
String: t.string, String: t.string,

View File

@ -5,6 +5,7 @@
mult @left mult @left
add @left add @left
comp @left comp @left
logic @left
pipe @left pipe @left
range range
} }
@ -40,7 +41,8 @@ expression[@isGroup=Expression] {
expression !add AddOp expression | expression !add AddOp expression |
expression !mult MultOp expression | expression !mult MultOp expression |
expression !exp ExpOp expression | expression !exp ExpOp expression |
expression !comp CompOp expression expression !comp CompOp expression |
expression !logic LogicOp expression
} | } |
UnaryExpression { UnaryOp expression } | UnaryExpression { UnaryOp expression } |
ParenthesizedExpression { "(" expression ")" } | ParenthesizedExpression { "(" expression ")" } |
@ -89,6 +91,7 @@ commaSep1NoTrailingComma<term> { term ("," term)* }
AddOp { "+" | "-" } AddOp { "+" | "-" }
MultOp { "/" | "*" | "\\" } MultOp { "/" | "*" | "\\" }
ExpOp { "^" } ExpOp { "^" }
LogicOp { "|" | "&" }
BangOp { "!" } BangOp { "!" }
CompOp { "==" | "!=" | "<=" | ">=" | "<" | ">" } CompOp { "==" | "!=" | "<=" | ">=" | "<" | ">" }
Equals { "=" } Equals { "=" }

View File

@ -17,6 +17,7 @@ import { kclPlugin } from '.'
import type * as LSP from 'vscode-languageserver-protocol' import type * as LSP from 'vscode-languageserver-protocol'
// @ts-ignore: No types available // @ts-ignore: No types available
import { parser } from './kcl.grammar' import { parser } from './kcl.grammar'
import { colorPicker } from './colors'
export interface LanguageOptions { export interface LanguageOptions {
workspaceFolders: LSP.WorkspaceFolder[] workspaceFolders: LSP.WorkspaceFolder[]
@ -54,14 +55,14 @@ export const KclLanguage = LRLanguage.define({
}) })
export function kcl(options: LanguageOptions) { export function kcl(options: LanguageOptions) {
return new LanguageSupport( return new LanguageSupport(KclLanguage, [
KclLanguage, colorPicker,
kclPlugin({ kclPlugin({
documentUri: options.documentUri, documentUri: options.documentUri,
workspaceFolders: options.workspaceFolders, workspaceFolders: options.workspaceFolders,
allowHTMLContent: true, allowHTMLContent: true,
client: options.client, client: options.client,
processLspNotification: options.processLspNotification, processLspNotification: options.processLspNotification,
}) }),
) ])
} }

View File

@ -1,7 +1,5 @@
import { LspWorkerEventType } from '@kittycad/codemirror-lsp-client' import { LspWorkerEventType } from '@kittycad/codemirror-lsp-client'
import { UnitLength } from 'wasm-lib/kcl/bindings/UnitLength'
export enum LspWorker { export enum LspWorker {
Kcl = 'kcl', Kcl = 'kcl',
Copilot = 'copilot', Copilot = 'copilot',
@ -9,7 +7,6 @@ export enum LspWorker {
export interface KclWorkerOptions { export interface KclWorkerOptions {
wasmUrl: string wasmUrl: string
token: string token: string
baseUnit: UnitLength
apiBaseUrl: string apiBaseUrl: string
} }

View File

@ -17,7 +17,6 @@ import {
KclWorkerOptions, KclWorkerOptions,
CopilotWorkerOptions, CopilotWorkerOptions,
} from 'editor/plugins/lsp/types' } from 'editor/plugins/lsp/types'
import { EngineCommandManager } from 'lang/std/engineConnection'
import { err, reportRejection } from 'lib/trap' import { err, reportRejection } from 'lib/trap'
const intoServer: IntoServer = new IntoServer() const intoServer: IntoServer = new IntoServer()
@ -46,14 +45,12 @@ export async function copilotLspRun(
export async function kclLspRun( export async function kclLspRun(
config: ServerConfig, config: ServerConfig,
engineCommandManager: EngineCommandManager | null,
token: string, token: string,
baseUnit: string,
baseUrl: string baseUrl: string
) { ) {
try { try {
console.log('start kcl lsp') console.log('start kcl lsp')
await kcl_lsp_run(config, engineCommandManager, baseUnit, token, baseUrl) await kcl_lsp_run(config, null, undefined, token, baseUrl)
} catch (e: any) { } catch (e: any) {
console.log('kcl lsp failed', e) console.log('kcl lsp failed', e)
// We can't restart here because a moved value, we should do this another way. // We can't restart here because a moved value, we should do this another way.
@ -82,13 +79,7 @@ onmessage = function (event: MessageEvent) {
switch (worker) { switch (worker) {
case LspWorker.Kcl: case LspWorker.Kcl:
const kclData = eventData as KclWorkerOptions const kclData = eventData as KclWorkerOptions
await kclLspRun( await kclLspRun(config, kclData.token, kclData.apiBaseUrl)
config,
null,
kclData.token,
kclData.baseUnit,
kclData.apiBaseUrl
)
break break
case LspWorker.Copilot: case LspWorker.Copilot:
let copilotData = eventData as CopilotWorkerOptions let copilotData = eventData as CopilotWorkerOptions

View File

@ -2,7 +2,7 @@ import { useLayoutEffect, useEffect, useRef } from 'react'
import { engineCommandManager, kclManager } from 'lib/singletons' import { engineCommandManager, kclManager } from 'lib/singletons'
import { deferExecution } from 'lib/utils' import { deferExecution } from 'lib/utils'
import { Themes } from 'lib/theme' import { Themes } from 'lib/theme'
import { makeDefaultPlanes, modifyGrid } from 'lang/wasm' import { makeDefaultPlanes } from 'lang/wasm'
import { useModelingContext } from './useModelingContext' import { useModelingContext } from './useModelingContext'
import { useNetworkContext } from 'hooks/useNetworkContext' import { useNetworkContext } from 'hooks/useNetworkContext'
import { useAppState, useAppStream } from 'AppState' import { useAppState, useAppStream } from 'AppState'
@ -56,9 +56,6 @@ export function useSetupEngineManager(
makeDefaultPlanes: () => { makeDefaultPlanes: () => {
return makeDefaultPlanes(kclManager.engineCommandManager) return makeDefaultPlanes(kclManager.engineCommandManager)
}, },
modifyGrid: (hidden: boolean) => {
return modifyGrid(kclManager.engineCommandManager, hidden)
},
}) })
hasSetNonZeroDimensions.current = true hasSetNonZeroDimensions.current = true
} }

View File

@ -317,3 +317,8 @@ code {
#code-mirror-override .cm-editor { #code-mirror-override .cm-editor {
height: 100% !important; height: 100% !important;
} }
/* Can't use #code-mirror-override here as we're outside of this div */
.body-bg .cm-diagnosticAction {
@apply bg-primary;
}

View File

@ -311,8 +311,6 @@ export class KclManager {
// Do not send send scene commands if the program was interrupted, go to clean up // Do not send send scene commands if the program was interrupted, go to clean up
if (!isInterrupted) { if (!isInterrupted) {
this.addDiagnostics(await lintAst({ ast: ast })) this.addDiagnostics(await lintAst({ ast: ast }))
sceneInfra.modelingSend({ type: 'code edit during sketch' })
setSelectionFilterToDefault(execState.memory, this.engineCommandManager) setSelectionFilterToDefault(execState.memory, this.engineCommandManager)
if (args.zoomToFit) { if (args.zoomToFit) {
@ -358,7 +356,13 @@ export class KclManager {
this.lastSuccessfulProgramMemory = execState.memory this.lastSuccessfulProgramMemory = execState.memory
} }
this.ast = { ...ast } this.ast = { ...ast }
// updateArtifactGraph relies on updated executeState/programMemory
await this.engineCommandManager.updateArtifactGraph(this.ast)
this._executeCallback() this._executeCallback()
if (!isInterrupted) {
sceneInfra.modelingSend({ type: 'code edit during sketch' })
}
this.engineCommandManager.addCommandLog({ this.engineCommandManager.addCommandLog({
type: 'execution-done', type: 'execution-done',
data: null, data: null,

View File

@ -9,6 +9,7 @@ describe('test kclErrToDiagnostic', () => {
kind: 'semantic', kind: 'semantic',
msg: 'Semantic error', msg: 'Semantic error',
sourceRange: [0, 1, true], sourceRange: [0, 1, true],
operations: [],
}, },
{ {
name: '', name: '',
@ -16,6 +17,7 @@ describe('test kclErrToDiagnostic', () => {
kind: 'type', kind: 'type',
msg: 'Type error', msg: 'Type error',
sourceRange: [4, 5, true], sourceRange: [4, 5, true],
operations: [],
}, },
] ]
const diagnostics = kclErrorsToDiagnostics(errors) const diagnostics = kclErrorsToDiagnostics(errors)

View File

@ -6,85 +6,94 @@ import { Diagnostic as LspDiagnostic } from 'vscode-languageserver-protocol'
import { Text } from '@codemirror/state' import { Text } from '@codemirror/state'
import { EditorView } from 'codemirror' import { EditorView } from 'codemirror'
import { SourceRange } from 'lang/wasm' import { SourceRange } from 'lang/wasm'
import { Operation } from 'wasm-lib/kcl/bindings/Operation'
type ExtractKind<T> = T extends { kind: infer K } ? K : never type ExtractKind<T> = T extends { kind: infer K } ? K : never
export class KCLError extends Error { export class KCLError extends Error {
kind: ExtractKind<RustKclError> | 'name' kind: ExtractKind<RustKclError> | 'name'
sourceRange: SourceRange sourceRange: SourceRange
msg: string msg: string
operations: Operation[]
constructor( constructor(
kind: ExtractKind<RustKclError> | 'name', kind: ExtractKind<RustKclError> | 'name',
msg: string, msg: string,
sourceRange: SourceRange sourceRange: SourceRange,
operations: Operation[]
) { ) {
super() super()
this.kind = kind this.kind = kind
this.msg = msg this.msg = msg
this.sourceRange = sourceRange this.sourceRange = sourceRange
this.operations = operations
Object.setPrototypeOf(this, KCLError.prototype) Object.setPrototypeOf(this, KCLError.prototype)
} }
} }
export class KCLLexicalError extends KCLError { export class KCLLexicalError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('lexical', msg, sourceRange) super('lexical', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLSyntaxError.prototype) Object.setPrototypeOf(this, KCLSyntaxError.prototype)
} }
} }
export class KCLInternalError extends KCLError { export class KCLInternalError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('internal', msg, sourceRange) super('internal', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLSyntaxError.prototype) Object.setPrototypeOf(this, KCLSyntaxError.prototype)
} }
} }
export class KCLSyntaxError extends KCLError { export class KCLSyntaxError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('syntax', msg, sourceRange) super('syntax', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLSyntaxError.prototype) Object.setPrototypeOf(this, KCLSyntaxError.prototype)
} }
} }
export class KCLSemanticError extends KCLError { export class KCLSemanticError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('semantic', msg, sourceRange) super('semantic', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLSemanticError.prototype) Object.setPrototypeOf(this, KCLSemanticError.prototype)
} }
} }
export class KCLTypeError extends KCLError { export class KCLTypeError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('type', msg, sourceRange) super('type', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLTypeError.prototype) Object.setPrototypeOf(this, KCLTypeError.prototype)
} }
} }
export class KCLUnimplementedError extends KCLError { export class KCLUnimplementedError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('unimplemented', msg, sourceRange) super('unimplemented', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLUnimplementedError.prototype) Object.setPrototypeOf(this, KCLUnimplementedError.prototype)
} }
} }
export class KCLUnexpectedError extends KCLError { export class KCLUnexpectedError extends KCLError {
constructor(msg: string, sourceRange: SourceRange) { constructor(msg: string, sourceRange: SourceRange, operations: Operation[]) {
super('unexpected', msg, sourceRange) super('unexpected', msg, sourceRange, operations)
Object.setPrototypeOf(this, KCLUnexpectedError.prototype) Object.setPrototypeOf(this, KCLUnexpectedError.prototype)
} }
} }
export class KCLValueAlreadyDefined extends KCLError { export class KCLValueAlreadyDefined extends KCLError {
constructor(key: string, sourceRange: SourceRange) { constructor(key: string, sourceRange: SourceRange, operations: Operation[]) {
super('name', `Key ${key} was already defined elsewhere`, sourceRange) super(
'name',
`Key ${key} was already defined elsewhere`,
sourceRange,
operations
)
Object.setPrototypeOf(this, KCLValueAlreadyDefined.prototype) Object.setPrototypeOf(this, KCLValueAlreadyDefined.prototype)
} }
} }
export class KCLUndefinedValueError extends KCLError { export class KCLUndefinedValueError extends KCLError {
constructor(key: string, sourceRange: SourceRange) { constructor(key: string, sourceRange: SourceRange, operations: Operation[]) {
super('name', `Key ${key} has not been defined`, sourceRange) super('name', `Key ${key} has not been defined`, sourceRange, operations)
Object.setPrototypeOf(this, KCLUndefinedValueError.prototype) Object.setPrototypeOf(this, KCLUndefinedValueError.prototype)
} }
} }
@ -100,11 +109,12 @@ export function lspDiagnosticsToKclErrors(
return diagnostics return diagnostics
.flatMap( .flatMap(
({ range, message }) => ({ range, message }) =>
new KCLError('unexpected', message, [ new KCLError(
posToOffset(doc, range.start)!, 'unexpected',
posToOffset(doc, range.end)!, message,
true, [posToOffset(doc, range.start)!, posToOffset(doc, range.end)!, true],
]) []
)
) )
.sort((a, b) => { .sort((a, b) => {
const c = a.sourceRange[0] const c = a.sourceRange[0]

View File

@ -480,7 +480,8 @@ const theExtrude = startSketchOn('XY')
new KCLError( new KCLError(
'undefined_value', 'undefined_value',
'memory item key `myVarZ` is not defined', 'memory item key `myVarZ` is not defined',
[129, 135, true] [129, 135, true],
[]
) )
) )
}) })

View File

@ -66,9 +66,7 @@ export async function executeAst({
? enginelessExecutor(ast, programMemoryOverride) ? enginelessExecutor(ast, programMemoryOverride)
: _executor(ast, engineCommandManager)) : _executor(ast, engineCommandManager))
await engineCommandManager.waitForAllCommands( await engineCommandManager.waitForAllCommands()
programMemoryOverride !== undefined
)
return { return {
logs: [], logs: [],

View File

@ -40,7 +40,6 @@ beforeAll(async () => {
makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager), makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager),
setMediaStream: () => {}, setMediaStream: () => {},
setIsStreamReady: () => {}, setIsStreamReady: () => {},
modifyGrid: async () => {},
callbackOnEngineLiteConnect: () => { callbackOnEngineLiteConnect: () => {
resolve(true) resolve(true)
}, },
@ -248,7 +247,7 @@ extrude003 = extrude(-15, sketch003)`
selectedSegmentSnippet, selectedSegmentSnippet,
expectedExtrudeSnippet expectedExtrudeSnippet
) )
}) }, 5_000)
}) })
const runModifyAstCloneWithEdgeTreatmentAndTag = async ( const runModifyAstCloneWithEdgeTreatmentAndTag = async (
@ -478,7 +477,7 @@ extrude001 = extrude(-15, sketch001)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(-15, sketch001) extrude001 = extrude(-15, sketch001)
|> chamfer({ length: 5, tags: [seg01] }, %)` |> chamfer({ length = 5, tags = [seg01] }, %)`
const segmentSnippets = ['line([-20, 0], %)'] const segmentSnippets = ['line([-20, 0], %)']
const expectedCode = `sketch001 = startSketchOn('XY') const expectedCode = `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, 10], %) |> startProfileAt([-10, 10], %)
@ -488,8 +487,8 @@ extrude001 = extrude(-15, sketch001)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(-15, sketch001) extrude001 = extrude(-15, sketch001)
|> chamfer({ length: 5, tags: [seg01] }, %) |> chamfer({ length = 5, tags = [seg01] }, %)
|> ${edgeTreatmentType}({ ${parameterName}: 3, tags: [seg02] }, %)` |> ${edgeTreatmentType}({ ${parameterName} = 3, tags = [seg02] }, %)`
await runModifyAstCloneWithEdgeTreatmentAndTag( await runModifyAstCloneWithEdgeTreatmentAndTag(
code, code,

View File

@ -397,6 +397,7 @@ function moreNodePathFromSourceRange(
} }
return path return path
} }
return path
} }
console.error('not implemented: ' + node.type) console.error('not implemented: ' + node.type)

View File

@ -13,7 +13,7 @@ Map {
"range": [ "range": [
12, 12,
31, 31,
0, true,
], ],
}, },
"id": "UUID", "id": "UUID",
@ -33,7 +33,7 @@ Map {
"range": [ "range": [
37, 37,
64, 64,
0, true,
], ],
}, },
"id": "UUID", "id": "UUID",
@ -60,7 +60,7 @@ Map {
"range": [ "range": [
70, 70,
86, 86,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -83,7 +83,7 @@ Map {
"range": [ "range": [
92, 92,
119, 119,
0, true,
], ],
}, },
"edgeCutId": "UUID", "edgeCutId": "UUID",
@ -107,7 +107,7 @@ Map {
"range": [ "range": [
125, 125,
150, 150,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -130,7 +130,7 @@ Map {
"range": [ "range": [
156, 156,
203, 203,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -153,7 +153,7 @@ Map {
"range": [ "range": [
209, 209,
217, 217,
0, true,
], ],
}, },
"edgeIds": [], "edgeIds": [],
@ -177,7 +177,7 @@ Map {
"range": [ "range": [
231, 231,
254, 254,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -320,7 +320,7 @@ Map {
"range": [ "range": [
260, 260,
299, 299,
0, true,
], ],
}, },
"consumedEdgeId": "UUID", "consumedEdgeId": "UUID",
@ -340,7 +340,7 @@ Map {
"range": [ "range": [
350, 350,
377, 377,
0, true,
], ],
}, },
"id": "UUID", "id": "UUID",
@ -366,7 +366,7 @@ Map {
"range": [ "range": [
383, 383,
398, 398,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -389,7 +389,7 @@ Map {
"range": [ "range": [
404, 404,
420, 420,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -412,7 +412,7 @@ Map {
"range": [ "range": [
426, 426,
473, 473,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -435,7 +435,7 @@ Map {
"range": [ "range": [
479, 479,
487, 487,
0, true,
], ],
}, },
"edgeIds": [], "edgeIds": [],
@ -459,7 +459,7 @@ Map {
"range": [ "range": [
501, 501,
522, 522,
0, true,
], ],
}, },
"edgeIds": [ "edgeIds": [
@ -478,7 +478,6 @@ Map {
"UUID", "UUID",
"UUID", "UUID",
"UUID", "UUID",
"UUID",
], ],
"type": "sweep", "type": "sweep",
}, },
@ -507,14 +506,6 @@ Map {
"type": "wall", "type": "wall",
}, },
"UUID-34" => { "UUID-34" => {
"edgeCutEdgeIds": [],
"id": "UUID",
"pathIds": [],
"subType": "start",
"sweepId": "UUID",
"type": "cap",
},
"UUID-35" => {
"edgeCutEdgeIds": [], "edgeCutEdgeIds": [],
"id": "UUID", "id": "UUID",
"pathIds": [], "pathIds": [],
@ -522,42 +513,42 @@ Map {
"sweepId": "UUID", "sweepId": "UUID",
"type": "cap", "type": "cap",
}, },
"UUID-36" => { "UUID-35" => {
"id": "UUID", "id": "UUID",
"segId": "UUID", "segId": "UUID",
"subType": "opposite", "subType": "opposite",
"sweepId": "UUID", "sweepId": "UUID",
"type": "sweepEdge", "type": "sweepEdge",
}, },
"UUID-36" => {
"id": "UUID",
"segId": "UUID",
"subType": "adjacent",
"sweepId": "UUID",
"type": "sweepEdge",
},
"UUID-37" => { "UUID-37" => {
"id": "UUID", "id": "UUID",
"segId": "UUID", "segId": "UUID",
"subType": "adjacent", "subType": "opposite",
"sweepId": "UUID", "sweepId": "UUID",
"type": "sweepEdge", "type": "sweepEdge",
}, },
"UUID-38" => { "UUID-38" => {
"id": "UUID", "id": "UUID",
"segId": "UUID", "segId": "UUID",
"subType": "opposite", "subType": "adjacent",
"sweepId": "UUID", "sweepId": "UUID",
"type": "sweepEdge", "type": "sweepEdge",
}, },
"UUID-39" => { "UUID-39" => {
"id": "UUID",
"segId": "UUID",
"subType": "adjacent",
"sweepId": "UUID",
"type": "sweepEdge",
},
"UUID-40" => {
"id": "UUID", "id": "UUID",
"segId": "UUID", "segId": "UUID",
"subType": "opposite", "subType": "opposite",
"sweepId": "UUID", "sweepId": "UUID",
"type": "sweepEdge", "type": "sweepEdge",
}, },
"UUID-41" => { "UUID-40" => {
"id": "UUID", "id": "UUID",
"segId": "UUID", "segId": "UUID",
"subType": "adjacent", "subType": "adjacent",

View File

@ -139,7 +139,6 @@ beforeAll(async () => {
makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager), makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager),
setMediaStream: () => {}, setMediaStream: () => {},
setIsStreamReady: () => {}, setIsStreamReady: () => {},
modifyGrid: async () => {},
// eslint-disable-next-line @typescript-eslint/no-misused-promises // eslint-disable-next-line @typescript-eslint/no-misused-promises
callbackOnEngineLiteConnect: async () => { callbackOnEngineLiteConnect: async () => {
const cacheEntries = Object.entries(codeToWriteCacheFor) as [ const cacheEntries = Object.entries(codeToWriteCacheFor) as [
@ -260,11 +259,13 @@ describe('testing createArtifactGraph', () => {
if (err(extrusion)) throw extrusion if (err(extrusion)) throw extrusion
expect(extrusion.type).toBe('sweep') expect(extrusion.type).toBe('sweep')
const firstExtrusionIsACubeIE6Sides = 6 const firstExtrusionIsACubeIE6Sides = 6
const secondExtrusionIsATriangularPrismIE5Sides = 5 // Each face of the triangular prism (5), but without the bottom cap.
// The engine doesn't generate that.
const secondExtrusionIsATriangularPrism = 4
expect(extrusion.surfaces.length).toBe( expect(extrusion.surfaces.length).toBe(
!index !index
? firstExtrusionIsACubeIE6Sides ? firstExtrusionIsACubeIE6Sides
: secondExtrusionIsATriangularPrismIE5Sides : secondExtrusionIsATriangularPrism
) )
}) })
}) })
@ -660,7 +661,7 @@ describe('testing getArtifactsToUpdate', () => {
sweepId: '', sweepId: '',
codeRef: { codeRef: {
pathToNode: [['body', '']], pathToNode: [['body', '']],
range: [37, 64, 0], range: [37, 64, true],
}, },
}, },
]) ])
@ -673,7 +674,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: [], surfaceIds: [],
edgeIds: [], edgeIds: [],
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -684,7 +685,7 @@ describe('testing getArtifactsToUpdate', () => {
planeId: expect.any(String), planeId: expect.any(String),
sweepId: expect.any(String), sweepId: expect.any(String),
codeRef: { codeRef: {
range: [37, 64, 0], range: [37, 64, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
solid2dId: expect.any(String), solid2dId: expect.any(String),
@ -698,7 +699,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceId: '', surfaceId: '',
edgeIds: [], edgeIds: [],
codeRef: { codeRef: {
range: [70, 86, 0], range: [70, 86, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -709,7 +710,7 @@ describe('testing getArtifactsToUpdate', () => {
planeId: expect.any(String), planeId: expect.any(String),
sweepId: expect.any(String), sweepId: expect.any(String),
codeRef: { codeRef: {
range: [37, 64, 0], range: [37, 64, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
solid2dId: expect.any(String), solid2dId: expect.any(String),
@ -724,7 +725,7 @@ describe('testing getArtifactsToUpdate', () => {
edgeIds: [], edgeIds: [],
surfaceId: '', surfaceId: '',
codeRef: { codeRef: {
range: [260, 299, 0], range: [260, 299, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -735,7 +736,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceId: expect.any(String), surfaceId: expect.any(String),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [92, 119, 0], range: [92, 119, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
edgeCutId: expect.any(String), edgeCutId: expect.any(String),
@ -757,7 +758,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceId: expect.any(String), surfaceId: expect.any(String),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [156, 203, 0], range: [156, 203, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -769,7 +770,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: expect.any(Array), surfaceIds: expect.any(Array),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -788,7 +789,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceId: expect.any(String), surfaceId: expect.any(String),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [125, 150, 0], range: [125, 150, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -800,7 +801,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: expect.any(Array), surfaceIds: expect.any(Array),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -819,7 +820,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceId: expect.any(String), surfaceId: expect.any(String),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [92, 119, 0], range: [92, 119, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
edgeCutId: expect.any(String), edgeCutId: expect.any(String),
@ -832,7 +833,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: expect.any(Array), surfaceIds: expect.any(Array),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -851,7 +852,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceId: expect.any(String), surfaceId: expect.any(String),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [70, 86, 0], range: [70, 86, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -863,7 +864,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: expect.any(Array), surfaceIds: expect.any(Array),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -883,7 +884,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: expect.any(Array), surfaceIds: expect.any(Array),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },
@ -903,7 +904,7 @@ describe('testing getArtifactsToUpdate', () => {
surfaceIds: expect.any(Array), surfaceIds: expect.any(Array),
edgeIds: expect.any(Array), edgeIds: expect.any(Array),
codeRef: { codeRef: {
range: [231, 254, 0], range: [231, 254, true],
pathToNode: [['body', '']], pathToNode: [['body', '']],
}, },
}, },

View File

@ -871,15 +871,3 @@ export function codeRefFromRange(range: SourceRange, ast: Program): CodeRef {
pathToNode: getNodePathFromSourceRange(ast, range), pathToNode: getNodePathFromSourceRange(ast, range),
} }
} }
export function isSolid2D(artifact: Artifact): artifact is solid2D {
return (artifact as solid2D).pathId !== undefined
}
export function isSegment(artifact: Artifact): artifact is SegmentArtifact {
return (artifact as SegmentArtifact).pathId !== undefined
}
export function isSweep(artifact: Artifact): artifact is SweepArtifact {
return (artifact as SweepArtifact).pathId !== undefined
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 357 KiB

After

Width:  |  Height:  |  Size: 326 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 577 KiB

After

Width:  |  Height:  |  Size: 568 KiB

View File

@ -1,4 +1,11 @@
import { defaultSourceRange, SourceRange } from 'lang/wasm' import {
defaultRustSourceRange,
defaultSourceRange,
Program,
RustSourceRange,
SourceRange,
sourceRangeFromRust,
} from 'lang/wasm'
import { VITE_KC_API_WS_MODELING_URL, VITE_KC_DEV_TOKEN } from 'env' import { VITE_KC_API_WS_MODELING_URL, VITE_KC_DEV_TOKEN } from 'env'
import { Models } from '@kittycad/lib' import { Models } from '@kittycad/lib'
import { exportSave } from 'lib/exportSave' import { exportSave } from 'lib/exportSave'
@ -1302,8 +1309,8 @@ export enum EngineCommandManagerEvents {
interface PendingMessage { interface PendingMessage {
command: EngineCommand command: EngineCommand
range: SourceRange range: RustSourceRange
idToRangeMap: { [key: string]: SourceRange } idToRangeMap: { [key: string]: RustSourceRange }
resolve: (data: [Models['WebSocketResponse_type']]) => void resolve: (data: [Models['WebSocketResponse_type']]) => void
reject: (reason: string) => void reject: (reason: string) => void
promise: Promise<[Models['WebSocketResponse_type']]> promise: Promise<[Models['WebSocketResponse_type']]>
@ -1399,7 +1406,6 @@ export class EngineCommandManager extends EventTarget {
} }
private makeDefaultPlanes: () => Promise<DefaultPlanes> | null = () => null private makeDefaultPlanes: () => Promise<DefaultPlanes> | null = () => null
private modifyGrid: (hidden: boolean) => Promise<void> | null = () => null
private onEngineConnectionOpened = () => {} private onEngineConnectionOpened = () => {}
private onEngineConnectionClosed = () => {} private onEngineConnectionClosed = () => {}
@ -1432,7 +1438,6 @@ export class EngineCommandManager extends EventTarget {
height, height,
token, token,
makeDefaultPlanes, makeDefaultPlanes,
modifyGrid,
settings = { settings = {
pool: null, pool: null,
theme: Themes.Dark, theme: Themes.Dark,
@ -1452,14 +1457,12 @@ export class EngineCommandManager extends EventTarget {
height: number height: number
token?: string token?: string
makeDefaultPlanes: () => Promise<DefaultPlanes> makeDefaultPlanes: () => Promise<DefaultPlanes>
modifyGrid: (hidden: boolean) => Promise<void>
settings?: SettingsViaQueryString settings?: SettingsViaQueryString
}) { }) {
if (settings) { if (settings) {
this.settings = settings this.settings = settings
} }
this.makeDefaultPlanes = makeDefaultPlanes this.makeDefaultPlanes = makeDefaultPlanes
this.modifyGrid = modifyGrid
if (width === 0 || height === 0) { if (width === 0 || height === 0) {
return return
} }
@ -1539,21 +1542,15 @@ export class EngineCommandManager extends EventTarget {
type: 'default_camera_get_settings', type: 'default_camera_get_settings',
}, },
}) })
// We want modify the grid first because we don't want it to flash. await this.initPlanes()
// Ideally these would already be default hidden in engine (TODO do setIsStreamReady(true)
// that) https://github.com/KittyCAD/engine/issues/2282
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.modifyGrid(!this.settings.showScaleGrid)?.then(async () => {
await this.initPlanes()
setIsStreamReady(true)
// Other parts of the application should use this to react on scene ready. // Other parts of the application should use this to react on scene ready.
this.dispatchEvent( this.dispatchEvent(
new CustomEvent(EngineCommandManagerEvents.SceneReady, { new CustomEvent(EngineCommandManagerEvents.SceneReady, {
detail: this.engineConnection, detail: this.engineConnection,
}) })
) )
})
} }
this.engineConnection.addEventListener( this.engineConnection.addEventListener(
@ -2003,7 +2000,7 @@ export class EngineCommandManager extends EventTarget {
{ {
command, command,
idToRangeMap: {}, idToRangeMap: {},
range: defaultSourceRange(), range: defaultRustSourceRange(),
}, },
true // isSceneCommand true // isSceneCommand
) )
@ -2034,9 +2031,9 @@ export class EngineCommandManager extends EventTarget {
return Promise.reject(new Error('rangeStr is undefined')) return Promise.reject(new Error('rangeStr is undefined'))
if (commandStr === undefined) if (commandStr === undefined)
return Promise.reject(new Error('commandStr is undefined')) return Promise.reject(new Error('commandStr is undefined'))
const range: SourceRange = JSON.parse(rangeStr) const range: RustSourceRange = JSON.parse(rangeStr)
const command: EngineCommand = JSON.parse(commandStr) const command: EngineCommand = JSON.parse(commandStr)
const idToRangeMap: { [key: string]: SourceRange } = const idToRangeMap: { [key: string]: RustSourceRange } =
JSON.parse(idToRangeStr) JSON.parse(idToRangeStr)
// Current executeAst is stale, going to interrupt, a new executeAst will trigger // Current executeAst is stale, going to interrupt, a new executeAst will trigger
@ -2079,10 +2076,14 @@ export class EngineCommandManager extends EventTarget {
if (message.command.type === 'modeling_cmd_req') { if (message.command.type === 'modeling_cmd_req') {
this.orderedCommands.push({ this.orderedCommands.push({
command: message.command, command: message.command,
range: message.range, range: sourceRangeFromRust(message.range),
}) })
} else if (message.command.type === 'modeling_cmd_batch_req') { } else if (message.command.type === 'modeling_cmd_batch_req') {
message.command.requests.forEach((req) => { message.command.requests.forEach((req) => {
const cmdId = req.cmd_id || ''
const range = cmdId
? sourceRangeFromRust(message.idToRangeMap[cmdId])
: defaultSourceRange()
const cmd: EngineCommand = { const cmd: EngineCommand = {
type: 'modeling_cmd_req', type: 'modeling_cmd_req',
cmd_id: req.cmd_id, cmd_id: req.cmd_id,
@ -2090,7 +2091,7 @@ export class EngineCommandManager extends EventTarget {
} }
this.orderedCommands.push({ this.orderedCommands.push({
command: cmd, command: cmd,
range: message.idToRangeMap[req.cmd_id || ''], range,
}) })
}) })
} }
@ -2109,30 +2110,23 @@ export class EngineCommandManager extends EventTarget {
* When an execution takes place we want to wait until we've got replies for all of the commands * When an execution takes place we want to wait until we've got replies for all of the commands
* When this is done when we build the artifact map synchronously. * When this is done when we build the artifact map synchronously.
*/ */
async waitForAllCommands(useFakeExecutor = false) { waitForAllCommands() {
await Promise.all(Object.values(this.pendingCommands).map((a) => a.promise)) return Promise.all(
setTimeout(() => { Object.values(this.pendingCommands).map((a) => a.promise)
// the ast is wrong without this one tick timeout. )
// an example is `Solids should be select and deletable` e2e test will fail }
// because the out of date ast messes with selections updateArtifactGraph(ast: Program) {
// TODO: race condition this.artifactGraph = createArtifactGraph({
if (!this?.kclManager) return orderedCommands: this.orderedCommands,
this.artifactGraph = createArtifactGraph({ responseMap: this.responseMap,
orderedCommands: this.orderedCommands, ast,
responseMap: this.responseMap,
ast: this.kclManager.ast,
})
if (useFakeExecutor) {
// mock executions don't produce an artifactGraph, so this will always be empty
// skipping the below logic to wait for the next real execution
return
}
if (this.artifactGraph.size) {
this.deferredArtifactEmptied(null)
} else {
this.deferredArtifactPopulated(null)
}
}) })
// TODO check if these still need to be deferred once e2e tests are working again.
if (this.artifactGraph.size) {
this.deferredArtifactEmptied(null)
} else {
this.deferredArtifactPopulated(null)
}
} }
/** /**
@ -2212,15 +2206,6 @@ export class EngineCommandManager extends EventTarget {
}).catch(reportRejection) }).catch(reportRejection)
} }
/**
* Set the visibility of the scale grid in the engine scene.
* @param visible - whether to show or hide the scale grid
*/
setScaleGridVisibility(visible: boolean) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.modifyGrid(!visible)
}
// Some "objects" have the same source range, such as sketch_mode_start and start_path. // Some "objects" have the same source range, such as sketch_mode_start and start_path.
// So when passing a range, we need to also specify the command type // So when passing a range, we need to also specify the command type
mapRangeToObjectId( mapRangeToObjectId(

View File

@ -1,14 +1,13 @@
import init, { import init, {
parse_wasm, parse_wasm,
recast_wasm, recast_wasm,
execute_wasm, execute,
kcl_lint, kcl_lint,
modify_ast_for_sketch_wasm, modify_ast_for_sketch_wasm,
is_points_ccw, is_points_ccw,
get_tangential_arc_to_info, get_tangential_arc_to_info,
program_memory_init, program_memory_init,
make_default_planes, make_default_planes,
modify_grid,
coredump, coredump,
toml_stringify, toml_stringify,
default_app_settings, default_app_settings,
@ -43,7 +42,10 @@ import { Environment } from '../wasm-lib/kcl/bindings/Environment'
import { Node } from 'wasm-lib/kcl/bindings/Node' import { Node } from 'wasm-lib/kcl/bindings/Node'
import { CompilationError } from 'wasm-lib/kcl/bindings/CompilationError' import { CompilationError } from 'wasm-lib/kcl/bindings/CompilationError'
import { SourceRange as RustSourceRange } from 'wasm-lib/kcl/bindings/SourceRange' import { SourceRange as RustSourceRange } from 'wasm-lib/kcl/bindings/SourceRange'
import { getAllCurrentSettings } from 'lib/settings/settingsUtils'
import { KclErrorWithOutputs } from 'wasm-lib/kcl/bindings/KclErrorWithOutputs'
export type { Configuration } from 'wasm-lib/kcl/bindings/Configuration'
export type { Program } from '../wasm-lib/kcl/bindings/Program' export type { Program } from '../wasm-lib/kcl/bindings/Program'
export type { Expr } from '../wasm-lib/kcl/bindings/Expr' export type { Expr } from '../wasm-lib/kcl/bindings/Expr'
export type { ObjectExpression } from '../wasm-lib/kcl/bindings/ObjectExpression' export type { ObjectExpression } from '../wasm-lib/kcl/bindings/ObjectExpression'
@ -64,6 +66,7 @@ export type { BinaryPart } from '../wasm-lib/kcl/bindings/BinaryPart'
export type { Literal } from '../wasm-lib/kcl/bindings/Literal' export type { Literal } from '../wasm-lib/kcl/bindings/Literal'
export type { LiteralValue } from '../wasm-lib/kcl/bindings/LiteralValue' export type { LiteralValue } from '../wasm-lib/kcl/bindings/LiteralValue'
export type { ArrayExpression } from '../wasm-lib/kcl/bindings/ArrayExpression' export type { ArrayExpression } from '../wasm-lib/kcl/bindings/ArrayExpression'
export type { SourceRange as RustSourceRange } from 'wasm-lib/kcl/bindings/SourceRange'
export type SyntaxType = export type SyntaxType =
| 'Program' | 'Program'
@ -92,16 +95,37 @@ export type { Solid } from '../wasm-lib/kcl/bindings/Solid'
export type { KclValue } from '../wasm-lib/kcl/bindings/KclValue' export type { KclValue } from '../wasm-lib/kcl/bindings/KclValue'
export type { ExtrudeSurface } from '../wasm-lib/kcl/bindings/ExtrudeSurface' export type { ExtrudeSurface } from '../wasm-lib/kcl/bindings/ExtrudeSurface'
/**
* The first two items are the start and end points (byte offsets from the start of the file).
* The third item is whether the source range belongs to the 'main' file, i.e., the file currently
* being rendered/displayed in the editor (TODO we need to handle modules better in the frontend).
*/
export type SourceRange = [number, number, boolean] export type SourceRange = [number, number, boolean]
/**
* Convert a SourceRange as used inside the KCL interpreter into the above one for use in the
* frontend (essentially we're eagerly checking whether the frontend should care about the SourceRange
* so as not to expose details of the interpreter's current representation of module ids throughout
* the frontend).
*/
export function sourceRangeFromRust(s: RustSourceRange): SourceRange { export function sourceRangeFromRust(s: RustSourceRange): SourceRange {
return [s[0], s[1], s[2] === 0] return [s[0], s[1], s[2] === 0]
} }
/**
* Create a default SourceRange for testing or as a placeholder.
*/
export function defaultSourceRange(): SourceRange { export function defaultSourceRange(): SourceRange {
return [0, 0, true] return [0, 0, true]
} }
/**
* Create a default RustSourceRange for testing or as a placeholder.
*/
export function defaultRustSourceRange(): RustSourceRange {
return [0, 0, 0]
}
export const wasmUrl = () => { export const wasmUrl = () => {
// For when we're in electron (file based) or web server (network based) // For when we're in electron (file based) or web server (network based)
// For some reason relative paths don't work as expected. Otherwise we would // For some reason relative paths don't work as expected. Otherwise we would
@ -122,7 +146,7 @@ const initialise = async () => {
const fullUrl = wasmUrl() const fullUrl = wasmUrl()
const input = await fetch(fullUrl) const input = await fetch(fullUrl)
const buffer = await input.arrayBuffer() const buffer = await input.arrayBuffer()
return await init(buffer) return await init({ module_or_path: buffer })
} catch (e) { } catch (e) {
console.log('Error initialising WASM', e) console.log('Error initialising WASM', e)
return Promise.reject(e) return Promise.reject(e)
@ -163,6 +187,10 @@ export class ParseResult {
} }
} }
/**
* Parsing was successful. There is guaranteed to be an AST and no fatal errors. There may or may
* not be warnings or non-fatal errors.
*/
class SuccessParseResult extends ParseResult { class SuccessParseResult extends ParseResult {
program: Node<Program> program: Node<Program>
@ -193,7 +221,8 @@ export const parse = (code: string | Error): ParseResult | Error => {
return new KCLError( return new KCLError(
parsed.kind, parsed.kind,
parsed.msg, parsed.msg,
sourceRangeFromRust(parsed.sourceRanges[0]) sourceRangeFromRust(parsed.sourceRanges[0]),
[]
) )
} }
} }
@ -230,7 +259,7 @@ export function emptyExecState(): ExecState {
function execStateFromRaw(raw: RawExecState): ExecState { function execStateFromRaw(raw: RawExecState): ExecState {
return { return {
memory: ProgramMemory.fromRaw(raw.memory), memory: ProgramMemory.fromRaw(raw.modLocal.memory),
} }
} }
@ -493,29 +522,31 @@ export const _executor = async (
return Promise.reject(programMemoryOverride) return Promise.reject(programMemoryOverride)
try { try {
let baseUnit = 'mm' let jsAppSettings = default_app_settings()
if (!TEST) { if (!TEST) {
const getSettingsState = import('components/SettingsAuthProvider').then( const lastSettingsSnapshot = await import(
(module) => module.getSettingsState 'components/SettingsAuthProvider'
) ).then((module) => module.lastSettingsContextSnapshot)
baseUnit = if (lastSettingsSnapshot) {
(await getSettingsState)()?.modeling.defaultUnit.current || 'mm' jsAppSettings = getAllCurrentSettings(lastSettingsSnapshot)
}
} }
const execState: RawExecState = await execute_wasm( const execState: RawExecState = await execute(
JSON.stringify(node), JSON.stringify(node),
JSON.stringify(programMemoryOverride?.toRaw() || null), JSON.stringify(programMemoryOverride?.toRaw() || null),
baseUnit, JSON.stringify({ settings: jsAppSettings }),
engineCommandManager, engineCommandManager,
fileSystemManager fileSystemManager
) )
return execStateFromRaw(execState) return execStateFromRaw(execState)
} catch (e: any) { } catch (e: any) {
console.log(e) console.log(e)
const parsed: RustKclError = JSON.parse(e.toString()) const parsed: KclErrorWithOutputs = JSON.parse(e.toString())
const kclError = new KCLError( const kclError = new KCLError(
parsed.kind, parsed.error.kind,
parsed.msg, parsed.error.msg,
sourceRangeFromRust(parsed.sourceRanges[0]) sourceRangeFromRust(parsed.error.sourceRanges[0]),
parsed.operations
) )
return Promise.reject(kclError) return Promise.reject(kclError)
@ -552,20 +583,6 @@ export const makeDefaultPlanes = async (
} }
} }
export const modifyGrid = async (
engineCommandManager: EngineCommandManager,
hidden: boolean
): Promise<void> => {
try {
await modify_grid(engineCommandManager, hidden)
return
} catch (e) {
// TODO: do something real with the error.
console.log('modify grid error', e)
return Promise.reject(e)
}
}
export const modifyAstForSketch = async ( export const modifyAstForSketch = async (
engineCommandManager: EngineCommandManager, engineCommandManager: EngineCommandManager,
ast: Node<Program>, ast: Node<Program>,
@ -588,7 +605,8 @@ export const modifyAstForSketch = async (
const kclError = new KCLError( const kclError = new KCLError(
parsed.kind, parsed.kind,
parsed.msg, parsed.msg,
sourceRangeFromRust(parsed.sourceRanges[0]) sourceRangeFromRust(parsed.sourceRanges[0]),
[]
) )
console.log(kclError) console.log(kclError)
@ -656,7 +674,8 @@ export function programMemoryInit(): ProgramMemory | Error {
return new KCLError( return new KCLError(
parsed.kind, parsed.kind,
parsed.msg, parsed.msg,
sourceRangeFromRust(parsed.sourceRanges[0]) sourceRangeFromRust(parsed.sourceRanges[0]),
[]
) )
} }
} }

View File

@ -10,7 +10,7 @@ const noModifiersPressed = (e: MouseEvent) =>
!e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey !e.ctrlKey && !e.shiftKey && !e.altKey && !e.metaKey
export type CameraSystem = export type CameraSystem =
| 'KittyCAD' | 'Zoo'
| 'OnShape' | 'OnShape'
| 'Trackpad Friendly' | 'Trackpad Friendly'
| 'Solidworks' | 'Solidworks'
@ -19,7 +19,7 @@ export type CameraSystem =
| 'AutoCAD' | 'AutoCAD'
export const cameraSystems: CameraSystem[] = [ export const cameraSystems: CameraSystem[] = [
'KittyCAD', 'Zoo',
'OnShape', 'OnShape',
'Trackpad Friendly', 'Trackpad Friendly',
'Solidworks', 'Solidworks',
@ -34,9 +34,8 @@ export function mouseControlsToCameraSystem(
switch (mouseControl) { switch (mouseControl) {
// TODO: understand why the values come back without underscores and fix the root cause // TODO: understand why the values come back without underscores and fix the root cause
// @ts-ignore: TS2678 // @ts-ignore: TS2678
case 'kittycad': case 'zoo':
case 'kitty_cad': return 'Zoo'
return 'KittyCAD'
// TODO: understand why the values come back without underscores and fix the root cause // TODO: understand why the values come back without underscores and fix the root cause
// @ts-ignore: TS2678 // @ts-ignore: TS2678
case 'onshape': case 'onshape':
@ -86,7 +85,7 @@ export const btnName = (e: MouseEvent) => ({
}) })
export const cameraMouseDragGuards: Record<CameraSystem, MouseGuard> = { export const cameraMouseDragGuards: Record<CameraSystem, MouseGuard> = {
KittyCAD: { Zoo: {
pan: { pan: {
description: 'Shift + Right click drag or middle click drag', description: 'Shift + Right click drag or middle click drag',
callback: (e) => callback: (e) =>

View File

@ -3,7 +3,6 @@ import { engineCommandManager } from 'lib/singletons'
import { uuidv4 } from 'lib/utils' import { uuidv4 } from 'lib/utils'
import { CommandBarContext } from 'machines/commandBarMachine' import { CommandBarContext } from 'machines/commandBarMachine'
import { Selections } from 'lib/selections' import { Selections } from 'lib/selections'
import { isSolid2D, isSegment, isSweep } from 'lang/std/artifactGraph'
export const disableDryRunWithRetry = async (numberOfRetries = 3) => { export const disableDryRunWithRetry = async (numberOfRetries = 3) => {
for (let tries = 0; tries < numberOfRetries; tries++) { for (let tries = 0; tries < numberOfRetries; tries++) {
@ -64,7 +63,7 @@ export const revolveAxisValidator = async ({
return 'Unable to revolve, sketch not found' return 'Unable to revolve, sketch not found'
} }
if (!(isSolid2D(artifact) || isSegment(artifact) || isSweep(artifact))) { if (!('pathId' in artifact)) {
return 'Unable to revolve, sketch has no path' return 'Unable to revolve, sketch has no path'
} }

View File

@ -118,3 +118,21 @@ export const KCL_AXIS_Y = 'Y'
export const KCL_AXIS_NEG_X = '-X' export const KCL_AXIS_NEG_X = '-X'
export const KCL_AXIS_NEG_Y = '-Y' export const KCL_AXIS_NEG_Y = '-Y'
export const KCL_DEFAULT_AXIS = 'X' export const KCL_DEFAULT_AXIS = 'X'
export enum AxisNames {
X = 'x',
Y = 'y',
Z = 'z',
NEG_X = '-x',
NEG_Y = '-y',
NEG_Z = '-z',
}
/** Semantic names of views from AxisNames */
export const VIEW_NAMES_SEMANTIC = {
[AxisNames.X]: 'Right',
[AxisNames.Y]: 'Back',
[AxisNames.Z]: 'Top',
[AxisNames.NEG_X]: 'Left',
[AxisNames.NEG_Y]: 'Front',
[AxisNames.NEG_Z]: 'Bottom',
} as const

View File

@ -15,6 +15,7 @@ import { fileSystemManager } from 'lang/std/fileSystemManager'
import { getProjectInfo } from './desktop' import { getProjectInfo } from './desktop'
import { createSettings } from './settings/initialSettings' import { createSettings } from './settings/initialSettings'
import { normalizeLineEndings } from 'lib/codeEditor' import { normalizeLineEndings } from 'lib/codeEditor'
import { OnboardingStatus } from 'wasm-lib/kcl/bindings/OnboardingStatus'
// The root loader simply resolves the settings and any errors that // The root loader simply resolves the settings and any errors that
// occurred during the settings load // occurred during the settings load
@ -53,14 +54,15 @@ export const telemetryLoader: LoaderFunction = async ({
// Redirect users to the appropriate onboarding page if they haven't completed it // Redirect users to the appropriate onboarding page if they haven't completed it
export const onboardingRedirectLoader: ActionFunction = async (args) => { export const onboardingRedirectLoader: ActionFunction = async (args) => {
const { settings } = await loadAndValidateSettings() const { settings } = await loadAndValidateSettings()
const onboardingStatus = settings.app.onboardingStatus.current || '' const onboardingStatus: OnboardingStatus =
settings.app.onboardingStatus.current || ''
const notEnRouteToOnboarding = !args.request.url.includes( const notEnRouteToOnboarding = !args.request.url.includes(
PATHS.ONBOARDING.INDEX PATHS.ONBOARDING.INDEX
) )
// '' is the initial state, 'done' and 'dismissed' are the final states // '' is the initial state, 'completed' and 'dismissed' are the final states
const hasValidOnboardingStatus = const hasValidOnboardingStatus =
onboardingStatus.length === 0 || onboardingStatus.length === 0 ||
!(onboardingStatus === 'done' || onboardingStatus === 'dismissed') !(onboardingStatus === 'completed' || onboardingStatus === 'dismissed')
const shouldRedirectToOnboarding = const shouldRedirectToOnboarding =
notEnRouteToOnboarding && hasValidOnboardingStatus notEnRouteToOnboarding && hasValidOnboardingStatus

View File

@ -19,6 +19,7 @@ import Tooltip from 'components/Tooltip'
import { toSync } from 'lib/utils' import { toSync } from 'lib/utils'
import { reportRejection } from 'lib/trap' import { reportRejection } from 'lib/trap'
import { CameraProjectionType } from 'wasm-lib/kcl/bindings/CameraProjectionType' import { CameraProjectionType } from 'wasm-lib/kcl/bindings/CameraProjectionType'
import { OnboardingStatus } from 'wasm-lib/kcl/bindings/OnboardingStatus'
/** /**
* A setting that can be set at the user or project level * A setting that can be set at the user or project level
@ -189,8 +190,10 @@ export function createSettings() {
inputType: 'boolean', inputType: 'boolean',
}, },
}), }),
onboardingStatus: new Setting<string>({ onboardingStatus: new Setting<OnboardingStatus>({
defaultValue: '', defaultValue: '',
// TODO: this could be better but we don't have a TS side real enum
// for this yet
validate: (v) => typeof v === 'string', validate: (v) => typeof v === 'string',
hideOnPlatform: 'both', hideOnPlatform: 'both',
}), }),
@ -283,7 +286,7 @@ export function createSettings() {
* The controls for how to navigate the 3D view * The controls for how to navigate the 3D view
*/ */
mouseControls: new Setting<CameraSystem>({ mouseControls: new Setting<CameraSystem>({
defaultValue: 'KittyCAD', defaultValue: 'Zoo',
description: 'The controls for how to navigate the 3D view', description: 'The controls for how to navigate the 3D view',
validate: (v) => cameraSystems.includes(v as CameraSystem), validate: (v) => cameraSystems.includes(v as CameraSystem),
hideOnLevel: 'project', hideOnLevel: 'project',

View File

@ -2,6 +2,7 @@ import { DeepPartial } from 'lib/types'
import { Configuration } from 'wasm-lib/kcl/bindings/Configuration' import { Configuration } from 'wasm-lib/kcl/bindings/Configuration'
import { import {
configurationToSettingsPayload, configurationToSettingsPayload,
getAllCurrentSettings,
projectConfigurationToSettingsPayload, projectConfigurationToSettingsPayload,
setSettingsAtLevel, setSettingsAtLevel,
} from './settingsUtils' } from './settingsUtils'
@ -65,3 +66,48 @@ describe(`testing settings initialization`, () => {
expect(settings.app.themeColor.current).toBe('200') expect(settings.app.themeColor.current).toBe('200')
}) })
}) })
describe(`testing getAllCurrentSettings`, () => {
it(`returns the correct settings`, () => {
// Set up the settings
let settings = createSettings()
const appConfiguration: DeepPartial<Configuration> = {
settings: {
app: {
appearance: {
theme: 'dark',
color: 190,
},
},
},
}
const projectConfiguration: DeepPartial<Configuration> = {
settings: {
app: {
appearance: {
theme: 'light',
color: 200,
},
},
modeling: {
base_unit: 'ft',
},
},
}
const appSettingsPayload = configurationToSettingsPayload(appConfiguration)
const projectSettingsPayload =
projectConfigurationToSettingsPayload(projectConfiguration)
setSettingsAtLevel(settings, 'user', appSettingsPayload)
setSettingsAtLevel(settings, 'project', projectSettingsPayload)
// Now the test: get all the settings' current resolved values
const allCurrentSettings = getAllCurrentSettings(settings)
// This one gets the 'user'-level theme because it's ignored at the project level
// (see the test "doesn't read theme from project settings")
expect(allCurrentSettings.app.theme).toBe('dark')
expect(allCurrentSettings.app.themeColor).toBe('200')
expect(allCurrentSettings.modeling.defaultUnit).toBe('ft')
})
})

View File

@ -286,6 +286,27 @@ export function getChangedSettingsAtLevel(
return changedSettings return changedSettings
} }
export function getAllCurrentSettings(
allSettings: typeof settings
): SaveSettingsPayload {
const currentSettings = {} as SaveSettingsPayload
Object.entries(allSettings).forEach(([category, settingsCategory]) => {
const categoryKey = category as keyof typeof settings
Object.entries(settingsCategory).forEach(
([setting, settingValue]: [string, Setting]) => {
const settingKey =
setting as keyof (typeof settings)[typeof categoryKey]
currentSettings[categoryKey] = {
...currentSettings[categoryKey],
[settingKey]: settingValue.current,
}
}
)
})
return currentSettings
}
export function setSettingsAtLevel( export function setSettingsAtLevel(
allSettings: typeof settings, allSettings: typeof settings,
level: SettingsLevel, level: SettingsLevel,

View File

@ -112,9 +112,6 @@ export async function executor(
makeDefaultPlanes: () => { makeDefaultPlanes: () => {
return new Promise((resolve) => resolve(defaultPlanes)) return new Promise((resolve) => resolve(defaultPlanes))
}, },
modifyGrid: (hidden: boolean) => {
return new Promise((resolve) => resolve())
},
}) })
return new Promise((resolve) => { return new Promise((resolve) => {

View File

@ -42,8 +42,6 @@ export const settingsMachine = setup({
setClientTheme: () => {}, setClientTheme: () => {},
'Execute AST': () => {}, 'Execute AST': () => {},
toastSuccess: () => {}, toastSuccess: () => {},
setEngineEdges: () => {},
setEngineScaleGridVisibility: () => {},
setClientSideSceneUnits: () => {}, setClientSideSceneUnits: () => {},
persistSettings: () => {}, persistSettings: () => {},
resetSettings: assign(({ context, event }) => { resetSettings: assign(({ context, event }) => {
@ -172,7 +170,7 @@ export const settingsMachine = setup({
'set.modeling.highlightEdges': { 'set.modeling.highlightEdges': {
target: 'persisting settings', target: 'persisting settings',
actions: ['setSettingAtLevel', 'toastSuccess', 'setEngineEdges'], actions: ['setSettingAtLevel', 'toastSuccess', 'Execute AST'],
}, },
'Reset settings': { 'Reset settings': {
@ -201,11 +199,7 @@ export const settingsMachine = setup({
'set.modeling.showScaleGrid': { 'set.modeling.showScaleGrid': {
target: 'persisting settings', target: 'persisting settings',
actions: [ actions: ['setSettingAtLevel', 'toastSuccess', 'Execute AST'],
'setSettingAtLevel',
'toastSuccess',
'setEngineScaleGridVisibility',
],
}, },
}, },
}, },

View File

@ -23,15 +23,6 @@ import argvFromYargs from './commandLineArgs'
let mainWindow: BrowserWindow | null = null let mainWindow: BrowserWindow | null = null
// Supporting multiple instances instead of multiple applications
let cmdQPressed = false
const instances: BrowserWindow[] = []
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
process.exit(0)
}
// Check the command line arguments for a project path // Check the command line arguments for a project path
const args = parseCLIArgs() const args = parseCLIArgs()
@ -53,11 +44,6 @@ process.env.VITE_KC_SITE_BASE_URL ??= 'https://zoo.dev'
process.env.VITE_KC_SKIP_AUTH ??= 'false' process.env.VITE_KC_SKIP_AUTH ??= 'false'
process.env.VITE_KC_CONNECTION_TIMEOUT_MS ??= '15000' process.env.VITE_KC_CONNECTION_TIMEOUT_MS ??= '15000'
// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) {
app.quit()
}
const ZOO_STUDIO_PROTOCOL = 'zoo-studio' const ZOO_STUDIO_PROTOCOL = 'zoo-studio'
/// Register our application to handle all "electron-fiddle://" protocols. /// Register our application to handle all "electron-fiddle://" protocols.
@ -126,34 +112,16 @@ const createWindow = (filePath?: string): BrowserWindow => {
newWindow.show() newWindow.show()
instances.push(newWindow)
return newWindow return newWindow
} }
// before-quit with multiple instances
if (process.platform === 'darwin') {
// Quit from the dock context menu should quit the application directly
app.on('before-quit', () => {
cmdQPressed = true
})
}
// Quit when all windows are closed, even on macOS. There, it's common // Quit when all windows are closed, even on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits // for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q, but it is a really weird behavior with our app. // explicitly with Cmd + Q, but it is a really weird behavior with our app.
// app.on('window-all-closed', () => {
// app.quit()
// })
app.on('window-all-closed', () => { app.on('window-all-closed', () => {
if (cmdQPressed || process.platform !== 'darwin') { app.quit()
app.quit()
}
}) })
// Various actions can trigger this event, such as launching the application for the first time,
// attempting to re-launch the application when it's already running, or clicking on the application's dock or taskbar icon.
app.on('activate', () => createWindow())
// This method will be called when Electron has finished // This method will be called when Electron has finished
// initialization and is ready to create browser windows. // initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs. // Some APIs can only be used after this event occurs.
@ -162,10 +130,6 @@ app.on('ready', (event, data) => {
mainWindow = createWindow() mainWindow = createWindow()
}) })
// This event will be emitted inside the primary instance of your application when a second instance
// has been executed and calls app.requestSingleInstanceLock().
app.on('second-instance', (event, argv, workingDirectory) => createWindow())
// For now there is no good reason to separate these out to another file(s) // For now there is no good reason to separate these out to another file(s)
// There is just not enough code to warrant it and further abstracts everything // There is just not enough code to warrant it and further abstracts everything
// which is already quite abstracted // which is already quite abstracted
@ -287,6 +251,9 @@ export function getAutoUpdater(): AppUpdater {
app.on('ready', () => { app.on('ready', () => {
const autoUpdater = getAutoUpdater() const autoUpdater = getAutoUpdater()
// TODO: we're getting `Error: Response ends without calling any handlers` with our setup,
// so at the moment this isn't worth enabling
autoUpdater.disableDifferentialDownload = true
setTimeout(() => { setTimeout(() => {
autoUpdater.checkForUpdates().catch(reportRejection) autoUpdater.checkForUpdates().catch(reportRejection)
}, 1000) }, 1000)

View File

@ -1,4 +1,6 @@
export const onboardingPaths = { import { OnboardingStatus } from 'wasm-lib/kcl/bindings/OnboardingStatus'
export const onboardingPaths: Record<string, OnboardingStatus> = {
INDEX: '/', INDEX: '/',
CAMERA: '/camera', CAMERA: '/camera',
STREAMING: '/streaming', STREAMING: '/streaming',

View File

@ -32,9 +32,11 @@ export const PACKAGE_NAME = isDesktop()
export const IS_NIGHTLY = PACKAGE_NAME.indexOf('-nightly') > -1 export const IS_NIGHTLY = PACKAGE_NAME.indexOf('-nightly') > -1
export const RELEASE_URL = `https://github.com/KittyCAD/modeling-app/releases/tag/${ export function getReleaseUrl(version: string = APP_VERSION) {
IS_NIGHTLY ? 'nightly-' : '' return `https://github.com/KittyCAD/modeling-app/releases/tag/${
}v${APP_VERSION}` IS_NIGHTLY ? 'nightly-' : ''
}v${version}`
}
export const Settings = () => { export const Settings = () => {
const navigate = useNavigate() const navigate = useNavigate()

103
src/wasm-lib/Cargo.lock generated
View File

@ -121,9 +121,9 @@ dependencies = [
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.93" version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c95c10ba0b00a02636238b814946408b1322d5ac4760326e6fb8ec956d85775" checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7"
dependencies = [ dependencies = [
"backtrace", "backtrace",
] ]
@ -401,9 +401,9 @@ dependencies = [
[[package]] [[package]]
name = "chrono" name = "chrono"
version = "0.4.38" version = "0.4.39"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" checksum = "7e36cc9d416881d2e24f9a963be5fb1cd90966419ac844274161d10488b3e825"
dependencies = [ dependencies = [
"android-tzdata", "android-tzdata",
"iana-time-zone", "iana-time-zone",
@ -723,7 +723,7 @@ dependencies = [
[[package]] [[package]]
name = "derive-docs" name = "derive-docs"
version = "0.1.32" version = "0.1.33"
dependencies = [ dependencies = [
"Inflector", "Inflector",
"anyhow", "anyhow",
@ -1112,7 +1112,7 @@ dependencies = [
"fnv", "fnv",
"futures-core", "futures-core",
"futures-sink", "futures-sink",
"http 1.1.0", "http 1.2.0",
"indexmap 2.7.0", "indexmap 2.7.0",
"slab", "slab",
"tokio", "tokio",
@ -1215,9 +1215,9 @@ dependencies = [
[[package]] [[package]]
name = "http" name = "http"
version = "1.1.0" version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea"
dependencies = [ dependencies = [
"bytes", "bytes",
"fnv", "fnv",
@ -1242,7 +1242,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
dependencies = [ dependencies = [
"bytes", "bytes",
"http 1.1.0", "http 1.2.0",
] ]
[[package]] [[package]]
@ -1253,7 +1253,7 @@ checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f"
dependencies = [ dependencies = [
"bytes", "bytes",
"futures-util", "futures-util",
"http 1.1.0", "http 1.2.0",
"http-body 1.0.1", "http-body 1.0.1",
"pin-project-lite", "pin-project-lite",
] ]
@ -1303,7 +1303,7 @@ dependencies = [
"futures-channel", "futures-channel",
"futures-util", "futures-util",
"h2", "h2",
"http 1.1.0", "http 1.2.0",
"http-body 1.0.1", "http-body 1.0.1",
"httparse", "httparse",
"itoa", "itoa",
@ -1320,7 +1320,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333"
dependencies = [ dependencies = [
"futures-util", "futures-util",
"http 1.1.0", "http 1.2.0",
"hyper 1.4.1", "hyper 1.4.1",
"hyper-util", "hyper-util",
"rustls", "rustls",
@ -1340,7 +1340,7 @@ dependencies = [
"bytes", "bytes",
"futures-channel", "futures-channel",
"futures-util", "futures-util",
"http 1.1.0", "http 1.2.0",
"http-body 1.0.1", "http-body 1.0.1",
"hyper 1.4.1", "hyper 1.4.1",
"pin-project-lite", "pin-project-lite",
@ -1674,16 +1674,17 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.72" version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" checksum = "6717b6b5b077764fb5966237269cb3c64edddde4b14ce42647430a78ced9e7b7"
dependencies = [ dependencies = [
"once_cell",
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]] [[package]]
name = "kcl-lib" name = "kcl-lib"
version = "0.2.28" version = "0.2.29"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"approx 0.5.1", "approx 0.5.1",
@ -1705,7 +1706,7 @@ dependencies = [
"git_rev", "git_rev",
"gltf-json", "gltf-json",
"handlebars", "handlebars",
"http 1.1.0", "http 1.2.0",
"iai", "iai",
"image", "image",
"indexmap 2.7.0", "indexmap 2.7.0",
@ -1721,7 +1722,9 @@ dependencies = [
"parse-display 0.9.1", "parse-display 0.9.1",
"pretty_assertions", "pretty_assertions",
"pyo3", "pyo3",
"regex",
"reqwest", "reqwest",
"rgba_simple",
"ropey", "ropey",
"schemars", "schemars",
"serde", "serde",
@ -1749,7 +1752,7 @@ dependencies = [
[[package]] [[package]]
name = "kcl-test-server" name = "kcl-test-server"
version = "0.1.18" version = "0.1.19"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"hyper 0.14.30", "hyper 0.14.30",
@ -1790,7 +1793,7 @@ dependencies = [
"data-encoding", "data-encoding",
"format_serde_error", "format_serde_error",
"futures", "futures",
"http 1.1.0", "http 1.2.0",
"itertools 0.13.0", "itertools 0.13.0",
"log", "log",
"mime_guess", "mime_guess",
@ -1816,9 +1819,9 @@ dependencies = [
[[package]] [[package]]
name = "kittycad-modeling-cmds" name = "kittycad-modeling-cmds"
version = "0.2.77" version = "0.2.79"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b77259b37acafa360d98af27431ac394bc8899eeed7037513832ddbee856811" checksum = "10a9cab4476455be70ea57643c31444068b056d091bd348cab6044c0d8ad7fcc"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@ -1826,7 +1829,7 @@ dependencies = [
"enum-iterator", "enum-iterator",
"enum-iterator-derive", "enum-iterator-derive",
"euler", "euler",
"http 1.1.0", "http 1.2.0",
"kittycad-modeling-cmds-macros", "kittycad-modeling-cmds-macros",
"kittycad-unit-conversion-derive", "kittycad-unit-conversion-derive",
"measurements", "measurements",
@ -2860,7 +2863,7 @@ dependencies = [
"futures-core", "futures-core",
"futures-util", "futures-util",
"h2", "h2",
"http 1.1.0", "http 1.2.0",
"http-body 1.0.1", "http-body 1.0.1",
"http-body-util", "http-body-util",
"hyper 1.4.1", "hyper 1.4.1",
@ -2902,7 +2905,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f67ad7fdf5c0a015763fcd164bee294b13fb7b6f89f1b55961d40f00c3e32d6b" checksum = "f67ad7fdf5c0a015763fcd164bee294b13fb7b6f89f1b55961d40f00c3e32d6b"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"http 1.1.0", "http 1.2.0",
"reqwest", "reqwest",
"reqwest-middleware", "reqwest-middleware",
] ]
@ -2915,7 +2918,7 @@ checksum = "d1ccd3b55e711f91a9885a2fa6fbbb2e39db1776420b062efc058c6410f7e5e3"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
"http 1.1.0", "http 1.2.0",
"reqwest", "reqwest",
"serde", "serde",
"thiserror 1.0.68", "thiserror 1.0.68",
@ -2932,7 +2935,7 @@ dependencies = [
"async-trait", "async-trait",
"futures", "futures",
"getrandom", "getrandom",
"http 1.1.0", "http 1.2.0",
"hyper 1.4.1", "hyper 1.4.1",
"parking_lot 0.11.2", "parking_lot 0.11.2",
"reqwest", "reqwest",
@ -2953,7 +2956,7 @@ dependencies = [
"anyhow", "anyhow",
"async-trait", "async-trait",
"getrandom", "getrandom",
"http 1.1.0", "http 1.2.0",
"matchit", "matchit",
"opentelemetry", "opentelemetry",
"reqwest", "reqwest",
@ -2971,6 +2974,12 @@ dependencies = [
"rand 0.8.5", "rand 0.8.5",
] ]
[[package]]
name = "rgba_simple"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6cd655523701785087f69900df39892fb7b9b0721aa67682f571c38c32ac58a"
[[package]] [[package]]
name = "ring" name = "ring"
version = "0.17.8" version = "0.17.8"
@ -3191,9 +3200,9 @@ checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.215" version = "1.0.216"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" checksum = "0b9781016e935a97e8beecf0c933758c97a5520d32930e460142b4cd80c6338e"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
@ -3209,9 +3218,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.215" version = "1.0.216"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" checksum = "46f859dbbf73865c6627ed570e78961cd3ac92407a2d117204c49232485da55e"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -4019,7 +4028,7 @@ dependencies = [
"byteorder", "byteorder",
"bytes", "bytes",
"data-encoding", "data-encoding",
"http 1.1.0", "http 1.2.0",
"httparse", "httparse",
"log", "log",
"rand 0.8.5", "rand 0.8.5",
@ -4227,9 +4236,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.95" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" checksum = "a474f6281d1d70c17ae7aa6a613c87fce69a127e2624002df63dcb39d6cf6396"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"once_cell", "once_cell",
@ -4238,13 +4247,12 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.95" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" checksum = "5f89bb38646b4f81674e8f5c3fb81b562be1fd936d84320f3264486418519c79"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"log", "log",
"once_cell",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.87", "syn 2.0.87",
@ -4253,22 +4261,23 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-futures" name = "wasm-bindgen-futures"
version = "0.4.44" version = "0.4.49"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65471f79c1022ffa5291d33520cbbb53b7687b01c2f8e83b57d102eed7ed479d" checksum = "38176d9b44ea84e9184eff0bc34cc167ed044f816accfe5922e54d84cf48eca2"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"futures-core", "futures-core",
"js-sys", "js-sys",
"once_cell",
"wasm-bindgen", "wasm-bindgen",
"web-sys", "web-sys",
] ]
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.95" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" checksum = "2cc6181fd9a7492eef6fef1f33961e3695e4579b9872a6f7c83aee556666d4fe"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@ -4276,9 +4285,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.95" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" checksum = "30d7a95b763d3c45903ed6c81f156801839e5ee968bb07e534c44df0fcd330c2"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -4289,9 +4298,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.95" version = "0.2.99"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" checksum = "943aab3fdaaa029a6e0271b35ea10b72b943135afe9bffca82384098ad0e06a6"
[[package]] [[package]]
name = "wasm-lib" name = "wasm-lib"
@ -4353,9 +4362,9 @@ dependencies = [
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.72" version = "0.3.76"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6488b90108c040df0fe62fa815cbdee25124641df01814dd7282749234c6112" checksum = "04dd7223427d52553d3702c004d3b2fe07c148165faa56313cb00211e31c12bc"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",

View File

@ -20,8 +20,8 @@ serde_json = "1.0.128"
tokio = { version = "1.41.1", features = ["sync"] } tokio = { version = "1.41.1", features = ["sync"] }
toml = "0.8.19" toml = "0.8.19"
uuid = { version = "1.11.0", features = ["v4", "js", "serde"] } uuid = { version = "1.11.0", features = ["v4", "js", "serde"] }
wasm-bindgen = "0.2.91" wasm-bindgen = "0.2.99"
wasm-bindgen-futures = "0.4.44" wasm-bindgen-futures = "0.4.49"
[dev-dependencies] [dev-dependencies]
anyhow = "1" anyhow = "1"
@ -43,7 +43,7 @@ wasm-bindgen-futures = { version = "0.4.44", features = ["futures-core-03-stream
wasm-streams = "0.4.1" wasm-streams = "0.4.1"
[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys] [target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
version = "0.3.72" version = "0.3.76"
features = [ features = [
"console", "console",
"HtmlTextAreaElement", "HtmlTextAreaElement",
@ -76,7 +76,7 @@ members = [
[workspace.dependencies] [workspace.dependencies]
http = "1" http = "1"
kittycad = { version = "0.3.28", default-features = false, features = ["js", "requests"] } kittycad = { version = "0.3.28", default-features = false, features = ["js", "requests"] }
kittycad-modeling-cmds = { version = "0.2.77", features = ["websocket"] } kittycad-modeling-cmds = { version = "0.2.79", features = ["websocket"] }
[workspace.lints.clippy] [workspace.lints.clippy]
assertions_on_result_states = "warn" assertions_on_result_states = "warn"

View File

@ -1,7 +1,7 @@
[package] [package]
name = "derive-docs" name = "derive-docs"
description = "A tool for generating documentation from Rust derive macros" description = "A tool for generating documentation from Rust derive macros"
version = "0.1.32" version = "0.1.33"
edition = "2021" edition = "2021"
license = "MIT" license = "MIT"
repository = "https://github.com/KittyCAD/modeling-app" repository = "https://github.com/KittyCAD/modeling-app"

View File

@ -6,6 +6,8 @@
mod tests; mod tests;
mod unbox; mod unbox;
use std::collections::HashMap;
use convert_case::Casing; use convert_case::Casing;
use inflector::Inflector; use inflector::Inflector;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
@ -38,6 +40,12 @@ struct StdlibMetadata {
#[serde(default)] #[serde(default)]
deprecated: bool, deprecated: bool,
/// Whether the function is displayed in the feature tree.
/// If true, calls to the function will be available for display.
/// If false, calls to the function will never be displayed.
#[serde(default)]
feature_tree_operation: bool,
/// If true, expects keyword arguments. /// If true, expects keyword arguments.
/// If false, expects positional arguments. /// If false, expects positional arguments.
#[serde(default)] #[serde(default)]
@ -47,6 +55,10 @@ struct StdlibMetadata {
/// If false, all arguments require labels. /// If false, all arguments require labels.
#[serde(default)] #[serde(default)]
unlabeled_first: bool, unlabeled_first: bool,
/// Key = argument name, value = argument doc.
#[serde(default)]
arg_docs: HashMap<String, String>,
} }
#[proc_macro_attribute] #[proc_macro_attribute]
@ -238,6 +250,12 @@ fn do_stdlib_inner(
quote! { false } quote! { false }
}; };
let feature_tree_operation = if metadata.feature_tree_operation {
quote! { true }
} else {
quote! { false }
};
let uses_keyword_arguments = if metadata.keywords { let uses_keyword_arguments = if metadata.keywords {
quote! { true } quote! { true }
} else { } else {
@ -282,6 +300,17 @@ fn do_stdlib_inner(
let ty_string = rust_type_to_openapi_type(&ty_string); let ty_string = rust_type_to_openapi_type(&ty_string);
let required = !ty_ident.to_string().starts_with("Option <"); let required = !ty_ident.to_string().starts_with("Option <");
let description = if let Some(s) = metadata.arg_docs.get(&arg_name) {
quote! { #s }
} else if metadata.keywords && ty_string != "Args" && ty_string != "ExecState" {
errors.push(Error::new_spanned(
&arg,
"Argument was not documented in the arg_docs block",
));
continue;
} else {
quote! { String::new() }
};
let label_required = !(i == 0 && metadata.unlabeled_first); let label_required = !(i == 0 && metadata.unlabeled_first);
if ty_string != "ExecState" && ty_string != "Args" { if ty_string != "ExecState" && ty_string != "Args" {
let schema = quote! { let schema = quote! {
@ -294,6 +323,7 @@ fn do_stdlib_inner(
schema: #schema, schema: #schema,
required: #required, required: #required,
label_required: #label_required, label_required: #label_required,
description: #description.to_string(),
} }
}); });
} }
@ -355,6 +385,7 @@ fn do_stdlib_inner(
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
} else { } else {
@ -451,6 +482,10 @@ fn do_stdlib_inner(
#deprecated #deprecated
} }
fn feature_tree_operation(&self) -> bool {
#feature_tree_operation
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
#code_blocks #code_blocks
} }
@ -744,6 +779,8 @@ fn rust_type_to_openapi_type(t: &str) -> String {
if t == "f64" { if t == "f64" {
return "number".to_string(); return "number".to_string();
} else if t == "u32" {
return "integer".to_string();
} else if t == "str" { } else if t == "str" {
return "string".to_string(); return "string".to_string();
} else { } else {
@ -778,7 +815,7 @@ fn generate_code_block_test(fn_name: &str, code_block: &str, index: usize) -> pr
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()).await.unwrap(); ctx.run(program.into(), &mut crate::ExecState::new()).await.unwrap();
} }
#[tokio::test(flavor = "multi_thread", worker_threads = 5)] #[tokio::test(flavor = "multi_thread", worker_threads = 5)]

View File

@ -116,6 +116,9 @@ fn test_stdlib_line_to() {
let (item, errors) = do_stdlib( let (item, errors) = do_stdlib(
quote! { quote! {
name = "lineTo", name = "lineTo",
arg_docs = {
sketch = "the sketch you're adding the line to"
}
}, },
quote! { quote! {
/// This is some function. /// This is some function.

View File

@ -14,7 +14,7 @@ mod test_examples_someFn {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -91,6 +91,7 @@ impl crate::docs::StdLibFn for SomeFn {
schema: generator.root_schema_for::<Foo>(), schema: generator.root_schema_for::<Foo>(),
required: true, required: true,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -105,6 +106,7 @@ impl crate::docs::StdLibFn for SomeFn {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -116,6 +118,10 @@ impl crate::docs::StdLibFn for SomeFn {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec!["someFn()"]; let code_blocks = vec!["someFn()"];
code_blocks code_blocks

View File

@ -14,7 +14,7 @@ mod test_examples_someFn {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -91,6 +91,7 @@ impl crate::docs::StdLibFn for SomeFn {
schema: generator.root_schema_for::<str>(), schema: generator.root_schema_for::<str>(),
required: true, required: true,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -105,6 +106,7 @@ impl crate::docs::StdLibFn for SomeFn {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -116,6 +118,10 @@ impl crate::docs::StdLibFn for SomeFn {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec!["someFn()"]; let code_blocks = vec!["someFn()"];
code_blocks code_blocks

View File

@ -15,7 +15,7 @@ mod test_examples_show {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -52,7 +52,7 @@ mod test_examples_show {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -129,6 +129,7 @@ impl crate::docs::StdLibFn for Show {
schema: generator.root_schema_for::<[f64; 2usize]>(), schema: generator.root_schema_for::<[f64; 2usize]>(),
required: true, required: true,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -143,6 +144,7 @@ impl crate::docs::StdLibFn for Show {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -154,6 +156,10 @@ impl crate::docs::StdLibFn for Show {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec![ let code_blocks = vec![
"This is another code block.\nyes sirrr.\nshow", "This is another code block.\nyes sirrr.\nshow",

View File

@ -15,7 +15,7 @@ mod test_examples_show {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -92,6 +92,7 @@ impl crate::docs::StdLibFn for Show {
schema: generator.root_schema_for::<f64>(), schema: generator.root_schema_for::<f64>(),
required: true, required: true,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -106,6 +107,7 @@ impl crate::docs::StdLibFn for Show {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -117,6 +119,10 @@ impl crate::docs::StdLibFn for Show {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec!["This is code.\nIt does other shit.\nshow"]; let code_blocks = vec!["This is code.\nIt does other shit.\nshow"];
code_blocks code_blocks

View File

@ -16,7 +16,7 @@ mod test_examples_my_func {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -53,7 +53,7 @@ mod test_examples_my_func {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -130,6 +130,7 @@ impl crate::docs::StdLibFn for MyFunc {
schema: generator.root_schema_for::<Option<kittycad::types::InputFormat>>(), schema: generator.root_schema_for::<Option<kittycad::types::InputFormat>>(),
required: false, required: false,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -144,6 +145,7 @@ impl crate::docs::StdLibFn for MyFunc {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -155,6 +157,10 @@ impl crate::docs::StdLibFn for MyFunc {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec![ let code_blocks = vec![
"This is another code block.\nyes sirrr.\nmyFunc", "This is another code block.\nyes sirrr.\nmyFunc",

View File

@ -16,7 +16,7 @@ mod test_examples_line_to {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -53,7 +53,7 @@ mod test_examples_line_to {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -131,6 +131,7 @@ impl crate::docs::StdLibFn for LineTo {
schema: generator.root_schema_for::<LineToData>(), schema: generator.root_schema_for::<LineToData>(),
required: true, required: true,
label_required: true, label_required: true,
description: String::new().to_string(),
}, },
crate::docs::StdLibFnArg { crate::docs::StdLibFnArg {
name: "sketch".to_string(), name: "sketch".to_string(),
@ -138,6 +139,7 @@ impl crate::docs::StdLibFn for LineTo {
schema: generator.root_schema_for::<Sketch>(), schema: generator.root_schema_for::<Sketch>(),
required: true, required: true,
label_required: true, label_required: true,
description: "the sketch you're adding the line to".to_string(),
}, },
] ]
} }
@ -153,6 +155,7 @@ impl crate::docs::StdLibFn for LineTo {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -164,6 +167,10 @@ impl crate::docs::StdLibFn for LineTo {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec![ let code_blocks = vec![
"This is another code block.\nyes sirrr.\nlineTo", "This is another code block.\nyes sirrr.\nlineTo",

View File

@ -15,7 +15,7 @@ mod test_examples_min {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -52,7 +52,7 @@ mod test_examples_min {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -129,6 +129,7 @@ impl crate::docs::StdLibFn for Min {
schema: generator.root_schema_for::<Vec<f64>>(), schema: generator.root_schema_for::<Vec<f64>>(),
required: true, required: true,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -143,6 +144,7 @@ impl crate::docs::StdLibFn for Min {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -154,6 +156,10 @@ impl crate::docs::StdLibFn for Min {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec![ let code_blocks = vec![
"This is another code block.\nyes sirrr.\nmin", "This is another code block.\nyes sirrr.\nmin",

View File

@ -15,7 +15,7 @@ mod test_examples_show {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -92,6 +92,7 @@ impl crate::docs::StdLibFn for Show {
schema: generator.root_schema_for::<Option<f64>>(), schema: generator.root_schema_for::<Option<f64>>(),
required: false, required: false,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -106,6 +107,7 @@ impl crate::docs::StdLibFn for Show {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -117,6 +119,10 @@ impl crate::docs::StdLibFn for Show {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec!["This is code.\nIt does other shit.\nshow"]; let code_blocks = vec!["This is code.\nIt does other shit.\nshow"];
code_blocks code_blocks

View File

@ -15,7 +15,7 @@ mod test_examples_import {
settings: Default::default(), settings: Default::default(),
context_type: crate::execution::ContextType::Mock, context_type: crate::execution::ContextType::Mock,
}; };
ctx.run(program.into(), &mut crate::ExecState::default()) ctx.run(program.into(), &mut crate::ExecState::new())
.await .await
.unwrap(); .unwrap();
} }
@ -92,6 +92,7 @@ impl crate::docs::StdLibFn for Import {
schema: generator.root_schema_for::<Option<kittycad::types::InputFormat>>(), schema: generator.root_schema_for::<Option<kittycad::types::InputFormat>>(),
required: false, required: false,
label_required: true, label_required: true,
description: String::new().to_string(),
}] }]
} }
@ -106,6 +107,7 @@ impl crate::docs::StdLibFn for Import {
schema, schema,
required: true, required: true,
label_required: true, label_required: true,
description: String::new(),
}) })
} }
@ -117,6 +119,10 @@ impl crate::docs::StdLibFn for Import {
false false
} }
fn feature_tree_operation(&self) -> bool {
false
}
fn examples(&self) -> Vec<String> { fn examples(&self) -> Vec<String> {
let code_blocks = vec!["This is code.\nIt does other shit.\nimport"]; let code_blocks = vec!["This is code.\nIt does other shit.\nimport"];
code_blocks code_blocks

Some files were not shown because too many files have changed in this diff Show More