Compare commits

..

82 Commits

Author SHA1 Message Date
9407162543 Merge branch 'main' into pierremtb/issue4472-Add-shell-point-and-click-operation-backup 2024-12-09 14:04:18 -05:00
067b83b468 Manual resolution of snapshot conflicts 2024-12-09 13:56:33 -05:00
c5b30341eb Add unit tests for doesSceneHaveExtrudedSketch 2024-12-09 12:26:21 -05:00
3e6441b563 Fix test annotations 2024-12-09 11:36:46 -05:00
acafcf2d4d Apply suggestions from Frank's review
Co-authored-by: Frank Noirot <frank@zoo.dev>
2024-12-09 11:33:41 -05:00
b9f31d94d5 Merge branch 'main' into pierremtb/issue4472-Add-shell-point-and-click-operation 2024-12-05 18:43:44 -05:00
9e03b58ae5 Cap and wall pw test 2024-12-05 18:21:20 -05:00
c591f73c70 Working multi-face shell across types 2024-12-05 17:56:18 -05:00
9330aaba13 Trigger CI 2024-12-05 17:27:16 -05:00
5a14f0189e Look at this (photo)Graph *in the voice of Nickelback* 2024-12-05 22:14:20 +00:00
9af001f22e Lint 2024-12-05 17:04:02 -05:00
435d1ea52e WIP circular dep 2024-12-05 16:53:57 -05:00
54847139f2 Merge branch 'main' into pierremtb/issue4472-Add-shell-point-and-click-operation 2024-12-05 15:00:34 -05:00
9369a17ea7 WIP mutliple faces 2024-12-05 14:59:44 -05:00
9ee2e7c3b0 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-05 19:42:39 +00:00
28ae261e5f Lint fix 2024-12-05 14:38:23 -05:00
e4b0de0ead Add selection guard and clean up 2024-12-05 14:06:09 -05:00
12859598a3 Merge branch 'main' into pierremtb/issue4472-Add-shell-point-and-click-operation 2024-12-05 13:02:35 -05:00
e9a334f433 Fix lint 2024-12-05 13:02:22 -05:00
e470a7b4af Add shell wall test 2024-12-05 12:33:46 -05:00
602c39f63c Add pw tests for cap shell 2024-12-05 12:03:45 -05:00
4994aa6f61 Handle walls 2024-12-05 11:38:03 -05:00
4aa07b81db Add extrude lookup for more generic shell 2024-12-05 10:26:58 -05:00
89ef4b3243 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-05 14:55:04 +00:00
001c9a8219 Update from main 2024-12-05 09:49:14 -05:00
4dde3f60e0 WIP: first time working shell mod 2024-12-04 18:41:45 -05:00
f407c53032 WIP: closer 2024-12-04 17:53:04 -05:00
9ba584487a WIP: more additions 2024-12-04 17:01:11 -05:00
96b66d6bca Merge branch 'pierremtb/issue4470-loft-ui' into pierremtb/issue4472-Add-shell-point-and-click-operation 2024-12-04 16:44:40 -05:00
8d66f3ffad Rollback pw values to pre cam change 2024-12-04 16:43:29 -05:00
f4c54cbbe4 WIP: initial shell code addition 2024-12-04 16:38:44 -05:00
5156b847f3 Trigger CI 2024-12-04 15:56:48 -05:00
ded9f2c56b A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 20:54:59 +00:00
5db5f79f9a Merge branch 'main' into pierremtb/issue4470-loft-ui 2024-12-04 15:46:18 -05:00
6a883f4a8d A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 20:43:39 +00:00
07b91f0fb1 Trigger CI 2024-12-04 15:39:26 -05:00
1b2e213afe A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 20:37:28 +00:00
f48a23c35e A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 20:36:20 +00:00
7e1d102496 Revert snapshots 2024-12-04 15:32:14 -05:00
94cb2535c0 Fix typo 2024-12-04 15:21:03 -05:00
9e08ec9096 A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 20:00:36 +00:00
17bd8ec32a A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 19:58:28 +00:00
d0f12e85e5 Trigger CI 2024-12-04 14:54:05 -05:00
94d185944e A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 19:52:22 +00:00
c38b2270c3 A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 19:51:34 +00:00
967ad66c98 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 19:47:04 +00:00
afeca9ca39 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 19:46:25 +00:00
61242282f0 Trigger CI 2024-12-04 14:42:00 -05:00
0065df13ce A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 16:55:39 +00:00
01c8d45c13 Remove comments 2024-12-04 11:44:49 -05:00
8b25527f21 Move error logic out of loftSketches, fix pw tests 2024-12-04 11:39:35 -05:00
2abd980de9 Move to fromPromise-based Actor 2024-12-04 11:02:51 -05:00
f783deb706 A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 15:25:38 +00:00
f4dd295ca1 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 15:17:19 +00:00
ceaa85fe3f A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 15:16:16 +00:00
3991bd9173 Trigger CI 2024-12-04 10:11:47 -05:00
b8f9da36c0 A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 10:54:14 +00:00
283315b5d2 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-04 10:44:01 +00:00
e204dfe564 A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-12-04 10:43:15 +00:00
208a36196b Merge branch 'main' into pierremtb/issue4470-loft-ui 2024-12-04 05:38:43 -05:00
660a349588 Add pw test for preselected sketches 2024-12-03 15:17:21 -05:00
56c37da317 Clean up loftSketches function 2024-12-03 15:02:56 -05:00
a46734b76d Add test for doesSceneHaveSweepableSketch with count = 2 2024-12-03 14:39:06 -05:00
4347e0cf84 Clean up and working pw test 2024-12-03 13:49:26 -05:00
df3e541cdf A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-12-03 17:51:57 +00:00
b1cec443b9 Merge branch 'main' into pierremtb/issue4470-loft-ui 2024-12-03 12:48:32 -05:00
967f49055d Lint 2024-12-02 14:30:43 -05:00
fe977524b5 First point-click loft test (not working locally, loft gets inserted at the wrong place) 2024-12-02 14:19:32 -05:00
d6f271fb0f Enable multiple selections after the button click 2024-12-01 07:00:13 -05:00
e851b2bcc4 Merge branch 'main' into pierremtb/issue4470-loft-ui 2024-11-29 20:01:32 -05:00
be569c91de Clean up 2024-11-29 19:51:56 -05:00
5080e304b9 Appends the loft line after the 'last' sketch in the code 2024-11-29 18:30:15 -05:00
f4e75b7b4f More checks 2024-11-29 13:38:52 -05:00
31cbc90f56 WIP selections 2024-11-29 12:37:53 -05:00
a7d3552472 WIP selections 2024-11-29 11:17:31 -05:00
e984b20664 First pass at handling more than 2 sketches 2024-11-29 10:09:10 -05:00
0c2cd24bda Working loft for two sketches in the right hardcoded order 2024-11-28 20:28:37 -05:00
9b2de237b8 Add selection guard 2024-11-28 16:45:41 -05:00
c79c02f18e A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-11-28 20:25:44 +00:00
4851aa2d71 A snapshot a day keeps the bugs away! 📷🐛 (OS: windows-latest-8-cores) 2024-11-28 20:17:17 +00:00
76fafa6fd0 A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu-latest-8-cores) 2024-11-28 20:11:35 +00:00
647ca11e08 WIP: experimenting with Loft UI
Relates to #4470
2024-11-27 15:55:01 -05:00
189 changed files with 8900 additions and 16113 deletions

View File

@ -0,0 +1,59 @@
# bash strict mode
set -euo pipefail
if [[ ! -f "test-results/.last-run.json" ]]; then
# if no last run artifact, than run plawright normally
echo "run playwright normally"
if [[ "$3" == ubuntu-latest* ]]; then
yarn test:playwright:browser:chrome:ubuntu -- --shard=$1/$2 || true
elif [[ "$3" == windows-latest* ]]; then
yarn test:playwright:browser:chrome:windows -- --shard=$1/$2 || true
else
echo "Do not run playwright. Unable to detect os runtime."
exit 1
fi
# # send to axiom
node playwrightProcess.mjs | tee /tmp/github-actions.log > /dev/null 2>&1
fi
retry=1
max_retrys=4
# retry failed tests, doing our own retries because using inbuilt playwright retries causes connection issues
while [[ $retry -le $max_retrys ]]; do
if [[ -f "test-results/.last-run.json" ]]; then
failed_tests=$(jq '.failedTests | length' test-results/.last-run.json)
if [[ $failed_tests -gt 0 ]]; then
echo "retried=true" >>$GITHUB_OUTPUT
echo "run playwright with last failed tests and retry $retry"
if [[ "$3" == ubuntu-latest* ]]; then
yarn test:playwright:browser:chrome:ubuntu -- --last-failed || true
elif [[ "$3" == windows-latest* ]]; then
yarn test:playwright:browser:chrome:windows -- --last-failed || true
else
echo "Do not run playwright. Unable to detect os runtime."
exit 1
fi
# send to axiom
node playwrightProcess.mjs | tee /tmp/github-actions.log > /dev/null 2>&1
retry=$((retry + 1))
else
echo "retried=false" >>$GITHUB_OUTPUT
exit 0
fi
else
echo "retried=false" >>$GITHUB_OUTPUT
exit 0
fi
done
echo "retried=false" >>$GITHUB_OUTPUT
if [[ -f "test-results/.last-run.json" ]]; then
failed_tests=$(jq '.failedTests | length' test-results/.last-run.json)
if [[ $failed_tests -gt 0 ]]; then
# if it still fails after 3 retrys, then fail the job
exit 1
fi
fi
exit 0

View File

@ -1,17 +1,15 @@
#!/bin/bash
# bash strict mode # bash strict mode
set -euo pipefail set -euo pipefail
if [[ ! -f "test-results/.last-run.json" ]]; then if [[ ! -f "test-results/.last-run.json" ]]; then
# if no last run artifact, than run plawright normally # if no last run artifact, than run plawright normally
echo "run playwright normally" echo "run playwright normally"
if [[ "$3" == ubuntu-latest* ]]; then if [[ "$1" == ubuntu-latest* ]]; then
xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- yarn test:playwright:electron:ubuntu -- --shard=$1/$2 || true xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- yarn test:playwright:electron:ubuntu || true
elif [[ "$3" == windows-latest* ]]; then elif [[ "$1" == windows-latest* ]]; then
yarn test:playwright:electron:windows -- --shard=$1/$2 || true yarn test:playwright:electron:windows || true
elif [[ "$3" == macos-14* ]]; then elif [[ "$1" == macos-14* ]]; then
yarn test:playwright:electron:macos -- --shard=$1/$2 || true yarn test:playwright:electron:macos || true
else else
echo "Do not run playwright. Unable to detect os runtime." echo "Do not run playwright. Unable to detect os runtime."
exit 1 exit 1
@ -30,11 +28,11 @@ while [[ $retry -le $max_retrys ]]; do
if [[ $failed_tests -gt 0 ]]; then if [[ $failed_tests -gt 0 ]]; then
echo "retried=true" >>$GITHUB_OUTPUT echo "retried=true" >>$GITHUB_OUTPUT
echo "run playwright with last failed tests and retry $retry" echo "run playwright with last failed tests and retry $retry"
if [[ "$3" == ubuntu-latest* ]]; then if [[ "$1" == ubuntu-latest* ]]; then
xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- yarn test:playwright:electron:ubuntu -- --last-failed || true xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- yarn test:playwright:electron:ubuntu -- --last-failed || true
elif [[ "$3" == windows-latest* ]]; then elif [[ "$1" == windows-latest* ]]; then
yarn test:playwright:electron:windows -- --last-failed || true yarn test:playwright:electron:windows -- --last-failed || true
elif [[ "$3" == macos-14* ]]; then elif [[ "$1" == macos-14* ]]; then
yarn test:playwright:electron:macos -- --last-failed || true yarn test:playwright:electron:macos -- --last-failed || true
else else
echo "Do not run playwright. Unable to detect os runtime." echo "Do not run playwright. Unable to detect os runtime."

View File

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

View File

@ -33,13 +33,13 @@ jobs:
rust: rust:
- 'src/wasm-lib/**' - 'src/wasm-lib/**'
electron: browser:
timeout-minutes: ${{ matrix.os == 'macos-14' && 60 || 50 }} timeout-minutes: ${{ matrix.os == 'macos-14' && 60 || 50 }}
name: playwright:electron:${{ matrix.os }} ${{ matrix.shardIndex }} ${{ matrix.shardTotal }} name: playwright:browser:${{ matrix.os }} ${{ matrix.shardIndex }} ${{ matrix.shardTotal }}
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [ubuntu-latest-8-cores, windows-latest-8-cores, macos-14-large] os: [ubuntu-latest-8-cores, windows-latest-8-cores]
shardIndex: [1, 2, 3, 4] shardIndex: [1, 2, 3, 4]
shardTotal: [4] shardTotal: [4]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
@ -123,13 +123,13 @@ jobs:
if: steps.download-wasm.outcome == 'failure' if: steps.download-wasm.outcome == 'failure'
shell: bash shell: bash
run: yarn build:wasm run: yarn build:wasm
- name: build electron - name: build web
run: yarn build:local
shell: bash shell: bash
run: yarn tron:package
- name: Run ubuntu/chrome snapshots - name: Run ubuntu/chrome snapshots
shell: bash shell: bash
run: | run: |
PLATFORM=web yarn playwright test --config=playwright.config.ts --retries="3" --update-snapshots --grep=@snapshot --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} yarn playwright test --project="Google Chrome" --config=playwright.ci.config.ts --retries="3" --update-snapshots --grep=@snapshot --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }}
env: env:
CI: true CI: true
NODE_ENV: development NODE_ENV: development
@ -186,12 +186,12 @@ jobs:
with: with:
name: test-results-${{ matrix.os }}-${{ matrix.shardIndex }}-${{ github.sha }} name: test-results-${{ matrix.os }}-${{ matrix.shardIndex }}-${{ github.sha }}
path: test-results/ path: test-results/
- name: Run playwright/electron flow (with retries) - name: Run playwright/chrome flow (with retries)
id: retry id: retry
if: ${{ !cancelled() && (success() || failure()) }} if: ${{ !cancelled() && (success() || failure()) }}
shell: bash shell: bash
run: | run: |
.github/ci-cd-scripts/playwright-electron.sh ${{matrix.shardIndex}} ${{matrix.shardTotal}} ${{matrix.os}} .github/ci-cd-scripts/playwright-browser-chrome.sh ${{matrix.shardIndex}} ${{matrix.shardTotal}} ${{matrix.os}}
env: env:
CI: true CI: true
FAIL_ON_CONSOLE_ERRORS: true FAIL_ON_CONSOLE_ERRORS: true
@ -199,6 +199,11 @@ jobs:
VITE_KC_DEV_TOKEN: ${{ secrets.KITTYCAD_API_TOKEN_DEV }} VITE_KC_DEV_TOKEN: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
VITE_KC_SKIP_AUTH: true VITE_KC_SKIP_AUTH: true
token: ${{ secrets.KITTYCAD_API_TOKEN_DEV }} token: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
- name: send to axiom
if: always()
shell: bash
run: |
node playwrightProcess.mjs | tee /tmp/github-actions.log
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v4
if: always() if: always()
with: with:
@ -216,3 +221,136 @@ jobs:
retention-days: 30 retention-days: 30
overwrite: true overwrite: true
electron:
name: playwright:electron:${{matrix.os}}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest-8-cores, windows-latest-8-cores, macos-14-large]
timeout-minutes: 60
runs-on: ${{ matrix.os }}
needs: check-rust-changes
steps:
- name: Tune GitHub-hosted runner network
uses: smorimoto/tune-github-hosted-runner-network@v1
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
- uses: KittyCAD/action-install-cli@main
- name: Install dependencies
shell: bash
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
shell: bash
run: yarn playwright install chromium --with-deps
- name: Download Wasm Cache
id: download-wasm
if: needs.check-rust-changes.outputs.rust-changed == 'false'
uses: dawidd6/action-download-artifact@v7
continue-on-error: true
with:
github_token: ${{secrets.GITHUB_TOKEN}}
name: wasm-bundle
workflow: build-and-store-wasm.yml
branch: main
path: src/wasm-lib/pkg
- name: copy wasm blob
if: needs.check-rust-changes.outputs.rust-changed == 'false'
shell: bash
run: cp src/wasm-lib/pkg/wasm_lib_bg.wasm public
continue-on-error: true
- name: Setup Rust
uses: dtolnay/rust-toolchain@stable
- name: Cache Wasm (because rust diff)
if: needs.check-rust-changes.outputs.rust-changed == 'true'
uses: Swatinem/rust-cache@v2
with:
workspaces: './src/wasm-lib'
- name: OR Cache Wasm (because wasm cache failed)
if: steps.download-wasm.outcome == 'failure'
uses: Swatinem/rust-cache@v2
with:
workspaces: './src/wasm-lib'
- name: install good sed
if: ${{ startsWith(matrix.os, 'macos') }}
shell: bash
run: |
brew install gnu-sed
echo "/opt/homebrew/opt/gnu-sed/libexec/gnubin" >> $GITHUB_PATH
- name: Install vector
if: ${{ startsWith(matrix.os, 'ubuntu') }}
shell: bash
run: |
curl --proto '=https' --tlsv1.2 -sSfL https://sh.vector.dev > /tmp/vector.sh
chmod +x /tmp/vector.sh
/tmp/vector.sh -y -no-modify-path
mkdir -p /tmp/vector
cp .github/workflows/vector.toml /tmp/vector.toml
sed -i "s#GITHUB_WORKFLOW#${GITHUB_WORKFLOW}#g" /tmp/vector.toml
sed -i "s#GITHUB_REPOSITORY#${GITHUB_REPOSITORY}#g" /tmp/vector.toml
sed -i "s#GITHUB_SHA#${GITHUB_SHA}#g" /tmp/vector.toml
sed -i "s#GITHUB_REF_NAME#${GITHUB_REF_NAME}#g" /tmp/vector.toml
sed -i "s#GH_ACTIONS_AXIOM_TOKEN#${{secrets.GH_ACTIONS_AXIOM_TOKEN}}#g" /tmp/vector.toml
cat /tmp/vector.toml
${HOME}/.vector/bin/vector --config /tmp/vector.toml &
- name: Build Wasm (because rust diff)
if: needs.check-rust-changes.outputs.rust-changed == 'true'
shell: bash
run: yarn build:wasm
- name: OR Build Wasm (because wasm cache failed)
if: steps.download-wasm.outcome == 'failure'
shell: bash
run: yarn build:wasm
- name: build electron
shell: bash
run: yarn tron:package
- uses: actions/download-artifact@v4
if: ${{ !cancelled() && (success() || failure()) }}
continue-on-error: true
with:
name: test-results-electron-${{ matrix.os }}-${{ github.sha }}
path: test-results/
- name: Run electron tests (with retries)
id: retry
if: ${{ !cancelled() && (success() || failure()) }}
shell: bash
run: |
.github/ci-cd-scripts/playwright-electron.sh ${{ matrix.os }}
env:
CI: true
FAIL_ON_CONSOLE_ERRORS: true
NODE_ENV: development
VITE_KC_DEV_TOKEN: ${{ secrets.KITTYCAD_API_TOKEN_DEV }}
VITE_KC_SKIP_AUTH: true
IS_UBUNTU: ${{ startsWith(matrix.os, 'ubuntu') && 'true' || 'false' }}
#DEBUG: 'pw:browser*'
- name: send to axiom
if: ${{ !cancelled() && (success() || failure()) && !startsWith(matrix.os, 'windows') }}
shell: bash
run: |
node playwrightProcess.mjs | tee /tmp/github-actions.log
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() && (success() || failure()) }}
with:
name: test-results-electron-${{ matrix.os }}-${{ github.sha }}
path: test-results/
include-hidden-files: true
retention-days: 30
overwrite: true
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() && (success() || failure()) }}
with:
name: playwright-report-electron-${{ matrix.os }}-${{ github.sha }}
path: playwright-report/
include-hidden-files: true
retention-days: 30
overwrite: true

View File

@ -388,6 +388,23 @@ yarn test:unit:local
#### E2E Tests #### E2E Tests
**Playwright Browser**
These E2E tests run in a browser (without electron).
There are tests that are skipped if they are ran in a windows OS or Linux OS. We can use playwright tags to implement test skipping.
Breaking down the command `yarn test:playwright:browser:chrome:windows`
- The application is `playwright`
- The runtime is a `browser`
- The specific `browser` is `chrome`
- The test should run in a `windows` environment. It will skip tests that are broken or flaky in the windows OS.
```
yarn test:playwright:browser:chrome
yarn test:playwright:browser:chrome:windows
yarn test:playwright:browser:chrome:ubuntu
```
**Playwright Electron** **Playwright Electron**
These E2E tests run in electron. There are tests that are skipped if they are ran in a windows, linux, or macos environment. We can use playwright tags to implement test skipping. These E2E tests run in electron. There are tests that are skipped if they are ran in a windows, linux, or macos environment. We can use playwright tags to implement test skipping.

View File

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

File diff suppressed because one or more lines are too long

View File

@ -19,7 +19,6 @@ layout: manual
* [`angledLineThatIntersects`](kcl/angledLineThatIntersects) * [`angledLineThatIntersects`](kcl/angledLineThatIntersects)
* [`angledLineToX`](kcl/angledLineToX) * [`angledLineToX`](kcl/angledLineToX)
* [`angledLineToY`](kcl/angledLineToY) * [`angledLineToY`](kcl/angledLineToY)
* [`appearance`](kcl/appearance)
* [`arc`](kcl/arc) * [`arc`](kcl/arc)
* [`arcTo`](kcl/arcTo) * [`arcTo`](kcl/arcTo)
* [`asin`](kcl/asin) * [`asin`](kcl/asin)

View File

@ -45,7 +45,7 @@ circles = map([1..3], drawCircle)
```js ```js
r = 10 // radius r = 10 // radius
// Call `map`, using an anonymous function instead of a named one. // Call `map`, using an anonymous function instead of a named one.
circles = map([1..3], fn(id) { circles = map([1..3], (id) {
return startSketchOn("XY") return startSketchOn("XY")
|> circle({ center = [id * 2 * r, 0], radius = r }, %) |> circle({ center = [id * 2 * r, 0], radius = r }, %)
}) })

View File

@ -61,7 +61,7 @@ assertEqual(sum([1, 2, 3]), 6, 0.00001, "1 + 2 + 3 summed is 6")
// an anonymous `add` function as its parameter, instead of declaring a // an anonymous `add` function as its parameter, instead of declaring a
// named function outside. // named function outside.
arr = [1, 2, 3] arr = [1, 2, 3]
sum = reduce(arr, 0, fn(i, result_so_far) { sum = reduce(arr, 0, (i, result_so_far) {
return i + result_so_far return i + result_so_far
}) })
@ -84,7 +84,7 @@ fn decagon(radius) {
// Use a `reduce` to draw the remaining decagon sides. // Use a `reduce` to draw the remaining decagon sides.
// For each number in the array 1..10, run the given function, // For each number in the array 1..10, run the given function,
// which takes a partially-sketched decagon and adds one more edge to it. // which takes a partially-sketched decagon and adds one more edge to it.
fullDecagon = reduce([1..10], startOfDecagonSketch, fn(i, partialDecagon) { fullDecagon = reduce([1..10], startOfDecagonSketch, (i, partialDecagon) {
// Draw one edge of the decagon. // Draw one edge of the decagon.
x = cos(stepAngle * i) * radius x = cos(stepAngle * i) * radius
y = sin(stepAngle * i) * radius y = sin(stepAngle * i) * radius

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -1,11 +1,22 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { setupElectron, tearDown } from './test-utils'
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Electron app header tests', () => { test.describe('Electron app header tests', () => {
test( test(
'Open Command Palette button has correct shortcut', 'Open Command Palette button has correct shortcut',
{ tag: '@electron' }, { tag: '@electron' },
async ({ page }, testInfo) => { async ({ browserName }, testInfo) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) const { electronApp, page } = await setupElectron({
testInfo,
folderSetupFn: async () => {},
})
await page.setViewportSize({ width: 1200, height: 500 })
// No space before the shortcut since it checks textContent. // No space before the shortcut since it checks textContent.
let text let text
@ -23,14 +34,21 @@ test.describe('Electron app header tests', () => {
const commandsButton = page.getByRole('button', { name: 'Commands' }) const commandsButton = page.getByRole('button', { name: 'Commands' })
await expect(commandsButton).toBeVisible() await expect(commandsButton).toBeVisible()
await expect(commandsButton).toHaveText(text) await expect(commandsButton).toHaveText(text)
await electronApp.close()
} }
) )
test( test(
'User settings has correct shortcut', 'User settings has correct shortcut',
{ tag: '@electron' }, { tag: '@electron' },
async ({ page }, testInfo) => { async ({ browserName }, testInfo) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) const { electronApp, page } = await setupElectron({
testInfo,
folderSetupFn: async () => {},
})
await page.setViewportSize({ width: 1200, height: 500 })
// Open the user sidebar menu. // Open the user sidebar menu.
await page.getByTestId('user-sidebar-toggle').click() await page.getByTestId('user-sidebar-toggle').click()
@ -41,6 +59,8 @@ test.describe('Electron app header tests', () => {
const userSettingsButton = page.getByTestId('user-settings') const userSettingsButton = page.getByTestId('user-settings')
await expect(userSettingsButton).toBeVisible() await expect(userSettingsButton).toBeVisible()
await expect(userSettingsButton).toHaveText(text) await expect(userSettingsButton).toHaveText(text)
await electronApp.close()
} }
) )
}) })

View File

@ -1,26 +1,29 @@
import { test, expect, Page } from './zoo-test' import { test, expect, Page } from '@playwright/test'
import { import {
getUtils, getUtils,
TEST_COLORS, TEST_COLORS,
setup,
tearDown,
commonPoints, commonPoints,
PERSIST_MODELING_CONTEXT, PERSIST_MODELING_CONTEXT,
} from './test-utils' } from './test-utils'
import { HomePageFixture } from './fixtures/homePageFixture'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.setTimeout(120000) test.setTimeout(120000)
async function doBasicSketch( async function doBasicSketch(page: Page, openPanes: string[]) {
page: Page,
homePage: HomePageFixture,
openPanes: string[]
) {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio const PUR = 400 / 37.5 //pixeltoUnitRatio
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.waitForTimeout()
await u.openDebugPanel() await u.openDebugPanel()
// If we have the code pane open, we should see the code. // If we have the code pane open, we should see the code.
@ -145,11 +148,13 @@ async function doBasicSketch(
} }
test.describe('Basic sketch', () => { test.describe('Basic sketch', () => {
test.fixme('code pane open at start', async ({ page, homePage }) => { test('code pane open at start', { tag: ['@skipWin'] }, async ({ page }) => {
await doBasicSketch(page, homePage, ['code']) // Skip on windows it is being weird.
test.skip(process.platform === 'win32', 'Skip on windows')
await doBasicSketch(page, ['code'])
}) })
test.fixme('code pane closed at start', async ({ page, homePage }) => { test('code pane closed at start', async ({ page }) => {
// Load the app with the code panes // Load the app with the code panes
await page.addInitScript(async (persistModelingContext) => { await page.addInitScript(async (persistModelingContext) => {
localStorage.setItem( localStorage.setItem(
@ -157,6 +162,6 @@ test.describe('Basic sketch', () => {
JSON.stringify({ openPanes: [] }) JSON.stringify({ openPanes: [] })
) )
}, PERSIST_MODELING_CONTEXT) }, PERSIST_MODELING_CONTEXT)
await doBasicSketch(page, homePage, []) await doBasicSketch(page, [])
}) })
}) })

View File

@ -1,21 +1,27 @@
import { test, expect, Page } from './zoo-test' import { test, expect } from '@playwright/test'
import { HomePageFixture } from './fixtures/homePageFixture' import { getUtils, setup, tearDown } from './test-utils'
import { getUtils } from './test-utils'
import { EngineCommand } from 'lang/std/artifactGraph' import { EngineCommand } from 'lang/std/artifactGraph'
import { uuidv4 } from 'lib/utils' import { uuidv4 } from 'lib/utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Can create sketches on all planes and their back sides', () => { test.describe('Can create sketches on all planes and their back sides', () => {
const sketchOnPlaneAndBackSideTest = async ( const sketchOnPlaneAndBackSideTest = async (
page: Page, page: any,
homePage: HomePageFixture,
plane: string, plane: string,
clickCoords: { x: number; y: number } clickCoords: { x: number; y: number }
) => { ) => {
const u = await getUtils(page) const u = await getUtils(page)
const PUR = 400 / 37.5 //pixeltoUnitRatio const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
const coord = const coord =
@ -77,39 +83,32 @@ test.describe('Can create sketches on all planes and their back sides', () => {
await u.clearCommandLogs() await u.clearCommandLogs()
await u.removeCurrentCode() await u.removeCurrentCode()
} }
test('XY', async ({ page, homePage }) => { test('XY', async ({ page }) => {
await sketchOnPlaneAndBackSideTest( await sketchOnPlaneAndBackSideTest(
page, page,
homePage,
'XY', 'XY',
{ x: 600, y: 388 } // red plane { x: 600, y: 388 } // red plane
// { x: 600, y: 400 }, // red plane // clicks grid helper and that causes problems, should fix so that these coords work too. // { x: 600, y: 400 }, // red plane // clicks grid helper and that causes problems, should fix so that these coords work too.
) )
}) })
test('YZ', async ({ page, homePage }) => { test('YZ', async ({ page }) => {
await sketchOnPlaneAndBackSideTest(page, homePage, 'YZ', { x: 700, y: 250 }) // green plane await sketchOnPlaneAndBackSideTest(page, 'YZ', { x: 700, y: 250 }) // green plane
}) })
test('XZ', async ({ page, homePage }) => { test('XZ', async ({ page }) => {
await sketchOnPlaneAndBackSideTest(page, homePage, '-XZ', { x: 700, y: 80 }) // blue plane await sketchOnPlaneAndBackSideTest(page, '-XZ', { x: 700, y: 80 }) // blue plane
}) })
test('-XY', async ({ page, homePage }) => { test('-XY', async ({ page }) => {
await sketchOnPlaneAndBackSideTest(page, homePage, '-XY', { await sketchOnPlaneAndBackSideTest(page, '-XY', { x: 600, y: 118 }) // back of red plane
x: 600,
y: 118,
}) // back of red plane
}) })
test('-YZ', async ({ page, homePage }) => { test('-YZ', async ({ page }) => {
await sketchOnPlaneAndBackSideTest(page, homePage, '-YZ', { await sketchOnPlaneAndBackSideTest(page, '-YZ', { x: 700, y: 219 }) // back of green plane
x: 700,
y: 219,
}) // back of green plan
}) })
test('-XZ', async ({ page, homePage }) => { test('-XZ', async ({ page }) => {
await sketchOnPlaneAndBackSideTest(page, homePage, 'XZ', { x: 700, y: 427 }) // back of blue plane await sketchOnPlaneAndBackSideTest(page, 'XZ', { x: 700, y: 427 }) // back of blue plane
}) })
}) })

View File

@ -1,15 +1,28 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { getUtils, executorInputPath } from './test-utils' import {
getUtils,
setup,
setupElectron,
tearDown,
executorInputPath,
} from './test-utils'
import { join } from 'path' import { join } from 'path'
import { bracket } from 'lib/exampleKcl' import { bracket } from 'lib/exampleKcl'
import { TEST_CODE_LONG_WITH_ERROR_OUT_OF_VIEW } from './storageStates' import { TEST_CODE_LONG_WITH_ERROR_OUT_OF_VIEW } from './storageStates'
import fsp from 'fs/promises' import fsp from 'fs/promises'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Code pane and errors', () => { test.describe('Code pane and errors', () => {
test('Typing KCL errors induces a badge on the code pane button', async ({ test('Typing KCL errors induces a badge on the code pane button', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
@ -18,18 +31,18 @@ test.describe('Code pane and errors', () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`// Extruded Triangle `// Extruded Triangle
sketch001 = startSketchOn('XZ') sketch001 = startSketchOn('XZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([10, 0], %) |> line([10, 0], %)
|> line([-5, 10], %) |> line([-5, 10], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(5, sketch001)` extrude001 = extrude(5, sketch001)`
) )
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -49,11 +62,11 @@ test.describe('Code pane and errors', () => {
await expect(codePaneButtonHolder).toContainText('notification') await expect(codePaneButtonHolder).toContainText('notification')
}) })
test.skip('Opening and closing the code pane will consistently show error diagnostics', async ({ test('Opening and closing the code pane will consistently show error diagnostics', async ({
page, page,
homePage,
editor,
}) => { }) => {
await page.goto('http://localhost:3000')
const u = await getUtils(page) const u = await getUtils(page)
// Load the app with the working starter code // Load the app with the working starter code
@ -61,8 +74,8 @@ test.describe('Code pane and errors', () => {
localStorage.setItem('persistCode', code) localStorage.setItem('persistCode', code)
}, bracket) }, bracket)
await page.setBodyDimensions({ width: 1200, height: 900 }) await page.setViewportSize({ width: 1200, height: 900 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -78,9 +91,8 @@ test.describe('Code pane and errors', () => {
await expect(codePaneButtonHolder).not.toContainText('notification') await expect(codePaneButtonHolder).not.toContainText('notification')
// Delete a character to break the KCL // Delete a character to break the KCL
await editor.openPane() await u.openKclCodePanel()
await editor.scrollToText('thickness, bracketLeg1Sketch)') await page.getByText('thickness, bracketLeg1Sketch)').click()
await page.getByText('extrude(thickness, bracketLeg1Sketch)').click()
await page.keyboard.press('Backspace') await page.keyboard.press('Backspace')
// Ensure that a badge appears on the button // Ensure that a badge appears on the button
@ -104,10 +116,7 @@ test.describe('Code pane and errors', () => {
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
// Open the code pane // Open the code pane
await editor.openPane() await u.openKclCodePanel()
// Go to our problematic code again (missing closing paren!)
await editor.scrollToText('extrude(thickness, bracketLeg1Sketch')
// Ensure that a badge appears on the button // Ensure that a badge appears on the button
await expect(codePaneButtonHolder).toContainText('notification') await expect(codePaneButtonHolder).toContainText('notification')
@ -120,58 +129,59 @@ test.describe('Code pane and errors', () => {
await expect(page.locator('.cm-tooltip').first()).toBeVisible() await expect(page.locator('.cm-tooltip').first()).toBeVisible()
}) })
test.fixme( test('When error is not in view you can click the badge to scroll to it', async ({
'When error is not in view you can click the badge to scroll to it',
async ({ page, homePage, context }) => {
// Load the app with the working starter code
await context.addInitScript((code) => {
localStorage.setItem('persistCode', code)
}, TEST_CODE_LONG_WITH_ERROR_OUT_OF_VIEW)
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene()
await page.waitForTimeout(1000)
// Ensure badge is present
const codePaneButtonHolder = page.locator('#code-button-holder')
await expect(codePaneButtonHolder).toContainText('notification')
// Ensure we have no errors in the gutter, since error out of view.
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
// Click the badge.
const badge = page.locator('#code-badge')
await expect(badge).toBeVisible()
await badge.click()
// Ensure we have an error diagnostic.
await expect(page.locator('.cm-lint-marker-error').first()).toBeVisible()
// Hover over the error to see the error message
await page.hover('.cm-lint-marker-error')
await expect(
page
.getByText(
'Modeling command failed: [ApiError { error_code: InternalEngine, message: "Solid3D revolve failed: sketch profile must lie entirely on one side of the revolution axis" }]'
)
.first()
).toBeVisible()
}
)
test('When error is not in view WITH LINTS you can click the badge to scroll to it', async ({
context,
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page)
// Load the app with the working starter code // Load the app with the working starter code
await context.addInitScript((code) => { await page.addInitScript((code) => {
localStorage.setItem('persistCode', code) localStorage.setItem('persistCode', code)
}, TEST_CODE_LONG_WITH_ERROR_OUT_OF_VIEW) }, TEST_CODE_LONG_WITH_ERROR_OUT_OF_VIEW)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await page.waitForTimeout(1000)
// Ensure badge is present
const codePaneButtonHolder = page.locator('#code-button-holder')
await expect(codePaneButtonHolder).toContainText('notification')
// Ensure we have no errors in the gutter, since error out of view.
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
// Click the badge.
const badge = page.locator('#code-badge')
await expect(badge).toBeVisible()
await badge.click()
// Ensure we have an error diagnostic.
await expect(page.locator('.cm-lint-marker-error').first()).toBeVisible()
// Hover over the error to see the error message
await page.hover('.cm-lint-marker-error')
await expect(
page
.getByText(
'sketch profile must lie entirely on one side of the revolution axis'
)
.first()
).toBeVisible()
})
test('When error is not in view WITH LINTS you can click the badge to scroll to it', async ({
page,
}) => {
const u = await getUtils(page)
// Load the app with the working starter code
await page.addInitScript((code) => {
localStorage.setItem('persistCode', code)
}, TEST_CODE_LONG_WITH_ERROR_OUT_OF_VIEW)
await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
await page.waitForTimeout(1000) await page.waitForTimeout(1000)
@ -231,29 +241,32 @@ test.describe('Code pane and errors', () => {
test( test(
'Opening multiple panes persists when switching projects', 'Opening multiple panes persists when switching projects',
{ tag: '@electron' }, { tag: '@electron' },
async ({ context, page }, testInfo) => { async ({ browserName }, testInfo) => {
// Setup multiple projects. // Setup multiple projects.
await context.folderSetupFn(async (dir) => { const { electronApp, page } = await setupElectron({
const routerTemplateDir = join(dir, 'router-template-slate') testInfo,
const bracketDir = join(dir, 'bracket') folderSetupFn: async (dir) => {
await Promise.all([ const routerTemplateDir = join(dir, 'router-template-slate')
fsp.mkdir(routerTemplateDir, { recursive: true }), const bracketDir = join(dir, 'bracket')
fsp.mkdir(bracketDir, { recursive: true }), await Promise.all([
]) fsp.mkdir(routerTemplateDir, { recursive: true }),
await Promise.all([ fsp.mkdir(bracketDir, { recursive: true }),
fsp.copyFile( ])
executorInputPath('router-template-slate.kcl'), await Promise.all([
join(routerTemplateDir, 'main.kcl') fsp.copyFile(
), executorInputPath('router-template-slate.kcl'),
fsp.copyFile( join(routerTemplateDir, 'main.kcl')
executorInputPath('focusrite_scarlett_mounting_braket.kcl'), ),
join(bracketDir, 'main.kcl') fsp.copyFile(
), executorInputPath('focusrite_scarlett_mounting_braket.kcl'),
]) join(bracketDir, 'main.kcl')
),
])
},
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await test.step('Opening the bracket project should load', async () => { await test.step('Opening the bracket project should load', async () => {
await expect(page.getByText('bracket')).toBeVisible() await expect(page.getByText('bracket')).toBeVisible()
@ -296,21 +309,30 @@ test(
await expect(page.locator('#variables-pane')).toBeVisible() await expect(page.locator('#variables-pane')).toBeVisible()
await expect(page.locator('#logs-pane')).toBeVisible() await expect(page.locator('#logs-pane')).toBeVisible()
}) })
await electronApp.close()
} }
) )
test( test(
'external change of file contents are reflected in editor', 'external change of file contents are reflected in editor',
{ tag: '@electron' }, { tag: '@electron' },
async ({ context, page }, testInfo) => { async ({ browserName }, testInfo) => {
const PROJECT_DIR_NAME = 'lee-was-here' const PROJECT_DIR_NAME = 'lee-was-here'
const { dir: projectsDir } = await context.folderSetupFn(async (dir) => { const {
const aProjectDir = join(dir, PROJECT_DIR_NAME) electronApp,
await fsp.mkdir(aProjectDir, { recursive: true }) page,
dir: projectsDir,
} = await setupElectron({
testInfo,
folderSetupFn: async (dir) => {
const aProjectDir = join(dir, PROJECT_DIR_NAME)
await fsp.mkdir(aProjectDir, { recursive: true })
},
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await test.step('Open the project', async () => { await test.step('Open the project', async () => {
await expect(page.getByText(PROJECT_DIR_NAME)).toBeVisible() await expect(page.getByText(PROJECT_DIR_NAME)).toBeVisible()
@ -329,5 +351,7 @@ test(
) )
await u.editorTextMatches(content) await u.editorTextMatches(content)
}) })
await electronApp.close()
} }
) )

View File

@ -1,30 +1,37 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { getUtils } from './test-utils' import { getUtils, setup, tearDown } from './test-utils'
import { KCL_DEFAULT_LENGTH } from 'lib/constants' import { KCL_DEFAULT_LENGTH } from 'lib/constants'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Command bar tests', () => { test.describe('Command bar tests', () => {
test('Extrude from command bar selects extrude line after', async ({ test('Extrude from command bar selects extrude line after', async ({
page, page,
homePage,
}) => { }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> xLine(-20, %) |> xLine(-20, %)
|> close(%) |> close(%)
` `
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
@ -45,24 +52,24 @@ test.describe('Command bar tests', () => {
) )
}) })
test('Fillet from command bar', async ({ page, homePage }) => { test('Fillet from command bar', async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-5, -5], %) |> startProfileAt([-5, -5], %)
|> line([0, 10], %) |> line([0, 10], %)
|> line([10, 0], %) |> line([10, 0], %)
|> line([0, -10], %) |> line([0, -10], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(-10, sketch001)` extrude001 = extrude(-10, sketch001)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
@ -80,16 +87,16 @@ test.describe('Command bar tests', () => {
await page.keyboard.press('Enter') // submit await page.keyboard.press('Enter') // submit
await page.waitForTimeout(100) await page.waitForTimeout(100)
await expect(page.locator('.cm-activeLine')).toContainText( await expect(page.locator('.cm-activeLine')).toContainText(
`fillet({ radius: ${KCL_DEFAULT_LENGTH}, tags: [seg01] }, %)` `fillet({ radius = ${KCL_DEFAULT_LENGTH}, tags = [seg01] }, %)`
) )
}) })
test('Command bar can change a setting, and switch back and forth between arguments', async ({ test('Command bar can change a setting, and switch back and forth between arguments', async ({
page, page,
homePage,
}) => { }) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) const u = await getUtils(page)
await homePage.goToModelingScene() await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
const commandBarButton = page.getByRole('button', { name: 'Commands' }) const commandBarButton = page.getByRole('button', { name: 'Commands' })
const cmdSearchBar = page.getByPlaceholder('Search commands') const cmdSearchBar = page.getByPlaceholder('Search commands')
@ -146,7 +153,7 @@ test.describe('Command bar tests', () => {
// Check that the visibility changed // Check that the visibility changed
await expect(paneSelector).not.toBeVisible() await expect(paneSelector).not.toBeVisible()
commandOptionInput = page.locator('[id="option-input"]') commandOptionInput = page.getByPlaceholder('off')
// Test case for https://github.com/KittyCAD/modeling-app/issues/2882 // Test case for https://github.com/KittyCAD/modeling-app/issues/2882
await commandBarButton.click() await commandBarButton.click()
@ -167,10 +174,10 @@ test.describe('Command bar tests', () => {
test('Command bar keybinding works from code editor and can change a setting', async ({ test('Command bar keybinding works from code editor and can change a setting', async ({
page, page,
homePage,
}) => { }) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) const u = await getUtils(page)
await homePage.goToModelingScene() await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
await expect( await expect(
page.getByRole('button', { name: 'Start Sketch' }) page.getByRole('button', { name: 'Start Sketch' })
@ -214,25 +221,25 @@ test.describe('Command bar tests', () => {
await expect(page.locator('body')).not.toHaveClass(`body-bg dark`) await expect(page.locator('body')).not.toHaveClass(`body-bg dark`)
}) })
test('Can extrude from the command bar', async ({ page, homePage }) => { test('Can extrude from the command bar', async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`distance = sqrt(20) `distance = sqrt(20)
sketch001 = startSketchOn('XZ') sketch001 = startSketchOn('XZ')
|> startProfileAt([-6.95, 10.98], %) |> startProfileAt([-6.95, 10.98], %)
|> line([25.1, 0.41], %) |> line([25.1, 0.41], %)
|> line([0.73, -20.93], %) |> line([0.73, -20.93], %)
|> line([-23.44, 0.52], %) |> line([-23.44, 0.52], %)
|> close(%) |> close(%)
` `
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// Make sure the stream is up // Make sure the stream is up
await u.openDebugPanel() await u.openDebugPanel()
@ -286,19 +293,26 @@ test.describe('Command bar tests', () => {
await continueButton.click() await continueButton.click()
await submitButton.click() await submitButton.click()
// Check that the code was updated
await u.waitForCmdReceive('extrude') await u.waitForCmdReceive('extrude')
// Unfortunately this indentation seems to matter for the test
await expect(page.locator('.cm-content')).toContainText( await expect(page.locator('.cm-content')).toHaveText(
'extrude001 = extrude(distance001, sketch001)' `distance = sqrt(20)
distance001 = ${KCL_DEFAULT_LENGTH}
sketch001 = startSketchOn('XZ')
|> startProfileAt([-6.95, 10.98], %)
|> line([25.1, 0.41], %)
|> line([0.73, -20.93], %)
|> line([-23.44, 0.52], %)
|> close(%)
extrude001 = extrude(distance001, sketch001)`.replace(/(\r\n|\n|\r)/gm, '') // remove newlines
) )
}) })
test('Can switch between sketch tools via command bar', async ({ test('Can switch between sketch tools via command bar', async ({ page }) => {
page, const u = await getUtils(page)
homePage, await page.setViewportSize({ width: 1200, height: 500 })
}) => { await u.waitForAuthSkipAppStart()
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene()
const sketchButton = page.getByRole('button', { name: 'Start Sketch' }) const sketchButton = page.getByRole('button', { name: 'Start Sketch' })
const cmdBarButton = page.getByRole('button', { name: 'Commands' }) const cmdBarButton = page.getByRole('button', { name: 'Commands' })

View File

@ -1,16 +1,23 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { getUtils } from './test-utils' import { getUtils, setup, tearDown } from './test-utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Copilot ghost text', () => { test.describe('Copilot ghost text', () => {
// eslint-disable-next-line jest/valid-title // eslint-disable-next-line jest/valid-title
test.skip(true, 'Needs to get covered again') test.skip(true, 'Needs to get covered again')
test('completes code in empty file', async ({ page, homePage }) => { test('completes code in empty file', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -45,13 +52,12 @@ test.describe('Copilot ghost text', () => {
test.skip('copilot disabled in sketch mode no select plane', async ({ test.skip('copilot disabled in sketch mode no select plane', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -95,13 +101,12 @@ test.describe('Copilot ghost text', () => {
test('copilot disabled in sketch mode after selecting plane', async ({ test('copilot disabled in sketch mode after selecting plane', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -179,12 +184,12 @@ test.describe('Copilot ghost text', () => {
await expect(page.locator('.cm-ghostText')).not.toBeVisible() await expect(page.locator('.cm-ghostText')).not.toBeVisible()
}) })
test('ArrowUp in code rejects the suggestion', async ({ page, homePage }) => { test('ArrowUp in code rejects the suggestion', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -207,15 +212,12 @@ test.describe('Copilot ghost text', () => {
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
}) })
test('ArrowDown in code rejects the suggestion', async ({ test('ArrowDown in code rejects the suggestion', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -238,15 +240,12 @@ test.describe('Copilot ghost text', () => {
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
}) })
test('ArrowLeft in code rejects the suggestion', async ({ test('ArrowLeft in code rejects the suggestion', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -269,15 +268,12 @@ test.describe('Copilot ghost text', () => {
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
}) })
test('ArrowRight in code rejects the suggestion', async ({ test('ArrowRight in code rejects the suggestion', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -300,12 +296,12 @@ test.describe('Copilot ghost text', () => {
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
}) })
test('Enter in code scoots it down', async ({ page, homePage }) => { test('Enter in code scoots it down', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -330,15 +326,12 @@ test.describe('Copilot ghost text', () => {
) )
}) })
test('Ctrl+shift+z in code rejects the suggestion', async ({ test('Ctrl+shift+z in code rejects the suggestion', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
@ -367,13 +360,12 @@ test.describe('Copilot ghost text', () => {
test('Ctrl+z in code rejects the suggestion and undos the last code', async ({ test('Ctrl+z in code rejects the suggestion and undos the last code', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await page.waitForTimeout(800) await page.waitForTimeout(800)
await u.codeLocator.click() await u.codeLocator.click()
@ -428,107 +420,98 @@ test.describe('Copilot ghost text', () => {
await expect(page.locator('.cm-ghostText').first()).not.toBeVisible() await expect(page.locator('.cm-ghostText').first()).not.toBeVisible()
// TODO when we make codemirror a widget, we can test this. // TODO when we make codemirror a widget, we can test this.
//await expect(page.locator('.cm-content')).toHaveText(``) }) //await expect(page.locator('.cm-content')).toHaveText(``)
})
test('delete in code rejects the suggestion', async ({ test('delete in code rejects the suggestion', async ({ page }) => {
page, const u = await getUtils(page)
homePage, // const PUR = 400 / 37.5 //pixeltoUnitRatio
}) => { await page.setViewportSize({ width: 1200, height: 500 })
const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
await expect(page.locator('.cm-ghostText')).not.toBeVisible() await expect(page.locator('.cm-ghostText')).not.toBeVisible()
await page.waitForTimeout(500) await page.waitForTimeout(500)
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await expect(page.locator('.cm-ghostText').first()).toBeVisible() await expect(page.locator('.cm-ghostText').first()).toBeVisible()
await expect(page.locator('.cm-content')).toHaveText( await expect(page.locator('.cm-content')).toHaveText(
`fn cube = (pos, scale) => { sg = startSketchOn('XY') |> startProfileAt(pos, %) |> line([0, scale], %) |> line([scale, 0], %) |> line([0, -scale], %) return sg}part001 = cube([0,0], 20) |> close(%) |> extrude(20, %)` `fn cube = (pos, scale) => { sg = startSketchOn('XY') |> startProfileAt(pos, %) |> line([0, scale], %) |> line([scale, 0], %) |> line([0, -scale], %) return sg}part001 = cube([0,0], 20) |> close(%) |> extrude(20, %)`
) )
await expect(page.locator('.cm-ghostText').first()).toHaveText( await expect(page.locator('.cm-ghostText').first()).toHaveText(
`fn cube = (pos, scale) => {` `fn cube = (pos, scale) => {`
) )
// Going elsewhere in the code should hide the ghost text. // Going elsewhere in the code should hide the ghost text.
await page.keyboard.press('Delete') await page.keyboard.press('Delete')
await expect(page.locator('.cm-ghostText').first()).not.toBeVisible() await expect(page.locator('.cm-ghostText').first()).not.toBeVisible()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
}) })
test('backspace in code rejects the suggestion', async ({ test('backspace in code rejects the suggestion', async ({ page }) => {
page, const u = await getUtils(page)
homePage, // const PUR = 400 / 37.5 //pixeltoUnitRatio
}) => { await page.setViewportSize({ width: 1200, height: 500 })
const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
await expect(page.locator('.cm-ghostText')).not.toBeVisible() await expect(page.locator('.cm-ghostText')).not.toBeVisible()
await page.waitForTimeout(500) await page.waitForTimeout(500)
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await expect(page.locator('.cm-ghostText').first()).toBeVisible() await expect(page.locator('.cm-ghostText').first()).toBeVisible()
await expect(page.locator('.cm-content')).toHaveText( await expect(page.locator('.cm-content')).toHaveText(
`fn cube = (pos, scale) => { sg = startSketchOn('XY') |> startProfileAt(pos, %) |> line([0, scale], %) |> line([scale, 0], %) |> line([0, -scale], %) return sg}part001 = cube([0,0], 20) |> close(%) |> extrude(20, %)` `fn cube = (pos, scale) => { sg = startSketchOn('XY') |> startProfileAt(pos, %) |> line([0, scale], %) |> line([scale, 0], %) |> line([0, -scale], %) return sg}part001 = cube([0,0], 20) |> close(%) |> extrude(20, %)`
) )
await expect(page.locator('.cm-ghostText').first()).toHaveText( await expect(page.locator('.cm-ghostText').first()).toHaveText(
`fn cube = (pos, scale) => {` `fn cube = (pos, scale) => {`
) )
// Going elsewhere in the code should hide the ghost text. // Going elsewhere in the code should hide the ghost text.
await page.keyboard.press('Backspace') await page.keyboard.press('Backspace')
await expect(page.locator('.cm-ghostText').first()).not.toBeVisible() await expect(page.locator('.cm-ghostText').first()).not.toBeVisible()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
}) })
test('focus outside code pane rejects the suggestion', async ({ test('focus outside code pane rejects the suggestion', async ({ page }) => {
page, const u = await getUtils(page)
homePage, // const PUR = 400 / 37.5 //pixeltoUnitRatio
}) => { await page.setViewportSize({ width: 1200, height: 500 })
const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.codeLocator.click() await u.codeLocator.click()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
await expect(page.locator('.cm-ghostText')).not.toBeVisible() await expect(page.locator('.cm-ghostText')).not.toBeVisible()
await page.waitForTimeout(500) await page.waitForTimeout(500)
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
await expect(page.locator('.cm-ghostText').first()).toBeVisible() await expect(page.locator('.cm-ghostText').first()).toBeVisible()
await expect(page.locator('.cm-content')).toHaveText( await expect(page.locator('.cm-content')).toHaveText(
`fn cube = (pos, scale) => { sg = startSketchOn('XY') |> startProfileAt(pos, %) |> line([0, scale], %) |> line([scale, 0], %) |> line([0, -scale], %) return sg}part001 = cube([0,0], 20) |> close(%) |> extrude(20, %)` `fn cube = (pos, scale) => { sg = startSketchOn('XY') |> startProfileAt(pos, %) |> line([0, scale], %) |> line([scale, 0], %) |> line([0, -scale], %) return sg}part001 = cube([0,0], 20) |> close(%) |> extrude(20, %)`
) )
await expect(page.locator('.cm-ghostText').first()).toHaveText( await expect(page.locator('.cm-ghostText').first()).toHaveText(
`fn cube = (pos, scale) => {` `fn cube = (pos, scale) => {`
) )
// Going outside the editor should hide the ghost text. // Going outside the editor should hide the ghost text.
await page.mouse.move(0, 0) await page.mouse.move(0, 0)
await page await page
.getByRole('button', { name: 'Start Sketch' }) .getByRole('button', { name: 'Start Sketch' })
.waitFor({ state: 'visible' }) .waitFor({ state: 'visible' })
await page.getByRole('button', { name: 'Start Sketch' }).click() await page.getByRole('button', { name: 'Start Sketch' }).click()
await expect(page.locator('.cm-ghostText').first()).not.toBeVisible() await expect(page.locator('.cm-ghostText').first()).not.toBeVisible()
await expect(page.locator('.cm-content')).toHaveText(``) await expect(page.locator('.cm-content')).toHaveText(``)
})
}) })
}) })

View File

@ -1,6 +1,14 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { getUtils } from './test-utils' import { getUtils, setup, tearDown } from './test-utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
function countNewlines(input: string): number { function countNewlines(input: string): number {
let count = 0 let count = 0
@ -16,14 +24,13 @@ test.describe('Debug pane', () => {
test('Artifact IDs in the artifact graph are stable across code edits', async ({ test('Artifact IDs in the artifact graph are stable across code edits', async ({
page, page,
context, context,
homePage,
}) => { }) => {
const code = `sketch001 = startSketchOn('XZ') const code = `sketch001 = startSketchOn('XZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([1, 1], %) |> line([1, 1], %)
` `
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
const tree = page.getByTestId('debug-feature-tree') const tree = page.getByTestId('debug-feature-tree')
const segment = tree.locator('li', { const segment = tree.locator('li', {
@ -32,7 +39,7 @@ test.describe('Debug pane', () => {
}) })
await test.step('Test setup', async () => { await test.step('Test setup', async () => {
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openKclCodePanel() await u.openKclCodePanel()
await u.openDebugPanel() await u.openDebugPanel()
// Set the code in the code editor. // Set the code in the code editor.

View File

@ -1,31 +1,39 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import path from 'path' import { join } from 'path'
import { import {
getUtils, getUtils,
setupElectron,
tearDown,
executorInputPath, executorInputPath,
getPlaywrightDownloadDir,
} from './test-utils' } from './test-utils'
import fsp from 'fs/promises' import fsp from 'fs/promises'
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test( test(
'export works on the first try', 'export works on the first try',
{ tag: '@electron' }, { tag: '@electron' },
async ({ page, context }, testInfo) => { async ({ browserName }, testInfo) => {
await context.folderSetupFn(async (dir) => { const { electronApp, page } = await setupElectron({
const bracketDir = path.join(dir, 'bracket') testInfo,
await Promise.all([fsp.mkdir(bracketDir, { recursive: true })]) folderSetupFn: async (dir) => {
await Promise.all([ const bracketDir = join(dir, 'bracket')
fsp.copyFile( await Promise.all([fsp.mkdir(bracketDir, { recursive: true })])
executorInputPath('router-template-slate.kcl'), await Promise.all([
path.join(bracketDir, 'other.kcl') fsp.copyFile(
), executorInputPath('router-template-slate.kcl'),
fsp.copyFile( join(bracketDir, 'other.kcl')
executorInputPath('focusrite_scarlett_mounting_braket.kcl'), ),
path.join(bracketDir, 'main.kcl') fsp.copyFile(
), executorInputPath('focusrite_scarlett_mounting_braket.kcl'),
]) join(bracketDir, 'main.kcl')
),
])
},
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
page.on('console', console.log) page.on('console', console.log)
@ -85,16 +93,12 @@ test(
await expect(successToastMessage).toBeVisible() await expect(successToastMessage).toBeVisible()
await expect(exportingToastMessage).not.toBeVisible() await expect(exportingToastMessage).not.toBeVisible()
const firstFileFullPath = path.resolve(
getPlaywrightDownloadDir(page),
exportFileName
)
await test.step('Check the export size', async () => { await test.step('Check the export size', async () => {
await expect await expect
.poll( .poll(
async () => { async () => {
try { try {
const outputGltf = await fsp.readFile(firstFileFullPath) const outputGltf = await fsp.readFile(exportFileName)
return outputGltf.byteLength return outputGltf.byteLength
} catch (e) { } catch (e) {
return 0 return 0
@ -103,6 +107,9 @@ test(
{ timeout: 15_000 } { timeout: 15_000 }
) )
.toBeGreaterThan(300_000) .toBeGreaterThan(300_000)
// clean up exported file
await fsp.rm(exportFileName)
}) })
}) })
@ -163,16 +170,12 @@ test(
expect(exportingToastMessage).not.toBeVisible(), expect(exportingToastMessage).not.toBeVisible(),
])) ]))
const secondFileFullPath = path.resolve(
getPlaywrightDownloadDir(page),
exportFileName
)
await test.step('Check the export size', async () => { await test.step('Check the export size', async () => {
await expect await expect
.poll( .poll(
async () => { async () => {
try { try {
const outputGltf = await fsp.readFile(secondFileFullPath) const outputGltf = await fsp.readFile(exportFileName)
return outputGltf.byteLength return outputGltf.byteLength
} catch (e) { } catch (e) {
return 0 return 0
@ -181,7 +184,13 @@ test(
{ timeout: 15_000 } { timeout: 15_000 }
) )
.toBeGreaterThan(100_000) .toBeGreaterThan(100_000)
// clean up exported file
await fsp.rm(exportFileName)
}) })
await electronApp.close()
}) })
await electronApp.close()
} }
) )

View File

@ -1,4 +1,4 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import fsp from 'fs/promises' import fsp from 'fs/promises'
import { uuidv4 } from 'lib/utils' import { uuidv4 } from 'lib/utils'
import { import {
@ -6,27 +6,37 @@ import {
darkModePlaneColorXZ, darkModePlaneColorXZ,
executorInputPath, executorInputPath,
getUtils, getUtils,
setup,
setupElectron,
tearDown,
} from './test-utils' } from './test-utils'
import { join } from 'path' import { join } from 'path'
test.describe('Editor tests', () => { test.beforeEach(async ({ context, page }, testInfo) => {
test('can comment out code with ctrl+/', async ({ page, homePage }) => { await setup(context, page, testInfo)
const u = await getUtils(page) })
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene() test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Editor tests', () => {
test('can comment out code with ctrl+/', async ({ page }) => {
const u = await getUtils(page)
await page.setViewportSize({ width: 1000, height: 500 })
await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
await u.codeLocator.click() await u.codeLocator.click()
await page.keyboard.type(`sketch001 = startSketchOn('XY') await page.keyboard.type(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
await page.keyboard.down('ControlOrMeta') await page.keyboard.down('ControlOrMeta')
await page.keyboard.press('/') await page.keyboard.press('/')
@ -34,11 +44,11 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XY') .toHaveText(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
// |> close(%)`) // |> close(%)`)
// uncomment the code // uncomment the code
await page.keyboard.down('ControlOrMeta') await page.keyboard.down('ControlOrMeta')
@ -47,63 +57,61 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XY') .toHaveText(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
}) })
test('if you click the format button it formats your code', async ({ test('if you click the format button it formats your code', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
await u.codeLocator.click() await u.codeLocator.click()
await page.keyboard.type(`sketch001 = startSketchOn('XY') await page.keyboard.type(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %)
|> line([20, 0], %)
|> line([0, 20], %)
|> line([-20, 0], %)
|> close(%)`)
await page.locator('#code-pane button:first-child').click()
await page.locator('button:has-text("Format code")').click()
await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
await page.locator('#code-pane button:first-child').click()
await page.locator('button:has-text("Format code")').click()
await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %)
|> line([20, 0], %)
|> line([0, 20], %)
|> line([-20, 0], %)
|> close(%)`)
}) })
test('if you click the format button it formats your code and executes so lints are still there', async ({ test('if you click the format button it formats your code and executes so lints are still there', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
await u.codeLocator.click() await u.codeLocator.click()
await page.keyboard.type(`sketch_001 = startSketchOn('XY') await page.keyboard.type(`sketch_001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
@ -127,11 +135,11 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch_001 = startSketchOn('XY') .toHaveText(`sketch_001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
// error in guter // error in guter
await expect(page.locator('.cm-lint-marker-info').first()).toBeVisible() await expect(page.locator('.cm-lint-marker-info').first()).toBeVisible()
@ -143,27 +151,29 @@ test.describe('Editor tests', () => {
).toBeVisible() ).toBeVisible()
}) })
test('fold gutters work', async ({ page, homePage }) => { test('fold gutters work', async ({ page }) => {
const u = await getUtils(page)
const fullCode = `sketch001 = startSketchOn('XY') const fullCode = `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)` |> close(%)`
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)` |> close(%)`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// TODO: Jess needs to fix this but you have to mod the code to get them to show // TODO: Jess needs to fix this but you have to mod the code to get them to show
// up, its an annoying codemirror thing. // up, its an annoying codemirror thing.
@ -214,25 +224,22 @@ test.describe('Editor tests', () => {
await expect(foldGutterFoldLine).not.toBeVisible() await expect(foldGutterFoldLine).not.toBeVisible()
}) })
test('hover over functions shows function description', async ({ test('hover over functions shows function description', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)` |> close(%)`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
@ -261,24 +268,23 @@ test.describe('Editor tests', () => {
test('if you use the format keyboard binding it formats your code', async ({ test('if you use the format keyboard binding it formats your code', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)` |> close(%)`
) )
localStorage.setItem('disableAxis', 'true') localStorage.setItem('disableAxis', 'true')
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
@ -295,33 +301,32 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XY') .toHaveText(`sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
}) })
test('if you use the format keyboard binding it formats your code and executes so lints are shown', async ({ test('if you use the format keyboard binding it formats your code and executes so lints are shown', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch_001 = startSketchOn('XY') `sketch_001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)` |> close(%)`
) )
localStorage.setItem('disableAxis', 'true') localStorage.setItem('disableAxis', 'true')
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
@ -348,11 +353,11 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch_001 = startSketchOn('XY') .toHaveText(`sketch_001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> line([-20, 0], %) |> line([-20, 0], %)
|> close(%)`) |> close(%)`)
// error in guter // error in guter
await expect(page.locator('.cm-lint-marker-info').first()).toBeVisible() await expect(page.locator('.cm-lint-marker-info').first()).toBeVisible()
@ -364,14 +369,11 @@ test.describe('Editor tests', () => {
).toBeVisible() ).toBeVisible()
}) })
test('if you write kcl with lint errors you get lints', async ({ test('if you write kcl with lint errors you get lints', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-info')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-info')).not.toBeVisible()
@ -407,26 +409,23 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-lint-marker-info')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-info')).not.toBeVisible()
}) })
test('if you fixup kcl errors you clear lints', async ({ test('if you fixup kcl errors you clear lints', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([3.29, 7.86], %) |> startProfileAt([3.29, 7.86], %)
|> line([2.48, 2.44], %) |> line([2.48, 2.44], %)
|> line([2.66, 1.17], %) |> line([2.66, 1.17], %)
|> close(%) |> close(%)
` `
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
@ -448,23 +447,20 @@ test.describe('Editor tests', () => {
).not.toBeVisible() ).not.toBeVisible()
}) })
test('if you write invalid kcl you get inlined errors', async ({ test('if you write invalid kcl you get inlined errors', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// check no error to begin with // check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
/* add the following code to the editor ($ error is not a valid line) /* add the following code to the editor ($ error is not a valid line)
$ error $ error
const topAng = 30 topAng = 30
const bottomAng = 25 bottomAng = 25
*/ */
await u.codeLocator.click() await u.codeLocator.click()
await page.keyboard.type('$ error') await page.keyboard.type('$ error')
@ -478,12 +474,14 @@ test.describe('Editor tests', () => {
await page.keyboard.type('bottomAng = 25') await page.keyboard.type('bottomAng = 25')
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
// error in guter // error in gutter
await expect(page.locator('.cm-lint-marker-error')).toBeVisible() await expect(page.locator('.cm-lint-marker-error')).toBeVisible()
// error text on hover // error text on hover
await page.hover('.cm-lint-marker-error') await page.hover('.cm-lint-marker-error')
await expect(page.getByText('Unexpected token: $').first()).toBeVisible() await expect(
page.getByText('Tag names must not be empty').first()
).toBeVisible()
// select the line that's causing the error and delete it // select the line that's causing the error and delete it
await page.getByText('$ error').click() await page.getByText('$ error').click()
@ -522,108 +520,106 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible() await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
}) })
test.fixme( // TODO currently multiple source ranges are not supported
'error with 2 source ranges gets 2 diagnostics', test.skip('error with 2 source ranges gets 2 diagnostics', async ({
async ({ page, homePage }) => {
const u = await getUtils(page)
await page.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`length = .750
width = 0.500
height = 0.500
dia = 4
fn squareHole = (l, w) => {
squareHoleSketch = startSketchOn('XY')
|> startProfileAt([-width / 2, -length / 2], %)
|> lineTo([width / 2, -length / 2], %)
|> lineTo([width / 2, length / 2], %)
|> lineTo([-width / 2, length / 2], %)
|> close(%)
return squareHoleSketch
}
`
)
})
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
await u.waitForPageLoad()
await page.waitForTimeout(1000)
await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel()
// check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
// Click on the bottom of the code editor to add a new line
await u.codeLocator.click()
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('Enter')
await page.keyboard.type(`extrusion = startSketchOn('XY')
|> circle({ center: [0, 0], radius: dia/2 }, %)
|> hole(squareHole(length, width, height), %)
|> extrude(height, %)`)
// error in gutter
await expect(page.locator('.cm-lint-marker-error').first()).toBeVisible()
await page.hover('.cm-lint-marker-error:first-child')
await expect(
page.getByText('Expected 2 arguments, got 3').first()
).toBeVisible()
// Make sure there are two diagnostics
await expect(page.locator('.cm-lint-marker-error')).toHaveCount(2)
}
)
test('if your kcl gets an error from the engine it is inlined', async ({
context,
page, page,
homePage,
}) => { }) => {
await context.addInitScript(async () => { const u = await getUtils(page)
await page.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`length = .750
width = 0.500
height = 0.500
dia = 4
fn squareHole = (l, w) => {
squareHoleSketch = startSketchOn('XY')
|> startProfileAt([-width / 2, -length / 2], %)
|> lineTo([width / 2, -length / 2], %)
|> lineTo([width / 2, length / 2], %)
|> lineTo([-width / 2, length / 2], %)
|> close(%)
return squareHoleSketch
}
`
)
})
await page.setViewportSize({ width: 1000, height: 500 })
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel()
// check no error to begin with
await expect(page.locator('.cm-lint-marker-error')).not.toBeVisible()
// Click on the bottom of the code editor to add a new line
await u.codeLocator.click()
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
await page.keyboard.press('Enter')
await page.keyboard.type(`extrusion = startSketchOn('XY')
|> circle({ center = [0, 0], radius = dia/2 }, %)
|> hole(squareHole(length, width, height), %)
|> extrude(height, %)`)
// error in gutter
await expect(page.locator('.cm-lint-marker-error').first()).toBeVisible()
await page.hover('.cm-lint-marker-error:first-child')
await expect(
page.getByText('Expected 2 arguments, got 3').first()
).toBeVisible()
// Make sure there are two diagnostics
await expect(page.locator('.cm-lint-marker-error')).toHaveCount(2)
})
test('if your kcl gets an error from the engine it is inlined', async ({
page,
}) => {
const u = await getUtils(page)
await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`box = startSketchOn('XY') `box = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([0, 10], %) |> line([0, 10], %)
|> line([10, 0], %) |> line([10, 0], %)
|> line([0, -10], %, $revolveAxis) |> line([0, -10], %, $revolveAxis)
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
sketch001 = startSketchOn(box, revolveAxis) sketch001 = startSketchOn(box, revolveAxis)
|> startProfileAt([5, 10], %) |> startProfileAt([5, 10], %)
|> line([0, -10], %) |> line([0, -10], %)
|> line([2, 0], %) |> line([2, 0], %)
|> line([0, -10], %) |> line([0, -10], %)
|> close(%) |> close(%)
|> revolve({ |> revolve({
axis: revolveAxis, axis = revolveAxis,
angle: 90 angle = 90
}, %) }, %)
` `
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await page.goto('/')
await u.waitForPageLoad()
await expect(page.locator('.cm-lint-marker-error')).toBeVisible() await expect(page.locator('.cm-lint-marker-error')).toBeVisible()
@ -634,15 +630,12 @@ test.describe('Editor tests', () => {
await expect(page.getByText(searchText)).toBeVisible() await expect(page.getByText(searchText)).toBeVisible()
}) })
test.describe('Autocomplete works', () => { test.describe('Autocomplete works', () => {
test('with enter/click to accept the completion', async ({ test('with enter/click to accept the completion', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// tests clicking on an option, selection the first option // tests clicking on an option, selection the first option
// and arrowing down to an option // and arrowing down to an option
@ -704,19 +697,19 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([3.14, 12], %) |> startProfileAt([3.14, 12], %)
|> xLine(5, %) // lin`) |> xLine(5, %) // lin`)
// expect there to be no KCL errors // expect there to be no KCL errors
await expect(page.locator('.cm-lint-marker-error')).toHaveCount(0) await expect(page.locator('.cm-lint-marker-error')).toHaveCount(0)
}) })
test('with tab to accept the completion', async ({ page, homePage }) => { test('with tab to accept the completion', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// this test might be brittle as we add and remove functions // this test might be brittle as we add and remove functions
// but should also be easy to update. // but should also be easy to update.
@ -778,30 +771,26 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([3.14, 12], %) |> startProfileAt([3.14, 12], %)
|> xLine(5, %) // lin`) |> xLine(5, %) // lin`)
}) })
}) })
test('Can undo a click and point extrude with ctrl+z', async ({ test('Can undo a click and point extrude with ctrl+z', async ({ page }) => {
page,
context,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await context.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([4.61, -14.01], %) |> startProfileAt([4.61, -14.01], %)
|> line([12.73, -0.09], %) |> line([12.73, -0.09], %)
|> tangentialArcTo([24.95, -5.38], %) |> tangentialArcTo([24.95, -5.38], %)
|> close(%)` |> close(%)`
) )
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await expect( await expect(
page.getByRole('button', { name: 'Start Sketch' }) page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled() ).not.toBeDisabled()
@ -854,32 +843,29 @@ test.describe('Editor tests', () => {
await page.waitForTimeout(100) await page.waitForTimeout(100)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([4.61, -14.01], %) |> startProfileAt([4.61, -14.01], %)
|> line([12.73, -0.09], %) |> line([12.73, -0.09], %)
|> tangentialArcTo([24.95, -5.38], %) |> tangentialArcTo([24.95, -5.38], %)
|> close(%)`) |> close(%)`)
}) })
test('Can undo a sketch modification with ctrl+z', async ({ test('Can undo a sketch modification with ctrl+z', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([4.61, -10.01], %) |> startProfileAt([4.61, -10.01], %)
|> line([12.73, -0.09], %) |> line([12.73, -0.09], %)
|> tangentialArcTo([24.95, -0.38], %) |> tangentialArcTo([24.95, -0.38], %)
|> close(%) |> close(%)
|> extrude(5, %)` |> extrude(5, %)`
) )
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await expect( await expect(
page.getByRole('button', { name: 'Start Sketch' }) page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled() ).not.toBeDisabled()
@ -906,7 +892,7 @@ test.describe('Editor tests', () => {
}) })
await page.waitForTimeout(100) await page.waitForTimeout(100)
const startPX = [1200 / 2, 500 / 2] const startPX = [665, 397]
const dragPX = 40 const dragPX = 40
@ -920,9 +906,9 @@ test.describe('Editor tests', () => {
await expect(page.getByTestId('segment-overlay')).toHaveCount(2) await expect(page.getByTestId('segment-overlay')).toHaveCount(2)
// drag startProfileAt handle // drag startProfieAt handle
await page.dragAndDrop('#stream', '#stream', { await page.dragAndDrop('#stream', '#stream', {
sourcePosition: { x: startPX[0] + 68, y: startPX[1] + 147 }, sourcePosition: { x: startPX[0], y: startPX[1] },
targetPosition: { x: startPX[0] + dragPX, y: startPX[1] + dragPX }, targetPosition: { x: startPX[0] + dragPX, y: startPX[1] + dragPX },
}) })
await page.waitForTimeout(100) await page.waitForTimeout(100)
@ -960,12 +946,12 @@ test.describe('Editor tests', () => {
// expect the code to have changed // expect the code to have changed
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([2.71, -2.71], %) |> startProfileAt([7.12, -12.68], %)
|> line([15.4, -2.78], %) |> line([15.39, -2.78], %)
|> tangentialArcTo([27.6, -3.05], %) |> tangentialArcTo([27.6, -3.05], %)
|> close(%) |> close(%)
|> extrude(5, %) |> extrude(5, %)
`) `)
// Hit undo // Hit undo
await page.keyboard.down('Control') await page.keyboard.down('Control')
@ -974,11 +960,11 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([2.71, -2.71], %) |> startProfileAt([7.12, -12.68], %)
|> line([15.4, -2.78], %) |> line([15.39, -2.78], %)
|> tangentialArcTo([24.95, -0.38], %) |> tangentialArcTo([24.95, -0.38], %)
|> close(%) |> close(%)
|> extrude(5, %)`) |> extrude(5, %)`)
// Hit undo again. // Hit undo again.
await page.keyboard.down('Control') await page.keyboard.down('Control')
@ -987,12 +973,12 @@ test.describe('Editor tests', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([2.71, -2.71], %) |> startProfileAt([7.12, -12.68], %)
|> line([12.73, -0.09], %) |> line([12.73, -0.09], %)
|> tangentialArcTo([24.95, -0.38], %) |> tangentialArcTo([24.95, -0.38], %)
|> close(%) |> close(%)
|> extrude(5, %) |> extrude(5, %)
`) `)
// Hit undo again. // Hit undo again.
await page.keyboard.down('Control') await page.keyboard.down('Control')
@ -1002,29 +988,31 @@ test.describe('Editor tests', () => {
await page.waitForTimeout(100) await page.waitForTimeout(100)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt([4.61, -10.01], %) |> startProfileAt([4.61, -10.01], %)
|> line([12.73, -0.09], %) |> line([12.73, -0.09], %)
|> tangentialArcTo([24.95, -0.38], %) |> tangentialArcTo([24.95, -0.38], %)
|> close(%) |> close(%)
|> extrude(5, %)`) |> extrude(5, %)`)
}) })
test.fixme( test.fixme(
`Can use the import stdlib function on a local OBJ file`, `Can use the import stdlib function on a local OBJ file`,
{ tag: '@electron' }, { tag: '@electron' },
async ({ page, context }, testInfo) => { async ({ browserName }, testInfo) => {
await context.folderSetupFn(async (dir) => { const { electronApp, page } = await setupElectron({
const bracketDir = join(dir, 'cube') testInfo,
await fsp.mkdir(bracketDir, { recursive: true }) folderSetupFn: async (dir) => {
await fsp.copyFile( const bracketDir = join(dir, 'cube')
executorInputPath('cube.obj'), await fsp.mkdir(bracketDir, { recursive: true })
join(bracketDir, 'cube.obj') await fsp.copyFile(
) executorInputPath('cube.obj'),
await fsp.writeFile(join(bracketDir, 'main.kcl'), '') join(bracketDir, 'cube.obj')
)
await fsp.writeFile(join(bracketDir, 'main.kcl'), '')
},
}) })
const viewportSize = { width: 1200, height: 500 } const viewportSize = { width: 1200, height: 500 }
await page.setBodyDimensions(viewportSize) await page.setViewportSize(viewportSize)
// Locators and constants // Locators and constants
const u = await getUtils(page) const u = await getUtils(page)
@ -1082,6 +1070,8 @@ test.describe('Editor tests', () => {
}) })
.toBeGreaterThan(15) .toBeGreaterThan(15)
}) })
await electronApp.close()
} }
) )
}) })

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,7 @@ export class EditorFixture {
reConstruct = (page: Page) => { reConstruct = (page: Page) => {
this.page = page this.page = page
this.codeContent = page.locator('.cm-content[data-language="kcl"]') this.codeContent = page.locator('.cm-content')
this.diagnosticsTooltip = page.locator('.cm-tooltip-lint') this.diagnosticsTooltip = page.locator('.cm-tooltip-lint')
this.diagnosticsGutterIcon = page.locator('.cm-lint-marker-error') this.diagnosticsGutterIcon = page.locator('.cm-lint-marker-error')
this.activeLine = this.page.locator('.cm-activeLine') this.activeLine = this.page.locator('.cm-activeLine')
@ -54,13 +54,13 @@ export class EditorFixture {
} }
} }
if (!shouldNormalise) { if (!shouldNormalise) {
const expectStart = expect.poll(() => this.codeContent.textContent()) const expectStart = expect(this.codeContent)
if (not) { if (not) {
const result = await expectStart.not.toContain(code) const result = await expectStart.not.toContainText(code, { timeout })
await resetPane() await resetPane()
return result return result
} }
const result = await expectStart.toContain(code) const result = await expectStart.toContainText(code, { timeout })
await resetPane() await resetPane()
return result return result
} }
@ -147,20 +147,4 @@ export class EditorFixture {
openPane() { openPane() {
return openPane(this.page, this.paneButtonTestId) return openPane(this.page, this.paneButtonTestId)
} }
scrollToText(text: string) {
return this.page.evaluate((scrollToText: string) => {
// editorManager is available on the window object.
// @ts-ignore
let index = editorManager._editorView.docView.view.state.doc
.toString()
.indexOf(scrollToText)
// @ts-ignore
editorManager._editorView.dispatch({
selection: {
anchor: index,
},
scrollIntoView: true,
})
}, text)
}
} }

View File

@ -1,11 +1,11 @@
import type { import type {
BrowserContext, BrowserContext,
ElectronApplication, ElectronApplication,
TestInfo,
Page, Page,
TestInfo,
} from '@playwright/test' } from '@playwright/test'
import { test as base } from '@playwright/test'
import { getUtils, setup, setupElectron } from '../test-utils' import { getUtils, setup, setupElectron, tearDown } from '../test-utils'
import fsp from 'fs/promises' import fsp from 'fs/promises'
import { join } from 'path' import { join } from 'path'
import { CmdBarFixture } from './cmdBarFixture' import { CmdBarFixture } from './cmdBarFixture'
@ -20,11 +20,11 @@ export class AuthenticatedApp {
public readonly page: Page public readonly page: Page
public readonly context: BrowserContext public readonly context: BrowserContext
public readonly testInfo: TestInfo public readonly testInfo: TestInfo
public readonly viewPortSize = { width: 1200, height: 500 } public readonly viewPortSize = { width: 1000, height: 500 }
constructor(context: BrowserContext, page: Page, testInfo: TestInfo) { constructor(context: BrowserContext, page: Page, testInfo: TestInfo) {
this.context = context
this.page = page this.page = page
this.context = context
this.testInfo = testInfo this.testInfo = testInfo
} }
@ -49,7 +49,9 @@ export class AuthenticatedApp {
} }
} }
export interface Fixtures { interface Fixtures {
app: AuthenticatedApp
tronApp: AuthenticatedTronApp
cmdBar: CmdBarFixture cmdBar: CmdBarFixture
editor: EditorFixture editor: EditorFixture
toolbar: ToolbarFixture toolbar: ToolbarFixture
@ -59,11 +61,9 @@ export interface Fixtures {
export class AuthenticatedTronApp { export class AuthenticatedTronApp {
public readonly _page: Page public readonly _page: Page
public page: Page public page: Page
public context: BrowserContext public readonly context: BrowserContext
public readonly testInfo: TestInfo public readonly testInfo: TestInfo
public electronApp?: ElectronApplication public electronApp?: ElectronApplication
public readonly viewPortSize = { width: 1200, height: 500 }
public dir: string = ''
constructor(context: BrowserContext, page: Page, testInfo: TestInfo) { constructor(context: BrowserContext, page: Page, testInfo: TestInfo) {
this._page = page this._page = page
@ -79,22 +79,15 @@ export class AuthenticatedTronApp {
appSettings?: Partial<SaveSettingsPayload> appSettings?: Partial<SaveSettingsPayload>
} = { fixtures: {} } } = { fixtures: {} }
) { ) {
const { electronApp, page, context, dir, options } = await setupElectron({ const { electronApp, page } = await setupElectron({
testInfo: this.testInfo, testInfo: this.testInfo,
folderSetupFn: arg.folderSetupFn, folderSetupFn: arg.folderSetupFn,
cleanProjectDir: arg.cleanProjectDir, cleanProjectDir: arg.cleanProjectDir,
appSettings: arg.appSettings, appSettings: arg.appSettings,
}) })
this.page = page this.page = page
this.context = context
this.electronApp = electronApp this.electronApp = electronApp
this.dir = dir await page.setViewportSize({ width: 1200, height: 500 })
// Easier to access throughout utils
this.page.dir = dir
// Setup localStorage, addCookies, reload
await setup(this.context, this.page, this.testInfo)
for (const key of unsafeTypedKeys(arg.fixtures)) { for (const key of unsafeTypedKeys(arg.fixtures)) {
const fixture = arg.fixtures[key] const fixture = arg.fixtures[key]
@ -117,20 +110,32 @@ export class AuthenticatedTronApp {
}) })
} }
export const fixtures = { export const test = base.extend<Fixtures>({
cmdBar: async ({ page }: { page: Page }, use: any) => { app: async ({ page, context }, use, testInfo) => {
await use(new AuthenticatedApp(context, page, testInfo))
},
tronApp: async ({ page, context }, use, testInfo) => {
await use(new AuthenticatedTronApp(context, page, testInfo))
},
cmdBar: async ({ page }, use) => {
await use(new CmdBarFixture(page)) await use(new CmdBarFixture(page))
}, },
editor: async ({ page }: { page: Page }, use: any) => { editor: async ({ page }, use) => {
await use(new EditorFixture(page)) await use(new EditorFixture(page))
}, },
toolbar: async ({ page }: { page: Page }, use: any) => { toolbar: async ({ page }, use) => {
await use(new ToolbarFixture(page)) await use(new ToolbarFixture(page))
}, },
scene: async ({ page }: { page: Page }, use: any) => { scene: async ({ page }, use) => {
await use(new SceneFixture(page)) await use(new SceneFixture(page))
}, },
homePage: async ({ page }: { page: Page }, use: any) => { homePage: async ({ page }, use) => {
await use(new HomePageFixture(page)) await use(new HomePageFixture(page))
}, },
} })
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
export { expect } from '@playwright/test'

View File

@ -14,14 +14,10 @@ interface HomePageState {
export class HomePageFixture { export class HomePageFixture {
public page: Page public page: Page
projectSection!: Locator
projectCard!: Locator projectCard!: Locator
projectCardTitle!: Locator projectCardTitle!: Locator
projectCardFile!: Locator projectCardFile!: Locator
projectCardFolder!: Locator projectCardFolder!: Locator
projectButtonNew!: Locator
projectButtonContinue!: Locator
projectTextName!: Locator
sortByDateBtn!: Locator sortByDateBtn!: Locator
sortByNameBtn!: Locator sortByNameBtn!: Locator
@ -32,19 +28,11 @@ export class HomePageFixture {
reConstruct = (page: Page) => { reConstruct = (page: Page) => {
this.page = page this.page = page
this.projectSection = this.page.getByTestId('home-section')
this.projectCard = this.page.getByTestId('project-link') this.projectCard = this.page.getByTestId('project-link')
this.projectCardTitle = this.page.getByTestId('project-title') this.projectCardTitle = this.page.getByTestId('project-title')
this.projectCardFile = this.page.getByTestId('project-file-count') this.projectCardFile = this.page.getByTestId('project-file-count')
this.projectCardFolder = this.page.getByTestId('project-folder-count') this.projectCardFolder = this.page.getByTestId('project-folder-count')
this.projectButtonNew = this.page.getByTestId('home-new-file')
this.projectTextName = this.page.getByTestId('cmd-bar-arg-value')
this.projectButtonContinue = this.page.getByRole('button', {
name: 'Continue',
})
this.sortByDateBtn = this.page.getByTestId('home-sort-by-modified') this.sortByDateBtn = this.page.getByTestId('home-sort-by-modified')
this.sortByNameBtn = this.page.getByTestId('home-sort-by-name') this.sortByNameBtn = this.page.getByTestId('home-sort-by-name')
} }
@ -103,25 +91,10 @@ export class HomePageFixture {
.toEqual(expectedState) .toEqual(expectedState)
} }
createAndGoToProject = async (projectTitle: string) => {
await expect(this.projectSection).not.toHaveText('Loading your Projects...')
await this.projectButtonNew.click()
await this.projectTextName.click()
await this.projectTextName.fill(projectTitle)
await this.projectButtonContinue.click()
}
openProject = async (projectTitle: string) => { openProject = async (projectTitle: string) => {
const projectCard = this.projectCard.locator( const projectCard = this.projectCard.locator(
this.page.getByText(projectTitle) this.page.getByText(projectTitle)
) )
await projectCard.click() await projectCard.click()
} }
goToModelingScene = async (name: string = 'testDefault') => {
// On web this is a no-op. There is no project view.
if (process.env.PLATFORM === 'web') return
await this.createAndGoToProject(name)
}
} }

View File

@ -53,9 +53,8 @@ export class SceneFixture {
expectState = async (expected: SceneSerialised) => { expectState = async (expected: SceneSerialised) => {
return expect return expect
.poll(async () => await this._serialiseScene(), { .poll(() => this._serialiseScene(), {
intervals: [1_000, 2_000, 10_000], message: `Expected scene state to match`,
timeout: 60000,
}) })
.toEqual(expected) .toEqual(expected)
} }
@ -188,10 +187,7 @@ export class SceneFixture {
type: 'default_camera_get_settings', type: 'default_camera_get_settings',
}, },
}) })
await this.page await this.waitForExecutionDone()
.locator(`[data-receive-command-type="default_camera_get_settings"]`)
.first()
.waitFor()
const position = await Promise.all([ const position = await Promise.all([
this.page.getByTestId('cam-x-position').inputValue().then(Number), this.page.getByTestId('cam-x-position').inputValue().then(Number),
this.page.getByTestId('cam-y-position').inputValue().then(Number), this.page.getByTestId('cam-y-position').inputValue().then(Number),
@ -242,7 +238,6 @@ export class SceneFixture {
} }
async clickGizmoMenuItem(name: string) { async clickGizmoMenuItem(name: string) {
await this.gizmo.hover()
await this.gizmo.click({ button: 'right' }) await this.gizmo.click({ button: 'right' })
const buttonToTest = this.page.getByRole('button', { const buttonToTest = this.page.getByRole('button', {
name: name, name: name,

View File

@ -1,5 +1,5 @@
import type { Page, Locator } from '@playwright/test' import type { Page, Locator } from '@playwright/test'
import { expect } from '../zoo-test' import { expect } from './fixtureSetup'
import { doAndWaitForImageDiff } from '../test-utils' import { doAndWaitForImageDiff } from '../test-utils'
export class ToolbarFixture { export class ToolbarFixture {

View File

@ -1,22 +1,29 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { executorInputPath } from './test-utils' import { setupElectron, tearDown, executorInputPath } from './test-utils'
import { join } from 'path' import { join } from 'path'
import fsp from 'fs/promises' import fsp from 'fs/promises'
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test( test(
'When machine-api server not found butt is disabled and shows the reason', 'When machine-api server not found butt is disabled and shows the reason',
{ tag: '@electron' }, { tag: '@electron' },
async ({ context, page }, testInfo) => { async ({ browserName }, testInfo) => {
await context.folderSetupFn(async (dir) => { const { electronApp, page } = await setupElectron({
const bracketDir = join(dir, 'bracket') testInfo,
await fsp.mkdir(bracketDir, { recursive: true }) folderSetupFn: async (dir) => {
await fsp.copyFile( const bracketDir = join(dir, 'bracket')
executorInputPath('focusrite_scarlett_mounting_braket.kcl'), await fsp.mkdir(bracketDir, { recursive: true })
join(bracketDir, 'main.kcl') await fsp.copyFile(
) executorInputPath('focusrite_scarlett_mounting_braket.kcl'),
join(bracketDir, 'main.kcl')
)
},
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await expect(page.getByText('bracket')).toBeVisible() await expect(page.getByText('bracket')).toBeVisible()
@ -40,23 +47,28 @@ test(
// that the machine-api server is not found // that the machine-api server is not found
await makeButton.hover() await makeButton.hover()
await expect(page.getByText(notFoundText).first()).toBeVisible() await expect(page.getByText(notFoundText).first()).toBeVisible()
await electronApp.close()
} }
) )
test( test(
'When machine-api server not found home screen & project status shows the reason', 'When machine-api server not found home screen & project status shows the reason',
{ tag: '@electron' }, { tag: '@electron' },
async ({ context, page }, testInfo) => { async ({ browserName }, testInfo) => {
await context.folderSetupFn(async (dir) => { const { electronApp, page } = await setupElectron({
const bracketDir = join(dir, 'bracket') testInfo,
await fsp.mkdir(bracketDir, { recursive: true }) folderSetupFn: async (dir) => {
await fsp.copyFile( const bracketDir = join(dir, 'bracket')
executorInputPath('focusrite_scarlett_mounting_braket.kcl'), await fsp.mkdir(bracketDir, { recursive: true })
join(bracketDir, 'main.kcl') await fsp.copyFile(
) executorInputPath('focusrite_scarlett_mounting_braket.kcl'),
join(bracketDir, 'main.kcl')
)
},
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
const notFoundText = 'Machine API server was not discovered' const notFoundText = 'Machine API server was not discovered'
@ -79,5 +91,7 @@ test(
await networkMachineToggle.hover() await networkMachineToggle.hover()
await expect(page.getByText(notFoundText).nth(1)).toBeVisible() await expect(page.getByText(notFoundText).nth(1)).toBeVisible()
await electronApp.close()
} }
) )

View File

@ -1,12 +0,0 @@
// These tests are meant to simply test starting and stopping the electron
// application, check it can make it to the project pane, and nothing more.
// It also tests our test wrappers are working.
// Additionally this serves as a nice minimal example.
import { test, expect } from './zoo-test'
test.describe('Open the application', () => {
test('see the project view', async ({ page, context }) => {
await expect(page.getByTestId('home-section')).toBeVisible()
})
})

View File

@ -1,63 +1,79 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { join } from 'path' import { join } from 'path'
import fsp from 'fs/promises' import fsp from 'fs/promises'
import { getUtils, executorInputPath, createProject } from './test-utils' import {
getUtils,
setup,
setupElectron,
tearDown,
executorInputPath,
createProject,
} from './test-utils'
import { bracket } from 'lib/exampleKcl' import { bracket } from 'lib/exampleKcl'
import { onboardingPaths } from 'routes/Onboarding/paths' import { onboardingPaths } from 'routes/Onboarding/paths'
import { import {
TEST_SETTINGS_KEY, TEST_SETTINGS_KEY,
TEST_SETTINGS_ONBOARDING_START, TEST_SETTINGS_ONBOARDING_START,
TEST_SETTINGS_ONBOARDING_EXPORT, TEST_SETTINGS_ONBOARDING_EXPORT,
TEST_SETTINGS_ONBOARDING_PARAMETRIC_MODELING,
TEST_SETTINGS_ONBOARDING_USER_MENU, TEST_SETTINGS_ONBOARDING_USER_MENU,
} from './storageStates' } from './storageStates'
import * as TOML from '@iarna/toml' import * as TOML from '@iarna/toml'
// Because onboarding relies on an app setting we need to set it as incompletel test.beforeEach(async ({ context, page }, testInfo) => {
// for all these tests. if (testInfo.tags.includes('@electron')) {
return
}
await setup(context, page)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Onboarding tests', () => { test.describe('Onboarding tests', () => {
test( test('Onboarding code is shown in the editor', async ({ page }) => {
'Onboarding code is shown in the editor', const u = await getUtils(page)
{
appSettings: { // Override beforeEach test setup
app: { await page.addInitScript(
onboardingStatus: 'incomplete', async ({ settingsKey }) => {
}, // Give no initial code, so that the onboarding start is shown immediately
localStorage.removeItem('persistCode')
localStorage.removeItem(settingsKey)
}, },
cleanProjectDir: true, { settingsKey: TEST_SETTINGS_KEY }
}, )
async ({ context, page, homePage }) => {
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene()
// Test that the onboarding pane loaded await page.setViewportSize({ width: 1200, height: 500 })
await expect(
page.getByText('Welcome to Modeling App! This')
).toBeVisible()
// *and* that the code is shown in the editor await u.waitForAuthSkipAppStart()
await expect(page.locator('.cm-content')).toContainText(
'// Shelf Bracket' // Test that the onboarding pane loaded
) await expect(page.getByText('Welcome to Modeling App! This')).toBeVisible()
}
) // *and* that the code is shown in the editor
await expect(page.locator('.cm-content')).toContainText('// Shelf Bracket')
})
test( test(
'Desktop: fresh onboarding executes and loads', 'Desktop: fresh onboarding executes and loads',
{ { tag: '@electron' },
tag: '@electron', async ({ browserName: _ }, testInfo) => {
appSettings: { const { electronApp, page } = await setupElectron({
app: { testInfo,
onboardingStatus: 'incomplete', appSettings: {
app: {
onboardingStatus: 'incomplete',
},
}, },
}, cleanProjectDir: true,
cleanProjectDir: true, })
},
async ({ page, homePage }, testInfo) => {
const u = await getUtils(page) const u = await getUtils(page)
const viewportSize = { width: 1200, height: 500 } const viewportSize = { width: 1200, height: 500 }
await page.setBodyDimensions(viewportSize) await page.setViewportSize(viewportSize)
await test.step(`Create a project and open to the onboarding`, async () => { await test.step(`Create a project and open to the onboarding`, async () => {
await createProject({ name: 'project-link', page }) await createProject({ name: 'project-link', page })
@ -77,361 +93,320 @@ test.describe('Onboarding tests', () => {
'// Shelf Bracket' '// Shelf Bracket'
) )
}) })
await electronApp.close()
} }
) )
test( test('Code resets after confirmation', async ({ page }) => {
'Code resets after confirmation', const initialCode = `sketch001 = startSketchOn('XZ')`
{
appSettings: {
app: {
onboardingStatus: 'incomplete',
},
},
cleanProjectDir: true,
},
async ({ context, page, homePage }) => {
const initialCode = `sketch001 = startSketchOn('XZ')`
// Load the page up with some code so we see the confirmation warning // Load the page up with some code so we see the confirmation warning
// when we go to replay onboarding // when we go to replay onboarding
await context.addInitScript((code) => { await page.addInitScript((code) => {
localStorage.setItem('persistCode', code) localStorage.setItem('persistCode', code)
}, initialCode) }, initialCode)
await page.setBodyDimensions({ width: 1200, height: 500 }) const u = await getUtils(page)
await homePage.goToModelingScene() await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
// Replay the onboarding // Replay the onboarding
await page.getByRole('link', { name: 'Settings' }).last().click() await page.getByRole('link', { name: 'Settings' }).last().click()
const replayButton = page.getByRole('button', { const replayButton = page.getByRole('button', { name: 'Replay onboarding' })
name: 'Replay onboarding', await expect(replayButton).toBeVisible()
await replayButton.click()
// Ensure we see the warning, and that the code has not yet updated
await expect(
page.getByText('Replaying onboarding resets your code')
).toBeVisible()
await expect(page.locator('.cm-content')).toHaveText(initialCode)
const nextButton = page.getByTestId('onboarding-next')
await expect(nextButton).toBeVisible()
await nextButton.click()
// Ensure we see the introduction and that the code has been reset
await expect(page.getByText('Welcome to Modeling App!')).toBeVisible()
await expect(page.locator('.cm-content')).toContainText('// Shelf Bracket')
// Ensure we persisted the code to local storage.
// Playwright's addInitScript method unfortunately will reset
// this code if we try reloading the page as a test,
// so this is our best way to test persistence afaik.
expect(
await page.evaluate(() => {
return localStorage.getItem('persistCode')
}) })
await expect(replayButton).toBeVisible() ).toContain('// Shelf Bracket')
await replayButton.click() })
// Ensure we see the warning, and that the code has not yet updated test('Click through each onboarding step', async ({ page }) => {
await expect(page.getByText('Would you like to create')).toBeVisible() const u = await getUtils(page)
await expect(page.locator('.cm-content')).toHaveText(initialCode)
const nextButton = page.getByTestId('onboarding-next') // Override beforeEach test setup
await nextButton.hover() await page.addInitScript(
await nextButton.click() async ({ settingsKey, settings }) => {
// Give no initial code, so that the onboarding start is shown immediately
// Ensure we see the introduction and that the code has been reset localStorage.setItem('persistCode', '')
await expect(page.getByText('Welcome to Modeling App!')).toBeVisible() localStorage.setItem(settingsKey, settings)
await expect(page.locator('.cm-content')).toContainText(
'// Shelf Bracket'
)
// There used to be old code here that checked if we stored the reset
// code into localStorage but that isnt the case on desktop. It gets
// saved to the file system, which we have other tests for.
}
)
test(
'Click through each onboarding step',
{
appSettings: {
app: {
onboardingStatus: 'incomplete',
},
}, },
}, {
async ({ context, page, homePage }) => { settingsKey: TEST_SETTINGS_KEY,
// Override beforeEach test setup settings: TOML.stringify({ settings: TEST_SETTINGS_ONBOARDING_START }),
await context.addInitScript(
async ({ settingsKey, settings }) => {
// Give no initial code, so that the onboarding start is shown immediately
localStorage.setItem('persistCode', '')
localStorage.setItem(settingsKey, settings)
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_START,
}),
}
)
await page.setBodyDimensions({ width: 1200, height: 1080 })
await homePage.goToModelingScene()
// Test that the onboarding pane loaded
await expect(
page.getByText('Welcome to Modeling App! This')
).toBeVisible()
const nextButton = page.getByTestId('onboarding-next')
while ((await nextButton.innerText()) !== 'Finish') {
await nextButton.hover()
await nextButton.click()
} }
)
// Finish the onboarding await page.setViewportSize({ width: 1200, height: 1080 })
await nextButton.hover()
await u.waitForAuthSkipAppStart()
// Test that the onboarding pane loaded
await expect(page.getByText('Welcome to Modeling App! This')).toBeVisible()
const nextButton = page.getByTestId('onboarding-next')
while ((await nextButton.innerText()) !== 'Finish') {
await expect(nextButton).toBeVisible()
await nextButton.click() await nextButton.click()
// Test that the onboarding pane is gone
await expect(page.getByTestId('onboarding-content')).not.toBeVisible()
await expect.poll(() => page.url()).not.toContain('/onboarding')
} }
)
test( // Finish the onboarding
'Onboarding redirects and code updating', await expect(nextButton).toBeVisible()
{ await nextButton.click()
appSettings: {
app: { // Test that the onboarding pane is gone
onboardingStatus: '/export', await expect(page.getByTestId('onboarding-content')).not.toBeVisible()
}, await expect(page.url()).not.toContain('onboarding')
})
test('Onboarding redirects and code updating', async ({ page }) => {
const u = await getUtils(page)
// Override beforeEach test setup
await page.addInitScript(
async ({ settingsKey, settings }) => {
// Give some initial code, so we can test that it's cleared
localStorage.setItem('persistCode', 'sigmaAllow = 15000')
localStorage.setItem(settingsKey, settings)
}, },
cleanProjectDir: true, {
}, settingsKey: TEST_SETTINGS_KEY,
async ({ context, page, homePage }) => { settings: TOML.stringify({ settings: TEST_SETTINGS_ONBOARDING_EXPORT }),
const originalCode = 'sigmaAllow = 15000'
// Override beforeEach test setup
await context.addInitScript(
async ({ settingsKey, settings }) => {
// Give some initial code, so we can test that it's cleared
localStorage.setItem('persistCode', originalCode)
localStorage.setItem(settingsKey, settings)
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_EXPORT,
}),
}
)
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene()
// Test that the redirect happened
await expect.poll(() => page.url()).toContain('/onboarding/export')
// Test that you come back to this page when you refresh
await page.reload()
await expect.poll(() => page.url()).toContain('/onboarding/export')
// Test that the code changes when you advance to the next step
await page.getByTestId('onboarding-next').hover()
await page.getByTestId('onboarding-next').click()
// Test that the onboarding pane loaded
const title = page.locator('[data-testid="onboarding-content"]')
await expect(title).toBeAttached()
await expect(page.locator('.cm-content')).not.toHaveText(originalCode)
// Test that the code is not empty when you click on the next step
await page.locator('[data-testid="onboarding-next"]').hover()
await page.locator('[data-testid="onboarding-next"]').click()
await expect(page.locator('.cm-content')).toHaveText(/.+/)
}
)
test(
'Onboarding code gets reset to demo on Interactive Numbers step',
{
appSettings: {
app: {
onboardingStatus: '/parametric-modeling',
},
},
cleanProjectDir: true,
},
async ({ context, page, homePage }) => {
const u = await getUtils(page)
const badCode = `// This is bad code we shouldn't see`
await page.setBodyDimensions({ width: 1200, height: 1080 })
await homePage.goToModelingScene()
await expect
.poll(() => page.url())
.toContain(onboardingPaths.PARAMETRIC_MODELING)
const bracketNoNewLines = bracket.replace(/\n/g, '')
// Check the code got reset on load
await expect(page.locator('#code-pane')).toBeVisible()
await expect(u.codeLocator).toHaveText(bracketNoNewLines, {
timeout: 10_000,
})
// Mess with the code again
await u.codeLocator.selectText()
await u.codeLocator.fill(badCode)
await expect(u.codeLocator).toHaveText(badCode)
// Click to the next step
await page.locator('[data-testid="onboarding-next"]').hover()
await page.locator('[data-testid="onboarding-next"]').click()
await page.waitForURL('**' + onboardingPaths.INTERACTIVE_NUMBERS, {
waitUntil: 'domcontentloaded',
})
// Check that the code has been reset
await expect(u.codeLocator).toHaveText(bracketNoNewLines)
}
)
// (lee) The two avatar tests are weird because even on main, we don't have
// anything to do with the avatar inside the onboarding test. Due to the
// low impact of an avatar not showing I'm changing this to fixme.
test.fixme(
'Avatar text updates depending on image load success',
{
appSettings: {
app: {
onboardingStatus: 'incomplete',
},
},
cleanProjectDir: true,
},
async ({ context, page, homePage }) => {
// Override beforeEach test setup
await context.addInitScript(
async ({ settingsKey, settings }) => {
localStorage.setItem(settingsKey, settings)
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_USER_MENU,
}),
}
)
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene()
// Test that the text in this step is correct
const avatarLocator = await page
.getByTestId('user-sidebar-toggle')
.locator('img')
const onboardingOverlayLocator = await page
.getByTestId('onboarding-content')
.locator('div')
.nth(1)
// Expect the avatar to be visible and for the text to reference it
await expect(avatarLocator).toBeVisible()
await expect(onboardingOverlayLocator).toBeVisible()
await expect(onboardingOverlayLocator).toContainText('your avatar')
// This is to force the avatar to 404.
// For our test image (only triggers locally. on CI, it's Kurt's /
// gravatar image )
await page.route('/cat.jpg', async (route) => {
await route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!',
})
})
// 404 the CI avatar image
await page.route(
'https://lh3.googleusercontent.com/**',
async (route) => {
await route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!',
})
}
)
await page.reload({ waitUntil: 'domcontentloaded' })
// Now expect the text to be different
await expect(avatarLocator).not.toBeVisible()
await expect(onboardingOverlayLocator).toBeVisible()
await expect(onboardingOverlayLocator).toContainText('the menu button')
}
)
test.fixme(
"Avatar text doesn't mention avatar when no avatar",
{
appSettings: {
app: {
onboardingStatus: 'incomplete',
},
},
cleanProjectDir: true,
},
async ({ context, page, homePage }) => {
// Override beforeEach test setup
await context.addInitScript(
async ({ settingsKey, settings }) => {
localStorage.setItem(settingsKey, settings)
localStorage.setItem('FORCE_NO_IMAGE', 'FORCE_NO_IMAGE')
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_USER_MENU,
}),
}
)
await page.setBodyDimensions({ width: 1200, height: 500 })
await homePage.goToModelingScene()
// Test that the text in this step is correct
const sidebar = page.getByTestId('user-sidebar-toggle')
const avatar = sidebar.locator('img')
const onboardingOverlayLocator = page
.getByTestId('onboarding-content')
.locator('div')
.nth(1)
// Expect the avatar to be visible and for the text to reference it
await expect(avatar).not.toBeVisible()
await expect(onboardingOverlayLocator).toBeVisible()
await expect(onboardingOverlayLocator).toContainText('the menu button')
// Test we mention what else is in this menu for https://github.com/KittyCAD/modeling-app/issues/2939
// which doesn't deserver its own full test spun up
const userMenuFeatures = [
'manage your account',
'report a bug',
'request a feature',
'sign out',
]
for (const feature of userMenuFeatures) {
await expect(onboardingOverlayLocator).toContainText(feature)
} }
)
await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
// Test that the redirect happened
await expect(page.url().split(':3000').slice(-1)[0]).toBe(
`/file/%2Fbrowser%2Fmain.kcl/onboarding/export`
)
// Test that you come back to this page when you refresh
await page.reload()
await expect(page.url().split(':3000').slice(-1)[0]).toBe(
`/file/%2Fbrowser%2Fmain.kcl/onboarding/export`
)
// Test that the onboarding pane loaded
const title = page.locator('[data-testid="onboarding-content"]')
await expect(title).toBeAttached()
// Test that the code changes when you advance to the next step
await page.locator('[data-testid="onboarding-next"]').click()
await expect(page.locator('.cm-content')).toHaveText('')
// Test that the code is not empty when you click on the next step
await page.locator('[data-testid="onboarding-next"]').click()
await expect(page.locator('.cm-content')).toHaveText(/.+/)
})
test('Onboarding code gets reset to demo on Interactive Numbers step', async ({
page,
}) => {
test.skip(
process.platform === 'darwin',
"Skip on macOS, because Playwright isn't behaving the same as the actual browser"
)
const u = await getUtils(page)
const badCode = `// This is bad code we shouldn't see`
// Override beforeEach test setup
await page.addInitScript(
async ({ settingsKey, settings, badCode }) => {
localStorage.setItem('persistCode', badCode)
localStorage.setItem(settingsKey, settings)
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_PARAMETRIC_MODELING,
}),
badCode,
}
)
await page.setViewportSize({ width: 1200, height: 1080 })
await u.waitForAuthSkipAppStart()
await page.waitForURL('**' + onboardingPaths.PARAMETRIC_MODELING, {
waitUntil: 'domcontentloaded',
})
const bracketNoNewLines = bracket.replace(/\n/g, '')
// Check the code got reset on load
await expect(page.locator('#code-pane')).toBeVisible()
await expect(u.codeLocator).toHaveText(bracketNoNewLines, {
timeout: 10_000,
})
// Mess with the code again
await u.codeLocator.selectText()
await u.codeLocator.fill(badCode)
await expect(u.codeLocator).toHaveText(badCode)
// Click to the next step
await page.locator('[data-testid="onboarding-next"]').click()
await page.waitForURL('**' + onboardingPaths.INTERACTIVE_NUMBERS, {
waitUntil: 'domcontentloaded',
})
// Check that the code has been reset
await expect(u.codeLocator).toHaveText(bracketNoNewLines)
})
test('Avatar text updates depending on image load success', async ({
page,
}) => {
// Override beforeEach test setup
await page.addInitScript(
async ({ settingsKey, settings }) => {
localStorage.setItem(settingsKey, settings)
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_USER_MENU,
}),
}
)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
await page.waitForURL('**/file/**', { waitUntil: 'domcontentloaded' })
// Test that the text in this step is correct
const avatarLocator = await page
.getByTestId('user-sidebar-toggle')
.locator('img')
const onboardingOverlayLocator = await page
.getByTestId('onboarding-content')
.locator('div')
.nth(1)
// Expect the avatar to be visible and for the text to reference it
await expect(avatarLocator).toBeVisible()
await expect(onboardingOverlayLocator).toBeVisible()
await expect(onboardingOverlayLocator).toContainText('your avatar')
// This is to force the avatar to 404.
// For our test image (only triggers locally. on CI, it's Kurt's /
// gravatar image )
await page.route('/cat.jpg', async (route) => {
await route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!',
})
})
// 404 the CI avatar image
await page.route('https://lh3.googleusercontent.com/**', async (route) => {
await route.fulfill({
status: 404,
contentType: 'text/plain',
body: 'Not Found!',
})
})
await page.reload({ waitUntil: 'domcontentloaded' })
// Now expect the text to be different
await expect(avatarLocator).not.toBeVisible()
await expect(onboardingOverlayLocator).toBeVisible()
await expect(onboardingOverlayLocator).toContainText('the menu button')
})
test("Avatar text doesn't mention avatar when no avatar", async ({
page,
}) => {
// Override beforeEach test setup
await page.addInitScript(
async ({ settingsKey, settings }) => {
localStorage.setItem(settingsKey, settings)
localStorage.setItem('FORCE_NO_IMAGE', 'FORCE_NO_IMAGE')
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: TEST_SETTINGS_ONBOARDING_USER_MENU,
}),
}
)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
await page.waitForURL('**/file/**', { waitUntil: 'domcontentloaded' })
// Test that the text in this step is correct
const sidebar = page.getByTestId('user-sidebar-toggle')
const avatar = sidebar.locator('img')
const onboardingOverlayLocator = page
.getByTestId('onboarding-content')
.locator('div')
.nth(1)
// Expect the avatar to be visible and for the text to reference it
await expect(avatar).not.toBeVisible()
await expect(onboardingOverlayLocator).toBeVisible()
await expect(onboardingOverlayLocator).toContainText('the menu button')
// Test we mention what else is in this menu for https://github.com/KittyCAD/modeling-app/issues/2939
// which doesn't deserver its own full test spun up
const userMenuFeatures = [
'manage your account',
'report a bug',
'request a feature',
'sign out',
]
for (const feature of userMenuFeatures) {
await expect(onboardingOverlayLocator).toContainText(feature)
} }
) })
}) })
test( test(
'Restarting onboarding on desktop takes one attempt', 'Restarting onboarding on desktop takes one attempt',
{ { tag: '@electron' },
appSettings: { async ({ browser: _ }, testInfo) => {
app: { const { electronApp, page } = await setupElectron({
onboardingStatus: 'dismissed', testInfo,
folderSetupFn: async (dir) => {
const routerTemplateDir = join(dir, 'router-template-slate')
await fsp.mkdir(routerTemplateDir, { recursive: true })
await fsp.copyFile(
executorInputPath('router-template-slate.kcl'),
join(routerTemplateDir, 'main.kcl')
)
}, },
},
cleanProjectDir: true,
},
async ({ context, page, homePage }, testInfo) => {
await context.folderSetupFn(async (dir) => {
const routerTemplateDir = join(dir, 'router-template-slate')
await fsp.mkdir(routerTemplateDir, { recursive: true })
await fsp.copyFile(
executorInputPath('router-template-slate.kcl'),
join(routerTemplateDir, 'main.kcl')
)
}) })
// Our constants // Our constants
@ -443,8 +418,9 @@ test(
const restartOnboardingButton = page.getByRole('button', { const restartOnboardingButton = page.getByRole('button', {
name: 'Reset onboarding', name: 'Reset onboarding',
}) })
const nextButton = page.getByTestId('onboarding-next') const restartConfirmationButton = page.getByRole('button', {
name: 'Make a new project',
})
const tutorialProjectIndicator = page const tutorialProjectIndicator = page
.getByTestId('project-sidebar-toggle') .getByTestId('project-sidebar-toggle')
.filter({ hasText: 'Tutorial Project 00' }) .filter({ hasText: 'Tutorial Project 00' })
@ -463,7 +439,7 @@ test(
}) })
await test.step('Navigate into project', async () => { await test.step('Navigate into project', async () => {
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
page.on('console', console.log) page.on('console', console.log)
@ -479,8 +455,8 @@ test(
await helpMenuButton.click() await helpMenuButton.click()
await restartOnboardingButton.click() await restartOnboardingButton.click()
await nextButton.hover() await expect(restartConfirmationButton).toBeVisible()
await nextButton.click() await restartConfirmationButton.click()
}) })
await test.step('Confirm that the onboarding has restarted', async () => { await test.step('Confirm that the onboarding has restarted', async () => {
@ -504,9 +480,11 @@ test(
await restartOnboardingSettingsButton.click() await restartOnboardingSettingsButton.click()
// Since the code is empty, we should not see the confirmation dialog // Since the code is empty, we should not see the confirmation dialog
await expect(nextButton).not.toBeVisible() await expect(restartConfirmationButton).not.toBeVisible()
await expect(tutorialProjectIndicator).toBeVisible() await expect(tutorialProjectIndicator).toBeVisible()
await expect(tutorialModalText).toBeVisible() await expect(tutorialModalText).toBeVisible()
}) })
await electronApp.close()
} }
) )

View File

@ -1,49 +1,25 @@
import { test, expect, Page } from './zoo-test' import { test, expect, AuthenticatedApp } from './fixtures/fixtureSetup'
import { EditorFixture } from './fixtures/editorFixture' import { EditorFixture } from './fixtures/editorFixture'
import { SceneFixture } from './fixtures/sceneFixture' import { SceneFixture } from './fixtures/sceneFixture'
import { ToolbarFixture } from './fixtures/toolbarFixture' import { ToolbarFixture } from './fixtures/toolbarFixture'
import fs from 'node:fs/promises'
import path from 'node:path'
import { getUtils } from './test-utils'
// test file is for testing point an click code gen functionality that's not sketch mode related // test file is for testing point an click code gen functionality that's not sketch mode related
test('verify extruding circle works', async ({ test(
context, 'verify extruding circle works',
homePage, { tag: ['@skipWin'] },
cmdBar, async ({ app, cmdBar, editor, toolbar, scene }) => {
editor, test.skip(
toolbar, process.platform === 'win32',
scene, 'Fails on windows in CI, can not be replicated locally on windows.'
}) => { )
const file = await fs.readFile( const file = await app.getInputFile('test-circle-extrude.kcl')
path.resolve( await app.initialise(file)
__dirname, const [clickCircle, moveToCircle] = scene.makeMouseHelpers(582, 217)
'../../',
'./src/wasm-lib/tests/executor/inputs/test-circle-extrude.kcl'
),
'utf-8'
)
await context.addInitScript((file) => {
localStorage.setItem('persistCode', file)
}, file)
await homePage.goToModelingScene()
const [clickCircle, moveToCircle] = scene.makeMouseHelpers(582, 217) await test.step('because there is sweepable geometry, verify extrude is enable when nothing is selected', async () => {
await scene.clickNoWhere()
await test.step('because there is sweepable geometry, verify extrude is enable when nothing is selected', async () => { await expect(toolbar.extrudeButton).toBeEnabled()
await scene.clickNoWhere()
await expect(toolbar.extrudeButton).toBeEnabled()
})
await test.step('check code model connection works and that button is still enable once circle is selected ', async () => {
await moveToCircle()
const circleSnippet =
'circle({ center = [318.33, 168.1], radius = 182.8 }, %)'
await editor.expectState({
activeLines: ["constsketch002=startSketchOn('XZ')"],
highlightedCode: circleSnippet,
diagnostics: [],
}) })
await test.step('check code model connection works and that button is still enable once circle is selected ', async () => { await test.step('check code model connection works and that button is still enable once circle is selected ', async () => {
@ -51,7 +27,7 @@ test('verify extruding circle works', async ({
const circleSnippet = const circleSnippet =
'circle({ center = [318.33, 168.1], radius = 182.8 }, %)' 'circle({ center = [318.33, 168.1], radius = 182.8 }, %)'
await editor.expectState({ await editor.expectState({
activeLines: ["constsketch002=startSketchOn('XZ')"], activeLines: [],
highlightedCode: circleSnippet, highlightedCode: circleSnippet,
diagnostics: [], diagnostics: [],
}) })
@ -64,40 +40,39 @@ test('verify extruding circle works', async ({
}) })
await expect(toolbar.extrudeButton).toBeEnabled() await expect(toolbar.extrudeButton).toBeEnabled()
}) })
await expect(toolbar.extrudeButton).toBeEnabled()
})
await test.step('do extrude flow and check extrude code is added to editor', async () => { await test.step('do extrude flow and check extrude code is added to editor', async () => {
await toolbar.extrudeButton.click() await toolbar.extrudeButton.click()
await cmdBar.expectState({ await cmdBar.expectState({
stage: 'arguments', stage: 'arguments',
currentArgKey: 'distance', currentArgKey: 'distance',
currentArgValue: '5', currentArgValue: '5',
headerArguments: { Selection: '1 face', Distance: '' }, headerArguments: { Selection: '1 face', Distance: '' },
highlightedHeaderArg: 'distance', highlightedHeaderArg: 'distance',
commandName: 'Extrude', commandName: 'Extrude',
})
await cmdBar.progressCmdBar()
const expectString = 'extrude001 = extrude(5, sketch001)'
await editor.expectEditor.not.toContain(expectString)
await cmdBar.expectState({
stage: 'review',
headerArguments: { Selection: '1 face', Distance: '5' },
commandName: 'Extrude',
})
await cmdBar.progressCmdBar()
await editor.expectEditor.toContain(expectString)
}) })
await cmdBar.progressCmdBar() }
)
const expectString = 'extrude001 = extrude(5, sketch001)'
await editor.expectEditor.not.toContain(expectString)
await cmdBar.expectState({
stage: 'review',
headerArguments: { Selection: '1 face', Distance: '5' },
commandName: 'Extrude',
})
await cmdBar.progressCmdBar()
await editor.expectEditor.toContain(expectString)
})
})
test.describe('verify sketch on chamfer works', () => { test.describe('verify sketch on chamfer works', () => {
const _sketchOnAChamfer = const _sketchOnAChamfer =
( (
page: Page, app: AuthenticatedApp,
editor: EditorFixture, editor: EditorFixture,
toolbar: ToolbarFixture, toolbar: ToolbarFixture,
scene: SceneFixture scene: SceneFixture
@ -149,7 +124,7 @@ test.describe('verify sketch on chamfer works', () => {
await toolbar.startSketchPlaneSelection() await toolbar.startSketchPlaneSelection()
await clickChamfer() await clickChamfer()
// timeout wait for engine animation is unavoidable // timeout wait for engine animation is unavoidable
await page.waitForTimeout(1000) await app.page.waitForTimeout(600)
await editor.expectEditor.toContain(afterChamferSelectSnippet) await editor.expectEditor.toContain(afterChamferSelectSnippet)
}) })
await test.step('make sure a basic sketch can be added', async () => { await test.step('make sure a basic sketch can be added', async () => {
@ -160,9 +135,7 @@ test.describe('verify sketch on chamfer works', () => {
pixelDiff: 50, pixelDiff: 50,
}) })
await rectangle2ndClick() await rectangle2ndClick()
await editor.expectEditor.toContain(afterRectangle2ndClickSnippet, { await editor.expectEditor.toContain(afterRectangle2ndClickSnippet)
shouldNormalise: true,
})
}) })
await test.step('Clean up so that `_sketchOnAChamfer` util can be called again', async () => { await test.step('Clean up so that `_sketchOnAChamfer` util can be called again', async () => {
@ -177,35 +150,24 @@ test.describe('verify sketch on chamfer works', () => {
}) })
}) })
} }
test('works on all edge selections and can break up multi edges in a chamfer array', async ({ test(
context, 'works on all edge selections and can break up multi edges in a chamfer array',
page, { tag: ['@skipWin'] },
homePage, async ({ app, editor, toolbar, scene }) => {
editor, test.skip(
toolbar, process.platform === 'win32',
scene, 'Fails on windows in CI, can not be replicated locally on windows.'
}) => { )
const file = await fs.readFile( const file = await app.getInputFile('e2e-can-sketch-on-chamfer.kcl')
path.resolve( await app.initialise(file)
__dirname,
'../../',
'./src/wasm-lib/tests/executor/inputs/e2e-can-sketch-on-chamfer.kcl'
),
'utf-8'
)
await context.addInitScript((file) => {
localStorage.setItem('persistCode', file)
}, file)
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
const sketchOnAChamfer = _sketchOnAChamfer(page, editor, toolbar, scene) const sketchOnAChamfer = _sketchOnAChamfer(app, editor, toolbar, scene)
await sketchOnAChamfer({ await sketchOnAChamfer({
clickCoords: { x: 570, y: 220 }, clickCoords: { x: 570, y: 220 },
cameraPos: { x: 16020, y: -2000, z: 10500 }, cameraPos: { x: 16020, y: -2000, z: 10500 },
cameraTarget: { x: -150, y: -4500, z: -80 }, cameraTarget: { x: -150, y: -4500, z: -80 },
beforeChamferSnippet: `angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01) beforeChamferSnippet: `angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)
chamfer({length = 30,tags = [ chamfer({length = 30,tags = [
seg01, seg01,
getNextAdjacentEdge(yo), getNextAdjacentEdge(yo),
@ -213,9 +175,10 @@ test.describe('verify sketch on chamfer works', () => {
getOppositeEdge(seg01) getOppositeEdge(seg01)
]}, %)`, ]}, %)`,
afterChamferSelectSnippet: 'sketch002 = startSketchOn(extrude001, seg03)', afterChamferSelectSnippet:
afterRectangle1stClickSnippet: 'startProfileAt([205.96, 254.59], %)', 'sketch002 = startSketchOn(extrude001, seg03)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.39], %, $rectangleSegmentA002) afterRectangle1stClickSnippet: 'startProfileAt([205.96, 254.59], %)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.39], %, $rectangleSegmentA002)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA002) - 90, segAng(rectangleSegmentA002) - 90,
105.26 105.26
@ -226,13 +189,13 @@ test.describe('verify sketch on chamfer works', () => {
], %, $rectangleSegmentC001) ], %, $rectangleSegmentC001)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)`, |> close(%)`,
}) })
await sketchOnAChamfer({ await sketchOnAChamfer({
clickCoords: { x: 690, y: 250 }, clickCoords: { x: 690, y: 250 },
cameraPos: { x: 16020, y: -2000, z: 10500 }, cameraPos: { x: 16020, y: -2000, z: 10500 },
cameraTarget: { x: -150, y: -4500, z: -80 }, cameraTarget: { x: -150, y: -4500, z: -80 },
beforeChamferSnippet: `angledLine([ beforeChamferSnippet: `angledLine([
segAng(rectangleSegmentA001) - 90, segAng(rectangleSegmentA001) - 90,
217.26 217.26
], %, $seg01)chamfer({ ], %, $seg01)chamfer({
@ -244,9 +207,10 @@ test.describe('verify sketch on chamfer works', () => {
] ]
}, %)`, }, %)`,
afterChamferSelectSnippet: 'sketch003 = startSketchOn(extrude001, seg04)', afterChamferSelectSnippet:
afterRectangle1stClickSnippet: 'startProfileAt([-209.64, 255.28], %)', 'sketch003 = startSketchOn(extrude001, seg04)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.56], %, $rectangleSegmentA003) afterRectangle1stClickSnippet: 'startProfileAt([-209.64, 255.28], %)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.56], %, $rectangleSegmentA003)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA003) - 90, segAng(rectangleSegmentA003) - 90,
106.84 106.84
@ -257,21 +221,22 @@ test.describe('verify sketch on chamfer works', () => {
], %, $rectangleSegmentC002) ], %, $rectangleSegmentC002)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)`, |> close(%)`,
}) })
await sketchOnAChamfer({ await sketchOnAChamfer({
clickCoords: { x: 677, y: 87 }, clickCoords: { x: 677, y: 87 },
cameraPos: { x: -6200, y: 1500, z: 6200 }, cameraPos: { x: -6200, y: 1500, z: 6200 },
cameraTarget: { x: 8300, y: 1100, z: 4800 }, cameraTarget: { x: 8300, y: 1100, z: 4800 },
beforeChamferSnippet: `angledLine([0, 268.43], %, $rectangleSegmentA001)chamfer({ beforeChamferSnippet: `angledLine([0, 268.43], %, $rectangleSegmentA001)chamfer({
length = 30, length = 30,
tags = [ tags = [
getNextAdjacentEdge(yo), getNextAdjacentEdge(yo),
getNextAdjacentEdge(seg02) getNextAdjacentEdge(seg02)
] ]
}, %)`, }, %)`,
afterChamferSelectSnippet: 'sketch003 = startSketchOn(extrude001, seg04)', afterChamferSelectSnippet:
afterRectangle1stClickSnippet: 'startProfileAt([75.8, 317.2], %)', 'sketch003 = startSketchOn(extrude001, seg04)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.56], %, $rectangleSegmentA003) afterRectangle1stClickSnippet: 'startProfileAt([-209.64, 255.28], %)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.56], %, $rectangleSegmentA003)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA003) - 90, segAng(rectangleSegmentA003) - 90,
106.84 106.84
@ -282,19 +247,20 @@ test.describe('verify sketch on chamfer works', () => {
], %, $rectangleSegmentC002) ], %, $rectangleSegmentC002)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)`, |> close(%)`,
}) })
/// last one /// last one
await sketchOnAChamfer({ await sketchOnAChamfer({
clickCoords: { x: 620, y: 300 }, clickCoords: { x: 620, y: 300 },
cameraPos: { x: -1100, y: -7700, z: 1600 }, cameraPos: { x: -1100, y: -7700, z: 1600 },
cameraTarget: { x: 1450, y: 670, z: 4000 }, cameraTarget: { x: 1450, y: 670, z: 4000 },
beforeChamferSnippet: `chamfer({ beforeChamferSnippet: `chamfer({
length = 30, length = 30,
tags = [getNextAdjacentEdge(yo)] tags = [getNextAdjacentEdge(yo)]
}, %)`, }, %)`,
afterChamferSelectSnippet: 'sketch005 = startSketchOn(extrude001, seg06)', afterChamferSelectSnippet:
afterRectangle1stClickSnippet: 'startProfileAt([-23.43, 19.69], %)', 'sketch005 = startSketchOn(extrude001, seg06)',
afterRectangle2ndClickSnippet: `angledLine([0, 9.1], %, $rectangleSegmentA005) afterRectangle1stClickSnippet: 'startProfileAt([-23.43, 19.69], %)',
afterRectangle2ndClickSnippet: `angledLine([0, 9.1], %, $rectangleSegmentA005)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA005) - 90, segAng(rectangleSegmentA005) - 90,
@ -306,11 +272,11 @@ test.describe('verify sketch on chamfer works', () => {
], %, $rectangleSegmentC004) ], %, $rectangleSegmentC004)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)`, |> close(%)`,
}) })
await test.step('verify at the end of the test that final code is what is expected', async () => { await test.step('verify at the end of the test that final code is what is expected', async () => {
await editor.expectEditor.toContain( await editor.expectEditor.toContain(
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([75.8, 317.2], %) // [$startCapTag, $EndCapTag] |> startProfileAt([75.8, 317.2], %) // [$startCapTag, $EndCapTag]
|> angledLine([0, 268.43], %, $rectangleSegmentA001) |> angledLine([0, 268.43], %, $rectangleSegmentA001)
@ -339,7 +305,7 @@ test.describe('verify sketch on chamfer works', () => {
tags = [getNextAdjacentEdge(yo)] tags = [getNextAdjacentEdge(yo)]
}, %, $seg06) }, %, $seg06)
sketch005 = startSketchOn(extrude001, seg06) sketch005 = startSketchOn(extrude001, seg06)
|> startProfileAt([-23.43,19.69], %) |> startProfileAt([-23.43, 19.69], %)
|> angledLine([0, 9.1], %, $rectangleSegmentA005) |> angledLine([0, 9.1], %, $rectangleSegmentA005)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA005) - 90, segAng(rectangleSegmentA005) - 90,
@ -352,7 +318,7 @@ test.describe('verify sketch on chamfer works', () => {
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
sketch004 = startSketchOn(extrude001, seg05) sketch004 = startSketchOn(extrude001, seg05)
|> startProfileAt([82.57,322.96], %) |> startProfileAt([82.57, 322.96], %)
|> angledLine([0, 11.16], %, $rectangleSegmentA004) |> angledLine([0, 11.16], %, $rectangleSegmentA004)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA004) - 90, segAng(rectangleSegmentA004) - 90,
@ -365,7 +331,7 @@ test.describe('verify sketch on chamfer works', () => {
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
sketch003 = startSketchOn(extrude001, seg04) sketch003 = startSketchOn(extrude001, seg04)
|> startProfileAt([-209.64,255.28], %) |> startProfileAt([-209.64, 255.28], %)
|> angledLine([0, 11.56], %, $rectangleSegmentA003) |> angledLine([0, 11.56], %, $rectangleSegmentA003)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA003) - 90, segAng(rectangleSegmentA003) - 90,
@ -378,7 +344,7 @@ test.describe('verify sketch on chamfer works', () => {
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
sketch002 = startSketchOn(extrude001, seg03) sketch002 = startSketchOn(extrude001, seg03)
|> startProfileAt([205.96,254.59], %) |> startProfileAt([205.96, 254.59], %)
|> angledLine([0, 11.39], %, $rectangleSegmentA002) |> angledLine([0, 11.39], %, $rectangleSegmentA002)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA002) - 90, segAng(rectangleSegmentA002) - 90,
@ -391,50 +357,43 @@ test.describe('verify sketch on chamfer works', () => {
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
`, `,
{ shouldNormalise: true } { shouldNormalise: true }
)
})
}
)
test(
'Works on chamfers that are non in a pipeExpression can break up multi edges in a chamfer array',
{ tag: ['@skipWin'] },
async ({ app, editor, toolbar, scene }) => {
test.skip(
process.platform === 'win32',
'Fails on windows in CI, can not be replicated locally on windows.'
) )
}) const file = await app.getInputFile(
}) 'e2e-can-sketch-on-chamfer-no-pipeExpr.kcl'
)
await app.initialise(file)
test('Works on chamfers that are non in a pipeExpression can break up multi edges in a chamfer array', async ({ const sketchOnAChamfer = _sketchOnAChamfer(app, editor, toolbar, scene)
context,
page,
homePage,
editor,
toolbar,
scene,
}) => {
const file = await fs.readFile(
path.resolve(
__dirname,
'../../',
'./src/wasm-lib/tests/executor/inputs/e2e-can-sketch-on-chamfer-no-pipeExpr.kcl'
),
'utf-8'
)
await context.addInitScript((file) => {
localStorage.setItem('persistCode', file)
}, file)
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
const sketchOnAChamfer = _sketchOnAChamfer(page, editor, toolbar, scene) await sketchOnAChamfer({
clickCoords: { x: 570, y: 220 },
await sketchOnAChamfer({ cameraPos: { x: 16020, y: -2000, z: 10500 },
clickCoords: { x: 570, y: 220 }, cameraTarget: { x: -150, y: -4500, z: -80 },
cameraPos: { x: 16020, y: -2000, z: 10500 }, beforeChamferSnippet: `angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)
cameraTarget: { x: -150, y: -4500, z: -80 },
beforeChamferSnippet: `angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)
chamfer({length=30,tags=[ chamfer({length=30,tags=[
seg01, seg01,
getNextAdjacentEdge(yo), getNextAdjacentEdge(yo),
getNextAdjacentEdge(seg02), getNextAdjacentEdge(seg02),
getOppositeEdge(seg01) getOppositeEdge(seg01)
]}, extrude001)`, ]}, extrude001)`,
beforeChamferSnippetEnd: '}, extrude001)', beforeChamferSnippetEnd: '}, extrude001)',
afterChamferSelectSnippet: 'sketch002 = startSketchOn(extrude001, seg03)', afterChamferSelectSnippet:
afterRectangle1stClickSnippet: 'startProfileAt([205.96, 254.59], %)', 'sketch002 = startSketchOn(extrude001, seg03)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.39], %, $rectangleSegmentA002) afterRectangle1stClickSnippet: 'startProfileAt([205.96, 254.59], %)',
afterRectangle2ndClickSnippet: `angledLine([0, 11.39], %, $rectangleSegmentA002)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA002) - 90, segAng(rectangleSegmentA002) - 90,
105.26 105.26
@ -445,9 +404,9 @@ test.describe('verify sketch on chamfer works', () => {
], %, $rectangleSegmentC001) ], %, $rectangleSegmentC001)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)`, |> close(%)`,
}) })
await editor.expectEditor.toContain( await editor.expectEditor.toContain(
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([75.8, 317.2], %) |> startProfileAt([75.8, 317.2], %)
|> angledLine([0, 268.43], %, $rectangleSegmentA001) |> angledLine([0, 268.43], %, $rectangleSegmentA001)
|> angledLine([ |> angledLine([
@ -487,56 +446,50 @@ sketch002 = startSketchOn(extrude001, seg03)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
`, `,
{ shouldNormalise: true } { shouldNormalise: true }
) )
}) }
)
}) })
test(`Verify axis, origin, and horizontal snapping`, async ({ test(`Verify axis, origin, and horizontal snapping`, async ({
page, app,
homePage,
editor, editor,
toolbar, toolbar,
scene, scene,
}) => { }) => {
const viewPortSize = { width: 1200, height: 500 }
await page.setBodyDimensions(viewPortSize)
await homePage.goToModelingScene()
// Constants and locators // Constants and locators
// These are mappings from screenspace to KCL coordinates, // These are mappings from screenspace to KCL coordinates,
// until we merge in our coordinate system helpers // until we merge in our coordinate system helpers
const xzPlane = [ const xzPlane = [
viewPortSize.width * 0.65, app.viewPortSize.width * 0.65,
viewPortSize.height * 0.3, app.viewPortSize.height * 0.3,
] as const ] as const
const originSloppy = { const originSloppy = {
screen: [ screen: [
viewPortSize.width / 2 + 3, // 3px off the center of the screen app.viewPortSize.width / 2 + 3, // 3px off the center of the screen
viewPortSize.height / 2, app.viewPortSize.height / 2,
], ],
kcl: [0, 0], kcl: [0, 0],
} as const } as const
const xAxisSloppy = { const xAxisSloppy = {
screen: [ screen: [
viewPortSize.width * 0.75, app.viewPortSize.width * 0.75,
viewPortSize.height / 2 - 3, // 3px off the X-axis app.viewPortSize.height / 2 - 3, // 3px off the X-axis
], ],
kcl: [20.34, 0], kcl: [16.95, 0],
} as const } as const
const offYAxis = { const offYAxis = {
screen: [ screen: [
viewPortSize.width * 0.6, // Well off the Y-axis, out of snapping range app.viewPortSize.width * 0.6, // Well off the Y-axis, out of snapping range
viewPortSize.height * 0.3, app.viewPortSize.height * 0.3,
], ],
kcl: [8.14, 6.78], kcl: [6.78, 6.78],
} as const } as const
const yAxisSloppy = { const yAxisSloppy = {
screen: [ screen: [
viewPortSize.width / 2 + 5, // 5px off the Y-axis app.viewPortSize.width / 2 + 5, // 5px off the Y-axis
viewPortSize.height * 0.3, app.viewPortSize.height * 0.3,
], ],
kcl: [0, 6.78], kcl: [0, 6.78],
} as const } as const
@ -557,13 +510,15 @@ test(`Verify axis, origin, and horizontal snapping`, async ({
afterSegmentDraggedOnYAxis: `startProfileAt([${yAxisSloppy.kcl[0]}, ${yAxisSloppy.kcl[1]}], %)`, afterSegmentDraggedOnYAxis: `startProfileAt([${yAxisSloppy.kcl[0]}, ${yAxisSloppy.kcl[1]}], %)`,
} }
await app.initialise()
await test.step(`Start a sketch on the XZ plane`, async () => { await test.step(`Start a sketch on the XZ plane`, async () => {
await editor.closePane() await editor.closePane()
await toolbar.startSketchPlaneSelection() await toolbar.startSketchPlaneSelection()
await moveToXzPlane() await moveToXzPlane()
await clickOnXzPlane() await clickOnXzPlane()
// timeout wait for engine animation is unavoidable // timeout wait for engine animation is unavoidable
await page.waitForTimeout(600) await app.page.waitForTimeout(600)
await editor.expectEditor.toContain(expectedCodeSnippets.sketchOnXzPlane) await editor.expectEditor.toContain(expectedCodeSnippets.sketchOnXzPlane)
}) })
await test.step(`Place a point a few pixels off the middle, verify it still snaps to 0,0`, async () => { await test.step(`Place a point a few pixels off the middle, verify it still snaps to 0,0`, async () => {
@ -598,15 +553,11 @@ test(`Verify axis, origin, and horizontal snapping`, async ({
}) })
test(`Verify user can double-click to edit a sketch`, async ({ test(`Verify user can double-click to edit a sketch`, async ({
context, app,
page,
homePage,
editor, editor,
toolbar, toolbar,
scene, scene,
}) => { }) => {
const u = await getUtils(page)
const initialCode = `closedSketch = startSketchOn('XZ') const initialCode = `closedSketch = startSketchOn('XZ')
|> circle({ center = [8, 5], radius = 2 }, %) |> circle({ center = [8, 5], radius = 2 }, %)
openSketch = startSketchOn('XY') openSketch = startSketchOn('XY')
@ -615,24 +566,15 @@ openSketch = startSketchOn('XY')
|> xLine(5, %) |> xLine(5, %)
|> tangentialArcTo([10, 0], %) |> tangentialArcTo([10, 0], %)
` `
const viewPortSize = { width: 1000, height: 500 } await app.initialise(initialCode)
await page.setBodyDimensions(viewPortSize)
await context.addInitScript((code) => {
localStorage.setItem('persistCode', code)
}, initialCode)
await homePage.goToModelingScene()
await u.waitForPageLoad()
await page.waitForTimeout(1000)
const pointInsideCircle = { const pointInsideCircle = {
x: viewPortSize.width * 0.63, x: app.viewPortSize.width * 0.63,
y: viewPortSize.height * 0.5, y: app.viewPortSize.height * 0.5,
} }
const pointOnPathAfterSketching = { const pointOnPathAfterSketching = {
x: viewPortSize.width * 0.65, x: app.viewPortSize.width * 0.58,
y: viewPortSize.height * 0.5, y: app.viewPortSize.height * 0.5,
} }
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const [_clickOpenPath, moveToOpenPath, dblClickOpenPath] = const [_clickOpenPath, moveToOpenPath, dblClickOpenPath] =
@ -665,59 +607,41 @@ openSketch = startSketchOn('XY')
diagnostics: [], diagnostics: [],
}) })
}) })
await page.waitForTimeout(1000)
await exitSketch() await exitSketch()
await page.waitForTimeout(1000)
// Drag the sketch line out of the axis view which blocks the click
await page.dragAndDrop('#stream', '#stream', {
sourcePosition: {
x: viewPortSize.width * 0.7,
y: viewPortSize.height * 0.5,
},
targetPosition: {
x: viewPortSize.width * 0.7,
y: viewPortSize.height * 0.4,
},
})
await page.waitForTimeout(500)
await test.step(`Double-click on the open sketch`, async () => { await test.step(`Double-click on the open sketch`, async () => {
await moveToOpenPath() await moveToOpenPath()
await scene.expectPixelColor([250, 250, 250], pointOnPathAfterSketching, 15) await scene.expectPixelColor([250, 250, 250], pointOnPathAfterSketching, 15)
// There is a full execution after exiting sketch that clears the scene. // There is a full execution after exiting sketch that clears the scene.
await page.waitForTimeout(500) await app.page.waitForTimeout(500)
await dblClickOpenPath() await dblClickOpenPath()
await expect(toolbar.startSketchBtn).not.toBeVisible() await expect(toolbar.startSketchBtn).not.toBeVisible()
await expect(toolbar.exitSketchBtn).toBeVisible() await expect(toolbar.exitSketchBtn).toBeVisible()
// Wait for enter sketch mode to complete // Wait for enter sketch mode to complete
await page.waitForTimeout(500) await app.page.waitForTimeout(500)
await editor.expectState({ await editor.expectState({
activeLines: [`|>tangentialArcTo([10,0],%)`], activeLines: [`|>xLine(5,%)`],
highlightedCode: 'tangentialArcTo([10,0],%)', highlightedCode: 'xLine(5,%)',
diagnostics: [], diagnostics: [],
}) })
}) })
}) })
test(`Offset plane point-and-click`, async ({ test(`Offset plane point-and-click`, async ({
context, app,
page,
homePage,
scene, scene,
editor, editor,
toolbar, toolbar,
cmdBar, cmdBar,
}) => { }) => {
await app.initialise()
// One dumb hardcoded screen pixel value // One dumb hardcoded screen pixel value
const testPoint = { x: 700, y: 150 } const testPoint = { x: 700, y: 150 }
const [clickOnXzPlane] = scene.makeMouseHelpers(testPoint.x, testPoint.y) const [clickOnXzPlane] = scene.makeMouseHelpers(testPoint.x, testPoint.y)
const expectedOutput = `plane001 = offsetPlane('XZ', 5)` const expectedOutput = `plane001 = offsetPlane('XZ', 5)`
await homePage.goToModelingScene()
await test.step(`Look for the blue of the XZ plane`, async () => { await test.step(`Look for the blue of the XZ plane`, async () => {
await scene.expectPixelColor([50, 51, 96], testPoint, 15) await scene.expectPixelColor([50, 51, 96], testPoint, 15)
}) })
@ -851,9 +775,7 @@ const shellPointAndClickCapCases = [
] ]
shellPointAndClickCapCases.forEach(({ shouldPreselect }) => { shellPointAndClickCapCases.forEach(({ shouldPreselect }) => {
test(`Shell point-and-click cap (preselected sketches: ${shouldPreselect})`, async ({ test(`Shell point-and-click cap (preselected sketches: ${shouldPreselect})`, async ({
context, app,
page,
homePage,
scene, scene,
editor, editor,
toolbar, toolbar,
@ -863,11 +785,7 @@ shellPointAndClickCapCases.forEach(({ shouldPreselect }) => {
|> circle({ center = [0, 0], radius = 30 }, %) |> circle({ center = [0, 0], radius = 30 }, %)
extrude001 = extrude(30, sketch001) extrude001 = extrude(30, sketch001)
` `
await context.addInitScript((initialCode) => { await app.initialise(initialCode)
localStorage.setItem('persistCode', initialCode)
}, initialCode)
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
// One dumb hardcoded screen pixel value // One dumb hardcoded screen pixel value
const testPoint = { x: 575, y: 200 } const testPoint = { x: 575, y: 200 }
@ -894,7 +812,6 @@ shellPointAndClickCapCases.forEach(({ shouldPreselect }) => {
commandName: 'Shell', commandName: 'Shell',
}) })
await clickOnCap() await clickOnCap()
await page.waitForTimeout(500)
await cmdBar.progressCmdBar() await cmdBar.progressCmdBar()
await cmdBar.progressCmdBar() await cmdBar.progressCmdBar()
await cmdBar.expectState({ await cmdBar.expectState({
@ -910,7 +827,6 @@ shellPointAndClickCapCases.forEach(({ shouldPreselect }) => {
} else { } else {
await test.step(`Preselect the cap`, async () => { await test.step(`Preselect the cap`, async () => {
await clickOnCap() await clickOnCap()
await page.waitForTimeout(500)
}) })
await test.step(`Go through the command bar flow with a preselected face (cap)`, async () => { await test.step(`Go through the command bar flow with a preselected face (cap)`, async () => {
@ -942,9 +858,8 @@ shellPointAndClickCapCases.forEach(({ shouldPreselect }) => {
}) })
test('Shell point-and-click wall', async ({ test('Shell point-and-click wall', async ({
context, app,
page, page,
homePage,
scene, scene,
editor, editor,
toolbar, toolbar,
@ -959,11 +874,7 @@ test('Shell point-and-click wall', async ({
|> close(%) |> close(%)
extrude001 = extrude(40, sketch001) extrude001 = extrude(40, sketch001)
` `
await context.addInitScript((initialCode) => { await app.initialise(initialCode)
localStorage.setItem('persistCode', initialCode)
}, initialCode)
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
// One dumb hardcoded screen pixel value // One dumb hardcoded screen pixel value
const testPoint = { x: 580, y: 180 } const testPoint = { x: 580, y: 180 }
@ -994,7 +905,7 @@ extrude001 = extrude(40, sketch001)
await clickOnCap() await clickOnCap()
await page.keyboard.down('Shift') await page.keyboard.down('Shift')
await clickOnWall() await clickOnWall()
await page.waitForTimeout(500) await app.page.waitForTimeout(500)
await page.keyboard.up('Shift') await page.keyboard.up('Shift')
await cmdBar.progressCmdBar() await cmdBar.progressCmdBar()
await cmdBar.progressCmdBar() await cmdBar.progressCmdBar()

File diff suppressed because it is too large Load Diff

View File

@ -1,37 +1,46 @@
import { test, expect, Page } from './zoo-test' import { test, expect, Page } from '@playwright/test'
import path from 'path' import { join } from 'path'
import * as fsp from 'fs/promises' import * as fsp from 'fs/promises'
import { getUtils, executorInputPath } from './test-utils' import {
getUtils,
setup,
setupElectron,
tearDown,
executorInputPath,
} from './test-utils'
import { TEST_CODE_TRIGGER_ENGINE_EXPORT_ERROR } from './storageStates' import { TEST_CODE_TRIGGER_ENGINE_EXPORT_ERROR } from './storageStates'
import { bracket } from 'lib/exampleKcl' import { bracket } from 'lib/exampleKcl'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Regression tests', () => { test.describe('Regression tests', () => {
// bugs we found that don't fit neatly into other categories // bugs we found that don't fit neatly into other categories
test('bad model has inline error #3251', async ({ test('bad model has inline error #3251', async ({ page }) => {
context,
page,
homePage,
}) => {
// because the model has `line([0,0]..` it is valid code, but the model is invalid // because the model has `line([0,0]..` it is valid code, but the model is invalid
// regression test for https://github.com/KittyCAD/modeling-app/issues/3251 // regression test for https://github.com/KittyCAD/modeling-app/issues/3251
// Since the bad model also found as issue with the artifact graph, which in tern blocked the editor diognostics // Since the bad model also found as issue with the artifact graph, which in tern blocked the editor diognostics
const u = await getUtils(page) const u = await getUtils(page)
await context.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch2 = startSketchOn("XY") `sketch2 = startSketchOn("XY")
sketch001 = startSketchAt([-0, -0]) sketch001 = startSketchAt([-0, -0])
|> line([0, 0], %) |> line([0, 0], %)
|> line([-4.84, -5.29], %) |> line([-4.84, -5.29], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)` |> close(%)`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
// error in guter // error in guter
await expect(page.locator('.cm-lint-marker-error')).toBeVisible() await expect(page.locator('.cm-lint-marker-error')).toBeVisible()
@ -47,7 +56,6 @@ test.describe('Regression tests', () => {
}) })
test('user should not have to press down twice in cmdbar', async ({ test('user should not have to press down twice in cmdbar', async ({
page, page,
homePage,
}) => { }) => {
// because the model has `line([0,0]..` it is valid code, but the model is invalid // because the model has `line([0,0]..` it is valid code, but the model is invalid
// regression test for https://github.com/KittyCAD/modeling-app/issues/3251 // regression test for https://github.com/KittyCAD/modeling-app/issues/3251
@ -56,38 +64,26 @@ test.describe('Regression tests', () => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch2 = startSketchOn("XY")
|> startProfileAt([82.33, 238.21], %) sketch001 = startSketchAt([-0, -0])
|> angledLine([0, 288.63], %, $rectangleSegmentA001) |> line([0, 0], %)
|> angledLine([ |> line([-4.84, -5.29], %)
segAng(rectangleSegmentA001) - 90,
197.97
], %, $rectangleSegmentB001)
|> angledLine([
segAng(rectangleSegmentA001),
-segLen(rectangleSegmentA001)
], %, $rectangleSegmentC001)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)`
extrude001 = extrude(50, sketch001)
`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await page.goto('/')
await u.waitForPageLoad() await u.waitForPageLoad()
await test.step('Check arrow down works', async () => { await test.step('Check arrow down works', async () => {
await page.getByTestId('command-bar-open-button').hover()
await page.getByTestId('command-bar-open-button').click() await page.getByTestId('command-bar-open-button').click()
const floppy = page.getByRole('option', { await page
name: 'floppy disk arrow Export', .getByRole('option', { name: 'floppy disk arrow Export' })
}) .click()
await floppy.click()
// press arrow down key twice // press arrow down key twice
await page.keyboard.press('ArrowDown') await page.keyboard.press('ArrowDown')
@ -119,22 +115,21 @@ extrude001 = extrude(50, sketch001)
) )
}) })
}) })
test('executes on load', async ({ page, homePage }) => { test('executes on load', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('-XZ') `sketch001 = startSketchOn('-XZ')
|> startProfileAt([-6.95, 4.98], %) |> startProfileAt([-6.95, 4.98], %)
|> line([25.1, 0.41], %) |> line([25.1, 0.41], %)
|> line([0.73, -14.93], %) |> line([0.73, -14.93], %)
|> line([-23.44, 0.52], %)` |> line([-23.44, 0.52], %)`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
// expand variables section // expand variables section
const variablesTabButton = page.getByTestId('variables-pane-button') const variablesTabButton = page.getByTestId('variables-pane-button')
@ -153,15 +148,14 @@ extrude001 = extrude(50, sketch001)
).toBeVisible() ).toBeVisible()
}) })
test('re-executes', async ({ page, homePage }) => { test('re-executes', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem('persistCode', `myVar = 5`) localStorage.setItem('persistCode', `myVar = 5`)
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
const variablesTabButton = page.getByTestId('variables-pane-button') const variablesTabButton = page.getByTestId('variables-pane-button')
await variablesTabButton.click() await variablesTabButton.click()
@ -180,33 +174,32 @@ extrude001 = extrude(50, sketch001)
page.locator('.pretty-json-container >> text=myVar:67') page.locator('.pretty-json-container >> text=myVar:67')
).toBeVisible() ).toBeVisible()
}) })
test('ProgramMemory can be serialised', async ({ page, homePage }) => { test('ProgramMemory can be serialised', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`part = startSketchOn('XY') `part = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> line([0, 1], %) |> line([0, 1], %)
|> line([1, 0], %) |> line([1, 0], %)
|> line([0, -1], %) |> line([0, -1], %)
|> close(%) |> close(%)
|> extrude(1, %) |> extrude(1, %)
|> patternLinear3d({ |> patternLinear3d({
axis: [1, 0, 1], axis: [1, 0, 1],
repetitions: 3, repetitions: 3,
distance: 6 distance: 6
}, %)` }, %)`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
const messages: string[] = [] const messages: string[] = []
// Listen for all console events and push the message text to an array // Listen for all console events and push the message text to an array
page.on('console', (message) => messages.push(message.text())) page.on('console', (message) => messages.push(message.text()))
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -219,26 +212,19 @@ extrude001 = extrude(50, sketch001)
}) })
}) })
}) })
test('ensure the Zoo logo is not a link in browser app', async ({ page }) => {
// Not relevant to us anymore, or at least for the time being.
test.skip('ensure the Zoo logo is not a link in browser app', async ({
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
const zooLogo = page.locator('[data-testid="app-logo"]') const zooLogo = page.locator('[data-testid="app-logo"]')
// Make sure it's not a link // Make sure it's not a link
await expect(zooLogo).not.toHaveAttribute('href') await expect(zooLogo).not.toHaveAttribute('href')
}) })
test( test(
'Position _ Is Out Of Range... regression test', 'Position _ Is Out Of Range... regression test',
{ tag: ['@skipWin'] }, { tag: ['@skipWin'] },
async ({ context, page, homePage }) => { async ({ page }) => {
// SKip on windows, its being weird. // SKip on windows, its being weird.
test.skip( test.skip(
process.platform === 'win32', process.platform === 'win32',
@ -247,26 +233,25 @@ extrude001 = extrude(50, sketch001)
const u = await getUtils(page) const u = await getUtils(page)
// const PUR = 400 / 37.5 //pixeltoUnitRatio // const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await context.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`exampleSketch = startSketchOn("XZ") `exampleSketch = startSketchOn("XZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLine({ angle: 50, length: 45 }, %) |> angledLine({ angle: 50, length: 45 }, %)
|> yLineTo(0, %) |> yLineTo(0, %)
|> close(%) |> close(%)
|> |>
example = extrude(5, exampleSketch) example = extrude(5, exampleSketch)
shell({ faces: ['end'], thickness: 0.25 }, exampleSketch)` shell({ faces: ['end'], thickness: 0.25 }, exampleSketch)`
) )
}) })
await expect(async () => { await expect(async () => {
await homePage.goToModelingScene() await page.goto('/')
await u.waitForPageLoad() await u.waitForPageLoad()
// error in guter // error in guter
await expect(page.locator('.cm-lint-marker-error')).toBeVisible({ await expect(page.locator('.cm-lint-marker-error')).toBeVisible({
timeout: 1_000, timeout: 1_000,
@ -308,12 +293,12 @@ extrude001 = extrude(50, sketch001)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toContainText(`exampleSketch = startSketchOn("XZ") .toContainText(`exampleSketch = startSketchOn("XZ")
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> angledLine({ angle: 50, length: 45 }, %) |> angledLine({ angle: 50, length: 45 }, %)
|> yLineTo(0, %) |> yLineTo(0, %)
|> close(%) |> close(%)
thing: "blah"`) thing: "blah"`)
await expect(page.locator('.cm-lint-marker-error')).toBeVisible() await expect(page.locator('.cm-lint-marker-error')).toBeVisible()
} }
@ -321,7 +306,6 @@ extrude001 = extrude(50, sketch001)
test('when engine fails export we handle the failure and alert the user', async ({ test('when engine fails export we handle the failure and alert the user', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript( await page.addInitScript(
@ -332,10 +316,9 @@ extrude001 = extrude(50, sketch001)
{ code: TEST_CODE_TRIGGER_ENGINE_EXPORT_ERROR } { code: TEST_CODE_TRIGGER_ENGINE_EXPORT_ERROR }
) )
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -391,6 +374,7 @@ extrude001 = extrude(50, sketch001)
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
await u.clearCommandLogs()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
@ -424,7 +408,7 @@ extrude001 = extrude(50, sketch001)
test( test(
'ensure you can not export while an export is already going', 'ensure you can not export while an export is already going',
{ tag: ['@skipLinux', '@skipWin'] }, { tag: ['@skipLinux', '@skipWin'] },
async ({ page, homePage }) => { async ({ page }) => {
// This is being weird on ubuntu and windows. // This is being weird on ubuntu and windows.
test.skip( test.skip(
// eslint-disable-next-line jest/valid-title // eslint-disable-next-line jest/valid-title
@ -444,10 +428,9 @@ extrude001 = extrude(50, sketch001)
} }
) )
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -517,17 +500,20 @@ extrude001 = extrude(50, sketch001)
test( test(
`Network health indicator only appears in modeling view`, `Network health indicator only appears in modeling view`,
{ tag: '@electron' }, { tag: '@electron' },
async ({ context, page }, testInfo) => { async ({ browserName: _ }, testInfo) => {
await context.folderSetupFn(async (dir) => { const { electronApp, page } = await setupElectron({
const bracketDir = path.join(dir, 'bracket') testInfo,
await fsp.mkdir(bracketDir, { recursive: true }) folderSetupFn: async (dir) => {
await fsp.copyFile( const bracketDir = join(dir, 'bracket')
executorInputPath('focusrite_scarlett_mounting_braket.kcl'), await fsp.mkdir(bracketDir, { recursive: true })
path.join(bracketDir, 'main.kcl') await fsp.copyFile(
) executorInputPath('focusrite_scarlett_mounting_braket.kcl'),
join(bracketDir, 'main.kcl')
)
},
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
const u = await getUtils(page) const u = await getUtils(page)
// Locators // Locators
@ -553,17 +539,18 @@ extrude001 = extrude(50, sketch001)
await u.waitForPageLoad() await u.waitForPageLoad()
await expect(networkHealthIndicator).toContainText('Connected') await expect(networkHealthIndicator).toContainText('Connected')
}) })
await electronApp.close()
} }
) )
test(`View gizmo stays visible even when zoomed out all the way`, async ({ test(`View gizmo stays visible even when zoomed out all the way`, async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
// Constants and locators // Constants and locators
const planeColor: [number, number, number] = [170, 220, 170] const planeColor: [number, number, number] = [161, 220, 155]
const bgColor: [number, number, number] = [27, 27, 27] const bgColor: [number, number, number] = [27, 27, 27]
const middlePixelIsColor = async (color: [number, number, number]) => { const middlePixelIsColor = async (color: [number, number, number]) => {
return u.getGreatestPixDiff({ x: 600, y: 250 }, color) return u.getGreatestPixDiff({ x: 600, y: 250 }, color)
@ -574,9 +561,8 @@ extrude001 = extrude(50, sketch001)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem('persistCode', '') localStorage.setItem('persistCode', '')
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await u.closeKclCodePanel() await u.closeKclCodePanel()
}) })

File diff suppressed because it is too large Load Diff

View File

@ -47,11 +47,7 @@ test.beforeEach(async ({ page }) => {
test.setTimeout(60_000) test.setTimeout(60_000)
// We test this end to end already - getting this to work on web just to take test(
// a snapshot of it feels weird. I'd rather our regular tests fail.
// The primary failure is doExport now relies on the filesystem. We can follow
// up with another PR if we want this back.
test.skip(
'exports of each format should work', 'exports of each format should work',
{ tag: ['@snapshot', '@skipWin', '@skipMacos'] }, { tag: ['@snapshot', '@skipWin', '@skipMacos'] },
async ({ page, context }) => { async ({ page, context }) => {
@ -954,75 +950,7 @@ test(
test.describe('Grid visibility', { tag: '@snapshot' }, () => { test.describe('Grid visibility', { tag: '@snapshot' }, () => {
// FIXME: Skip on macos its being weird. // FIXME: Skip on macos its being weird.
// test.skip(process.platform === 'darwin', 'Skip on macos') test.skip(process.platform === 'darwin', 'Skip on macos')
test('Grid turned off to on via command bar', async ({ page }) => {
const u = await getUtils(page)
const stream = page.getByTestId('stream')
const mask = [
page.locator('#app-header'),
page.locator('#sidebar-top-ribbon'),
page.locator('#sidebar-bottom-ribbon'),
]
await page.setViewportSize({ width: 1200, height: 500 })
await page.goto('/')
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
// wait for execution done
await expect(
page.locator('[data-message-type="execution-done"]')
).toHaveCount(1)
await u.closeDebugPanel()
await u.closeKclCodePanel()
// TODO: Find a way to truly know that the objects have finished
// rendering, because an execution-done message is not sufficient.
await page.waitForTimeout(1000)
// Open the command bar.
await page
.getByRole('button', { name: 'Commands', exact: false })
.or(page.getByRole('button', { name: '⌘K' }))
.click()
const commandName = 'show scale grid'
const commandOption = page.getByRole('option', {
name: commandName,
exact: false,
})
const cmdSearchBar = page.getByPlaceholder('Search commands')
// This selector changes after we set the setting
await cmdSearchBar.fill(commandName)
await expect(commandOption).toBeVisible()
await commandOption.click()
const toggleInput = page.getByPlaceholder('Off')
await expect(toggleInput).toBeVisible()
await expect(toggleInput).toBeFocused()
// Select On
await page.keyboard.press('ArrowDown')
await expect(page.getByRole('option', { name: 'Off' })).toHaveAttribute(
'data-headlessui-state',
'active selected'
)
await page.keyboard.press('ArrowUp')
await expect(page.getByRole('option', { name: 'On' })).toHaveAttribute(
'data-headlessui-state',
'active'
)
await page.keyboard.press('Enter')
// Check the toast appeared
await expect(
page.getByText(`Set show scale grid to "true" as a user default`)
).toBeVisible()
await expect(stream).toHaveScreenshot({
maxDiffPixels: 100,
mask,
})
})
test('Grid turned off', async ({ page }) => { test('Grid turned off', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

View File

@ -109,21 +109,242 @@ keychain = startSketchOn("XY")
|> close(%) |> close(%)
|> extrude(thickness, %) |> extrude(thickness, %)
keychain1 = startSketchOn("XY") // generated from /home/paultag/Downloads/zma-logomark.svg
|> startProfileAt([0, 0], %) fn svg = (surface, origin, depth) => {
|> lineTo([width, 0], %) let a0 = surface |> startProfileAt([origin[0] + 45.430427, origin[1] + -14.627736], %)
|> lineTo([width, height], %) |> bezierCurve({
|> lineTo([0, height], %) control1: [ 0, 0.764157 ],
|> close(%) control2: [ 0, 1.528314 ],
|> extrude(thickness, %) to: [ 0, 2.292469 ]
}, %)
|> bezierCurve({
control1: [ -3.03202, 0 ],
control2: [ -6.064039, 0 ],
to: [ -9.09606, 0 ]
}, %)
|> bezierCurve({
control1: [ 0, -1.077657 ],
control2: [ 0, -2.155312 ],
to: [ 0, -3.232969 ]
}, %)
|> bezierCurve({
control1: [ 2.741805, 0 ],
control2: [ 5.483613, 0 ],
to: [ 8.225417, 0 ]
}, %)
|> bezierCurve({
control1: [ -2.740682, -2.961815 ],
control2: [ -5.490342, -5.925794 ],
to: [ -8.225417, -8.886255 ]
}, %)
|> bezierCurve({
control1: [ 0, -0.723995 ],
control2: [ 0, -1.447988 ],
to: [ 0, -2.171981 ]
}, %)
|> bezierCurve({
control1: [ 0.712124, 0.05061 ],
control2: [ 1.511636, -0.09877 ],
to: [ 2.172096, 0.07005 ]
}, %)
|> bezierCurve({
control1: [ 0.68573, 0.740811 ],
control2: [ 1.371459, 1.481622 ],
to: [ 2.057187, 2.222436 ]
}, %)
|> bezierCurve({
control1: [ 0, -0.76416 ],
control2: [ 0, -1.52832 ],
to: [ 0, -2.29248 ]
}, %)
|> bezierCurve({
control1: [ 3.032013, 0 ],
control2: [ 6.064026, 0 ],
to: [ 9.096038, 0 ]
}, %)
|> bezierCurve({
control1: [ 0, 1.077657 ],
control2: [ 0, 2.155314 ],
to: [ 0, 3.232973 ]
}, %)
|> bezierCurve({
control1: [ -2.741312, 0 ],
control2: [ -5.482623, 0 ],
to: [ -8.223936, 0 ]
}, %)
|> bezierCurve({
control1: [ 2.741313, 2.961108 ],
control2: [ 5.482624, 5.922216 ],
to: [ 8.223936, 8.883325 ]
}, %)
|> bezierCurve({
control1: [ 0, 0.724968 ],
control2: [ 0, 1.449938 ],
to: [ 0, 2.174907 ]
}, %)
|> bezierCurve({
control1: [ -0.712656, -0.05145 ],
control2: [ -1.512554, 0.09643 ],
to: [ -2.173592, -0.07298 ]
}, %)
|> bezierCurve({
control1: [ -0.685222, -0.739834 ],
control2: [ -1.370445, -1.479669 ],
to: [ -2.055669, -2.219505 ]
}, %)
|> close(%)
|> extrude(depth, %)
keychain2 = startSketchOn("XY") let a1 = surface |> startProfileAt([origin[0] + 57.920488, origin[1] + -15.244943], %)
|> startProfileAt([0, 0], %) |> bezierCurve({
|> lineTo([width, 0], %) control1: [ -2.78904, 0.106635 ],
|> lineTo([width, height], %) control2: [ -5.052548, -2.969529 ],
|> lineTo([0, height], %) to: [ -4.055141, -5.598369 ]
|> close(%) }, %)
|> extrude(thickness, %) |> bezierCurve({
control1: [ 0.841523, -0.918736 ],
control2: [ 0.439412, -1.541892 ],
to: [ -0.368488, -2.214378 ]
}, %)
|> bezierCurve({
control1: [ -0.418245, -0.448461 ],
control2: [ -0.836489, -0.896922 ],
to: [ -1.254732, -1.345384 ]
}, %)
|> bezierCurve({
control1: [ -2.76806, 2.995359 ],
control2: [ -2.32667, 8.18409 ],
to: [ 0.897655, 10.678932 ]
}, %)
|> bezierCurve({
control1: [ 2.562822, 2.186098 ],
control2: [ 6.605111, 2.28043 ],
to: [ 9.271202, 0.226476 ]
}, %)
|> bezierCurve({
control1: [ -0.743744, -0.797465 ],
control2: [ -1.487487, -1.594932 ],
to: [ -2.231232, -2.392397 ]
}, %)
|> bezierCurve({
control1: [ -0.672938, 0.421422 ],
control2: [ -1.465362, 0.646946 ],
to: [ -2.259264, 0.64512 ]
}, %)
|> close(%)
|> extrude(depth, %)
let a2 = surface |> startProfileAt([origin[0] + 62.19406300000001, origin[1] + -19.500698999999997], %)
|> bezierCurve({
control1: [ 0.302938, 1.281141 ],
control2: [ -1.53575, 2.434288 ],
to: [ -0.10908, 3.279477 ]
}, %)
|> bezierCurve({
control1: [ 0.504637, 0.54145 ],
control2: [ 1.009273, 1.082899 ],
to: [ 1.513909, 1.624348 ]
}, %)
|> bezierCurve({
control1: [ 2.767778, -2.995425 ],
control2: [ 2.327135, -8.184384 ],
to: [ -0.897661, -10.679047 ]
}, %)
|> bezierCurve({
control1: [ -2.562947, -2.186022 ],
control2: [ -6.604089, -2.279606 ],
to: [ -9.271196, -0.227813 ]
}, %)
|> bezierCurve({
control1: [ 0.744231, 0.797952 ],
control2: [ 1.488461, 1.595904 ],
to: [ 2.232692, 2.393856 ]
}, %)
|> bezierCurve({
control1: [ 2.302377, -1.564629 ],
control2: [ 5.793126, -0.15358 ],
to: [ 6.396577, 2.547372 ]
}, %)
|> bezierCurve({
control1: [ 0.08981, 0.346302 ],
control2: [ 0.134865, 0.704078 ],
to: [ 0.13476, 1.061807 ]
}, %)
|> close(%)
|> extrude(depth, %)
let a3 = surface |> startProfileAt([origin[0] + 74.124866, origin[1] + -15.244943], %)
|> bezierCurve({
control1: [ -2.78904, 0.106635 ],
control2: [ -5.052549, -2.969529 ],
to: [ -4.055142, -5.598369 ]
}, %)
|> bezierCurve({
control1: [ 0.841527, -0.918738 ],
control2: [ 0.43941, -1.541892 ],
to: [ -0.368497, -2.214367 ]
}, %)
|> bezierCurve({
control1: [ -0.418254, -0.448466 ],
control2: [ -0.836507, -0.896931 ],
to: [ -1.254761, -1.345395 ]
}, %)
|> bezierCurve({
control1: [ -2.768019, 2.995371 ],
control2: [ -2.326624, 8.184088 ],
to: [ 0.897678, 10.678932 ]
}, %)
|> bezierCurve({
control1: [ 2.56289, 2.186191 ],
control2: [ 6.60516, 2.280307 ],
to: [ 9.271371, 0.226476 ]
}, %)
|> bezierCurve({
control1: [ -0.743808, -0.797465 ],
control2: [ -1.487616, -1.594932 ],
to: [ -2.231424, -2.392397 ]
}, %)
|> bezierCurve({
control1: [ -0.672916, 0.421433 ],
control2: [ -1.465344, 0.646926 ],
to: [ -2.259225, 0.64512 ]
}, %)
|> close(%)
|> extrude(depth, %)
let a4 = surface |> startProfileAt([origin[0] + 77.57333899999998, origin[1] + -16.989262999999998], %)
|> bezierCurve({
control1: [ 0.743298, 0.797463 ],
control2: [ 1.486592, 1.594926 ],
to: [ 2.229888, 2.392389 ]
}, %)
|> bezierCurve({
control1: [ 2.767827, -2.995393 ],
control2: [ 2.327103, -8.184396 ],
to: [ -0.897672, -10.679047 ]
}, %)
|> bezierCurve({
control1: [ -2.562939, -2.186037 ],
control2: [ -6.604077, -2.279589 ],
to: [ -9.271185, -0.227813 ]
}, %)
|> bezierCurve({
control1: [ 0.744243, 0.797952 ],
control2: [ 1.488486, 1.595904 ],
to: [ 2.232729, 2.393856 ]
}, %)
|> bezierCurve({
control1: [ 2.302394, -1.564623 ],
control2: [ 5.793201, -0.153598 ],
to: [ 6.396692, 2.547372 ]
}, %)
|> bezierCurve({
control1: [ 0.32074, 1.215468 ],
control2: [ 0.06159, 2.564765 ],
to: [ -0.690452, 3.573243 ]
}, %)
|> close(%)
|> extrude(depth, %)
box = startSketchOn('XY') box = startSketchOn('XY')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
@ -133,7 +354,7 @@ box = startSketchOn('XY')
|> close(%) |> close(%)
|> extrude(10, %) |> extrude(10, %)
sketch001 = startSketchOn(box, revolveAxis) sketch001 = startSketchOn(box, revolveAxis)
|> startProfileAt([5, 10], %) |> startProfileAt([5, 10], %)
|> line([0, -10], %) |> line([0, -10], %)
|> line([2, 0], %) |> line([2, 0], %)
@ -143,12 +364,18 @@ sketch001 = startSketchOn(box, revolveAxis)
axis: revolveAxis, axis: revolveAxis,
angle: 90 angle: 90
}, %) }, %)
return 0
}
sketch001 = startSketchOn('XZ')
|> startProfileAt([0.0, 0.0], %)
|> xLine(0.0, %)
|> close(%)
`
svg(startSketchOn(keychain, 'end'), [-33, 32], -thickness)
startSketchOn(keychain, 'end')
|> circle({ center: [
width / 2,
height - (keychainHoleSize + 1.5)
], radius: keychainHoleSize }, %)
|> extrude(-thickness, %)`
export const TEST_CODE_TRIGGER_ENGINE_EXPORT_ERROR = `thing = 1` export const TEST_CODE_TRIGGER_ENGINE_EXPORT_ERROR = `thing = 1`

View File

@ -1,16 +1,29 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { commonPoints, getUtils } from './test-utils' import { commonPoints, getUtils, setup, tearDown } from './test-utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Test network and connection issues', () => { test.describe('Test network and connection issues', () => {
test('simulate network down and network little widget', async ({ test('simulate network down and network little widget', async ({
page, page,
homePage, browserName,
}) => { }) => {
// TODO: Don't skip Mac for these. After `window.tearDown` is working in Safari, these should work on webkit
test.skip(
browserName === 'webkit',
'Skip on Safari until `window.tearDown` is working there'
)
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
const networkToggle = page.getByTestId('network-toggle') const networkToggle = page.getByTestId('network-toggle')
@ -49,7 +62,7 @@ test.describe('Test network and connection issues', () => {
}) })
// Expect the network to be down // Expect the network to be down
await expect(networkToggle).toContainText('Problem') await expect(networkToggle).toContainText('Offline')
// Click the network widget // Click the network widget
await networkWidget.click() await networkWidget.click()
@ -80,19 +93,26 @@ test.describe('Test network and connection issues', () => {
test('Engine disconnect & reconnect in sketch mode', async ({ test('Engine disconnect & reconnect in sketch mode', async ({
page, page,
homePage, browserName,
}) => { }) => {
// TODO: Don't skip Mac for these. After `window.tearDown` is working in Safari, these should work on webkit // TODO: Don't skip Mac for these. After `window.tearDown` is working in Safari, these should work on webkit
test.skip(
browserName === 'webkit',
'Skip on Safari until `window.tearDown` is working there'
)
const networkToggle = page.getByTestId('network-toggle') const networkToggle = page.getByTestId('network-toggle')
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio const PUR = 400 / 37.5 //pixeltoUnitRatio
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await u.openDebugPanel() await u.openDebugPanel()
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled({ timeout: 15000 })
// click on "Start Sketch" button // click on "Start Sketch" button
await u.clearCommandLogs() await u.clearCommandLogs()
await page.getByRole('button', { name: 'Start Sketch' }).click() await page.getByRole('button', { name: 'Start Sketch' }).click()
@ -112,7 +132,7 @@ test.describe('Test network and connection issues', () => {
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10) await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt(${commonPoints.startAt}, %)`) |> startProfileAt(${commonPoints.startAt}, %)`)
await page.waitForTimeout(100) await page.waitForTimeout(100)
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10) await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
@ -120,8 +140,8 @@ test.describe('Test network and connection issues', () => {
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt(${commonPoints.startAt}, %) |> startProfileAt(${commonPoints.startAt}, %)
|> xLine(${commonPoints.num1}, %)`) |> xLine(${commonPoints.num1}, %)`)
// Expect the network to be up // Expect the network to be up
await expect(networkToggle).toContainText('Connected') await expect(networkToggle).toContainText('Connected')
@ -136,7 +156,7 @@ test.describe('Test network and connection issues', () => {
}) })
// Expect the network to be down // Expect the network to be down
await expect(networkToggle).toContainText('Problem') await expect(networkToggle).toContainText('Offline')
// Ensure we are not in sketch mode // Ensure we are not in sketch mode
await expect( await expect(

View File

@ -1,20 +1,22 @@
import { import {
expect, expect,
Page,
Download,
BrowserContext, BrowserContext,
TestInfo, TestInfo,
_electron as electron, _electron as electron,
Locator, Locator,
test,
} from '@playwright/test' } from '@playwright/test'
import { test, Page } from './zoo-test'
import { EngineCommand } from 'lang/std/artifactGraph' import { EngineCommand } from 'lang/std/artifactGraph'
import fsp from 'fs/promises' import fsp from 'fs/promises'
import fsSync from 'fs' import fsSync from 'fs'
import path from 'path' import { join } from 'path'
import pixelMatch from 'pixelmatch' import pixelMatch from 'pixelmatch'
import { PNG } from 'pngjs' import { PNG } from 'pngjs'
import { Protocol } from 'playwright-core/types/protocol' import { Protocol } from 'playwright-core/types/protocol'
import type { Models } from '@kittycad/lib' import type { Models } from '@kittycad/lib'
import { COOKIE_NAME } from 'lib/constants' import { APP_NAME, COOKIE_NAME } from 'lib/constants'
import { secrets } from './secrets' import { secrets } from './secrets'
import { import {
TEST_SETTINGS_KEY, TEST_SETTINGS_KEY,
@ -28,134 +30,6 @@ import { isErrorWhitelisted } from './lib/console-error-whitelist'
import { isArray } from 'lib/utils' import { isArray } from 'lib/utils'
import { reportRejection } from 'lib/trap' import { reportRejection } from 'lib/trap'
// The below is copied from playwright-core because it exports none of them :(
import { Env, BrowserContextOptions } from 'playwright-core'
import type * as channels from '@protocol/channels'
// Copied from playwright-core
function envObjectToArray(env: Env): { name: string; value: string }[] {
const result: { name: string; value: string }[] = []
for (const name in env) {
if (!Object.is(env[name], undefined))
result.push({ name, value: String(env[name]) })
}
return result
}
// Copied from playwright-core
export async function toClientCertificatesProtocol(
certs?: BrowserContextOptions['clientCertificates']
): Promise<channels.PlaywrightNewRequestParams['clientCertificates']> {
if (!certs) return undefined
const bufferizeContent = async (
value?: Buffer,
path?: string
): Promise<Buffer | undefined> => {
if (value) return value
if (path) return await fs.promises.readFile(path)
}
return await Promise.all(
certs.map(async (cert) => ({
origin: cert.origin,
cert: await bufferizeContent(cert.cert, cert.certPath),
key: await bufferizeContent(cert.key, cert.keyPath),
pfx: await bufferizeContent(cert.pfx, cert.pfxPath),
passphrase: cert.passphrase,
}))
)
}
// Copied from playwright-core
function toAcceptDownloadsProtocol(acceptDownloads?: boolean) {
if (acceptDownloads === undefined) return undefined
if (acceptDownloads) return 'accept'
return 'deny'
}
// Copied from playwright-core
function prepareRecordHarOptions(
options: BrowserContextOptions['recordHar']
): channels.RecordHarOptions | undefined {
if (!options) return
return {
path: options.path,
content: options.content || (options.omitContent ? 'omit' : undefined),
urlGlob: isString(options.urlFilter) ? options.urlFilter : undefined,
urlRegexSource: isRegExp(options.urlFilter)
? options.urlFilter.source
: undefined,
urlRegexFlags: isRegExp(options.urlFilter)
? options.urlFilter.flags
: undefined,
mode: options.mode,
}
}
// Copied from playwright-core
async function prepareStorageState(
options: BrowserContextOptions
): Promise<channels.BrowserNewContextParams['storageState']> {
if (typeof options.storageState !== 'string') return options.storageState
try {
return JSON.parse(await fs.promises.readFile(options.storageState, 'utf8'))
} catch (e) {
rewriteErrorMessage(
e,
`Error reading storage state from ${options.storageState}:\n` + e.message
)
throw e
}
}
// Copied from playwright-core
async function prepareBrowserContextParams(
options: BrowserContextOptions
): Promise<channels.BrowserNewContextParams> {
if (options.videoSize && !options.videosPath)
throw new Error(`"videoSize" option requires "videosPath" to be specified`)
if (options.extraHTTPHeaders)
network.validateHeaders(options.extraHTTPHeaders)
const contextParams: channels.BrowserNewContextParams = {
...options,
viewport: options.viewport === null ? undefined : options.viewport,
noDefaultViewport: options.viewport === null,
extraHTTPHeaders: options.extraHTTPHeaders
? headersObjectToArray(options.extraHTTPHeaders)
: undefined,
storageState: await prepareStorageState(options),
serviceWorkers: options.serviceWorkers,
recordHar: prepareRecordHarOptions(options.recordHar),
colorScheme:
options.colorScheme === null ? 'no-override' : options.colorScheme,
reducedMotion:
options.reducedMotion === null ? 'no-override' : options.reducedMotion,
forcedColors:
options.forcedColors === null ? 'no-override' : options.forcedColors,
acceptDownloads: toAcceptDownloadsProtocol(options.acceptDownloads),
clientCertificates: await toClientCertificatesProtocol(
options.clientCertificates
),
}
if (!contextParams.recordVideo && options.videosPath) {
contextParams.recordVideo = {
dir: options.videosPath,
size: options.videoSize,
}
}
if (contextParams.recordVideo && contextParams.recordVideo.dir)
contextParams.recordVideo.dir = path.resolve(
process.cwd(),
contextParams.recordVideo.dir
)
return contextParams
}
const toNormalizedCode = (text: string) => {
return text.replace(/\s+/g, '')
}
type TestColor = [number, number, number] type TestColor = [number, number, number]
export const TEST_COLORS = { export const TEST_COLORS = {
WHITE: [249, 249, 249] as TestColor, WHITE: [249, 249, 249] as TestColor,
@ -224,16 +98,11 @@ async function removeCurrentCode(page: Page) {
} }
export async function sendCustomCmd(page: Page, cmd: EngineCommand) { export async function sendCustomCmd(page: Page, cmd: EngineCommand) {
const json = JSON.stringify(cmd) await page.getByTestId('custom-cmd-input').fill(JSON.stringify(cmd))
await page.getByTestId('custom-cmd-input').fill(json)
await expect(page.getByTestId('custom-cmd-input')).toHaveValue(json)
await page.getByTestId('custom-cmd-send-button').scrollIntoViewIfNeeded()
await page.getByTestId('custom-cmd-send-button').click() await page.getByTestId('custom-cmd-send-button').click()
} }
async function clearCommandLogs(page: Page) { async function clearCommandLogs(page: Page) {
await page.getByTestId('custom-cmd-input').fill('')
await page.getByTestId('clear-commands').scrollIntoViewIfNeeded()
await page.getByTestId('clear-commands').click() await page.getByTestId('clear-commands').click()
} }
@ -281,19 +150,6 @@ export async function closePane(page: Page, testId: string) {
async function openKclCodePanel(page: Page) { async function openKclCodePanel(page: Page) {
await openPane(page, 'code-pane-button') await openPane(page, 'code-pane-button')
// Code Mirror lazy loads text! Wowza! Let's force-load the text for tests.
await page.evaluate(() => {
// editorManager is available on the window object.
//@ts-ignore this is in an entirely different context that tsc can't see.
editorManager._editorView.dispatch({
selection: {
//@ts-ignore this is in an entirely different context that tsc can't see.
anchor: editorManager._editorView.docView.length,
},
scrollIntoView: true,
})
})
} }
async function closeKclCodePanel(page: Page) { async function closeKclCodePanel(page: Page) {
@ -309,9 +165,6 @@ async function closeKclCodePanel(page: Page) {
async function openDebugPanel(page: Page) { async function openDebugPanel(page: Page) {
await openPane(page, 'debug-pane-button') await openPane(page, 'debug-pane-button')
// The debug pane needs time to load everything.
await page.waitForTimeout(3000)
} }
export async function closeDebugPanel(page: Page) { export async function closeDebugPanel(page: Page) {
@ -559,10 +412,6 @@ export async function getUtils(page: Page, test_?: typeof test) {
.boundingBox({ timeout: 5_000 }) .boundingBox({ timeout: 5_000 })
.then((box) => ({ ...box, x: box?.x || 0, y: box?.y || 0 })), .then((box) => ({ ...box, x: box?.x || 0, y: box?.y || 0 })),
codeLocator: page.locator('.cm-content'), codeLocator: page.locator('.cm-content'),
crushKclCodeIntoOneLineAndThenMaybeSome: async () => {
const code = await page.locator('.cm-content').innerText()
return code.replaceAll(' ', '').replaceAll('\n', '')
},
normalisedEditorCode: async () => { normalisedEditorCode: async () => {
const code = await page.locator('.cm-content').innerText() const code = await page.locator('.cm-content').innerText()
return normaliseKclNumbers(code) return normaliseKclNumbers(code)
@ -633,18 +482,13 @@ export async function getUtils(page: Page, test_?: typeof test) {
) )
}, },
toNormalizedCode(text: string) { toNormalizedCode: (text: string) => {
return toNormalizedCode(text) return text.replace(/\s+/g, '')
}, },
async editorTextMatches(code: string) { editorTextMatches: async (code: string) => {
const editor = page.locator(editorSelector) const editor = page.locator(editorSelector)
return expect return expect(editor).toHaveText(code, { useInnerText: true })
.poll(async () => {
const text = await editor.textContent()
return toNormalizedCode(text ?? '')
})
.toContain(toNormalizedCode(code))
}, },
pasteCodeInEditor: async (code: string) => { pasteCodeInEditor: async (code: string) => {
@ -670,7 +514,7 @@ export async function getUtils(page: Page, test_?: typeof test) {
page.getByRole('button', { name: 'Start Sketch' }) page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled() ).not.toBeDisabled()
await page.getByTestId('create-file-button').click() await page.getByTestId('create-file-button').click()
await page.getByTestId('tree-input-field').fill(name) await page.getByTestId('file-rename-field').fill(name)
await page.keyboard.press('Enter') await page.keyboard.press('Enter')
}) })
}, },
@ -830,34 +674,6 @@ export const makeTemplate: (
} }
} }
const PLAYWRIGHT_DOWNLOAD_DIR = 'downloads-during-playwright'
export const getPlaywrightDownloadDir = (page: Page) => {
return path.resolve(page.dir, PLAYWRIGHT_DOWNLOAD_DIR)
}
const moveDownloadedFileTo = async (page: Page, toLocation: string) => {
await fsp.mkdir(path.dirname(toLocation), { recursive: true })
const downloadDir = getPlaywrightDownloadDir(page)
// Expect there to be at least one file
await expect
.poll(async () => {
const files = await fsp.readdir(downloadDir)
return files.length
})
.toBeGreaterThan(0)
// Go through the downloads dir and move files to new location
const files = await fsp.readdir(downloadDir)
// Assumption: only ever one file here.
for (let file of files) {
await fsp.rename(path.resolve(downloadDir, file), toLocation)
}
}
export interface Paths { export interface Paths {
modelPath: string modelPath: string
imagePath: string imagePath: string
@ -870,8 +686,7 @@ export const doExport = async (
exportFrom: 'dropdown' | 'sidebarButton' | 'commandBar' = 'dropdown' exportFrom: 'dropdown' | 'sidebarButton' | 'commandBar' = 'dropdown'
): Promise<Paths> => { ): Promise<Paths> => {
if (exportFrom === 'dropdown') { if (exportFrom === 'dropdown') {
await page.getByTestId('project-sidebar-toggle').click() await page.getByRole('button', { name: APP_NAME }).click()
const exportMenuButton = page.getByRole('button', { const exportMenuButton = page.getByRole('button', {
name: 'Export current part', name: 'Export current part',
}) })
@ -912,12 +727,25 @@ export const doExport = async (
} }
await expect(page.getByText('Confirm Export')).toBeVisible() 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
if (exportFrom === 'dropdown')
page.on('download', async (download) => {
if (downloadCnt === 0) {
downloadResolve1(download)
}
downloadCnt++
})
await page.getByRole('button', { name: 'Submit command' }).click() await page.getByRole('button', { name: 'Submit command' }).click()
// This usually happens immediately after. If we're too slow we don't
// catch it.
await expect(page.getByText('Exported successfully')).toBeVisible()
if (exportFrom === 'sidebarButton' || exportFrom === 'commandBar') { if (exportFrom === 'sidebarButton' || exportFrom === 'commandBar') {
return { return {
modelPath: '', modelPath: '',
@ -927,12 +755,15 @@ export const doExport = async (
} }
// Handle download // Handle download
const download = await downloadPromise1
const downloadLocationer = (extra = '', isImage = false) => const downloadLocationer = (extra = '', isImage = false) =>
`./e2e/playwright/export-snapshots/${output.type}-${ `./e2e/playwright/export-snapshots/${output.type}-${
'storage' in output ? output.storage : '' 'storage' in output ? output.storage : ''
}${extra}.${isImage ? 'png' : output.type}` }${extra}.${isImage ? 'png' : output.type}`
const downloadLocation = downloadLocationer() const downloadLocation = downloadLocationer()
await download.saveAs(downloadLocation)
if (output.type === 'step') { if (output.type === 'step') {
// stable timestamps for step files // stable timestamps for step files
const fileContents = await fsp.readFile(downloadLocation, 'utf-8') const fileContents = await fsp.readFile(downloadLocation, 'utf-8')
@ -941,12 +772,6 @@ export const doExport = async (
'1970-01-01T00:00:00.0+00:00' '1970-01-01T00:00:00.0+00:00'
) )
await fsp.writeFile(downloadLocation, newFileContents) await fsp.writeFile(downloadLocation, newFileContents)
} else {
// By default all files are downloaded to the same place in playwright
// (declared in src/lib/exportSave)
// To remain consistent with our old web tests, we want to move some downloads
// (images) to another directory.
await moveDownloadedFileTo(page, downloadLocation)
} }
return { return {
@ -973,8 +798,6 @@ export async function tearDown(page: Page, testInfo: TestInfo) {
// It seems it's best to give the browser about 3s to close things // It seems it's best to give the browser about 3s to close things
// It's not super reliable but we have no real other choice for now // It's not super reliable but we have no real other choice for now
await page.waitForTimeout(3000) await page.waitForTimeout(3000)
await testInfo.tronApp?.close()
} }
// settingsOverrides may need to be augmented to take more generic items, // settingsOverrides may need to be augmented to take more generic items,
@ -985,24 +808,12 @@ export async function setup(
testInfo?: TestInfo testInfo?: TestInfo
) { ) {
await context.addInitScript( await context.addInitScript(
async ({ async ({ token, settingsKey, settings, IS_PLAYWRIGHT_KEY }) => {
token,
settingsKey,
settings,
IS_PLAYWRIGHT_KEY,
PLAYWRIGHT_TEST_DIR,
PERSIST_MODELING_CONTEXT,
}) => {
localStorage.clear() localStorage.clear()
localStorage.setItem('TOKEN_PERSIST_KEY', token) localStorage.setItem('TOKEN_PERSIST_KEY', token)
localStorage.setItem('persistCode', ``) localStorage.setItem('persistCode', ``)
localStorage.setItem(
PERSIST_MODELING_CONTEXT,
JSON.stringify({ openPanes: ['code'] })
)
localStorage.setItem(settingsKey, settings) localStorage.setItem(settingsKey, settings)
localStorage.setItem(IS_PLAYWRIGHT_KEY, 'true') localStorage.setItem(IS_PLAYWRIGHT_KEY, 'true')
localStorage.setItem('PLAYWRIGHT_TEST_DIR', PLAYWRIGHT_TEST_DIR)
}, },
{ {
token: secrets.token, token: secrets.token,
@ -1019,8 +830,6 @@ export async function setup(
} as Partial<SaveSettingsPayload>, } as Partial<SaveSettingsPayload>,
}), }),
IS_PLAYWRIGHT_KEY, IS_PLAYWRIGHT_KEY,
PLAYWRIGHT_TEST_DIR: TEST_SETTINGS.app.projectDirectory,
PERSIST_MODELING_CONTEXT,
} }
) )
@ -1039,15 +848,12 @@ export async function setup(
await page.emulateMedia({ reducedMotion: 'reduce' }) await page.emulateMedia({ reducedMotion: 'reduce' })
// Trigger a navigation, since loading file:// doesn't. // Trigger a navigation, since loading file:// doesn't.
// await page.reload() await page.reload()
} }
let electronApp = undefined
let context = undefined
let page = undefined
export async function setupElectron({ export async function setupElectron({
testInfo, testInfo,
folderSetupFn,
cleanProjectDir = true, cleanProjectDir = true,
appSettings, appSettings,
}: { }: {
@ -1070,7 +876,7 @@ export async function setupElectron({
await fsp.mkdir(projectDirName) await fsp.mkdir(projectDirName)
} }
const options = { const electronApp = await electron.launch({
args: ['.', '--no-sandbox'], args: ['.', '--no-sandbox'],
env: { env: {
...process.env, ...process.env,
@ -1080,22 +886,14 @@ export async function setupElectron({
...(process.env.ELECTRON_OVERRIDE_DIST_PATH ...(process.env.ELECTRON_OVERRIDE_DIST_PATH
? { executablePath: process.env.ELECTRON_OVERRIDE_DIST_PATH + 'electron' } ? { executablePath: process.env.ELECTRON_OVERRIDE_DIST_PATH + 'electron' }
: {}), : {}),
} })
const context = electronApp.context()
// Do this once and then reuse window on subsequent calls. const page = await electronApp.firstWindow()
if (!electronApp) { context.on('console', console.log)
electronApp = await electron.launch(options) page.on('console', console.log)
}
if (!context || !page) {
context = electronApp.context()
page = await electronApp.firstWindow()
context.on('console', console.log)
page.on('console', console.log)
}
if (cleanProjectDir) { if (cleanProjectDir) {
const tempSettingsFilePath = path.join(projectDirName, SETTINGS_FILE_NAME) const tempSettingsFilePath = join(projectDirName, SETTINGS_FILE_NAME)
const settingsOverrides = TOML.stringify( const settingsOverrides = TOML.stringify(
appSettings appSettings
? { ? {
@ -1122,7 +920,11 @@ export async function setupElectron({
await fsp.writeFile(tempSettingsFilePath, settingsOverrides) await fsp.writeFile(tempSettingsFilePath, settingsOverrides)
} }
return { electronApp, page, context, dir: projectDirName, options } await folderSetupFn?.(projectDirName)
await setup(context, page)
return { electronApp, page, dir: projectDirName }
} }
function failOnConsoleErrors(page: Page, testInfo?: TestInfo) { function failOnConsoleErrors(page: Page, testInfo?: TestInfo) {
@ -1208,7 +1010,7 @@ export async function createProject({
} }
export function executorInputPath(fileName: string): string { export function executorInputPath(fileName: string): string {
return path.join('src', 'wasm-lib', 'tests', 'executor', 'inputs', fileName) return join('src', 'wasm-lib', 'tests', 'executor', 'inputs', fileName)
} }
export async function doAndWaitForImageDiff( export async function doAndWaitForImageDiff(
@ -1299,12 +1101,3 @@ export function getPixelRGBs(page: Page) {
}) })
} }
} }
export async function pollEditorLinesSelectedLength(page: Page, lines: number) {
return expect
.poll(async () => {
const lines = await page.locator('.cm-activeLine').all()
return lines.length
})
.toBe(lines)
}

View File

@ -1,14 +1,23 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { EngineCommand } from 'lang/std/artifactGraph' import { EngineCommand } from 'lang/std/artifactGraph'
import { uuidv4 } from 'lib/utils' import { uuidv4 } from 'lib/utils'
import { getUtils } from './test-utils' import { getUtils, setup, tearDown } from './test-utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Testing Camera Movement', () => { test.describe('Testing Camera Movement', () => {
test('Can move camera reliably', async ({ page, context, homePage }) => { test('Can move camera reliably', async ({ page, context }) => {
test.skip(process.platform === 'darwin', 'Can move camera reliably')
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openAndClearDebugPanel() await u.openAndClearDebugPanel()
await u.closeKclCodePanel() await u.closeKclCodePanel()
@ -174,7 +183,6 @@ test.describe('Testing Camera Movement', () => {
test('Zoom should be consistent when exiting or entering sketches', async ({ test('Zoom should be consistent when exiting or entering sketches', async ({
page, page,
homePage,
}) => { }) => {
// start new sketch pan and zoom before exiting, when exiting the sketch should stay in the same place // start new sketch pan and zoom before exiting, when exiting the sketch should stay in the same place
// than zoom and pan outside of sketch mode and enter again and it should not change from where it is // than zoom and pan outside of sketch mode and enter again and it should not change from where it is
@ -182,9 +190,9 @@ test.describe('Testing Camera Movement', () => {
test.skip(process.platform !== 'darwin', 'Zoom should be consistent') test.skip(process.platform !== 'darwin', 'Zoom should be consistent')
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await expect( await expect(
@ -336,10 +344,7 @@ test.describe('Testing Camera Movement', () => {
}) })
}) })
test(`Zoom by scroll should not fire while orbiting`, async ({ test(`Zoom by scroll should not fire while orbiting`, async ({ page }) => {
page,
homePage,
}) => {
/** /**
* Currently we only allow zooming by scroll when no other camera movement is happening, * Currently we only allow zooming by scroll when no other camera movement is happening,
* set within cameraMouseDragGuards in cameraControls.ts, * set within cameraMouseDragGuards in cameraControls.ts,
@ -378,7 +383,7 @@ test.describe('Testing Camera Movement', () => {
const expectedOrbitCamZPosition = 64.0 const expectedOrbitCamZPosition = 64.0
await test.step(`Test setup`, async () => { await test.step(`Test setup`, async () => {
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.closeKclCodePanel() await u.closeKclCodePanel()
// This test requires the mouse controls to be set to Solidworks // This test requires the mouse controls to be set to Solidworks
await u.openDebugPanel() await u.openDebugPanel()

View File

@ -1,32 +1,35 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { import { getUtils, setup, tearDown, TEST_COLORS } from './test-utils'
getUtils,
TEST_COLORS,
pollEditorLinesSelectedLength,
} from './test-utils'
import { XOR } from 'lib/utils' import { XOR } from 'lib/utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Testing constraints', () => { test.describe('Testing constraints', () => {
test('Can constrain line length', async ({ page, homePage }) => { test('Can constrain line length', async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-10, -10], %) |> startProfileAt([-10, -10], %)
|> line([20, 0], %) |> line([20, 0], %)
|> line([0, 20], %) |> line([0, 20], %)
|> xLine(-20, %) |> xLine(-20, %)
` `
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
const PUR = 400 / 37.5 //pixeltoUnitRatio const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
@ -38,9 +41,7 @@ test.describe('Testing constraints', () => {
// enter sketch again // enter sketch again
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
await page.waitForTimeout(500) // wait for animation
// Wait for overlays to populate
await page.waitForTimeout(1000)
const startXPx = 500 const startXPx = 500
await page.mouse.move(startXPx + PUR * 15, 250 - PUR * 10) await page.mouse.move(startXPx + PUR * 15, 250 - PUR * 10)
@ -62,48 +63,42 @@ test.describe('Testing constraints', () => {
page.getByRole('button', { name: 'Exit Sketch' }) page.getByRole('button', { name: 'Exit Sketch' })
).toBeVisible() ).toBeVisible()
await page.waitForTimeout(2500) // wait for animation await page.waitForTimeout(500) // wait for animation
// Exit sketch // Exit sketch
await page.mouse.move(startXPx + PUR * 15, 250 - PUR * 10) await page.mouse.move(startXPx + PUR * 15, 250 - PUR * 10)
await expect await page.keyboard.press('Escape')
.poll(async () => { await expect(
await page.keyboard.press('Escape', { delay: 500 }) page.getByRole('button', { name: 'Exit Sketch' })
return page.getByRole('button', { name: 'Exit Sketch' }).isVisible() ).not.toBeVisible()
})
.toBe(true)
}) })
test(`Remove constraints`, async ({ page, homePage }) => { test(`Remove constraints`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 79 `yo = 79
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %, $seg01) |> line([74.36, 130.4], %, $seg01)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> angledLine([segAng(seg01), yo], %) |> angledLine([segAng(seg01), yo], %)
|> line([41.19, 58.97 + 5], %) |> line([41.19, 58.97 + 5], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 120], %) |> startProfileAt([299.05, 120], %)
|> xLine(-385.34, %, $seg_what) |> xLine(-385.34, %, $seg_what)
|> yLine(-170.06, %) |> yLine(-170.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %, $seg01)').click() await page.getByText('line([74.36, 130.4], %, $seg01)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const line3 = await u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`) const line3 = await u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`)
await page.mouse.click(line3.x, line3.y) await page.mouse.click(line3.x, line3.y)
@ -116,8 +111,8 @@ test.describe('Testing constraints', () => {
await page.getByRole('button', { name: 'remove constraints' }).click() await page.getByRole('button', { name: 'remove constraints' }).click()
await page.getByText('line([39.13, 68.63], %)').click() await page.getByText('line([39.13, 68.63], %)').click()
await pollEditorLinesSelectedLength(page, 1)
const activeLinesContent = await page.locator('.cm-activeLine').all() const activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent).toHaveLength(1)
await expect(activeLinesContent[0]).toHaveText('|> line([39.13, 68.63], %)') await expect(activeLinesContent[0]).toHaveText('|> line([39.13, 68.63], %)')
// checking the count of the overlays is a good proxy check that the client sketch scene is in a good state // checking the count of the overlays is a good proxy check that the client sketch scene is in a good state
@ -135,75 +130,43 @@ test.describe('Testing constraints', () => {
}, },
] as const ] as const
for (const { testName, offset } of cases) { for (const { testName, offset } of cases) {
test(`${testName}`, async ({ page, homePage }) => { test(`${testName}`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %, $seg01) |> line([74.36, 130.4], %, $seg01)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> angledLine([segAng(seg01), 78.33], %) |> angledLine([segAng(seg01), 78.33], %)
|> line([51.19, 48.97], %) |> line([51.19, 48.97], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
const isChecked = await createNewVariableCheckbox.isChecked()
const addVariable = testName === 'Add variable'
XOR(isChecked, addVariable) && // XOR because no need to click the checkbox if the state is already correct
(await createNewVariableCheckbox.click())
await page
.getByRole('button', { name: 'Add constraining value' })
.click()
// Wait for the codemod to take effect
await expect(page.locator('.cm-content')).toContainText(`angle: -57,`)
await expect(page.locator('.cm-content')).toContainText(
`offset: ${offset},`
)
await pollEditorLinesSelectedLength(page, 2)
const activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent[0]).toHaveText(
`|> line([74.36, 130.4], %, $seg01)`
)
await expect(activeLinesContent[1]).toHaveText(`}, %)`)
// checking the count of the overlays is a good proxy check that the client sketch scene is in a good state
await expect(page.getByTestId('segment-overlay')).toHaveCount(4)
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %, $seg01)').click() await page.getByText('line([74.36, 130.4], %, $seg01)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Give time for overlays to populate
await page.waitForTimeout(1000)
const [line1, line3] = await Promise.all([ const [line1, line3] = await Promise.all([
u.getSegmentBodyCoords(`[data-overlay-index="${0}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${0}"]`),
u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`),
]) ])
await page.mouse.click(line1.x, line1.y) await page.mouse.click(line1.x, line1.y)
await page.keyboard.up('Shift')
await page.keyboard.down('Shift') await page.keyboard.down('Shift')
await page.waitForTimeout(100)
await page.mouse.click(line3.x, line3.y) await page.mouse.click(line3.x, line3.y)
await page.waitForTimeout(100) await page.waitForTimeout(100) // this wait is needed for webkit - not sure why
await page.keyboard.up('Shift') await page.keyboard.up('Shift')
await page.waitForTimeout(100)
await page await page
.getByRole('button', { .getByRole('button', {
name: 'Length: open menu', name: 'Length: open menu',
@ -231,7 +194,6 @@ test.describe('Testing constraints', () => {
`offset = ${offset},` `offset = ${offset},`
) )
await pollEditorLinesSelectedLength(page, 2)
const activeLinesContent = await page.locator('.cm-activeLine').all() const activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent[0]).toHaveText( await expect(activeLinesContent[0]).toHaveText(
`|> line([74.36, 130.4], %, $seg01)` `|> line([74.36, 130.4], %, $seg01)`
@ -267,37 +229,33 @@ test.describe('Testing constraints', () => {
}, },
] as const ] as const
for (const { testName, value, constraint } of cases) { for (const { testName, value, constraint } of cases) {
test(`${constraint} - ${testName}`, async ({ page, homePage }) => { test(`${constraint} - ${testName}`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %) |> line([74.36, 130.4], %)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> line([9.16, 77.79], %) |> line([9.16, 77.79], %)
|> line([51.19, 48.97], %) |> line([51.19, 48.97], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const [line1, line3] = await Promise.all([ const [line1, line3] = await Promise.all([
u.getSegmentBodyCoords(`[data-overlay-index="${0}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${0}"]`),
u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`),
@ -377,37 +335,33 @@ test.describe('Testing constraints', () => {
}, },
] as const ] as const
for (const { testName, addVariable, value, constraint } of cases) { for (const { testName, addVariable, value, constraint } of cases) {
test(`${constraint} - ${testName}`, async ({ page, homePage }) => { test(`${constraint} - ${testName}`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %) |> line([74.36, 130.4], %)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> line([9.16, 77.79], %) |> line([9.16, 77.79], %)
|> line([51.19, 48.97], %) |> line([51.19, 48.97], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const [line3] = await Promise.all([ const [line3] = await Promise.all([
u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`),
]) ])
@ -418,11 +372,9 @@ test.describe('Testing constraints', () => {
await page.mouse.click(900, 250) await page.mouse.click(900, 250)
} }
await page.keyboard.down('Shift') await page.keyboard.down('Shift')
await page.waitForTimeout(100)
await page.mouse.click(line3.x, line3.y) await page.mouse.click(line3.x, line3.y)
await page.waitForTimeout(100) await page.waitForTimeout(100) // this wait is needed for webkit - not sure why
await page.keyboard.up('Shift') await page.keyboard.up('Shift')
await page.waitForTimeout(100)
await page await page
.getByRole('button', { .getByRole('button', {
name: 'Length: open menu', name: 'Length: open menu',
@ -490,37 +442,33 @@ test.describe('Testing constraints', () => {
}, },
] as const ] as const
for (const { testName, addVariable, value, axisSelect } of cases) { for (const { testName, addVariable, value, axisSelect } of cases) {
test(`${testName}`, async ({ page, homePage }) => { test(`${testName}`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %) |> line([74.36, 130.4], %)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> line([9.16, 77.79], %) |> line([9.16, 77.79], %)
|> line([51.19, 48.97], %) |> line([51.19, 48.97], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const [line1, line3] = await Promise.all([ const [line1, line3] = await Promise.all([
u.getSegmentBodyCoords(`[data-overlay-index="${0}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${0}"]`),
u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`), u.getSegmentBodyCoords(`[data-overlay-index="${2}"]`),
@ -576,7 +524,7 @@ test.describe('Testing constraints', () => {
}) })
} }
}) })
test.describe('Test Angle constraint single selection', () => { test.describe('Test Angle/Length constraint single selection', () => {
const cases = [ const cases = [
{ {
testName: 'Angle - Add variable', testName: 'Angle - Add variable',
@ -590,70 +538,6 @@ test.describe('Testing constraints', () => {
constraint: 'angle', constraint: 'angle',
value: '83, 78.33', value: '83, 78.33',
}, },
] as const
for (const { testName, addVariable, value, constraint } of cases) {
test(`${testName}`, async ({ page, homePage }) => {
await page.addInitScript(async () => {
localStorage.setItem(
'persistCode',
`yo = 5
part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %)
|> line([78.92, -120.11], %)
|> line([9.16, 77.79], %)
|> line([51.19, 48.97], %)
part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %)
|> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)`
)
})
const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const line3 = await u.getSegmentBodyCoords(
`[data-overlay-index="${2}"]`
)
await page.mouse.click(line3.x, line3.y)
await page
.getByRole('button', {
name: 'Length: open menu',
})
.click()
await page.getByTestId('dropdown-constraint-' + constraint).click()
if (!addVariable) {
await page.getByTestId('create-new-variable-checkbox').click()
}
await page
.getByRole('button', { name: 'Add constraining value' })
.click()
const changedCode = `|> angledLine([${value}], %)`
await expect(page.locator('.cm-content')).toContainText(changedCode)
// checking active assures the cursor is where it should be
await expect(page.locator('.cm-activeLine')).toHaveText(changedCode)
// checking the count of the overlays is a good proxy check that the client sketch scene is in a good state
await expect(page.getByTestId('segment-overlay')).toHaveCount(4)
})
}
})
test.describe('Test Length constraint single selection', () => {
const cases = [
{ {
testName: 'Length - Add variable', testName: 'Length - Add variable',
addVariable: true, addVariable: true,
@ -668,17 +552,7 @@ test.describe('Testing constraints', () => {
}, },
] as const ] as const
for (const { testName, addVariable, value, constraint } of cases) { for (const { testName, addVariable, value, constraint } of cases) {
test(`${testName}`, async ({ context, homePage, page }) => { test(`${testName}`, async ({ page }) => {
// constants and locators
const cmdBarKclInput = page
.getByTestId('cmd-bar-arg-value')
.getByRole('textbox')
const cmdBarKclVariableNameInput =
page.getByPlaceholder('Variable name')
const cmdBarSubmitButton = page.getByRole('button', {
name: 'arrow right Continue',
})
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
@ -698,9 +572,9 @@ part002 = startSketchOn('XZ')
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
@ -718,13 +592,11 @@ part002 = startSketchOn('XZ')
await page.getByTestId('dropdown-constraint-' + constraint).click() await page.getByTestId('dropdown-constraint-' + constraint).click()
if (!addVariable) { if (!addVariable) {
await test.step(`Clear the variable input`, async () => { await page.getByTestId('create-new-variable-checkbox').click()
await cmdBarKclVariableNameInput.clear()
await cmdBarKclVariableNameInput.press('Backspace')
})
} }
await expect(cmdBarKclInput).toHaveText('78.33') await page
await cmdBarSubmitButton.click() .getByRole('button', { name: 'Add constraining value' })
.click()
const changedCode = `|> angledLine([${value}], %)` const changedCode = `|> angledLine([${value}], %)`
await expect(page.locator('.cm-content')).toContainText(changedCode) await expect(page.locator('.cm-content')).toContainText(changedCode)
@ -756,37 +628,33 @@ part002 = startSketchOn('XZ')
}, },
] as const ] as const
for (const { codeAfter, constraintName } of cases) { for (const { codeAfter, constraintName } of cases) {
test(`${constraintName}`, async ({ page, homePage }) => { test(`${constraintName}`, async ({ page }) => {
await page.addInitScript(async (customCode) => { await page.addInitScript(async (customCode) => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %) |> line([74.36, 130.4], %)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> line([9.16, 77.79], %) |> line([9.16, 77.79], %)
|> line([51.19, 48.97], %) |> line([51.19, 48.97], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const line1 = await u.getSegmentBodyCoords( const line1 = await u.getSegmentBodyCoords(
`[data-overlay-index="${0}"]` `[data-overlay-index="${0}"]`
) )
@ -805,8 +673,8 @@ part002 = startSketchOn('XZ')
await page.keyboard.up('Shift') await page.keyboard.up('Shift')
// check actives lines // check actives lines
await pollEditorLinesSelectedLength(page, codeAfter.length)
const activeLinesContent = await page.locator('.cm-activeLine').all() const activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent).toHaveLength(codeAfter.length)
const constraintMenuButton = page.getByRole('button', { const constraintMenuButton = page.getByRole('button', {
name: 'Length: open menu', name: 'Length: open menu',
@ -857,36 +725,32 @@ part002 = startSketchOn('XZ')
}, },
] as const ] as const
for (const { codeAfter, constraintName } of cases) { for (const { codeAfter, constraintName } of cases) {
test(`${constraintName}`, async ({ page, homePage }) => { test(`${constraintName}`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %) |> line([74.36, 130.4], %)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> line([9.16, 77.79], %) |> line([9.16, 77.79], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const line1 = await u.getBoundingBox(`[data-overlay-index="${0}"]`) const line1 = await u.getBoundingBox(`[data-overlay-index="${0}"]`)
const line3 = await u.getBoundingBox(`[data-overlay-index="${2}"]`) const line3 = await u.getBoundingBox(`[data-overlay-index="${2}"]`)
@ -913,8 +777,8 @@ part002 = startSketchOn('XZ')
// check there are still 2 cursors (they should stay on the same lines as before constraint was applied) // check there are still 2 cursors (they should stay on the same lines as before constraint was applied)
await expect(page.locator('.cm-cursor')).toHaveCount(2) await expect(page.locator('.cm-cursor')).toHaveCount(2)
// check actives lines // check actives lines
await pollEditorLinesSelectedLength(page, 2)
const activeLinesContent = await page.locator('.cm-activeLine').all() const activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent).toHaveLength(2)
// check both cursors are where they should be after constraint is applied // check both cursors are where they should be after constraint is applied
await expect(activeLinesContent[0]).toHaveText( await expect(activeLinesContent[0]).toHaveText(
@ -938,47 +802,40 @@ part002 = startSketchOn('XZ')
}, },
] as const ] as const
for (const { codeAfter, constraintName, axisClick } of cases) { for (const { codeAfter, constraintName, axisClick } of cases) {
test(`${constraintName}`, async ({ page, homePage }) => { test(`${constraintName}`, async ({ page }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 5 `yo = 5
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> line([74.36, 130.4], %) |> line([74.36, 130.4], %)
|> line([78.92, -120.11], %) |> line([78.92, -120.11], %)
|> line([9.16, 77.79], %) |> line([9.16, 77.79], %)
part002 = startSketchOn('XZ') part002 = startSketchOn('XZ')
|> startProfileAt([299.05, 231.45], %) |> startProfileAt([299.05, 231.45], %)
|> xLine(-425.34, %, $seg_what) |> xLine(-425.34, %, $seg_what)
|> yLine(-264.06, %) |> yLine(-264.06, %)
|> xLine(segLen(seg_what), %) |> xLine(segLen(seg_what), %)
|> lineTo([profileStartX(%), profileStartY(%)], %)` |> lineTo([profileStartX(%), profileStartY(%)], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([74.36, 130.4], %)').click() await page.getByText('line([74.36, 130.4], %)').click()
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
const line3 = await u.getBoundingBox(`[data-overlay-index="${2}"]`) const line3 = await u.getBoundingBox(`[data-overlay-index="${2}"]`)
// select segment and axis by holding down shift // select segment and axis by holding down shift
await page.mouse.click(line3.x - 3, line3.y + 20) await page.mouse.click(line3.x - 3, line3.y + 20)
await page.waitForTimeout(100)
await page.keyboard.down('Shift') await page.keyboard.down('Shift')
await page.waitForTimeout(100) await page.waitForTimeout(100)
await page.mouse.click(axisClick.x, axisClick.y) await page.mouse.click(axisClick.x, axisClick.y)
await page.waitForTimeout(100)
await page.keyboard.up('Shift') await page.keyboard.up('Shift')
await page.waitForTimeout(100)
const constraintMenuButton = page.getByRole('button', { const constraintMenuButton = page.getByRole('button', {
name: 'Length: open menu', name: 'Length: open menu',
}) })
@ -1000,23 +857,21 @@ part002 = startSketchOn('XZ')
test('Horizontally constrained line remains selected after applying constraint', async ({ test('Horizontally constrained line remains selected after applying constraint', async ({
page, page,
homePage,
}) => { }) => {
test.setTimeout(70_000) test.setTimeout(70_000)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XY') `sketch001 = startSketchOn('XY')
|> startProfileAt([-1.05, -1.07], %) |> startProfileAt([-1.05, -1.07], %)
|> line([3.79, 2.68], %, $seg01) |> line([3.79, 2.68], %, $seg01)
|> line([3.13, -2.4], %)` |> line([3.13, -2.4], %)`
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await page.getByText('line([3.79, 2.68], %, $seg01)').click() await page.getByText('line([3.79, 2.68], %, $seg01)').click()
await expect(page.getByRole('button', { name: 'Edit Sketch' })).toBeEnabled( await expect(page.getByRole('button', { name: 'Edit Sketch' })).toBeEnabled(
@ -1024,9 +879,6 @@ part002 = startSketchOn('XZ')
) )
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
// Wait for overlays to populate
await page.waitForTimeout(1000)
await page.waitForTimeout(100) await page.waitForTimeout(100)
const lineBefore = await u.getSegmentBodyCoords( const lineBefore = await u.getSegmentBodyCoords(
`[data-overlay-index="1"]`, `[data-overlay-index="1"]`,
@ -1047,17 +899,11 @@ part002 = startSketchOn('XZ')
name: 'Length: open menu', name: 'Length: open menu',
}) })
.click() .click()
await page.waitForTimeout(500)
await page.getByRole('button', { name: 'Horizontal', exact: true }).click() await page.getByRole('button', { name: 'Horizontal', exact: true }).click()
await page.waitForTimeout(500)
await pollEditorLinesSelectedLength(page, 1)
let activeLinesContent = await page.locator('.cm-activeLine').all() let activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent[0]).toHaveText(`|> xLine(3.13, %)`) await expect(activeLinesContent[0]).toHaveText(`|> xLine(3.13, %)`)
// Wait for code editor to settle.
await page.waitForTimeout(2000)
// If the overlay-angle is updated the THREE.js scene is in a good state // If the overlay-angle is updated the THREE.js scene is in a good state
await expect( await expect(
await page.locator('[data-overlay-index="1"]') await page.locator('[data-overlay-index="1"]')
@ -1067,17 +913,11 @@ part002 = startSketchOn('XZ')
`[data-overlay-index="1"]`, `[data-overlay-index="1"]`,
0 0
) )
expect(
await u.getGreatestPixDiff(lineAfter, TEST_COLORS.BLUE)
).toBeLessThan(3)
const linebb = await u.getBoundingBox('[data-overlay-index="1"]') await page.waitForTimeout(300)
await page.mouse.move(linebb.x, linebb.y, { steps: 25 })
await page.mouse.click(linebb.x, linebb.y)
await expect
.poll(async () => await u.getGreatestPixDiff(lineAfter, TEST_COLORS.BLUE))
.toBeLessThan(3)
await page.waitForTimeout(500)
await page await page
.getByRole('button', { .getByRole('button', {
name: 'Length: open menu', name: 'Length: open menu',
@ -1091,7 +931,6 @@ part002 = startSketchOn('XZ')
await page.getByLabel('length Value').fill('10') await page.getByLabel('length Value').fill('10')
await page.getByRole('button', { name: 'Add constraining value' }).click() await page.getByRole('button', { name: 'Add constraining value' }).click()
await pollEditorLinesSelectedLength(page, 1)
activeLinesContent = await page.locator('.cm-activeLine').all() activeLinesContent = await page.locator('.cm-activeLine').all()
await expect(activeLinesContent[0]).toHaveText(`|> xLine(length001, %)`) await expect(activeLinesContent[0]).toHaveText(`|> xLine(length001, %)`)

View File

@ -1,9 +1,18 @@
import { test, expect } from './zoo-test' import { _test, _expect } from './playwright-deprecated'
import { getUtils } from './test-utils' import { test } from './fixtures/fixtureSetup'
import { getUtils, setup, tearDown } from './test-utils'
import { uuidv4 } from 'lib/utils' import { uuidv4 } from 'lib/utils'
import { TEST_CODE_GIZMO } from './storageStates' import { TEST_CODE_GIZMO } from './storageStates'
test.describe('Testing Gizmo', () => { _test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
_test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
_test.describe('Testing Gizmo', () => {
const cases = [ const cases = [
{ {
testDescription: 'top view', testDescription: 'top view',
@ -48,17 +57,14 @@ test.describe('Testing Gizmo', () => {
expectedCameraTarget, expectedCameraTarget,
testDescription, testDescription,
} of cases) { } of cases) {
test(`check ${testDescription}`, async ({ page, homePage }) => { _test(`check ${testDescription}`, async ({ page, browserName }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript((TEST_CODE_GIZMO) => { await page.addInitScript((TEST_CODE_GIZMO) => {
localStorage.setItem('persistCode', TEST_CODE_GIZMO) localStorage.setItem('persistCode', TEST_CODE_GIZMO)
}, TEST_CODE_GIZMO) }, TEST_CODE_GIZMO)
await page.setViewportSize({ width: 1000, height: 500 })
await page.setBodyDimensions({ width: 1000, height: 500 }) await u.waitForAuthSkipAppStart()
await homePage.goToModelingScene()
await u.waitForPageLoad()
await page.waitForTimeout(100) await page.waitForTimeout(100)
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -111,30 +117,30 @@ test.describe('Testing Gizmo', () => {
await Promise.all([ await Promise.all([
// position // position
expect(page.getByTestId('cam-x-position')).toHaveValue( _expect(page.getByTestId('cam-x-position')).toHaveValue(
expectedCameraPosition.x.toString() expectedCameraPosition.x.toString()
), ),
expect(page.getByTestId('cam-y-position')).toHaveValue( _expect(page.getByTestId('cam-y-position')).toHaveValue(
expectedCameraPosition.y.toString() expectedCameraPosition.y.toString()
), ),
expect(page.getByTestId('cam-z-position')).toHaveValue( _expect(page.getByTestId('cam-z-position')).toHaveValue(
expectedCameraPosition.z.toString() expectedCameraPosition.z.toString()
), ),
// target // target
expect(page.getByTestId('cam-x-target')).toHaveValue( _expect(page.getByTestId('cam-x-target')).toHaveValue(
expectedCameraTarget.x.toString() expectedCameraTarget.x.toString()
), ),
expect(page.getByTestId('cam-y-target')).toHaveValue( _expect(page.getByTestId('cam-y-target')).toHaveValue(
expectedCameraTarget.y.toString() expectedCameraTarget.y.toString()
), ),
expect(page.getByTestId('cam-z-target')).toHaveValue( _expect(page.getByTestId('cam-z-target')).toHaveValue(
expectedCameraTarget.z.toString() expectedCameraTarget.z.toString()
), ),
]) ])
}) })
} }
test('Context menu and popover menu', async ({ page, homePage }) => { _test('Context menu and popover menu', async ({ page }) => {
const testCase = { const testCase = {
testDescription: 'Right view', testDescription: 'Right view',
expectedCameraPosition: { x: 5660.02, y: -152, z: 26 }, expectedCameraPosition: { x: 5660.02, y: -152, z: 26 },
@ -146,9 +152,9 @@ test.describe('Testing Gizmo', () => {
await page.addInitScript((TEST_CODE_GIZMO) => { await page.addInitScript((TEST_CODE_GIZMO) => {
localStorage.setItem('persistCode', TEST_CODE_GIZMO) localStorage.setItem('persistCode', TEST_CODE_GIZMO)
}, TEST_CODE_GIZMO) }, TEST_CODE_GIZMO)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await page.waitForTimeout(100) await page.waitForTimeout(100)
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -190,7 +196,7 @@ test.describe('Testing Gizmo', () => {
const buttonToTest = page.getByRole('button', { const buttonToTest = page.getByRole('button', {
name: testCase.testDescription, name: testCase.testDescription,
}) })
await expect(buttonToTest).toBeVisible() await _expect(buttonToTest).toBeVisible()
await buttonToTest.click() await buttonToTest.click()
// Now assert we've moved to the correct view // Now assert we've moved to the correct view
@ -209,23 +215,23 @@ test.describe('Testing Gizmo', () => {
await Promise.all([ await Promise.all([
// position // position
expect(page.getByTestId('cam-x-position')).toHaveValue( _expect(page.getByTestId('cam-x-position')).toHaveValue(
testCase.expectedCameraPosition.x.toString() testCase.expectedCameraPosition.x.toString()
), ),
expect(page.getByTestId('cam-y-position')).toHaveValue( _expect(page.getByTestId('cam-y-position')).toHaveValue(
testCase.expectedCameraPosition.y.toString() testCase.expectedCameraPosition.y.toString()
), ),
expect(page.getByTestId('cam-z-position')).toHaveValue( _expect(page.getByTestId('cam-z-position')).toHaveValue(
testCase.expectedCameraPosition.z.toString() testCase.expectedCameraPosition.z.toString()
), ),
// target // target
expect(page.getByTestId('cam-x-target')).toHaveValue( _expect(page.getByTestId('cam-x-target')).toHaveValue(
testCase.expectedCameraTarget.x.toString() testCase.expectedCameraTarget.x.toString()
), ),
expect(page.getByTestId('cam-y-target')).toHaveValue( _expect(page.getByTestId('cam-y-target')).toHaveValue(
testCase.expectedCameraTarget.y.toString() testCase.expectedCameraTarget.y.toString()
), ),
expect(page.getByTestId('cam-z-target')).toHaveValue( _expect(page.getByTestId('cam-z-target')).toHaveValue(
testCase.expectedCameraTarget.z.toString() testCase.expectedCameraTarget.z.toString()
), ),
]) ])
@ -236,59 +242,32 @@ test.describe('Testing Gizmo', () => {
const gizmoPopoverButton = page.getByRole('button', { const gizmoPopoverButton = page.getByRole('button', {
name: 'view settings', name: 'view settings',
}) })
await expect(gizmoPopoverButton).toBeVisible() await _expect(gizmoPopoverButton).toBeVisible()
await gizmoPopoverButton.click() await gizmoPopoverButton.click()
await expect(buttonToTest).toBeVisible() await _expect(buttonToTest).toBeVisible()
}) })
}) })
test.describe(`Testing gizmo, fixture-based`, () => { test.describe(`Testing gizmo, fixture-based`, () => {
test('Center on selection from menu', async ({ test('Center on selection from menu', async ({
context, app,
page,
homePage,
cmdBar, cmdBar,
editor, editor,
toolbar, toolbar,
scene, scene,
}) => { }) => {
await context.addInitScript(() => { test.skip(
localStorage.setItem( process.platform === 'win32',
'persistCode', 'Fails on windows in CI, can not be replicated locally on windows.'
` )
const sketch002 = startSketchOn('XZ')
|> startProfileAt([-108.83, -57.48], %)
|> angledLine([0, 105.13], %, $rectangleSegmentA001)
|> angledLine([
segAng(rectangleSegmentA001) - 90,
77.9
], %)
|> angledLine([
segAng(rectangleSegmentA001),
-segLen(rectangleSegmentA001)
], %)
|> close(%)
const sketch001 = startSketchOn('XZ')
|> circle({
center: [818.33, 168.1],
radius: 182.8
}, %)
|> extrude(50, %)
`
)
})
await page.setBodyDimensions({ width: 1000, height: 500 })
await homePage.goToModelingScene()
const u = await getUtils(page)
await u.waitForPageLoad()
await test.step(`Setup`, async () => { await test.step(`Setup`, async () => {
const file = await app.getInputFile('test-circle-extrude.kcl')
await app.initialise(file)
await scene.expectState({ await scene.expectState({
camera: { camera: {
position: [11912.6, -39586.98, 21391.21], position: [4982.21, -23865.37, 13810.64],
target: [11912.6, -635, 3317.49], target: [4982.21, 0, 2737.1],
}, },
}) })
}) })
@ -296,7 +275,7 @@ test.describe(`Testing gizmo, fixture-based`, () => {
await test.step(`Select an edge of this circle`, async () => { await test.step(`Select an edge of this circle`, async () => {
const circleSnippet = const circleSnippet =
'circle({ center: [818.33, 168.1], radius: 182.8 }, %)' 'circle({ center = [318.33, 168.1], radius = 182.8 }, %)'
await moveToCircle() await moveToCircle()
await clickCircle() await clickCircle()
await editor.expectState({ await editor.expectState({
@ -313,8 +292,8 @@ test.describe(`Testing gizmo, fixture-based`, () => {
await test.step(`Verify the camera moved`, async () => { await test.step(`Verify the camera moved`, async () => {
await scene.expectState({ await scene.expectState({
camera: { camera: {
position: [20785.58, -40221.98, 22343.46], position: [0, -23865.37, 11073.53],
target: [20785.58, -1270, 4269.74], target: [0, 0, 0],
}, },
}) })
}) })

View File

@ -1,8 +1,18 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { getUtils } from './test-utils' import { getUtils, setup, tearDown } from './test-utils'
import { TEST_SETTINGS, TEST_SETTINGS_KEY } from './storageStates'
import * as TOML from '@iarna/toml'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Test toggling perspective', () => { test.describe('Test toggling perspective', () => {
test.fixme('via command palette and toggle', async ({ page, homePage }) => { test('via command palette and toggle', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
// Locators and constants // Locators and constants
@ -10,7 +20,7 @@ test.describe('Test toggling perspective', () => {
const screenHeight = 500 const screenHeight = 500
const checkedScreenLocation = { const checkedScreenLocation = {
x: screenWidth * 0.71, x: screenWidth * 0.71,
y: screenHeight * 0.2, y: screenHeight * 0.4,
} }
const backgroundColor: [number, number, number] = [29, 29, 29] const backgroundColor: [number, number, number] = [29, 29, 29]
const xzPlaneColor: [number, number, number] = [82, 55, 96] const xzPlaneColor: [number, number, number] = [82, 55, 96]
@ -30,8 +40,8 @@ test.describe('Test toggling perspective', () => {
}) })
await test.step('Setup', async () => { await test.step('Setup', async () => {
await page.setBodyDimensions({ width: screenWidth, height: screenHeight }) await page.setViewportSize({ width: screenWidth, height: screenHeight })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.closeKclCodePanel() await u.closeKclCodePanel()
await expect await expect
.poll(async () => locationToHaveColor(backgroundColor), { .poll(async () => locationToHaveColor(backgroundColor), {
@ -42,17 +52,11 @@ test.describe('Test toggling perspective', () => {
await expect(projectionToggle).toHaveAttribute('aria-checked', 'true') await expect(projectionToggle).toHaveAttribute('aria-checked', 'true')
}) })
// Extremely wild note: flicking between ortho and persp actually changes
// the orientation of the axis/camera. How can you see this? Well toggle it,
// then refresh. You'll see it doesn't match what we left.
await test.step('Switch to ortho via command palette', async () => { await test.step('Switch to ortho via command palette', async () => {
await commandPaletteButton.click() await commandPaletteButton.click()
await page.waitForTimeout(1000)
await commandOption.click() await commandOption.click()
await page.waitForTimeout(1000)
await orthoOption.click() await orthoOption.click()
await expect(commandToast).toBeVisible() await expect(commandToast).toBeVisible()
await expect(commandToast).not.toBeVisible()
await expect await expect
.poll(async () => locationToHaveColor(xzPlaneColor), { .poll(async () => locationToHaveColor(xzPlaneColor), {
timeout: 5000, timeout: 5000,
@ -63,9 +67,27 @@ test.describe('Test toggling perspective', () => {
}) })
await test.step(`Refresh the page and ensure the stream is loaded in ortho`, async () => { await test.step(`Refresh the page and ensure the stream is loaded in ortho`, async () => {
// In playwright web, the settings set while testing are not persisted because
// the `addInitScript` within `setup` is re-run on page reload
await page.addInitScript(
({ settingsKey, settings }) => {
localStorage.setItem(settingsKey, settings)
},
{
settingsKey: TEST_SETTINGS_KEY,
settings: TOML.stringify({
settings: {
...TEST_SETTINGS,
modeling: {
...TEST_SETTINGS.modeling,
cameraProjection: 'orthographic',
},
},
}),
}
)
await page.reload() await page.reload()
await page.waitForTimeout(1000) await u.waitForAuthSkipAppStart()
await u.closeKclCodePanel()
await expect await expect
.poll(async () => locationToHaveColor(xzPlaneColor), { .poll(async () => locationToHaveColor(xzPlaneColor), {
timeout: 5000, timeout: 5000,

View File

@ -1,30 +1,35 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { getUtils } from './test-utils' import { getUtils, setup, setupElectron, tearDown } from './test-utils'
import { bracket } from 'lib/exampleKcl' import { bracket } from 'lib/exampleKcl'
import * as fsp from 'fs/promises' import * as fsp from 'fs/promises'
import { join } from 'path' import { join } from 'path'
import { FILE_EXT } from 'lib/constants' import { FILE_EXT } from 'lib/constants'
import { UnitLength_type } from '@kittycad/lib/dist/types/src/models' import { UnitLength_type } from '@kittycad/lib/dist/types/src/models'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Testing in-app sample loading', () => { test.describe('Testing in-app sample loading', () => {
/** /**
* Note this test implicitly depends on the KCL sample "car-wheel.kcl", * Note this test implicitly depends on the KCL sample "car-wheel.kcl",
* its title, and its units settings. https://github.com/KittyCAD/kcl-samples/blob/main/car-wheel/car-wheel.kcl * its title, and its units settings. https://github.com/KittyCAD/kcl-samples/blob/main/car-wheel/car-wheel.kcl
*/ */
test('Web: should overwrite current code, cannot create new file', async ({ test('Web: should overwrite current code, cannot create new file', async ({
editor,
context,
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await test.step(`Test setup`, async () => { await test.step(`Test setup`, async () => {
await context.addInitScript((code) => { await page.addInitScript((code) => {
window.localStorage.setItem('persistCode', code) window.localStorage.setItem('persistCode', code)
}, bracket) }, bracket)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
}) })
// Locators and constants // Locators and constants
@ -49,13 +54,13 @@ test.describe('Testing in-app sample loading', () => {
}) })
const warningText = page.getByText('Overwrite current file and units?') const warningText = page.getByText('Overwrite current file and units?')
const confirmButton = page.getByRole('button', { name: 'Submit command' }) const confirmButton = page.getByRole('button', { name: 'Submit command' })
const codeLocator = page.locator('.cm-content')
const unitsToast = (unit: UnitLength_type) => const unitsToast = (unit: UnitLength_type) =>
page.getByText(`Set default unit to "${unit}" for this project`) page.getByText(`Set default unit to "${unit}" for this project`)
await test.step(`Precondition: check the initial code`, async () => { await test.step(`Precondition: check the initial code`, async () => {
await u.openKclCodePanel() await u.openKclCodePanel()
await editor.scrollToText(bracket.split('\n')[0]) await expect(codeLocator).toContainText(bracket.split('\n')[0])
await editor.expectEditor.toContain(bracket.split('\n')[0])
}) })
await test.step(`Load a KCL sample with the command palette`, async () => { await test.step(`Load a KCL sample with the command palette`, async () => {
@ -68,7 +73,7 @@ test.describe('Testing in-app sample loading', () => {
await expect(warningText).toBeVisible() await expect(warningText).toBeVisible()
await confirmButton.click() await confirmButton.click()
await editor.expectEditor.toContain('// ' + newSample.title) await expect(codeLocator).toContainText('// ' + newSample.title)
await expect(unitsToast('in')).toBeVisible() await expect(unitsToast('in')).toBeVisible()
}) })
}) })
@ -81,13 +86,16 @@ test.describe('Testing in-app sample loading', () => {
test( test(
'Desktop: should create new file by default, optionally overwrite', 'Desktop: should create new file by default, optionally overwrite',
{ tag: '@electron' }, { tag: '@electron' },
async ({ editor, context, page }, testInfo) => { async ({ browserName: _ }, testInfo) => {
const { dir } = await context.folderSetupFn(async (dir) => { const { electronApp, page, dir } = await setupElectron({
const bracketDir = join(dir, 'bracket') testInfo,
await fsp.mkdir(bracketDir, { recursive: true }) folderSetupFn: async (dir) => {
await fsp.writeFile(join(bracketDir, 'main.kcl'), bracket, { const bracketDir = join(dir, 'bracket')
encoding: 'utf-8', await fsp.mkdir(bracketDir, { recursive: true })
}) await fsp.writeFile(join(bracketDir, 'main.kcl'), bracket, {
encoding: 'utf-8',
})
},
}) })
const u = await getUtils(page) const u = await getUtils(page)
@ -126,19 +134,19 @@ test.describe('Testing in-app sample loading', () => {
page.getByRole('listitem').filter({ page.getByRole('listitem').filter({
has: page.getByRole('button', { name }), has: page.getByRole('button', { name }),
}) })
const codeLocator = page.locator('.cm-content')
const unitsToast = (unit: UnitLength_type) => const unitsToast = (unit: UnitLength_type) =>
page.getByText(`Set default unit to "${unit}" for this project`) page.getByText(`Set default unit to "${unit}" for this project`)
await test.step(`Test setup`, async () => { await test.step(`Test setup`, async () => {
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await projectCard.click() await projectCard.click()
await u.waitForPageLoad() await u.waitForPageLoad()
}) })
await test.step(`Precondition: check the initial code`, async () => { await test.step(`Precondition: check the initial code`, async () => {
await u.openKclCodePanel() await u.openKclCodePanel()
await editor.scrollToText(bracket.split('\n')[0]) await expect(codeLocator).toContainText(bracket.split('\n')[0])
await editor.expectEditor.toContain(bracket.split('\n')[0])
await u.openFilePanel() await u.openFilePanel()
await expect(projectMenuButton).toContainText('main.kcl') await expect(projectMenuButton).toContainText('main.kcl')
@ -155,7 +163,7 @@ test.describe('Testing in-app sample loading', () => {
}) })
await test.step(`Ensure we made and opened a new file`, async () => { await test.step(`Ensure we made and opened a new file`, async () => {
await editor.expectEditor.toContain('// ' + sampleOne.title) await expect(codeLocator).toContainText('// ' + sampleOne.title)
await expect(newlyCreatedFile(sampleOne.file)).toBeVisible() await expect(newlyCreatedFile(sampleOne.file)).toBeVisible()
await expect(projectMenuButton).toContainText(sampleOne.file) await expect(projectMenuButton).toContainText(sampleOne.file)
await expect(unitsToast('in')).toBeVisible() await expect(unitsToast('in')).toBeVisible()
@ -174,7 +182,7 @@ test.describe('Testing in-app sample loading', () => {
}) })
await test.step(`Ensure we overwrote the current file without navigating`, async () => { await test.step(`Ensure we overwrote the current file without navigating`, async () => {
await editor.expectEditor.toContain('// ' + sampleTwo.title) await expect(codeLocator).toContainText('// ' + sampleTwo.title)
await test.step(`Check actual file contents`, async () => { await test.step(`Check actual file contents`, async () => {
await expect await expect
.poll(async () => { .poll(async () => {
@ -190,6 +198,8 @@ test.describe('Testing in-app sample loading', () => {
await expect(projectMenuButton).toContainText(sampleOne.file) await expect(projectMenuButton).toContainText(sampleOne.file)
await expect(unitsToast('mm')).toBeVisible() await expect(unitsToast('mm')).toBeVisible()
}) })
await electronApp.close()
} }
) )
}) })

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,24 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { commonPoints, getUtils } from './test-utils' import { commonPoints, getUtils, setup, tearDown } from './test-utils'
import { Coords2d } from 'lang/std/sketch' import { Coords2d } from 'lang/std/sketch'
import { KCL_DEFAULT_LENGTH } from 'lib/constants' import { KCL_DEFAULT_LENGTH } from 'lib/constants'
import { uuidv4 } from 'lib/utils' import { uuidv4 } from 'lib/utils'
test.beforeEach(async ({ context, page }, testInfo) => {
await setup(context, page, testInfo)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Testing selections', () => { test.describe('Testing selections', () => {
test.setTimeout(90_000) test.setTimeout(90_000)
test( test(
'Selections work on fresh and edited sketch', 'Selections work on fresh and edited sketch',
{ tag: ['@skipWin'] }, { tag: ['@skipWin'] },
async ({ page, homePage }) => { async ({ page }) => {
// Skip on windows its being weird. // Skip on windows its being weird.
test.skip(process.platform === 'win32', 'Skip on windows') test.skip(process.platform === 'win32', 'Skip on windows')
@ -19,9 +27,9 @@ test.describe('Testing selections', () => {
// source ranges are wrong, hovers won't work // source ranges are wrong, hovers won't work
const u = await getUtils(page) const u = await getUtils(page)
const PUR = 400 / 37.5 //pixeltoUnitRatio const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
const yAxisClick = () => const yAxisClick = () =>
@ -71,31 +79,31 @@ test.describe('Testing selections', () => {
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10) await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt(${commonPoints.startAt}, %)`) |> startProfileAt(${commonPoints.startAt}, %)`)
await page.waitForTimeout(100) await page.waitForTimeout(100)
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10) await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt(${commonPoints.startAt}, %) |> startProfileAt(${commonPoints.startAt}, %)
|> xLine(${commonPoints.num1}, %)`) |> xLine(${commonPoints.num1}, %)`)
await page.waitForTimeout(100) await page.waitForTimeout(100)
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20) await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt(${commonPoints.startAt}, %) |> startProfileAt(${commonPoints.startAt}, %)
|> xLine(${commonPoints.num1}, %) |> xLine(${commonPoints.num1}, %)
|> yLine(${commonPoints.num1 + 0.01}, %)`) |> yLine(${commonPoints.num1 + 0.01}, %)`)
await page.waitForTimeout(100) await page.waitForTimeout(100)
await page.mouse.click(startXPx, 500 - PUR * 20) await page.mouse.click(startXPx, 500 - PUR * 20)
await expect(page.locator('.cm-content')) await expect(page.locator('.cm-content'))
.toHaveText(`sketch001 = startSketchOn('XZ') .toHaveText(`sketch001 = startSketchOn('XZ')
|> startProfileAt(${commonPoints.startAt}, %) |> startProfileAt(${commonPoints.startAt}, %)
|> xLine(${commonPoints.num1}, %) |> xLine(${commonPoints.num1}, %)
|> yLine(${commonPoints.num1 + 0.01}, %) |> yLine(${commonPoints.num1 + 0.01}, %)
|> xLine(${commonPoints.num2 * -1}, %)`) |> xLine(${commonPoints.num2 * -1}, %)`)
// deselect line tool // deselect line tool
await page.getByRole('button', { name: 'line Line', exact: true }).click() await page.getByRole('button', { name: 'line Line', exact: true }).click()
@ -256,78 +264,78 @@ test.describe('Testing selections', () => {
} }
) )
test('Solids should be select and deletable', async ({ page, homePage }) => { test('Solids should be select and deletable', async ({ page }) => {
test.setTimeout(90_000) test.setTimeout(90_000)
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([-79.26, 95.04], %) |> startProfileAt([-79.26, 95.04], %)
|> line([112.54, 127.64], %, $seg02) |> line([112.54, 127.64], %, $seg02)
|> line([170.36, -121.61], %, $seg01) |> line([170.36, -121.61], %, $seg01)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(50, sketch001) extrude001 = extrude(50, sketch001)
sketch005 = startSketchOn(extrude001, 'END') sketch005 = startSketchOn(extrude001, 'END')
|> startProfileAt([23.24, 136.52], %) |> startProfileAt([23.24, 136.52], %)
|> line([-8.44, 36.61], %) |> line([-8.44, 36.61], %)
|> line([49.4, 2.05], %) |> line([49.4, 2.05], %)
|> line([29.69, -46.95], %) |> line([29.69, -46.95], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
sketch003 = startSketchOn(extrude001, seg01) sketch003 = startSketchOn(extrude001, seg01)
|> startProfileAt([21.23, 17.81], %) |> startProfileAt([21.23, 17.81], %)
|> line([51.97, 21.32], %) |> line([51.97, 21.32], %)
|> line([4.07, -22.75], %) |> line([4.07, -22.75], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
sketch002 = startSketchOn(extrude001, seg02) sketch002 = startSketchOn(extrude001, seg02)
|> startProfileAt([-100.54, 16.99], %) |> startProfileAt([-100.54, 16.99], %)
|> line([0, 20.03], %) |> line([0, 20.03], %)
|> line([62.61, 0], %, $seg03) |> line([62.61, 0], %, $seg03)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude002 = extrude(50, sketch002) extrude002 = extrude(50, sketch002)
sketch004 = startSketchOn(extrude002, seg03) sketch004 = startSketchOn(extrude002, seg03)
|> startProfileAt([57.07, 134.77], %) |> startProfileAt([57.07, 134.77], %)
|> line([-4.72, 22.84], %) |> line([-4.72, 22.84], %)
|> line([28.8, 6.71], %) |> line([28.8, 6.71], %)
|> line([9.19, -25.33], %) |> line([9.19, -25.33], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude003 = extrude(20, sketch004) extrude003 = extrude(20, sketch004)
pipeLength = 40 pipeLength = 40
pipeSmallDia = 10 pipeSmallDia = 10
pipeLargeDia = 20 pipeLargeDia = 20
thickness = 0.5 thickness = 0.5
part009 = startSketchOn('XY') part009 = startSketchOn('XY')
|> startProfileAt([pipeLargeDia - (thickness / 2), 38], %) |> startProfileAt([pipeLargeDia - (thickness / 2), 38], %)
|> line([thickness, 0], %) |> line([thickness, 0], %)
|> line([0, -1], %) |> line([0, -1], %)
|> angledLineToX({ |> angledLineToX({
angle = 60, angle = 60,
to = pipeSmallDia + thickness to = pipeSmallDia + thickness
}, %) }, %)
|> line([0, -pipeLength], %) |> line([0, -pipeLength], %)
|> angledLineToX({ |> angledLineToX({
angle = -60, angle = -60,
to = pipeLargeDia + thickness to = pipeLargeDia + thickness
}, %) }, %)
|> line([0, -1], %) |> line([0, -1], %)
|> line([-thickness, 0], %) |> line([-thickness, 0], %)
|> line([0, 1], %) |> line([0, 1], %)
|> angledLineToX({ angle = 120, to = pipeSmallDia }, %) |> angledLineToX({ angle = 120, to = pipeSmallDia }, %)
|> line([0, pipeLength], %) |> line([0, pipeLength], %)
|> angledLineToX({ angle = 60, to = pipeLargeDia }, %) |> angledLineToX({ angle = 60, to = pipeLargeDia }, %)
|> close(%) |> close(%)
rev = revolve({ axis: 'y' }, part009) rev = revolve({ axis = 'y' }, part009)
` `
) )
}, KCL_DEFAULT_LENGTH) }, KCL_DEFAULT_LENGTH)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await page.goto('/')
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
@ -387,29 +395,29 @@ test.describe('Testing selections', () => {
`extrude001 = extrude(50, sketch001)` `extrude001 = extrude(50, sketch001)`
) )
await expect(u.codeLocator).toContainText(`sketch005 = startSketchOn({ await expect(u.codeLocator).toContainText(`sketch005 = startSketchOn({
plane = { plane = {
origin = { x = 0, y = -50, z = 0 }, origin = { x = 0, y = -50, z = 0 },
x_axis = { x = 1, y = 0, z = 0 }, x_axis = { x = 1, y = 0, z = 0 },
y_axis = { x = 0, y = 0, z = 1 }, y_axis = { x = 0, y = 0, z = 1 },
z_axis = { x = 0, y = -1, z = 0 } z_axis = { x = 0, y = -1, z = 0 }
} }
})`) })`)
await expect(u.codeLocator).toContainText(`sketch003 = startSketchOn({ await expect(u.codeLocator).toContainText(`sketch003 = startSketchOn({
plane = { plane = {
origin = { x = 116.53, y = 0, z = 163.25 }, origin = { x = 116.53, y = 0, z = 163.25 },
x_axis = { x = -0.81, y = 0, z = 0.58 }, x_axis = { x = -0.81, y = 0, z = 0.58 },
y_axis = { x = 0, y = -1, z = 0 }, y_axis = { x = 0, y = -1, z = 0 },
z_axis = { x = 0.58, y = 0, z = 0.81 } z_axis = { x = 0.58, y = 0, z = 0.81 }
} }
})`) })`)
await expect(u.codeLocator).toContainText(`sketch002 = startSketchOn({ await expect(u.codeLocator).toContainText(`sketch002 = startSketchOn({
plane = { plane = {
origin = { x = -91.74, y = 0, z = 80.89 }, origin = { x = -91.74, y = 0, z = 80.89 },
x_axis = { x = -0.66, y = 0, z = -0.75 }, x_axis = { x = -0.66, y = 0, z = -0.75 },
y_axis = { x = 0, y = -1, z = 0 }, y_axis = { x = 0, y = -1, z = 0 },
z_axis = { x = -0.75, y = 0, z = 0.66 } z_axis = { x = -0.75, y = 0, z = 0.66 }
} }
})`) })`)
// DELETE SOLID 2D // DELETE SOLID 2D
await page.mouse.click(solid2d.x, solid2d.y) await page.mouse.click(solid2d.x, solid2d.y)
@ -425,32 +433,31 @@ test.describe('Testing selections', () => {
}) })
test("Deleting solid that the AST mod can't handle results in a toast message", async ({ test("Deleting solid that the AST mod can't handle results in a toast message", async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([-79.26, 95.04], %) |> startProfileAt([-79.26, 95.04], %)
|> line([112.54, 127.64], %, $seg02) |> line([112.54, 127.64], %, $seg02)
|> line([170.36, -121.61], %, $seg01) |> line([170.36, -121.61], %, $seg01)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(50, sketch001) extrude001 = extrude(50, sketch001)
launderExtrudeThroughVar = extrude001 launderExtrudeThroughVar = extrude001
sketch002 = startSketchOn(launderExtrudeThroughVar, seg02) sketch002 = startSketchOn(launderExtrudeThroughVar, seg02)
|> startProfileAt([-100.54, 16.99], %) |> startProfileAt([-100.54, 16.99], %)
|> line([0, 20.03], %) |> line([0, 20.03], %)
|> line([62.61, 0], %, $seg03) |> line([62.61, 0], %, $seg03)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
` `
) )
}, KCL_DEFAULT_LENGTH) }, KCL_DEFAULT_LENGTH)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await page.goto('/')
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]', 10_000) await u.expectCmdLog('[data-message-type="execution-done"]', 10_000)
@ -490,38 +497,37 @@ test.describe('Testing selections', () => {
}) })
test('Hovering over 3d features highlights code, clicking puts the cursor in the right place and sends selection id to engine', async ({ test('Hovering over 3d features highlights code, clicking puts the cursor in the right place and sends selection id to engine', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async (KCL_DEFAULT_LENGTH) => { await page.addInitScript(async (KCL_DEFAULT_LENGTH) => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`part001 = startSketchOn('XZ') `part001 = startSketchOn('XZ')
|> startProfileAt([20, 0], %) |> startProfileAt([20, 0], %)
|> line([7.13, 4 + 0], %) |> line([7.13, 4 + 0], %)
|> angledLine({ angle = 3 + 0, length = 3.14 + 0 }, %) |> angledLine({ angle = 3 + 0, length = 3.14 + 0 }, %)
|> lineTo([20.14 + 0, -0.14 + 0], %) |> lineTo([20.14 + 0, -0.14 + 0], %)
|> xLineTo(29 + 0, %) |> xLineTo(29 + 0, %)
|> yLine(-3.14 + 0, %, $a) |> yLine(-3.14 + 0, %, $a)
|> xLine(1.63, %) |> xLine(1.63, %)
|> angledLineOfXLength({ angle = 3 + 0, length = 3.14 }, %) |> angledLineOfXLength({ angle = 3 + 0, length = 3.14 }, %)
|> angledLineOfYLength({ angle = 30, length = 3 + 0 }, %) |> angledLineOfYLength({ angle = 30, length = 3 + 0 }, %)
|> angledLineToX({ angle = 22.14 + 0, to = 12 }, %) |> angledLineToX({ angle = 22.14 + 0, to = 12 }, %)
|> angledLineToY({ angle = 30, to = 11.14 }, %) |> angledLineToY({ angle = 30, to = 11.14 }, %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle = 3.14, angle = 3.14,
intersectTag = a, intersectTag = a,
offset = 0 offset = 0
}, %) }, %)
|> tangentialArcTo([13.14 + 0, 13.14], %) |> tangentialArcTo([13.14 + 0, 13.14], %)
|> close(%) |> close(%)
|> extrude(5 + 7, %) |> extrude(5 + 7, %)
` `
) )
}, KCL_DEFAULT_LENGTH) }, KCL_DEFAULT_LENGTH)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -644,7 +650,7 @@ test.describe('Testing selections', () => {
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'flatExtrusionFace', 'flatExtrusionFace',
flatExtrusionFace, flatExtrusionFace,
`angledLineThatIntersects({angle:3.14,intersectTag:a,offset:0},%)extrude(5+7,%)`, `angledLineThatIntersects({angle=3.14,intersectTag=a,offset=0},%)extrude(5+7,%)`,
'}, %)' '}, %)'
) )
@ -701,19 +707,19 @@ test.describe('Testing selections', () => {
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'straightSegmentEdge', 'straightSegmentEdge',
straightSegmentEdge, straightSegmentEdge,
`angledLineToY({angle:30,to:11.14},%)`, `angledLineToY({angle=30,to=11.14},%)`,
'angledLineToY({ angle: 30, to: 11.14 }, %)' 'angledLineToY({ angle = 30, to = 11.14 }, %)'
) )
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'straightSegmentOppositeEdge', 'straightSegmentOppositeEdge',
straightSegmentOppositeEdge, straightSegmentOppositeEdge,
`angledLineToY({angle:30,to:11.14},%)`, `angledLineToY({angle=30,to=11.14},%)`,
'angledLineToY({ angle: 30, to: 11.14 }, %)' 'angledLineToY({ angle = 30, to = 11.14 }, %)'
) )
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'straightSegmentAdjacentEdge', 'straightSegmentAdjacentEdge',
straightSegmentAdjacentEdge, straightSegmentAdjacentEdge,
`angledLineThatIntersects({angle:3.14,intersectTag:a,offset:0},%)`, `angledLineThatIntersects({angle=3.14,intersectTag=a,offset=0},%)`,
'}, %)' '}, %)'
) )
@ -721,29 +727,29 @@ test.describe('Testing selections', () => {
await u.removeCurrentCode() await u.removeCurrentCode()
await u.codeLocator.fill(`sketch001 = startSketchOn('XZ') await u.codeLocator.fill(`sketch001 = startSketchOn('XZ')
|> startProfileAt([75.8, 317.2], %) // [$startCapTag, $EndCapTag] |> startProfileAt([75.8, 317.2], %) // [$startCapTag, $EndCapTag]
|> angledLine([0, 268.43], %, $rectangleSegmentA001) |> angledLine([0, 268.43], %, $rectangleSegmentA001)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA001) - 90, segAng(rectangleSegmentA001) - 90,
217.26 217.26
], %, $seg01) ], %, $seg01)
|> angledLine([ |> angledLine([
segAng(rectangleSegmentA001), segAng(rectangleSegmentA001),
-segLen(rectangleSegmentA001) -segLen(rectangleSegmentA001)
], %, $yo) ], %, $yo)
|> lineTo([profileStartX(%), profileStartY(%)], %, $seg02) |> lineTo([profileStartX(%), profileStartY(%)], %, $seg02)
|> close(%) |> close(%)
extrude001 = extrude(100, sketch001) extrude001 = extrude(100, sketch001)
|> chamfer({ |> chamfer({
length = 30, length = 30,
tags = [ tags = [
seg01, seg01,
getNextAdjacentEdge(yo), getNextAdjacentEdge(yo),
getNextAdjacentEdge(seg02), getNextAdjacentEdge(seg02),
getOppositeEdge(seg01) getOppositeEdge(seg01)
] ]
}, %) }, %)
`) `)
await expect( await expect(
page.getByTestId('model-state-indicator-execution-done') page.getByTestId('model-state-indicator-execution-done')
).toBeVisible() ).toBeVisible()
@ -780,14 +786,14 @@ test.describe('Testing selections', () => {
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'oppositeChamfer', 'oppositeChamfer',
oppositeChamfer, oppositeChamfer,
`angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)chamfer({length:30,tags:[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`, `angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)chamfer({length=30,tags=[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`,
'}, %)' '}, %)'
) )
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'baseChamfer', 'baseChamfer',
baseChamfer, baseChamfer,
`angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)chamfer({length:30,tags:[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`, `angledLine([segAng(rectangleSegmentA001)-90,217.26],%,$seg01)chamfer({length=30,tags=[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`,
'}, %)' '}, %)'
) )
@ -818,58 +824,52 @@ test.describe('Testing selections', () => {
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'adjacentChamfer1', 'adjacentChamfer1',
adjacentChamfer1, adjacentChamfer1,
`lineTo([profileStartX(%),profileStartY(%)],%,$seg02)chamfer({length:30,tags:[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`, `lineTo([profileStartX(%),profileStartY(%)],%,$seg02)chamfer({length=30,tags=[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`,
'}, %)' '}, %)'
) )
await checkCodeAtHoverPosition( await checkCodeAtHoverPosition(
'adjacentChamfer2', 'adjacentChamfer2',
adjacentChamfer2, adjacentChamfer2,
`angledLine([segAng(rectangleSegmentA001),-segLen(rectangleSegmentA001)],%,$yo)chamfer({length:30,tags:[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`, `angledLine([segAng(rectangleSegmentA001),-segLen(rectangleSegmentA001)],%,$yo)chamfer({length=30,tags=[seg01,getNextAdjacentEdge(yo),getNextAdjacentEdge(seg02),getOppositeEdge(seg01)]},%)`,
'}, %)' '}, %)'
) )
}) })
test("Extrude button should be disabled if there's no extrudable geometry when nothing is selected", async ({ test("Extrude button should be disabled if there's no extrudable geometry when nothing is selected", async ({
page, page,
editor,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([3.29, 7.86], %) |> startProfileAt([3.29, 7.86], %)
|> line([2.48, 2.44], %) |> line([2.48, 2.44], %)
|> line([2.66, 1.17], %) |> line([2.66, 1.17], %)
|> line([3.75, 0.46], %) |> line([3.75, 0.46], %)
|> line([4.99, -0.46], %, $seg01) |> line([4.99, -0.46], %, $seg01)
|> line([3.3, -2.12], %) |> line([3.3, -2.12], %)
|> line([2.16, -3.33], %) |> line([2.16, -3.33], %)
|> line([0.85, -3.08], %) |> line([0.85, -3.08], %)
|> line([-0.18, -3.36], %) |> line([-0.18, -3.36], %)
|> line([-3.86, -2.73], %) |> line([-3.86, -2.73], %)
|> line([-17.67, 0.85], %) |> line([-17.67, 0.85], %)
|> close(%) |> close(%)
extrude001 = extrude(10, sketch001) extrude001 = extrude(10, sketch001)
` `
) )
}) })
await page.setViewportSize({ width: 1000, height: 500 })
await page.setBodyDimensions({ width: 1200, height: 500 }) await u.waitForAuthSkipAppStart()
await homePage.goToModelingScene()
await u.waitForPageLoad()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
const selectUnExtrudable = async () => { const selectUnExtrudable = () =>
await editor.scrollToText(`line([4.99, -0.46], %, $seg01)`) page.getByText(`line([4.99, -0.46], %, $seg01)`).click()
await page.getByText(`line([4.99, -0.46], %, $seg01)`).click()
}
const clickEmpty = () => page.mouse.click(700, 460) const clickEmpty = () => page.mouse.click(700, 460)
await selectUnExtrudable() await selectUnExtrudable()
// expect extrude button to be disabled // expect extrude button to be disabled
@ -879,18 +879,17 @@ test.describe('Testing selections', () => {
// expect active line to contain nothing // expect active line to contain nothing
await expect(page.locator('.cm-activeLine')).toHaveText('') await expect(page.locator('.cm-activeLine')).toHaveText('')
// and extrude to still be disabled // and extrude to still be disabled
await expect(page.getByRole('button', { name: 'Extrude' })).toBeDisabled() await expect(page.getByRole('button', { name: 'Extrude' })).toBeDisabled()
const codeToAdd = `${await u.codeLocator.allInnerTexts()} const codeToAdd = `${await u.codeLocator.allInnerTexts()}
sketch002 = startSketchOn(extrude001, $seg01) sketch002 = startSketchOn(extrude001, $seg01)
|> startProfileAt([-12.94, 6.6], %) |> startProfileAt([-12.94, 6.6], %)
|> line([2.45, -0.2], %) |> line([2.45, -0.2], %)
|> line([-2, -1.25], %) |> line([-2, -1.25], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
` `
await u.codeLocator.fill(codeToAdd) await u.codeLocator.fill(codeToAdd)
await selectUnExtrudable() await selectUnExtrudable()
@ -905,23 +904,23 @@ test.describe('Testing selections', () => {
).not.toBeDisabled() ).not.toBeDisabled()
}) })
test('Fillet button states test', async ({ page, homePage }) => { test('Fillet button states test', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([-5, -5], %) |> startProfileAt([-5, -5], %)
|> line([0, 10], %) |> line([0, 10], %)
|> line([10, 0], %) |> line([10, 0], %)
|> line([0, -10], %) |> line([0, -10], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)` |> close(%)`
) )
}) })
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
@ -938,7 +937,7 @@ test.describe('Testing selections', () => {
// test fillet button with the body in the scene // test fillet button with the body in the scene
const codeToAdd = `${await u.codeLocator.allInnerTexts()} const codeToAdd = `${await u.codeLocator.allInnerTexts()}
extrude001 = extrude(10, sketch001)` extrude001 = extrude(10, sketch001)`
await u.codeLocator.clear() await u.codeLocator.clear()
await u.codeLocator.fill(codeToAdd) await u.codeLocator.fill(codeToAdd)
await selectSegment() await selectSegment()
@ -959,7 +958,6 @@ test.describe('Testing selections', () => {
test('Testing selections (and hovers) work on sketches when NOT in sketch mode', async ({ test('Testing selections (and hovers) work on sketches when NOT in sketch mode', async ({
page, page,
homePage,
}) => { }) => {
const cases = [ const cases = [
{ {
@ -980,21 +978,21 @@ test.describe('Testing selections', () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`yo = 79 `yo = 79
part001 = startSketchOn('XZ') part001 = startSketchOn('XZ')
|> startProfileAt([-7.54, -26.74], %) |> startProfileAt([-7.54, -26.74], %)
|> ${cases[0].expectedCode} |> ${cases[0].expectedCode}
|> line([-3.19, -138.43], %) |> line([-3.19, -138.43], %)
|> ${cases[1].expectedCode} |> ${cases[1].expectedCode}
|> line([41.19, 28.97 + 5], %) |> line([41.19, 28.97 + 5], %)
|> ${cases[2].expectedCode}` |> ${cases[2].expectedCode}`
) )
}, },
{ cases } { cases }
) )
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openAndClearDebugPanel() await u.openAndClearDebugPanel()
await u.sendCustomCmd({ await u.sendCustomCmd({
@ -1027,25 +1025,24 @@ test.describe('Testing selections', () => {
}) })
test("Hovering and selection of extruded faces works, and is not overridden shortly after user's click", async ({ test("Hovering and selection of extruded faces works, and is not overridden shortly after user's click", async ({
page, page,
homePage,
}) => { }) => {
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([-79.26, 95.04], %) |> startProfileAt([-79.26, 95.04], %)
|> line([112.54, 127.64], %) |> line([112.54, 127.64], %)
|> line([170.36, -121.61], %, $seg01) |> line([170.36, -121.61], %, $seg01)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)
extrude001 = extrude(50, sketch001) extrude001 = extrude(50, sketch001)
` `
) )
}) })
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openAndClearDebugPanel() await u.openAndClearDebugPanel()
await u.sendCustomCmd({ await u.sendCustomCmd({
@ -1128,7 +1125,6 @@ test.describe('Testing selections', () => {
}) })
test("Various pipe expressions should and shouldn't allow edit and or extrude", async ({ test("Various pipe expressions should and shouldn't allow edit and or extrude", async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
const selectionsSnippets = { const selectionsSnippets = {
@ -1147,46 +1143,46 @@ test.describe('Testing selections', () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`part001 = startSketchOn('XZ') `part001 = startSketchOn('XZ')
${extrudeAndEditBlocked} ${extrudeAndEditBlocked}
|> line([25.96, 2.93], %) |> line([25.96, 2.93], %)
|> line([5.25, -5.72], %) |> line([5.25, -5.72], %)
|> line([-2.01, -10.35], %) |> line([-2.01, -10.35], %)
|> line([-27.65, -2.78], %) |> line([-27.65, -2.78], %)
|> close(%) |> close(%)
|> extrude(5, %) |> extrude(5, %)
sketch002 = startSketchOn('XZ') sketch002 = startSketchOn('XZ')
${extrudeAndEditAllowed} ${extrudeAndEditAllowed}
|> line([10.32, 6.47], %) |> line([10.32, 6.47], %)
|> line([9.71, -6.16], %) |> line([9.71, -6.16], %)
|> line([-3.08, -9.86], %) |> line([-3.08, -9.86], %)
|> line([-12.02, -1.54], %) |> line([-12.02, -1.54], %)
|> close(%) |> close(%)
sketch003 = startSketchOn('XZ') sketch003 = startSketchOn('XZ')
${editOnly} ${editOnly}
|> line([27.55, -1.65], %) |> line([27.55, -1.65], %)
|> line([4.95, -8], %) |> line([4.95, -8], %)
|> line([-20.38, -10.12], %) |> line([-20.38, -10.12], %)
|> line([-15.79, 17.08], %) |> line([-15.79, 17.08], %)
fn yohey = (pos) => { fn yohey = (pos) => {
sketch004 = startSketchOn('XZ') sketch004 = startSketchOn('XZ')
${extrudeAndEditBlockedInFunction} ${extrudeAndEditBlockedInFunction}
|> line([27.55, -1.65], %) |> line([27.55, -1.65], %)
|> line([4.95, -10.53], %) |> line([4.95, -10.53], %)
|> line([-20.38, -8], %) |> line([-20.38, -8], %)
|> line([-15.79, 17.08], %) |> line([-15.79, 17.08], %)
return '' return ''
} }
yohey([15.79, -34.6]) yohey([15.79, -34.6])
` `
) )
}, },
selectionsSnippets selectionsSnippets
) )
await page.setBodyDimensions({ width: 1200, height: 1000 }) await page.setViewportSize({ width: 1200, height: 1000 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -1226,7 +1222,6 @@ test.describe('Testing selections', () => {
test('Deselecting line tool should mean nothing happens on click', async ({ test('Deselecting line tool should mean nothing happens on click', async ({
page, page,
homePage,
}) => { }) => {
/** /**
* If the line tool is clicked when the state is 'No Points' it will exit Sketch mode. * If the line tool is clicked when the state is 'No Points' it will exit Sketch mode.
@ -1235,9 +1230,9 @@ test.describe('Testing selections', () => {
* To continue to test this workflow, we now enter sketch mode and place a single point before exiting the line tool. * To continue to test this workflow, we now enter sketch mode and place a single point before exiting the line tool.
*/ */
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await expect( await expect(

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,29 @@
import { test, expect, Page } from './zoo-test' import { test, expect, Page } from '@playwright/test'
import { getUtils, createProject } from './test-utils' import {
getUtils,
setup,
tearDown,
setupElectron,
createProject,
} from './test-utils'
import { join } from 'path' import { join } from 'path'
import fs from 'fs' import fs from 'fs'
test.beforeEach(async ({ context, page }) => {
await setup(context, page)
})
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test.describe('Text-to-CAD tests', () => { test.describe('Text-to-CAD tests', () => {
test('basic lego happy case', async ({ page, homePage }) => { test('basic lego happy case', async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
await test.step('Set up', async () => { await test.step('Set up', async () => {
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
}) })
await sendPromptFromCommandBar(page, 'a 2x4 lego') await sendPromptFromCommandBar(page, 'a 2x4 lego')
@ -30,17 +43,25 @@ test.describe('Text-to-CAD tests', () => {
const successToastMessage = page.getByText(`Text-to-CAD successful`) const successToastMessage = page.getByText(`Text-to-CAD successful`)
await expect(successToastMessage).toBeVisible({ timeout: 15000 }) await expect(successToastMessage).toBeVisible({ timeout: 15000 })
// Hit accept. await expect(page.getByText('Copied')).not.toBeVisible()
// Hit copy to clipboard.
const copyToClipboardButton = page.getByRole('button', { const copyToClipboardButton = page.getByRole('button', {
name: 'Accept', name: 'Copy to clipboard',
}) })
await expect(copyToClipboardButton).toBeVisible() await expect(copyToClipboardButton).toBeVisible()
await copyToClipboardButton.click() await copyToClipboardButton.click()
// Expect the code to be copied.
await expect(page.getByText('Copied')).toBeVisible()
// Click in the code editor. // Click in the code editor.
await page.locator('.cm-content').click() await page.locator('.cm-content').click()
// Paste the code.
await page.keyboard.press('ControlOrMeta+KeyV')
// Expect the code to be pasted. // Expect the code to be pasted.
await expect(page.locator('.cm-content')).toContainText(`const`) await expect(page.locator('.cm-content')).toContainText(`const`)
@ -49,18 +70,29 @@ test.describe('Text-to-CAD tests', () => {
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
// Find the toast close button.
const closeButton = page
.getByRole('status')
.locator('div')
.filter({ hasText: 'Text-to-CAD successfulPrompt' })
.first()
.getByRole('button', { name: 'Close' })
await expect(closeButton).toBeVisible()
await closeButton.click()
// The toast should disappear.
await expect(successToastMessage).not.toBeVisible()
}) })
test('success model, then ignore success toast, user can create new prompt from command bar', async ({ test('success model, then ignore success toast, user can create new prompt from command bar', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await sendPromptFromCommandBar(page, 'a 2x6 lego') await sendPromptFromCommandBar(page, 'a 2x6 lego')
@ -79,6 +111,10 @@ test.describe('Text-to-CAD tests', () => {
const successToastMessage = page.getByText(`Text-to-CAD successful`) const successToastMessage = page.getByText(`Text-to-CAD successful`)
await expect(successToastMessage).toBeVisible({ timeout: 15000 }) await expect(successToastMessage).toBeVisible({ timeout: 15000 })
await expect(page.getByText('Copied')).not.toBeVisible()
await expect(successToastMessage).toBeVisible()
// Can send a new prompt from the command bar. // Can send a new prompt from the command bar.
await sendPromptFromCommandBar(page, 'a 2x4 lego') await sendPromptFromCommandBar(page, 'a 2x4 lego')
@ -97,14 +133,12 @@ test.describe('Text-to-CAD tests', () => {
test('you can reject text-to-cad output and it does nothing', async ({ test('you can reject text-to-cad output and it does nothing', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await sendPromptFromCommandBar(page, 'a 2x4 lego') await sendPromptFromCommandBar(page, 'a 2x4 lego')
@ -136,16 +170,12 @@ test.describe('Text-to-CAD tests', () => {
await expect(page.locator('.cm-content')).toContainText(``) await expect(page.locator('.cm-content')).toContainText(``)
}) })
test('sending a bad prompt fails, can dismiss', async ({ test('sending a bad prompt fails, can dismiss', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
const commandBarButton = page.getByRole('button', { name: 'Commands' }) const commandBarButton = page.getByRole('button', { name: 'Commands' })
await expect(commandBarButton).toBeVisible() await expect(commandBarButton).toBeVisible()
@ -206,14 +236,12 @@ test.describe('Text-to-CAD tests', () => {
test('sending a bad prompt fails, can start over from toast', async ({ test('sending a bad prompt fails, can start over from toast', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
const commandBarButton = page.getByRole('button', { name: 'Commands' }) const commandBarButton = page.getByRole('button', { name: 'Commands' })
await expect(commandBarButton).toBeVisible() await expect(commandBarButton).toBeVisible()
@ -296,14 +324,12 @@ test.describe('Text-to-CAD tests', () => {
test('sending a bad prompt fails, can ignore toast, can start over from command bar', async ({ test('sending a bad prompt fails, can ignore toast, can start over from command bar', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
const commandBarButton = page.getByRole('button', { name: 'Commands' }) const commandBarButton = page.getByRole('button', { name: 'Commands' })
await expect(commandBarButton).toBeVisible() await expect(commandBarButton).toBeVisible()
@ -365,21 +391,19 @@ test.describe('Text-to-CAD tests', () => {
await expect(successToastMessage).toBeVisible({ timeout: 15000 }) await expect(successToastMessage).toBeVisible({ timeout: 15000 })
await expect(page.getByText('Copied')).not.toBeVisible()
// old failure toast should stick around. // old failure toast should stick around.
await expect(failureToastMessage).toBeVisible() await expect(failureToastMessage).toBeVisible()
await expect(page.getByText(`Text-to-CAD failed`)).toBeVisible() await expect(page.getByText(`Text-to-CAD failed`)).toBeVisible()
}) })
test('ensure you can shift+enter in the prompt box', async ({ test('ensure you can shift+enter in the prompt box', async ({ page }) => {
page,
homePage,
}) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
const promptWithNewline = `a 2x4\nlego` const promptWithNewline = `a 2x4\nlego`
@ -432,7 +456,7 @@ test.describe('Text-to-CAD tests', () => {
test( test(
'can do many at once and get many prompts back, and interact with many', 'can do many at once and get many prompts back, and interact with many',
{ tag: ['@skipWin'] }, { tag: ['@skipWin'] },
async ({ page, homePage }) => { async ({ page }) => {
// Let this test run longer since we've seen it timeout. // Let this test run longer since we've seen it timeout.
test.setTimeout(180_000) test.setTimeout(180_000)
// skip on windows // skip on windows
@ -443,10 +467,9 @@ test.describe('Text-to-CAD tests', () => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await sendPromptFromCommandBar(page, 'a 2x4 lego') await sendPromptFromCommandBar(page, 'a 2x4 lego')
@ -472,6 +495,8 @@ test.describe('Text-to-CAD tests', () => {
// We should have three success toasts. // We should have three success toasts.
await expect(successToastMessage).toHaveCount(3, { timeout: 25_000 }) await expect(successToastMessage).toHaveCount(3, { timeout: 25_000 })
await expect(page.getByText('Copied')).not.toBeVisible()
await expect(page.getByText(`a 2x4 lego`)).toBeVisible() await expect(page.getByText(`a 2x4 lego`)).toBeVisible()
await expect(page.getByText(`a 2x8 lego`)).toBeVisible() await expect(page.getByText(`a 2x8 lego`)).toBeVisible()
await expect(page.getByText(`a 2x10 lego`)).toBeVisible() await expect(page.getByText(`a 2x10 lego`)).toBeVisible()
@ -489,15 +514,31 @@ test.describe('Text-to-CAD tests', () => {
// Ensure you can copy the code for one of the models remaining. // Ensure you can copy the code for one of the models remaining.
const copyToClipboardButton = page.getByRole('button', { const copyToClipboardButton = page.getByRole('button', {
name: 'Accept', name: 'Copy to clipboard',
}) })
await expect(copyToClipboardButton.first()).toBeVisible() await expect(copyToClipboardButton.first()).toBeVisible()
// Click the button. // Click the button.
await copyToClipboardButton.first().click() await copyToClipboardButton.first().click()
// Expect the code to be copied.
await expect(page.getByText('Copied')).toBeVisible()
// Click in the code editor.
await page.locator('.cm-content').click({ position: { x: 10, y: 10 } })
// Paste the code.
await page.keyboard.down('ControlOrMeta')
await page.keyboard.press('KeyV')
await page.keyboard.up('ControlOrMeta')
// Expect the code to be pasted. // Expect the code to be pasted.
await expect(page.locator('.cm-content')).toContainText(`2x8`) await expect(page.locator('.cm-content')).toContainText(`2x8`)
// Find the toast close button.
const closeButton = page.locator('[data-negative-button="close"]').first()
await expect(closeButton).toBeVisible()
await closeButton.click()
// Ensure the final toast remains. // Ensure the final toast remains.
await expect(page.getByText(`a 2x10 lego`)).not.toBeVisible() await expect(page.getByText(`a 2x10 lego`)).not.toBeVisible()
await expect(page.getByText(`Prompt: "a 2x8 lego`)).not.toBeVisible() await expect(page.getByText(`Prompt: "a 2x8 lego`)).not.toBeVisible()
@ -508,21 +549,40 @@ test.describe('Text-to-CAD tests', () => {
// Click the button. // Click the button.
await copyToClipboardButton.click() await copyToClipboardButton.click()
// Expect the code to be copied.
await expect(page.getByText('Copied')).toBeVisible()
// Click in the code editor.
await page.locator('.cm-content').click({ position: { x: 10, y: 10 } })
// Paste the code.
await page.keyboard.down('ControlOrMeta')
await page.keyboard.press('KeyA')
await page.keyboard.up('ControlOrMeta')
await page.keyboard.press('Backspace')
await page.keyboard.down('ControlOrMeta')
await page.keyboard.press('KeyV')
await page.keyboard.up('ControlOrMeta')
// Expect the code to be pasted. // Expect the code to be pasted.
await expect(page.locator('.cm-content')).toContainText(`2x4`) await expect(page.locator('.cm-content')).toContainText(`2x4`)
// Expect the toast to disappear.
// Find the toast close button.
await expect(closeButton).toBeVisible()
await closeButton.click()
await expect(successToastMessage).not.toBeVisible()
} }
) )
test('can do many at once with errors, clicking dismiss error does not dismiss all', async ({ test('can do many at once with errors, clicking dismiss error does not dismiss all', async ({
page, page,
homePage,
}) => { }) => {
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1000, height: 500 }) await page.setViewportSize({ width: 1000, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.waitForPageLoad()
await sendPromptFromCommandBar(page, 'a 2x4 lego') await sendPromptFromCommandBar(page, 'a 2x4 lego')
@ -571,37 +631,57 @@ test.describe('Text-to-CAD tests', () => {
// Ensure you can copy the code for one of the models remaining. // Ensure you can copy the code for one of the models remaining.
const copyToClipboardButton = page.getByRole('button', { const copyToClipboardButton = page.getByRole('button', {
name: 'Accept', name: 'Copy to clipboard',
}) })
await expect(copyToClipboardButton.first()).toBeVisible() await expect(copyToClipboardButton.first()).toBeVisible()
// Click the button. // Click the button.
await copyToClipboardButton.first().click() await copyToClipboardButton.first().click()
// Expect the code to be copied.
await expect(page.getByText('Copied')).toBeVisible()
// Click in the code editor.
await page.locator('.cm-content').click({ position: { x: 10, y: 10 } })
// Paste the code.
await page.keyboard.down('ControlOrMeta')
await page.keyboard.press('KeyV')
await page.keyboard.up('ControlOrMeta')
// Expect the code to be pasted. // Expect the code to be pasted.
await expect(page.locator('.cm-content')).toContainText(`2x4`) await expect(page.locator('.cm-content')).toContainText(`2x4`)
// Find the toast close button.
const closeButton = page
.getByRole('status')
.locator('div')
.filter({ hasText: 'Text-to-CAD successfulPrompt' })
.first()
.getByRole('button', { name: 'Close' })
await expect(closeButton).toBeVisible()
await closeButton.click()
// Expect the toast to disappear.
await expect(page.getByText('Copied')).not.toBeVisible()
await expect(successToastMessage).not.toBeVisible()
}) })
}) })
async function sendPromptFromCommandBar(page: Page, promptStr: string) { async function sendPromptFromCommandBar(page: Page, promptStr: string) {
await page.waitForTimeout(1000)
await test.step(`Send prompt from command bar: ${promptStr}`, async () => { await test.step(`Send prompt from command bar: ${promptStr}`, async () => {
const commandBarButton = page.getByRole('button', { name: 'Commands' }) const commandBarButton = page.getByRole('button', { name: 'Commands' })
await expect(commandBarButton).toBeVisible() await expect(commandBarButton).toBeVisible()
// Click the command bar button // Click the command bar button
await commandBarButton.hover()
await commandBarButton.click() await commandBarButton.click()
await page.waitForTimeout(1000)
// Wait for the command bar to appear // Wait for the command bar to appear
const cmdSearchBar = page.getByPlaceholder('Search commands') const cmdSearchBar = page.getByPlaceholder('Search commands')
await expect(cmdSearchBar).toBeVisible() await expect(cmdSearchBar).toBeVisible()
const textToCadCommand = page.getByText('Use the Zoo Text-to-CAD API') const textToCadCommand = page.getByText('Use the Zoo Text-to-CAD API ')
await expect(textToCadCommand.first()).toBeVisible() await expect(textToCadCommand.first()).toBeVisible()
// Click the Text-to-CAD command // Click the Text-to-CAD command
await textToCadCommand.first().scrollIntoViewIfNeeded()
await textToCadCommand.first().click() await textToCadCommand.first().click()
await page.waitForTimeout(1000)
// Enter the prompt. // Enter the prompt.
const prompt = page.getByText('Prompt') const prompt = page.getByText('Prompt')
@ -617,13 +697,12 @@ async function sendPromptFromCommandBar(page: Page, promptStr: string) {
test( test(
'Text-to-CAD functionality', 'Text-to-CAD functionality',
{ tag: '@electron' }, { tag: '@electron' },
async ({ context, page }, testInfo) => { async ({ browserName }, testInfo) => {
const projectName = 'project-000' const projectName = 'project-000'
const prompt = 'lego 2x4' const prompt = 'lego 2x4'
const textToCadFileName = 'lego-2x4.kcl' const textToCadFileName = 'lego-2x4.kcl'
const { dir } = await context.folderSetupFn(async () => {}) const { electronApp, page, dir } = await setupElectron({ testInfo })
const fileExists = () => const fileExists = () =>
fs.existsSync(join(dir, projectName, textToCadFileName)) fs.existsSync(join(dir, projectName, textToCadFileName))
@ -632,7 +711,7 @@ test(
test test
) )
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
// Locators // Locators
const projectMenuButton = page const projectMenuButton = page
@ -682,5 +761,7 @@ test(
// Confirm we've navigated back to the main.kcl file after deletion // Confirm we've navigated back to the main.kcl file after deletion
await expect(projectMenuButton).toContainText('main.kcl') await expect(projectMenuButton).toContainText('main.kcl')
}) })
await electronApp.close()
} }
) )

View File

@ -1,10 +1,19 @@
import { test, expect } from './zoo-test' import { test, expect } from '@playwright/test'
import { doExport, getUtils, makeTemplate } from './test-utils' import { doExport, getUtils, makeTemplate, setup, tearDown } from './test-utils'
test.fixme('Units menu', async ({ page, homePage }) => { test.beforeEach(async ({ context, page }, testInfo) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) await setup(context, page, testInfo)
await homePage.goToModelingScene() })
test.afterEach(async ({ page }, testInfo) => {
await tearDown(page, testInfo)
})
test('Units menu', async ({ page }) => {
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
const unitsMenuButton = page.getByRole('button', { const unitsMenuButton = page.getByRole('button', {
name: 'Current Units', name: 'Current Units',
@ -32,7 +41,7 @@ test.fixme('Units menu', async ({ page, homePage }) => {
await expect(unitsMenuButton).toContainText('mm') await expect(unitsMenuButton).toContainText('mm')
}) })
test('Successful export shows a success toast', async ({ page, homePage }) => { test('Successful export shows a success toast', async ({ page }) => {
// FYI this test doesn't work with only engine running locally // FYI this test doesn't work with only engine running locally
// And you will need to have the KittyCAD CLI installed // And you will need to have the KittyCAD CLI installed
const u = await getUtils(page) const u = await getUtils(page)
@ -48,41 +57,41 @@ totalHeightHalf = 2
armThick = 0.5 armThick = 0.5
totalLen = 9.5 totalLen = 9.5
part001 = startSketchOn('-XZ') part001 = startSketchOn('-XZ')
|> startProfileAt([0, 0], %) |> startProfileAt([0, 0], %)
|> yLine(baseHeight, %) |> yLine(baseHeight, %)
|> xLine(baseLen, %) |> xLine(baseLen, %)
|> angledLineToY({ |> angledLineToY({
angle = topAng, angle: topAng,
to = totalHeightHalf, to: totalHeightHalf,
}, %, $seg04) }, %, $seg04)
|> xLineTo(totalLen, %, $seg03) |> xLineTo(totalLen, %, $seg03)
|> yLine(-armThick, %, $seg01) |> yLine(-armThick, %, $seg01)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle = HALF_TURN, angle: HALF_TURN,
offset = -armThick, offset: -armThick,
intersectTag = seg04 intersectTag: seg04
}, %) }, %)
|> angledLineToY([segAng(seg04) + 180, ZERO], %) |> angledLineToY([segAng(seg04) + 180, ZERO], %)
|> angledLineToY({ |> angledLineToY({
angle = -bottomAng, angle: -bottomAng,
to = -totalHeightHalf - armThick, to: -totalHeightHalf - armThick,
}, %, $seg02) }, %, $seg02)
|> xLineTo(segEndX(seg03) + 0, %) |> xLineTo(segEndX(seg03) + 0, %)
|> yLine(-segLen(seg01), %) |> yLine(-segLen(seg01), %)
|> angledLineThatIntersects({ |> angledLineThatIntersects({
angle = HALF_TURN, angle: HALF_TURN,
offset = -armThick, offset: -armThick,
intersectTag = seg02 intersectTag: seg02
}, %) }, %)
|> angledLineToY([segAng(seg02) + 180, -baseHeight], %) |> angledLineToY([segAng(seg02) + 180, -baseHeight], %)
|> xLineTo(ZERO, %) |> xLineTo(ZERO, %)
|> close(%) |> close(%)
|> extrude(4, %)` |> extrude(4, %)`
) )
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.waitForCmdReceive('extrude') await u.waitForCmdReceive('extrude')
@ -97,14 +106,25 @@ part001 = startSketchOn('-XZ')
}, },
page page
) )
// This is the main thing we're testing,
// We test the export functionality across all
// file types in snapshot-tests.spec.ts
await expect(page.getByText('Exported successfully')).toBeVisible()
}) })
test('Paste should not work unless an input is focused', async ({ test('Paste should not work unless an input is focused', async ({
page, page,
homePage, browserName,
}) => { }) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) // To run this test locally, uncomment Firefox in playwright.config.ts
await homePage.goToModelingScene() test.skip(
browserName !== 'firefox',
"This bug is really Firefox-only, which we don't run in CI."
)
const u = await getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
await page await page
.getByRole('button', { name: 'Start Sketch' }) .getByRole('button', { name: 'Start Sketch' })
.waitFor({ state: 'visible' }) .waitFor({ state: 'visible' })
@ -144,12 +164,12 @@ test('Paste should not work unless an input is focused', async ({
test('Keyboard shortcuts can be viewed through the help menu', async ({ test('Keyboard shortcuts can be viewed through the help menu', async ({
page, page,
homePage,
}) => { }) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) const u = await getUtils(page)
await homePage.goToModelingScene() await page.setViewportSize({ width: 1200, height: 500 })
await u.waitForAuthSkipAppStart()
await page.waitForURL('file:///**', { waitUntil: 'domcontentloaded' }) await page.waitForURL('**/file/**', { waitUntil: 'domcontentloaded' })
await page await page
.getByRole('button', { name: 'Start Sketch' }) .getByRole('button', { name: 'Start Sketch' })
.waitFor({ state: 'visible' }) .waitFor({ state: 'visible' })
@ -161,7 +181,7 @@ test('Keyboard shortcuts can be viewed through the help menu', async ({
await page.getByRole('button', { name: 'Keyboard Shortcuts' }).click() await page.getByRole('button', { name: 'Keyboard Shortcuts' }).click()
// Verify the URL and that you can see a list of shortcuts // Verify the URL and that you can see a list of shortcuts
await expect.poll(() => page.url()).toContain('?tab=keybindings') await expect(page.url()).toContain('?tab=keybindings')
await expect( await expect(
page.getByRole('heading', { name: 'Enter Sketch Mode' }) page.getByRole('heading', { name: 'Enter Sketch Mode' })
).toBeAttached() ).toBeAttached()
@ -169,13 +189,12 @@ test('Keyboard shortcuts can be viewed through the help menu', async ({
test('First escape in tool pops you out of tool, second exits sketch mode', async ({ test('First escape in tool pops you out of tool, second exits sketch mode', async ({
page, page,
homePage,
}) => { }) => {
// Wait for the app to be ready for use // Wait for the app to be ready for use
const u = await getUtils(page) const u = await getUtils(page)
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
@ -239,7 +258,7 @@ test('First escape in tool pops you out of tool, second exits sketch mode', asyn
test.fixme( test.fixme(
'Basic default modeling and sketch hotkeys work', 'Basic default modeling and sketch hotkeys work',
async ({ page, homePage }) => { async ({ page }) => {
const u = await getUtils(page) const u = await getUtils(page)
// This test can run long if it takes a little too long to load // This test can run long if it takes a little too long to load
@ -266,8 +285,8 @@ test.fixme(
}) })
) )
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
await u.openDebugPanel() await u.openDebugPanel()
await u.expectCmdLog('[data-message-type="execution-done"]') await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel() await u.closeDebugPanel()
@ -418,11 +437,10 @@ test.fixme(
} }
) )
test('Delete key does not navigate back', async ({ page, homePage }) => { test('Delete key does not navigate back', async ({ page }) => {
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await page.goto('/')
await page.waitForURL('**/file/**', { waitUntil: 'domcontentloaded' })
await page.waitForURL('file:///**', { waitUntil: 'domcontentloaded' })
const settingsButton = page.getByRole('link', { const settingsButton = page.getByRole('link', {
name: 'Settings', name: 'Settings',
@ -431,45 +449,45 @@ test('Delete key does not navigate back', async ({ page, homePage }) => {
const settingsCloseButton = page.getByTestId('settings-close-button') const settingsCloseButton = page.getByTestId('settings-close-button')
await settingsButton.click() await settingsButton.click()
await expect.poll(() => page.url()).toContain('/settings') await expect(page.url()).toContain('/settings')
// Make sure that delete doesn't go back from settings // Make sure that delete doesn't go back from settings
await page.keyboard.press('Delete') await page.keyboard.press('Delete')
await expect.poll(() => page.url()).toContain('/settings') await expect(page.url()).toContain('/settings')
// Now close the settings and try delete again, // Now close the settings and try delete again,
// make sure it doesn't go back to settings // make sure it doesn't go back to settings
await settingsCloseButton.click() await settingsCloseButton.click()
await page.keyboard.press('Delete') await page.keyboard.press('Delete')
await expect.poll(() => page.url()).not.toContain('/settings') await expect(page.url()).not.toContain('/settings')
}) })
test('Sketch on face', async ({ page, homePage }) => { test('Sketch on face', async ({ page }) => {
test.setTimeout(90_000) test.setTimeout(90_000)
const u = await getUtils(page) const u = await getUtils(page)
await page.addInitScript(async () => { await page.addInitScript(async () => {
localStorage.setItem( localStorage.setItem(
'persistCode', 'persistCode',
`sketch001 = startSketchOn('XZ') `sketch001 = startSketchOn('XZ')
|> startProfileAt([3.29, 7.86], %) |> startProfileAt([3.29, 7.86], %)
|> line([2.48, 2.44], %) |> line([2.48, 2.44], %)
|> line([2.66, 1.17], %) |> line([2.66, 1.17], %)
|> line([3.75, 0.46], %) |> line([3.75, 0.46], %)
|> line([4.99, -0.46], %) |> line([4.99, -0.46], %)
|> line([3.3, -2.12], %) |> line([3.3, -2.12], %)
|> line([2.16, -3.33], %) |> line([2.16, -3.33], %)
|> line([0.85, -3.08], %) |> line([0.85, -3.08], %)
|> line([-0.18, -3.36], %) |> line([-0.18, -3.36], %)
|> line([-3.86, -2.73], %) |> line([-3.86, -2.73], %)
|> line([-17.67, 0.85], %) |> line([-17.67, 0.85], %)
|> close(%) |> close(%)
extrude001 = extrude(5 + 7, sketch001)` extrude001 = extrude(5 + 7, sketch001)`
) )
}) })
await page.setBodyDimensions({ width: 1200, height: 500 }) await page.setViewportSize({ width: 1200, height: 500 })
await homePage.goToModelingScene() await u.waitForAuthSkipAppStart()
// wait for execution done // wait for execution done
await u.openDebugPanel() await u.openDebugPanel()
@ -523,8 +541,7 @@ extrude001 = extrude(5 + 7, sketch001)`
|> line([2.45, -0.2], %) |> line([2.45, -0.2], %)
|> line([-2.6, -1.25], %) |> line([-2.6, -1.25], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%) |> close(%)`)
`)
) )
await u.openAndClearDebugPanel() await u.openAndClearDebugPanel()
@ -539,7 +556,7 @@ extrude001 = extrude(5 + 7, sketch001)`
await page.getByRole('button', { name: 'Edit Sketch' }).click() await page.getByRole('button', { name: 'Edit Sketch' }).click()
await page.waitForTimeout(400) await page.waitForTimeout(400)
await page.waitForTimeout(150) await page.waitForTimeout(150)
await page.setBodyDimensions({ width: 1200, height: 1200 }) await page.setViewportSize({ width: 1200, height: 1200 })
await u.openAndClearDebugPanel() await u.openAndClearDebugPanel()
await u.updateCamPosition([452, -152, 1166]) await u.updateCamPosition([452, -152, 1166])
await u.closeDebugPanel() await u.closeDebugPanel()
@ -557,11 +574,11 @@ extrude001 = extrude(5 + 7, sketch001)`
previousCodeContent = await page.locator('.cm-content').innerText() previousCodeContent = await page.locator('.cm-content').innerText()
const result = makeTemplate`sketch002 = startSketchOn(extrude001, seg01) const result = makeTemplate`sketch002 = startSketchOn(extrude001, seg01)
|> startProfileAt([-12.83, 6.7], %) |> startProfileAt([-12.83, 6.7], %)
|> line([${[2.28, 2.35]}, -${0.07}], %) |> line([${[2.28, 2.35]}, -${0.07}], %)
|> line([-3.05, -1.47], %) |> line([-3.05, -1.47], %)
|> lineTo([profileStartX(%), profileStartY(%)], %) |> lineTo([profileStartX(%), profileStartY(%)], %)
|> close(%)` |> close(%)`
await expect(page.locator('.cm-content')).toHaveText(result.regExp) await expect(page.locator('.cm-content')).toHaveText(result.regExp)
@ -585,6 +602,6 @@ extrude001 = extrude(5 + 7, sketch001)`
await page.getByRole('button', { name: 'checkmark Submit command' }).click() await page.getByRole('button', { name: 'checkmark Submit command' }).click()
const result2 = result.genNext` const result2 = result.genNext`
const sketch002 = extrude(${[5, 5]} + 7, sketch002)` const sketch002 = extrude(${[5, 5]} + 7, sketch002)`
await expect(page.locator('.cm-content')).toHaveText(result2.regExp) await expect(page.locator('.cm-content')).toHaveText(result2.regExp)
}) })

View File

@ -1,334 +0,0 @@
import {
test as playwrightTestFn,
TestInfo as TestInfoPlaywright,
BrowserContext as BrowserContextPlaywright,
Page as PagePlaywright,
TestDetails as TestDetailsPlaywright,
PlaywrightTestArgs,
PlaywrightTestOptions,
PlaywrightWorkerArgs,
PlaywrightWorkerOptions,
ElectronApplication,
} from '@playwright/test'
import {
fixtures,
Fixtures,
AuthenticatedTronApp,
AuthenticatedApp,
} from './fixtures/fixtureSetup'
import { SaveSettingsPayload } from 'lib/settings/settingsTypes'
export { expect } from '@playwright/test'
declare module '@playwright/test' {
interface TestInfo {
tronApp?: AuthenticatedTronApp
}
interface BrowserContext {
folderSetupFn: (
cb: (dir: string) => Promise<void>
) => Promise<{ dir: string }>
}
interface Page {
dir: string
TEST_SETTINGS_FILE_KEY?: string
setBodyDimensions: (dims: {
width: number
height: number
}) => Promise<void>
}
}
export type TestInfo = TestInfoPlaywright
export type BrowserContext = BrowserContextPlaywright
export type Page = PagePlaywright
export type TestDetails = TestDetailsPlaywright & {
cleanProjectDir?: boolean
appSettings?: Partial<SaveSettingsPayload>
}
// Our custom decorated Zoo test object. Makes it easier to add fixtures, and
// switch between web and electron if needed.
const pwTestFnWithFixtures = playwrightTestFn.extend<Fixtures>(fixtures)
// In JavaScript you cannot replace a function's body only (despite functions
// are themselves objects, which you'd expect a body property or something...)
// So we must redefine the function and then re-attach properties.
type PWFunction = (
args: PlaywrightTestArgs &
Fixtures &
PlaywrightWorkerArgs &
PlaywrightTestOptions &
PlaywrightWorkerOptions & {
electronApp?: ElectronApplication
},
testInfo: TestInfo
) => void | Promise<void>
let firstUrl = ''
// The below error is due to the extreme type spaghetti going on. playwright/
// types/test.d.ts does not export 2 functions (below is one of them) but tsc
// is trying to use a interface name it can't see.
// e2e/playwright/zoo-test.ts:64:14 - error TS4023: Exported variable 'test' has
// or is using name 'TestFunction' from external module
// "/home/lee/Code/Zoo/modeling-app/dirty2/node_modules/playwright/types/test"
// but cannot be named.
export const test = (
desc: string,
objOrFn: PWFunction | TestDetails,
fnMaybe?: PWFunction
) => {
const hasTestConf = typeof objOrFn === 'object'
const fn = hasTestConf ? fnMaybe : objOrFn
return pwTestFnWithFixtures(
desc,
hasTestConf ? objOrFn : {},
async (
{
page,
context,
cmdBar,
editor,
toolbar,
scene,
homePage,
request,
playwright,
browser,
acceptDownloads,
bypassCSP,
colorScheme,
clientCertificates,
deviceScaleFactor,
extraHTTPHeaders,
geolocation,
hasTouch,
httpCredentials,
ignoreHTTPSErrors,
isMobile,
javaScriptEnabled,
locale,
offline,
permissions,
proxy,
storageState,
timezoneId,
userAgent,
viewport,
baseURL,
contextOptions,
actionTimeout,
navigationTimeout,
serviceWorkers,
testIdAttribute,
browserName,
defaultBrowserType,
headless,
channel,
launchOptions,
connectOptions,
screenshot,
trace,
video,
},
testInfo
) => {
// To switch to web, use PLATFORM=web environment variable.
// Only use this for debugging, since the playwright tracer is busted
// for electron.
let tronApp
if (process.env.PLATFORM === 'web') {
tronApp = new AuthenticatedApp(context, page, testInfo)
} else {
tronApp = new AuthenticatedTronApp(context, page, testInfo)
}
const fixtures: Fixtures = { cmdBar, editor, toolbar, scene, homePage }
if (tronApp instanceof AuthenticatedTronApp) {
const options = {
fixtures,
}
if (hasTestConf) {
Object.assign(options, {
appSettings: objOrFn?.appSettings,
cleanProjectDir: objOrFn?.cleanProjectDir,
})
}
await tronApp.initialise(options)
} else {
await tronApp.initialise('')
}
// We need to patch this because addInitScript will bind too late in our
// electron tests, never running. We need to call reload() after each call
// to guarantee it runs.
const oldContextAddInitScript = tronApp.context.addInitScript
tronApp.context.addInitScript = async function (a, b) {
// @ts-ignore pretty sure way out of tsc's type checking capabilities.
// This code works perfectly fine.
await oldContextAddInitScript.apply(this, [a, b])
await tronApp.page.reload()
}
// No idea why we mix and match page and context's addInitScript but we do
const oldPageAddInitScript = tronApp.page.addInitScript
tronApp.page.addInitScript = async function (a: any, b: any) {
// @ts-ignore pretty sure way out of tsc's type checking capabilities.
// This code works perfectly fine.
await oldPageAddInitScript.apply(this, [a, b])
await tronApp.page.reload()
}
// Create a consistent way to resize the page across electron and web.
// (lee) I had to do everyhting in the book to make electron change its
// damn window size. I succeded in making it consistently and reliably
// do it after a whole afternoon.
tronApp.page.setBodyDimensions = async function (dims: {
width: number
height: number
}) {
await tronApp.page.setViewportSize(dims)
if (!(tronApp instanceof AuthenticatedTronApp)) {
return
}
await tronApp.electronApp?.evaluateHandle(async ({ app }, dims) => {
// @ts-ignore sorry jon but see comment in main.ts why this is ignored
await app.resizeWindow(dims.width, dims.height)
}, dims)
return tronApp.page.evaluate(
async (dims: { width: number; height: number }) => {
await window.electron.resizeWindow(dims.width, dims.height)
window.document.body.style.width = dims.width + 'px'
window.document.body.style.height = dims.height + 'px'
window.document.documentElement.style.width = dims.width + 'px'
window.document.documentElement.style.height = dims.height + 'px'
},
dims
)
}
await tronApp.page.setBodyDimensions(tronApp.viewPortSize)
// We need to expose this in order for some tests that require folder
// creation. Before they used to do this by their own electronSetup({...})
// calls.
if (tronApp instanceof AuthenticatedTronApp) {
tronApp.context.folderSetupFn = async function (fn) {
return fn(tronApp.dir)
.then(() => tronApp.page.reload())
.then(() => ({
dir: tronApp.dir,
}))
}
}
if (!firstUrl) {
await tronApp.page.getByText('Your Projects').count()
firstUrl = tronApp.page.url()
}
// Due to the app controlling its own window context we need to inject new
// options and context here.
// NOTE TO LEE: Seems to destroy page context when calling an electron loadURL.
// await tronApp.electronApp.evaluate(({ app }) => {
// return app.reuseWindowForTest();
// });
await tronApp.electronApp.evaluate(({ app }, projectDirName) => {
console.log('ABCDEFGHI', app.testProperty['TEST_SETTINGS_FILE_KEY'])
app.testProperty['TEST_SETTINGS_FILE_KEY'] = projectDirName
}, tronApp.dir)
// Always start at the root view
await tronApp.page.goto(firstUrl)
// Force a hard reload, destroying the stream and other state
await tronApp.page.reload()
// tsc aint smart enough to know this'll never be undefined
// but I dont blame it, the logic to know is complex
if (fn) {
await fn(
{
context: tronApp.context,
page: tronApp.page,
electronApp:
tronApp instanceof AuthenticatedTronApp
? tronApp.electronApp
: undefined,
...fixtures,
request,
playwright,
browser,
acceptDownloads,
bypassCSP,
colorScheme,
clientCertificates,
deviceScaleFactor,
extraHTTPHeaders,
geolocation,
hasTouch,
httpCredentials,
ignoreHTTPSErrors,
isMobile,
javaScriptEnabled,
locale,
offline,
permissions,
proxy,
storageState,
timezoneId,
userAgent,
viewport,
baseURL,
contextOptions,
actionTimeout,
navigationTimeout,
serviceWorkers,
testIdAttribute,
browserName,
defaultBrowserType,
headless,
channel,
launchOptions,
connectOptions,
screenshot,
trace,
video,
},
testInfo
)
}
testInfo.tronApp =
tronApp instanceof AuthenticatedTronApp ? tronApp : undefined
}
)
}
type ZooTest = typeof test
test.describe = pwTestFnWithFixtures.describe
test.beforeEach = pwTestFnWithFixtures.beforeEach
test.afterEach = pwTestFnWithFixtures.afterEach
test.step = pwTestFnWithFixtures.step
test.skip = pwTestFnWithFixtures.skip
test.setTimeout = pwTestFnWithFixtures.setTimeout
test.fixme = pwTestFnWithFixtures.fixme as unknown as ZooTest
test.only = pwTestFnWithFixtures.only
test.fail = pwTestFnWithFixtures.fail
test.slow = pwTestFnWithFixtures.slow
test.beforeAll = pwTestFnWithFixtures.beforeAll
test.afterAll = pwTestFnWithFixtures.afterAll
test.use = pwTestFnWithFixtures.use
test.expect = pwTestFnWithFixtures.expect
test.extend = pwTestFnWithFixtures.extend
test.info = pwTestFnWithFixtures.info

View File

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

1
interface.d.ts vendored
View File

@ -7,7 +7,6 @@ import { MachinesListing } from 'components/MachineManagerProvider'
type EnvFn = (value?: string) => string type EnvFn = (value?: string) => string
export interface IElectronAPI { export interface IElectronAPI {
resizeWindow: (width: number, height: number) => Promise<void>
open: typeof dialog.showOpenDialog open: typeof dialog.showOpenDialog
save: typeof dialog.showSaveDialog save: typeof dialog.showSaveDialog
openExternal: typeof shell.openExternal openExternal: typeof shell.openExternal

View File

@ -39,6 +39,7 @@
"chokidar": "^4.0.1", "chokidar": "^4.0.1",
"codemirror": "^6.0.1", "codemirror": "^6.0.1",
"decamelize": "^6.0.0", "decamelize": "^6.0.0",
"electron-squirrel-startup": "^1.0.1",
"electron-updater": "6.3.0", "electron-updater": "6.3.0",
"fuse.js": "^7.0.0", "fuse.js": "^7.0.0",
"html2canvas-pro": "^1.5.8", "html2canvas-pro": "^1.5.8",
@ -68,7 +69,7 @@
"yargs": "^17.7.2" "yargs": "^17.7.2"
}, },
"scripts": { "scripts": {
"start": "vite --port=3000 --host=0.0.0.0", "start": "vite",
"start:prod": "vite preview --port=3000", "start:prod": "vite preview --port=3000",
"serve": "vite serve --port=3000", "serve": "vite serve --port=3000",
"build": "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && source \"$HOME/.cargo/env\" && curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -y && yarn build:wasm && vite build", "build": "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && source \"$HOME/.cargo/env\" && curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -y && yarn build:wasm && vite build",
@ -105,22 +106,24 @@
"tron:package": "electron-forge package", "tron:package": "electron-forge package",
"tron:make": "electron-forge make", "tron:make": "electron-forge make",
"tron:publish": "electron-forge publish", "tron:publish": "electron-forge publish",
"chrome:test": "PLATFORM=web NODE_ENV=development yarn playwright test --config=playwright.config.ts --project='Google Chrome' --grep-invert='@snapshot'", "tron:test": "NODE_ENV=development yarn playwright test --config=playwright.electron.config.ts --grep=@electron",
"tron:test": "NODE_ENV=development yarn playwright test --config=playwright.electron.config.ts --grep-invert='@snapshot'",
"tronb:vite": "vite build -c vite.main.config.ts && vite build -c vite.preload.config.ts && vite build -c vite.renderer.config.ts", "tronb:vite": "vite build -c vite.main.config.ts && vite build -c vite.preload.config.ts && vite build -c vite.renderer.config.ts",
"tronb:package": "electron-builder --config electron-builder.yml", "tronb:package": "electron-builder --config electron-builder.yml",
"test-setup": "yarn install && yarn build:wasm", "test-setup": "yarn install && yarn build:wasm",
"test": "vitest --mode development", "test": "vitest --mode development",
"test:unit": "vitest run --mode development --exclude **/kclSamples.test.ts", "test:unit": "vitest run --mode development --exclude **/kclSamples.test.ts",
"test:unit:kcl-samples": "vitest run --mode development ./src/lang/kclSamples.test.ts", "test:unit:kcl-samples": "vitest run --mode development ./src/lang/kclSamples.test.ts",
"test:playwright:electron": "playwright test --config=playwright.electron.config.ts --grep-invert='@snapshot'", "test:playwright:browser:chrome": "playwright test --project='Google Chrome' --config=playwright.ci.config.ts --grep-invert='@snapshot|@electron'",
"test:playwright:electron:windows": "playwright test --config=playwright.electron.config.ts --grep-invert='@skipWin|@snapshot'", "test:playwright:browser:chrome:windows": "playwright test --project=\"Google Chrome\" --config=playwright.ci.config.ts --grep-invert=\"@snapshot|@electron|@skipWin\"",
"test:playwright:electron:macos": "playwright test --config=playwright.electron.config.ts --grep-invert='@skipMacos|@snapshot'", "test:playwright:browser:chrome:ubuntu": "playwright test --project='Google Chrome' --config=playwright.ci.config.ts --grep-invert='@snapshot|@electron|@skipLinux'",
"test:playwright:electron:ubuntu": "playwright test --config=playwright.electron.config.ts --grep-invert='@skipLinux|@snapshot'", "test:playwright:electron": "playwright test --config=playwright.electron.config.ts --grep=@electron",
"test:playwright:electron:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@snapshot'", "test:playwright:electron:windows": "playwright test --config=playwright.electron.config.ts --grep=@electron --grep-invert=@skipWin",
"test:playwright:electron:windows:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipWin|@snapshot'", "test:playwright:electron:macos": "playwright test --config=playwright.electron.config.ts --grep=@electron --grep-invert=@skipMacos",
"test:playwright:electron:macos:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipMacos|@snapshot'", "test:playwright:electron:ubuntu": "playwright test --config=playwright.electron.config.ts --grep=@electron --grep-invert=@skipLinux",
"test:playwright:electron:ubuntu:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep-invert='@skipLinux|@snapshot'", "test:playwright:electron:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep=@electron",
"test:playwright:electron:windows:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep=@electron --grep-invert=@skipWin",
"test:playwright:electron:macos:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep=@electron --grep-invert=@skipMacos",
"test:playwright:electron:ubuntu:local": "yarn tron:package && NODE_ENV=development playwright test --config=playwright.electron.config.ts --grep=@electron --grep-invert=@skipLinux",
"test:unit:local": "yarn simpleserver:bg && yarn test:unit; kill-port 3000", "test:unit:local": "yarn simpleserver:bg && yarn test:unit; kill-port 3000",
"test:unit:kcl-samples:local": "yarn simpleserver:bg && yarn test:unit:kcl-samples; kill-port 3000" "test:unit:kcl-samples:local": "yarn simpleserver:bg && yarn test:unit:kcl-samples; kill-port 3000"
}, },
@ -145,14 +148,21 @@
"devDependencies": { "devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11", "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@babel/preset-env": "^7.25.4", "@babel/preset-env": "^7.25.4",
"@electron-forge/cli": "7.4.0", "@electron-forge/cli": "^7.4.0",
"@electron-forge/plugin-fuses": "7.4.0", "@electron-forge/maker-deb": "^7.4.0",
"@electron-forge/plugin-vite": "7.4.0", "@electron-forge/maker-rpm": "^7.4.0",
"@electron/fuses": "1.8.0", "@electron-forge/maker-squirrel": "^7.4.0",
"@electron-forge/maker-wix": "^7.5.0",
"@electron-forge/maker-zip": "^7.5.0",
"@electron-forge/plugin-auto-unpack-natives": "^7.4.0",
"@electron-forge/plugin-fuses": "^7.4.0",
"@electron-forge/plugin-vite": "^7.4.0",
"@electron/fuses": "^1.8.0",
"@electron/rebuild": "^3.6.0",
"@iarna/toml": "^2.2.5", "@iarna/toml": "^2.2.5",
"@lezer/generator": "^1.7.1", "@lezer/generator": "^1.7.1",
"@nabla/vite-plugin-eslint": "^2.0.5", "@nabla/vite-plugin-eslint": "^2.0.5",
"@playwright/test": "^1.49.0", "@playwright/test": "^1.46.1",
"@testing-library/jest-dom": "^5.14.1", "@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^15.0.2", "@testing-library/react": "^15.0.2",
"@types/d3-force": "^3.0.10", "@types/d3-force": "^3.0.10",
@ -178,9 +188,9 @@
"@xstate/cli": "^0.5.17", "@xstate/cli": "^0.5.17",
"autoprefixer": "^10.4.19", "autoprefixer": "^10.4.19",
"d3-force": "^3.0.0", "d3-force": "^3.0.0",
"electron": "32.1.2", "electron": "^32.1.2",
"electron-builder": "24.13.3", "electron-builder": "^24.13.3",
"electron-notarize": "1.2.2", "electron-notarize": "^1.2.2",
"eslint": "^8.0.1", "eslint": "^8.0.1",
"eslint-config-react-app": "^7.0.1", "eslint-config-react-app": "^7.0.1",
"eslint-plugin-css-modules": "^2.12.0", "eslint-plugin-css-modules": "^2.12.0",

58
playwright.ci.config.ts Normal file
View File

@ -0,0 +1,58 @@
import { defineConfig, devices } from '@playwright/test'
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
timeout: 120_000, // override the default 30s timeout
testDir: './e2e/playwright',
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: true,
/* Do not retry */
retries: 0,
/* Different amount of parallelism on CI and local. */
workers: 1,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: [
['dot'],
['list'],
['json', { outputFile: './test-results/report.json' }],
['html'],
],
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: 'http://localhost:3000',
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'retain-on-failure',
actionTimeout: 15_000,
screenshot: 'only-on-failure',
},
/* Configure projects for major browsers */
projects: [
{
name: 'Google Chrome',
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',
use: { ...devices['Desktop Safari'] },
},
],
webServer: {
command: 'yarn start',
reuseExistingServer: false,
},
})

View File

@ -13,7 +13,7 @@ export default defineConfig({
/* Do not retry */ /* Do not retry */
retries: 0, retries: 0,
/* Different amount of parallelism on CI and local. */ /* Different amount of parallelism on CI and local. */
workers: 30, workers: 1,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */ /* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: [ reporter: [
['dot'], ['dot'],

View File

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

View File

@ -505,8 +505,7 @@ const ConstraintSymbol = ({
constrainInfo: ConstrainInfo constrainInfo: ConstrainInfo
verticalPosition: 'top' | 'bottom' verticalPosition: 'top' | 'bottom'
}) => { }) => {
const { commandBarSend } = useCommandsContext() const { context, send } = useModelingContext()
const { context } = useModelingContext()
const varNameMap: { const varNameMap: {
[key in ConstrainInfo['type']]: { [key in ConstrainInfo['type']]: {
varName: string varName: string
@ -625,18 +624,11 @@ const ConstraintSymbol = ({
// disabled={implicitDesc} TODO why does this change styles that are hard to override? // disabled={implicitDesc} TODO why does this change styles that are hard to override?
onClick={toSync(async () => { onClick={toSync(async () => {
if (!isConstrained) { if (!isConstrained) {
commandBarSend({ send({
type: 'Find and select command', type: 'Convert to variable',
data: { data: {
name: 'Constrain with named value', pathToNode,
groupId: 'modeling', variableName: varName,
argDefaultValues: {
currentValue: {
pathToNode,
variableName: varName,
valueText: value,
},
},
}, },
}) })
} else if (isConstrained) { } else if (isConstrained) {

View File

@ -8,16 +8,11 @@ import { getSystemTheme } from 'lib/theme'
import { useCalculateKclExpression } from 'lib/useCalculateKclExpression' import { useCalculateKclExpression } from 'lib/useCalculateKclExpression'
import { roundOff } from 'lib/utils' import { roundOff } from 'lib/utils'
import { varMentions } from 'lib/varCompletionExtension' import { varMentions } from 'lib/varCompletionExtension'
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useHotkeys } from 'react-hotkeys-hook' import { useHotkeys } from 'react-hotkeys-hook'
import styles from './CommandBarKclInput.module.css' import styles from './CommandBarKclInput.module.css'
import { createIdentifier, createVariableDeclaration } from 'lang/modifyAst' import { createIdentifier, createVariableDeclaration } from 'lang/modifyAst'
import { useCodeMirror } from 'components/ModelingSidebar/ModelingPanes/CodeEditor' import { useCodeMirror } from 'components/ModelingSidebar/ModelingPanes/CodeEditor'
import { useSelector } from '@xstate/react'
const machineContextSelector = (snapshot?: {
context: Record<string, unknown>
}) => snapshot?.context
function CommandBarKclInput({ function CommandBarKclInput({
arg, arg,
@ -36,44 +31,12 @@ function CommandBarKclInput({
arg.name arg.name
] as KclCommandValue | undefined ] as KclCommandValue | undefined
const { settings } = useSettingsAuthContext() const { settings } = useSettingsAuthContext()
const argMachineContext = useSelector( const defaultValue = (arg.defaultValue as string) || ''
arg.machineActor,
machineContextSelector
)
const defaultValue = useMemo(
() =>
arg.defaultValue
? arg.defaultValue instanceof Function
? arg.defaultValue(commandBarState.context, argMachineContext)
: arg.defaultValue
: '',
[arg.defaultValue, commandBarState.context, argMachineContext]
)
const initialVariableName = useMemo(() => {
// Use the configured variable name if it exists
if (arg.variableName !== undefined) {
return arg.variableName instanceof Function
? arg.variableName(commandBarState.context, argMachineContext)
: arg.variableName
}
// or derive it from the previously set value or the argument name
return previouslySetValue && 'variableName' in previouslySetValue
? previouslySetValue.variableName
: arg.name
}, [
arg.variableName,
commandBarState.context,
argMachineContext,
arg.name,
previouslySetValue,
])
const [value, setValue] = useState( const [value, setValue] = useState(
previouslySetValue?.valueText || defaultValue || '' previouslySetValue?.valueText || defaultValue || ''
) )
const [createNewVariable, setCreateNewVariable] = useState( const [createNewVariable, setCreateNewVariable] = useState(
(previouslySetValue && 'variableName' in previouslySetValue) || previouslySetValue && 'variableName' in previouslySetValue
arg.createVariableByDefault ||
false
) )
const [canSubmit, setCanSubmit] = useState(true) const [canSubmit, setCanSubmit] = useState(true)
useHotkeys('mod + k, mod + /', () => commandBarSend({ type: 'Close' })) useHotkeys('mod + k, mod + /', () => commandBarSend({ type: 'Close' }))
@ -89,7 +52,10 @@ function CommandBarKclInput({
isNewVariableNameUnique, isNewVariableNameUnique,
} = useCalculateKclExpression({ } = useCalculateKclExpression({
value, value,
initialVariableName, initialVariableName:
previouslySetValue && 'variableName' in previouslySetValue
? previouslySetValue.variableName
: arg.name,
}) })
const varMentionData: Completion[] = prevVariables.map((v) => ({ const varMentionData: Completion[] = prevVariables.map((v) => ({
label: v.key, label: v.key,

View File

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

View File

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

View File

@ -41,10 +41,7 @@ import {
angleBetweenInfo, angleBetweenInfo,
applyConstraintAngleBetween, applyConstraintAngleBetween,
} from './Toolbar/SetAngleBetween' } from './Toolbar/SetAngleBetween'
import { import { applyConstraintAngleLength } from './Toolbar/setAngleLength'
applyConstraintAngleLength,
applyConstraintLength,
} from './Toolbar/setAngleLength'
import { import {
canSweepSelection, canSweepSelection,
handleSelectionBatch, handleSelectionBatch,
@ -54,7 +51,6 @@ import {
Selections, Selections,
updateSelections, updateSelections,
canLoftSelection, canLoftSelection,
canRevolveSelection,
canShellSelection, canShellSelection,
} from 'lib/selections' } from 'lib/selections'
import { applyConstraintIntersect } from './Toolbar/Intersect' import { applyConstraintIntersect } from './Toolbar/Intersect'
@ -67,13 +63,12 @@ import {
getSketchOrientationDetails, getSketchOrientationDetails,
} from 'clientSideScene/sceneEntities' } from 'clientSideScene/sceneEntities'
import { import {
insertNamedConstant, moveValueIntoNewVariablePath,
replaceValueAtNodePath,
sketchOnExtrudedFace, sketchOnExtrudedFace,
sketchOnOffsetPlane, sketchOnOffsetPlane,
startSketchOnDefault, startSketchOnDefault,
} from 'lang/modifyAst' } from 'lang/modifyAst'
import { PathToNode, Program, parse, recast, resultIsOk } from 'lang/wasm' import { Program, parse, recast, resultIsOk } from 'lang/wasm'
import { import {
doesSceneHaveExtrudedSketch, doesSceneHaveExtrudedSketch,
doesSceneHaveSweepableSketch, doesSceneHaveSweepableSketch,
@ -86,6 +81,7 @@ import toast from 'react-hot-toast'
import { EditorSelection, Transaction } from '@codemirror/state' import { EditorSelection, Transaction } from '@codemirror/state'
import { useLoaderData, useNavigate, useSearchParams } from 'react-router-dom' import { useLoaderData, useNavigate, useSearchParams } from 'react-router-dom'
import { letEngineAnimateAndSyncCamAfter } from 'clientSideScene/CameraControls' import { letEngineAnimateAndSyncCamAfter } from 'clientSideScene/CameraControls'
import { getVarNameModal } from 'hooks/useToolbarGuards'
import { err, reportRejection, trap } from 'lib/trap' import { err, reportRejection, trap } from 'lib/trap'
import { useCommandsContext } from 'hooks/useCommandsContext' import { useCommandsContext } from 'hooks/useCommandsContext'
import { modelingMachineEvent } from 'editor/manager' import { modelingMachineEvent } from 'editor/manager'
@ -576,26 +572,6 @@ export const ModelingMachineProvider = ({
if (err(canSweep)) return false if (err(canSweep)) return false
return canSweep return canSweep
}, },
'has valid revolve selection': ({ context: { selectionRanges } }) => {
// A user can begin extruding if they either have 1+ faces selected or nothing selected
// TODO: I believe this guard only allows for extruding a single face at a time
const hasNoSelection =
selectionRanges.graphSelections.length === 0 ||
isRangeBetweenCharacters(selectionRanges) ||
isSelectionLastLine(selectionRanges, codeManager.code)
if (hasNoSelection) {
// they have no selection, we should enable the button
// so they can select the face through the cmdbar
// BUT only if there's extrudable geometry
return doesSceneHaveSweepableSketch(kclManager.ast)
}
if (!isSketchPipe(selectionRanges)) return false
const canSweep = canRevolveSelection(selectionRanges)
if (err(canSweep)) return false
return canSweep
},
'has valid loft selection': ({ context: { selectionRanges } }) => { 'has valid loft selection': ({ context: { selectionRanges } }) => {
const hasNoSelection = const hasNoSelection =
selectionRanges.graphSelections.length === 0 || selectionRanges.graphSelections.length === 0 ||
@ -913,18 +889,12 @@ export const ModelingMachineProvider = ({
} }
} }
), ),
astConstrainLength: fromPromise( 'Get length info': fromPromise(
async ({ async ({ input: { selectionRanges, sketchDetails } }) => {
input: { selectionRanges, sketchDetails, lengthValue }, const { modifiedAst, pathToNodeMap } =
}) => { await applyConstraintAngleLength({
if (!lengthValue) selectionRanges,
return Promise.reject(new Error('No length value')) })
const constraintResult = await applyConstraintLength({
selectionRanges,
length: lengthValue,
})
if (err(constraintResult)) return Promise.reject(constraintResult)
const { modifiedAst, pathToNodeMap } = constraintResult
const pResult = parse(recast(modifiedAst)) const pResult = parse(recast(modifiedAst))
if (trap(pResult) || !resultIsOk(pResult)) if (trap(pResult) || !resultIsOk(pResult))
return Promise.reject(new Error('Unexpected compilation error')) return Promise.reject(new Error('Unexpected compilation error'))
@ -1093,88 +1063,38 @@ export const ModelingMachineProvider = ({
} }
} }
), ),
'Apply named value constraint': fromPromise( 'Get convert to variable info': fromPromise(
async ({ input: { selectionRanges, sketchDetails, data } }) => { async ({ input: { selectionRanges, sketchDetails, data } }) => {
if (!sketchDetails) { if (!sketchDetails)
return Promise.reject(new Error('No sketch details')) return Promise.reject(new Error('No sketch details'))
} const { variableName } = await getVarNameModal({
if (!data) { valueName: data?.variableName || 'var',
return Promise.reject(new Error('No data from command flow')) })
}
let pResult = parse(recast(kclManager.ast)) let pResult = parse(recast(kclManager.ast))
if (trap(pResult) || !resultIsOk(pResult)) if (trap(pResult) || !resultIsOk(pResult))
return Promise.reject(new Error('Unexpected compilation error')) return Promise.reject(new Error('Unexpected compilation error'))
let parsed = pResult.program let parsed = pResult.program
let result: { const { modifiedAst: _modifiedAst, pathToReplacedNode } =
modifiedAst: Node<Program> moveValueIntoNewVariablePath(
pathToReplaced: PathToNode | null parsed,
} = { kclManager.programMemory,
modifiedAst: parsed, data?.pathToNode || [],
pathToReplaced: null, variableName
}
// If the user provided a constant name,
// we need to insert the named constant
// and then replace the node with the constant's name.
if ('variableName' in data.namedValue) {
const astAfterReplacement = replaceValueAtNodePath({
ast: parsed,
pathToNode: data.currentValue.pathToNode,
newExpressionString: data.namedValue.variableName,
})
if (trap(astAfterReplacement)) {
return Promise.reject(astAfterReplacement)
}
const parseResultAfterInsertion = parse(
recast(
insertNamedConstant({
node: astAfterReplacement.modifiedAst,
newExpression: data.namedValue,
})
)
) )
if ( pResult = parse(recast(_modifiedAst))
trap(parseResultAfterInsertion) ||
!resultIsOk(parseResultAfterInsertion)
)
return Promise.reject(parseResultAfterInsertion)
result = {
modifiedAst: parseResultAfterInsertion.program,
pathToReplaced: astAfterReplacement.pathToReplaced,
}
} else if ('valueText' in data.namedValue) {
// If they didn't provide a constant name,
// just replace the node with the value.
const astAfterReplacement = replaceValueAtNodePath({
ast: parsed,
pathToNode: data.currentValue.pathToNode,
newExpressionString: data.namedValue.valueText,
})
if (trap(astAfterReplacement)) {
return Promise.reject(astAfterReplacement)
}
// The `replacer` function returns a pathToNode that assumes
// an identifier is also being inserted into the AST, creating an off-by-one error.
// This corrects that error, but TODO we should fix this upstream
// to avoid this kind of error in the future.
astAfterReplacement.pathToReplaced[1][0] =
(astAfterReplacement.pathToReplaced[1][0] as number) - 1
result = astAfterReplacement
}
pResult = parse(recast(result.modifiedAst))
if (trap(pResult) || !resultIsOk(pResult)) if (trap(pResult) || !resultIsOk(pResult))
return Promise.reject(new Error('Unexpected compilation error')) return Promise.reject(new Error('Unexpected compilation error'))
parsed = pResult.program parsed = pResult.program
if (trap(parsed)) return Promise.reject(parsed) if (trap(parsed)) return Promise.reject(parsed)
parsed = parsed as Node<Program> parsed = parsed as Node<Program>
if (!result.pathToReplaced) if (!pathToReplacedNode)
return Promise.reject(new Error('No path to replaced node')) return Promise.reject(new Error('No path to replaced node'))
const updatedAst = const updatedAst =
await sceneEntitiesManager.updateAstAndRejigSketch( await sceneEntitiesManager.updateAstAndRejigSketch(
result.pathToReplaced || [], pathToReplacedNode || [],
parsed, parsed,
sketchDetails.zAxis, sketchDetails.zAxis,
sketchDetails.yAxis, sketchDetails.yAxis,
@ -1187,7 +1107,7 @@ export const ModelingMachineProvider = ({
) )
const selection = updateSelections( const selection = updateSelections(
{ 0: result.pathToReplaced }, { 0: pathToReplacedNode },
selectionRanges, selectionRanges,
updatedAst.newAst updatedAst.newAst
) )
@ -1195,7 +1115,7 @@ export const ModelingMachineProvider = ({
return { return {
selectionType: 'completeSelection', selectionType: 'completeSelection',
selection, selection,
updatedPathToNode: result.pathToReplaced, updatedPathToNode: pathToReplacedNode,
} }
} }
), ),

View File

@ -76,7 +76,7 @@ export const ModelingPane = ({
return ( return (
<section <section
{...props} {...props}
aria-label={title && typeof title === 'string' ? title : ''} title={title && typeof title === 'string' ? title : ''}
data-testid={detailsTestId} data-testid={detailsTestId}
id={id} id={id}
className={ className={

View File

@ -10,7 +10,7 @@ interface AllKeybindingsFieldsProps {}
export const AllKeybindingsFields = forwardRef( export const AllKeybindingsFields = forwardRef(
( (
_props: AllKeybindingsFieldsProps, props: AllKeybindingsFieldsProps,
scrollRef: ForwardedRef<HTMLDivElement> scrollRef: ForwardedRef<HTMLDivElement>
) => { ) => {
// This is how we will get the interaction map from the context // This is how we will get the interaction map from the context
@ -25,7 +25,7 @@ export const AllKeybindingsFields = forwardRef(
.map(([category, categoryItems]) => ( .map(([category, categoryItems]) => (
<div className="flex flex-col gap-4 px-2 pr-4"> <div className="flex flex-col gap-4 px-2 pr-4">
<h2 <h2
id={`category-${category.replaceAll(/\s/g, '-')}`} id={`category-${category}`}
className="text-xl mt-6 first-of-type:mt-0 capitalize font-bold" className="text-xl mt-6 first-of-type:mt-0 capitalize font-bold"
> >
{category} {category}

View File

@ -13,7 +13,7 @@ import { isDesktop } from 'lib/isDesktop'
import { ActionButton } from 'components/ActionButton' import { ActionButton } from 'components/ActionButton'
import { SettingsFieldInput } from './SettingsFieldInput' import { SettingsFieldInput } from './SettingsFieldInput'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { APP_VERSION, IS_NIGHTLY, getReleaseUrl } from 'routes/Settings' import { APP_VERSION, PACKAGE_NAME } from 'routes/Settings'
import { PATHS } from 'lib/paths' import { PATHS } from 'lib/paths'
import { import {
createAndOpenNewTutorialProject, createAndOpenNewTutorialProject,
@ -246,8 +246,10 @@ export const AllSettingsFields = forwardRef(
to inject the version from package.json */} to inject the version from package.json */}
App version {APP_VERSION}.{' '} App version {APP_VERSION}.{' '}
<a <a
onClick={openExternalBrowserIfDesktop(getReleaseUrl())} onClick={openExternalBrowserIfDesktop(
href={getReleaseUrl()} `https://github.com/KittyCAD/modeling-app/releases/tag/v${APP_VERSION}`
)}
href={`https://github.com/KittyCAD/modeling-app/releases/tag/v${APP_VERSION}`}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
@ -269,7 +271,7 @@ export const AllSettingsFields = forwardRef(
, and start a discussion if you don't see it! Your feedback will , and start a discussion if you don't see it! Your feedback will
help us prioritize what to build next. help us prioritize what to build next.
</p> </p>
{!IS_NIGHTLY && ( {PACKAGE_NAME.indexOf('-nightly') === -1 && (
<p className="max-w-2xl mt-6"> <p className="max-w-2xl mt-6">
Want to experience the latest and (hopefully) greatest from our Want to experience the latest and (hopefully) greatest from our
main development branch?{' '} main development branch?{' '}

View File

@ -19,7 +19,7 @@ export function KeybindingsSectionsList({
key={category} key={category}
onClick={() => onClick={() =>
scrollRef.current scrollRef.current
?.querySelector(`#category-${category.replaceAll(/\s/g, '-')}`) ?.querySelector(`#category-${category}`)
?.scrollIntoView({ ?.scrollIntoView({
block: 'center', block: 'center',
behavior: 'smooth', behavior: 'smooth',

View File

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

View File

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

View File

@ -22,7 +22,6 @@ import { removeDoubleNegatives } from '../AvailableVarsHelpers'
import { normaliseAngle } from '../../lib/utils' import { normaliseAngle } from '../../lib/utils'
import { kclManager } from 'lib/singletons' import { kclManager } from 'lib/singletons'
import { err } from 'lib/trap' import { err } from 'lib/trap'
import { KclCommandValue } from 'lib/commandTypes'
const getModalInfo = createSetAngleLengthModal(SetAngleLengthModal) const getModalInfo = createSetAngleLengthModal(SetAngleLengthModal)
@ -64,57 +63,6 @@ export function angleLengthInfo({
return { enabled, transforms } return { enabled, transforms }
} }
export async function applyConstraintLength({
length,
selectionRanges,
}: {
length: KclCommandValue
selectionRanges: Selections
}) {
const ast = kclManager.ast
const angleLength = angleLengthInfo({ selectionRanges })
if (err(angleLength)) return angleLength
const { transforms } = angleLength
let distanceExpression: Expr = length.valueAst
/**
* To be "constrained", the value must be a binary expression, a named value, or a function call.
* If it has a variable name, we need to insert a variable declaration at the correct index.
*/
if (
'variableName' in length &&
length.variableName &&
length.insertIndex !== undefined
) {
const newBody = [...ast.body]
newBody.splice(length.insertIndex, 0, length.variableDeclarationAst)
ast.body = newBody
distanceExpression = createIdentifier(length.variableName)
}
if (!isExprBinaryPart(distanceExpression)) {
return new Error('Invalid valueNode, is not a BinaryPart')
}
const retval = transformAstSketchLines({
ast,
selectionRanges,
transformInfos: transforms,
programMemory: kclManager.programMemory,
referenceSegName: '',
forceValueUsedInTransform: distanceExpression,
})
if (err(retval)) return Promise.reject(retval)
const { modifiedAst: _modifiedAst, pathToNodeMap } = retval
return {
modifiedAst: _modifiedAst,
pathToNodeMap,
}
}
export async function applyConstraintAngleLength({ export async function applyConstraintAngleLength({
selectionRanges, selectionRanges,
angleOrLength = 'setLength', angleOrLength = 'setLength',

View File

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

View File

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

View File

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

View File

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

View File

@ -24,8 +24,6 @@ export function useConvertToVariable(range?: SourceRange) {
}, [enable]) }, [enable])
useEffect(() => { useEffect(() => {
// Return early if there are no selection ranges for whatever reason
if (!context.selectionRanges) return
const parsed = ast const parsed = ast
const meta = isNodeSafeToReplace( const meta = isNodeSafeToReplace(

View File

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

View File

@ -45,7 +45,7 @@ export default class CodeManager {
} else if (storedCode === null) { } else if (storedCode === null) {
this.code = bracket this.code = bracket
} else { } else {
this.code = storedCode || '' this.code = storedCode
} }
} }
@ -57,10 +57,6 @@ export default class CodeManager {
return this._code return this._code
} }
localStoragePersistCode(): string {
return safeLSGetItem(PERSIST_CODE_KEY) || ''
}
registerCallBacks({ setCode }: { setCode: (arg: string) => void }) { registerCallBacks({ setCode }: { setCode: (arg: string) => void }) {
this.#updateState = setCode this.#updateState = setCode
} }
@ -169,7 +165,7 @@ export default class CodeManager {
} }
function safeLSGetItem(key: string) { function safeLSGetItem(key: string) {
if (typeof window === 'undefined') return if (typeof window === 'undefined') return null
return localStorage?.getItem(key) return localStorage?.getItem(key)
} }

View File

@ -45,7 +45,6 @@ import { TagDeclarator } from 'wasm-lib/kcl/bindings/TagDeclarator'
import { Models } from '@kittycad/lib' import { Models } from '@kittycad/lib'
import { ExtrudeFacePlane } from 'machines/modelingMachine' import { ExtrudeFacePlane } from 'machines/modelingMachine'
import { Node } from 'wasm-lib/kcl/bindings/Node' import { Node } from 'wasm-lib/kcl/bindings/Node'
import { KclExpressionWithVariable } from 'lib/commandTypes'
export function startSketchOnDefault( export function startSketchOnDefault(
node: Node<Program>, node: Node<Program>,
@ -591,25 +590,6 @@ export function addOffsetPlane({
} }
} }
/**
* Return a modified clone of an AST with a named constant inserted into the body
*/
export function insertNamedConstant({
node,
newExpression,
}: {
node: Node<Program>
newExpression: KclExpressionWithVariable
}): Node<Program> {
const ast = structuredClone(node)
ast.body.splice(
newExpression.insertIndex,
0,
newExpression.variableDeclarationAst
)
return ast
}
/** /**
* Modify the AST to create a new sketch using the variable declaration * Modify the AST to create a new sketch using the variable declaration
* of an offset plane. The new sketch just has to come after the offset * of an offset plane. The new sketch just has to come after the offset
@ -953,31 +933,6 @@ export function giveSketchFnCallTag(
} }
} }
/**
* Replace a
*/
export function replaceValueAtNodePath({
ast,
pathToNode,
newExpressionString,
}: {
ast: Node<Program>
pathToNode: PathToNode
newExpressionString: string
}) {
const replaceCheckResult = isNodeSafeToReplacePath(ast, pathToNode)
if (err(replaceCheckResult)) {
return replaceCheckResult
}
const { isSafe, value, replacer } = replaceCheckResult
if (!isSafe || value.type === 'Identifier') {
return new Error('Not safe to replace')
}
return replacer(ast, newExpressionString)
}
export function moveValueIntoNewVariablePath( export function moveValueIntoNewVariablePath(
ast: Node<Program>, ast: Node<Program>,
programMemory: ProgramMemory, programMemory: ProgramMemory,

View File

@ -40,6 +40,7 @@ beforeAll(async () => {
makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager), makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager),
setMediaStream: () => {}, setMediaStream: () => {},
setIsStreamReady: () => {}, setIsStreamReady: () => {},
modifyGrid: async () => {},
callbackOnEngineLiteConnect: () => { callbackOnEngineLiteConnect: () => {
resolve(true) resolve(true)
}, },

View File

@ -335,7 +335,7 @@ export function mutateAstWithTagForSketchSegment(
return { modifiedAst: astClone, tag } return { modifiedAst: astClone, tag }
} }
export function getEdgeTagCall( function getEdgeTagCall(
tag: string, tag: string,
artifact: Artifact artifact: Artifact
): Node<Identifier | CallExpression> { ): Node<Identifier | CallExpression> {

View File

@ -1,154 +0,0 @@
import { err } from 'lib/trap'
import { KCL_DEFAULT_CONSTANT_PREFIXES } from 'lib/constants'
import {
Program,
PathToNode,
Expr,
CallExpression,
PipeExpression,
VariableDeclarator,
} from 'lang/wasm'
import { Selections } from 'lib/selections'
import { Node } from 'wasm-lib/kcl/bindings/Node'
import {
createLiteral,
createCallExpressionStdLib,
createObjectExpression,
createIdentifier,
createPipeExpression,
findUniqueName,
createVariableDeclaration,
} from 'lang/modifyAst'
import { getNodeFromPath, getNodePathFromSourceRange } from 'lang/queryAst'
import {
mutateAstWithTagForSketchSegment,
getEdgeTagCall,
} from 'lang/modifyAst/addEdgeTreatment'
export function revolveSketch(
ast: Node<Program>,
pathToSketchNode: PathToNode,
shouldPipe = false,
angle: Expr = createLiteral(4),
axis: Selections
):
| {
modifiedAst: Node<Program>
pathToSketchNode: PathToNode
pathToRevolveArg: PathToNode
}
| Error {
const clonedAst = structuredClone(ast)
const sketchNode = getNodeFromPath(clonedAst, pathToSketchNode)
if (err(sketchNode)) return sketchNode
// testing code
const pathToAxisSelection = getNodePathFromSourceRange(
clonedAst,
axis.graphSelections[0]?.codeRef.range
)
const lineNode = getNodeFromPath<CallExpression>(
clonedAst,
pathToAxisSelection,
'CallExpression'
)
if (err(lineNode)) return lineNode
// TODO Kevin: What if |> close(%)?
// TODO Kevin: What if opposite edge
// TODO Kevin: What if the edge isn't planar to the sketch?
// TODO Kevin: add a tag.
const tagResult = mutateAstWithTagForSketchSegment(
clonedAst,
pathToAxisSelection
)
// Have the tag whether it is already created or a new one is generated
if (err(tagResult)) return tagResult
const { tag } = tagResult
/* Original Code */
const { node: sketchExpression } = sketchNode
// determine if sketchExpression is in a pipeExpression or not
const sketchPipeExpressionNode = getNodeFromPath<PipeExpression>(
clonedAst,
pathToSketchNode,
'PipeExpression'
)
if (err(sketchPipeExpressionNode)) return sketchPipeExpressionNode
const { node: sketchPipeExpression } = sketchPipeExpressionNode
const isInPipeExpression = sketchPipeExpression.type === 'PipeExpression'
const sketchVariableDeclaratorNode = getNodeFromPath<VariableDeclarator>(
clonedAst,
pathToSketchNode,
'VariableDeclarator'
)
if (err(sketchVariableDeclaratorNode)) return sketchVariableDeclaratorNode
const {
node: sketchVariableDeclarator,
shallowPath: sketchPathToDecleration,
} = sketchVariableDeclaratorNode
const axisSelection = axis?.graphSelections[0]?.artifact
if (!axisSelection) return new Error('Axis selection is missing.')
const revolveCall = createCallExpressionStdLib('revolve', [
createObjectExpression({
angle: angle,
axis: getEdgeTagCall(tag, axisSelection),
}),
createIdentifier(sketchVariableDeclarator.id.name),
])
if (shouldPipe) {
const pipeChain = createPipeExpression(
isInPipeExpression
? [...sketchPipeExpression.body, revolveCall]
: [sketchExpression as any, revolveCall]
)
sketchVariableDeclarator.init = pipeChain
const pathToRevolveArg: PathToNode = [
...sketchPathToDecleration,
['init', 'VariableDeclarator'],
['body', ''],
[pipeChain.body.length - 1, 'index'],
['arguments', 'CallExpression'],
[0, 'index'],
]
return {
modifiedAst: clonedAst,
pathToSketchNode,
pathToRevolveArg,
}
}
// We're not creating a pipe expression,
// but rather a separate constant for the extrusion
const name = findUniqueName(clonedAst, KCL_DEFAULT_CONSTANT_PREFIXES.REVOLVE)
const VariableDeclaration = createVariableDeclaration(name, revolveCall)
const sketchIndexInPathToNode =
sketchPathToDecleration.findIndex((a) => a[0] === 'body') + 1
const sketchIndexInBody = sketchPathToDecleration[sketchIndexInPathToNode][0]
if (typeof sketchIndexInBody !== 'number')
return new Error('expected sketchIndexInBody to be a number')
clonedAst.body.splice(sketchIndexInBody + 1, 0, VariableDeclaration)
const pathToRevolveArg: PathToNode = [
['body', ''],
[sketchIndexInBody + 1, 'index'],
['declaration', 'VariableDeclaration'],
['init', 'VariableDeclarator'],
['arguments', 'CallExpression'],
[0, 'index'],
]
return {
modifiedAst: clonedAst,
pathToSketchNode: [...pathToSketchNode.slice(0, -1), [-1, 'index']],
pathToRevolveArg,
}
}

View File

@ -111,7 +111,8 @@ export function addShell({
const pathToNode: PathToNode = [ const pathToNode: PathToNode = [
['body', ''], ['body', ''],
[modifiedAst.body.length - 1, 'index'], [modifiedAst.body.length - 1, 'index'],
['declaration', 'VariableDeclaration'], ['declarations', 'VariableDeclaration'],
['0', 'index'],
['init', 'VariableDeclarator'], ['init', 'VariableDeclarator'],
['arguments', 'CallExpression'], ['arguments', 'CallExpression'],
[0, 'index'], [0, 'index'],

View File

@ -661,7 +661,7 @@ describe('Testing doesSceneHaveExtrudedSketch', () => {
|> circle({ center = [0, 0], radius = 1 }, %) |> circle({ center = [0, 0], radius = 1 }, %)
extrude001 = extrude(1, sketch001) extrude001 = extrude(1, sketch001)
` `
const ast = assertParse(exampleCode) const ast = parse(exampleCode)
if (err(ast)) throw ast if (err(ast)) throw ast
const extrudable = doesSceneHaveExtrudedSketch(ast) const extrudable = doesSceneHaveExtrudedSketch(ast)
expect(extrudable).toBeTruthy() expect(extrudable).toBeTruthy()
@ -671,7 +671,7 @@ extrude001 = extrude(1, sketch001)
|> circle({ center = [0, 0], radius = 1 }, %) |> circle({ center = [0, 0], radius = 1 }, %)
|> extrude(1, %) |> extrude(1, %)
` `
const ast = assertParse(exampleCode) const ast = parse(exampleCode)
if (err(ast)) throw ast if (err(ast)) throw ast
const extrudable = doesSceneHaveExtrudedSketch(ast) const extrudable = doesSceneHaveExtrudedSketch(ast)
expect(extrudable).toBeTruthy() expect(extrudable).toBeTruthy()
@ -680,7 +680,7 @@ extrude001 = extrude(1, sketch001)
const exampleCode = `extrude001 = startSketchOn('XZ') const exampleCode = `extrude001 = startSketchOn('XZ')
|> circle({ center = [0, 0], radius = 1 }, %) |> circle({ center = [0, 0], radius = 1 }, %)
` `
const ast = assertParse(exampleCode) const ast = parse(exampleCode)
if (err(ast)) throw ast if (err(ast)) throw ast
const extrudable = doesSceneHaveExtrudedSketch(ast) const extrudable = doesSceneHaveExtrudedSketch(ast)
expect(extrudable).toBeFalsy() expect(extrudable).toBeFalsy()

View File

@ -139,6 +139,7 @@ beforeAll(async () => {
makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager), makeDefaultPlanes: () => makeDefaultPlanes(engineCommandManager),
setMediaStream: () => {}, setMediaStream: () => {},
setIsStreamReady: () => {}, setIsStreamReady: () => {},
modifyGrid: async () => {},
// eslint-disable-next-line @typescript-eslint/no-misused-promises // eslint-disable-next-line @typescript-eslint/no-misused-promises
callbackOnEngineLiteConnect: async () => { callbackOnEngineLiteConnect: async () => {
const cacheEntries = Object.entries(codeToWriteCacheFor) as [ const cacheEntries = Object.entries(codeToWriteCacheFor) as [

View File

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

View File

@ -1399,6 +1399,7 @@ export class EngineCommandManager extends EventTarget {
} }
private makeDefaultPlanes: () => Promise<DefaultPlanes> | null = () => null private makeDefaultPlanes: () => Promise<DefaultPlanes> | null = () => null
private modifyGrid: (hidden: boolean) => Promise<void> | null = () => null
private onEngineConnectionOpened = () => {} private onEngineConnectionOpened = () => {}
private onEngineConnectionClosed = () => {} private onEngineConnectionClosed = () => {}
@ -1431,6 +1432,7 @@ export class EngineCommandManager extends EventTarget {
height, height,
token, token,
makeDefaultPlanes, makeDefaultPlanes,
modifyGrid,
settings = { settings = {
pool: null, pool: null,
theme: Themes.Dark, theme: Themes.Dark,
@ -1450,12 +1452,14 @@ export class EngineCommandManager extends EventTarget {
height: number height: number
token?: string token?: string
makeDefaultPlanes: () => Promise<DefaultPlanes> makeDefaultPlanes: () => Promise<DefaultPlanes>
modifyGrid: (hidden: boolean) => Promise<void>
settings?: SettingsViaQueryString settings?: SettingsViaQueryString
}) { }) {
if (settings) { if (settings) {
this.settings = settings this.settings = settings
} }
this.makeDefaultPlanes = makeDefaultPlanes this.makeDefaultPlanes = makeDefaultPlanes
this.modifyGrid = modifyGrid
if (width === 0 || height === 0) { if (width === 0 || height === 0) {
return return
} }
@ -1535,15 +1539,21 @@ export class EngineCommandManager extends EventTarget {
type: 'default_camera_get_settings', type: 'default_camera_get_settings',
}, },
}) })
await this.initPlanes() // We want modify the grid first because we don't want it to flash.
setIsStreamReady(true) // Ideally these would already be default hidden in engine (TODO do
// that) https://github.com/KittyCAD/engine/issues/2282
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.modifyGrid(!this.settings.showScaleGrid)?.then(async () => {
await this.initPlanes()
setIsStreamReady(true)
// Other parts of the application should use this to react on scene ready. // Other parts of the application should use this to react on scene ready.
this.dispatchEvent( this.dispatchEvent(
new CustomEvent(EngineCommandManagerEvents.SceneReady, { new CustomEvent(EngineCommandManagerEvents.SceneReady, {
detail: this.engineConnection, detail: this.engineConnection,
}) })
) )
})
} }
this.engineConnection.addEventListener( this.engineConnection.addEventListener(
@ -2202,6 +2212,15 @@ export class EngineCommandManager extends EventTarget {
}).catch(reportRejection) }).catch(reportRejection)
} }
/**
* Set the visibility of the scale grid in the engine scene.
* @param visible - whether to show or hide the scale grid
*/
setScaleGridVisibility(visible: boolean) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.modifyGrid(!visible)
}
// Some "objects" have the same source range, such as sketch_mode_start and start_path. // Some "objects" have the same source range, such as sketch_mode_start and start_path.
// So when passing a range, we need to also specify the command type // So when passing a range, we need to also specify the command type
mapRangeToObjectId( mapRangeToObjectId(

View File

@ -1,13 +1,9 @@
import { err } from 'lib/trap' import { err } from 'lib/trap'
import { initPromise, parse, ParseResult } from './wasm' import { parse, ParseResult } from './wasm'
import { enginelessExecutor } from 'lib/testHelpers' import { enginelessExecutor } from 'lib/testHelpers'
import { Node } from 'wasm-lib/kcl/bindings/Node' import { Node } from 'wasm-lib/kcl/bindings/Node'
import { Program } from '../wasm-lib/kcl/bindings/Program' import { Program } from '../wasm-lib/kcl/bindings/Program'
beforeEach(async () => {
await initPromise
})
it('can execute parsed AST', async () => { it('can execute parsed AST', async () => {
const code = `x = 1 const code = `x = 1
// A comment.` // A comment.`

View File

@ -1,13 +1,14 @@
import init, { import init, {
parse_wasm, parse_wasm,
recast_wasm, recast_wasm,
execute, execute_wasm,
kcl_lint, kcl_lint,
modify_ast_for_sketch_wasm, modify_ast_for_sketch_wasm,
is_points_ccw, is_points_ccw,
get_tangential_arc_to_info, get_tangential_arc_to_info,
program_memory_init, program_memory_init,
make_default_planes, make_default_planes,
modify_grid,
coredump, coredump,
toml_stringify, toml_stringify,
default_app_settings, default_app_settings,
@ -42,9 +43,7 @@ import { Environment } from '../wasm-lib/kcl/bindings/Environment'
import { Node } from 'wasm-lib/kcl/bindings/Node' import { Node } from 'wasm-lib/kcl/bindings/Node'
import { CompilationError } from 'wasm-lib/kcl/bindings/CompilationError' import { CompilationError } from 'wasm-lib/kcl/bindings/CompilationError'
import { SourceRange as RustSourceRange } from 'wasm-lib/kcl/bindings/SourceRange' import { SourceRange as RustSourceRange } from 'wasm-lib/kcl/bindings/SourceRange'
import { getAllCurrentSettings } from 'lib/settings/settingsUtils'
export type { Configuration } from 'wasm-lib/kcl/bindings/Configuration'
export type { Program } from '../wasm-lib/kcl/bindings/Program' export type { Program } from '../wasm-lib/kcl/bindings/Program'
export type { Expr } from '../wasm-lib/kcl/bindings/Expr' export type { Expr } from '../wasm-lib/kcl/bindings/Expr'
export type { ObjectExpression } from '../wasm-lib/kcl/bindings/ObjectExpression' export type { ObjectExpression } from '../wasm-lib/kcl/bindings/ObjectExpression'
@ -93,26 +92,12 @@ export type { Solid } from '../wasm-lib/kcl/bindings/Solid'
export type { KclValue } from '../wasm-lib/kcl/bindings/KclValue' export type { KclValue } from '../wasm-lib/kcl/bindings/KclValue'
export type { ExtrudeSurface } from '../wasm-lib/kcl/bindings/ExtrudeSurface' export type { ExtrudeSurface } from '../wasm-lib/kcl/bindings/ExtrudeSurface'
/**
* The first two items are the start and end points (byte offsets from the start of the file).
* The third item is whether the source range belongs to the 'main' file, i.e., the file currently
* being rendered/displayed in the editor (TODO we need to handle modules better in the frontend).
*/
export type SourceRange = [number, number, boolean] export type SourceRange = [number, number, boolean]
/**
* Convert a SourceRange as used inside the KCL interpreter into the above one for use in the
* frontend (essentially we're eagerly checking whether the frontend should care about the SourceRange
* so as not to expose details of the interpreter's current representation of module ids throughout
* the frontend).
*/
export function sourceRangeFromRust(s: RustSourceRange): SourceRange { export function sourceRangeFromRust(s: RustSourceRange): SourceRange {
return [s[0], s[1], s[2] === 0] return [s[0], s[1], s[2] === 0]
} }
/**
* Create a default SourceRange for testing or as a placeholder.
*/
export function defaultSourceRange(): SourceRange { export function defaultSourceRange(): SourceRange {
return [0, 0, true] return [0, 0, true]
} }
@ -137,7 +122,7 @@ const initialise = async () => {
const fullUrl = wasmUrl() const fullUrl = wasmUrl()
const input = await fetch(fullUrl) const input = await fetch(fullUrl)
const buffer = await input.arrayBuffer() const buffer = await input.arrayBuffer()
return await init({ module_or_path: buffer }) return await init(buffer)
} catch (e) { } catch (e) {
console.log('Error initialising WASM', e) console.log('Error initialising WASM', e)
return Promise.reject(e) return Promise.reject(e)
@ -178,10 +163,6 @@ export class ParseResult {
} }
} }
/**
* Parsing was successful. There is guaranteed to be an AST and no fatal errors. There may or may
* not be warnings or non-fatal errors.
*/
class SuccessParseResult extends ParseResult { class SuccessParseResult extends ParseResult {
program: Node<Program> program: Node<Program>
@ -512,19 +493,18 @@ export const _executor = async (
return Promise.reject(programMemoryOverride) return Promise.reject(programMemoryOverride)
try { try {
let jsAppSettings = default_app_settings() let baseUnit = 'mm'
if (!TEST) { if (!TEST) {
const lastSettingsSnapshot = await import( const getSettingsState = import('components/SettingsAuthProvider').then(
'components/SettingsAuthProvider' (module) => module.getSettingsState
).then((module) => module.lastSettingsContextSnapshot) )
if (lastSettingsSnapshot) { baseUnit =
jsAppSettings = getAllCurrentSettings(lastSettingsSnapshot) (await getSettingsState)()?.modeling.defaultUnit.current || 'mm'
}
} }
const execState: RawExecState = await execute( const execState: RawExecState = await execute_wasm(
JSON.stringify(node), JSON.stringify(node),
JSON.stringify(programMemoryOverride?.toRaw() || null), JSON.stringify(programMemoryOverride?.toRaw() || null),
JSON.stringify({ settings: jsAppSettings }), baseUnit,
engineCommandManager, engineCommandManager,
fileSystemManager fileSystemManager
) )
@ -572,6 +552,20 @@ export const makeDefaultPlanes = async (
} }
} }
export const modifyGrid = async (
engineCommandManager: EngineCommandManager,
hidden: boolean
): Promise<void> => {
try {
await modify_grid(engineCommandManager, hidden)
return
} catch (e) {
// TODO: do something real with the error.
console.log('modify grid error', e)
return Promise.reject(e)
}
}
export const modifyAstForSketch = async ( export const modifyAstForSketch = async (
engineCommandManager: EngineCommandManager, engineCommandManager: EngineCommandManager,
ast: Node<Program>, ast: Node<Program>,

View File

@ -32,14 +32,8 @@ export function mouseControlsToCameraSystem(
mouseControl: MouseControlType | undefined mouseControl: MouseControlType | undefined
): CameraSystem | undefined { ): CameraSystem | undefined {
switch (mouseControl) { switch (mouseControl) {
// TODO: understand why the values come back without underscores and fix the root cause
// @ts-ignore: TS2678
case 'kittycad':
case 'kitty_cad': case 'kitty_cad':
return 'KittyCAD' return 'KittyCAD'
// TODO: understand why the values come back without underscores and fix the root cause
// @ts-ignore: TS2678
case 'onshape':
case 'on_shape': case 'on_shape':
return 'OnShape' return 'OnShape'
case 'trackpad_friendly': case 'trackpad_friendly':
@ -50,9 +44,6 @@ export function mouseControlsToCameraSystem(
return 'NX' return 'NX'
case 'creo': case 'creo':
return 'Creo' return 'Creo'
// TODO: understand why the values come back without underscores and fix the root cause
// @ts-ignore: TS2678
case 'autocad':
case 'auto_cad': case 'auto_cad':
return 'AutoCAD' return 'AutoCAD'
default: default:

View File

@ -1,15 +1,9 @@
import { Models } from '@kittycad/lib' import { Models } from '@kittycad/lib'
import { angleLengthInfo } from 'components/Toolbar/setAngleLength'
import { transformAstSketchLines } from 'lang/std/sketchcombos'
import { PathToNode } from 'lang/wasm'
import { StateMachineCommandSetConfig, KclCommandValue } from 'lib/commandTypes' import { StateMachineCommandSetConfig, KclCommandValue } from 'lib/commandTypes'
import { KCL_DEFAULT_LENGTH, KCL_DEFAULT_DEGREE } from 'lib/constants' import { KCL_DEFAULT_LENGTH, KCL_DEFAULT_DEGREE } from 'lib/constants'
import { components } from 'lib/machine-api' import { components } from 'lib/machine-api'
import { Selections } from 'lib/selections' import { Selections } from 'lib/selections'
import { kclManager } from 'lib/singletons'
import { err } from 'lib/trap'
import { modelingMachine, SketchTool } from 'machines/modelingMachine' import { modelingMachine, SketchTool } from 'machines/modelingMachine'
import { revolveAxisValidator } from './validators'
type OutputFormat = Models['OutputFormat_type'] type OutputFormat = Models['OutputFormat_type']
type OutputTypeKey = OutputFormat['type'] type OutputTypeKey = OutputFormat['type']
@ -47,7 +41,6 @@ export type ModelingCommandSchema = {
Revolve: { Revolve: {
selection: Selections selection: Selections
angle: KclCommandValue angle: KclCommandValue
axis: Selections
} }
Fillet: { Fillet: {
// todo // todo
@ -61,18 +54,6 @@ export type ModelingCommandSchema = {
'change tool': { 'change tool': {
tool: SketchTool tool: SketchTool
} }
'Constrain length': {
selection: Selections
length: KclCommandValue
}
'Constrain with named value': {
currentValue: {
valueText: string
pathToNode: PathToNode
variableName: string
}
namedValue: KclCommandValue
}
'Text-to-CAD': { 'Text-to-CAD': {
prompt: string prompt: string
} }
@ -332,13 +313,6 @@ export const modelingMachineCommandConfig: StateMachineCommandSetConfig<
required: true, required: true,
skip: true, skip: true,
}, },
axis: {
required: true,
inputType: 'selection',
selectionTypes: ['segment', 'sweepEdge', 'edgeCutEdge'],
multiple: false,
validation: revolveAxisValidator,
},
angle: { angle: {
inputType: 'kcl', inputType: 'kcl',
defaultValue: KCL_DEFAULT_DEGREE, defaultValue: KCL_DEFAULT_DEGREE,
@ -386,88 +360,6 @@ export const modelingMachineCommandConfig: StateMachineCommandSetConfig<
}, },
}, },
}, },
'Constrain length': {
description: 'Constrain the length of one or more segments.',
icon: 'dimension',
args: {
selection: {
inputType: 'selection',
selectionTypes: ['segment'],
multiple: false,
required: true,
skip: true,
},
length: {
inputType: 'kcl',
required: true,
createVariableByDefault: true,
defaultValue(_, machineContext) {
const selectionRanges = machineContext?.selectionRanges
if (!selectionRanges) return KCL_DEFAULT_LENGTH
const angleLength = angleLengthInfo({
selectionRanges,
angleOrLength: 'setLength',
})
if (err(angleLength)) return KCL_DEFAULT_LENGTH
const { transforms } = angleLength
// QUESTION: is it okay to reference kclManager here? will its state be up to date?
const sketched = transformAstSketchLines({
ast: structuredClone(kclManager.ast),
selectionRanges,
transformInfos: transforms,
programMemory: kclManager.programMemory,
referenceSegName: '',
})
if (err(sketched)) return KCL_DEFAULT_LENGTH
const { valueUsedInTransform } = sketched
return valueUsedInTransform?.toString() || KCL_DEFAULT_LENGTH
},
},
},
},
'Constrain with named value': {
description: 'Constrain a value by making it a named constant.',
icon: 'make-variable',
args: {
currentValue: {
description:
'Path to the node in the AST to constrain. This is never shown to the user.',
inputType: 'text',
required: false,
skip: true,
},
namedValue: {
inputType: 'kcl',
required: true,
createVariableByDefault: true,
variableName(commandBarContext, machineContext) {
const { currentValue } = commandBarContext.argumentsToSubmit
if (
!currentValue ||
!(currentValue instanceof Object) ||
!('variableName' in currentValue) ||
typeof currentValue.variableName !== 'string'
) {
return 'value'
}
return currentValue.variableName
},
defaultValue: (commandBarContext) => {
const { currentValue } = commandBarContext.argumentsToSubmit
if (
!currentValue ||
!(currentValue instanceof Object) ||
!('valueText' in currentValue) ||
typeof currentValue.valueText !== 'string'
) {
return KCL_DEFAULT_LENGTH
}
return currentValue.valueText
},
},
},
},
'Text-to-CAD': { 'Text-to-CAD': {
description: 'Use the Zoo Text-to-CAD API to generate part starters.', description: 'Use the Zoo Text-to-CAD API to generate part starters.',
icon: 'chat', icon: 'chat',

View File

@ -1,107 +0,0 @@
import { Models } from '@kittycad/lib'
import { engineCommandManager } from 'lib/singletons'
import { uuidv4 } from 'lib/utils'
import { CommandBarContext } from 'machines/commandBarMachine'
import { Selections } from 'lib/selections'
import { isSolid2D, isSegment, isSweep } from 'lang/std/artifactGraph'
export const disableDryRunWithRetry = async (numberOfRetries = 3) => {
for (let tries = 0; tries < numberOfRetries; tries++) {
try {
await engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: { type: 'disable_dry_run' },
})
// Exit out since the command was successful
return
} catch (e) {
console.error(e)
console.error('disable_dry_run failed. This is bad!')
}
}
}
// Takes a callback function and wraps it around enable_dry_run and disable_dry_run
export const dryRunWrapper = async (callback: () => Promise<any>) => {
// Gotcha: What about race conditions?
try {
await engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: { type: 'enable_dry_run' },
})
const result = await callback()
return result
} catch (e) {
console.error(e)
} finally {
await disableDryRunWithRetry(5)
}
}
function isSelections(selections: unknown): selections is Selections {
return (
(selections as Selections).graphSelections !== undefined &&
(selections as Selections).otherSelections !== undefined
)
}
export const revolveAxisValidator = async ({
data,
context,
}: {
data: { [key: string]: Selections }
context: CommandBarContext
}): Promise<boolean | string> => {
if (!isSelections(context.argumentsToSubmit.selection)) {
return 'Unable to revolve, selections are missing'
}
const artifact =
context.argumentsToSubmit.selection.graphSelections[0].artifact
if (!artifact) {
return 'Unable to revolve, sketch not found'
}
if (!(isSolid2D(artifact) || isSegment(artifact) || isSweep(artifact))) {
return 'Unable to revolve, sketch has no path'
}
const sketchSelection = artifact.pathId
let edgeSelection = data.axis.graphSelections[0].artifact?.id
if (!sketchSelection) {
return 'Unable to revolve, sketch is missing'
}
if (!edgeSelection) {
return 'Unable to revolve, edge is missing'
}
const angleInDegrees: Models['Angle_type'] = {
unit: 'degrees',
value: 360,
}
const revolveAboutEdgeCommand = async () => {
return await engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'revolve_about_edge',
angle: angleInDegrees,
edge_id: edgeSelection,
target: sketchSelection,
tolerance: 0.0001,
},
})
}
const attemptRevolve = await dryRunWrapper(revolveAboutEdgeCommand)
if (attemptRevolve?.success) {
return true
} else {
// return error message for the toast
return 'Unable to revolve with selected axis'
}
}

View File

@ -7,7 +7,7 @@ import { ReactNode } from 'react'
import { MachineManager } from 'components/MachineManagerProvider' import { MachineManager } from 'components/MachineManagerProvider'
import { Node } from 'wasm-lib/kcl/bindings/Node' import { Node } from 'wasm-lib/kcl/bindings/Node'
import { Artifact } from 'lang/std/artifactGraph' import { Artifact } from 'lang/std/artifactGraph'
import { CommandBarContext } from 'machines/commandBarMachine'
type Icon = CustomIconName type Icon = CustomIconName
const PLATFORMS = ['both', 'web', 'desktop'] as const const PLATFORMS = ['both', 'web', 'desktop'] as const
const INPUT_TYPES = [ const INPUT_TYPES = [
@ -147,30 +147,8 @@ export type CommandArgumentConfig<
inputType: 'selection' inputType: 'selection'
selectionTypes: Artifact['type'][] selectionTypes: Artifact['type'][]
multiple: boolean multiple: boolean
validation?: ({
data,
context,
}: {
data: any
context: CommandBarContext
}) => Promise<boolean | string>
}
| {
inputType: 'kcl'
createVariableByDefault?: boolean
variableName?:
| string
| ((
commandBarContext: ContextFrom<typeof commandBarMachine>,
machineContext?: C
) => string)
defaultValue?:
| string
| ((
commandBarContext: ContextFrom<typeof commandBarMachine>,
machineContext?: C
) => string)
} }
| { inputType: 'kcl'; defaultValue?: string } // KCL expression inputs have simple strings as default values
| { | {
inputType: 'string' inputType: 'string'
defaultValue?: defaultValue?:
@ -243,30 +221,8 @@ export type CommandArgument<
inputType: 'selection' inputType: 'selection'
selectionTypes: Artifact['type'][] selectionTypes: Artifact['type'][]
multiple: boolean multiple: boolean
validation?: ({
data,
context,
}: {
data: any
context: CommandBarContext
}) => Promise<boolean | string>
}
| {
inputType: 'kcl'
createVariableByDefault?: boolean
variableName?:
| string
| ((
commandBarContext: ContextFrom<typeof commandBarMachine>,
machineContext?: ContextFrom<T>
) => string)
defaultValue?:
| string
| ((
commandBarContext: ContextFrom<typeof commandBarMachine>,
machineContext?: ContextFrom<T>
) => string)
} }
| { inputType: 'kcl'; defaultValue?: string } // KCL expression inputs have simple strings as default value
| { | {
inputType: 'string' inputType: 'string'
defaultValue?: defaultValue?:

View File

@ -111,10 +111,3 @@ export const KCL_SAMPLES_MANIFEST_URLS = {
/** Toast id for the app auto-updater toast */ /** Toast id for the app auto-updater toast */
export const AUTO_UPDATER_TOAST_ID = 'auto-updater-toast' export const AUTO_UPDATER_TOAST_ID = 'auto-updater-toast'
/** Local sketch axis values in KCL for operations, it could either be 'X' or 'Y' */
export const KCL_AXIS_X = 'X'
export const KCL_AXIS_Y = 'Y'
export const KCL_AXIS_NEG_X = '-X'
export const KCL_AXIS_NEG_Y = '-Y'
export const KCL_DEFAULT_AXIS = 'X'

View File

@ -155,8 +155,6 @@ export function buildCommandArgument<
context: ContextFrom<T>, context: ContextFrom<T>,
machineActor: Actor<T> machineActor: Actor<T>
): CommandArgument<O, T> & { inputType: typeof arg.inputType } { ): CommandArgument<O, T> & { inputType: typeof arg.inputType } {
// GOTCHA: modelingCommandConfig is not a 1:1 mapping to this baseCommandArgument
// You need to manually add key/value pairs here.
const baseCommandArgument = { const baseCommandArgument = {
description: arg.description, description: arg.description,
required: arg.required, required: arg.required,
@ -183,13 +181,10 @@ export function buildCommandArgument<
...baseCommandArgument, ...baseCommandArgument,
multiple: arg.multiple, multiple: arg.multiple,
selectionTypes: arg.selectionTypes, selectionTypes: arg.selectionTypes,
validation: arg.validation,
} satisfies CommandArgument<O, T> & { inputType: 'selection' } } satisfies CommandArgument<O, T> & { inputType: 'selection' }
} else if (arg.inputType === 'kcl') { } else if (arg.inputType === 'kcl') {
return { return {
inputType: arg.inputType, inputType: arg.inputType,
createVariableByDefault: arg.createVariableByDefault,
variableName: arg.variableName,
defaultValue: arg.defaultValue, defaultValue: arg.defaultValue,
...baseCommandArgument, ...baseCommandArgument,
} satisfies CommandArgument<O, T> & { inputType: 'kcl' } } satisfies CommandArgument<O, T> & { inputType: 'kcl' }

View File

@ -391,9 +391,7 @@ const getAppFolderName = () => {
export const getAppSettingsFilePath = async () => { export const getAppSettingsFilePath = async () => {
const isTestEnv = window.electron.process.env.IS_PLAYWRIGHT === 'true' const isTestEnv = window.electron.process.env.IS_PLAYWRIGHT === 'true'
const testSettingsPath = await window.electron.getAppTestProperty( const testSettingsPath = window.electron.process.env.TEST_SETTINGS_FILE_KEY
'TEST_SETTINGS_FILE_KEY'
)
const appConfig = await window.electron.getPath('appData') const appConfig = await window.electron.getPath('appData')
const fullPath = isTestEnv const fullPath = isTestEnv
? testSettingsPath ? testSettingsPath
@ -410,9 +408,7 @@ export const getAppSettingsFilePath = async () => {
} }
const getTokenFilePath = async () => { const getTokenFilePath = async () => {
const isTestEnv = window.electron.process.env.IS_PLAYWRIGHT === 'true' const isTestEnv = window.electron.process.env.IS_PLAYWRIGHT === 'true'
const testSettingsPath = await window.electron.getAppTestProperty( const testSettingsPath = window.electron.process.env.TEST_SETTINGS_FILE_KEY
'TEST_SETTINGS_FILE_KEY'
)
const appConfig = await window.electron.getPath('appData') const appConfig = await window.electron.getPath('appData')
const fullPath = isTestEnv const fullPath = isTestEnv
? testSettingsPath ? testSettingsPath

View File

@ -17,17 +17,9 @@ const save_ = async (file: ModelingAppFile, toastId: string) => {
} }
if (window.electron.process.env.IS_PLAYWRIGHT) { if (window.electron.process.env.IS_PLAYWRIGHT) {
// Skip file picker, save to the test dir downloads directory // skip file picker, save to default location
const testSettingsPath = await window.electron.getAppTestProperty(
'TEST_SETTINGS_FILE_KEY'
)
const downloadDir = window.electron.join(
testSettingsPath,
'downloads-during-playwright'
)
await window.electron.mkdir(downloadDir, { recursive: true })
await window.electron.writeFile( await window.electron.writeFile(
window.electron.join(downloadDir, file.name), file.name,
new Uint8Array(file.contents) new Uint8Array(file.contents)
) )
toast.success(EXPORT_TOAST_MESSAGES.SUCCESS, { id: toastId }) toast.success(EXPORT_TOAST_MESSAGES.SUCCESS, { id: toastId })

View File

@ -85,13 +85,12 @@ export const fileLoader: LoaderFunction = async (
) )
const isBrowserProject = params.id === decodeURIComponent(BROWSER_PATH) const isBrowserProject = params.id === decodeURIComponent(BROWSER_PATH)
let code = ''
if (!isBrowserProject && projectPathData) { if (!isBrowserProject && projectPathData) {
const { projectName, projectPath, currentFileName, currentFilePath } = const { projectName, projectPath, currentFileName, currentFilePath } =
projectPathData projectPathData
const urlObj = new URL(routerData.request.url) const urlObj = new URL(routerData.request.url)
let code = ''
if (!urlObj.pathname.endsWith('/settings')) { if (!urlObj.pathname.endsWith('/settings')) {
const fallbackFile = isDesktop() const fallbackFile = isDesktop()
@ -121,10 +120,6 @@ export const fileLoader: LoaderFunction = async (
}) })
code = normalizeLineEndings(code) code = normalizeLineEndings(code)
// If persistCode in localStorage is present, it'll persist that code
// through *anything*. INTENDED FOR TESTS.
code = codeManager.localStoragePersistCode() || code
// Update both the state and the editor's code. // Update both the state and the editor's code.
// We explicitly do not write to the file here since we are loading from // We explicitly do not write to the file here since we are loading from
// the file system and not the editor. // the file system and not the editor.
@ -152,6 +147,12 @@ export const fileLoader: LoaderFunction = async (
? await getProjectInfo(projectPath) ? await getProjectInfo(projectPath)
: null : null
console.log('maybeProjectInfo', {
maybeProjectInfo,
defaultProjectData,
projectPathData,
})
const projectData: IndexLoaderData = { const projectData: IndexLoaderData = {
code, code,
project: maybeProjectInfo ?? defaultProjectData, project: maybeProjectInfo ?? defaultProjectData,
@ -168,7 +169,7 @@ export const fileLoader: LoaderFunction = async (
} }
return { return {
code, code: '',
project: { project: {
name: BROWSER_PROJECT_NAME, name: BROWSER_PROJECT_NAME,
path: '/' + BROWSER_PROJECT_NAME, path: '/' + BROWSER_PROJECT_NAME,

View File

@ -569,17 +569,6 @@ export function canSweepSelection(selection: Selections) {
) )
} }
export function canRevolveSelection(selection: Selections) {
const commonNodes = selection.graphSelections.map((_, i) =>
buildCommonNodeFromSelection(selection, i)
)
return (
!!isSketchPipe(selection) &&
(commonNodes.every((n) => nodeHasClose(n)) ||
commonNodes.every((n) => nodeHasCircle(n)))
)
}
export function canLoftSelection(selection: Selections) { export function canLoftSelection(selection: Selections) {
const commonNodes = selection.graphSelections.map((_, i) => const commonNodes = selection.graphSelections.map((_, i) =>
buildCommonNodeFromSelection(selection, i) buildCommonNodeFromSelection(selection, i)
@ -641,29 +630,12 @@ export function getSelectionCountByType(
} }
}) })
selection.graphSelections.forEach((graphSelection) => { selection.graphSelections.forEach((selection) => {
if (!graphSelection.artifact) { if (!selection.artifact) {
/** incrementOrInitializeSelectionType('other')
* TODO: remove this heuristic-based selection type detection. return
* Currently, if you've created a sketch and have not left sketch mode,
* the selection will be a segment selection with no artifact.
* This is because the mock execution does not update the artifact graph.
* Once we move the artifactGraph creation to WASM, we can remove this,
* as the artifactGraph will always be up-to-date.
*/
if (isSingleCursorInPipe(selection, kclManager.ast)) {
incrementOrInitializeSelectionType('segment')
return
} else {
console.warn(
'Selection is outside of a sketch but has no artifact. Sketch segment selections are the only kind that can have a valid selection with no artifact.',
JSON.stringify(graphSelection)
)
incrementOrInitializeSelectionType('other')
return
}
} }
incrementOrInitializeSelectionType(graphSelection.artifact.type) incrementOrInitializeSelectionType(selection.artifact.type)
}) })
return selectionsByType return selectionsByType

View File

@ -12,7 +12,7 @@ export type InteractionMapItem = {
* Controls both the available names for interaction map categories * Controls both the available names for interaction map categories
* and the order in which they are displayed. * and the order in which they are displayed.
*/ */
const interactionMapCategories = [ export const interactionMapCategories = [
'Sketching', 'Sketching',
'Modeling', 'Modeling',
'Command Palette', 'Command Palette',

View File

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

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