Compare commits

...

140 Commits

Author SHA1 Message Date
eda736a85e Neaten up array_to_point3d 2024-06-22 09:06:26 -05:00
abbfdae7d2 rm spaces 2024-06-22 08:57:17 -05:00
ddbdd9094c Compute each repetition's transform. 2024-06-21 15:41:10 -05:00
7954b6da96 Pass in everything we need to actually call the transform closure 2024-06-21 14:01:06 -05:00
bdb84ab3c1 Use kittycad.rs from github main 2024-06-21 14:01:06 -05:00
54e160e8d2 Define transform patterns
Defines a `pattern` stdlib fn and parses args for it.
TODO: The actual body of the `pattern` stdlib fn.
2024-06-21 14:01:06 -05:00
2c5a8d439f Allow lifetime refs in KCL stdlib parameters 2024-06-21 14:01:05 -05:00
47a5e1f6d3 Bump proc-macro2 from 1.0.85 to 1.0.86 in /src/wasm-lib (#2732)
Bumps [proc-macro2](https://github.com/dtolnay/proc-macro2) from 1.0.85 to 1.0.86.
- [Release notes](https://github.com/dtolnay/proc-macro2/releases)
- [Commits](https://github.com/dtolnay/proc-macro2/compare/1.0.85...1.0.86)

---
updated-dependencies:
- dependency-name: proc-macro2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-21 08:50:48 -07:00
d85211c5a4 Disable extrude button if there is no extrudable geometry (#2730)
Disable extrude button if there is no extrudeable geometry
2024-06-21 13:20:42 +10:00
1beb6b5186 Cut release v0.22.3 (#2729) 2024-06-21 13:17:14 +10:00
17978ab1d7 Reset code on critical onboarding steps (#2727)
* Make sure we always reset the code on important steps no matter what the user did to it

* Convert comments in codeManager to JSDoc comments so they appear in diagnostics

* Was using the wrong codeManager callback

* Make sure editorView is available before resetting code

* Add Playwright test that shows the code being reset

* Fix up text that looks like linksÏ

* fmt

* Skip test on MacOS, make test more reliable on Chrome

* Update cargo-clippy to run based on paths on PRs as well

* playw fix

* try keep reports

* add fix me

* try one last thing

* fmt

---------

Co-authored-by: Kurt Hutten <k.hutten@protonmail.ch>
2024-06-21 11:39:01 +10:00
a1bcad9dfb Implement Core Dump for modeling app state (#2653) 2024-06-20 19:36:28 -04:00
2e7bdf02cf Franknoirot/onboarding avatar text (#2726)
* Add failing playwright test

* Fix the problem to get the test passing

* Give the avatar button a tooltip too
2024-06-20 14:06:11 -04:00
6f76196b72 pin ts-rs to release (#2725)
Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-20 10:55:53 -07:00
e7af064518 Fix onboarding example code loading (#2723)
* Add Playwright test to verify that example code loads

* Just let the loaded code be null if it's null
2024-06-20 12:07:21 -04:00
674d49e2ae fix clear diagnostics when not wasm (#2715)
Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-19 19:45:55 -07:00
4cb48674c6 add a feature flag to disable printlns in kcl-lib for the lsp (#2712)
* 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>

* cleanup weird printlns

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

* updates

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

* check

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

* rename file

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-19 19:38:56 -07:00
82daec2aff more pyo3 methods (#2711)
more pyo3

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-19 18:04:56 -07:00
f1ef9d5200 add pyo3 as a feature flag for python bindings (#2710)
* updates

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

* thing

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

* add feature flag for pyo3 for gregs stuff;

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

* add more

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-19 17:32:08 -07:00
dc226d3270 Disable SSAO temporarily (#2709) 2024-06-19 18:54:22 -04:00
7bf50d8fe0 get responses back from batch (#2687)
* 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>

* fixes

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

* remove my stupid println

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

* updates

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

* weird typescript

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

* better batch stuff;

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

* updates

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

* ckeanup

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

* fixes

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

* updates

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

* fixes

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

* typpo

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

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

* batch more

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

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

* thing

* updates

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

* up[dates

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

* updates

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

* fixes

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

* updates

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

* fix tests

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

* fixces

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

* cleanups

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

* images

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

* fixes

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

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

* empty

* cleanups

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

* console log all the things

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

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

* fixups

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

* updates

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

* console log cleanup

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

* fixes

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

* nicer types

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

* updates

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

* remove logs

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

* remove logs

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-06-19 13:57:50 -07:00
b26764bc9a Clear the AST if there was a parse error. (#2706)
Clear the AST if there was a parse error.

This leads to an unfortunate loop (good -> invalid -> original) that
wouldn't clear the diagnostics from the invalid step.
2024-06-19 16:15:22 -04:00
1b0c6298d7 Revert "Bump dashmap from 5.5.3 to 6.0.0 in /src/wasm-lib" (#2707)
Revert "Bump dashmap from 5.5.3 to 6.0.0 in /src/wasm-lib (#2704)"

This reverts commit bd42ea037b.
2024-06-19 12:19:17 -07:00
fe9a483726 Bump url from 2.5.1 to 2.5.2 in /src/wasm-lib (#2705)
Bumps [url](https://github.com/servo/rust-url) from 2.5.1 to 2.5.2.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.5.1...v2.5.2)

---
updated-dependencies:
- dependency-name: url
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-18 22:51:07 -07:00
bd42ea037b Bump dashmap from 5.5.3 to 6.0.0 in /src/wasm-lib (#2704)
Bumps [dashmap](https://github.com/xacrimon/dashmap) from 5.5.3 to 6.0.0.
- [Release notes](https://github.com/xacrimon/dashmap/releases)
- [Commits](https://github.com/xacrimon/dashmap/compare/v.5.5.3...v6.0.0)

---
updated-dependencies:
- dependency-name: dashmap
  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-06-18 20:46:12 -07:00
fdb1b21af3 Bump dawidd6/action-download-artifact from 5 to 6 (#2649)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 5 to 6.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  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-06-18 19:32:59 -07:00
630ef316b8 Bump serde_tokenstream from 0.2.0 to 0.2.1 in /src/wasm-lib (#2648)
Bumps [serde_tokenstream](https://github.com/oxidecomputer/serde_tokenstream) from 0.2.0 to 0.2.1.
- [Release notes](https://github.com/oxidecomputer/serde_tokenstream/releases)
- [Commits](https://github.com/oxidecomputer/serde_tokenstream/compare/v0.2.0...v0.2.1)

---
updated-dependencies:
- dependency-name: serde_tokenstream
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-18 19:32:50 -07:00
e322926be9 Bump url from 2.5.0 to 2.5.1 in /src/wasm-lib (#2644)
Bumps [url](https://github.com/servo/rust-url) from 2.5.0 to 2.5.1.
- [Release notes](https://github.com/servo/rust-url/releases)
- [Commits](https://github.com/servo/rust-url/compare/v2.5.0...v2.5.1)

---
updated-dependencies:
- dependency-name: url
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-18 19:31:21 -07:00
a9e61da8b5 Recast bug fix (#2703)
* fix gregs recast bug

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

* fixes

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-18 18:48:30 -07:00
e2a835a437 rename radius to length for chamfer; (#2702)
Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-18 18:33:57 -07:00
c61273085f KCL execution server (#2686)
Adds a new library, the kcl-test-server. It lets you easily start a HTTP server with one endpoint, which accepts JSON. The JSON body contains a KCL program and a test name. The server has a pool of active engine sessions, and when it gets a KCL program, it executes it on one of those engine sessions.

This addresses part of #2580 but currently the sketch-on-face tests don't pass with this new test server yet.

This is a library, not a binary, because I want to use it in both the wasm-lib unit tests and in the zoo CLI.
2024-06-18 14:38:25 -05:00
a79e365c0f Slight tauri e2e cleanup (#2659)
* WIP: Break the tauri e2e tests apart
Will fix #2658

* Clean up

* Longer before timeout

* Also exclude tauri tests from vitest

* Utils fn back in app.spec.ts

* Remove utils

* Change before back to it

* Remove explicit mocha dep

* Revert other attemps at fixing the browser issues. mocha dep was the issue

* Clean up

* Signin/out sep with auth flows

* Lint

---------

Co-authored-by: Frank Noirot <frank@zoo.dev>
2024-06-18 14:01:39 -04:00
2386ba24e5 Better styling for pane and KCL editor focus (#2691)
* Pane styling first steps

* More style tweaks

* Make pane background nearly opaque when focus is within them
2024-06-18 12:42:47 -04:00
e42a891df8 Add nix flake and direnv config (#2694) 2024-06-18 11:32:08 -04:00
98200565bf Add a dismiss button to the command bar (#2647)
* Remove tab hotkey from selection input

* Add dismiss button to the command bar

* update Cargo.lock

* tweak close button styles

* Switch from padding to margin for positioning without messing up focus outline

* Revert "update Cargo.lock"

This reverts commit 862a6897ba.

* Restore Cargo.lock I hate VSCode sometimes

* Update Cargo.lock in src-tauri, fix clippy

---------

Co-authored-by: Adam Chalmers <adam.chalmers@zoo.dev>
2024-06-18 09:06:46 -04:00
570fd827ed fix zoom issues with sketch mode (#2664)
* cam stuff start

* more progress

* mostly done

* fix snapshot tests

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

* fix

* fix ubuntu

* more tweaks fixes

* add test

* more FE fixes

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-18 16:08:41 +10:00
0add26cf61 Cut release v0.22.2 (#2685) 2024-06-17 17:44:30 -04:00
b54fc534c2 Patterning a pattern should always work (#2680)
* patterning a pattern should alwayus work

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

* add images;

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

* std lib

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

* bu,mp

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

* fix tests

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

* update lock

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

* bump

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

* fixes

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

* fixes

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-17 13:35:44 -07:00
c66f851a3f add shell (#2683)
* add shell

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

* add shell

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-17 13:10:40 -07:00
13b8ab71d8 Bump tokio-tungstenite from 0.23.0 to 0.23.1 in /src/wasm-lib (#2663)
Bumps [tokio-tungstenite](https://github.com/snapview/tokio-tungstenite) from 0.23.0 to 0.23.1.
- [Changelog](https://github.com/snapview/tokio-tungstenite/blob/master/CHANGELOG.md)
- [Commits](https://github.com/snapview/tokio-tungstenite/commits)

---
updated-dependencies:
- dependency-name: tokio-tungstenite
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-17 14:36:56 -05:00
bdeab4f87d Bump clap from 4.5.4 to 4.5.7 in /src/wasm-lib (#2643)
Bumps [clap](https://github.com/clap-rs/clap) from 4.5.4 to 4.5.7.
- [Release notes](https://github.com/clap-rs/clap/releases)
- [Changelog](https://github.com/clap-rs/clap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/clap-rs/clap/compare/clap_complete-v4.5.4...v4.5.7)

---
updated-dependencies:
- dependency-name: clap
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-17 14:16:10 -05:00
05ccf5e2f4 Chamfer is just a fancy fillet so easy to add (#2681)
* add chamfer

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

* generate docs

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

* generate docs

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-17 12:13:19 -07:00
7ab015d783 Ensure settings are persisted before we navigate for onboarding dismissal (#2678)
* Nicer types on OnboardingPaths

* Update persistSettings to be a service
2024-06-17 15:10:30 -04:00
3d6cfa980f Release kcl-lib 0.1.59 (#2679) 2024-06-17 13:29:32 -05:00
9f5f1eb8c3 Bump kittycad libs (#2665)
* Bump kittycad.rs lib

* Bump kittycad.ts lib

* Update cargo.lock again

* Bump lib again, and fix fillet typing

* Update kittycad.rs to v0.3.5

* Revert schemars to v0.8.17

* Update to kcl spec
2024-06-17 18:01:45 +00:00
50fcdff879 Prevent stale Cargo.lock (#2652)
Sometimes the `src-tauri/` project gets out of date Cargo.lock. This
adds a CI check to prevent it.

This can happen because `src-tauri` is a separate Cargo project from
`src/wasm-lib`, but the former includes the latter as a dependency. So,
when wasm-lib updates a dep (e.g. bump databake from 1.7 to 1.8), the
former will, upon recompilation, pull in the newer databake dep. But
programmers in the wasm-lib repo don't usually work in the src-tauri repo
and so the src-tauri repo doesn't get updated.
2024-06-14 11:48:31 +02:00
efaae2b193 Bump bson from 2.10.0 to 2.11.0 in /src/wasm-lib (#2614)
Bumps [bson](https://github.com/mongodb/bson-rust) from 2.10.0 to 2.11.0.
- [Release notes](https://github.com/mongodb/bson-rust/releases)
- [Commits](https://github.com/mongodb/bson-rust/compare/v2.10.0...v2.11.0)

---
updated-dependencies:
- dependency-name: bson
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-13 15:42:47 -04:00
7e4ebacb72 Stale Cargo.lock, clippy 1.79 fixes (#2651)
* Update Cargo.lock in src-tauri, fix clippy

* Update circular pattern 3d test
2024-06-13 15:42:21 -04:00
72482506c3 add lint playwright test (#2646)
add lint test

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-06-11 17:05:25 -07:00
a51b5b09a3 Add in a prototype KCL linter (#2521)
* Add in a prototype KCL linter

This is a fork-and-replce of an experimental project I hacked up called
"kcl-vet", which was mostly the same code. This integrates kcl-vet into
the kcl_lib crate, which will let us use this from the zoo cli, as well
as via wasm in the lsp. this contains the intial integration with the
lsp, adding all lints as informational to start.

I need to go back and clean some of this up (and merge some of this back
into other parts of kcl_lib); but this has some pretty good progress
already.

Co-authored-by: jess@zoo.dev
Signed-off-by: Paul R. Tagliamonte <paul@zoo.dev>

* ty clippy :)

* add in a lint test

* add in some docstrings

* whoops

* sigh

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

* uno reverse card

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

* wtf stop it robot fuck

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

* Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)"

This reverts commit 5b18f3c035.

* hurm

* try harder to type slower

* try harder? this all passes locally.

* try this now

* simplify, add debugging for trace

* fix enter use

* re-order again

* reorder a bit more

* enter

* ok fine no other enters?

* nerd

* wip

* move control of clearing to typescript

* move result out

* err check

* remove log

* remove clear

* remove add to diag

* THERE CAN BE ONLY ONE

* _err

* dedupe

* Revert "dedupe"

This reverts commit f66de88200.

* attempt to dedupe

* clear diagnostics on mock execute, too

* handle dupe diagnostics

* fmt

* dedupe tsc

* == vs ===

* fix dedupe

* return this to the wasm for now

* clear the map every go around

this is different than the old code isnce it won't republish

---------

Signed-off-by: Paul R. Tagliamonte <paul@zoo.dev>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-11 16:23:35 -07:00
53ccc1ed6c Swap out icons for bug and refresh, tweak tooltip appearance (#2641)
* add bug icon, swap out refresh icon

* remove lame theme color outline from tooltips

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

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-11 14:37:15 -04:00
8106749ccf Bump databake from 0.1.7 to 0.1.8 in /src/wasm-lib (#2545)
Bumps [databake](https://github.com/unicode-org/icu4x) from 0.1.7 to 0.1.8.
- [Release notes](https://github.com/unicode-org/icu4x/releases)
- [Changelog](https://github.com/unicode-org/icu4x/blob/main/CHANGELOG.md)
- [Commits](https://github.com/unicode-org/icu4x/commits)

---
updated-dependencies:
- dependency-name: databake
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jess Frazelle <jessfraz@users.noreply.github.com>
2024-06-11 07:49:30 -05:00
081e34a600 Bump regex from 1.10.4 to 1.10.5 in /src/wasm-lib (#2637)
Bumps [regex](https://github.com/rust-lang/regex) from 1.10.4 to 1.10.5.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.10.4...1.10.5)

---
updated-dependencies:
- dependency-name: regex
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-10 17:29:24 -07:00
541400f4be Cut release v0.22.1 (#2634) 2024-06-07 14:49:29 -04:00
39d249030d remove more page.clicks (#2630)
* remove more page.clicks

* fmt
2024-06-07 12:31:22 +10:00
f8a69fac73 Remove page.clicks from test utils (#2629)
* remove page.clicks from test utils

* timeout
2024-06-07 00:48:42 +00:00
24f4bf160f Add a right-click (or "context") menu to file tree and gizmo (#2628)
* Basic context menu components

* Working context menu!

* Show keyboard shortcuts in file tree context menu

* Add context menu to Gizmo

* Little polish on components

* Add a test for the gizmo, firm up other gizmo tests

* Updated Cargo lock

* Updated Cargo.lock
2024-06-06 19:56:46 -04:00
8011594e24 Fix most trackpad zoom jank (#2613)
* Remove zoom throttling

And use the mouse zoom for sketch mode

* test tweaks

* test tweak

---------

Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
2024-06-07 09:48:54 +10:00
0e09affb8f Remove debug logging from Engine Connection (#2623)
* Remove debug logging from Engine Connection

Left console.log('connectionstatechange: ' + event.target?.connectionState) intentionally

* Bring that beat back

@lf94 request that we keep this one and also make sure it's in coredump.
2024-06-07 07:16:55 +10:00
197a47346a Refactor: Break functions into smaller functions (#2622)
* Factor ExecutionCtx into its own fn

* Add hyper for tests

* Further factor out functions
2024-06-07 07:01:41 +10:00
9d083710e0 Bump actions/cache from 3 to 4 (#2616)
Bumps [actions/cache](https://github.com/actions/cache) from 3 to 4.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/cache
  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-06-06 13:05:20 -07:00
afa7c1dc4e Bump toml from 0.8.13 to 0.8.14 in /src/wasm-lib (#2615)
Bumps [toml](https://github.com/toml-rs/toml) from 0.8.13 to 0.8.14.
- [Commits](https://github.com/toml-rs/toml/compare/toml-v0.8.13...toml-v0.8.14)

---
updated-dependencies:
- dependency-name: toml
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-06 13:05:01 -07:00
c74b695a71 Remove an orphaned grackle file (#2611) 2024-06-06 14:48:58 -05:00
d0c244e05e Do not aggressively disconnect when video stream goes down (#2621) 2024-06-06 11:40:39 -04:00
a315b77f02 More selection verification (#2619) 2024-06-06 11:55:22 +00:00
15c854ff18 verify sketches can be selected outside of sketches (#2618) 2024-06-06 08:07:42 +00:00
acd3a5717d improve selections and remove redundant edit_mode (#2617) 2024-06-06 16:03:10 +10:00
8a2555550f Adding a sample using a custom axis in revolve.rs (#2596)
* Adding a sample using a custom axis in revolve.rs

* Adding updated docs and snapshot of generated part

* Running fmt
2024-06-05 19:48:59 +00:00
62e75c852a Bump dawidd6/action-download-artifact from 4 to 5 (#2601)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 4 to 5.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v4...v5)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  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-06-05 09:44:13 -07:00
max
dd3601ea7b Gizmo Normal Snapping (#2539)
* gizmo 2.0

nice and clickable

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

* initial mouse position fix

when the scene first loads, mouse position is 0,0, which renders the gizmo selected.

* animation loop / disposal optimization

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

* reset camera tweak

* add cam target to debug panel

* test stub

* reset camera position handle removed from gizmo

it is now a button in the debug panel

* gizmo refactoring

* small fix

* reset camera view

bug fix

* nicer updateCameraToAxis

now gizmo rotates around the target instead of world 0,0,0

* micro refactoring

* playwright update

* playwright remove timeout + fmt

* hide gizmo while loading stream

* Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)"

This reverts commit f0a506d6b9.

* Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)"

This reverts commit 2781261331.

* try make gizmo test more realiable

* tweak

* refactoring

* increase timeout time

* 1 sec wait after mouse click

* 3 sec timeout

* better clickPosition

* test with 10 sec timeout

* 0.5 sec timeout

* add passive update for gizmo to avoid some edge cases

* default_camera_get_settings after click

* try and remove timeouts

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
2024-06-05 12:43:12 +00:00
a5e7782d9a Re-enable rust cache for src-tauri on Windows (#2586) 2024-06-05 06:06:25 -04:00
79b0b70688 Bump ts-rs from badbac0 to be0349d in /src/wasm-lib (#2602) 2024-06-05 03:40:42 -05:00
1d134c1be0 Timeout ahead of flaky sign out (#2593) 2024-06-05 04:36:26 -04:00
1c58572234 cache playwright follow up (#2605)
cache plawwright follow up
2024-06-05 05:53:21 +00:00
ecee51e82b cache playwright browsers (#2604) 2024-06-05 05:10:49 +00:00
978ac42f1c get pixel colour util for e2e tests (#2599)
* get pixel colour for e2e tests

* remove cleverness
2024-06-05 00:36:12 +00:00
893996430e Bump parse-display from 0.9.0 to 0.9.1 in /src/wasm-lib (#2561)
Bumps [parse-display](https://github.com/frozenlib/parse-display) from 0.9.0 to 0.9.1.
- [Changelog](https://github.com/frozenlib/parse-display/blob/master/CHANGELOG.md)
- [Commits](https://github.com/frozenlib/parse-display/compare/v0.9.0...v0.9.1)

---
updated-dependencies:
- dependency-name: parse-display
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Jess Frazelle <jessfraz@users.noreply.github.com>
2024-06-04 17:27:47 -07:00
41e65fc4e9 Bump proc-macro2 from 1.0.84 to 1.0.85 in /src/wasm-lib (#2575)
Bumps [proc-macro2](https://github.com/dtolnay/proc-macro2) from 1.0.84 to 1.0.85.
- [Release notes](https://github.com/dtolnay/proc-macro2/releases)
- [Commits](https://github.com/dtolnay/proc-macro2/compare/1.0.84...1.0.85)

---
updated-dependencies:
- dependency-name: proc-macro2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-04 17:27:32 -07:00
99aa74ceba Bump tokio-tungstenite from 0.21.0 to 0.23.0 in /src/wasm-lib (#2576)
Bumps [tokio-tungstenite](https://github.com/snapview/tokio-tungstenite) from 0.21.0 to 0.23.0.
- [Changelog](https://github.com/snapview/tokio-tungstenite/blob/master/CHANGELOG.md)
- [Commits](https://github.com/snapview/tokio-tungstenite/commits)

---
updated-dependencies:
- dependency-name: tokio-tungstenite
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-04 17:27:22 -07:00
0bcf33ed00 Bump tokio from 1.37.0 to 1.38.0 in /src/wasm-lib (#2562)
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.37.0 to 1.38.0.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.37.0...tokio-1.38.0)

---
updated-dependencies:
- dependency-name: tokio
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-04 16:47:26 -07:00
d0a9b5ecab Faster debug builds (#2571)
Suggested reading:

https://doc.rust-lang.org/cargo/reference/profiles.html#profiles
https://doc.rust-lang.org/cargo/reference/profiles.html#debug
2024-06-04 22:10:28 +00:00
a569f818cf Bump image and 2020 crates (#2556) 2024-06-04 22:09:01 +00:00
f73556ba7b Remove grackle (#2566) 2024-06-04 16:28:32 -05:00
29cdc66b34 Prevent Firefox's global paste behavior if paste target is not also focused (#2581)
* Prevent Firefox's global paste behavior if paste target is not also focused

* Write a test, fix code thanks to test

* Add one more comment to test
2024-06-04 14:36:34 -04:00
c9800a58d0 Update code mods for extrude so that new top-level constants are created (#2549)
* Make sketch and extrude produce separate top-level constants

* Fix most tests

* Add a breaking test for sketch on face AST mod

* Use `extrude` instead of `part`

* Implement @Irev-Dev's branch changes from https://github.com/KittyCAD/modeling-app/pull/2472

* Get extrude on face working

* Update incorrect sketch on face test

* Update unit tests

* Fix up E2E test changes

* fmt

* Fix a couple of goofed up test updates

* More specific names for paths to node sent to modelingMachine

* Bump down playwright workers for now

* Slightly more explicit type coercion

* Update snapshot tests

* Missed one other new flow test that wasn't updated to use "sketch001"

* Typo

* Damn missed one more sorry

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

* Re-run CI

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

* I think the multiple sketches test reverted from under me

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-04 13:57:01 -04:00
e46aca4992 Add tab to Settings dialog to view keyboard shortcuts (#2567)
* Add keyboard custom icon

* Refactor Settings to be more modular

* Add basic keybindings view to settings

* Add more shortcuts

* Add link to see keyboard shortcuts tab

* Little more bottom padding

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

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

* Add keybindings to settings search

* Add a playwright test for opening the the keyboard shortcuts

* fmt

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-04 13:56:20 -04:00
9564890b29 Bump dawidd6/action-download-artifact from 3 to 4 (#2588)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 3 to 4.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  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-06-04 09:49:17 -07:00
f8a1f40f20 Show when user can't connect because of a bad token (#2105)
* Reapply "Add ping pong health, remove a timeout interval, fix up netwo… (#1771)

This reverts commit 1913519f68.

* Fix build errors

* Add new error states to network status notification

* Remove unused variable

* Refactor to use Context API for network status

* Don't do any stream events if network is not ok

* Catch LSP errors on bad auth

* Show when authentication is bad (cookie header only)

* Fix formatting

* Fix up types

* Revert awaiting on lsp failure

* Fix tsc

* wip

* wip

* fmt

* Fix typing

* Incorporate ping health; yarn make:dev; faster video stream loss notice

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

* run ci pls

* run ci pls

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

* run ci pls again

* Remove unused variables

* Add new instructions on running Playwright anywhere

* Please the Playwright. Praise the Playwright.

* Correct a vitest

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

* ci again

* Fix tests unrelated to this PR

* Fix flakiness in for segments tests

* Bump to 2 workers

* fmt

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

* fmt

* fmt

* Fixups

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

* ci

* Set workers to 1

* Wait for network status listeners before connecting

* Fix initial connection requirements and trying 2 workers again

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-06-04 08:32:24 -04:00
c551d88db4 add remove constraints to overlays (#2584)
* add remove constrainst to overlay three dot menu

* add tests
2024-06-04 06:29:20 +00:00
8eee3e1c58 Cut release v0.22.0 (#2582) 2024-06-03 21:53:39 -04:00
b02529cae0 perpendicular distance & remove constraint - constraint fixes (#2579)
* perpendicular distance constraint

* remove constraints fix
2024-06-03 12:40:59 +00:00
cf03021366 length constraint fix (#2578)
length constraint
2024-06-03 08:30:30 +00:00
f52d2d55f1 fix horz vert distance contraint (#2572)
fix hor vert distance contraint
2024-06-03 15:37:23 +10:00
59b1319e50 Update rectangle code gen to use profileStart to close shape (#2565)
* Update rectangle code gen to use profileStart to close shape

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

* Re-run CI

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-31 14:02:46 -04:00
b07bbda20b Remove FileTree from ProjectSiderbarMenu (#2544)
* Remove FileTree from ProjectSiderbarMenu

* Remove tests sidebar menu component tests that are no longer relevant
2024-05-31 06:42:20 -04:00
3c01924184 fix ABS XY constraint (#2560)
* fix source rangen for abs x y constraints

* fix abs bug

* add e2e test
2024-05-31 04:00:32 +00:00
bd16902f02 fix single selection angle constraint (#2555)
* fix single selection angle constraint

* fix angle for multi selections

* make test more robust for makos
2024-05-31 11:36:08 +10:00
8c3af1a72a Small refactor and renames (#2548)
Stuff that came up while working on multiple profiles per sketchgroup
2024-05-30 17:48:59 -05:00
33f5d7740d Enable Windows Tauri e2e tests in CI (#2554)
* Renable windows tauri e2e ci, no cache, manual debug build

* Cleanup and add workaround from https://github.com/actions/runner-images/issues/9538

* Added comment
2024-05-30 11:26:56 -07:00
b388f60648 hovering over axis should not remove overlays (#2553) 2024-05-30 11:25:20 +00:00
8f4380be74 Get existing tauri e2e tests to work on Windows (#2394)
* WIP: Get existing tauri e2e tests to work on Windows
Will fix #2393

* Enable windows stage (will fail)

* WIP msedge version sync

* Move setup edge before build

* Manual debug build (no action)

* Specify v119 for npm package

* Fixes on auth test

* Working test on win10

* Clean up

* Disable yarn cache to help debug the mismatch issue

* Revert "Disable yarn cache to help debug the mismatch issue"

This reverts commit e6abc7db42.

* Explicit webviewOptions and remove tauri driver fork

* Double \\ workaround for windows

* Clean up

* Clean up and readme

* Quick fix

* Lint

* Clippy fix

* Back to tauri-action and disable windows CI tests for early merge

* Back to 10sec delay

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

* Timer reset

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

* Trigger CI

* Back to 1 pw worker

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-30 06:23:56 -04:00
9ae8042a57 Update selections after constraint is applied [horizontal and vertical] (#2551)
* source range for vert horz constraints

* remove commented out code
2024-05-30 09:43:35 +00:00
4b676d47da Update selections after constraint is applied [equal length, parallel, snap to x or y] (#2543)
* migrate one constraint

* typo

* update snap to y, snap to x, horz align, vert align, equal length

* add some e2e tests

* add e2e test for snap to axis contsraits

* remove works for now
2024-05-30 13:28:29 +10:00
e6641e68f3 Add a promise-based toast when exporting (#2541)
* Add loading and success toasts to export engine command

* Move doExport out to a test utility, test visibility of loading spinner

* Add playwright test for export success toast

* Update Cargo.lock

* Remove loading assertion, it flashes too quickly for Playwright to pick up
2024-05-29 18:04:27 -04:00
450afb1605 increase playwright workers (#2518) 2024-05-28 05:32:02 +00:00
04433fecad Bump zip from 1.3.0 to 2.0.0 in /src/wasm-lib (#2536)
Bumps [zip](https://github.com/zip-rs/zip2) from 1.3.0 to 2.0.0.
- [Release notes](https://github.com/zip-rs/zip2/releases)
- [Changelog](https://github.com/zip-rs/zip2/blob/master/CHANGELOG.md)
- [Commits](https://github.com/zip-rs/zip2/compare/v1.3.0...v2.0.0)

---
updated-dependencies:
- dependency-name: zip
  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-05-28 00:31:28 +00:00
6567e2ff92 Bump serde from 1.0.202 to 1.0.203 in /src/wasm-lib (#2537)
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.202 to 1.0.203.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.202...v1.0.203)

---
updated-dependencies:
- dependency-name: serde
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-27 21:31:18 +00:00
91c32a7fe2 Bump proc-macro2 from 1.0.83 to 1.0.84 in /src/wasm-lib (#2538)
Bumps [proc-macro2](https://github.com/dtolnay/proc-macro2) from 1.0.83 to 1.0.84.
- [Release notes](https://github.com/dtolnay/proc-macro2/releases)
- [Commits](https://github.com/dtolnay/proc-macro2/compare/1.0.83...1.0.84)

---
updated-dependencies:
- dependency-name: proc-macro2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-27 19:38:53 +00:00
f735cdc22e fix and simulate engine disconnect when in sketch mode (#2524)
* fix and simulate engine disconnect when in sketch mode

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

* Update e2e/playwright/test-utils.ts

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-24 23:11:49 +00:00
1b72c7df85 Cut release v0.21.9 (#2522) 2024-05-24 23:08:26 +00:00
062abd148f Franknoirot/file tree fixes (#2525)
* Navigate between files with single-click

* Better semantic name for optional event passed into FileTree

* Bug fix: reset modeling state when navigating to a new file

* Add more context to E2E test TODO comment

* Newly-created file tree items are immediately set to renaming mode

* Bug fix: redirect to working file if you delete your current one

* Remove ContextMenu, unrelated branch

* Turn off autocorrect in renaming form

* Gracefully handle renaming a folder that our current file is inside of

* Update cargo.lock

* Fix renaming queue

* Navigate to newly-created files

* Make delete project and delete file/folder share deletion confirmation component

* Bug fix: navigate to project root if we delete our current file's parent directory

* Don't navigate to newly-created directories
2024-05-24 22:12:39 +00:00
c93ed0f306 add a test case for project folders with no kcl files (#2523)
Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-24 21:35:28 +00:00
27e2518dde Fire off "Cancel" modelingMachine event before unmount (#2520)
Co-authored-by: Jess Frazelle <jessfraz@users.noreply.github.com>
2024-05-24 13:01:16 -07:00
dc6505acaf Bump formik from 2.4.5 to 2.4.6 (#2512)
Bumps [formik](https://github.com/jaredpalmer/formik) from 2.4.5 to 2.4.6.
- [Release notes](https://github.com/jaredpalmer/formik/releases)
- [Commits](https://github.com/jaredpalmer/formik/compare/formik@2.4.5...formik@2.4.6)

---
updated-dependencies:
- dependency-name: formik
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-24 12:37:22 -07:00
6ff3284eca Bump @vitejs/plugin-react from 4.2.1 to 4.3.0 (#2513)
Bumps [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) from 4.2.1 to 4.3.0.
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/v4.3.0/packages/plugin-react)

---
updated-dependencies:
- dependency-name: "@vitejs/plugin-react"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-24 12:36:36 -07:00
4cb6ceb043 zoom to fit on between projects tauri fix (#2504)
* fixes

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

* triiger

* make better

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

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

* empty

* fix tests

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-05-24 19:32:15 +00:00
1db3e1b5e4 Bump syn from 2.0.65 to 2.0.66 in /src/wasm-lib (#2516) 2024-05-24 08:36:24 -05:00
d797d20d50 remove semver from snapshots (#2519)
* remove semver from snapshots

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

* trigger ci

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-24 11:59:51 +00:00
cf52e151fb Symbols overlay (#2033)
* start of overlay work

* add new icons

* add constraint symbols

* add three dots

* add primary colours

* refactor how we get constraint info for overlays

* refactor how we get constraint info for overlays

* get symbols working for tangential arc too

* extra data on constraint info

* add initial delete

* fix types and circular dep issue after rebase

* fix quirk with horz vert line overlays

* fix setup and tear down of overlays

* remove overlays that are too small

* throttle overlay updates and prove tests selecting html instead of hardcoded px coords

* initial show overaly on segment hover

* remove overlays when tool is equipped

* dounce overlay updates

* tsc

* make higlighting robust to small changes in source ranges

* replace with variable for unconstrained values, and improve styles for popover

* background tweak

* make overlays unconstrain inputs

* fix small regression

* write query for finding related tag references

* make delete segment safe

* typo

* un used imports

* test deleteSegmentFromPipeExpression

* add getConstraintInfo test

* test removeSingleConstraintInfo

* more tests

* tsc

* add tests for overlay buttons

* rename tests

* fmt

* better naming structure

* more reliablity

* more test tweaks

* fix selection test

* add delete segments with overlays tests

* dependant tag tests for segment delet

* typo

* test clean up

* fix some perf issus

* clean up

* clean up

* make things a little more dry

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

* trigger ci

* Make constraint hover popovers readable on light mode

* Touch up the new variable dialog

* Little touch-up to three-dot menu style

* fix highlight issue

* fmt

* use optional chain

* Revert "A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)"

This reverts commit be3d61e4a3.

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

* disable var panel in sketch mode

* fix overlay tests after mergi in main

* test tweak

* try fix ubuntu

* fmt

* more test tweaks

* tweak

* tweaks

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Frank Noirot <frank@kittycad.io>
2024-05-24 20:54:42 +10:00
87c551b869 quick gizmo homescreen fix (#2509)
* quick gizmo homescreen fix

* better fix
2024-05-24 03:00:15 +00:00
2001262494 add an example for a custom plane (#2507)
* updates

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

* regenerate images

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-23 19:28:13 -07:00
777b225066 Cut release v0.21.8 (#2498)
Co-authored-by: Jess Frazelle <jessfraz@users.noreply.github.com>
2024-05-23 18:01:54 -07:00
ae6373e4f5 actually test that we dont exit sketch mode on first escape (#2501)
* actually test that we dont exit sketch mode on first escape

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

* better test

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-24 00:23:15 +00:00
87979b17cf zoom to fit on load (#2201)
* zoom to fit on load

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

* updates

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

* lint

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

* add zoom to fit calls to the correct places

* update comment

* clean up comment

* add snapshot test zoom to git

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)

* subscribe to camera updates from zoom to fit

* fix types

* partial test fix

* updatges

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

* fix another test

* remove my enhancements

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-24 00:05:54 +00:00
4be63e7331 Allow any value to start a pipe expression (#2496)
Relaxes an arbitrary restriction. Previously KCL pipelines couldn't start
with a number, e.g. `2 |> double(%)`. Now they can.
2024-05-23 16:06:30 -07:00
56d930c4f2 Handle export errors with empty scene or KCL errors (#2477)
* Update Cargo.lock

* Handle bad or empty scene export

Log error and send toast to user

* fmt
2024-05-23 16:03:34 -07:00
d48eb0c66c add plugin for saving scoped permissions will help with dialog behvior (#2497)
* build with persisted scope

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

* more scopes

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-23 14:23:14 -07:00
a69d7d03d0 Check the winnow ParseError before indexing (#2491)
* Check the winnow ParseError before indexing

From the winnow docs at[1]

> The location in ParseError::input where parsing failed
>
> Note: This is an offset, not an index, and may point to the end of input
> (input.len()) on eof errors.

This will bounds check the index before slicing into the `input` vec,
and return an EOF erorr rather than an unknown token error.

[1]: https://docs.rs/winnow/latest/winnow/error/struct.ParseError.html#method.offset

I have a hunch somewhere something is mixing up bytes and chars (more
specifically, a codepoint or grapheme), which is causing bounds to go
past the end of the list since something is talking byte indexes and
the other is dealing with char/codepoint indexes.

For now this is going to fix the crash, but the EOF error may be masking
an actual bad token error in some cases? Our code looks right, so I'm
not quite sure what is going on in the winnow internals here.

Signed-off-by: Paul R. Tagliamonte <paul@kittycad.io>
2024-05-23 16:27:54 -04:00
max
00a8273173 Add Client-Side Gizmo (#2354)
* draft #2279

Add client side gizmo #2279, work in progress

* draft #2279

unreliableSubscriptions

* draft #2279

nice Gizmo

* blue ring

give the canvas a round shape and a border, wrapping rounded div element around the canvas

* Refactor Gizmo Component

Extracted reusable constants
Modularized the code
Simplified the useEffect logic
Added TypeScript type annotations
Improved overall code structure and readability

* remove old gizmo

* fmt

* styling and relocation

 Add className "pointer-events-none" to gizmo wrapper div (for now to prevent context menu)
 Make LowerRightControls container element have these classNames: flex flex-col items-end gap-3
 Move gizmo into LowerRightControls.tsx as the first child of the section element
 Remove the fixed styling from the gizmo div so it flows in flexbox

* fmt

* fix camera up problem

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

* up tweak

* Revert "up tweak"

This reverts commit a53a0ef240.

* test tweak

* tweak test

---------

Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Frank Noirot <frank@kittycad.io>
2024-05-24 06:02:25 +10:00
51868f892b Deduplicate executor code (#2494)
There are many places in the executor codebase which evaluate an AST expression and produce a KCL memory item. They could be deduplicated and put into one central location.

Fixes <https://github.com/KittyCAD/modeling-app/issues/1931>.
2024-05-23 14:50:22 -05:00
8e9286a747 Fix the fuzzer to work with the changed API (#2493)
Simplify the fuzzer a bit

This is the same code, but we'll offload the string parsing to the fuzz
lib, and we can inline the `if Ok(v)`

Signed-off-by: Paul R. Tagliamonte <paul@kittycad.io>
2024-05-23 09:12:40 -07:00
023ed1a687 Home page touch-ups (#2135)
* Save part images when navigating home

* Load part images in project cards if available

* Polish home page

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

* Merge branch 'main' into franknoirot/project-images

* Mostly restored link + form functionality

* Working cards with images

* Comment out project image stuff

* Little style tweaks

* Remove unused imports

* More minor styling tweaks

* Merge branch 'main' into franknoirot/project-images

* Was using the wrong imported `Project` type

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

* Revert any docs changes

* Revert wasm-lib divergences

* Move ProjectCard into its component folder

* Remove unused hook useSaveVideoFrame

* Remove "hideOnLevel" config from theme setting

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-05-23 11:47:02 -04:00
5b7d707b26 playwright test and framework for network stuff (#2480)
* playwright test and framework for network bullshit

 chrome protocol docs for params you can send

 https://chromedevtools.github.io/devtools-protocol/1-3/Network/#method-emulateNetworkConditions

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

* fmt

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

* skip on webkit

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

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-05-23 02:20:40 -07:00
5b95194aa7 fix test hotkey (#2490) 2024-05-23 15:44:19 +10:00
6080a99e73 Bump @react-hook/resize-observer from 1.2.6 to 2.0.1 (#2486)
Bumps [@react-hook/resize-observer](https://github.com/jaredLunde/react-hook) from 1.2.6 to 2.0.1.
- [Commits](https://github.com/jaredLunde/react-hook/commits)

---
updated-dependencies:
- dependency-name: "@react-hook/resize-observer"
  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-05-23 05:22:24 +00:00
5106c49e21 bump kittycad (#2481) 2024-05-23 15:09:40 +10:00
25f18845c7 Update point-and-click sketch close code generation to use explicit lines (#2489)
* Modify sketch profile completion to use `profileStart` utilties

* Fix up playwright tests

* Rerun CI
2024-05-23 00:53:15 -04:00
0a7f1a41fc Bump vscode-jsonrpc from 8.2.0 to 8.2.1 (#2484)
Bumps [vscode-jsonrpc](https://github.com/Microsoft/vscode-languageserver-node/tree/HEAD/jsonrpc) from 8.2.0 to 8.2.1.
- [Release notes](https://github.com/Microsoft/vscode-languageserver-node/releases)
- [Commits](https://github.com/Microsoft/vscode-languageserver-node/commits/release/jsonrpc/8.2.1/jsonrpc)

---
updated-dependencies:
- dependency-name: vscode-jsonrpc
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-22 21:31:34 -07:00
1625b58577 Bump @tauri-apps/api from 2.0.0-beta.8 to 2.0.0-beta.12 (#2483)
Bumps [@tauri-apps/api](https://github.com/tauri-apps/tauri) from 2.0.0-beta.8 to 2.0.0-beta.12.
- [Release notes](https://github.com/tauri-apps/tauri/releases)
- [Commits](https://github.com/tauri-apps/tauri/compare/@tauri-apps/api-v2.0.0-beta.8...@tauri-apps/api-v2.0.0-beta.12)

---
updated-dependencies:
- dependency-name: "@tauri-apps/api"
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-22 21:31:21 -07:00
ab6115c4e2 Bump ws from 8.16.0 to 8.17.0 (#2482)
Bumps [ws](https://github.com/websockets/ws) from 8.16.0 to 8.17.0.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.16.0...8.17.0)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-22 21:30:55 -07:00
387 changed files with 27403 additions and 13746 deletions

View File

@ -1,3 +1,3 @@
[codespell]
ignore-words-list: crate,everytime,inout,co-ordinate,ot,nwo,absolutey,atleast
ignore-words-list: crate,everytime,inout,co-ordinate,ot,nwo,absolutey,atleast,ue
skip: **/target,node_modules,build,**/Cargo.lock,./docs/kcl/*.md,./src-tauri/gen/schemas

1
.envrc Normal file
View File

@ -0,0 +1 @@
use flake .

40
.github/workflows/cargo-check.yml vendored Normal file
View File

@ -0,0 +1,40 @@
on:
push:
branches:
- main
paths:
- '**/Cargo.toml'
- '**/Cargo.lock'
- '**/rust-toolchain.toml'
- '**.rs'
- .github/workflows/cargo-check.yml
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
name: cargo check
jobs:
cargocheck:
name: cargo check
runs-on: ubuntu-latest
strategy:
matrix:
dir: ['src/wasm-lib']
steps:
- uses: actions/checkout@v4
- name: Install latest rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@v2.6.1
- name: Run check
run: |
cd "${{ matrix.dir }}"
# We specifically want to test the disable-println feature
# Since it is not enabled by default, we need to specify it
# This is used in kcl-lsp
cargo check --all --features disable-println --features pyo3

View File

@ -9,6 +9,12 @@ on:
- '**.rs'
- .github/workflows/cargo-clippy.yml
pull_request:
paths:
- '**/Cargo.toml'
- '**/Cargo.lock'
- '**/rust-toolchain.toml'
- '**.rs'
- .github/workflows/cargo-clippy.yml
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true
@ -54,3 +60,8 @@ jobs:
run: |
cd "${{ matrix.dir }}"
cargo clippy --all --tests --benches -- -D warnings
# If this fails, run "cargo check" to update Cargo.lock,
# then add Cargo.lock to the PR.
- name: Check Cargo.lock doesn't need updating
run: |
cargo check --locked || echo "Pls run cargo check and commit the changed Cargo.lock"

View File

@ -147,6 +147,14 @@ jobs:
cp artifact/src-tauri/tauri.conf.json src-tauri/tauri.conf.json
cp artifact/src-tauri/tauri.release.conf.json src-tauri/tauri.release.conf.json
- name: Update WebView2 on Windows
if: matrix.os == 'windows-latest'
# Workaround needed to build the tauri windows app with matching edge version.
# From https://github.com/actions/runner-images/issues/9538
run: |
Invoke-WebRequest -Uri 'https://go.microsoft.com/fwlink/p/?LinkId=2124703' -OutFile 'setup.exe'
Start-Process -FilePath setup.exe -Verb RunAs -Wait
- name: Install ubuntu system dependencies
if: matrix.os == 'ubuntu-latest'
run: |
@ -172,9 +180,7 @@ jobs:
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
# TODO: re-enable for Windows builds, see https://github.com/tauri-apps/tauri/issues/9045
- name: Setup Rust cache
if: matrix.os != 'windows-latest'
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
@ -364,6 +370,17 @@ jobs:
E2E_APPLICATION: "./src-tauri/target/${{ env.BUILD_RELEASE == 'true' && 'release' || 'debug' }}/zoo-modeling-app"
KITTYCAD_API_TOKEN: ${{ env.BUILD_RELEASE == 'true' && secrets.KITTYCAD_API_TOKEN || secrets.KITTYCAD_API_TOKEN_DEV }}
- name: Run e2e tests (windows only)
if: ${{ matrix.os == 'windows-latest' && github.event_name != 'release' && github.event_name != 'schedule' }}
run: |
cargo install tauri-driver --force
yarn wdio run wdio.conf.ts
env:
E2E_APPLICATION: ".\\src-tauri\\target\\${{ env.BUILD_RELEASE == 'true' && 'release' || 'debug' }}\\Zoo Modeling App.exe"
KITTYCAD_API_TOKEN: ${{ env.BUILD_RELEASE == 'true' && secrets.KITTYCAD_API_TOKEN || secrets.KITTYCAD_API_TOKEN_DEV }}
VITE_KC_API_BASE_URL: ${{ env.BUILD_RELEASE == 'true' && 'https://api.zoo.dev' || 'https://api.dev.zoo.dev' }}
E2E_TAURI_ENABLED: true
TS_NODE_COMPILER_OPTIONS: '{"module": "commonjs"}'
publish-apps-release:
runs-on: ubuntu-latest

View File

@ -46,12 +46,18 @@ jobs:
- uses: KittyCAD/action-install-cli@main
- name: Install dependencies
run: yarn
- name: Cache Playwright Browsers
uses: actions/cache@v4
with:
path: |
~/.cache/ms-playwright/
key: ${{ runner.os }}-playwright-${{ hashFiles('yarn.lock') }}
- name: Install Playwright Browsers
run: yarn playwright install --with-deps
- name: Download Wasm Cache
id: download-wasm
if: needs.check-rust-changes.outputs.rust-changed == 'false'
uses: dawidd6/action-download-artifact@v3
uses: dawidd6/action-download-artifact@v6
continue-on-error: true
with:
github_token: ${{secrets.GITHUB_TOKEN}}
@ -127,7 +133,7 @@ jobs:
- uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
name: playwright-report-ubuntu
path: playwright-report/
retention-days: 30
@ -143,12 +149,20 @@ jobs:
cache: 'yarn'
- name: Install dependencies
run: yarn
- name: Cache Playwright Browsers
uses: actions/cache@v4
with:
path: |
~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install Playwright Browsers
run: yarn playwright install --with-deps
- name: Download Wasm Cache
id: download-wasm
if: needs.check-rust-changes.outputs.rust-changed == 'false'
uses: dawidd6/action-download-artifact@v3
uses: dawidd6/action-download-artifact@v6
continue-on-error: true
with:
github_token: ${{secrets.GITHUB_TOKEN}}
@ -190,6 +204,6 @@ jobs:
- uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
name: playwright-report-macos
path: playwright-report/
retention-days: 30

1
.gitignore vendored
View File

@ -17,6 +17,7 @@
.env.development.local
.env.test.local
.env.production.local
.direnv
npm-debug.log*
yarn-debug.log*

14
Makefile Normal file
View File

@ -0,0 +1,14 @@
.PHONY: dev
WASM_LIB_FILES := $(wildcard src/wasm-lib/**/*.rs)
dev: node_modules public/wasm_lib_bg.wasm
yarn start
public/wasm_lib_bg.wasm: $(WASM_LIB_FILES)
yarn build:wasm-dev
node_modules: package.json
package.json:
yarn install

View File

@ -197,28 +197,32 @@ For more information on fuzzing you can check out
### Playwright
First time running plawright locally, you'll need to add the secrets file
For a portable way to run Playwright you'll need Docker.
After that, open a terminal and run:
```bash
touch ./e2e/playwright/playwright-secrets.env
printf 'token="your-token"\nsnapshottoken="your-snapshot-token"' > ./e2e/playwright/playwright-secrets.env
docker run --network host --rm --init -it playwright/chrome:playwright-1.43.1
```
and in another terminal, run:
```bash
PW_TEST_CONNECT_WS_ENDPOINT=ws://127.0.0.1:4444/ yarn playwright test --project="Google Chrome" <test suite>
```
An example of a `<test suite>` is: `e2e/playwright/flow-tests.spec.ts`
YOU WILL NEED A PLAYWRIGHT-SECRETS.ENV FILE:
```bash
# ./e2e/playwright/playwright-secrets.env
token=<your-token>
snapshottoken=<your-snapshot-token>
```
then replace "your-token" with a dev token from dev.zoo.dev/account/api-tokens
then:
run playwright
```
yarn playwright test
```
run a specific test suite
```
yarn playwright test src/e2e-tests/example.spec.ts
```
run a specific test change the test from `test('...` to `test.only('...`
(note if you commit this, the tests will instantly fail without running any of the tests)
@ -309,6 +313,25 @@ PS: for the debug panel, the following JSON is useful for snapping the camera
</details>
### Tauri e2e tests
#### Windows (local only until the CI edge version mismatch is fixed)
```
yarn install
yarn build:wasm-dev
cp src/wasm-lib/pkg/wasm_lib_bg.wasm public
yarn vite build --mode development
yarn tauri build --debug -b
$env:KITTYCAD_API_TOKEN="<YOUR_KITTYCAD_API_TOKEN>"
$env:VITE_KC_API_BASE_URL="https://api.dev.zoo.dev"
$env:E2E_TAURI_ENABLED="true"
$env:TS_NODE_COMPILER_OPTIONS='{"module": "commonjs"}'
$env:E2E_APPLICATION=".\src-tauri\target\debug\Zoo Modeling App.exe"
Stop-Process -Name msedgedriver
yarn wdio run wdio.conf.ts
```
## KCL
For how to contribute to KCL, [see our KCL README](https://github.com/KittyCAD/modeling-app/tree/main/src/wasm-lib/kcl).

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

323
docs/kcl/chamfer.md Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -23,6 +23,7 @@ layout: manual
* [`atan`](kcl/atan)
* [`bezierCurve`](kcl/bezierCurve)
* [`ceil`](kcl/ceil)
* [`chamfer`](kcl/chamfer)
* [`circle`](kcl/circle)
* [`close`](kcl/close)
* [`cos`](kcl/cos)
@ -64,6 +65,7 @@ layout: manual
* [`segEndX`](kcl/segEndX)
* [`segEndY`](kcl/segEndY)
* [`segLen`](kcl/segLen)
* [`shell`](kcl/shell)
* [`sin`](kcl/sin)
* [`sqrt`](kcl/sqrt)
* [`startProfileAt`](kcl/startProfileAt)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

311
docs/kcl/shell.md Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
import { test, expect, Download } from '@playwright/test'
import { test, expect } from '@playwright/test'
import { secrets } from './secrets'
import { getUtils } from './test-utils'
import { Paths, doExport, getUtils } from './test-utils'
import { Models } from '@kittycad/lib'
import fsp from 'fs/promises'
import { spawn } from 'child_process'
import { APP_NAME, KCL_DEFAULT_LENGTH } from 'lib/constants'
import { KCL_DEFAULT_LENGTH } from 'lib/constants'
import JSZip from 'jszip'
import path from 'path'
import { TEST_SETTINGS, TEST_SETTINGS_KEY } from './storageStates'
@ -20,6 +20,7 @@ test.beforeEach(async ({ page }) => {
localStorage.setItem('TOKEN_PERSIST_KEY', token)
localStorage.setItem('persistCode', ``)
localStorage.setItem(settingsKey, settings)
localStorage.setItem('playwright', 'true')
},
{
token: secrets.token,
@ -44,7 +45,7 @@ test.setTimeout(60_000)
test('exports of each format should work', async ({ page, context }) => {
// FYI this test doesn't work with only engine running locally
// And you will need to have the KittyCAD CLI installed
const u = getUtils(page)
const u = await getUtils(page)
await context.addInitScript(async () => {
;(window as any).playwrightSkipFilePicker = true
localStorage.setItem(
@ -98,78 +99,6 @@ const part001 = startSketchOn('-XZ')
await page.waitForTimeout(1000)
await u.clearAndCloseDebugPanel()
interface Paths {
modelPath: string
imagePath: string
outputType: string
}
const doExport = async (
output: Models['OutputFormat_type']
): Promise<Paths> => {
await page.getByRole('button', { name: APP_NAME }).click()
await expect(
page.getByRole('button', { name: 'Export Part' })
).toBeVisible()
await page.getByRole('button', { name: 'Export Part' }).click()
await expect(page.getByTestId('command-bar')).toBeVisible()
// Go through export via command bar
await page.getByRole('option', { name: output.type, exact: false }).click()
await page.locator('#arg-form').waitFor({ state: 'detached' })
if ('storage' in output) {
await page.getByTestId('arg-name-storage').waitFor({ timeout: 1000 })
await page.getByRole('button', { name: 'storage', exact: false }).click()
await page
.getByRole('option', { name: output.storage, exact: false })
.click()
await page.locator('#arg-form').waitFor({ state: 'detached' })
}
await expect(page.getByText('Confirm Export')).toBeVisible()
const getPromiseAndResolve = () => {
let resolve: any = () => {}
const promise = new Promise<Download>((r) => {
resolve = r
})
return [promise, resolve]
}
const [downloadPromise1, downloadResolve1] = getPromiseAndResolve()
let downloadCnt = 0
page.on('download', async (download) => {
if (downloadCnt === 0) {
downloadResolve1(download)
}
downloadCnt++
})
await page.getByRole('button', { name: 'Submit command' }).click()
// Handle download
const download = await downloadPromise1
const downloadLocationer = (extra = '', isImage = false) =>
`./e2e/playwright/export-snapshots/${output.type}-${
'storage' in output ? output.storage : ''
}${extra}.${isImage ? 'png' : output.type}`
const downloadLocation = downloadLocationer()
await download.saveAs(downloadLocation)
if (output.type === 'step') {
// stable timestamps for step files
const fileContents = await fsp.readFile(downloadLocation, 'utf-8')
const newFileContents = fileContents.replace(
/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+[0-9]+[0-9]\+[0-9]{2}:[0-9]{2}/g,
'1970-01-01T00:00:00.0+00:00'
)
await fsp.writeFile(downloadLocation, newFileContents)
}
return {
modelPath: downloadLocation,
imagePath: downloadLocationer('', true),
outputType: output.type,
}
}
const axisDirectionPair: Models['AxisDirectionPair_type'] = {
axis: 'z',
direction: 'positive',
@ -185,84 +114,114 @@ const part001 = startSketchOn('-XZ')
// just note that only `type` and `storage` are used for selecting the drop downs is the app
// the rest are only there to make typescript happy
exportLocations.push(
await doExport({
type: 'step',
coords: sysType,
})
await doExport(
{
type: 'step',
coords: sysType,
},
page
)
)
exportLocations.push(
await doExport({
type: 'ply',
coords: sysType,
selection: { type: 'default_scene' },
storage: 'ascii',
units: 'in',
})
await doExport(
{
type: 'ply',
coords: sysType,
selection: { type: 'default_scene' },
storage: 'ascii',
units: 'in',
},
page
)
)
exportLocations.push(
await doExport({
type: 'ply',
storage: 'binary_little_endian',
coords: sysType,
selection: { type: 'default_scene' },
units: 'in',
})
await doExport(
{
type: 'ply',
storage: 'binary_little_endian',
coords: sysType,
selection: { type: 'default_scene' },
units: 'in',
},
page
)
)
exportLocations.push(
await doExport({
type: 'ply',
storage: 'binary_big_endian',
coords: sysType,
selection: { type: 'default_scene' },
units: 'in',
})
await doExport(
{
type: 'ply',
storage: 'binary_big_endian',
coords: sysType,
selection: { type: 'default_scene' },
units: 'in',
},
page
)
)
exportLocations.push(
await doExport({
type: 'stl',
storage: 'ascii',
coords: sysType,
units: 'in',
selection: { type: 'default_scene' },
})
await doExport(
{
type: 'stl',
storage: 'ascii',
coords: sysType,
units: 'in',
selection: { type: 'default_scene' },
},
page
)
)
exportLocations.push(
await doExport({
type: 'stl',
storage: 'binary',
coords: sysType,
units: 'in',
selection: { type: 'default_scene' },
})
await doExport(
{
type: 'stl',
storage: 'binary',
coords: sysType,
units: 'in',
selection: { type: 'default_scene' },
},
page
)
)
exportLocations.push(
await doExport({
// obj seems to be a little flaky, times out tests sometimes
type: 'obj',
coords: sysType,
units: 'in',
})
await doExport(
{
// obj seems to be a little flaky, times out tests sometimes
type: 'obj',
coords: sysType,
units: 'in',
},
page
)
)
exportLocations.push(
await doExport({
type: 'gltf',
storage: 'embedded',
presentation: 'pretty',
})
await doExport(
{
type: 'gltf',
storage: 'embedded',
presentation: 'pretty',
},
page
)
)
exportLocations.push(
await doExport({
type: 'gltf',
storage: 'binary',
presentation: 'pretty',
})
await doExport(
{
type: 'gltf',
storage: 'binary',
presentation: 'pretty',
},
page
)
)
exportLocations.push(
await doExport({
type: 'gltf',
storage: 'standard',
presentation: 'pretty',
})
await doExport(
{
type: 'gltf',
storage: 'standard',
presentation: 'pretty',
},
page
)
)
// close page to disconnect websocket since we can only have one open atm
@ -369,7 +328,7 @@ const extrudeDefaultPlane = async (context: any, page: any, plane: string) => {
localStorage.setItem('persistCode', code)
})
const u = getUtils(page)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
await page.goto('/')
await u.waitForAuthSkipAppStart()
@ -424,7 +383,7 @@ test.describe('extrude on default planes should be stable', () => {
})
test('Draft segments should look right', async ({ page, context }) => {
const u = getUtils(page)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.goto('/')
@ -446,17 +405,16 @@ test('Draft segments should look right', async ({ page, context }) => {
// select a plane
await page.mouse.click(700, 200)
await expect(page.locator('.cm-content')).toHaveText(
`const part001 = startSketchOn('XZ')`
)
let code = `const sketch001 = startSketchOn('XZ')`
await expect(page.locator('.cm-content')).toHaveText(code)
await page.waitForTimeout(300) // TODO detect animation ending, or disable animation
await page.waitForTimeout(700) // TODO detect animation ending, or disable animation
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([9.06, -12.22], %)`)
code += `
|> startProfileAt([7.19, -9.7], %)`
await expect(page.locator('.cm-content')).toHaveText(code)
await page.waitForTimeout(100)
await u.closeDebugPanel()
@ -468,10 +426,9 @@ test('Draft segments should look right', async ({ page, context }) => {
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([9.06, -12.22], %)
|> line([9.14, 0], %)`)
code += `
|> line([7.25, 0], %)`
await expect(page.locator('.cm-content')).toHaveText(code)
await page.getByRole('button', { name: 'Tangential Arc' }).click()
@ -483,7 +440,7 @@ test('Draft segments should look right', async ({ page, context }) => {
})
test('Draft rectangles should look right', async ({ page, context }) => {
const u = getUtils(page)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.goto('/')
@ -506,7 +463,7 @@ test('Draft rectangles should look right', async ({ page, context }) => {
await page.mouse.click(700, 200)
await expect(page.locator('.cm-content')).toHaveText(
`const part001 = startSketchOn('XZ')`
`const sketch001 = startSketchOn('XZ')`
)
await page.waitForTimeout(500) // TODO detect animation ending, or disable animation
@ -530,7 +487,7 @@ test('Draft rectangles should look right', async ({ page, context }) => {
test.describe('Client side scene scale should match engine scale', () => {
test('Inch scale', async ({ page }) => {
const u = getUtils(page)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.goto('/')
@ -554,17 +511,16 @@ test.describe('Client side scene scale should match engine scale', () => {
// select a plane
await page.mouse.click(700, 200)
await expect(page.locator('.cm-content')).toHaveText(
`const part001 = startSketchOn('XZ')`
)
let code = `const sketch001 = startSketchOn('XZ')`
await expect(page.locator('.cm-content')).toHaveText(code)
await page.waitForTimeout(300) // TODO detect animation ending, or disable animation
await page.waitForTimeout(600) // TODO detect animation ending, or disable animation
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([9.06, -12.22], %)`)
code += `
|> startProfileAt([7.19, -9.7], %)`
await expect(u.codeLocator).toHaveText(code)
await page.waitForTimeout(100)
await u.closeDebugPanel()
@ -572,21 +528,18 @@ test.describe('Client side scene scale should match engine scale', () => {
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([9.06, -12.22], %)
|> line([9.14, 0], %)`)
code += `
|> line([7.25, 0], %)`
await expect(u.codeLocator).toHaveText(code)
await page.getByRole('button', { name: 'Tangential Arc' }).click()
await page.waitForTimeout(100)
await page.mouse.click(startXPx + PUR * 30, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([9.06, -12.22], %)
|> line([9.14, 0], %)
|> tangentialArcTo([27.34, -3.08], %)`)
code += `
|> tangentialArcTo([21.7, -2.44], %)`
await expect(u.codeLocator).toHaveText(code)
// click tangential arc tool again to unequip it
await page.getByRole('button', { name: 'Tangential Arc' }).click()
@ -633,7 +586,7 @@ test.describe('Client side scene scale should match engine scale', () => {
}),
}
)
const u = getUtils(page)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.goto('/')
@ -657,17 +610,16 @@ test.describe('Client side scene scale should match engine scale', () => {
// select a plane
await page.mouse.click(700, 200)
await expect(page.locator('.cm-content')).toHaveText(
`const part001 = startSketchOn('XZ')`
)
let code = `const sketch001 = startSketchOn('XZ')`
await expect(u.codeLocator).toHaveText(code)
await page.waitForTimeout(300) // TODO detect animation ending, or disable animation
await page.waitForTimeout(600) // TODO detect animation ending, or disable animation
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([230.03, -310.32], %)`)
code += `
|> startProfileAt([182.59, -246.32], %)`
await expect(u.codeLocator).toHaveText(code)
await page.waitForTimeout(100)
await u.closeDebugPanel()
@ -675,21 +627,18 @@ test.describe('Client side scene scale should match engine scale', () => {
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([230.03, -310.32], %)
|> line([232.2, 0], %)`)
code += `
|> line([184.3, 0], %)`
await expect(u.codeLocator).toHaveText(code)
await page.getByRole('button', { name: 'Tangential Arc' }).click()
await page.waitForTimeout(100)
await page.mouse.click(startXPx + PUR * 30, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('XZ')
|> startProfileAt([230.03, -310.32], %)
|> line([232.2, 0], %)
|> tangentialArcTo([694.43, -78.12], %)`)
code += `
|> tangentialArcTo([551.2, -62.01], %)`
await expect(u.codeLocator).toHaveText(code)
await page.getByRole('button', { name: 'Tangential Arc' }).click()
await page.waitForTimeout(100)
@ -719,7 +668,7 @@ test.describe('Client side scene scale should match engine scale', () => {
})
test('Sketch on face with none z-up', async ({ page, context }) => {
const u = getUtils(page)
const u = await getUtils(page)
await context.addInitScript(async (KCL_DEFAULT_LENGTH) => {
localStorage.setItem(
'persistCode',
@ -773,3 +722,76 @@ const part002 = startSketchOn(part001, 'seg01')
maxDiffPixels: 100,
})
})
test('Zoom to fit on load - solid 2d', async ({ page, context }) => {
const u = await getUtils(page)
await context.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`const part001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %)
|> line([20, 0], %)
|> line([0, 20], %)
|> line([-20, 0], %)
|> close(%)
`
)
}, KCL_DEFAULT_LENGTH)
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(2)
await u.closeDebugPanel()
// Wait for the second extrusion to appear
// 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)
await expect(page).toHaveScreenshot({
maxDiffPixels: 100,
})
})
test('Zoom to fit on load - solid 3d', async ({ page, context }) => {
const u = await getUtils(page)
await context.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`const part001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %)
|> line([20, 0], %)
|> line([0, 20], %)
|> line([-20, 0], %)
|> close(%)
|> extrude(10, %)
`
)
}, KCL_DEFAULT_LENGTH)
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(2)
await u.closeDebugPanel()
// Wait for the second extrusion to appear
// 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)
await expect(page).toHaveScreenshot({
maxDiffPixels: 100,
})
})

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 45 KiB

View File

@ -1,5 +1,6 @@
import { SaveSettingsPayload } from 'lib/settings/settingsTypes'
import { Themes } from 'lib/theme'
import { onboardingPaths } from 'routes/Onboarding/paths'
export const TEST_SETTINGS_KEY = '/settings.toml'
export const TEST_SETTINGS = {
@ -22,9 +23,22 @@ export const TEST_SETTINGS = {
},
} satisfies Partial<SaveSettingsPayload>
export const TEST_SETTINGS_ONBOARDING_USER_MENU = {
...TEST_SETTINGS,
app: { ...TEST_SETTINGS.app, onboardingStatus: onboardingPaths.USER_MENU },
} satisfies Partial<SaveSettingsPayload>
export const TEST_SETTINGS_ONBOARDING_EXPORT = {
...TEST_SETTINGS,
app: { ...TEST_SETTINGS.app, onboardingStatus: '/export' },
app: { ...TEST_SETTINGS.app, onboardingStatus: onboardingPaths.EXPORT },
} satisfies Partial<SaveSettingsPayload>
export const TEST_SETTINGS_ONBOARDING_PARAMETRIC_MODELING = {
...TEST_SETTINGS,
app: {
...TEST_SETTINGS.app,
onboardingStatus: onboardingPaths.PARAMETRIC_MODELING,
},
} satisfies Partial<SaveSettingsPayload>
export const TEST_SETTINGS_ONBOARDING_START = {
@ -50,3 +64,25 @@ export const TEST_SETTINGS_CORRUPTED = {
textWrapping: true,
},
} satisfies Partial<SaveSettingsPayload>
export const TEST_CODE_GIZMO = `const part001 = startSketchOn('XZ')
|> startProfileAt([20, 0], %)
|> line([7.13, 4 + 0], %)
|> angledLine({ angle: 3 + 0, length: 3.14 + 0 }, %)
|> lineTo([20.14 + 0, -0.14 + 0], %)
|> xLineTo(29 + 0, %)
|> yLine(-3.14 + 0, %, 'a')
|> xLine(1.63, %)
|> angledLineOfXLength({ angle: 3 + 0, length: 3.14 }, %)
|> angledLineOfYLength({ angle: 30, length: 3 + 0 }, %)
|> angledLineToX({ angle: 22.14 + 0, to: 12 }, %)
|> angledLineToY({ angle: 30, to: 11.14 }, %)
|> angledLineThatIntersects({
angle: 3.14,
intersectTag: 'a',
offset: 0
}, %)
|> tangentialArcTo([13.14 + 0, 13.14], %)
|> close(%)
|> extrude(5 + 7, %)
`

View File

@ -1,21 +1,27 @@
import { expect, Page } from '@playwright/test'
import { test, expect, Page, Download } from '@playwright/test'
import { EngineCommand } from '../../src/lang/std/engineConnection'
import os from 'os'
import fsp from 'fs/promises'
import pixelMatch from 'pixelmatch'
import { PNG } from 'pngjs'
import { Protocol } from 'playwright-core/types/protocol'
import type { Models } from '@kittycad/lib'
import { APP_NAME } from 'lib/constants'
async function waitForPageLoad(page: Page) {
// wait for 'Loading stream...' spinner
await page.getByTestId('loading-stream').waitFor()
// wait for all spinners to be gone
await page.getByTestId('loading').waitFor({ state: 'detached' })
await page
.getByTestId('loading')
.waitFor({ state: 'detached', timeout: 20_000 })
await page.getByTestId('start-sketch').waitFor()
}
async function removeCurrentCode(page: Page) {
const hotkey = process.platform === 'darwin' ? 'Meta' : 'Control'
await page.click('.cm-content')
await page.locator('.cm-content').click()
await page.keyboard.down(hotkey)
await page.keyboard.press('a')
await page.keyboard.up(hotkey)
@ -24,12 +30,12 @@ async function removeCurrentCode(page: Page) {
}
async function sendCustomCmd(page: Page, cmd: EngineCommand) {
await page.fill('[data-testid="custom-cmd-input"]', JSON.stringify(cmd))
await page.click('[data-testid="custom-cmd-send-button"]')
await page.getByTestId('custom-cmd-input').fill(JSON.stringify(cmd))
await page.getByTestId('custom-cmd-send-button').click()
}
async function clearCommandLogs(page: Page) {
await page.click('[data-testid="clear-commands"]')
await page.getByTestId('clear-commands').click()
}
async function expectCmdLog(page: Page, locatorStr: string) {
@ -93,7 +99,80 @@ async function waitForCmdReceive(page: Page, commandType: string) {
.waitFor()
}
export function getUtils(page: Page) {
export const wiggleMove = async (
page: any,
x: number,
y: number,
steps: number,
dist: number,
ang: number,
amplitude: number,
freq: number
) => {
const tau = Math.PI * 2
const deg = tau / 360
const step = dist / steps
for (let i = 0, j = 0; i < dist; i += step, j += 1) {
const [x1, y1] = [0, Math.sin((tau / steps) * j * freq) * amplitude]
const [x2, y2] = [
Math.cos(-ang * deg) * i - Math.sin(-ang * deg) * y1,
Math.sin(-ang * deg) * i + Math.cos(-ang * deg) * y1,
]
const [xr, yr] = [x2, y2]
await page.mouse.move(x + xr, y + yr, { steps: 2 })
}
}
export const getMovementUtils = (opts: any) => {
// The way we truncate is kinda odd apparently, so we need this function
// "[k]itty[c]ad round"
const kcRound = (n: number) => Math.trunc(n * 100) / 100
// To translate between screen and engine ("[U]nit") coordinates
// NOTE: these pretty much can't be perfect because of screen scaling.
// Handle on a case-by-case.
const toU = (x: number, y: number) => [
kcRound(x * 0.0678),
kcRound(-y * 0.0678), // Y is inverted in our coordinate system
]
// Turn the array into a string with specific formatting
const fromUToString = (xy: number[]) => `[${xy[0]}, ${xy[1]}]`
// Combine because used often
const toSU = (xy: number[]) => fromUToString(toU(xy[0], xy[1]))
// Make it easier to click around from center ("click [from] zero zero")
const click00 = (x: number, y: number) =>
opts.page.mouse.click(opts.center.x + x, opts.center.y + y)
// Relative clicker, must keep state
let last = { x: 0, y: 0 }
const click00r = (x?: number, y?: number) => {
// reset relative coordinates when anything is undefined
if (x === undefined || y === undefined) {
last.x = 0
last.y = 0
return
}
const ret = click00(last.x + x, last.y + y)
last.x += x
last.y += y
// Returns the new absolute coordinate if you need it.
return ret.then(() => [last.x, last.y])
}
return { toSU, click00r }
}
export async function getUtils(page: Page) {
// Chrome devtools protocol session only works in Chromium
const browserType = page.context().browser()?.browserType().name()
const cdpSession =
browserType !== 'chromium' ? null : await page.context().newCDPSession(page)
return {
waitForAuthSkipAppStart: () => waitForPageLoad(page),
removeCurrentCode: () => removeCurrentCode(page),
@ -124,6 +203,30 @@ export function getUtils(page: Page) {
},
waitForCmdReceive: (commandType: string) =>
waitForCmdReceive(page, commandType),
getSegmentBodyCoords: async (locator: string, px = 30) => {
const overlay = page.locator(locator)
const bbox = await overlay
.boundingBox()
.then((box) => ({ ...box, x: box?.x || 0, y: box?.y || 0 }))
const angle = Number(await overlay.getAttribute('data-overlay-angle'))
const angleXOffset = Math.cos(((angle - 180) * Math.PI) / 180) * px
const angleYOffset = Math.sin(((angle - 180) * Math.PI) / 180) * px
return {
x: Math.round(bbox.x + angleXOffset),
y: Math.round(bbox.y - angleYOffset),
}
},
getAngle: async (locator: string) => {
const overlay = page.locator(locator)
return Number(await overlay.getAttribute('data-overlay-angle'))
},
getBoundingBox: async (locator: string) =>
page
.locator(locator)
.boundingBox()
.then((box) => ({ ...box, x: box?.x || 0, y: box?.y || 0 })),
codeLocator: page.locator('.cm-content'),
canvasLocator: page.getByTestId('client-side-scene'),
doAndWaitForCmd: async (
fn: () => Promise<void>,
commandType: string,
@ -139,6 +242,30 @@ export function getUtils(page: Page) {
await closeDebugPanel(page)
}
},
/**
* Given an expected RGB value, diff if the channel with the largest difference
*/
getGreatestPixDiff: async (
coords: { x: number; y: number },
expected: [number, number, number]
): Promise<number> => {
const buffer = await page.screenshot({
fullPage: true,
})
const screenshot = await PNG.sync.read(buffer)
// most likely related to pixel density but the screenshots for webkit are 2x the size
// there might be a more robust way of doing this.
const pixMultiplier = browserType === 'webkit' ? 2 : 1
const index =
(screenshot.width * coords.y * pixMultiplier +
coords.x * pixMultiplier) *
4 // rbga is 4 channels
return Math.max(
Math.abs(screenshot.data[index] - expected[0]),
Math.abs(screenshot.data[index + 1] - expected[1]),
Math.abs(screenshot.data[index + 2] - expected[2])
)
},
doAndWaitForImageDiff: (fn: () => Promise<any>, diffCount = 200) =>
new Promise(async (resolve) => {
await page.screenshot({
@ -180,6 +307,17 @@ export function getUtils(page: Page) {
}
}, 50)
}),
emulateNetworkConditions: async (
networkOptions: Protocol.Network.emulateNetworkConditionsParameters
) => {
// Skip on non-Chromium browsers, since we need to use the CDP.
test.skip(
cdpSession === null,
'Network emulation is only supported in Chromium'
)
cdpSession?.send('Network.emulateNetworkConditions', networkOptions)
},
}
}
@ -255,3 +393,82 @@ export const makeTemplate: (
),
}
}
export interface Paths {
modelPath: string
imagePath: string
outputType: string
}
export const doExport = async (
output: Models['OutputFormat_type'],
page: Page
): Promise<Paths> => {
await page.getByRole('button', { name: APP_NAME }).click()
await expect(page.getByRole('button', { name: 'Export Part' })).toBeVisible()
await page.getByRole('button', { name: 'Export Part' }).click()
await expect(page.getByTestId('command-bar')).toBeVisible()
// Go through export via command bar
await page.getByRole('option', { name: output.type, exact: false }).click()
await page.locator('#arg-form').waitFor({ state: 'detached' })
if ('storage' in output) {
await page.getByTestId('arg-name-storage').waitFor({ timeout: 1000 })
await page.getByRole('button', { name: 'storage', exact: false }).click()
await page
.getByRole('option', { name: output.storage, exact: false })
.click()
await page.locator('#arg-form').waitFor({ state: 'detached' })
}
await expect(page.getByText('Confirm Export')).toBeVisible()
const getPromiseAndResolve = () => {
let resolve: any = () => {}
const promise = new Promise<Download>((r) => {
resolve = r
})
return [promise, resolve]
}
const [downloadPromise1, downloadResolve1] = getPromiseAndResolve()
let downloadCnt = 0
page.on('download', async (download) => {
if (downloadCnt === 0) {
downloadResolve1(download)
}
downloadCnt++
})
await page.getByRole('button', { name: 'Submit command' }).click()
// Handle download
const download = await downloadPromise1
const downloadLocationer = (extra = '', isImage = false) =>
`./e2e/playwright/export-snapshots/${output.type}-${
'storage' in output ? output.storage : ''
}${extra}.${isImage ? 'png' : output.type}`
const downloadLocation = downloadLocationer()
await download.saveAs(downloadLocation)
if (output.type === 'step') {
// stable timestamps for step files
const fileContents = await fsp.readFile(downloadLocation, 'utf-8')
const newFileContents = fileContents.replace(
/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+[0-9]+[0-9]\+[0-9]{2}:[0-9]{2}/g,
'1970-01-01T00:00:00.0+00:00'
)
await fsp.writeFile(downloadLocation, newFileContents)
}
return {
modelPath: downloadLocation,
imagePath: downloadLocationer('', true),
outputType: output.type,
}
}
/**
* Gets the appropriate modifier key for the platform.
*/
export const metaModifier = os.platform() === 'darwin' ? 'Meta' : 'Control'

View File

@ -1,31 +1,23 @@
import { browser, $, expect } from '@wdio/globals'
import fs from 'fs/promises'
import path from 'path'
import os from 'os'
import { click, setDatasetValue } from '../utils'
const documentsDir = `${process.env.HOME}/Documents`
const userSettingsDir = `${process.env.HOME}/.config/dev.zoo.modeling-app`
const defaultProjectDir = `${documentsDir}/zoo-modeling-app-projects`
const newProjectDir = `${documentsDir}/a-different-directory`
const userCodeDir = '/tmp/kittycad_user_code'
const isWin32 = os.platform() === 'win32'
const documentsDir = path.join(os.homedir(), 'Documents')
const userSettingsDir = path.join(
os.homedir(),
'.config',
'dev.zoo.modeling-app'
)
const defaultProjectDir = path.join(documentsDir, 'zoo-modeling-app-projects')
const newProjectDir = path.join(documentsDir, 'a-different-directory')
const tmp = process.env.TEMP || '/tmp'
const userCodeDir = path.join(tmp, 'kittycad_user_code')
async function click(element: WebdriverIO.Element): Promise<void> {
// Workaround for .click(), see https://github.com/tauri-apps/tauri/issues/6541
await element.waitForClickable()
await browser.execute('arguments[0].click();', element)
}
/* Shoutout to @Sheap on Github for a great workaround utility:
* https://github.com/tauri-apps/tauri/issues/6541#issue-1638944060
*/
async function setDatasetValue(
field: WebdriverIO.Element,
property: string,
value: string
) {
await browser.execute(`arguments[0].dataset.${property} = "${value}"`, field)
}
describe('ZMA (Tauri, Linux)', () => {
it('opens the auth page and signs in', async () => {
describe('ZMA sign in flow', () => {
before(async () => {
// Clean up filesystem from previous tests
await new Promise((resolve) => setTimeout(resolve, 100))
await fs.rm(defaultProjectDir, { force: true, recursive: true })
@ -34,7 +26,9 @@ describe('ZMA (Tauri, Linux)', () => {
await fs.rm(userSettingsDir, { force: true, recursive: true })
await fs.mkdir(defaultProjectDir, { recursive: true })
await fs.mkdir(newProjectDir, { recursive: true })
})
it('opens the auth page and signs in', async () => {
const signInButton = await $('[data-testid="sign-in-button"]')
expect(await signInButton.getText()).toEqual('Sign in')
@ -42,9 +36,7 @@ describe('ZMA (Tauri, Linux)', () => {
await new Promise((resolve) => setTimeout(resolve, 2000))
// Get from main.rs
const userCode = await (
await fs.readFile('/tmp/kittycad_user_code')
).toString()
const userCode = await (await fs.readFile(userCodeDir)).toString()
console.log(`Found user code ${userCode}`)
// Device flow: verify
@ -76,6 +68,10 @@ describe('ZMA (Tauri, Linux)', () => {
const newFileButton = await $('[data-testid="home-new-file"]')
expect(await newFileButton.getText()).toEqual('New project')
})
})
describe('ZMA authorized user flows', () => {
// Note: each flow below is intended to start *and* end from the home page
it('opens the settings page, checks filesystem settings, and closes the settings page', async () => {
const menuButton = await $('[data-testid="user-sidebar-toggle"]')
@ -92,7 +88,12 @@ describe('ZMA (Tauri, Linux)', () => {
* to be able to skip the folder selection dialog if data-testValue
* has a value, allowing us to test the input otherwise works.
*/
await setDatasetValue(projectDirInput, 'testValue', newProjectDir)
// TODO: understand why we need to force double \ on Windows
await setDatasetValue(
projectDirInput,
'testValue',
isWin32 ? newProjectDir.replaceAll('\\', '\\\\') : newProjectDir
)
const projectDirButton = await $('[data-testid="project-directory-button"]')
await click(projectDirButton)
await new Promise((resolve) => setTimeout(resolve, 500))
@ -102,6 +103,15 @@ describe('ZMA (Tauri, Linux)', () => {
const nameInput = await $('[data-testid="projects-defaultProjectName"]')
expect(await nameInput.getValue()).toEqual('project-$nnn')
// Setting it back (for back to back local tests)
await new Promise((resolve) => setTimeout(resolve, 5000))
await setDatasetValue(
projectDirInput,
'testValue',
isWin32 ? defaultProjectDir.replaceAll('\\', '\\\\') : newProjectDir
)
await click(projectDirButton)
const closeButton = await $('[data-testid="settings-close-button"]')
await click(closeButton)
})
@ -120,12 +130,21 @@ describe('ZMA (Tauri, Linux)', () => {
it('opens the new file and expects a loading stream', async () => {
const projectLink = await $('[data-testid="project-link"]')
await click(projectLink)
const errorText = await $('[data-testid="unexpected-error"]')
expect(await errorText.getText()).toContain('unexpected error')
await browser.execute('window.location.href = "tauri://localhost/home"')
if (isWin32) {
// TODO: actually do something to check that the stream is up
await new Promise((resolve) => setTimeout(resolve, 5000))
} else {
const errorText = await $('[data-testid="unexpected-error"]')
expect(await errorText.getText()).toContain('unexpected error')
}
const base = isWin32 ? 'http://tauri.localhost' : 'tauri://localhost'
await browser.execute(`window.location.href = "${base}/home"`)
})
})
describe('ZMA sign out flow', () => {
it('signs out', async () => {
await new Promise((resolve) => setTimeout(resolve, 1000))
const menuButton = await $('[data-testid="user-sidebar-toggle"]')
await click(menuButton)
const signoutButton = await $('[data-testid="user-sidebar-sign-out"]')

18
e2e/tauri/utils.ts Normal file
View File

@ -0,0 +1,18 @@
import { browser } from '@wdio/globals'
export async function click(element: WebdriverIO.Element): Promise<void> {
// Workaround for .click(), see https://github.com/tauri-apps/tauri/issues/6541
await element.waitForClickable()
await browser.execute('arguments[0].click();', element)
}
/* Shoutout to @Sheap on Github for a great workaround utility:
* https://github.com/tauri-apps/tauri/issues/6541#issue-1638944060
*/
export async function setDatasetValue(
field: WebdriverIO.Element,
property: string,
value: string
) {
await browser.execute(`arguments[0].dataset.${property} = "${value}"`, field)
}

62
flake.lock generated Normal file
View File

@ -0,0 +1,62 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1718470082,
"narHash": "sha256-u2F0MMYE+Efc+ocruTbtU/wWHuYHWcJafp5zJ++n/YE=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "3027ba73dfef68eb555fc2fa97aed4e999e74f97",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs_2": {
"locked": {
"lastModified": 1718428119,
"narHash": "sha256-WdWDpNaq6u1IPtxtYHHWpl5BmabtpmLnMAx0RdJ/vo8=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "e6cea36f83499eb4e9cd184c8a8e823296b50ad5",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs",
"rust-overlay": "rust-overlay"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1718681902,
"narHash": "sha256-E/T7Ge6ayEQe7FVKMJqDBoHyLhRhjc6u9CmU8MyYfy0=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "16c8ad83297c278eebe740dea5491c1708960dd1",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

70
flake.nix Normal file
View File

@ -0,0 +1,70 @@
{
description = "modeling-app development environment";
# Flake inputs
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
rust-overlay.url = "github:oxalica/rust-overlay"; # A helper for Rust + Nix
};
# Flake outputs
outputs = { self, nixpkgs, rust-overlay }:
let
# Overlays enable you to customize the Nixpkgs attribute set
overlays = [
# Makes a `rust-bin` attribute available in Nixpkgs
(import rust-overlay)
# Provides a `rustToolchain` attribute for Nixpkgs that we can use to
# create a Rust environment
(self: super: {
rustToolchain = super. rust-bin.stable.latest.default.override {
targets = [ "wasm32-unknown-unknown" ];
extensions = [ "rustfmt" "llvm-tools-preview" ];
};
})
];
# Systems supported
allSystems = [
"x86_64-linux" # 64-bit Intel/AMD Linux
"aarch64-linux" # 64-bit ARM Linux
"x86_64-darwin" # 64-bit Intel macOS
"aarch64-darwin" # 64-bit ARM macOS
];
# Helper to provide system-specific attributes
forAllSystems = f: nixpkgs.lib.genAttrs allSystems (system: f {
pkgs = import nixpkgs { inherit overlays system; };
});
in
{
# Development environment output
devShells = forAllSystems ({ pkgs }: {
default = pkgs.mkShell {
# The Nix packages provided in the environment
packages = (with pkgs; [
# The package provided by our custom overlay. Includes cargo, Clippy, cargo-fmt,
# rustdoc, rustfmt, and other tools.
rustToolchain
cargo-llvm-cov
cargo-nextest
just
postgresql.lib
openssl
pkg-config
nodejs_22
]) ++ pkgs.lib.optionals pkgs.stdenv.isDarwin (with pkgs; [
libiconv
darwin.apple_sdk.frameworks.Security
]);
TARGET_CC = "${pkgs.stdenv.cc}/bin/${pkgs.stdenv.cc.targetPrefix}cc";
LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
};
});
};
}

View File

@ -1,6 +1,6 @@
{
"name": "untitled-app",
"version": "0.21.7",
"version": "0.22.3",
"private": true,
"dependencies": {
"@codemirror/autocomplete": "^6.16.0",
@ -10,12 +10,12 @@
"@fortawesome/react-fontawesome": "^0.2.0",
"@headlessui/react": "^1.7.19",
"@headlessui/tailwindcss": "^0.2.0",
"@kittycad/lib": "^0.0.60",
"@kittycad/lib": "^0.0.67",
"@lezer/javascript": "^1.4.9",
"@open-rpc/client-js": "^1.8.1",
"@react-hook/resize-observer": "^1.2.6",
"@react-hook/resize-observer": "^2.0.1",
"@replit/codemirror-interact": "^6.3.1",
"@tauri-apps/api": "2.0.0-beta.8",
"@tauri-apps/api": "2.0.0-beta.12",
"@tauri-apps/plugin-dialog": "^2.0.0-beta.2",
"@tauri-apps/plugin-fs": "^2.0.0-beta.3",
"@tauri-apps/plugin-http": "^2.0.0-beta.2",
@ -37,7 +37,7 @@
"crypto-js": "^4.2.0",
"debounce-promise": "^3.1.2",
"decamelize": "^6.0.0",
"formik": "^2.4.5",
"formik": "^2.4.6",
"fuse.js": "^7.0.0",
"html2canvas-pro": "^1.4.3",
"http-server": "^14.1.1",
@ -61,11 +61,11 @@
"ua-parser-js": "^1.0.37",
"uuid": "^9.0.1",
"vitest": "^1.6.0",
"vscode-jsonrpc": "^8.1.0",
"vscode-jsonrpc": "^8.2.1",
"vscode-languageserver-protocol": "^3.17.5",
"wasm-pack": "^0.12.1",
"web-vitals": "^3.5.2",
"ws": "^8.16.0",
"ws": "^8.17.0",
"xstate": "^4.38.2",
"zustand": "^4.5.2"
},
@ -95,7 +95,8 @@
"lint": "eslint --fix src",
"bump-jsons": "echo \"$(jq --arg v \"$VERSION\" '.version=$v' package.json --indent 2)\" > package.json && echo \"$(jq --arg v \"$VERSION\" '.version=$v' src-tauri/tauri.conf.json --indent 2)\" > src-tauri/tauri.conf.json",
"postinstall": "yarn xstate:typegen",
"xstate:typegen": "yarn xstate typegen \"src/**/*.ts?(x)\""
"xstate:typegen": "yarn xstate typegen \"src/**/*.ts?(x)\"",
"make:dev": "make dev"
},
"prettier": {
"trailingComma": "es5",
@ -133,7 +134,7 @@
"@types/wait-on": "^5.3.4",
"@types/wicg-file-system-access": "^2023.10.5",
"@types/ws": "^8.5.10",
"@vitejs/plugin-react": "^4.2.1",
"@vitejs/plugin-react": "^4.3.0",
"@vitest/web-worker": "^1.5.0",
"@wdio/cli": "^8.24.3",
"@wdio/globals": "^8.36.0",

View File

@ -12,12 +12,12 @@ import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './e2e/playwright',
/* Run tests in files in parallel */
fullyParallel: true,
fullyParallel: false,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,
/* Retry on CI only */
retries: process.env.CI ? 3 : 0,
/* Opt out of parallel tests on CI. */
/* Different amount of parallelism on CI and local. */
workers: process.env.CI ? 1 : 1,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
@ -34,7 +34,14 @@ export default defineConfig({
projects: [
{
name: 'Google Chrome',
use: { ...devices['Desktop Chrome'], channel: 'chrome' }, // or 'chrome-beta'
use: {
...devices['Desktop Chrome'],
channel: 'chrome',
contextOptions: {
/* Chromium is the only one with these permission types */
permissions: ['clipboard-write', 'clipboard-read'],
},
}, // or 'chrome-beta'
},
{
name: 'webkit',
@ -72,7 +79,7 @@ export default defineConfig({
/* Run your local dev server before starting the tests */
webServer: {
command: 'yarn serve',
command: 'yarn start',
// url: 'http://127.0.0.1:3000',
reuseExistingServer: !process.env.CI,
},

1689
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -16,11 +16,11 @@ tauri-build = { version = "2.0.0-beta.13", features = [] }
[dependencies]
anyhow = "1"
kcl-lib = { version = "0.1.53", path = "../src/wasm-lib/kcl" }
kittycad = "0.3.0"
kittycad = "0.3.5"
log = "0.4.21"
oauth2 = "4.4.2"
serde_json = "1.0"
tauri = { version = "2.0.0-beta.15", features = [ "devtools", "unstable"] }
tauri = { version = "2.0.0-beta.22", features = [ "devtools", "unstable"] }
tauri-plugin-cli = { version = "2.0.0-beta.3" }
tauri-plugin-deep-link = { version = "2.0.0-beta.3" }
tauri-plugin-dialog = { version = "2.0.0-beta.6" }
@ -28,6 +28,7 @@ tauri-plugin-fs = { version = "2.0.0-beta.6" }
tauri-plugin-http = { version = "2.0.0-beta.6" }
tauri-plugin-log = { version = "2.0.0-beta.4" }
tauri-plugin-os = { version = "2.0.0-beta.2" }
tauri-plugin-persisted-scope = { version = "2.0.0-beta.7" }
tauri-plugin-process = { version = "2.0.0-beta.2" }
tauri-plugin-shell = { version = "2.0.0-beta.2" }
tauri-plugin-updater = { version = "2.0.0-beta.4" }

View File

@ -32,6 +32,15 @@
{
"identifier": "fs:scope",
"allow": [
{
"path": "$TEMP"
},
{
"path": "$TEMP/**/*"
},
{
"path": "$HOME"
},
{
"path": "$HOME/**/*"
},

View File

@ -267,7 +267,15 @@ async fn login(app: tauri::AppHandle, host: &str) -> Result<String, InvokeError>
let e2e_tauri_enabled = env::var("E2E_TAURI_ENABLED").is_ok();
if e2e_tauri_enabled {
log::warn!("E2E_TAURI_ENABLED is set, won't open {} externally", auth_uri.secret());
tokio::fs::write("/tmp/kittycad_user_code", details.user_code().secret())
let mut temp = String::from("/tmp");
// Overwrite with Windows variable
match env::var("TEMP") {
Ok(val) => temp = val,
Err(_e) => println!("Fallback to default /tmp"),
}
let path = Path::new(&temp).join("kittycad_user_code");
println!("Writing to {}", path.to_string_lossy());
tokio::fs::write(path, details.user_code().secret())
.await
.map_err(|e| InvokeError::from_anyhow(e.into()))?;
} else {
@ -425,6 +433,7 @@ fn main() -> Result<()> {
.build(),
)
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_persisted_scope::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_shell::init())
.setup(|app| {

View File

@ -63,16 +63,17 @@
"subcommands": {}
},
"deep-link": {
"domains": [
{
"host": "app.zoo.dev"
}
]
"mobile": [],
"desktop": {
"schemes": [
"app.zoo.dev"
]
}
},
"shell": {
"open": true
}
},
"productName": "Zoo Modeling App",
"version": "0.21.7"
"version": "0.22.3"
}

View File

@ -24,6 +24,7 @@ import { ModelingSidebar } from 'components/ModelingSidebar/ModelingSidebar'
import { LowerRightControls } from 'components/LowerRightControls'
import ModalContainer from 'react-modal-promise'
import useHotkeyWrapper from 'lib/hotkeyWrapper'
import Gizmo from 'components/Gizmo'
export function App() {
useRefreshSettings(paths.FILE + 'SETTINGS')
@ -126,9 +127,11 @@ export function App() {
/>
<ModalContainer />
<ModelingSidebar paneOpacity={paneOpacity} />
<Stream className="absolute inset-0 z-0" />
<Stream />
{/* <CamToggle /> */}
<LowerRightControls />
<LowerRightControls>
<Gizmo />
</LowerRightControls>
</div>
)
}

View File

@ -12,6 +12,8 @@ import SignIn from './routes/SignIn'
import { Auth } from './Auth'
import { isTauri } from './lib/isTauri'
import Home from './routes/Home'
import { NetworkContext } from './hooks/useNetworkContext'
import { useNetworkStatus } from './hooks/useNetworkStatus'
import makeUrlPathRelative from './lib/makeUrlPathRelative'
import DownloadAppBanner from 'components/DownloadAppBanner'
import { WasmErrBanner } from 'components/WasmErrBanner'
@ -155,5 +157,11 @@ const router = createBrowserRouter([
* @returns RouterProvider
*/
export const Router = () => {
return <RouterProvider router={router} />
const networkStatus = useNetworkStatus()
return (
<NetworkContext.Provider value={networkStatus}>
<RouterProvider router={router} />
</NetworkContext.Provider>
)
}

View File

@ -3,22 +3,22 @@ import { isCursorInSketchCommandRange } from 'lang/util'
import { engineCommandManager, kclManager } from 'lib/singletons'
import { useModelingContext } from 'hooks/useModelingContext'
import { useCommandsContext } from 'hooks/useCommandsContext'
import { useNetworkContext } from 'hooks/useNetworkContext'
import { NetworkHealthState } from 'hooks/useNetworkStatus'
import { ActionButton } from 'components/ActionButton'
import { isSingleCursorInPipe } from 'lang/queryAst'
import { useKclContext } from 'lang/KclProvider'
import {
NetworkHealthState,
useNetworkStatus,
} from 'components/NetworkHealthIndicator'
import { useStore } from 'useStore'
import { ActionButtonDropdown } from 'components/ActionButtonDropdown'
import { useHotkeys } from 'react-hotkeys-hook'
import Tooltip from 'components/Tooltip'
export const Toolbar = () => {
const { commandBarSend } = useCommandsContext()
export function Toolbar({
className = '',
...props
}: React.HTMLAttributes<HTMLElement>) {
const { state, send, context } = useModelingContext()
const toolbarButtonsRef = useRef<HTMLUListElement>(null)
const { commandBarSend } = useCommandsContext()
const iconClassName =
'group-disabled:text-chalkboard-50 group-enabled:group-hover:!text-primary dark:group-enabled:group-hover:!text-inherit group-pressed:!text-chalkboard-10 group-ui-open:!text-chalkboard-10 dark:group-ui-open:!text-chalkboard-10'
const bgClassName =
@ -34,13 +34,18 @@ export const Toolbar = () => {
context.selectionRanges
)
}, [engineCommandManager.artifactMap, context.selectionRanges])
const { overallState } = useNetworkStatus()
const toolbarButtonsRef = useRef<HTMLUListElement>(null)
const { overallState } = useNetworkContext()
const { isExecuting } = useKclContext()
const { isStreamReady } = useStore((s) => ({
isStreamReady: s.isStreamReady,
}))
const disableAllButtons =
overallState !== NetworkHealthState.Ok || isExecuting || !isStreamReady
(overallState !== NetworkHealthState.Ok &&
overallState !== NetworkHealthState.Weak) ||
isExecuting ||
!isStreamReady
useHotkeys(
'l',
@ -100,12 +105,45 @@ export const Toolbar = () => {
span.scrollLeft = span.scrollLeft += ev.deltaY
}
const nextEvents = useMemo(() => state.nextEvents, [state.nextEvents])
const splitMenuItems = useMemo(
() =>
nextEvents
.filter(
(eventName) =>
eventName.includes('Make segment') ||
eventName.includes('Constrain')
)
.sort((a, b) => {
const aisEnabled = nextEvents
.filter((event) => state.can(event as any))
.includes(a)
const bIsEnabled = nextEvents
.filter((event) => state.can(event as any))
.includes(b)
if (aisEnabled && !bIsEnabled) {
return -1
}
if (!aisEnabled && bIsEnabled) {
return 1
}
return 0
})
.map((eventName) => ({
label: eventName
.replace('Make segment ', '')
.replace('Constrain ', ''),
onClick: () => send(eventName),
disabled:
!nextEvents
.filter((event) => state.can(event as any))
.includes(eventName) || disableAllButtons,
})),
function ToolbarButtons({
className = '',
...props
}: React.HTMLAttributes<HTMLElement>) {
return (
[JSON.stringify(nextEvents), state]
)
return (
<menu className="max-w-full whitespace-nowrap rounded px-1.5 py-0.5 backdrop-blur-sm bg-chalkboard-10/80 dark:bg-chalkboard-110/70 relative">
<ul
{...props}
ref={toolbarButtonsRef}
@ -113,7 +151,7 @@ export const Toolbar = () => {
className={'m-0 py-1 rounded-l-sm flex gap-2 items-center ' + className}
style={{ scrollbarWidth: 'thin' }}
>
{state.nextEvents.includes('Enter sketch') && (
{nextEvents.includes('Enter sketch') && (
<li className="contents">
<ActionButton
className={buttonClassName}
@ -139,7 +177,7 @@ export const Toolbar = () => {
</ActionButton>
</li>
)}
{state.nextEvents.includes('Enter sketch') && pathId && (
{nextEvents.includes('Enter sketch') && pathId && (
<li className="contents">
<ActionButton
className={buttonClassName}
@ -163,7 +201,7 @@ export const Toolbar = () => {
</ActionButton>
</li>
)}
{state.nextEvents.includes('Cancel') && !state.matches('idle') && (
{nextEvents.includes('Cancel') && !state.matches('idle') && (
<li className="contents">
<ActionButton
className={buttonClassName}
@ -286,43 +324,13 @@ export const Toolbar = () => {
</>
)}
{state.matches('Sketch.SketchIdle') &&
state.nextEvents.filter(
nextEvents.filter(
(eventName) =>
eventName.includes('Make segment') ||
eventName.includes('Constrain')
).length > 0 && (
<ActionButtonDropdown
splitMenuItems={state.nextEvents
.filter(
(eventName) =>
eventName.includes('Make segment') ||
eventName.includes('Constrain')
)
.sort((a, b) => {
const aisEnabled = state.nextEvents
.filter((event) => state.can(event as any))
.includes(a)
const bIsEnabled = state.nextEvents
.filter((event) => state.can(event as any))
.includes(b)
if (aisEnabled && !bIsEnabled) {
return -1
}
if (!aisEnabled && bIsEnabled) {
return 1
}
return 0
})
.map((eventName) => ({
label: eventName
.replace('Make segment ', '')
.replace('Constrain ', ''),
onClick: () => send(eventName),
disabled:
!state.nextEvents
.filter((event) => state.can(event as any))
.includes(eventName) || disableAllButtons,
}))}
splitMenuItems={splitMenuItems}
className={buttonClassName}
Element="button"
iconStart={{
@ -369,12 +377,6 @@ export const Toolbar = () => {
</li>
)}
</ul>
)
}
return (
<menu className="max-w-full whitespace-nowrap rounded px-1.5 py-0.5 backdrop-blur-sm bg-chalkboard-10/80 dark:bg-chalkboard-110/70 relative">
<ToolbarButtons />
</menu>
)
}

View File

@ -20,6 +20,7 @@ import {
EngineCommand,
Subscription,
EngineCommandManager,
UnreliableSubscription,
} from 'lang/std/engineConnection'
import { uuidv4 } from 'lib/utils'
import { deg2Rad } from 'lib/utils2d'
@ -47,12 +48,14 @@ export type ReactCameraProperties =
type: 'perspective'
fov?: number
position: [number, number, number]
target: [number, number, number]
quaternion: [number, number, number, number]
}
| {
type: 'orthographic'
zoom?: number
position: [number, number, number]
target: [number, number, number]
quaternion: [number, number, number, number]
}
@ -171,41 +174,6 @@ export class CameraControls {
}
}
throttledUpdateEngineFov = throttle(
(vals: {
position: Vector3
quaternion: Quaternion
zoom: number
fov: number
target: Vector3
}) => {
const cmd: EngineCommand = {
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_perspective_settings',
...convertThreeCamValuesToEngineCam({
...vals,
isPerspective: true,
}),
fov_y: vals.fov,
...calculateNearFarFromFOV(vals.fov),
},
}
this.engineCommandManager.sendSceneCommand(cmd)
this.lastPerspectiveCmd = cmd
this.lastPerspectiveCmdTime = Date.now()
if (this.lastPerspectiveCmdTimeoutId !== null) {
clearTimeout(this.lastPerspectiveCmdTimeoutId)
}
this.lastPerspectiveCmdTimeoutId = setTimeout(
this.sendLastPerspectiveReliableChannel,
lastCmdDelay
) as any as number
},
1000 / 30
)
constructor(
isOrtho = false,
domElement: HTMLCanvasElement,
@ -232,9 +200,19 @@ export class CameraControls {
this.update()
this._usePerspectiveCamera()
const cb: Subscription<
'default_camera_zoom' | 'camera_drag_end' | 'default_camera_get_settings'
>['callback'] = ({ data, type }) => {
type CallBackParam = Parameters<
(
| Subscription<
| 'default_camera_zoom'
| 'camera_drag_end'
| 'default_camera_get_settings'
| 'zoom_to_fit'
>
| UnreliableSubscription<'camera_drag_move'>
)['callback']
>[0]
const cb = ({ data, type }: CallBackParam) => {
const camSettings = data.settings
this.camera.position.set(
camSettings.pos.x,
@ -246,7 +224,13 @@ export class CameraControls {
camSettings.center.y,
camSettings.center.z
)
this.camera.up.set(camSettings.up.x, camSettings.up.y, camSettings.up.z)
const quat = new Quaternion(
camSettings.orientation.x,
camSettings.orientation.y,
camSettings.orientation.z,
camSettings.orientation.w
).invert()
this.camera.up.copy(new Vector3(0, 1, 0).applyQuaternion(quat))
if (this.camera instanceof PerspectiveCamera && camSettings.ortho) {
this.useOrthographicCamera()
}
@ -287,6 +271,14 @@ export class CameraControls {
event: 'default_camera_get_settings',
callback: cb,
})
this.engineCommandManager.subscribeTo({
event: 'zoom_to_fit',
callback: cb,
})
this.engineCommandManager.subscribeToUnreliable({
event: 'camera_drag_move',
callback: cb,
})
})
}
@ -417,7 +409,7 @@ export class CameraControls {
this.handleEnd()
return
}
this.throttledEngCmd({
this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd: {
type: 'default_camera_zoom',
@ -429,11 +421,11 @@ export class CameraControls {
return
}
const isTrackpad = Math.abs(event.deltaY) <= 1 || event.deltaY % 1 === 0
// Else "clientToEngine" (Sketch Mode) or forceUpdate
const zoomSpeed = isTrackpad ? 0.02 : 0.1 // Reduced zoom speed for trackpad
// From onMouseMove zoom handling which seems to be really smooth
this.pendingZoom = this.pendingZoom ? this.pendingZoom : 1
this.pendingZoom *= 1 + (event.deltaY > 0 ? zoomSpeed : -zoomSpeed)
this.pendingZoom *= 1 + event.deltaY * 0.01
this.handleEnd()
}
@ -507,26 +499,28 @@ export class CameraControls {
direction.normalize()
this.camera.position.copy(this.target).addScaledVector(direction, distance)
}
usePerspectiveCamera = () => {
usePerspectiveCamera = async () => {
this._usePerspectiveCamera()
this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_perspective',
parameters: {
fov_y:
this.camera instanceof PerspectiveCamera ? this.camera.fov : 45,
...calculateNearFarFromFOV(this.lastPerspectiveFov),
if (this.syncDirection === 'clientToEngine') {
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_perspective',
parameters: {
fov_y:
this.camera instanceof PerspectiveCamera ? this.camera.fov : 45,
...calculateNearFarFromFOV(this.lastPerspectiveFov),
},
},
},
})
})
}
this.onCameraChange()
this.update()
return this.camera
}
dollyZoom = (newFov: number) => {
dollyZoom = async (newFov: number, splitEngineCalls = false) => {
if (!(this.camera instanceof PerspectiveCamera)) {
console.warn('Dolly zoom is only applicable to perspective cameras.')
return
@ -577,13 +571,52 @@ export class CameraControls {
this.camera.near = z_near
this.camera.far = z_far
this.throttledUpdateEngineFov({
fov: newFov,
position: newPosition,
quaternion: this.camera.quaternion,
zoom: this.camera.zoom,
target: this.target,
})
if (splitEngineCalls) {
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_look_at',
...convertThreeCamValuesToEngineCam({
isPerspective: true,
position: newPosition,
quaternion: this.camera.quaternion,
zoom: this.camera.zoom,
target: this.target,
}),
},
})
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_perspective',
parameters: {
fov_y: newFov,
z_near: 0.01,
z_far: 1000,
},
},
})
} else {
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_perspective_settings',
...convertThreeCamValuesToEngineCam({
isPerspective: true,
position: newPosition,
quaternion: this.camera.quaternion,
zoom: this.camera.zoom,
target: this.target,
}),
fov_y: newFov,
z_near: 0.01,
z_far: 1000,
},
})
}
}
update = (forceUpdate = false) => {
@ -748,6 +781,75 @@ export class CameraControls {
})
}
async updateCameraToAxis(
axis: 'x' | 'y' | 'z' | '-x' | '-y' | '-z'
): Promise<void> {
const distance = this.camera.position.distanceTo(this.target)
const vantage = this.target.clone()
let up = { x: 0, y: 0, z: 1 }
if (axis === 'x') {
vantage.x += distance
} else if (axis === 'y') {
vantage.y += distance
} else if (axis === 'z') {
vantage.z += distance
up = { x: -1, y: 0, z: 0 }
} else if (axis === '-x') {
vantage.x -= distance
} else if (axis === '-y') {
vantage.y -= distance
} else if (axis === '-z') {
vantage.z -= distance
up = { x: -1, y: 0, z: 0 }
}
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_look_at',
center: this.target,
vantage: vantage,
up: up,
},
})
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_get_settings',
},
})
}
async resetCameraPosition(): Promise<void> {
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_look_at',
center: this.target,
vantage: {
x: this.target.x,
y: this.target.y - 128,
z: this.target.z + 64,
},
up: { x: 0, y: 0, z: 1 },
},
})
await this.engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'zoom_to_fit',
object_ids: [], // leave empty to zoom to all objects
padding: 0.2, // padding around the objects
},
})
}
async tweenCameraToQuaternion(
targetQuaternion: Quaternion,
targetPosition = new Vector3(),
@ -919,6 +1021,29 @@ export class CameraControls {
.onComplete(onComplete)
.start()
})
snapToPerspectiveBeforeHandingBackControlToEngine = async (
targetCamUp = new Vector3(0, 0, 1)
) => {
if (this.syncDirection === 'engineToClient') {
console.warn(
'animate To Perspective not design to work with engineToClient syncDirection.'
)
}
this.isFovAnimationInProgress = true
const targetFov = this.fovBeforeOrtho // Target FOV for perspective
this.lastPerspectiveFov = 4
let currentFov = 4
const initialCameraUp = this.camera.up.clone()
this.usePerspectiveCamera()
const tempVec = new Vector3()
currentFov = this.lastPerspectiveFov + (targetFov - this.lastPerspectiveFov)
const currentUp = tempVec.lerpVectors(initialCameraUp, targetCamUp, 1)
this.camera.up.copy(currentUp)
await this.dollyZoom(currentFov, true)
this.isFovAnimationInProgress = false
}
get reactCameraProperties(): ReactCameraProperties {
return {
@ -932,6 +1057,11 @@ export class CameraControls {
roundOff(this.camera.position.y, 2),
roundOff(this.camera.position.z, 2),
],
target: [
roundOff(this.target.x, 2),
roundOff(this.target.y, 2),
roundOff(this.target.z, 2),
],
quaternion: [
roundOff(this.camera.quaternion.x, 2),
roundOff(this.camera.quaternion.y, 2),
@ -986,7 +1116,7 @@ function calculateNearFarFromFOV(fov: number) {
// const nearFarRatio = (fov - 3) / (45 - 3)
// const z_near = 0.1 + nearFarRatio * (5 - 0.1)
// const z_far = 1000 + nearFarRatio * (100000 - 1000)
return { z_near: 0.1, z_far: 1000 }
return { z_near: 0.01, z_far: 1000 }
}
function convertThreeCamValuesToEngineCam({
@ -1005,11 +1135,6 @@ function convertThreeCamValuesToEngineCam({
// leaving for now since it's working but maybe revisit later
const euler = new Euler().setFromQuaternion(quaternion, 'XYZ')
const lookAtVector = new Vector3(0, 0, -1)
.applyEuler(euler)
.normalize()
.add(position)
const upVector = new Vector3(0, 1, 0).applyEuler(euler).normalize()
if (isPerspective) {
return {
@ -1018,6 +1143,10 @@ function convertThreeCamValuesToEngineCam({
vantage: position,
}
}
const lookAtVector = new Vector3(0, 0, -1)
.applyEuler(euler)
.normalize()
.add(position)
const fudgeFactor2 = zoom * 0.9979224466814468 - 0.03473692325839295
const zoomFactor = (-ZOOM_MAGIC_NUMBER + fudgeFactor2) / zoom
const direction = lookAtVector.clone().sub(position).normalize()

View File

@ -1,4 +1,4 @@
import { useRef, useEffect, useState } from 'react'
import { useRef, useEffect, useState, useMemo, Fragment } from 'react'
import { useModelingContext } from 'hooks/useModelingContext'
import { cameraMouseDragGuards } from 'lib/cameraControls'
@ -6,12 +6,44 @@ import { useSettingsAuthContext } from 'hooks/useSettingsAuthContext'
import { ARROWHEAD, DEBUG_SHOW_BOTH_SCENES } from './sceneInfra'
import { ReactCameraProperties } from './CameraControls'
import { throttle } from 'lib/utils'
import { sceneInfra } from 'lib/singletons'
import {
sceneInfra,
kclManager,
codeManager,
editorManager,
sceneEntitiesManager,
engineCommandManager,
} from 'lib/singletons'
import {
EXTRA_SEGMENT_HANDLE,
PROFILE_START,
getParentGroup,
} from './sceneEntities'
import { SegmentOverlay, SketchDetails } from 'machines/modelingMachine'
import { findUsesOfTagInPipe, getNodeFromPath } from 'lang/queryAst'
import {
CallExpression,
PathToNode,
Program,
SourceRange,
Value,
parse,
recast,
} from 'lang/wasm'
import { CustomIcon, CustomIconName } from 'components/CustomIcon'
import { ConstrainInfo } from 'lang/std/stdTypes'
import { getConstraintInfo } from 'lang/std/sketch'
import { Dialog, Popover, Transition } from '@headlessui/react'
import { LineInputsType } from 'lang/std/sketchcombos'
import toast from 'react-hot-toast'
import { InstanceProps, create } from 'react-modal-promise'
import { executeAst } from 'useStore'
import {
deleteSegmentFromPipeExpression,
makeRemoveSingleConstraintInput,
removeSingleConstraintInfo,
} from 'lang/modifyAst'
import { ActionButton } from 'components/ActionButton'
function useShouldHideScene(): { hideClient: boolean; hideServer: boolean } {
const [isCamMoving, setIsCamMoving] = useState(false)
@ -100,17 +132,535 @@ export const ClientSideScene = ({
}
return (
<div
ref={canvasRef}
style={{ cursor: cursor }}
className={`absolute inset-0 h-full w-full transition-all duration-300 ${
hideClient ? 'opacity-0' : 'opacity-100'
} ${hideServer ? 'bg-chalkboard-10 dark:bg-chalkboard-100' : ''} ${
!hideClient && !hideServer && state.matches('Sketch')
? 'bg-chalkboard-10/80 dark:bg-chalkboard-100/80'
: ''
}`}
></div>
<>
<div
ref={canvasRef}
style={{ cursor: cursor }}
data-testid="client-side-scene"
className={`absolute inset-0 h-full w-full transition-all duration-300 ${
hideClient ? 'opacity-0' : 'opacity-100'
} ${hideServer ? 'bg-chalkboard-10 dark:bg-chalkboard-100' : ''} ${
!hideClient && !hideServer && state.matches('Sketch')
? 'bg-chalkboard-10/80 dark:bg-chalkboard-100/80'
: ''
}`}
></div>
<Overlays />
</>
)
}
const Overlays = () => {
const { context } = useModelingContext()
if (context.mouseState.type === 'isDragging') return null
return (
<div className="absolute inset-0 pointer-events-none">
{Object.entries(context.segmentOverlays)
.filter((a) => a[1].visible)
.map(([pathToNodeString, overlay], index) => {
return (
<Overlay
overlay={overlay}
key={pathToNodeString}
pathToNodeString={pathToNodeString}
overlayIndex={index}
/>
)
})}
</div>
)
}
const Overlay = ({
overlay,
overlayIndex,
pathToNodeString,
}: {
overlay: SegmentOverlay
overlayIndex: number
pathToNodeString: string
}) => {
const { context, send, state } = useModelingContext()
let xAlignment = overlay.angle < 0 ? '0%' : '-100%'
let yAlignment = overlay.angle < -90 || overlay.angle >= 90 ? '0%' : '-100%'
const callExpression = getNodeFromPath<CallExpression>(
kclManager.ast,
overlay.pathToNode,
'CallExpression'
).node
const constraints = getConstraintInfo(
callExpression,
codeManager.code,
overlay.pathToNode
)
const offset = 20 // px
// We could put a boolean in settings that
const offsetAngle = 90
const xOffset =
Math.cos(((overlay.angle + offsetAngle) * Math.PI) / 180) * offset
const yOffset =
Math.sin(((overlay.angle + offsetAngle) * Math.PI) / 180) * offset
const shouldShow =
overlay.visible &&
typeof context?.segmentHoverMap?.[pathToNodeString] === 'number' &&
!(
state.matches('Sketch.Line tool') ||
state.matches('Sketch.Tangential arc to') ||
state.matches('Sketch.Rectangle tool')
)
return (
<div className={`absolute w-0 h-0`}>
<div
data-testid="segment-overlay"
data-path-to-node={pathToNodeString}
data-overlay-index={overlayIndex}
data-overlay-angle={overlay.angle}
className="pointer-events-auto absolute w-0 h-0"
style={{
transform: `translate3d(${overlay.windowCoords[0]}px, ${overlay.windowCoords[1]}px, 0)`,
}}
></div>
{shouldShow && (
<div
className={`px-0 pointer-events-auto absolute flex gap-1`}
style={{
transform: `translate3d(calc(${
overlay.windowCoords[0] + xOffset
}px + ${xAlignment}), calc(${
overlay.windowCoords[1] - yOffset
}px + ${yAlignment}), 0)`,
}}
onMouseEnter={() =>
send({
type: 'Set mouse state',
data: {
type: 'isHovering',
on: overlay.group,
},
})
}
onMouseLeave={() =>
send({
type: 'Set mouse state',
data: { type: 'idle' },
})
}
>
{constraints &&
constraints.map((constraintInfo, i) => (
<ConstraintSymbol
constrainInfo={constraintInfo}
key={i}
verticalPosition={
overlay.windowCoords[1] > window.innerHeight / 2
? 'top'
: 'bottom'
}
/>
))}
<SegmentMenu
verticalPosition={
overlay.windowCoords[1] > window.innerHeight / 2
? 'top'
: 'bottom'
}
pathToNode={overlay.pathToNode}
stdLibFnName={constraints[0]?.stdLibFnName}
/>
</div>
)}
</div>
)
}
type ConfirmModalProps = InstanceProps<boolean, boolean> & { text: string }
export const ConfirmModal = ({
isOpen,
onResolve,
onReject,
text,
}: ConfirmModalProps) => {
return (
<Transition appear show={isOpen} as={Fragment}>
<Dialog
as="div"
className="relative z-10"
onClose={() => onResolve(false)}
>
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-300"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-200"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="rounded relative mx-auto px-4 py-8 bg-chalkboard-10 dark:bg-chalkboard-100 border dark:border-chalkboard-70 max-w-xl w-full shadow-lg">
<div>{text}</div>
<div className="mt-8 flex justify-between">
<ActionButton
Element="button"
onClick={() => onResolve(true)}
>
Continue and unconstrain
</ActionButton>
<ActionButton
Element="button"
onClick={() => onReject(false)}
>
Cancel
</ActionButton>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
)
}
export const confirmModal = create<ConfirmModalProps, boolean, boolean>(
ConfirmModal
)
export async function deleteSegment({
pathToNode,
sketchDetails,
}: {
pathToNode: PathToNode
sketchDetails: SketchDetails | null
}) {
let modifiedAst: Program = kclManager.ast
const dependentRanges = findUsesOfTagInPipe(modifiedAst, pathToNode)
const shouldContinueSegDelete = dependentRanges.length
? await confirmModal({
text: `At least ${dependentRanges.length} segment rely on the segment you're deleting.\nDo you want to continue and unconstrain these segments?`,
isOpen: true,
})
: true
if (!shouldContinueSegDelete) return
modifiedAst = deleteSegmentFromPipeExpression(
dependentRanges,
modifiedAst,
kclManager.programMemory,
codeManager.code,
pathToNode
)
const newCode = recast(modifiedAst)
modifiedAst = parse(newCode)
const testExecute = await executeAst({
ast: modifiedAst,
useFakeExecutor: true,
engineCommandManager: engineCommandManager,
})
if (testExecute.errors.length) {
toast.error('Segment tag used outside of current Sketch. Could not delete.')
return
}
if (!sketchDetails) return
sceneEntitiesManager.updateAstAndRejigSketch(
sketchDetails.sketchPathToNode,
modifiedAst,
sketchDetails.zAxis,
sketchDetails.yAxis,
sketchDetails.origin
)
}
const SegmentMenu = ({
verticalPosition,
pathToNode,
stdLibFnName,
}: {
verticalPosition: 'top' | 'bottom'
pathToNode: PathToNode
stdLibFnName: string
}) => {
const { send } = useModelingContext()
const dependentSourceRanges = findUsesOfTagInPipe(kclManager.ast, pathToNode)
return (
<Popover className="relative">
{({ open }) => (
<>
<Popover.Button
data-testid="overlay-menu"
data-stdlib-fn-name={stdLibFnName}
className="bg-chalkboard-10 dark:bg-chalkboard-100 border !border-transparent hover:!border-chalkboard-40 dark:hover:!border-chalkboard-70 ui-open:!border-chalkboard-40 dark:ui-open:!border-chalkboard-70 h-[26px] w-[26px] rounded-sm p-0 m-0"
>
<CustomIcon name={'three-dots'} />
</Popover.Button>
<Popover.Panel
as="menu"
className={`absolute ${
verticalPosition === 'top' ? 'bottom-full' : 'top-full'
} z-10 w-36 flex flex-col gap-1 divide-y divide-chalkboard-20 dark:divide-chalkboard-70 align-stretch px-0 py-1 bg-chalkboard-10 dark:bg-chalkboard-100 rounded-sm shadow-lg border border-solid border-chalkboard-20/50 dark:border-chalkboard-80/50`}
>
<button
className="!border-transparent rounded-sm text-left p-1 text-nowrap"
onClick={() => {
send({ type: 'Constrain remove constraints', data: pathToNode })
}}
>
Remove constraints
</button>
<button
className="!border-transparent rounded-sm text-left p-1 text-nowrap"
title={
dependentSourceRanges.length > 0
? `At least ${dependentSourceRanges.length} segment rely on this segment's tag.`
: ''
}
onClick={() => {
send({ type: 'Delete segment', data: pathToNode })
}}
>
Delete Segment
</button>
</Popover.Panel>
</>
)}
</Popover>
)
}
const ConstraintSymbol = ({
constrainInfo: { type: _type, isConstrained, value, pathToNode, argPosition },
verticalPosition,
}: {
constrainInfo: ConstrainInfo
verticalPosition: 'top' | 'bottom'
}) => {
const { context, send } = useModelingContext()
const varNameMap: {
[key in ConstrainInfo['type']]: {
varName: string
displayName: string
iconName: CustomIconName
implicitConstraintDesc?: string
}
} = {
xRelative: {
varName: 'xRel',
displayName: 'X Relative',
iconName: 'xRelative',
},
xAbsolute: {
varName: 'xAbs',
displayName: 'X Absolute',
iconName: 'xAbsolute',
},
yRelative: {
varName: 'yRel',
displayName: 'Y Relative',
iconName: 'yRelative',
},
yAbsolute: {
varName: 'yAbs',
displayName: 'Y Absolute',
iconName: 'yAbsolute',
},
angle: {
varName: 'angle',
displayName: 'Angle',
iconName: 'angle',
},
length: {
varName: 'len',
displayName: 'Length',
iconName: 'dimension',
},
intersectionOffset: {
varName: 'perpDist',
displayName: 'Intersection Offset',
iconName: 'intersection-offset',
},
// implicit constraints
vertical: {
varName: '',
displayName: '',
iconName: 'vertical',
implicitConstraintDesc: 'vertically',
},
horizontal: {
varName: '',
displayName: '',
iconName: 'horizontal',
implicitConstraintDesc: 'horizontally',
},
tangentialWithPrevious: {
varName: '',
displayName: '',
iconName: 'tangent',
implicitConstraintDesc: 'tangential to previous segment',
},
// we don't render this one
intersectionTag: {
varName: '',
displayName: '',
iconName: 'dimension',
},
}
const varName =
_type in varNameMap ? varNameMap[_type as LineInputsType].varName : 'var'
const name: CustomIconName = varNameMap[_type as LineInputsType].iconName
const displayName = varNameMap[_type as LineInputsType]?.displayName
const implicitDesc =
varNameMap[_type as LineInputsType]?.implicitConstraintDesc
const node = useMemo(
() => getNodeFromPath<Value>(kclManager.ast, pathToNode).node,
[kclManager.ast, pathToNode]
)
const range: SourceRange = node ? [node.start, node.end] : [0, 0]
if (_type === 'intersectionTag') return null
return (
<div className="relative group">
<button
data-testid="constraint-symbol"
data-is-implicit-constraint={implicitDesc ? 'true' : 'false'}
data-constraint-type={_type}
data-is-constrained={isConstrained ? 'true' : 'false'}
className={`${
implicitDesc
? 'bg-chalkboard-10 dark:bg-chalkboard-100 border-transparent border-0 rounded'
: isConstrained
? 'bg-chalkboard-10 dark:bg-chalkboard-90 dark:hover:bg-chalkboard-80 border-chalkboard-40 dark:border-chalkboard-70 rounded-sm'
: 'bg-primary/30 dark:bg-primary text-primary dark:text-chalkboard-10 dark:border-transparent group-hover:bg-primary/40 group-hover:border-primary/50 group-hover:brightness-125'
} h-[26px] w-[26px] rounded-sm relative m-0 p-0`}
onMouseEnter={() => {
editorManager.setHighlightRange(range)
}}
onMouseLeave={() => {
editorManager.setHighlightRange([0, 0])
}}
// disabled={isConstrained || !convertToVarEnabled}
// disabled={implicitDesc} TODO why does this change styles that are hard to override?
onClick={async () => {
if (!isConstrained) {
send({
type: 'Convert to variable',
data: {
pathToNode,
variableName: varName,
},
})
} else if (isConstrained) {
try {
const shallowPath = getNodeFromPath<CallExpression>(
parse(recast(kclManager.ast)),
pathToNode,
'CallExpression',
true
).shallowPath
const input = makeRemoveSingleConstraintInput(
argPosition,
shallowPath
)
if (!input || !context.sketchDetails) return
const transform = removeSingleConstraintInfo(
input,
kclManager.ast,
kclManager.programMemory
)
if (!transform) return
const { modifiedAst } = transform
kclManager.updateAst(modifiedAst, true)
} catch (e) {
console.log('error', e)
}
toast.success('Constraint removed')
}
}}
>
<CustomIcon name={name} />
</button>
<div
className={`absolute ${
verticalPosition === 'top'
? 'top-0 -translate-y-full'
: 'bottom-0 translate-y-full'
} group-hover:block hidden w-[2px] h-2 translate-x-[12px] bg-white/40`}
></div>
<div
className={`absolute ${
verticalPosition === 'top' ? 'top-0' : 'bottom-0'
} group-hover:block hidden`}
style={{
transform: `translate3d(calc(-50% + 13px), ${
verticalPosition === 'top' ? '-100%' : '100%'
}, 0)`,
}}
>
<div
className="bg-chalkboard-10 dark:bg-chalkboard-90 p-2 px-3 rounded-sm border border-solid border-chalkboard-20 dark:border-chalkboard-80 shadow-sm"
data-testid="constraint-symbol-popover"
>
{implicitDesc ? (
<div className="min-w-48">
<pre className="inline-block">
<code className="text-primary">{value}</code>
</pre>{' '}
<span>is implicitly constrained {implicitDesc}</span>
</div>
) : (
<>
<div className="flex mb-1">
<span className="text-nowrap">
<span className="font-bold">
{isConstrained ? 'Constrained' : 'Unconstrained'}
</span>
<span className="text-white/80 text-sm pl-2">
{displayName}
</span>
</span>
</div>
<div className="flex mb-1">
<span className="pr-2 whitespace-nowrap">Set to</span>
<pre>
<code className="text-primary">{value}</code>
</pre>
</div>
<div className="text-sm text-chalkboard-70 dark:text-chalkboard-40 text-nowrap">
{isConstrained
? 'Click to unconstrain with raw number'
: 'Click to constrain with variable'}
</div>
</>
)}
</div>
</div>
</div>
)
}
@ -150,6 +700,15 @@ export const CamDebugSettings = () => {
}
}}
/>
<div>
<button
onClick={() => {
sceneInfra.camControls.resetCameraPosition()
}}
>
Reset Camera Position
</button>
</div>
{camSettings.type === 'perspective' && (
<input
type="range"
@ -267,6 +826,71 @@ export const CamDebugSettings = () => {
</li>
</ul>
</div>
<div>
target
<ul className="flex">
<li>
<span className="pl-2 pr-1">x:</span>
<input
type="number"
step={5}
data-testid="cam-x-target"
value={camSettings.target[0]}
className="text-black w-16"
onChange={(e) => {
sceneInfra.camControls.setCam({
...camSettings,
target: [
parseFloat(e.target.value),
camSettings.target[1],
camSettings.target[2],
],
})
}}
/>
</li>
<li>
<span className="pl-2 pr-1">y:</span>
<input
type="number"
step={5}
data-testid="cam-y-target"
value={camSettings.target[1]}
className="text-black w-16"
onChange={(e) => {
sceneInfra.camControls.setCam({
...camSettings,
target: [
camSettings.target[0],
parseFloat(e.target.value),
camSettings.target[2],
],
})
}}
/>
</li>
<li>
<span className="pl-2 pr-1">z:</span>
<input
type="number"
step={5}
data-testid="cam-z-target"
value={camSettings.target[2]}
className="text-black w-16"
onChange={(e) => {
sceneInfra.camControls.setCam({
...camSettings,
target: [
camSettings.target[0],
camSettings.target[1],
parseFloat(e.target.value),
],
})
}}
/>
</li>
</ul>
</div>
</div>
)
}

View File

@ -32,9 +32,7 @@ import {
SKETCH_GROUP_SEGMENTS,
SKETCH_LAYER,
X_AXIS,
XZ_PLANE,
Y_AXIS,
YZ_PLANE,
} from './sceneInfra'
import { isQuaternionVertical, quaternionFromUpNForward } from './helpers'
import {
@ -69,12 +67,13 @@ import {
tangentialArcToSegment,
} from './segments'
import {
addCallExpressionsToPipe,
addCloseToPipe,
addNewSketchLn,
changeSketchArguments,
updateStartProfileAtArgs,
} from 'lang/std/sketch'
import { roundOff, throttle } from 'lib/utils'
import { normaliseAngle, roundOff, throttle } from 'lib/utils'
import {
createArrayExpression,
createCallExpressionStdLib,
@ -91,8 +90,11 @@ import { getTangentPointFromPreviousArc } from 'lib/utils2d'
import { createGridHelper, orthoScale, perspScale } from './helpers'
import { Models } from '@kittycad/lib'
import { uuidv4 } from 'lib/utils'
import { SketchDetails } from 'machines/modelingMachine'
import { EngineCommandManager } from 'lang/std/engineConnection'
import { SegmentOverlayPayload, SketchDetails } from 'machines/modelingMachine'
import {
ArtifactMapCommand,
EngineCommandManager,
} from 'lang/std/engineConnection'
import {
getRectangleCallExpressions,
updateRectangleSketch,
@ -138,8 +140,8 @@ export class SceneEntities {
}
onCamChange = () => {
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
Object.values(this.activeSegments).forEach((segment) => {
const callbacks: (() => SegmentOverlayPayload | null)[] = []
Object.values(this.activeSegments).forEach((segment, index) => {
const factor =
(sceneInfra.camControls.camera instanceof OrthographicCamera
? orthoFactor
@ -150,12 +152,14 @@ export class SceneEntities {
segment.userData.to &&
segment.userData.type === STRAIGHT_SEGMENT
) {
this.updateStraightSegment({
from: segment.userData.from,
to: segment.userData.to,
group: segment,
scale: factor,
})
callbacks.push(
this.updateStraightSegment({
from: segment.userData.from,
to: segment.userData.to,
group: segment,
scale: factor,
})
)
}
if (
@ -164,13 +168,15 @@ export class SceneEntities {
segment.userData.prevSegment &&
segment.userData.type === TANGENTIAL_ARC_TO_SEGMENT
) {
this.updateTangentialArcToSegment({
prevSegment: segment.userData.prevSegment,
from: segment.userData.from,
to: segment.userData.to,
group: segment,
scale: factor,
})
callbacks.push(
this.updateTangentialArcToSegment({
prevSegment: segment.userData.prevSegment,
from: segment.userData.from,
to: segment.userData.to,
group: segment,
scale: factor,
})
)
}
if (segment.name === PROFILE_START) {
segment.scale.set(factor, factor, factor)
@ -186,6 +192,7 @@ export class SceneEntities {
const y = this.axisGroup.getObjectByName(Y_AXIS)
y?.scale.set(factor / sceneInfra._baseUnitMultiplier, 1, 1)
}
sceneInfra.overlayCallbacks(callbacks)
}
createIntersectionPlane() {
@ -365,7 +372,7 @@ export class SceneEntities {
})
group.add(_profileStart)
this.activeSegments[JSON.stringify(segPathToNode)] = _profileStart
const callbacks: (() => SegmentOverlayPayload | null)[] = []
sketchGroup.value.forEach((segment, index) => {
let segPathToNode = getNodePathFromSourceRange(
maybeModdedAst,
@ -410,6 +417,15 @@ export class SceneEntities {
texture: sceneInfra.extraSegmentTexture,
theme: sceneInfra._theme,
})
callbacks.push(
this.updateTangentialArcToSegment({
prevSegment: sketchGroup.value[index - 1],
from: segment.from,
to: segment.to,
group: seg,
scale: factor,
})
)
} else {
seg = straightSegment({
from: segment.from,
@ -422,6 +438,14 @@ export class SceneEntities {
texture: sceneInfra.extraSegmentTexture,
theme: sceneInfra._theme,
})
callbacks.push(
this.updateStraightSegment({
from: segment.from,
to: segment.to,
group: seg,
scale: factor,
})
)
}
seg.layers.set(SKETCH_LAYER)
seg.traverse((child) => {
@ -446,6 +470,7 @@ export class SceneEntities {
this.intersectionPlane.position.set(...position)
this.scene.add(group)
sceneInfra.camControls.enableRotate = false
sceneInfra.overlayCallbacks(callbacks)
return {
truncatedAst,
@ -536,10 +561,34 @@ export class SceneEntities {
let modifiedAst
if (profileStart) {
modifiedAst = addCloseToPipe({
const lastSegment = sketchGroup.value.slice(-1)[0]
modifiedAst = addCallExpressionsToPipe({
node: kclManager.ast,
programMemory: kclManager.programMemory,
pathToNode: sketchPathToNode,
expressions: [
createCallExpressionStdLib(
lastSegment.type === 'TangentialArcTo'
? 'tangentialArcTo'
: 'lineTo',
[
createArrayExpression([
createCallExpressionStdLib('profileStartX', [
createPipeSubstitution(),
]),
createCallExpressionStdLib('profileStartY', [
createPipeSubstitution(),
]),
]),
createPipeSubstitution(),
]
),
],
})
modifiedAst = addCloseToPipe({
node: modifiedAst,
programMemory: kclManager.programMemory,
pathToNode: sketchPathToNode,
})
} else if (intersection2d) {
const lastSegment = sketchGroup.value.slice(-1)[0]
@ -560,13 +609,17 @@ export class SceneEntities {
}
await kclManager.executeAstMock(modifiedAst)
this.setUpDraftSegment(
sketchPathToNode,
forward,
up,
origin,
segmentName
)
if (profileStart) {
sceneInfra.modelingSend({ type: 'CancelSketch' })
} else {
this.setUpDraftSegment(
sketchPathToNode,
forward,
up,
origin,
segmentName
)
}
},
onMove: (args) => {
this.onDragSegment({
@ -707,14 +760,6 @@ export class SceneEntities {
_ast = parse(recast(_ast))
console.log('onClick', {
sketchInit: sketchInit,
_ast,
x,
y,
truncatedAst,
})
// Update the primary AST and unequip the rectangle tool
await kclManager.executeAstMock(_ast)
sceneInfra.modelingSend({ type: 'CancelSketch' })
@ -990,7 +1035,8 @@ export class SceneEntities {
orthoFactor,
sketchGroup
)
sgPaths.forEach((group, index) =>
const callBacks = sgPaths.map((group, index) =>
this.updateSegment(
group,
index,
@ -1000,6 +1046,7 @@ export class SceneEntities {
sketchGroup
)
)
sceneInfra.overlayCallbacks(callBacks)
})()
}
@ -1020,7 +1067,7 @@ export class SceneEntities {
modifiedAst: Program,
orthoFactor: number,
sketchGroup: SketchGroup
) => {
): (() => SegmentOverlayPayload | null) => {
const segPathToNode = getNodePathFromSourceRange(
modifiedAst,
segment.__geoMeta.sourceRange
@ -1041,7 +1088,7 @@ export class SceneEntities {
: perspScale(sceneInfra.camControls.camera, group)) /
sceneInfra._baseUnitMultiplier
if (type === TANGENTIAL_ARC_TO_SEGMENT) {
this.updateTangentialArcToSegment({
return this.updateTangentialArcToSegment({
prevSegment: sgPaths[index - 1],
from: segment.from,
to: segment.to,
@ -1049,7 +1096,7 @@ export class SceneEntities {
scale: factor,
})
} else if (type === STRAIGHT_SEGMENT) {
this.updateStraightSegment({
return this.updateStraightSegment({
from: segment.from,
to: segment.to,
group,
@ -1059,6 +1106,7 @@ export class SceneEntities {
group.position.set(segment.from[0], segment.from[1], 0)
group.scale.set(factor, factor, factor)
}
return () => null
}
updateTangentialArcToSegment({
@ -1073,7 +1121,7 @@ export class SceneEntities {
to: [number, number]
group: Group
scale?: number
}) {
}): () => SegmentOverlayPayload | null {
group.userData.from = from
group.userData.to = to
group.userData.prevSegment = prevSegment
@ -1161,6 +1209,18 @@ export class SceneEntities {
scale,
})
}
const angle = normaliseAngle(
(arcInfo.endAngle * 180) / Math.PI + (arcInfo.ccw ? 90 : -90)
)
return () =>
sceneInfra.updateOverlayDetails({
arrowGroup,
group,
isHandlesVisible,
from,
to,
angle,
})
}
throttledUpdateDashedArcGeo = throttle(
(
@ -1181,7 +1241,7 @@ export class SceneEntities {
to: [number, number]
group: Group
scale?: number
}) {
}): () => SegmentOverlayPayload | null {
group.userData.from = from
group.userData.to = to
const shape = new Shape()
@ -1258,13 +1318,14 @@ export class SceneEntities {
scale
)
}
}
async animateAfterSketch() {
// if (isReducedMotion()) {
// sceneInfra.camControls.usePerspectiveCamera()
// return
// }
await sceneInfra.camControls.animateToPerspective()
return () =>
sceneInfra.updateOverlayDetails({
arrowGroup,
group,
isHandlesVisible,
from,
to,
})
}
removeSketchGrid() {
if (this.axisGroup) this.scene.remove(this.axisGroup)
@ -1329,87 +1390,135 @@ export class SceneEntities {
selected.material.color = defaultPlaneColor(type)
},
onClick: async (args) => {
const checkExtrudeFaceClick = async (): Promise<
['face' | 'plane' | 'other', string]
> => {
const { streamDimensions } = useStore.getState()
const { entity_id } = await sendSelectEventToEngine(
args?.mouseEvent,
document.getElementById('video-stream') as HTMLVideoElement,
streamDimensions
)
if (!entity_id) return ['other', '']
if (
engineCommandManager.defaultPlanes?.xy === entity_id ||
engineCommandManager.defaultPlanes?.xz === entity_id ||
engineCommandManager.defaultPlanes?.yz === entity_id
) {
return ['plane', entity_id]
const { streamDimensions } = useStore.getState()
const { entity_id, ...rest } = await sendSelectEventToEngine(
args?.mouseEvent,
document.getElementById('video-stream') as HTMLVideoElement,
streamDimensions
)
let _entity_id = entity_id
console.log('things', _entity_id, rest)
if (!_entity_id) return
if (
engineCommandManager.defaultPlanes?.xy === _entity_id ||
engineCommandManager.defaultPlanes?.xz === _entity_id ||
engineCommandManager.defaultPlanes?.yz === _entity_id ||
engineCommandManager.defaultPlanes?.negXy === _entity_id ||
engineCommandManager.defaultPlanes?.negXz === _entity_id ||
engineCommandManager.defaultPlanes?.negYz === _entity_id
) {
const defaultPlaneStrMap: Record<string, DefaultPlaneStr> = {
[engineCommandManager.defaultPlanes.xy]: 'XY',
[engineCommandManager.defaultPlanes.xz]: 'XZ',
[engineCommandManager.defaultPlanes.yz]: 'YZ',
[engineCommandManager.defaultPlanes.negXy]: '-XY',
[engineCommandManager.defaultPlanes.negXz]: '-XZ',
[engineCommandManager.defaultPlanes.negYz]: '-YZ',
}
const artifact = this.engineCommandManager.artifactMap[entity_id]
if (artifact?.commandType !== 'solid3d_get_extrusion_face_info')
return ['other', entity_id]
// TODO can we get this information from rust land when it creates the default planes?
// maybe returned from make_default_planes (src/wasm-lib/src/wasm.rs)
let zAxis: [number, number, number] = [0, 0, 1]
let yAxis: [number, number, number] = [0, 1, 0]
const faceInfo = await getFaceDetails(entity_id)
if (!faceInfo?.origin || !faceInfo?.z_axis || !faceInfo?.y_axis)
return ['other', entity_id]
const { z_axis, y_axis, origin } = faceInfo
const pathToNode = getNodePathFromSourceRange(
kclManager.ast,
artifact.range
)
// get unit vector from camera position to target
const camVector = sceneInfra.camControls.camera.position
.clone()
.sub(sceneInfra.camControls.target)
if (engineCommandManager.defaultPlanes?.xy === _entity_id) {
console.log('XY')
zAxis = [0, 0, 1]
yAxis = [0, 1, 0]
if (camVector.z < 0) {
zAxis = [0, 0, -1]
_entity_id = engineCommandManager.defaultPlanes?.negXy || ''
}
} else if (engineCommandManager.defaultPlanes?.yz === _entity_id) {
console.log('YZ')
zAxis = [1, 0, 0]
yAxis = [0, 0, 1]
if (camVector.x < 0) {
zAxis = [-1, 0, 0]
_entity_id = engineCommandManager.defaultPlanes?.negYz || ''
}
} else if (engineCommandManager.defaultPlanes?.xz === _entity_id) {
console.log('XZ')
zAxis = [0, 1, 0]
yAxis = [0, 0, 1]
_entity_id = engineCommandManager.defaultPlanes?.negXz || ''
if (camVector.y < 0) {
zAxis = [0, -1, 0]
_entity_id = engineCommandManager.defaultPlanes?.xz || ''
}
}
sceneInfra.modelingSend({
type: 'Select default plane',
data: {
type: 'extrudeFace',
zAxis: [z_axis.x, z_axis.y, z_axis.z],
yAxis: [y_axis.x, y_axis.y, y_axis.z],
position: [origin.x, origin.y, origin.z].map(
(num) => num / sceneInfra._baseUnitMultiplier
) as [number, number, number],
extrudeSegmentPathToNode: pathToNode,
cap:
artifact?.additionalData?.type === 'cap'
? artifact.additionalData.info
: 'none',
faceId: entity_id,
type: 'defaultPlane',
planeId: _entity_id,
plane: defaultPlaneStrMap[_entity_id],
zAxis,
yAxis,
},
})
return ['face', entity_id]
return
}
const artifact = this.engineCommandManager.artifactMap[_entity_id]
// If we clicked on an extrude wall, we climb up the parent Id
// to get the sketch profile's face ID. If we clicked on an endcap,
// we already have it.
const targetId =
'additionalData' in artifact &&
artifact.additionalData?.type === 'cap'
? _entity_id
: artifact.parentId
const faceResult = await checkExtrudeFaceClick()
console.log('faceResult', faceResult)
if (faceResult[0] === 'face') return
// tsc cannot infer that target can have extrusions
// from the commandType (why?) so we need to cast it
const target = this.engineCommandManager.artifactMap?.[
targetId || ''
] as ArtifactMapCommand & { extrusions?: string[] }
// TODO: We get the first extrusion command ID,
// which is fine while backend systems only support one extrusion.
// but we need to more robustly handle resolving to the correct extrusion
// if there are multiple.
const extrusions =
this.engineCommandManager.artifactMap?.[target?.extrusions?.[0] || '']
if (artifact?.commandType !== 'solid3d_get_extrusion_face_info') return
const faceInfo = await getFaceDetails(_entity_id)
if (!faceInfo?.origin || !faceInfo?.z_axis || !faceInfo?.y_axis) return
const { z_axis, y_axis, origin } = faceInfo
const sketchPathToNode = getNodePathFromSourceRange(
kclManager.ast,
artifact.range
)
const extrudePathToNode = extrusions?.range
? getNodePathFromSourceRange(kclManager.ast, extrusions.range)
: []
if (!args || !args.intersects?.[0]) return
if (args.mouseEvent.which !== 1) return
const { intersects } = args
const type = intersects?.[0].object.name || ''
const posNorm = Number(intersects?.[0]?.normal?.z) > 0
let planeString: DefaultPlaneStr = posNorm ? 'XY' : '-XY'
let zAxis: [number, number, number] = posNorm ? [0, 0, 1] : [0, 0, -1]
let yAxis: [number, number, number] = [0, 1, 0]
if (type === YZ_PLANE) {
planeString = posNorm ? 'YZ' : '-YZ'
zAxis = posNorm ? [1, 0, 0] : [-1, 0, 0]
yAxis = [0, 0, 1]
} else if (type === XZ_PLANE) {
planeString = posNorm ? '-XZ' : 'XZ'
zAxis = posNorm ? [0, 1, 0] : [0, -1, 0]
yAxis = [0, 0, 1]
}
sceneInfra.modelingSend({
type: 'Select default plane',
data: {
type: 'defaultPlane',
plane: planeString,
zAxis,
yAxis,
planeId: faceResult[1],
type: 'extrudeFace',
zAxis: [z_axis.x, z_axis.y, z_axis.z],
yAxis: [y_axis.x, y_axis.y, y_axis.z],
position: [origin.x, origin.y, origin.z].map(
(num) => num / sceneInfra._baseUnitMultiplier
) as [number, number, number],
sketchPathToNode,
extrudePathToNode,
cap:
artifact?.additionalData?.type === 'cap'
? artifact.additionalData.info
: 'none',
faceId: _entity_id,
},
})
return
},
})
}
@ -1529,6 +1638,14 @@ export class SceneEntities {
},
}
}
resetOverlays() {
sceneInfra.modelingSend({
type: 'Set Segment Overlays',
data: {
type: 'clear',
},
})
}
}
export type DefaultPlaneStr = 'XY' | 'XZ' | 'YZ' | '-XY' | '-XZ' | '-YZ'

View File

@ -21,15 +21,15 @@ import {
TextureLoader,
Texture,
} from 'three'
import { compareVec2Epsilon2 } from 'lang/std/sketch'
import { Coords2d, compareVec2Epsilon2 } from 'lang/std/sketch'
import { useModelingContext } from 'hooks/useModelingContext'
import * as TWEEN from '@tweenjs/tween.js'
import { Axis } from 'lib/selections'
import { type BaseUnit } from 'lib/settings/settingsTypes'
import { CameraControls } from './CameraControls'
import { EngineCommandManager } from 'lang/std/engineConnection'
import { settings } from 'lib/settings/initialSettings'
import { MouseState } from 'machines/modelingMachine'
import { MouseState, SegmentOverlayPayload } from 'machines/modelingMachine'
import { getAngle, throttle } from 'lib/utils'
import { Themes } from 'lib/theme'
type SendType = ReturnType<typeof useModelingContext>['send']
@ -155,8 +155,88 @@ export class SceneInfra {
}
modelingSend: SendType = (() => {}) as any
throttledModelingSend: any = (() => {}) as any
setSend(send: SendType) {
this.modelingSend = send
this.throttledModelingSend = throttle(send, 100)
}
overlayTimeout = 0
callbacks: (() => SegmentOverlayPayload | null)[] = []
_overlayCallbacks(callbacks: (() => SegmentOverlayPayload | null)[]) {
const segmentOverlayPayload: SegmentOverlayPayload = {
type: 'set-many',
overlays: {},
}
callbacks.forEach((cb) => {
const overlay = cb()
if (overlay?.type === 'set-one') {
segmentOverlayPayload.overlays[overlay.pathToNodeString] = overlay.seg
}
})
this.modelingSend({
type: 'Set Segment Overlays',
data: segmentOverlayPayload,
})
}
overlayCallbacks(
callbacks: (() => SegmentOverlayPayload | null)[],
instant = false
) {
if (instant) {
this._overlayCallbacks(callbacks)
return
}
this.callbacks = callbacks
if (this.overlayTimeout) clearTimeout(this.overlayTimeout)
this.overlayTimeout = setTimeout(() => {
this._overlayCallbacks(this.callbacks)
}, 100) as unknown as number
}
overlayThrottleMap: { [pathToNodeString: string]: number } = {}
updateOverlayDetails({
arrowGroup,
group,
isHandlesVisible,
from,
to,
angle,
}: {
arrowGroup: Group
group: Group
isHandlesVisible: boolean
from: Coords2d
to: Coords2d
angle?: number
}): SegmentOverlayPayload | null {
if (group.userData.pathToNode && arrowGroup) {
const vector = new Vector3(0, 0, 0)
// Get the position of the object3D in world space
// console.log('arrowGroup', arrowGroup)
arrowGroup.getWorldPosition(vector)
// Project that position to screen space
vector.project(this.camControls.camera)
const _angle = typeof angle === 'number' ? angle : getAngle(from, to)
const x = (vector.x * 0.5 + 0.5) * window.innerWidth
const y = (-vector.y * 0.5 + 0.5) * window.innerHeight
const pathToNodeString = JSON.stringify(group.userData.pathToNode)
return {
type: 'set-one',
pathToNodeString,
seg: {
windowCoords: [x, y],
angle: _angle,
group,
pathToNode: group.userData.pathToNode,
visible: isHandlesVisible,
},
}
}
return null
}
hoveredObject: null | any = null
@ -182,15 +262,6 @@ export class SceneInfra {
this.renderer.setClearColor(0x000000, 0) // Set clear color to black with 0 alpha (fully transparent)
window.addEventListener('resize', this.onWindowResize)
// CAMERA
const camHeightDistanceRatio = 0.5
const baseUnit: BaseUnit = settings.modeling.defaultUnit.current
const baseRadius = 5.6
const length = baseUnitTomm(baseUnit) * baseRadius
const ang = Math.atan(camHeightDistanceRatio)
const x = Math.cos(ang) * length
const y = Math.sin(ang) * length
this.camControls = new CameraControls(
false,
this.renderer.domElement,
@ -198,7 +269,6 @@ export class SceneInfra {
)
this.camControls.subscribeToCamChange(() => this.onCameraChange())
this.camControls.camera.layers.enable(SKETCH_LAYER)
this.camControls.camera.position.set(0, -x, y)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camControls.camera.layers.enable(INTERSECTION_PLANE_LAYER)

View File

@ -39,6 +39,7 @@ export function ActionButtonDropdown({
onClick={item.onClick}
className="block px-3 py-1 hover:bg-primary/10 dark:hover:bg-chalkboard-80 border-0 m-0 text-sm w-full rounded-none text-left disabled:!bg-transparent dark:disabled:text-chalkboard-60"
disabled={item.disabled}
data-testid={item.label}
>
<span className="capitalize">{item.label}</span>
{item.shortcut && (

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